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);
25 # Check is SSL is enabled and available
27 eval "use Net::SSLeay";
30 # These functions only exist for SSLeay 1.0
31 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
32 eval "Net::SSLeay::load_error_strings()";
33 if ($config{'no_ssl2'}) {
34 eval "Net::SSLeay::CTX_set_options($ctx,&Net::SSLeay::OP_NO_SSLv2)";
36 if (defined(&Net::SSLeay::X509_STORE_CTX_get_current_cert) &&
37 defined(&Net::SSLeay::CTX_load_verify_locations) &&
38 defined(&Net::SSLeay::CTX_set_verify)) {
44 # Check if the syslog module is available to log hacking attempts
45 if ($config{'syslog'} && !$config{'inetd'}) {
46 eval "use Sys::Syslog qw(:DEFAULT setlogsock)";
52 # check if the TCP-wrappers module is available
53 if ($config{'libwrap'}) {
54 eval "use Authen::Libwrap qw(hosts_ctl STRING_UNKNOWN)";
60 # Check if the MD5 perl module is available
66 eval "use Digest::MD5";
68 $use_md5 = "Digest::MD5";
72 # Get miniserv's perl path and location
74 open(SOURCE, $miniserv_path);
75 <SOURCE> =~ /^#!(\S+)/;
82 $linked_perl_path = readlink($perl_path);
84 @miniserv_argv = @ARGV;
86 # Check vital config options
87 &update_vital_config();
89 $sidname = $config{'sidname'};
90 die "Session authentication cannot be used in inetd mode"
91 if ($config{'inetd'} && $config{'session'});
93 # check if the PAM module is available to authenticate
94 if (!$config{'no_pam'}) {
95 eval "use Authen::PAM;";
97 # check if the PAM authentication can be used by opening a
100 if (ref($pamh = new Authen::PAM($config{'pam'}, "root",
102 # Now test a login to see if /etc/pam.d/XXX is set
104 $pam_conv_func_called = 0;
105 $pam_username = "test";
106 $pam_password = "test";
107 $pamh->pam_authenticate();
108 if ($pam_conv_func_called) {
109 $pam_msg = "PAM authentication enabled";
113 $pam_msg = "PAM test failed - maybe /etc/pam.d/$config{'pam'} does not exist";
117 $pam_msg = "PAM initialization of Authen::PAM failed";
121 $pam_msg = "Perl module Authen::PAM needed for PAM is not installed : $@";
124 if ($config{'pam_only'} && !$use_pam) {
125 $pam_msg2 = "PAM use is mandatory, but could not be enabled!";
127 elsif ($pam_msg && !$use_pam) {
128 $pam_msg2 = "Continuing without the Authen::PAM perl module";
131 # Check if the User::Utmp perl module is installed
132 if ($config{'utmp'}) {
133 eval "use User::Utmp;";
136 $utmp_msg = "UTMP logging enabled";
139 $utmp_msg = "Perl module User::Utmp needed for Utmp logging is not installed : $@";
143 # See if the crypt function fails
144 eval "crypt('foo', 'xx')";
146 eval "use Crypt::UnixCrypt";
149 $crypt_msg = "Using Crypt::UnixCrypt for password encryption\n";
152 $crypt_msg = "crypt() function un-implemented, and Crypt::UnixCrypt not installed - password authentication will probably fail\n";
156 # Check if /dev/urandom really generates random IDs, by calling it twice
157 local $rand1 = &generate_random_id("foo", 1);
158 local $rand2 = &generate_random_id("foo", 2);
160 if ($rand1 eq $rand2) {
162 $rand_msg = "Random number generator file /dev/urandom is not reliable";
165 # Check if we can call sudo
166 if ($config{'sudo'} && &has_command("sudo")) {
172 $sudo_msg = "Perl module IO::Pty needed for calling sudo is not installed : $@";
176 # init days and months for http_date
177 @weekday = ( "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" );
178 @month = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun",
179 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" );
181 # Change dir to the server root
182 @roots = ( $config{'root'} );
183 for($i=0; defined($config{"extraroot_$i"}); $i++) {
184 push(@roots, $config{"extraroot_$i"});
187 eval { $user_homedir = (getpwuid($<))[7]; };
189 # getpwuid doesn't work on windows
190 $user_homedir = $ENV{"HOME"} || $ENV{"USERPROFILE"} || "/";
197 # Setup SSL if possible and if requested
198 if (!-r $config{'keyfile'} ||
199 $config{'certfile'} && !-r $config{'certfile'}) {
200 # Key file doesn't exist!
203 @ipkeys = &get_ipkeys(\%config);
205 if ($config{'ssl_version'}) {
206 # Force an SSL version
207 $Net::SSLeay::version = $config{'ssl_version'};
208 $Net::SSLeay::ssl_version = $config{'ssl_version'};
210 $client_certs = 0 if (!-r $config{'ca'} || !%certs);
211 $ssl_contexts{"*"} = &create_ssl_context($config{'keyfile'},
212 $config{'certfile'});
213 foreach $ipkey (@ipkeys) {
214 $ctx = &create_ssl_context($ipkey->{'key'}, $ipkey->{'cert'});
215 foreach $ip (@{$ipkey->{'ips'}}) {
216 $ssl_contexts{$ip} = $ctx;
221 # Setup syslog support if possible and if requested
223 open(ERRDUP, ">&STDERR");
224 open(STDERR, ">/dev/null");
225 $log_socket = $config{"logsock"} || "unix";
226 eval 'openlog($config{"pam"}, "cons,pid,ndelay", "authpriv"); setlogsock($log_socket)';
231 local $msg = ucfirst($config{'pam'})." starting";
232 eval { syslog("info", "%s", $msg); };
236 syslog("info", "%s", $msg);
239 # All attempts to use syslog have failed..
244 open(STDERR, ">&ERRDUP");
248 # Read MIME types file and add extra types
252 if ($config{'log'}) {
253 local(@gmt, @lct, $days, $hours, $mins);
254 @gmt = gmtime(time());
255 @lct = localtime(time());
256 $days = $lct[3] - $gmt[3];
257 $hours = ($days < -1 ? 24 : 1 < $days ? -24 : $days * 24) +
259 $mins = $hours * 60 + $lct[1] - $gmt[1];
260 $timezone = ($mins < 0 ? "-" : "+"); $mins = abs($mins);
261 $timezone .= sprintf "%2.2d%2.2d", $mins/60, $mins%60;
264 # Build various maps from the config files
265 &build_config_mappings();
267 # start up external authentication program, if needed
268 if ($config{'extauth'}) {
269 socketpair(EXTAUTH, EXTAUTH2, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
270 if (!($extauth = fork())) {
274 open(STDIN, "<&EXTAUTH2");
275 open(STDOUT, ">&EXTAUTH2");
276 exec($config{'extauth'}) or die "exec failed : $!\n";
279 local $os = select(EXTAUTH);
283 # Pre-load any libraries
284 foreach $pl (split(/\s+/, $config{'preload'})) {
285 ($pkg, $lib) = split(/=/, $pl);
286 $pkg =~ s/[^A-Za-z0-9]/_/g;
287 eval "package $pkg; do '$config{'root'}/$lib'";
289 print STDERR "Failed to pre-load $lib in $pkg : $@\n";
292 print STDERR "Pre-loaded $lib in $pkg\n";
295 foreach $pl (split(/\s+/, $config{'premodules'})) {
297 ($dir, $mod) = split(/\//, $pl);
300 ($dir, $mod) = (undef, $pl);
302 push(@INC, "$config{'root'}/$dir");
303 eval "package $mod; use $mod ()";
305 print STDERR "Failed to pre-load $mod : $@\n";
308 print STDERR "Pre-loaded $mod\n";
312 # Open debug log if set
313 if ($config{'debuglog'}) {
314 open(DEBUG, ">>$config{'debuglog'}");
315 chmod(0700, $config{'debuglog'});
316 select(DEBUG); $| = 1; select(STDOUT);
317 print DEBUG "miniserv.pl starting ..\n";
320 # Write out (empty) blocked hosts file
321 &write_blocked_file();
323 # Re-direct STDERR to a log file
324 if ($config{'errorlog'} ne '-') {
325 open(STDERR, ">>$config{'errorlog'}") || die "failed to open $config{'errorlog'} : $!";
326 if ($config{'logperms'}) {
327 chmod(oct($config{'logperms'}), $config{'errorlog'});
330 select(STDERR); $| = 1; select(STDOUT);
332 if ($config{'inetd'}) {
333 # We are being run from inetd - go direct to handling the request
334 $SIG{'HUP'} = 'IGNORE';
335 $SIG{'TERM'} = 'DEFAULT';
336 $SIG{'PIPE'} = 'DEFAULT';
337 open(SOCK, "+>&STDIN");
339 # Check if it is time for the logfile to be cleared
340 if ($config{'logclear'}) {
341 local $write_logtime = 0;
342 local @st = stat("$config{'logfile'}.time");
344 if ($st[9]+$config{'logtime'}*60*60 < time()){
347 unlink($config{'logfile'});
350 else { $write_logtime = 1; }
351 if ($write_logtime) {
352 open(LOGTIME, ">$config{'logfile'}.time");
353 print LOGTIME time(),"\n";
358 # Initialize SSL for this connection
360 $ssl_con = &ssl_connection_for_ip(SOCK);
364 # Work out the hostname for this web server
365 $host = &get_socket_name(SOCK);
367 $port = $config{'port'};
368 $acptaddr = getpeername(SOCK);
371 print DEBUG "main: Starting handle_request loop pid=$$\n";
372 while(&handle_request($acptaddr, getsockname(SOCK))) { }
373 print DEBUG "main: Done handle_request loop pid=$$\n";
378 # Build list of sockets to listen on
379 if ($config{"bind"} && $config{"bind"} ne "*") {
380 push(@sockets, [ inet_aton($config{'bind'}), $config{'port'} ]);
383 push(@sockets, [ INADDR_ANY, $config{'port'} ]);
385 foreach $s (split(/\s+/, $config{'sockets'})) {
386 if ($s =~ /^(\d+)$/) {
387 # Just listen on another port on the main IP
388 push(@sockets, [ $sockets[0]->[0], $s ]);
390 elsif ($s =~ /^(\S+):(\d+)$/) {
391 # Listen on a specific port and IP
392 push(@sockets, [ $1 eq "*" ? INADDR_ANY : inet_aton($1), $2 ]);
394 elsif ($s =~ /^([0-9\.]+):\*$/ || $s =~ /^([0-9\.]+)$/) {
395 # Listen on the main port on another IP
396 push(@sockets, [ inet_aton($1), $sockets[0]->[1] ]);
400 # Open all the sockets
401 $proto = getprotobyname('tcp');
403 $tried_inaddr_any = 0;
404 for($i=0; $i<@sockets; $i++) {
406 socket($fh, PF_INET, SOCK_STREAM, $proto) ||
407 die "Failed to open socket : $!";
408 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
409 for($j=0; $j<5; $j++) {
410 last if (bind($fh, pack_sockaddr_in($sockets[$i]->[1],
411 $sockets[$i]->[0])));
415 # All attempts failed .. give up
416 if ($sockets[$i]->[0] eq INADDR_ANY) {
417 push(@sockerrs, "Failed to bind to port $sockets[$i]->[1] : $!");
418 $tried_inaddr_any = 1;
421 $ip = inet_ntoa($sockets[$i]->[0]);
422 push(@sockerrs, "Failed to bind to IP $ip port $sockets[$i]->[1] : $!");
426 listen($fh, SOMAXCONN);
427 push(@socketfhs, $fh);
430 foreach $se (@sockerrs) {
431 print STDERR $se,"\n";
434 # If all binds failed, try binding to any address
435 if (!@socketfhs && !$tried_inaddr_any) {
436 print STDERR "Falling back to listening on any address\n";
438 socket($fh, PF_INET, SOCK_STREAM, $proto) ||
439 die "Failed to open socket : $!";
440 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
441 bind($fh, pack_sockaddr_in($sockets[0]->[1], INADDR_ANY)) ||
442 die "Failed to bind to port $sockets[0]->[1] : $!";
443 listen($fh, SOMAXCONN);
444 push(@socketfhs, $fh);
446 elsif (!@socketfhs && $tried_inaddr_any) {
447 die "Could not listen on any ports";
450 if ($config{'listen'}) {
451 # Open the socket that allows other webmin servers to find this one
452 $proto = getprotobyname('udp');
453 if (socket(LISTEN, PF_INET, SOCK_DGRAM, $proto)) {
454 setsockopt(LISTEN, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
455 bind(LISTEN, pack_sockaddr_in($config{'listen'}, INADDR_ANY));
456 listen(LISTEN, SOMAXCONN);
459 $config{'listen'} = 0;
463 # Split from the controlling terminal, unless configured not to
464 if (!$config{'nofork'}) {
465 if (fork()) { exit; }
467 eval { setsid(); }; # may not work on Windows
469 # Close standard file handles
470 open(STDIN, "</dev/null");
471 open(STDOUT, ">/dev/null");
472 &log_error("miniserv.pl started");
473 &log_error($pam_msg) if ($pam_msg);
474 &log_error($pam_msg2) if ($pam_msg2);
475 &log_error($utmp_msg) if ($utmp_msg);
476 &log_error($crypt_msg) if ($crypt_msg);
477 &log_error($sudo_msg) if ($sudo_msg);
478 &log_error($rand_msg) if ($rand_msg);
480 # write out the PID file
483 # Start the log-clearing process, if needed. This checks every minute
484 # to see if the log has passed its reset time, and if so clears it
485 if ($config{'logclear'}) {
486 if (!($logclearer = fork())) {
487 &close_all_sockets();
490 local $write_logtime = 0;
491 local @st = stat("$config{'logfile'}.time");
493 if ($st[9]+$config{'logtime'}*60*60 < time()){
496 unlink($config{'logfile'});
499 else { $write_logtime = 1; }
500 if ($write_logtime) {
501 open(LOGTIME, ">$config{'logfile'}.time");
502 print LOGTIME time(),"\n";
509 push(@childpids, $logclearer);
512 # Setup the logout time dbm if needed
513 if ($config{'session'}) {
514 eval "use SDBM_File";
515 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
516 eval "\$sessiondb{'1111111111'} = 'foo bar';";
518 dbmclose(%sessiondb);
519 eval "use NDBM_File";
520 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
523 delete($sessiondb{'1111111111'});
528 $SIG{'HUP'} = 'miniserv::trigger_restart';
529 $SIG{'TERM'} = 'miniserv::term_handler';
530 $SIG{'USR1'} = 'miniserv::trigger_reload';
531 $SIG{'PIPE'} = 'IGNORE';
532 local $remove_session_count = 0;
533 $need_pipes = $config{'passdelay'} || $config{'session'};
534 $last_pid_time = time();
536 # wait for a new connection, or a message from a child process
538 if (@childpids <= $config{'maxconns'}) {
539 # Only accept new main socket connects when ready
541 foreach $s (@socketfhs) {
542 vec($rmask, fileno($s), 1) = 1;
546 printf STDERR "too many children (%d > %d)\n",
547 scalar(@childpids), $config{'maxconns'};
550 for($i=0; $i<@passin; $i++) {
551 vec($rmask, fileno($passin[$i]), 1) = 1;
554 vec($rmask, fileno(LISTEN), 1) = 1 if ($config{'listen'});
556 # Wait for a connection
557 local $sel = select($rmask, undef, undef, 10);
559 # Check the flag files
560 if ($config{'restartflag'} && -r $config{'restartflag'}) {
561 print STDERR "restart flag file detected\n";
562 unlink($config{'restartflag'});
565 if ($config{'reloadflag'} && -r $config{'reloadflag'}) {
566 unlink($config{'reloadflag'});
571 # Got a HUP signal while in select() .. restart now
575 # Got a USR1 signal while in select() .. re-read config
577 &reload_config_file();
579 local $time_now = time();
581 # Write the PID every 10 seconds
582 if ($time_now - $last_pid_time > 10) {
584 $last_pid_time = $time_now;
587 # Clean up finished processes
589 do { $pid = waitpid(-1, WNOHANG);
590 @childpids = grep { $_ != $pid } @childpids;
591 } while($pid != 0 && $pid != -1);
593 # run the unblocking procedure to check if enough time has passed to
594 # unblock hosts that heve been blocked because of password failures
596 if ($config{'blockhost_failures'}) {
598 while ($i <= $#deny) {
599 if ($blockhosttime{$deny[$i]} &&
600 $config{'blockhost_time'} != 0 &&
601 ($time_now - $blockhosttime{$deny[$i]}) >=
602 $config{'blockhost_time'}) {
603 # the host can be unblocked now
604 $hostfail{$deny[$i]} = 0;
605 splice(@deny, $i, 1);
612 # Do the same for blocked users
613 if ($config{'blockuser_failures'}) {
615 while ($i <= $#deny) {
616 if ($blockusertime{$deny[$i]} &&
617 $config{'blockuser_time'} != 0 &&
618 ($time_now - $blockusertime{$deny[$i]}) >=
619 $config{'blockuser_time'}) {
620 # the user can be unblocked now
621 $userfail{$deny[$i]} = 0;
622 splice(@denyusers, $i, 1);
629 &write_blocked_file();
632 if ($config{'session'} && (++$remove_session_count%50) == 0) {
633 # Remove sessions with more than 7 days of inactivity,
635 foreach $s (keys %sessiondb) {
636 local ($user, $ltime, $lip) =
637 split(/\s+/, $sessiondb{$s});
638 if ($time_now - $ltime > 7*24*60*60) {
639 &run_logout_script($s, $user);
640 &write_logout_utmp($user, $lip);
641 delete($sessiondb{$s});
644 "Timeout of session for $user");
650 if ($use_pam && $config{'pam_conv'}) {
651 # Remove PAM sessions with more than 5 minutes of inactivity
653 foreach $c (values %conversations) {
654 if ($time_now - $c->{'time'} > 5*60) {
655 &end_pam_conversation($c);
657 syslog("info", "%s", "Timeout of PAM ".
658 "session for $c->{'user'}");
664 # Don't check any sockets if there is no activity
667 # Check if any of the main sockets have received a new connection
669 foreach $s (@socketfhs) {
670 if (vec($rmask, fileno($s), 1)) {
672 $acptaddr = accept(SOCK, $s);
673 if (!$acptaddr) { next; }
674 binmode(SOCK); # turn off any Perl IO stuff
677 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
679 ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw) =
683 # Check username of connecting user
684 local ($peerp, $peera) = unpack_sockaddr_in($acptaddr);
685 $localauth_user = undef;
686 if ($config{'localauth'} && inet_ntoa($peera) eq "127.0.0.1") {
687 if (open(TCP, "/proc/net/tcp")) {
688 # Get the info direct from the kernel
691 local @t = split(/[\s:]+/, $_);
692 if ($t[1] eq '0100007F' &&
693 $t[2] eq sprintf("%4.4X", $peerp)) {
694 $localauth_user = getpwuid($t[11]);
700 if (!$localauth_user) {
701 # Call lsof for the info
702 local $lsofpid = open(LSOF,
703 "$config{'localauth'} -i TCP\@127.0.0.1:$peerp |");
705 if (/^(\S+)\s+(\d+)\s+(\S+)/ &&
706 $2 != $$ && $2 != $lsofpid) {
707 $localauth_user = $3;
714 # Work out the hostname for this web server
715 $host = &get_socket_name(SOCK);
717 print STDERR "Failed to get local socket name : $!\n";
721 $port = $sockets[$sn]->[1];
723 # fork the subprocess
725 if (!($handpid = fork())) {
726 # setup signal handlers
727 $SIG{'TERM'} = 'DEFAULT';
728 $SIG{'PIPE'} = 'DEFAULT';
729 #$SIG{'CHLD'} = 'IGNORE';
730 $SIG{'HUP'} = 'IGNORE';
731 $SIG{'USR1'} = 'IGNORE';
733 # Initialize SSL for this connection
735 $ssl_con = &ssl_connection_for_ip(SOCK);
739 # Close the file handle for the session DBM
740 dbmclose(%sessiondb);
742 # close useless pipes
745 close($PASSINr); close($PASSOUTw);
747 &close_all_sockets();
751 "main: Starting handle_request loop pid=$$\n";
752 while(&handle_request($acptaddr,
753 getsockname(SOCK))) { }
755 "main: Done handle_request loop pid=$$\n";
758 close($PASSINw); close($PASSOUTw);
761 push(@childpids, $handpid);
763 close($PASSINw); close($PASSOUTr);
764 push(@passin, $PASSINr);
765 push(@passout, $PASSOUTw);
772 if ($config{'listen'} && vec($rmask, fileno(LISTEN), 1)) {
773 # Got UDP packet from another webmin server
775 local $from = recv(LISTEN, $rcvbuf, 1024, 0);
777 local $fromip = inet_ntoa((unpack_sockaddr_in($from))[1]);
778 local $toip = inet_ntoa((unpack_sockaddr_in(
779 getsockname(LISTEN)))[1]);
780 if ((!@deny || !&ip_match($fromip, $toip, @deny)) &&
781 (!@allow || &ip_match($fromip, $toip, @allow))) {
782 local $listenhost = &get_socket_name(LISTEN);
783 send(LISTEN, "$listenhost:$config{'port'}:".
784 ($use_ssl || $config{'inetd_ssl'} ? 1 : 0).":".
785 ($config{'listenhost'} ?
786 &get_system_hostname() : ""),
792 # check for session, password-timeout and PAM messages from subprocesses
793 for($i=0; $i<@passin; $i++) {
794 if (vec($rmask, fileno($passin[$i]), 1)) {
795 # this sub-process is asking about a password
796 local $infd = $passin[$i];
797 local $outfd = $passout[$i];
798 #local $inline = <$infd>;
799 local $inline = &sysread_line($infd);
801 print DEBUG "main: inline $inline";
804 print DEBUG "main: inline EOF\n";
806 if ($inline =~ /^delay\s+(\S+)\s+(\S+)\s+(\d+)/) {
807 # Got a delay request from a subprocess.. for
808 # valid logins, there is no delay (to prevent
809 # denial of service attacks), but for invalid
810 # logins the delay increases with each failed
813 # login OK.. no delay
814 print $outfd "0 0\n";
815 $wasblocked = $hostfail{$2} ||
820 &write_blocked_file();
829 # add the host to the block list,
831 if ($config{'blockhost_failures'} &&
833 $config{'blockhost_failures'}) {
835 $blockhosttime{$2} = $time_now;
838 local $logtext = "Security alert: Host $2 blocked after $config{'blockhost_failures'} failed logins for user $1";
844 # add the user to the user block list,
846 if ($config{'blockuser_failures'} &&
848 $config{'blockuser_failures'}) {
849 push(@denyusers, $1);
850 $blockusertime{$1} = $time_now;
853 local $logtext = "Security alert: User $1 blocked after $config{'blockuser_failures'} failed logins";
859 # Lock out the user's password, if enabled
860 if ($config{'blocklock'} &&
862 $config{'blockuser_failures'}) {
863 my $lk = &lock_user_password($1);
866 local $logtext = $lk == 1 ? "Security alert: User $1 locked after $config{'blockuser_failures'} failed logins" : $lk < 0 ? "Security alert: User could not be locked" : "Security alert: User is already locked";
873 $dl = $userdlay{$1} -
874 int(($time_now - $userlast{$1})/50);
875 $dl = $dl < 0 ? 0 : $dl+1;
876 print $outfd "$dl $blocked\n";
879 # Write out blocked status file
881 &write_blocked_file();
884 $userlast{$1} = $time_now;
886 elsif ($inline =~ /^verify\s+(\S+)\s+(\S+)/) {
887 # Verifying a session ID
888 local $session_id = $1;
889 local $notimeout = $2;
890 local $skey = $sessiondb{$session_id} ?
892 &hash_session_id($session_id);
893 if (!defined($sessiondb{$skey})) {
894 # Session doesn't exist
895 print $outfd "0 0\n";
898 local ($user, $ltime) =
899 split(/\s+/, $sessiondb{$skey});
900 local $lot = &get_logout_time($user, $session_id);
902 $time_now - $ltime > $lot*60 &&
904 # Session has timed out
905 print $outfd "1 ",$time_now - $ltime,"\n";
906 #delete($sessiondb{$skey});
910 print $outfd "2 $user\n";
914 $sessiondb{$skey} = "$user $time_now";
919 elsif ($inline =~ /^new\s+(\S+)\s+(\S+)\s+(\S+)/) {
920 # Creating a new session
921 local $session_id = $1;
924 $sessiondb{&hash_session_id($session_id)} =
925 "$user $time_now $ip";
927 elsif ($inline =~ /^delete\s+(\S+)/) {
928 # Logging out a session
929 local $session_id = $1;
930 local $skey = $sessiondb{$session_id} ?
932 &hash_session_id($session_id);
933 local @sdb = split(/\s+/, $sessiondb{$skey});
934 print $outfd $sdb[0],"\n";
935 delete($sessiondb{$skey});
937 elsif ($inline =~ /^pamstart\s+(\S+)\s+(\S+)\s+(.*)/) {
938 # Starting a new PAM conversation
939 local ($cid, $host, $user) = ($1, $2, $3);
941 # Does this user even need PAM?
942 local ($realuser, $canlogin) =
943 &can_user_login($user, undef, $host);
945 if ($canlogin == 0) {
947 print $outfd "0 Invalid username\n";
949 elsif ($canlogin != 2) {
950 # Not using PAM .. so just ask for
952 $conv = { 'user' => $realuser,
957 print $outfd "3 Password\n";
960 # Start the PAM conversation
961 # sub-process, and get a question
962 $conv = { 'user' => $realuser,
966 local ($PAMINr, $PAMINw, $PAMOUTr,
967 $PAMOUTw) = &allocate_pipes();
968 local $pampid = fork();
970 close($PAMOUTr); close($PAMINw);
971 &pam_conversation_process(
975 close($PAMOUTw); close($PAMINr);
976 $conv->{'pid'} = $pampid;
977 $conv->{'PAMOUTr'} = $PAMOUTr;
978 $conv->{'PAMINw'} = $PAMINw;
979 push(@childpids, $pampid);
981 # Get the first PAM question
982 local $pok = &recv_pam_question(
985 &end_pam_conversation($conv);
989 $conversations{$cid} = $conv if ($conv);
991 elsif ($inline =~ /^pamanswer\s+(\S+)\s+(.*)/) {
992 # A response to a PAM question
993 local ($cid, $answer) = ($1, $2);
994 local $conv = $conversations{$cid};
996 # No such conversation?
997 print $outfd "0 Bad login session\n";
999 elsif ($conv->{'pid'}) {
1000 # Send the PAM response and get
1002 &send_pam_answer($conv, $answer);
1003 local $pok = &recv_pam_question($conv, $outfd);
1005 &end_pam_conversation($conv);
1009 # This must be the password .. try it
1010 # and send back the results
1011 local ($vu, $expired, $nonexist) =
1012 &validate_user($conv->{'user'},
1015 local $ok = $vu ? 1 : 0;
1016 print $outfd "2 $conv->{'user'} $ok $expired $notexist\n";
1017 &end_pam_conversation($conv);
1020 elsif ($inline =~ /^writesudo\s+(\S+)\s+(\d+)/) {
1021 # Store the fact that some user can sudo to root
1022 local ($user, $ok) = ($1, $2);
1023 $sudocache{$user} = $ok." ".time();
1025 elsif ($inline =~ /^readsudo\s+(\S+)/) {
1026 # Query the user sudo cache (valid for 1 minute)
1028 local ($ok, $last) =
1029 split(/\s+/, $sudocache{$user});
1030 if ($last < time()-60) {
1035 # Tell client OK or not
1036 print $outfd "$ok\n";
1039 elsif ($inline =~ /\S/) {
1040 # Unknown line from pipe?
1041 print DEBUG "main: Unknown line from pipe $inline\n";
1042 print STDERR "Unknown line from pipe $inline\n";
1046 close($infd); close($outfd);
1047 $passin[$i] = $passout[$i] = undef;
1051 @passin = grep { defined($_) } @passin;
1052 @passout = grep { defined($_) } @passout;
1055 # handle_request(remoteaddress, localaddress)
1056 # Where the real work is done
1059 $acptip = inet_ntoa((unpack_sockaddr_in($_[0]))[1]);
1060 $localip = $_[1] ? inet_ntoa((unpack_sockaddr_in($_[1]))[1]) : undef;
1061 print DEBUG "handle_request: from $acptip to $localip\n";
1062 if ($config{'loghost'}) {
1063 $acpthost = gethostbyaddr(inet_aton($acptip), AF_INET);
1064 $acpthost = $acptip if (!$acpthost);
1067 $acpthost = $acptip;
1069 $datestr = &http_date(time());
1071 $ok_message = "Document follows";
1072 $logged_code = undef;
1073 $reqline = $request_uri = $page = undef;
1077 # check address against access list
1078 if (@deny && &ip_match($acptip, $localip, @deny) ||
1079 @allow && !&ip_match($acptip, $localip, @allow)) {
1080 &http_error(403, "Access denied for $acptip");
1085 # Check address with TCP-wrappers
1086 if (!hosts_ctl($config{'pam'}, STRING_UNKNOWN,
1087 $acptip, STRING_UNKNOWN)) {
1088 &http_error(403, "Access denied for $acptip by TCP wrappers");
1092 print DEBUG "handle_request: passed IP checks\n";
1094 # Compute a timeout for the start of headers, based on the number of
1095 # child processes. As this increases, we use a shorter timeout to avoid
1096 # an attacker overloading the system.
1097 local $header_timeout = 60 + ($config{'maxconns'} - @childpids) * 10;
1099 # Wait at most 60 secs for start of headers for initial requests, or
1100 # 10 minutes for kept-alive connections
1102 vec($rmask, fileno(SOCK), 1) = 1;
1103 local $to = $checked_timeout ? 10*60 : $header_timeout;
1104 local $sel = select($rmask, undef, undef, $to);
1106 if ($checked_timeout) {
1107 print DEBUG "handle_request: exiting due to timeout of $to\n";
1111 &http_error(400, "Timeout",
1112 "Waited for that $to seconds for start of headers");
1116 print DEBUG "handle_request: passed timeout check\n";
1118 # Read the HTTP request and headers
1119 local $origreqline = &read_line();
1120 ($reqline = $origreqline) =~ s/\r|\n//g;
1121 $method = $page = $request_uri = undef;
1122 print DEBUG "handle_request reqline=$reqline\n";
1123 if (!$reqline && (!$use_ssl || $checked_timeout > 1)) {
1124 # An empty request .. just close the connection
1125 print DEBUG "handle_request: rejecting empty request\n";
1128 elsif ($reqline !~ /^(\S+)\s+(.*)\s+HTTP\/1\..$/) {
1129 print DEBUG "handle_request: invalid reqline=$reqline\n";
1131 # This could be an http request when it should be https
1133 local $url = $config{'musthost'} ?
1134 "https://$config{'musthost'}:$port/" :
1135 "https://$host:$port/";
1136 if ($config{'ssl_redirect'}) {
1137 # Just re-direct to the correct URL
1138 sleep(1); # Give browser a change to finish
1139 # sending its request
1140 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1141 &write_data("Date: $datestr\r\n");
1142 &write_data("Server: $config{'server'}\r\n");
1143 &write_data("Location: $url\r\n");
1144 &write_keep_alive(0);
1145 &write_data("\r\n");
1149 # Tell user the correct URL
1150 &http_error(200, "Bad Request", "This web server is running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1153 elsif (ord(substr($reqline, 0, 1)) == 128 && !$use_ssl) {
1154 # This could be an https request when it should be http ..
1155 # need to fake a HTTP response
1158 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
1159 eval "Net::SSLeay::load_error_strings()";
1160 $ssl_ctx = Net::SSLeay::CTX_new();
1161 Net::SSLeay::CTX_use_RSAPrivateKey_file(
1162 $ssl_ctx, $config{'keyfile'},
1163 &Net::SSLeay::FILETYPE_PEM);
1164 Net::SSLeay::CTX_use_certificate_file(
1166 $config{'certfile'} || $config{'keyfile'},
1167 &Net::SSLeay::FILETYPE_PEM);
1168 $ssl_con = Net::SSLeay::new($ssl_ctx);
1172 select(SSLw); $| = 1; select(STDOUT);
1173 print SSLw $origreqline;
1175 while(sysread(SOCK, $buf, 1) > 0) {
1182 Net::SSLeay::set_wfd($ssl_con, fileno(SOCK));
1183 Net::SSLeay::set_rfd($ssl_con, fileno(SSLr));
1184 Net::SSLeay::accept($ssl_con) || die "accept() failed";
1186 local $url = $config{'musthost'} ?
1187 "https://$config{'musthost'}:$port/" :
1188 "https://$host:$port/";
1189 if ($config{'ssl_redirect'}) {
1190 # Just re-direct to the correct URL
1191 sleep(1); # Give browser a change to
1192 # finish sending its request
1193 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1194 &write_data("Date: $datestr\r\n");
1195 &write_data("Server: $config{'server'}\r\n");
1196 &write_data("Location: $url\r\n");
1197 &write_keep_alive(0);
1198 &write_data("\r\n");
1202 # Tell user the correct URL
1203 &http_error(200, "Bad Request", "This web server is not running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1207 &http_error(400, "Bad Request");
1211 &http_error(400, "Bad Request");
1215 $request_uri = $page = $2;
1219 ($headline = &read_line()) =~ s/\r|\n//g;
1220 last if ($headline eq "");
1221 print DEBUG "handle_request: got headline $headline\n";
1222 if ($headline =~ /^(\S+):\s*(.*)$/) {
1223 $header{$lastheader = lc($1)} = $2;
1225 elsif ($headline =~ /^\s+(.*)$/) {
1226 $header{$lastheader} .= $headline;
1229 &http_error(400, "Bad Header $headline");
1232 if (defined($header{'host'})) {
1233 if ($header{'host'} =~ /^([^:]+):([0-9]+)$/) {
1234 ($host, $port) = ($1, $2);
1237 $host = $header{'host'};
1239 if ($config{'musthost'} && $host ne $config{'musthost'}) {
1240 # Disallowed hostname used
1241 &http_error(400, "Invalid HTTP hostname");
1245 if ($page =~ /^([^\?]+)\?(.*)$/) {
1246 # There is some query string information
1249 print DEBUG "handle_request: querystring=$querystring\n";
1250 if ($querystring !~ /=/) {
1251 $queryargs = $querystring;
1252 $queryargs =~ s/\+/ /g;
1253 $queryargs =~ s/%(..)/pack("c",hex($1))/ge;
1257 # Parse query-string parameters
1258 local @in = split(/\&/, $querystring);
1260 local ($k, $v) = split(/=/, $i, 2);
1261 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1262 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1267 $posted_data = undef;
1268 if ($method eq 'POST' &&
1269 $header{'content-type'} eq 'application/x-www-form-urlencoded') {
1270 # Read in posted query string information, up the configured maximum
1271 # post request length
1272 $clen = $header{"content-length"};
1273 $clen_read = $clen > $config{'max_post'} ? $config{'max_post'} : $clen;
1274 while(length($posted_data) < $clen_read) {
1275 $buf = &read_data($clen_read - length($posted_data));
1276 if (!length($buf)) {
1277 &http_error(500, "Failed to read POST request");
1279 chomp($posted_data);
1280 $posted_data =~ s/\015$//mg;
1281 $posted_data .= $buf;
1283 print DEBUG "clen_read=$clen_read clen=$clen posted_data=",length($posted_data),"\n";
1284 if ($clen_read != $clen && length($posted_data) > $clen) {
1285 # If the client sent more data than we asked for, chop the
1287 $posted_data = substr($posted_data, 0, $clen);
1289 if (length($posted_data) > $clen) {
1290 # When the client sent too much, delay so that it gets headers
1293 if ($header{'user-agent'} =~ /MSIE/ &&
1294 $header{'user-agent'} !~ /Opera/i) {
1295 # MSIE includes an extra newline in the data
1296 $posted_data =~ s/\r|\n//g;
1298 local @in = split(/\&/, $posted_data);
1300 local ($k, $v) = split(/=/, $i, 2);
1302 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1303 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1306 print DEBUG "handle_request: posted_data=$posted_data\n";
1309 # replace %XX sequences in page
1310 $page =~ s/%(..)/pack("c",hex($1))/ge;
1312 # Check if the browser's user agent indicates a mobile device
1313 $mobile_device = &is_mobile_useragent($header{'user-agent'});
1315 # Check if Host: header is for a mobile URL
1316 foreach my $m (@mobile_prefixes) {
1317 if ($header{'host'} =~ /^\Q$m\E/i) {
1322 # check for the logout flag file, and if existant deny authentication
1323 if ($config{'logout'} && -r $config{'logout'}.$in{'miniserv_logout_id'}) {
1324 print DEBUG "handle_request: logout flag set\n";
1325 $deny_authentication++;
1326 open(LOGOUT, $config{'logout'}.$in{'miniserv_logout_id'});
1327 chop($count = <LOGOUT>);
1331 open(LOGOUT, ">$config{'logout'}$in{'miniserv_logout_id'}");
1332 print LOGOUT "$count\n";
1336 unlink($config{'logout'}.$in{'miniserv_logout_id'});
1340 # check for any redirect for the requested URL
1341 foreach my $pfx (@strip_prefix) {
1342 my $l = length($pfx);
1343 if(length($page) >= $l &&
1344 substr($page,0,$l) eq $pfx) {
1345 $page=substr($page,$l);
1349 $simple = &simplify_path($page, $bogus);
1351 $rpath .= "&".$querystring if (defined($querystring));
1352 $redir = $redirect{$rpath};
1353 if (defined($redir)) {
1354 print DEBUG "handle_request: redir=$redir\n";
1355 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1356 &write_data("Date: $datestr\r\n");
1357 &write_data("Server: $config{'server'}\r\n");
1358 local $ssl = $use_ssl || $config{'inetd_ssl'};
1359 $portstr = $port == 80 && !$ssl ? "" :
1360 $port == 443 && $ssl ? "" : ":$port";
1361 $prot = $ssl ? "https" : "http";
1362 &write_data("Location: $prot://$host$portstr$redir\r\n");
1363 &write_keep_alive(0);
1364 &write_data("\r\n");
1368 # Check for a DAV request
1370 foreach my $d (@davpaths) {
1371 if ($simple eq $d || $simple =~ /^\Q$d\E\//) {
1376 if (!$davpath && ($method eq "SEARCH" || $method eq "PUT")) {
1377 &http_error(400, "Bad Request method $method");
1380 # Check for password if needed
1382 print DEBUG "handle_request: Need authentication\n";
1386 # Session authentication is never used for connections by
1387 # another webmin server, or for specified pages, or for DAV, or XMLRPC,
1388 # or mobile browsers if requested.
1389 if ($header{'user-agent'} =~ /webmin/i ||
1390 $header{'user-agent'} =~ /$config{'agents_nosession'}/i ||
1391 $sessiononly{$simple} || $davpath ||
1392 $simple eq "/xmlrpc.cgi" ||
1393 $acptip eq $config{'host_nosession'} ||
1394 $mobile_device && $config{'mobile_nosession'}) {
1395 print DEBUG "handle_request: Forcing HTTP authentication\n";
1396 $config{'session'} = 0;
1399 # check for SSL authentication
1400 if ($use_ssl && $verified_client) {
1401 $peername = Net::SSLeay::X509_NAME_oneline(
1402 Net::SSLeay::X509_get_subject_name(
1403 Net::SSLeay::get_peer_certificate(
1405 local $peername2 = $peername;
1406 $peername2 =~ s/Email=/emailAddress=/ ||
1407 $peername2 =~ s/emailAddress=/Email=/;
1408 foreach $u (keys %certs) {
1409 if ($certs{$u} eq $peername ||
1410 $certs{$u} eq $peername2) {
1413 #syslog("info", "%s", "SSL login as $authuser from $acpthost") if ($use_syslog);
1417 if ($use_syslog && !$validated) {
1418 syslog("crit", "%s",
1419 "Unknown SSL certificate $peername");
1423 if (!$validated && !$deny_authentication) {
1424 # check for IP-based authentication
1426 foreach $a (keys %ipaccess) {
1427 if ($acptip eq $a) {
1428 # It does! Auth as the user
1430 $baseauthuser = $authuser =
1436 # Check for normal HTTP authentication
1437 if (!$validated && !$deny_authentication && !$config{'session'} &&
1438 $header{authorization} =~ /^basic\s+(\S+)$/i) {
1439 # authorization given..
1440 ($authuser, $authpass) = split(/:/, &b64decode($1), 2);
1441 print DEBUG "handle_request: doing basic auth check authuser=$authuser authpass=$authpass\n";
1442 local ($vu, $expired, $nonexist) =
1443 &validate_user($authuser, $authpass, $host);
1444 print DEBUG "handle_request: vu=$vu expired=$expired nonexist=$nonexist\n";
1445 if ($vu && (!$expired || $config{'passwd_mode'} == 1)) {
1452 if ($use_syslog && !$validated) {
1453 syslog("crit", "%s",
1454 ($nonexist ? "Non-existent" :
1455 $expired ? "Expired" : "Invalid").
1456 " login as $authuser from $acpthost");
1458 if ($authuser =~ /\r|\n|\s/) {
1459 &http_error(500, "Invalid username",
1460 "Username contains invalid characters");
1462 if ($authpass =~ /\r|\n/) {
1463 &http_error(500, "Invalid password",
1464 "Password contains invalid characters");
1467 if ($config{'passdelay'} && !$config{'inetd'}) {
1468 # check with main process for delay
1469 print DEBUG "handle_request: about to ask for password delay\n";
1470 print $PASSINw "delay $authuser $acptip $validated\n";
1471 <$PASSOUTr> =~ /(\d+) (\d+)/;
1473 print DEBUG "handle_request: password delay $1 $2\n";
1478 # Check for a visit to the special session login page
1479 if ($config{'session'} && !$deny_authentication &&
1480 $page eq $config{'session_login'}) {
1481 if ($in{'logout'} && $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1482 # Logout clicked .. remove the session
1484 print $PASSINw "delete $sid\n";
1485 local $louser = <$PASSOUTr>;
1488 $already_session_id = undef;
1489 $authuser = $baseauthuser = undef;
1492 syslog("info", "%s", "Logout by $louser from $acpthost");
1494 &run_logout_script($louser, $sid,
1496 &write_logout_utmp($louser, $actphost);
1501 if ($in{'user'} =~ /\r|\n|\s/) {
1502 &http_error(500, "Invalid username",
1503 "Username contains invalid characters");
1505 if ($in{'pass'} =~ /\r|\n/) {
1506 &http_error(500, "Invalid password",
1507 "Password contains invalid characters");
1510 local ($vu, $expired, $nonexist) =
1511 &validate_user($in{'user'}, $in{'pass'}, $host);
1512 local $hrv = &handle_login(
1513 $vu || $in{'user'}, $vu ? 1 : 0,
1514 $expired, $nonexist, $in{'pass'},
1515 $in{'notestingcookie'});
1516 return $hrv if (defined($hrv));
1520 # Check for a visit to the special PAM login page
1521 if ($config{'session'} && !$deny_authentication &&
1522 $use_pam && $config{'pam_conv'} && $page eq $config{'pam_login'} &&
1524 # A question has been entered .. submit it to the main process
1525 print DEBUG "handle_request: Got call to $page ($in{'cid'})\n";
1526 print DEBUG "handle_request: For PAM, authuser=$authuser\n";
1527 if ($in{'answer'} =~ /\r|\n/ || $in{'cid'} =~ /\r|\n|\s/) {
1528 &http_error(500, "Invalid response",
1529 "Response contains invalid characters");
1533 # Start of a new conversation - answer must be username
1534 $cid = &generate_random_id($in{'answer'});
1535 print $PASSINw "pamstart $cid $host $in{'answer'}\n";
1538 # A response to a previous question
1540 print $PASSINw "pamanswer $cid $in{'answer'}\n";
1543 # Read back the response, and the next question (if any)
1544 local $line = <$PASSOUTr>;
1545 $line =~ s/\r|\n//g;
1546 local ($rv, $question) = split(/\s+/, $line, 2);
1549 local $hrv = &handle_login(
1550 !$in{'cid'} && $in{'answer'} ? $in{'answer'}
1553 return $hrv if (defined($hrv));
1555 elsif ($rv == 1 || $rv == 3) {
1556 # Another question .. force use of PAM CGI
1559 $querystring .= "&cid=$cid&question=".
1561 $querystring .= "&password=1" if ($rv == 3);
1563 $page = $config{'pam_login'};
1564 $miniserv_internal = 1;
1568 # Got back a final ok or failure
1569 local ($user, $ok, $expired, $nonexist) =
1570 split(/\s+/, $question);
1571 local $hrv = &handle_login(
1572 $user, $ok, $expired, $nonexist, undef,
1573 $in{'notestingcookie'});
1574 return $hrv if (defined($hrv));
1577 # A message from PAM .. tell the user
1580 $querystring .= "&cid=$cid&message=".
1583 $page = $config{'pam_login'};
1584 $miniserv_internal = 1;
1589 # Check for a visit to the special password change page
1590 if ($config{'session'} && !$deny_authentication &&
1591 $page eq $config{'password_change'} && !$validated) {
1592 # Just let this slide ..
1594 $miniserv_internal = 3;
1597 # Check for an existing session
1598 if ($config{'session'} && !$validated) {
1599 if ($already_session_id) {
1600 $session_id = $already_session_id;
1601 $authuser = $already_authuser;
1604 elsif (!$deny_authentication &&
1605 $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1607 local $notimeout = $in{'webmin_notimeout'} ? 1 : 0;
1608 print $PASSINw "verify $session_id $notimeout\n";
1609 <$PASSOUTr> =~ /(\d+)\s+(\S+)/;
1611 # Valid session continuation
1614 #$already_session_id = $session_id;
1615 $already_authuser = $authuser;
1622 # Invalid session ID .. don't set verified
1627 # Check for local authentication
1628 if ($localauth_user && !$header{'x-forwarded-for'} && !$header{'via'}) {
1629 if (defined($users{$localauth_user})) {
1630 # Local user exists in webmin users file
1632 $authuser = $localauth_user;
1635 # Check if local user is allowed by unixauth
1636 local @can = &can_user_login($localauth_user,
1640 $authuser = $localauth_user;
1643 $localauth_user = undef;
1649 # Check if this path allows anonymous access
1651 foreach $a (keys %anonymous) {
1652 if (substr($simple, 0, length($a)) eq $a) {
1653 # It does! Auth as the user, if IP access
1654 # control allows him.
1655 if (&check_user_ip($anonymous{$a}) &&
1656 &check_user_time($anonymous{$a})) {
1658 $baseauthuser = $authuser =
1666 # Check if this path allows unauthenticated access
1667 local ($u, $unauth);
1668 foreach $u (@unauth) {
1669 $unauth++ if ($simple =~ /$u/);
1671 if (!$bogus && $unauth) {
1672 # Unauthenticated directory or file request - approve it
1674 $baseauthuser = $authuser = undef;
1679 if ($blocked == 0) {
1680 # No password given.. ask
1681 if ($config{'pam_conv'} && $use_pam) {
1682 # Force CGI for PAM question, starting with
1683 # the username which is always needed
1686 $querystring .= "&initial=1&question=".
1687 &urlize("Username");
1688 $querystring .= "&failed=$failed_user" if ($failed_user);
1689 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1691 $page = $config{'pam_login'};
1692 $miniserv_internal = 1;
1695 elsif ($config{'session'}) {
1696 # Force CGI for session login
1699 $querystring .= "&logout=1&page=/";
1702 # Re-direct to current module only
1703 local $rpage = $request_uri;
1704 if (!$config{'loginkeeppage'}) {
1705 $rpage =~ s/\?.*$//;
1706 $rpage =~ s/[^\/]+$//
1708 $querystring = "page=".&urlize($rpage);
1711 $querystring .= "&failed=$failed_user" if ($failed_user);
1712 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1714 $page = $config{'session_login'};
1715 $miniserv_internal = 1;
1719 # Ask for login with HTTP authentication
1720 &write_data("HTTP/1.0 401 Unauthorized\r\n");
1721 &write_data("Date: $datestr\r\n");
1722 &write_data("Server: $config{'server'}\r\n");
1723 &write_data("WWW-authenticate: Basic ".
1724 "realm=\"$config{'realm'}\"\r\n");
1725 &write_keep_alive(0);
1726 &write_data("Content-type: text/html\r\n");
1727 &write_data("\r\n");
1728 &reset_byte_count();
1729 &write_data("<html>\n");
1730 &write_data("<head><title>Unauthorized</title></head>\n");
1731 &write_data("<body><h1>Unauthorized</h1>\n");
1732 &write_data("A password is required to access this\n");
1733 &write_data("web server. Please try again. <p>\n");
1734 &write_data("</body></html>\n");
1735 &log_request($acpthost, undef, $reqline, 401, &byte_count());
1739 elsif ($blocked == 1) {
1740 # when the host has been blocked, give it an error
1741 &http_error(403, "Access denied for $acptip. The host ".
1742 "has been blocked because of too ".
1743 "many authentication failures.");
1745 elsif ($blocked == 2) {
1746 # when the user has been blocked, give it an error
1747 &http_error(403, "Access denied. The user ".
1748 "has been blocked because of too ".
1749 "many authentication failures.");
1753 # Get the real Webmin username
1754 local @can = &can_user_login($authuser, undef, $host);
1755 $baseauthuser = $can[3] || $authuser;
1757 if ($config{'remoteuser'} && !$< && $validated) {
1758 # Switch to the UID of the remote user (if he exists)
1759 local @u = getpwnam($authuser);
1760 if (@u && $< != $u[2]) {
1761 $( = $u[3]; $) = "$u[3] $u[3]";
1762 ($>, $<) = ($u[2], $u[2]);
1765 &http_error(500, "Unix user $authuser does not exist");
1771 # Check per-user IP access control
1772 if (!&check_user_ip($baseauthuser)) {
1773 &http_error(403, "Access denied for $acptip for $baseauthuser");
1777 # Check per-user allowed times
1778 if (!&check_user_time($baseauthuser)) {
1779 &http_error(403, "Access denied at the current time");
1784 # Validate the path, and convert to canonical form
1786 $simple = &simplify_path($page, $bogus);
1787 print DEBUG "handle_request: page=$page simple=$simple\n";
1789 &http_error(400, "Invalid path");
1792 # Check for a DAV request
1794 return &handle_dav_request($davpath);
1797 # Work out the active theme(s)
1798 local $preroots = $mobile_device && defined($config{'mobile_preroot'}) ?
1799 $config{'mobile_preroot'} :
1800 $authuser && defined($config{'preroot_'.$authuser}) ?
1801 $config{'preroot_'.$authuser} :
1802 $authuser && $baseauthuser &&
1803 defined($config{'preroot_'.$baseauthuser}) ?
1804 $config{'preroot_'.$baseauthuser} :
1806 local @preroots = reverse(split(/\s+/, $preroots));
1808 # Canonicalize the directories
1809 foreach my $preroot (@preroots) {
1810 # Always under the current webmin root
1811 $preroot =~ s/^.*\///g;
1812 $preroot = $roots[0].'/'.$preroot;
1815 # Look in the theme root directories first
1816 local ($full, @stfull);
1818 foreach my $preroot (@preroots) {
1821 $full = $preroot.$sofar;
1822 $scriptname = $simple;
1823 foreach $b (split(/\//, $simple)) {
1824 if ($b ne "") { $sofar .= "/$b"; }
1825 $full = $preroot.$sofar;
1826 @stfull = stat($full);
1827 if (!@stfull) { undef($full); last; }
1829 # Check if this is a directory
1831 # It is.. go on parsing
1839 # Check if this is a CGI program
1840 if (&get_type($full) eq "internal/cgi") {
1841 $pathinfo = substr($simple, length($sofar));
1842 $pathinfo .= "/" if ($page =~ /\/$/);
1843 $scriptname = $sofar;
1848 # Don't stop at a directory unless this is the last theme, which
1849 # is the 'real' one that provides the .cgi scripts
1850 if ($is_directory && $preroot ne $preroots[$#preroots]) {
1857 $cgi_pwd = $roots[0];
1859 elsif ($is_directory) {
1860 $cgi_pwd = "$roots[0]$sofar";
1863 "$roots[0]$sofar" =~ /^(.*\/)[^\/]+$/;
1866 $foundroot = $preroot;
1867 if ($is_directory) {
1868 # Check for index files in the directory
1870 foreach $idx (split(/\s+/, $config{"index_docs"})) {
1871 $idxfull = "$full/$idx";
1872 local @stidxfull = stat($idxfull);
1873 if (-r _ && !-d _) {
1875 @stfull = @stidxfull;
1878 if ($scriptname ne "/");
1883 @stfull = stat($full) if (!$foundidx);
1886 last if ($foundroot);
1888 print DEBUG "handle_request: initial full=$full\n";
1890 # Look in the real root directories, stopping when we find a file or directory
1891 if (!$full || $is_directory) {
1892 ROOT: foreach $root (@roots) {
1894 $full = $root.$sofar;
1895 $scriptname = $simple;
1896 foreach $b ($simple eq "/" ? ( "" ) : split(/\//, $simple)) {
1897 if ($b ne "") { $sofar .= "/$b"; }
1898 $full = $root.$sofar;
1899 @stfull = stat($full);
1904 # Check if this is a directory
1906 # It is.. go on parsing
1910 # Check if this is a CGI program
1911 if (&get_type($full) eq "internal/cgi") {
1912 $pathinfo = substr($simple, length($sofar));
1913 $pathinfo .= "/" if ($page =~ /\/$/);
1914 $scriptname = $sofar;
1919 # Run CGI in the same directory as whatever file
1921 $full =~ /^(.*\/)[^\/]+$/; $cgi_pwd = $1;
1930 if (!@stfull) { &http_error(404, "File not found"); }
1932 print DEBUG "handle_request: full=$full\n";
1933 @stfull = stat($full) if (!@stfull);
1935 # check filename against denyfile regexp
1936 local $denyfile = $config{'denyfile'};
1937 if ($denyfile && $full =~ /$denyfile/) {
1938 &http_error(403, "Access denied to $page");
1942 # Reached the end of the path OK.. see what we've got
1944 # See if the URL ends with a / as it should
1945 print DEBUG "handle_request: found a directory\n";
1946 if ($page !~ /\/$/) {
1947 # It doesn't.. redirect
1948 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1949 $ssl = $use_ssl || $config{'inetd_ssl'};
1950 $portstr = $port == 80 && !$ssl ? "" :
1951 $port == 443 && $ssl ? "" : ":$port";
1952 &write_data("Date: $datestr\r\n");
1953 &write_data("Server: $config{server}\r\n");
1954 $prot = $ssl ? "https" : "http";
1955 &write_data("Location: $prot://$host$portstr$page/\r\n");
1956 &write_keep_alive(0);
1957 &write_data("\r\n");
1958 &log_request($acpthost, $authuser, $reqline, 302, 0);
1961 # A directory.. check for index files
1963 foreach $idx (split(/\s+/, $config{"index_docs"})) {
1964 $idxfull = "$full/$idx";
1965 @stidxfull = stat($idxfull);
1966 if (-r _ && !-d _) {
1969 @stfull = @stidxfull;
1970 $scriptname .= "/" if ($scriptname ne "/");
1975 @stfull = stat($full) if (!$foundidx);
1978 # This is definately a directory.. list it
1979 print DEBUG "handle_request: listing directory\n";
1980 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
1981 "Date: $datestr\r\n".
1982 "Server: $config{server}\r\n".
1983 "Content-type: text/html\r\n";
1985 &write_keep_alive(0);
1986 &write_data("\r\n");
1987 &reset_byte_count();
1988 &write_data("<h1>Index of $simple</h1>\n");
1989 &write_data("<pre>\n");
1990 &write_data(sprintf "%-35.35s %-20.20s %-10.10s\n",
1991 "Name", "Last Modified", "Size");
1992 &write_data("<hr>\n");
1993 opendir(DIR, $full);
1994 while($df = readdir(DIR)) {
1995 if ($df =~ /^\./) { next; }
1996 $fulldf = $full eq "/" ? $full.$df : $full."/".$df;
1997 (@stbuf = stat($fulldf)) || next;
1998 if (-d _) { $df .= "/"; }
1999 @tm = localtime($stbuf[9]);
2000 $fdate = sprintf "%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d",
2001 $tm[3],$tm[4]+1,$tm[5]+1900,
2002 $tm[0],$tm[1],$tm[2];
2003 $len = length($df); $rest = " "x(35-$len);
2005 "<a href=\"%s\">%-${len}.${len}s</a>$rest %-20.20s %-10.10s\n",
2006 $df, $df, $fdate, $stbuf[7]);
2009 &log_request($acpthost, $authuser, $reqline, $ok_code, &byte_count());
2013 # CGI or normal file
2015 if (&get_type($full) eq "internal/cgi" && $validated != 4) {
2016 # A CGI program to execute
2017 print DEBUG "handle_request: executing CGI\n";
2018 $envtz = $ENV{"TZ"};
2019 $envuser = $ENV{"USER"};
2020 $envpath = $ENV{"PATH"};
2021 $envlang = $ENV{"LANG"};
2022 $envroot = $ENV{"SystemRoot"};
2023 foreach my $k (keys %ENV) {
2026 $ENV{"PATH"} = $envpath if ($envpath);
2027 $ENV{"TZ"} = $envtz if ($envtz);
2028 $ENV{"USER"} = $envuser if ($envuser);
2029 $ENV{"OLD_LANG"} = $envlang if ($envlang);
2030 $ENV{"SystemRoot"} = $envroot if ($envroot);
2031 $ENV{"HOME"} = $user_homedir;
2032 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
2033 $ENV{"SERVER_NAME"} = $host;
2034 $ENV{"SERVER_ADMIN"} = $config{"email"};
2035 $ENV{"SERVER_ROOT"} = $roots[0];
2036 $ENV{"SERVER_REALROOT"} = $realroot;
2037 $ENV{"SERVER_PORT"} = $port;
2038 $ENV{"REMOTE_HOST"} = $acpthost;
2039 $ENV{"REMOTE_ADDR"} = $acptip;
2040 $ENV{"REMOTE_USER"} = $authuser;
2041 $ENV{"BASE_REMOTE_USER"} = $authuser ne $baseauthuser ?
2042 $baseauthuser : undef;
2043 $ENV{"REMOTE_PASS"} = $authpass if (defined($authpass) &&
2044 $config{'pass_password'});
2045 print DEBUG "REMOTE_USER = ",$ENV{"REMOTE_USER"},"\n";
2046 print DEBUG "BASE_REMOTE_USER = ",$ENV{"BASE_REMOTE_USER"},"\n";
2047 $ENV{"SSL_USER"} = $peername if ($validated == 2);
2048 $ENV{"ANONYMOUS_USER"} = "1" if ($validated == 3 || $validated == 4);
2049 $ENV{"DOCUMENT_ROOT"} = $roots[0];
2050 $ENV{"DOCUMENT_REALROOT"} = $realroot;
2051 $ENV{"GATEWAY_INTERFACE"} = "CGI/1.1";
2052 $ENV{"SERVER_PROTOCOL"} = "HTTP/1.0";
2053 $ENV{"REQUEST_METHOD"} = $method;
2054 $ENV{"SCRIPT_NAME"} = $scriptname;
2055 $ENV{"SCRIPT_FILENAME"} = $full;
2056 $ENV{"REQUEST_URI"} = $request_uri;
2057 $ENV{"PATH_INFO"} = $pathinfo;
2059 $ENV{"PATH_TRANSLATED"} = "$roots[0]$pathinfo";
2060 $ENV{"PATH_REALTRANSLATED"} = "$realroot$pathinfo";
2062 $ENV{"QUERY_STRING"} = $querystring;
2063 $ENV{"MINISERV_CONFIG"} = $config_file;
2064 $ENV{"HTTPS"} = "ON" if ($use_ssl || $config{'inetd_ssl'});
2065 $ENV{"SESSION_ID"} = $session_id if ($session_id);
2066 $ENV{"LOCAL_USER"} = $localauth_user if ($localauth_user);
2067 $ENV{"MINISERV_INTERNAL"} = $miniserv_internal if ($miniserv_internal);
2068 if (defined($header{"content-length"})) {
2069 $ENV{"CONTENT_LENGTH"} = $header{"content-length"};
2071 if (defined($header{"content-type"})) {
2072 $ENV{"CONTENT_TYPE"} = $header{"content-type"};
2074 foreach $h (keys %header) {
2075 ($hname = $h) =~ tr/a-z/A-Z/;
2077 $ENV{"HTTP_$hname"} = $header{$h};
2079 $ENV{"PWD"} = $cgi_pwd;
2080 foreach $k (keys %config) {
2081 if ($k =~ /^env_(\S+)$/) {
2082 $ENV{$1} = $config{$k};
2085 delete($ENV{'HTTP_AUTHORIZATION'});
2086 $ENV{'HTTP_COOKIE'} =~ s/;?\s*$sidname=([a-f0-9]+)//;
2087 $ENV{'MOBILE_DEVICE'} = 1 if ($mobile_device);
2089 # Check if the CGI can be handled internally
2091 local $first = <CGI>;
2093 $first =~ s/[#!\r\n]//g;
2094 $nph_script = ($full =~ /\/nph-([^\/]+)$/);
2096 if (!$config{'forkcgis'} &&
2097 ($first eq $perl_path || $first eq $linked_perl_path) &&
2099 $config{'internalcgis'}) {
2100 # setup environment for eval
2102 @ARGV = split(/\s+/, $queryargs);
2105 # Already read the post input
2106 $postinput = $posted_data;
2108 $clen = $header{"content-length"};
2109 $SIG{'CHLD'} = 'DEFAULT';
2111 # Have SOCK closed if the perl exec's something
2113 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
2117 if ($config{'log'}) {
2118 open(MINISERVLOG, ">>$config{'logfile'}");
2119 if ($config{'logperms'}) {
2120 chmod(oct($config{'logperms'}),
2121 $config{'logfile'});
2124 chmod(0600, $config{'logfile'});
2128 $main_process_id = $$;
2130 if ($full =~ /^\Q$foundroot\E\/([^\/]+)\//) {
2131 # Eval in package from Webmin module name
2133 $pkg =~ s/[^A-Za-z0-9]/_/g;
2138 tie(*STDOUT, 'miniserv');
2139 tie(*STDIN, 'miniserv');
2140 do \$miniserv::full;
2146 &http_error(500, "Perl execution failed",
2147 $config{'noshowstderr'} ? undef : $@);
2149 elsif (!$doneheaders && !$nph_script) {
2150 &http_error(500, "Missing Headers");
2157 # fork the process that actually executes the CGI
2158 pipe(CGIINr, CGIINw);
2159 pipe(CGIOUTr, CGIOUTw);
2160 pipe(CGIERRr, CGIERRw);
2161 if (!($cgipid = fork())) {
2162 @execargs = ( $full, split(/\s+/, $queryargs) );
2165 open(STDIN, "<&CGIINr");
2166 open(STDOUT, ">&CGIOUTw");
2167 open(STDERR, ">&CGIERRw");
2168 close(CGIINw); close(CGIOUTr); close(CGIERRr);
2170 die "Failed to exec $full : $!\n";
2173 close(CGIINr); close(CGIOUTw); close(CGIERRw);
2176 # write CGI input to a temp file
2177 $infile = "$config{'tempbase'}.$$";
2178 open(CGIINw, ">$infile");
2179 # NOT binary mode, as CGIs don't read in it!
2184 # already read the posted data
2185 print CGIINw $posted_data;
2187 $clen = $header{"content-length"};
2188 if ($method eq "POST" && $clen_read < $clen) {
2189 $SIG{'PIPE'} = 'IGNORE';
2191 while($got < $clen) {
2192 $buf = &read_data($clen-$got);
2193 if (!length($buf)) {
2194 kill('TERM', $cgipid);
2195 unlink($infile) if ($infile);
2196 &http_error(500, "Failed to read ".
2199 $got += length($buf);
2200 local ($wrote) = (print CGIINw $buf);
2203 # If the CGI terminated early, we still need to read
2204 # from the browser and throw away
2205 while($got < $clen) {
2206 $buf = &read_data($clen-$got);
2207 if (!length($buf)) {
2208 kill('TERM', $cgipid);
2209 unlink($infile) if ($infile);
2210 &http_error(500, "Failed to read ".
2213 $got += length($buf);
2215 $SIG{'PIPE'} = 'DEFAULT';
2221 # Run the CGI program, and feed it input
2223 local $qqueryargs = join(" ", map { "\"$_\"" }
2224 split(/\s+/, $queryargs));
2225 if ($first =~ /(perl|perl.exe)$/i) {
2226 # On Windows, run with Perl
2227 open(CGIOUTr, "$perl_path \"$full\" $qqueryargs <$infile |");
2230 open(CGIOUTr, "\"$full\" $qqueryargs <$infile |");
2236 # read back cgi headers
2237 select(CGIOUTr); $|=1; select(STDOUT);
2241 $line =~ s/\r|\n//g;
2243 if ($got_blank || %cgiheader) { last; }
2247 if ($line !~ /^(\S+):\s+(.*)$/) {
2248 $errs = &read_errors(CGIERRr);
2249 close(CGIOUTr); close(CGIERRr);
2250 unlink($infile) if ($infile);
2251 &http_error(500, "Bad Header", $errs);
2253 $cgiheader{lc($1)} = $2;
2254 push(@cgiheader, [ $1, $2 ]);
2256 if ($cgiheader{"location"}) {
2257 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2258 &write_data("Date: $datestr\r\n");
2259 &write_data("Server: $config{'server'}\r\n");
2260 &write_keep_alive(0);
2261 # ignore the rest of the output. This is a hack,
2262 # but is necessary for IE in some cases :(
2263 close(CGIOUTr); close(CGIERRr);
2265 elsif ($cgiheader{"content-type"} eq "") {
2266 close(CGIOUTr); close(CGIERRr);
2267 unlink($infile) if ($infile);
2268 $errs = &read_errors(CGIERRr);
2269 &http_error(500, "Missing Content-Type Header",
2270 $config{'noshowstderr'} ? undef : $errs);
2273 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2274 &write_data("Date: $datestr\r\n");
2275 &write_data("Server: $config{'server'}\r\n");
2276 &write_keep_alive(0);
2278 foreach $h (@cgiheader) {
2279 &write_data("$h->[0]: $h->[1]\r\n");
2281 &write_data("\r\n");
2283 &reset_byte_count();
2284 while($line = <CGIOUTr>) {
2289 unlink($infile) if ($infile);
2295 print DEBUG "handle_request: outputting file\n";
2296 open(FILE, $full) || &http_error(404, "Failed to open file");
2298 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2299 "Date: $datestr\r\n".
2300 "Server: $config{server}\r\n".
2301 "Content-type: ".&get_type($full)."\r\n".
2302 "Content-length: $stfull[7]\r\n".
2303 "Last-Modified: ".&http_date($stfull[9])."\r\n".
2304 "Expires: ".&http_date(time()+$config{'expires'})."\r\n";
2306 $rv = &write_keep_alive();
2307 &write_data("\r\n");
2308 &reset_byte_count();
2309 while(read(FILE, $buf, 1024) > 0) {
2316 &log_request($acpthost, $authuser, $reqline,
2317 $logged_code ? $logged_code :
2318 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2322 # http_error(code, message, body, [dontexit])
2325 local $eh = $error_handler_recurse ? undef :
2326 $config{"error_handler_$_[0]"} ? $config{"error_handler_$_[0]"} :
2327 $config{'error_handler'} ? $config{'error_handler'} : undef;
2328 print DEBUG "http_error code=$_[0] message=$_[1] body=$_[2]\n";
2330 # Call a CGI program for the error
2332 $querystring = "code=$_[0]&message=".&urlize($_[1]).
2333 "&body=".&urlize($_[2]);
2334 $error_handler_recurse++;
2336 $ok_message = $_[1];
2340 # Use the standard error message display
2341 &write_data("HTTP/1.0 $_[0] $_[1]\r\n");
2342 &write_data("Server: $config{server}\r\n");
2343 &write_data("Date: $datestr\r\n");
2344 &write_data("Content-type: text/html\r\n");
2345 &write_keep_alive(0);
2346 &write_data("\r\n");
2347 &reset_byte_count();
2348 &write_data("<h1>Error - $_[1]</h1>\n");
2350 &write_data("<pre>$_[2]</pre>\n");
2353 &log_request($acpthost, $authuser, $reqline, $_[0], &byte_count())
2355 &log_error($_[1], $_[2] ? " : $_[2]" : "");
2362 if ($_[0] =~ /\.([A-z0-9]+)$/) {
2368 return "text/plain";
2371 # simplify_path(path, bogus)
2372 # Given a path, maybe containing stuff like ".." and "." convert it to a
2373 # clean, absolute form.
2376 local($dir, @bits, @fixedbits, $b);
2378 $dir =~ s/\\/\//g; # fix windows \ in path
2381 $dir =~ s/\0//g; # remove null bytes
2382 @bits = split(/\/+/, $dir);
2385 foreach $b (@bits) {
2389 elsif ($b eq ".." || $b eq "...") {
2391 if (scalar(@fixedbits) == 0) {
2399 push(@fixedbits, $b);
2402 return "/" . join('/', @fixedbits);
2406 # Converts a string from base64 format to normal
2409 local($str) = $_[0];
2411 $str =~ tr|A-Za-z0-9+=/||cd;
2413 $str =~ tr|A-Za-z0-9+/| -_|;
2414 while ($str =~ /(.{1,60})/gs) {
2415 my $len = chr(32 + length($1)*3/4);
2416 $res .= unpack("u", $len . $1 );
2421 # ip_match(remoteip, localip, [match]+)
2422 # Checks an IP address against a list of IPs, networks and networks/masks
2425 local(@io, @mo, @ms, $i, $j, $hn, $needhn);
2426 @io = split(/\./, $_[0]);
2427 for($i=2; $i<@_; $i++) {
2428 $needhn++ if ($_[$i] =~ /^\*(\S+)$/);
2430 if ($needhn && !defined($hn = $ip_match_cache{$_[0]})) {
2431 $hn = gethostbyaddr(inet_aton($_[0]), AF_INET);
2432 $hn = "" if (&to_ipaddress($hn) ne $_[0]);
2433 $ip_match_cache{$_[0]} = $hn;
2435 for($i=2; $i<@_; $i++) {
2436 local $mismatch = 0;
2437 if ($_[$i] =~ /^(\S+)\/(\d+)$/) {
2438 # Convert CIDR to netmask format
2439 $_[$i] = $1."/".&prefix_to_mask($2);
2441 if ($_[$i] =~ /^(\S+)\/(\S+)$/) {
2442 # Compare with network/mask
2443 @mo = split(/\./, $1); @ms = split(/\./, $2);
2444 for($j=0; $j<4; $j++) {
2445 if ((int($io[$j]) & int($ms[$j])) != int($mo[$j])) {
2450 elsif ($_[$i] =~ /^\*(\S+)$/) {
2451 # Compare with hostname regexp
2452 $mismatch = 1 if ($hn !~ /$1$/);
2454 elsif ($_[$i] eq 'LOCAL') {
2455 # Compare with local network
2456 local @lo = split(/\./, $_[1]);
2458 $mismatch = 1 if ($lo[0] != $io[0]);
2460 elsif ($lo[0] < 192) {
2461 $mismatch = 1 if ($lo[0] != $io[0] ||
2465 $mismatch = 1 if ($lo[0] != $io[0] ||
2470 elsif ($_[$i] !~ /^[0-9\.]+$/) {
2471 # Compare with hostname
2472 $mismatch = 1 if ($_[0] ne &to_ipaddress($_[$i]));
2475 # Compare with IP or network
2476 @mo = split(/\./, $_[$i]);
2477 while(@mo && !$mo[$#mo]) { pop(@mo); }
2478 for($j=0; $j<@mo; $j++) {
2479 if ($mo[$j] != $io[$j]) {
2484 return 1 if (!$mismatch);
2489 # users_match(&uinfo, user, ...)
2490 # Returns 1 if a user is in a list of users and groups
2493 local $uinfo = shift(@_);
2495 local @ginfo = getgrgid($uinfo->[3]);
2497 if ($u =~ /^\@(\S+)$/) {
2498 return 1 if (&is_group_member($uinfo, $1));
2500 elsif ($u =~ /^(\d*)-(\d*)$/ && ($1 || $2)) {
2501 return (!$1 || $uinfo[2] >= $1) &&
2502 (!$2 || $uinfo[2] <= $2);
2505 return 1 if ($u eq $uinfo->[0]);
2511 # restart_miniserv()
2512 # Called when a SIGHUP is received to restart the web server. This is done
2513 # by exec()ing perl with the same command line as was originally used
2514 sub restart_miniserv
2516 print STDERR "restarting miniserv\n";
2517 &log_error("Restarting");
2519 &close_all_sockets();
2521 dbmclose(%sessiondb);
2522 kill('KILL', $logclearer) if ($logclearer);
2523 kill('KILL', $extauth) if ($extauth);
2524 exec($perl_path, $miniserv_path, @miniserv_argv);
2525 die "Failed to restart miniserv with $perl_path $miniserv_path";
2542 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2543 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/) { push(@rv, $i); }
2544 else { push(@rv, join('.', unpack("CCCC", inet_aton($i)))); }
2546 return wantarray ? @rv : $rv[0];
2549 # read_line(no-wait, no-limit)
2550 # Reads one line from SOCK or SSL
2553 local ($nowait, $nolimit) = @_;
2554 local($idx, $more, $rv);
2555 while(($idx = index($main::read_buffer, "\n")) < 0) {
2556 if (length($main::read_buffer) > 10000 && !$nolimit) {
2557 &http_error(414, "Request too long",
2558 "Received excessive line <pre>$main::read_buffer</pre>");
2561 # need to read more..
2562 &wait_for_data_error() if (!$nowait);
2564 $more = Net::SSLeay::read($ssl_con);
2567 local $ok = sysread(SOCK, $more, 1024);
2568 $more = undef if ($ok <= 0);
2572 $rv = $main::read_buffer;
2573 undef($main::read_buffer);
2576 $main::read_buffer .= $more;
2578 $rv = substr($main::read_buffer, 0, $idx+1);
2579 $main::read_buffer = substr($main::read_buffer, $idx+1);
2584 # Reads up to some amount of data from SOCK or the SSL connection
2588 if (length($main::read_buffer)) {
2589 if (length($main::read_buffer) > $_[0]) {
2590 # Return the first part of the buffer
2591 $rv = substr($main::read_buffer, 0, $_[0]);
2592 $main::read_buffer = substr($main::read_buffer, $_[0]);
2596 # Return the whole buffer
2597 $rv = $main::read_buffer;
2598 undef($main::read_buffer);
2603 # Call SSL read function
2604 return Net::SSLeay::read($ssl_con, $_[0]);
2607 # Just do a normal read
2609 sysread(SOCK, $buf, $_[0]) || return undef;
2615 # Read a line from a file handle, using sysread to get a byte at a time
2622 $got = sysread($fh, $buf, 1);
2623 last if ($got <= 0);
2625 last if ($buf eq "\n");
2630 # wait_for_data(secs)
2631 # Waits at most the given amount of time for some data on SOCK, returning
2632 # 0 if not found, 1 if some arrived.
2636 vec($rmask, fileno(SOCK), 1) = 1;
2637 local $got = select($rmask, undef, undef, $_[0]);
2638 return $got == 0 ? 0 : 1;
2641 # wait_for_data_error()
2642 # Waits 60 seconds for data on SOCK, and fails if none arrives
2643 sub wait_for_data_error
2645 local $got = &wait_for_data(60);
2647 &http_error(400, "Timeout",
2648 "Waited more than 60 seconds for request data");
2652 # write_data(data, ...)
2653 # Writes a string to SOCK or the SSL connection
2656 local $str = join("", @_);
2658 Net::SSLeay::write($ssl_con, $str);
2661 syswrite(SOCK, $str, length($str));
2663 # Intentionally introduce a small delay to avoid problems where IE reports
2664 # the page as empty / DNS failed when it get a large response too quickly!
2665 select(undef, undef, undef, .01) if ($write_data_count%10 == 0);
2666 $write_data_count += length($str);
2669 # reset_byte_count()
2670 sub reset_byte_count { $write_data_count = 0; }
2673 sub byte_count { return $write_data_count; }
2675 # log_request(hostname, user, request, code, bytes)
2678 if ($config{'log'}) {
2679 local ($user, $ident, $headers);
2680 if ($config{'logident'}) {
2681 # add support for rfc1413 identity checking here
2683 else { $ident = "-"; }
2684 $user = $_[1] ? $_[1] : "-";
2685 local $dstr = &make_datestr();
2686 if (fileno(MINISERVLOG)) {
2687 seek(MINISERVLOG, 0, 2);
2690 open(MINISERVLOG, ">>$config{'logfile'}");
2691 chmod(0600, $config{'logfile'});
2693 if (defined($config{'logheaders'})) {
2694 foreach $h (split(/\s+/, $config{'logheaders'})) {
2695 $headers .= " $h=\"$header{$h}\"";
2698 elsif ($config{'logclf'}) {
2699 $headers = " \"$header{'referer'}\" \"$header{'user-agent'}\"";
2704 print MINISERVLOG "$_[0] $ident $user [$dstr] \"$_[2]\" ",
2705 "$_[3] $_[4]$headers\n";
2713 local @tm = localtime(time());
2714 return sprintf "%2.2d/%s/%4.4d:%2.2d:%2.2d:%2.2d %s",
2715 $tm[3], $month[$tm[4]], $tm[5]+1900,
2716 $tm[2], $tm[1], $tm[0], $timezone;
2719 # log_error(message)
2723 print STDERR "[",&make_datestr(),"] ",
2724 $acpthost ? ( "[",$acpthost,"] " ) : ( ),
2725 $page ? ( $page," : " ) : ( ),
2729 # read_errors(handle)
2730 # Read and return all input from some filehandle
2733 local($fh, $_, $rv);
2735 while(<$fh>) { $rv .= $_; }
2739 sub write_keep_alive
2742 if ($config{'nokeepalive'}) {
2743 # Keep alives have been disabled in config
2746 elsif (@childpids > $config{'maxconns'}*.8) {
2747 # Disable because nearing process limit
2751 # Keep alive specified by caller
2755 # Keep alive determined by browser
2756 $mode = $header{'connection'} =~ /keep-alive/i;
2758 &write_data("Connection: ".($mode ? "Keep-Alive" : "close")."\r\n");
2764 kill('TERM', @childpids) if (@childpids);
2765 kill('KILL', $logclearer) if ($logclearer);
2766 kill('KILL', $extauth) if ($extauth);
2772 local @tm = gmtime($_[0]);
2773 return sprintf "%s, %d %s %d %2.2d:%2.2d:%2.2d GMT",
2774 $weekday[$tm[6]], $tm[3], $month[$tm[4]], $tm[5]+1900,
2775 $tm[2], $tm[1], $tm[0];
2780 my $i; bless \$i, shift;
2786 my($buf,$len,$offset) = @_;
2787 &write_to_sock(substr($buf, $offset, $len));
2794 my $buf = join(defined($,) ? $, : "", @_);
2795 $buf .= $\ if defined($\);
2796 &write_to_sock($buf);
2803 &write_to_sock(sprintf $fmt, @_);
2806 # Send back already read data while we have it, then read from SOCK
2810 my $bufref = \$_[0];
2813 if ($postpos < length($postinput)) {
2814 # Reading from already fetched array
2815 my $left = length($postinput) - $postpos;
2816 my $canread = $len > $left ? $left : $len;
2817 substr($$bufref, $offset, $canread) =
2818 substr($postinput, $postpos, $canread);
2819 $postpos += $canread;
2823 # Read from network socket
2824 local $data = &read_data($len);
2825 if ($data eq '' && $len) {
2827 print STDERR "finished reading - shutting down socket\n";
2830 substr($$bufref, $offset, length($data)) = $data;
2831 return length($data);
2837 #print STDERR "open() called - should never happen!\n";
2840 # Read a line of input
2844 if ($postpos < length($postinput) &&
2845 ($idx = index($postinput, "\n", $postpos)) >= 0) {
2846 # A line exists in the memory buffer .. use it
2847 my $line = substr($postinput, $postpos, $idx-$postpos+1);
2852 # Need to read from the socket
2854 if ($postpos < length($postinput)) {
2855 # Start with in-memory data
2856 $line = substr($postinput, $postpos);
2857 $postpos = length($postinput);
2859 my $nl = &read_line(0, 1);
2862 print STDERR "finished reading - shutting down socket\n";
2865 $line .= $nl if (defined($nl));
2870 # Read one character of input
2875 my $got = READ($r, \$buf, 1, 0);
2876 return $got > 0 ? $buf : undef;
2881 return fileno(SOCK);
2888 # write_to_sock(data, ...)
2893 if ($doneheaders || $miniserv::nph_script) {
2898 while(!$doneheaders && $headers =~ s/^([^\r\n]*)(\r)?\n//) {
2899 if ($1 =~ /^(\S+):\s+(.*)$/) {
2900 $cgiheader{lc($1)} = $2;
2901 push(@cgiheader, [ $1, $2 ]);
2903 elsif ($1 !~ /\S/) {
2907 &http_error(500, "Bad Header");
2911 if ($cgiheader{"location"}) {
2913 "HTTP/1.0 302 Moved Temporarily\r\n");
2914 &write_data("Date: $datestr\r\n");
2915 &write_data("Server: $config{server}\r\n");
2916 &write_keep_alive(0);
2918 elsif ($cgiheader{"content-type"} eq "") {
2919 &http_error(500, "Missing Content-Type Header");
2922 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2923 &write_data("Date: $datestr\r\n");
2924 &write_data("Server: $config{server}\r\n");
2925 &write_keep_alive(0);
2927 foreach $h (@cgiheader) {
2928 &write_data("$h->[0]: $h->[1]\r\n");
2930 &write_data("\r\n");
2931 &reset_byte_count();
2932 &write_data($headers);
2940 local $cert = Net::SSLeay::X509_STORE_CTX_get_current_cert($_[1]);
2942 local $errnum = Net::SSLeay::X509_STORE_CTX_get_error($_[1]);
2943 $verified_client = 1 if (!$errnum);
2950 if ($doing_eval && $$ == $main_process_id) {
2951 # A CGI program called exit! This is a horrible hack to
2952 # finish up before really exiting
2955 close($PASSINw); close($PASSOUTw);
2956 &log_request($acpthost, $authuser, $reqline,
2957 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2962 # Convert a string to a form ok for putting in a URL
2964 local($tmp, $tmp2, $c);
2967 while(($c = chop($tmp)) ne "") {
2968 if ($c !~ /[A-z0-9]/) {
2969 $c = sprintf("%%%2.2X", ord($c));
2976 # validate_user(username, password, host)
2977 # Checks if some username and password are valid. Returns the modified username,
2978 # the expired / temp pass flag, and the non-existence flag
2981 local ($user, $pass, $host) = @_;
2982 return ( ) if (!$user);
2983 print DEBUG "validate_user: user=$user pass=$pass host=$host\n";
2984 local ($canuser, $canmode, $notexist, $webminuser, $sudo) =
2985 &can_user_login($user, undef, $host);
2986 print DEBUG "validate_user: canuser=$canuser canmode=$canmode notexist=$notexist webminuser=$webminuser sudo=$sudo\n";
2988 # User doesn't even exist, so go no further
2989 return ( undef, 0, 1 );
2991 elsif ($canmode == 0) {
2992 # User does exist but cannot login
2993 return ( $canuser, 0, 0 );
2995 elsif ($canmode == 1) {
2996 # Attempt Webmin authentication
2997 if ($users{$webminuser} eq
2998 &password_crypt($pass, $users{$webminuser})) {
2999 # Password is valid .. but check for expiry
3000 local $lc = $lastchanges{$user};
3001 if ($config{'pass_maxdays'} && $lc && !$nochange{$user}) {
3002 local $daysold = (time() - $lc)/(24*60*60);
3003 print DEBUG "maxdays=$config{'pass_maxdays'} daysold=$daysold temppass=$temppass{$user}\n";
3004 if ($config{'pass_lockdays'} &&
3005 $daysold > $config{'pass_lockdays'}) {
3006 # So old that the account is locked
3007 return ( undef, 0, 0 );
3009 elsif ($daysold > $config{'pass_maxdays'}) {
3010 # Password has expired
3011 return ( $user, 1, 0 );
3014 if ($temppass{$user}) {
3015 # Temporary password - force change now
3016 return ( $user, 2, 0 );
3018 return ( $user, 0, 0 );
3021 return ( undef, 0, 0 );
3024 elsif ($canmode == 2 || $canmode == 3) {
3025 # Attempt PAM or passwd file authentication
3026 local $val = &validate_unix_user($canuser, $pass);
3027 print DEBUG "validate_user: unix val=$val\n";
3028 if ($val && $sudo) {
3029 # Need to check if this Unix user can sudo
3030 if (!&check_sudo_permissions($canuser, $pass)) {
3031 print DEBUG "validate_user: sudo failed\n";
3035 print DEBUG "validate_user: sudo passed\n";
3038 return $val == 2 ? ( $canuser, 1, 0 ) :
3039 $val == 1 ? ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3041 elsif ($canmode == 4) {
3042 # Attempt external authentication
3043 return &validate_external_user($canuser, $pass) ?
3044 ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3052 # validate_unix_user(user, password)
3053 # Returns 1 if a username and password are valid under unix, 0 if not,
3054 # or 2 if the account has expired.
3055 # Checks PAM if available, and falls back to reading the system password
3057 sub validate_unix_user
3061 $pam_username = $_[0];
3062 $pam_password = $_[1];
3063 local $pamh = new Authen::PAM($config{'pam'}, $pam_username,
3066 local $pam_ret = $pamh->pam_authenticate();
3067 if ($pam_ret == PAM_SUCCESS()) {
3068 # Logged in OK .. make sure password hasn't expired
3069 local $acct_ret = $pamh->pam_acct_mgmt();
3070 if ($acct_ret == PAM_SUCCESS()) {
3071 $pamh->pam_open_session();
3074 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3075 $acct_ret == PAM_ACCT_EXPIRED()) {
3079 print STDERR "Unknown pam_acct_mgmt return value : $acct_ret\n";
3086 elsif ($config{'pam_only'}) {
3087 # Pam is not available, but configuration forces it's use!
3090 elsif ($config{'passwd_file'}) {
3091 # Check in a password file
3093 open(FILE, $config{'passwd_file'});
3094 if ($config{'passwd_file'} eq '/etc/security/passwd') {
3095 # Assume in AIX format
3098 if (/^\s*(\S+):/ && $1 eq $_[0]) {
3100 if (/^\s*password\s*=\s*(\S+)\s*$/) {
3101 $rv = $1 eq &password_crypt($_[1], $1) ?
3109 # Read the system password or shadow file
3111 local @l = split(/:/, $_, -1);
3112 local $u = $l[$config{'passwd_uindex'}];
3113 local $p = $l[$config{'passwd_pindex'}];
3115 $rv = $p eq &password_crypt($_[1], $p) ? 1 : 0;
3116 if ($config{'passwd_cindex'} ne '' && $rv) {
3117 # Password may have expired!
3118 local $c = $l[$config{'passwd_cindex'}];
3119 local $m = $l[$config{'passwd_mindex'}];
3120 local $day = time()/(24*60*60);
3121 if ($c =~ /^\d+/ && $m =~ /^\d+/ &&
3127 if ($p eq "" && $config{'passwd_blank'}) {
3128 # Force password change
3136 return $rv if ($rv);
3139 # Fallback option - check password returned by getpw*
3140 local @uinfo = getpwnam($_[0]);
3141 if ($uinfo[1] ne '' && &password_crypt($_[1], $uinfo[1]) eq $uinfo[1]) {
3145 return 0; # Totally failed
3148 # validate_external_user(user, pass)
3149 # Validate a user by passing the username and password to an external
3150 # squid-style authentication program
3151 sub validate_external_user
3153 return 0 if (!$config{'extauth'});
3155 local $str = "$_[0] $_[1]\n";
3156 syswrite(EXTAUTH, $str, length($str));
3157 local $resp = <EXTAUTH>;
3159 return $resp =~ /^OK/i ? 1 : 0;
3162 # can_user_login(username, no-append, host)
3163 # Checks if a user can login or not.
3164 # First return value is the username.
3165 # Second is 0 if cannot login, 1 if using Webmin pass, 2 if PAM, 3 if password
3166 # file, 4 if external.
3167 # Third is 1 if the user does not exist at all, 0 if he does.
3168 # Fourth is the Webmin username whose permissions apply, based on unixauth.
3169 # Fifth is a flag indicating if a sudo check is needed.
3172 if (!$users{$_[0]}) {
3173 # See if this user exists in Unix and can be validated by the same
3174 # method as the unixauth webmin user
3175 local $realuser = $unixauth{$_[0]};
3179 eval { @uinfo = getpwnam($_[0]); }; # may fail on windows
3180 if (!$realuser && @uinfo) {
3181 # No unixauth entry for the username .. try his groups
3182 foreach my $ua (keys %unixauth) {
3183 if ($ua =~ /^\@(.*)$/) {
3184 if (&is_group_member(\@uinfo, $1)) {
3185 $realuser = $unixauth{$ua};
3191 if (!$realuser && @uinfo) {
3192 # Fall back to unix auth for all Unix users
3193 $realuser = $unixauth{"*"};
3195 if (!$realuser && $use_sudo && @uinfo) {
3196 # Allow login effectively as root, if sudo permits it
3200 if (!$realuser && !@uinfo && $config{'pamany'}) {
3201 # If the user completely doesn't exist, we can still allow
3202 # him to authenticate via PAM
3203 $realuser = $config{'pamany'};
3207 # For Usermin, always fall back to unix auth for any user,
3208 # so that later checks with domain added / removed are done.
3209 $realuser = $unixauth{"*"};
3211 return (undef, 0, 1, undef) if (!$realuser);
3212 local $up = $users{$realuser};
3213 return (undef, 0, 1, undef) if (!defined($up));
3215 # Work out possible domain names from the hostname
3216 local @doms = ( $_[2] );
3217 if ($_[2] =~ /^([^\.]+)\.(\S+)$/) {
3221 if ($config{'user_mapping'} && !defined(%user_mapping)) {
3222 # Read the user mapping file
3224 open(MAPPING, $config{'user_mapping'});
3228 if (/^(\S+)\s+(\S+)/) {
3229 if ($config{'user_mapping_reverse'}) {
3230 $user_mapping{$1} = $2;
3233 $user_mapping{$2} = $1;
3240 # Check the user mapping file to see if there is an entry for the
3241 # user login in which specifies a new effective user
3243 foreach my $d (@doms) {
3244 $um ||= $user_mapping{"$_[0]\@$d"};
3246 $um ||= $user_mapping{$_[0]};
3247 if (defined($um) && ($_[1]&4) == 0) {
3248 # A mapping exists - use it!
3249 return &can_user_login($um, $_[1]+4, $_[2]);
3252 # Check if a user with the entered login and the domains appended
3253 # or prepended exists, and if so take it to be the effective user
3254 if (!@uinfo && $config{'domainuser'}) {
3255 # Try again with name.domain and name.firstpart
3256 local @firsts = map { /^([^\.]+)/; $1 } @doms;
3257 if (($_[1]&1) == 0) {
3259 foreach $a (@firsts, @doms) {
3260 foreach $p ("$_[0].${a}", "$_[0]-${a}",
3261 "${a}.$_[0]", "${a}-$_[0]",
3262 "$_[0]_${a}", "${a}_$_[0]") {
3263 local @vu = &can_user_login(
3264 $p, $_[1]+1, $_[2]);
3265 return @vu if ($vu[1]);
3271 # Check if the user entered a domain at the end of his username when
3272 # he really shouldn't have, and if so try without it
3273 if (!@uinfo && $config{'domainstrip'} &&
3274 $_[0] =~ /^(\S+)\@(\S+)$/ && ($_[1]&2) == 0) {
3275 local ($stripped, $dom) = ($1, $2);
3276 local @vu = &can_user_login($stripped, $_[1] + 2, $_[2]);
3277 return @vu if ($vu[1]);
3278 local @vu = &can_user_login($stripped, $_[1] + 2, $dom);
3279 return @vu if ($vu[1]);
3282 return ( undef, 0, 1, undef ) if (!@uinfo && !$pamany);
3285 if (defined(@allowusers)) {
3286 # Only allow people on the allow list
3287 return ( undef, 0, 0, undef )
3288 if (!&users_match(\@uinfo, @allowusers));
3290 elsif (defined(@denyusers)) {
3291 # Disallow people on the deny list
3292 return ( undef, 0, 0, undef )
3293 if (&users_match(\@uinfo, @denyusers));
3295 if ($config{'shells_deny'}) {
3297 open(SHELLS, $config{'shells_deny'});
3301 $found++ if ($_ eq $uinfo[8]);
3304 return ( undef, 0, 0, undef ) if (!$found);
3309 # PAM or passwd file authentication
3310 return ( $_[0], $use_pam ? 2 : 3, 0, $realuser, $sudo );
3312 elsif ($up eq 'e') {
3313 # External authentication
3314 return ( $_[0], 4, 0, $realuser, $sudo );
3317 # Fixed Webmin password
3318 return ( $_[0], 1, 0, $realuser, $sudo );
3321 elsif ($users{$_[0]} eq 'x') {
3322 # Webmin user authenticated via PAM or password file
3323 return ( $_[0], $use_pam ? 2 : 3, 0, $_[0] );
3325 elsif ($users{$_[0]} eq 'e') {
3326 # Webmin user authenticated externally
3327 return ( $_[0], 4, 0, $_[0] );
3330 # Normal Webmin user
3331 return ( $_[0], 1, 0, $_[0] );
3335 # the PAM conversation function for interactive logins
3338 $pam_conv_func_called++;
3345 $ans = $pam_username if ($code == PAM_PROMPT_ECHO_ON() );
3346 $ans = $pam_password if ($code == PAM_PROMPT_ECHO_OFF() );
3348 push @res, PAM_SUCCESS();
3351 push @res, PAM_SUCCESS();
3360 # get_socket_name(handle)
3361 # Returns the local hostname or IP address of some connection
3364 return $config{'host'} if ($config{'host'});
3365 local $sn = getsockname($_[0]);
3366 return undef if (!$sn);
3367 local $myaddr = (unpack_sockaddr_in($sn))[1];
3368 if (!$get_socket_name_cache{$myaddr}) {
3370 if (!$config{'no_resolv_myname'}) {
3371 $myname = gethostbyaddr($myaddr, AF_INET);
3373 if ($myname eq "") {
3374 $myname = inet_ntoa($myaddr);
3376 $get_socket_name_cache{$myaddr} = $myname;
3378 return $get_socket_name_cache{$myaddr};
3381 # run_login_script(username, sid, remoteip, localip)
3382 sub run_login_script
3384 if ($config{'login_script'}) {
3385 system($config{'login_script'}.
3386 " ".join(" ", map { quotemeta($_) } @_).
3387 " >/dev/null 2>&1 </dev/null");
3391 # run_logout_script(username, sid, remoteip, localip)
3392 sub run_logout_script
3394 if ($config{'logout_script'}) {
3395 system($config{'logout_script'}.
3396 " ".join(" ", map { quotemeta($_) } @_).
3397 " >/dev/null 2>&1 </dev/null");
3401 # close_all_sockets()
3402 # Closes all the main listening sockets
3403 sub close_all_sockets
3406 foreach $s (@socketfhs) {
3412 # Close all pipes for talking to sub-processes
3416 foreach $p (@passin) { close($p); }
3417 foreach $p (@passout) { close($p); }
3418 foreach $p (values %conversations) {
3419 if ($p->{'PAMOUTr'}) {
3420 close($p->{'PAMOUTr'});
3421 close($p->{'PAMINw'});
3426 # check_user_ip(user)
3427 # Returns 1 if some user is allowed to login from the accepting IP, 0 if not
3431 &ip_match($acptip, $localip, @{$deny{$_[0]}}) ||
3433 !&ip_match($acptip, $localip, @{$allow{$_[0]}})) {
3439 # check_user_time(user)
3440 # Returns 1 if some user is allowed to login at the current date and time
3443 return 1 if (!$allowdays{$_[0]} && !$allowhours{$_[0]});
3444 local @tm = localtime(time());
3445 if ($allowdays{$_[0]}) {
3446 # Make sure day is allowed
3447 return 0 if (&indexof($tm[6], @{$allowdays{$_[0]}}) < 0);
3449 if ($allowhours{$_[0]}) {
3450 # Make sure time is allowed
3451 local $m = $tm[2]*60+$tm[1];
3452 return 0 if ($m < $allowhours{$_[0]}->[0] ||
3453 $m > $allowhours{$_[0]}->[1]);
3458 # generate_random_id(password, [force-urandom])
3459 # Returns a random session ID number
3460 sub generate_random_id
3462 local ($pass, $force_urandom) = @_;
3464 if (!$bad_urandom) {
3465 # First try /dev/urandom, unless we have marked it as bad
3466 $SIG{ALRM} = "miniserv::urandom_timeout";
3468 if (open(RANDOM, "/dev/urandom")) {
3470 if (read(RANDOM, $tmpsid, 16) == 16) {
3471 $sid = lc(unpack('h*',$tmpsid));
3477 if (!$sid && !$force_urandom) {
3480 foreach $c (split(//, &unix_crypt($pass, substr($$, -2)))) {
3481 $sid += ord($c) * $mul;
3488 # handle_login(username, ok, expired, not-exists, password, [no-test-cookie])
3489 # Called from handle_session to either mark a user as logged in, or not
3492 local ($vu, $ok, $expired, $nonexist, $pass, $notest) = @_;
3493 $authuser = $vu if ($ok);
3495 # check if the test cookie is set
3496 if ($header{'cookie'} !~ /testing=1/ && $vu &&
3497 !$config{'no_testing_cookie'} && !$notest) {
3498 &http_error(500, "No cookies",
3499 "Your browser does not support cookies, ".
3500 "which are required for this web server to ".
3501 "work in session authentication mode");
3504 # check with main process for delay
3505 if ($config{'passdelay'} && $vu) {
3506 print $PASSINw "delay $vu $acptip $ok\n";
3507 <$PASSOUTr> =~ /(\d+) (\d+)/;
3512 if ($ok && (!$expired ||
3513 $config{'passwd_mode'} == 1)) {
3514 # Logged in OK! Tell the main process about
3516 local $sid = &generate_random_id($pass);
3517 print $PASSINw "new $sid $authuser $acptip\n";
3519 # Run the post-login script, if any
3520 &run_login_script($authuser, $sid,
3523 # Check for a redirect URL for the user
3524 local $rurl = &login_redirect($authuser, $pass, $host);
3526 # Got one .. go to it
3527 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3528 &write_data("Date: $datestr\r\n");
3529 &write_data("Server: $config{'server'}\r\n");
3530 &write_data("Location: $rurl\r\n");
3531 &write_keep_alive(0);
3532 &write_data("\r\n");
3533 &log_request($acpthost, $authuser, $reqline, 302, 0);
3536 # Set cookie and redirect to originally requested page
3537 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3538 &write_data("Date: $datestr\r\n");
3539 &write_data("Server: $config{'server'}\r\n");
3540 local $ssl = $use_ssl || $config{'inetd_ssl'};
3541 $portstr = $port == 80 && !$ssl ? "" :
3542 $port == 443 && $ssl ? "" : ":$port";
3543 $prot = $ssl ? "https" : "http";
3544 local $sec = $ssl ? "; secure" : "";
3545 #$sec .= "; httpOnly";
3547 &write_data("Set-Cookie: $sidname=$sid; path=/; expires=\"Thu, 31-Dec-2037 00:00:00\"$sec\r\n");
3550 &write_data("Set-Cookie: $sidname=$sid; path=/$sec\r\n");
3552 &write_data("Location: $prot://$host$portstr$in{'page'}\r\n");
3553 &write_keep_alive(0);
3554 &write_data("\r\n");
3555 &log_request($acpthost, $authuser, $reqline, 302, 0);
3556 syslog("info", "%s", "Successful login as $authuser from $acpthost") if ($use_syslog);
3557 &write_login_utmp($authuser, $acpthost);
3561 elsif ($ok && $expired &&
3562 ($config{'passwd_mode'} == 2 || $expired == 2)) {
3563 # Login was ok, but password has expired or was temporary. Need
3564 # to force display of password change form.
3567 $querystring = "&user=".&urlize($vu).
3569 "&expired=".$expired;
3572 $page = $config{'password_form'};
3574 $miniserv_internal = 2;
3575 syslog("crit", "%s",
3576 "Expired login as $vu ".
3577 "from $acpthost") if ($use_syslog);
3580 # Login failed, or password has expired. The login form will be
3581 # displayed again by later code
3583 $request_uri = $in{'page'};
3584 $already_session_id = undef;
3586 $authuser = $baseauthuser = undef;
3587 syslog("crit", "%s",
3588 ($nonexist ? "Non-existent" :
3589 $expired ? "Expired" : "Invalid").
3590 " login as $vu from $acpthost")
3596 # write_login_utmp(user, host)
3597 # Record the login by some user in utmp
3598 sub write_login_utmp
3601 # Write utmp record for login
3602 %utmp = ( 'ut_host' => $_[1],
3603 'ut_time' => time(),
3605 'ut_type' => 7, # user process
3606 'ut_pid' => $main_process_id,
3607 'ut_line' => $config{'pam'},
3609 if (defined(&User::Utmp::putut)) {
3610 User::Utmp::putut(\%utmp);
3613 User::Utmp::pututline(\%utmp);
3618 # write_logout_utmp(user, host)
3619 # Record the logout by some user in utmp
3620 sub write_logout_utmp
3623 # Write utmp record for logout
3624 %utmp = ( 'ut_host' => $_[1],
3625 'ut_time' => time(),
3627 'ut_type' => 8, # dead process
3628 'ut_pid' => $main_process_id,
3629 'ut_line' => $config{'pam'},
3631 if (defined(&User::Utmp::putut)) {
3632 User::Utmp::putut(\%utmp);
3635 User::Utmp::pututline(\%utmp);
3640 # pam_conversation_process(username, write-pipe, read-pipe)
3641 # This function is called inside a sub-process to communicate with PAM. It sends
3642 # questions down one pipe, and reads responses from another
3643 sub pam_conversation_process
3645 local ($user, $writer, $reader) = @_;
3646 $miniserv::pam_conversation_process_writer = $writer;
3647 $miniserv::pam_conversation_process_reader = $reader;
3648 local $convh = new Authen::PAM(
3649 $config{'pam'}, $user, \&miniserv::pam_conversation_process_func);
3650 local $pam_ret = $convh->pam_authenticate();
3651 if ($pam_ret == PAM_SUCCESS()) {
3652 local $acct_ret = $convh->pam_acct_mgmt();
3653 if ($acct_ret == PAM_SUCCESS()) {
3654 $convh->pam_open_session();
3655 print $writer "x2 $user 1 0 0\n";
3657 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3658 $acct_ret == PAM_ACCT_EXPIRED()) {
3659 print $writer "x2 $user 1 1 0\n";
3662 print $writer "x0 Unknown PAM account status $acct_ret\n";
3666 print $writer "x2 $user 0 0 0\n";
3671 # pam_conversation_process_func(type, message, [type, message, ...])
3672 # A pipe that talks to both PAM and the master process
3673 sub pam_conversation_process_func
3676 select($miniserv::pam_conversation_process_writer); $| = 1; select(STDOUT);
3678 local ($type, $msg) = (shift, shift);
3680 local $ok = (print $miniserv::pam_conversation_process_writer "$type $msg\n");
3681 print $miniserv::pam_conversation_process_writer "\n";
3682 local $answer = <$miniserv::pam_conversation_process_reader>;
3683 $answer =~ s/\r|\n//g;
3684 push(@rv, PAM_SUCCESS(), $answer);
3686 push(@rv, PAM_SUCCESS());
3691 # Returns 4 new pipe file handles
3694 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3696 local %taken = ( (map { $_, 1 } @passin),
3697 (map { $_->{'PASSINr'} } values %conversations) );
3698 for($p=0; $taken{"PASSINr$p"}; $p++) { }
3699 $PASSINr = "PASSINr$p";
3700 $PASSINw = "PASSINw$p";
3701 $PASSOUTr = "PASSOUTr$p";
3702 $PASSOUTw = "PASSOUTw$p";
3703 pipe($PASSINr, $PASSINw);
3704 pipe($PASSOUTr, $PASSOUTw);
3705 select($PASSINw); $| = 1;
3706 select($PASSINr); $| = 1;
3707 select($PASSOUTw); $| = 1;
3708 select($PASSOUTw); $| = 1;
3710 return ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3713 # recv_pam_question(&conv, fd)
3714 # Reads one PAM question from the sub-process, and sends it to the HTTP handler.
3715 # Returns 0 if the conversation is over, 1 if not.
3716 sub recv_pam_question
3718 local ($conf, $fh) = @_;
3719 local $pr = $conf->{'PAMOUTr'};
3720 select($pr); $| = 1; select(STDOUT);
3721 local $line = <$pr>;
3722 $line =~ s/\r|\n//g;
3725 $line =~ s/\r|\n//g;
3727 $conf->{'last'} = time();
3730 print $fh "0 PAM conversation error\n";
3734 local ($type, $msg) = split(/\s+/, $line, 2);
3735 if ($type =~ /^x(\d+)/) {
3736 # Pass this status code through
3737 print $fh "$1 $msg\n";
3738 return $1 == 2 || $1 == 0 ? 0 : 1;
3740 elsif ($type == PAM_PROMPT_ECHO_ON()) {
3742 print $fh "1 $msg\n";
3745 elsif ($type == PAM_PROMPT_ECHO_OFF()) {
3747 print $fh "3 $msg\n";
3750 elsif ($type == PAM_ERROR_MSG() || $type == PAM_TEXT_INFO()) {
3751 # A message that does not require a response
3752 print $fh "4 $msg\n";
3757 print $fh "0 Unknown PAM message type $type\n";
3763 # send_pam_answer(&conv, answer)
3764 # Sends a response from the user to the PAM sub-process
3767 local ($conf, $answer) = @_;
3768 local $pw = $conf->{'PAMINw'};
3769 $conf->{'last'} = time();
3770 print $pw "$answer\n";
3773 # end_pam_conversation(&conv)
3774 # Clean up PAM conversation pipes and processes
3775 sub end_pam_conversation
3778 kill('KILL', $conv->{'pid'}) if ($conv->{'pid'});
3779 if ($conv->{'PAMINr'}) {
3780 close($conv->{'PAMINr'});
3781 close($conv->{'PAMOUTr'});
3782 close($conv->{'PAMINw'});
3783 close($conv->{'PAMOUTw'});
3785 delete($conversations{$conv->{'cid'}});
3788 # get_ipkeys(&miniserv)
3789 # Returns a list of IP address to key file mappings from a miniserv.conf entry
3793 foreach $k (keys %{$_[0]}) {
3794 if ($k =~ /^ipkey_(\S+)/) {
3795 local $ipkey = { 'ips' => [ split(/,/, $1) ],
3796 'key' => $_[0]->{$k},
3797 'index' => scalar(@rv) };
3798 $ipkey->{'cert'} = $_[0]->{'ipcert_'.$1};
3805 # create_ssl_context(keyfile, [certfile])
3806 sub create_ssl_context
3808 local ($keyfile, $certfile) = @_;
3810 eval { $ssl_ctx = Net::SSLeay::new_x_ctx() };
3811 $ssl_ctx ||= Net::SSLeay::CTX_new();
3812 $ssl_ctx || die "Failed to create SSL context : $!";
3813 if ($client_certs) {
3814 Net::SSLeay::CTX_load_verify_locations(
3815 $ssl_ctx, $config{'ca'}, "");
3816 Net::SSLeay::CTX_set_verify(
3817 $ssl_ctx, &Net::SSLeay::VERIFY_PEER, \&verify_client);
3819 if ($config{'extracas'}) {
3821 foreach $p (split(/\s+/, $config{'extracas'})) {
3822 Net::SSLeay::CTX_load_verify_locations(
3827 Net::SSLeay::CTX_use_RSAPrivateKey_file(
3829 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL key $keyfile";
3830 Net::SSLeay::CTX_use_certificate_file(
3831 $ssl_ctx, $certfile || $keyfile,
3832 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL cert $certfile";
3837 # ssl_connection_for_ip(socket)
3838 # Returns a new SSL connection object for some socket, or undef if failed
3839 sub ssl_connection_for_ip
3842 local $sn = getsockname($sock);
3844 print STDERR "Failed to get address for socket $sock\n";
3847 local $myip = inet_ntoa((unpack_sockaddr_in($sn))[1]);
3848 local $ssl_ctx = $ssl_contexts{$myip} || $ssl_contexts{"*"};
3849 local $ssl_con = Net::SSLeay::new($ssl_ctx);
3850 if ($config{'ssl_cipher_list'}) {
3851 # Force use of ciphers
3852 eval "Net::SSLeay::set_cipher_list(
3853 \$ssl_con, \$config{'ssl_cipher_list'})";
3855 print STDERR "SSL cipher $config{'ssl_cipher_list'} failed : ",
3861 Net::SSLeay::set_fd($ssl_con, fileno($sock));
3862 if (!Net::SSLeay::accept($ssl_con)) {
3863 print STDERR "Failed to initialize SSL connection\n";
3869 # login_redirect(username, password, host)
3870 # Calls the login redirect script (if configured), which may output a URL to
3871 # re-direct a user to after logging in.
3874 return undef if (!$config{'login_redirect'});
3875 local $quser = quotemeta($_[0]);
3876 local $qpass = quotemeta($_[1]);
3877 local $qhost = quotemeta($_[2]);
3878 local $url = `$config{'login_redirect'} $quser $qpass $qhost`;
3883 # reload_config_file()
3884 # Re-read %config, and call post-config actions
3885 sub reload_config_file
3887 &log_error("Reloading configuration");
3888 %config = &read_config_file($config_file);
3889 &update_vital_config();
3892 &build_config_mappings();
3893 if ($config{'session'}) {
3894 dbmclose(%sessiondb);
3895 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
3899 # read_config_file(file)
3900 # Reads the given config file, and returns a hash of values
3901 sub read_config_file
3904 open(CONF, $_[0]) || die "Failed to open config file $_[0] : $!";
3907 if (/^#/ || !/\S/) { next; }
3909 $name = $1; $val = $2;
3910 $name =~ s/^\s+//g; $name =~ s/\s+$//g;
3911 $val =~ s/^\s+//g; $val =~ s/\s+$//g;
3918 # update_vital_config()
3919 # Updates %config with defaults, and dies if something vital is missing
3920 sub update_vital_config
3922 my %vital = ("port", 80,
3924 "server", "MiniServ/0.01",
3925 "index_docs", "index.html index.htm index.cgi index.php",
3926 "addtype_html", "text/html",
3927 "addtype_txt", "text/plain",
3928 "addtype_gif", "image/gif",
3929 "addtype_jpg", "image/jpeg",
3930 "addtype_jpeg", "image/jpeg",
3931 "realm", "MiniServ",
3932 "session_login", "/session_login.cgi",
3933 "pam_login", "/pam_login.cgi",
3934 "password_form", "/password_form.cgi",
3935 "password_change", "/password_change.cgi",
3939 "unauth", "^/unauthenticated/ ^[A-Za-z0-9\\-/]+\\.jar\$ ^[A-Za-z0-9\\-/]+\\.class\$ ^[A-Za-z0-9\\-/]+\\.gif\$ ^[A-Za-z0-9\\-/]+\\.conf\$ ^[A-Za-z0-9\\-/]+\\.ico\$",
3941 "expires", 7*24*60*60,
3943 foreach my $v (keys %vital) {
3945 if ($vital{$v} eq "") {
3946 die "Missing config option $v";
3948 $config{$v} = $vital{$v};
3951 if (!$config{'sessiondb'}) {
3952 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3953 $config{'sessiondb'} = "$1/sessiondb";
3955 if (!$config{'errorlog'}) {
3956 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
3957 $config{'errorlog'} = "$1/miniserv.error";
3959 if (!$config{'tempbase'}) {
3960 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3961 $config{'tempbase'} = "$1/cgitemp";
3963 if (!$config{'blockedfile'}) {
3964 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3965 $config{'blockedfile'} = "$1/blocked";
3970 # Fills the %users and %certs hashes from the users file in %config
3979 undef(%lastchanges);
3982 if ($config{'userfile'}) {
3983 open(USERS, $config{'userfile'});
3986 local @user = split(/:/, $_, -1);
3987 $users{$user[0]} = $user[1];
3988 $certs{$user[0]} = $user[3] if ($user[3]);
3989 if ($user[4] =~ /^allow\s+(.*)/) {
3990 $allow{$user[0]} = $config{'alwaysresolve'} ?
3991 [ split(/\s+/, $1) ] :
3992 [ &to_ipaddress(split(/\s+/, $1)) ];
3994 elsif ($user[4] =~ /^deny\s+(.*)/) {
3995 $deny{$user[0]} = $config{'alwaysresolve'} ?
3996 [ split(/\s+/, $1) ] :
3997 [ &to_ipaddress(split(/\s+/, $1)) ];
3999 if ($user[5] =~ /days\s+(\S+)/) {
4000 $allowdays{$user[0]} = [ split(/,/, $1) ];
4002 if ($user[5] =~ /hours\s+(\d+)\.(\d+)-(\d+).(\d+)/) {
4003 $allowhours{$user[0]} = [ $1*60+$2, $3*60+$4 ];
4005 $lastchanges{$user[0]} = $user[6];
4006 $nochange{$user[0]} = $user[9];
4007 $temppass{$user[0]} = $user[10];
4014 # Fills %mime with entries from file in %config and extra settings in %config
4018 if ($config{"mimetypes"} ne "") {
4019 open(MIME, $config{"mimetypes"});
4022 if (/^(\S+)\s+(.*)$/) {
4024 my @exts = split(/\s+/, $2);
4025 foreach my $ext (@exts) {
4026 $mime{$ext} = $type;
4032 foreach my $k (keys %config) {
4033 if ($k !~ /^addtype_(.*)$/) { next; }
4034 $mime{$1} = $config{$k};
4038 # build_config_mappings()
4039 # Build the anonymous access list, IP access list, unauthenticated URLs list,
4040 # redirect mapping and allow and deny lists from %config
4041 sub build_config_mappings
4043 # build anonymous access list
4045 foreach my $a (split(/\s+/, $config{'anonymous'})) {
4046 if ($a =~ /^([^=]+)=(\S+)$/) {
4047 $anonymous{$1} = $2;
4051 # build IP access list
4053 foreach my $a (split(/\s+/, $config{'ipaccess'})) {
4054 if ($a =~ /^([^=]+)=(\S+)$/) {
4059 # build unauthenticated URLs list
4060 @unauth = split(/\s+/, $config{'unauth'});
4062 # build redirect mapping
4064 foreach my $r (split(/\s+/, $config{'redirect'})) {
4065 if ($r =~ /^([^=]+)=(\S+)$/) {
4070 # build prefixes to be stripped
4071 undef(@strip_prefix);
4072 foreach my $r (split(/\s+/, $config{'strip_prefix'})) {
4073 push(@strip_prefix, $r);
4076 # Init allow and deny lists
4077 @deny = split(/\s+/, $config{"deny"});
4078 @deny = &to_ipaddress(@deny) if (!$config{'alwaysresolve'});
4079 @allow = split(/\s+/, $config{"allow"});
4080 @allow = &to_ipaddress(@allow) if (!$config{'alwaysresolve'});
4083 if ($config{'allowusers'}) {
4084 @allowusers = split(/\s+/, $config{'allowusers'});
4086 elsif ($config{'denyusers'}) {
4087 @denyusers = split(/\s+/, $config{'denyusers'});
4090 # Build list of unixauth mappings
4092 foreach my $ua (split(/\s+/, $config{'unixauth'})) {
4093 if ($ua =~ /^(\S+)=(\S+)$/) {
4097 $unixauth{"*"} = $ua;
4101 # Build list of non-session-auth pages
4102 undef(%sessiononly);
4103 foreach my $sp (split(/\s+/, $config{'sessiononly'})) {
4104 $sessiononly{$sp} = 1;
4107 # Build list of logout times
4108 undef(@logouttimes);
4109 foreach my $a (split(/\s+/, $config{'logouttimes'})) {
4110 if ($a =~ /^([^=]+)=(\S+)$/) {
4111 push(@logouttimes, [ $1, $2 ]);
4114 push(@logouttimes, [ undef, $config{'logouttime'} ]);
4116 # Build list of DAV pathss
4118 foreach my $d (split(/\s+/, $config{'davpaths'})) {
4119 push(@davpaths, $d);
4121 @davusers = split(/\s+/, $config{'dav_users'});
4123 # Mobile agent substrings and hostname prefixes
4124 @mobile_agents = split(/\t+/, $config{'mobile_agents'});
4125 @mobile_prefixes = split(/\s+/, $config{'mobile_prefixes'});
4129 if ($config{'debug'}) {
4130 open(DEBUG, ">>$config{'debug'}");
4133 open(DEBUG, ">/dev/null");
4136 # Reset cache of sudo checks
4140 # is_group_member(&uinfo, groupname)
4141 # Returns 1 if some user is a primary or secondary member of a group
4144 local ($uinfo, $group) = @_;
4145 local @ginfo = getgrnam($group);
4146 return 0 if (!@ginfo);
4147 return 1 if ($ginfo[2] == $uinfo->[3]); # primary member
4148 foreach my $m (split(/\s+/, $ginfo[3])) {
4149 return 1 if ($m eq $uinfo->[0]);
4154 # prefix_to_mask(prefix)
4155 # Converts a number like 24 to a mask like 255.255.255.0
4158 return $_[0] >= 24 ? "255.255.255.".(256-(2 ** (32-$_[0]))) :
4159 $_[0] >= 16 ? "255.255.".(256-(2 ** (24-$_[0]))).".0" :
4160 $_[0] >= 8 ? "255.".(256-(2 ** (16-$_[0]))).".0.0" :
4161 (256-(2 ** (8-$_[0]))).".0.0.0";
4164 # get_logout_time(user, session-id)
4165 # Given a username, returns the idle time before he will be logged out
4168 local ($user, $sid) = @_;
4169 if (!defined($logout_time_cache{$user,$sid})) {
4171 foreach my $l (@logouttimes) {
4172 if ($l->[0] =~ /^\@(.*)$/) {
4173 # Check group membership
4174 local @uinfo = getpwnam($user);
4175 if (@uinfo && &is_group_member(\@uinfo, $1)) {
4179 elsif ($l->[0] =~ /^\//) {
4180 # Check file contents
4181 open(FILE, $l->[0]);
4198 if ($l->[0] eq $user) {
4202 last if (defined($time));
4204 $logout_time_cache{$user,$sid} = $time;
4206 return $logout_time_cache{$user,$sid};
4209 # password_crypt(password, salt)
4210 # If the salt looks like MD5 and we have a library for it, perform MD5 hashing
4211 # of a password. Otherwise, do Unix crypt.
4214 local ($pass, $salt) = @_;
4215 if ($salt =~ /^\$1\$/ && $use_md5) {
4216 return &encrypt_md5($pass, $salt);
4219 return &unix_crypt($pass, $salt);
4223 # unix_crypt(password, salt)
4224 # Performs standard Unix hashing for a password
4227 local ($pass, $salt) = @_;
4228 if ($use_perl_crypt) {
4229 return Crypt::UnixCrypt::crypt($pass, $salt);
4232 return crypt($pass, $salt);
4236 # handle_dav_request(davpath)
4237 # Pass a request on to the Net::DAV::Server module
4238 sub handle_dav_request
4241 eval "use Filesys::Virtual::Plain";
4242 eval "use Net::DAV::Server";
4243 eval "use HTTP::Request";
4244 eval "use HTTP::Headers";
4246 if ($Net::DAV::Server::VERSION eq '1.28' && $config{'dav_nolock'}) {
4247 delete $Net::DAV::Server::implemented{lock};
4248 delete $Net::DAV::Server::implemented{unlock};
4251 # Read in request data
4252 if (!$posted_data) {
4253 local $clen = $header{"content-length"};
4254 while(length($posted_data) < $clen) {
4255 $buf = &read_data($clen - length($posted_data));
4256 if (!length($buf)) {
4257 &http_error(500, "Failed to read POST request");
4259 chomp($posted_data);
4260 #$posted_data =~ s/\015$//mg;
4261 $posted_data .= $buf;
4265 # For subsequent logging
4266 open(MINISERVLOG, ">>$config{'logfile'}");
4270 local @u = getpwnam($authuser);
4271 if ($config{'dav_remoteuser'} && !$< && $validated) {
4274 $( = $u[3]; $) = "$u[3] $u[3]";
4275 ($>, $<) = ($u[2], $u[2]);
4277 if ($config{'dav_root'} eq '*') {
4282 &http_error(500, "Unix user $authuser does not exist");
4286 $root ||= $config{'dav_root'};
4289 # Check if this user can use DAV
4291 &users_match(\@u, @davusers) ||
4292 &http_error(500, "You are not allowed to access DAV");
4296 my $filesys = Filesys::Virtual::Plain->new({root_path => $root});
4297 my $webdav = Net::DAV::Server->new();
4298 $webdav->filesys($filesys);
4300 # Make up a request object, and feed to DAV
4301 local $ho = HTTP::Headers->new;
4302 foreach my $h (keys %header) {
4303 next if (lc($h) eq "connection");
4304 $ho->header($h => $header{$h});
4307 $request_uri =~ s/^\Q$path\E//;
4308 $request_uri = "/" if ($request_uri eq "");
4310 my $request = HTTP::Request->new($method, $request_uri, $ho,
4312 if ($config{'dav_debug'}) {
4313 print STDERR "DAV request :\n";
4314 print STDERR "---------------------------------------------\n";
4315 print STDERR $request->as_string();
4316 print STDERR "---------------------------------------------\n";
4318 my $response = $webdav->run($request);
4320 # Send back the reply
4321 &write_data("HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n");
4322 local $content = $response->content();
4324 $content =~ s|href>/(.+)<|href>$path/$1<|g;
4325 $content =~ s|href>/<|href>$path<|g;
4327 foreach my $h ($response->header_field_names) {
4328 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4329 &write_data("$h: ",$response->header($h),"\r\n");
4331 &write_data("Content-length: ",length($content),"\r\n");
4332 local $rv = &write_keep_alive(0);
4333 &write_data("\r\n");
4334 &write_data($content);
4336 if ($config{'dav_debug'}) {
4337 print STDERR "DAV reply :\n";
4338 print STDERR "---------------------------------------------\n";
4339 print STDERR "HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n";
4340 foreach my $h ($response->header_field_names) {
4341 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4342 print STDERR "$h: ",$response->header($h),"\r\n";
4344 print STDERR "Content-length: ",length($content),"\r\n";
4345 print STDERR "\r\n";
4346 print STDERR $content;
4347 print STDERR "---------------------------------------------\n";
4351 &log_request($acpthost, $authuser, $reqline, $response->code(),
4352 length($response->content()));
4355 # get_system_hostname()
4356 # Returns the hostname of this system, for reporting to listeners
4357 sub get_system_hostname
4359 # On Windows, try computername environment variable
4360 return $ENV{'computername'} if ($ENV{'computername'});
4361 return $ENV{'COMPUTERNAME'} if ($ENV{'COMPUTERNAME'});
4363 # If a specific command is set, use it first
4364 if ($config{'hostname_command'}) {
4365 local $out = `($config{'hostname_command'}) 2>&1`;
4372 # First try the hostname command
4373 local $out = `hostname 2>&1`;
4374 if (!$? && $out =~ /\S/) {
4379 # Try the Sys::Hostname module
4380 eval "use Sys::Hostname";
4382 local $rv = eval "hostname()";
4388 # Must use net name on Windows
4389 local $out = `net name 2>&1`;
4390 if ($out =~ /\-+\r?\n(\S+)/) {
4397 # indexof(string, array)
4398 # Returns the index of some value in an array, or -1
4401 for($i=1; $i <= $#_; $i++) {
4402 if ($_[$i] eq $_[0]) { return $i - 1; }
4408 # has_command(command)
4409 # Returns the full path if some command is in the path, undef if not
4413 if (!$_[0]) { return undef; }
4414 if (exists($has_command_cache{$_[0]})) {
4415 return $has_command_cache{$_[0]};
4418 if ($_[0] =~ /^\//) {
4419 $rv = -x $_[0] ? $_[0] : undef;
4422 local $sp = $on_windows ? ';' : ':';
4423 foreach $d (split($sp, $ENV{PATH})) {
4424 if (-x "$d/$_[0]") {
4429 foreach my $sfx (".exe", ".com", ".bat") {
4430 if (-r "$d/$_[0]".$sfx) {
4431 $rv = "$d/$_[0]".$sfx;
4438 $has_command_cache{$_[0]} = $rv;
4442 # check_sudo_permissions(user, pass)
4443 # Returns 1 if some user can run any command via sudo
4444 sub check_sudo_permissions
4446 local ($user, $pass) = @_;
4448 # First try the pipes
4450 print DEBUG "check_sudo_permissions: querying cache for $user\n";
4451 print $PASSINw "readsudo $user\n";
4452 local $can = <$PASSOUTr>;
4454 print DEBUG "check_sudo_permissions: cache said $can\n";
4455 if ($can =~ /^\d+$/ && $can != 2) {
4460 local $ptyfh = new IO::Pty;
4461 print DEBUG "check_sudo_permissions: ptyfh=$ptyfh\n";
4463 print STDERR "Failed to create new PTY with IO::Pty\n";
4466 local @uinfo = getpwnam($user);
4468 print STDERR "Unix user $user does not exist for sudo\n";
4472 # Execute sudo in a sub-process, via a pty
4473 local $ttyfh = $ptyfh->slave();
4474 print DEBUG "check_sudo_permissions: ttyfh=$ttyfh\n";
4475 local $tty = $ptyfh->ttyname();
4476 print DEBUG "check_sudo_permissions: tty=$tty\n";
4477 chown($uinfo[2], $uinfo[3], $tty);
4479 print DEBUG "check_sudo_permissions: about to fork..\n";
4480 local $pid = fork();
4481 print DEBUG "check_sudo_permissions: fork=$pid pid=$$\n";
4483 print STDERR "fork for sudo failed : $!\n";
4488 $ptyfh->make_slave_controlling_terminal();
4489 close(STDIN); close(STDOUT); close(STDERR);
4490 untie(*STDIN); untie(*STDOUT); untie(*STDERR);
4491 close($PASSINw); close($PASSOUTr);
4492 $( = $uinfo[3]; $) = "$uinfo[3] $uinfo[3]";
4493 ($>, $<) = ($uinfo[2], $uinfo[2]);
4498 open(STDIN, "<&SUDOr");
4499 open(STDOUT, ">$tty");
4500 open(STDERR, ">&STDOUT");
4503 print "Exec failed : $!\n";
4506 print DEBUG "check_sudo_permissions: pid=$pid\n";
4508 $ptyfh->close_slave();
4510 # Send password, and get back response
4511 local $oldfh = select(SUDOw);
4514 print DEBUG "check_sudo_permissions: about to send pass\n";
4515 local $SIG{'PIPE'} = 'ignore'; # Sometimes sudo doesn't ask for a password
4516 print SUDOw $pass,"\n";
4517 print DEBUG "check_sudo_permissions: sent pass=$pass\n";
4521 print DEBUG "check_sudo_permissions: got $_";
4527 local ($ok) = ($out =~ /\(ALL\)\s+ALL/ ? 1 : 0);
4531 print $PASSINw "writesudo $user $ok\n";
4537 # is_mobile_useragent(agent)
4538 # Returns 1 if some user agent looks like a cellphone or other mobile device,
4540 sub is_mobile_useragent
4542 local ($agent) = @_;
4544 "UP.Link", # Openwave
4545 "Nokia", # All Nokias start with Nokia
4546 "MOT-", # All Motorola phones start with MOT-
4547 "SAMSUNG", # Samsung browsers
4548 "Samsung", # Samsung browsers
4549 "SEC-", # Samsung browsers
4550 "AU-MIC", # Samsung browsers
4551 "AUDIOVOX", # Audiovox
4552 "BlackBerry", # BlackBerry
4553 "hiptop", # Danger hiptop Sidekick
4554 "SonyEricsson", # Sony Ericsson
4555 "Ericsson", # Old Ericsson browsers , mostly WAP
4556 "Mitsu/1.1.A", # Mitsubishi phones
4557 "Panasonic WAP", # Panasonic old WAP phones
4558 "DoCoMo", # DoCoMo phones
4559 "Lynx", # Lynx text-mode linux browser
4560 "Links", # Another text-mode linux browser
4562 local @substrings = (
4563 "UP.Browser", # Openwave
4564 "MobilePhone", # NetFront
4565 "AU-MIC-A700", # Samsung A700 Obigo browsers
4566 "Danger hiptop", # Danger Sidekick hiptop
4567 "Windows CE", # Windows CE Pocket PC
4568 "IEMobile", # Windows mobile browser
4569 "Blazer", # Palm Treo Blazer
4570 "BlackBerry", # BlackBerries can emulate other browsers, but
4571 # they still keep this string in the UserAgent
4572 "SymbianOS", # New Series60 browser has safari in it and
4573 # SymbianOS is the only distinguishing string
4574 "iPhone", # Apple iPhone KHTML browser
4575 "iPod", # iPod touch browser
4576 "MobileSafari", # HTTP client in iPhone
4578 "Opera Mini", # Opera Mini
4579 "HTC_P3700", # HTC mobile device
4581 foreach my $p (@prefixes) {
4582 return 1 if ($agent =~ /^\Q$p\E/);
4584 foreach my $s (@substrings, @mobile_agents) {
4585 return 1 if ($agent =~ /\Q$s\E/);
4590 # write_blocked_file()
4591 # Writes out a text file of blocked hosts and users
4592 sub write_blocked_file
4594 open(BLOCKED, ">$config{'blockedfile'}");
4595 foreach my $d (grep { $hostfail{$_} } @deny) {
4596 print BLOCKED "host $d $hostfail{$d} $blockhosttime{$d}\n";
4598 foreach my $d (grep { $userfail{$_} } @denyusers) {
4599 print BLOCKED "user $d $userfail{$d} $blockusertime{$d}\n";
4602 chmod(0700, $config{'blockedfile'});
4607 open(PIDFILE, ">$config{'pidfile'}");
4608 printf PIDFILE "%d\n", getpid();
4612 # lock_user_password(user)
4613 # Updates a user's password file entry to lock it, both in memory and on disk.
4614 # Returns 1 if done, -1 if no such user, 0 if already locked
4615 sub lock_user_password
4618 if ($users{$user}) {
4619 if ($users{$user} !~ /^\!/) {
4621 $users{$user} = "!".$users{$user};
4622 open(USERS, $config{'userfile'});
4623 local @ufile = <USERS>;
4625 foreach my $u (@ufile) {
4626 local @uinfo = split(/:/, $u);
4627 if ($uinfo[0] eq $user) {
4628 $uinfo[1] = $users{$user};
4630 $u = join(":", @uinfo);
4632 open(USERS, ">$config{'userfile'}");
4642 # hash_session_id(sid)
4643 # Returns an MD5 or Unix-crypted session ID
4647 if (!$hash_session_id_cache{$sid}) {
4650 $hash_session_id_cache{$sid} = &encrypt_md5($sid);
4654 $hash_session_id_cache{$sid} = &unix_crypt($sid, "XX");
4657 return $hash_session_id_cache{$sid};
4660 # encrypt_md5(string, [salt])
4661 # Returns a string encrypted in MD5 format
4664 local ($passwd, $salt) = @_;
4665 local $magic = '$1$';
4666 if ($salt =~ /^\$1\$([^\$]+)/) {
4667 # Extract actual salt from already encrypted password
4672 local $ctx = eval "new $use_md5";
4679 # Add some more stuff from the hash of the password and salt
4680 local $ctx1 = eval "new $use_md5";
4681 $ctx1->add($passwd);
4685 $ctx1->add($passwd);
4686 local $final = $ctx1->digest();
4687 for($pl=length($passwd); $pl>0; $pl-=16) {
4688 $ctx->add($pl > 16 ? $final : substr($final, 0, $pl));
4691 # This piece of code seems rather pointless, but it's in the C code that
4692 # does MD5 in PAM so it has to go in!
4695 for($i=length($passwd); $i; $i >>= 1) {
4700 $ctx->add(substr($passwd, $j, 1));
4703 $final = $ctx->digest();
4706 # This loop exists only to waste time
4707 for($i=0; $i<1000; $i++) {
4708 $ctx1 = eval "new $use_md5";
4709 $ctx1->add($i & 1 ? $passwd : $final);
4710 $ctx1->add($salt) if ($i % 3);
4711 $ctx1->add($passwd) if ($i % 7);
4712 $ctx1->add($i & 1 ? $final : $passwd);
4713 $final = $ctx1->digest();
4717 # Convert the 16-byte final string into a readable form
4719 local @final = map { ord($_) } split(//, $final);
4720 $l = ($final[ 0]<<16) + ($final[ 6]<<8) + $final[12];
4721 $rv .= &to64($l, 4);
4722 $l = ($final[ 1]<<16) + ($final[ 7]<<8) + $final[13];
4723 $rv .= &to64($l, 4);
4724 $l = ($final[ 2]<<16) + ($final[ 8]<<8) + $final[14];
4725 $rv .= &to64($l, 4);
4726 $l = ($final[ 3]<<16) + ($final[ 9]<<8) + $final[15];
4727 $rv .= &to64($l, 4);
4728 $l = ($final[ 4]<<16) + ($final[10]<<8) + $final[ 5];
4729 $rv .= &to64($l, 4);
4731 $rv .= &to64($l, 2);
4733 # Add salt if needed
4735 return $magic.$salt.'$'.$rv;
4744 local ($v, $n) = @_;
4747 $r .= $itoa64[$v & 0x3f];