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 main; 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{'answer'} || "unknown", 0, 0, 1, undef);
1551 return $hrv if (defined($hrv));
1553 elsif ($rv == 1 || $rv == 3) {
1554 # Another question .. force use of PAM CGI
1557 $querystring .= "&cid=$cid&question=".
1559 $querystring .= "&password=1" if ($rv == 3);
1561 $page = $config{'pam_login'};
1562 $miniserv_internal = 1;
1566 # Got back a final ok or failure
1567 local ($user, $ok, $expired, $nonexist) =
1568 split(/\s+/, $question);
1569 local $hrv = &handle_login(
1570 $user, $ok, $expired, $nonexist, undef,
1571 $in{'notestingcookie'});
1572 return $hrv if (defined($hrv));
1575 # A message from PAM .. tell the user
1578 $querystring .= "&cid=$cid&message=".
1581 $page = $config{'pam_login'};
1582 $miniserv_internal = 1;
1587 # Check for a visit to the special password change page
1588 if ($config{'session'} && !$deny_authentication &&
1589 $page eq $config{'password_change'} && !$validated) {
1590 # Just let this slide ..
1592 $miniserv_internal = 3;
1595 # Check for an existing session
1596 if ($config{'session'} && !$validated) {
1597 if ($already_session_id) {
1598 $session_id = $already_session_id;
1599 $authuser = $already_authuser;
1602 elsif (!$deny_authentication &&
1603 $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1605 local $notimeout = $in{'webmin_notimeout'} ? 1 : 0;
1606 print $PASSINw "verify $session_id $notimeout\n";
1607 <$PASSOUTr> =~ /(\d+)\s+(\S+)/;
1609 # Valid session continuation
1612 #$already_session_id = $session_id;
1613 $already_authuser = $authuser;
1620 # Invalid session ID .. don't set verified
1625 # Check for local authentication
1626 if ($localauth_user && !$header{'x-forwarded-for'} && !$header{'via'}) {
1627 if (defined($users{$localauth_user})) {
1628 # Local user exists in webmin users file
1630 $authuser = $localauth_user;
1633 # Check if local user is allowed by unixauth
1634 local @can = &can_user_login($localauth_user,
1638 $authuser = $localauth_user;
1641 $localauth_user = undef;
1647 # Check if this path allows anonymous access
1649 foreach $a (keys %anonymous) {
1650 if (substr($simple, 0, length($a)) eq $a) {
1651 # It does! Auth as the user, if IP access
1652 # control allows him.
1653 if (&check_user_ip($anonymous{$a}) &&
1654 &check_user_time($anonymous{$a})) {
1656 $baseauthuser = $authuser =
1664 # Check if this path allows unauthenticated access
1665 local ($u, $unauth);
1666 foreach $u (@unauth) {
1667 $unauth++ if ($simple =~ /$u/);
1669 if (!$bogus && $unauth) {
1670 # Unauthenticated directory or file request - approve it
1672 $baseauthuser = $authuser = undef;
1677 if ($blocked == 0) {
1678 # No password given.. ask
1679 if ($config{'pam_conv'} && $use_pam) {
1680 # Force CGI for PAM question, starting with
1681 # the username which is always needed
1684 $querystring .= "&initial=1&question=".
1685 &urlize("Username");
1686 $querystring .= "&failed=$failed_user" if ($failed_user);
1687 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1689 $page = $config{'pam_login'};
1690 $miniserv_internal = 1;
1693 elsif ($config{'session'}) {
1694 # Force CGI for session login
1697 $querystring .= "&logout=1&page=/";
1700 # Re-direct to current module only
1701 local $rpage = $request_uri;
1702 if (!$config{'loginkeeppage'}) {
1703 $rpage =~ s/\?.*$//;
1704 $rpage =~ s/[^\/]+$//
1706 $querystring = "page=".&urlize($rpage);
1709 $querystring .= "&failed=$failed_user" if ($failed_user);
1710 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1712 $page = $config{'session_login'};
1713 $miniserv_internal = 1;
1717 # Ask for login with HTTP authentication
1718 &write_data("HTTP/1.0 401 Unauthorized\r\n");
1719 &write_data("Date: $datestr\r\n");
1720 &write_data("Server: $config{'server'}\r\n");
1721 &write_data("WWW-authenticate: Basic ".
1722 "realm=\"$config{'realm'}\"\r\n");
1723 &write_keep_alive(0);
1724 &write_data("Content-type: text/html\r\n");
1725 &write_data("\r\n");
1726 &reset_byte_count();
1727 &write_data("<html>\n");
1728 &write_data("<head><title>Unauthorized</title></head>\n");
1729 &write_data("<body><h1>Unauthorized</h1>\n");
1730 &write_data("A password is required to access this\n");
1731 &write_data("web server. Please try again. <p>\n");
1732 &write_data("</body></html>\n");
1733 &log_request($acpthost, undef, $reqline, 401, &byte_count());
1737 elsif ($blocked == 1) {
1738 # when the host has been blocked, give it an error
1739 &http_error(403, "Access denied for $acptip. The host ".
1740 "has been blocked because of too ".
1741 "many authentication failures.");
1743 elsif ($blocked == 2) {
1744 # when the user has been blocked, give it an error
1745 &http_error(403, "Access denied. The user ".
1746 "has been blocked because of too ".
1747 "many authentication failures.");
1751 # Get the real Webmin username
1752 local @can = &can_user_login($authuser, undef, $host);
1753 $baseauthuser = $can[3] || $authuser;
1755 if ($config{'remoteuser'} && !$< && $validated) {
1756 # Switch to the UID of the remote user (if he exists)
1757 local @u = getpwnam($authuser);
1758 if (@u && $< != $u[2]) {
1759 $( = $u[3]; $) = "$u[3] $u[3]";
1760 ($>, $<) = ($u[2], $u[2]);
1763 &http_error(500, "Unix user $authuser does not exist");
1769 # Check per-user IP access control
1770 if (!&check_user_ip($baseauthuser)) {
1771 &http_error(403, "Access denied for $acptip for $baseauthuser");
1775 # Check per-user allowed times
1776 if (!&check_user_time($baseauthuser)) {
1777 &http_error(403, "Access denied at the current time");
1782 # Validate the path, and convert to canonical form
1784 $simple = &simplify_path($page, $bogus);
1785 print DEBUG "handle_request: page=$page simple=$simple\n";
1787 &http_error(400, "Invalid path");
1790 # Check for a DAV request
1792 return &handle_dav_request($davpath);
1795 # Work out the active theme(s)
1796 local $preroots = $mobile_device && defined($config{'mobile_preroot'}) ?
1797 $config{'mobile_preroot'} :
1798 $authuser && defined($config{'preroot_'.$authuser}) ?
1799 $config{'preroot_'.$authuser} :
1800 $authuser && $baseauthuser &&
1801 defined($config{'preroot_'.$baseauthuser}) ?
1802 $config{'preroot_'.$baseauthuser} :
1804 local @preroots = reverse(split(/\s+/, $preroots));
1806 # Canonicalize the directories
1807 foreach my $preroot (@preroots) {
1808 # Always under the current webmin root
1809 $preroot =~ s/^.*\///g;
1810 $preroot = $roots[0].'/'.$preroot;
1813 # Look in the theme root directories first
1814 local ($full, @stfull);
1816 foreach my $preroot (@preroots) {
1819 $full = $preroot.$sofar;
1820 $scriptname = $simple;
1821 foreach $b (split(/\//, $simple)) {
1822 if ($b ne "") { $sofar .= "/$b"; }
1823 $full = $preroot.$sofar;
1824 @stfull = stat($full);
1825 if (!@stfull) { undef($full); last; }
1827 # Check if this is a directory
1829 # It is.. go on parsing
1837 # Check if this is a CGI program
1838 if (&get_type($full) eq "internal/cgi") {
1839 $pathinfo = substr($simple, length($sofar));
1840 $pathinfo .= "/" if ($page =~ /\/$/);
1841 $scriptname = $sofar;
1846 # Don't stop at a directory unless this is the last theme, which
1847 # is the 'real' one that provides the .cgi scripts
1848 if ($is_directory && $preroot ne $preroots[$#preroots]) {
1855 $cgi_pwd = $roots[0];
1857 elsif ($is_directory) {
1858 $cgi_pwd = "$roots[0]$sofar";
1861 "$roots[0]$sofar" =~ /^(.*\/)[^\/]+$/;
1864 $foundroot = $preroot;
1865 if ($is_directory) {
1866 # Check for index files in the directory
1868 foreach $idx (split(/\s+/, $config{"index_docs"})) {
1869 $idxfull = "$full/$idx";
1870 local @stidxfull = stat($idxfull);
1871 if (-r _ && !-d _) {
1873 @stfull = @stidxfull;
1876 if ($scriptname ne "/");
1881 @stfull = stat($full) if (!$foundidx);
1884 last if ($foundroot);
1886 print DEBUG "handle_request: initial full=$full\n";
1888 # Look in the real root directories, stopping when we find a file or directory
1889 if (!$full || $is_directory) {
1890 ROOT: foreach $root (@roots) {
1892 $full = $root.$sofar;
1893 $scriptname = $simple;
1894 foreach $b ($simple eq "/" ? ( "" ) : split(/\//, $simple)) {
1895 if ($b ne "") { $sofar .= "/$b"; }
1896 $full = $root.$sofar;
1897 @stfull = stat($full);
1902 # Check if this is a directory
1904 # It is.. go on parsing
1908 # Check if this is a CGI program
1909 if (&get_type($full) eq "internal/cgi") {
1910 $pathinfo = substr($simple, length($sofar));
1911 $pathinfo .= "/" if ($page =~ /\/$/);
1912 $scriptname = $sofar;
1917 # Run CGI in the same directory as whatever file
1919 $full =~ /^(.*\/)[^\/]+$/; $cgi_pwd = $1;
1928 if (!@stfull) { &http_error(404, "File not found"); }
1930 print DEBUG "handle_request: full=$full\n";
1931 @stfull = stat($full) if (!@stfull);
1933 # check filename against denyfile regexp
1934 local $denyfile = $config{'denyfile'};
1935 if ($denyfile && $full =~ /$denyfile/) {
1936 &http_error(403, "Access denied to $page");
1940 # Reached the end of the path OK.. see what we've got
1942 # See if the URL ends with a / as it should
1943 print DEBUG "handle_request: found a directory\n";
1944 if ($page !~ /\/$/) {
1945 # It doesn't.. redirect
1946 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1947 $ssl = $use_ssl || $config{'inetd_ssl'};
1948 $portstr = $port == 80 && !$ssl ? "" :
1949 $port == 443 && $ssl ? "" : ":$port";
1950 &write_data("Date: $datestr\r\n");
1951 &write_data("Server: $config{server}\r\n");
1952 $prot = $ssl ? "https" : "http";
1953 &write_data("Location: $prot://$host$portstr$page/\r\n");
1954 &write_keep_alive(0);
1955 &write_data("\r\n");
1956 &log_request($acpthost, $authuser, $reqline, 302, 0);
1959 # A directory.. check for index files
1961 foreach $idx (split(/\s+/, $config{"index_docs"})) {
1962 $idxfull = "$full/$idx";
1963 @stidxfull = stat($idxfull);
1964 if (-r _ && !-d _) {
1967 @stfull = @stidxfull;
1968 $scriptname .= "/" if ($scriptname ne "/");
1973 @stfull = stat($full) if (!$foundidx);
1976 # This is definately a directory.. list it
1977 print DEBUG "handle_request: listing directory\n";
1978 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
1979 "Date: $datestr\r\n".
1980 "Server: $config{server}\r\n".
1981 "Content-type: text/html\r\n";
1983 &write_keep_alive(0);
1984 &write_data("\r\n");
1985 &reset_byte_count();
1986 &write_data("<h1>Index of $simple</h1>\n");
1987 &write_data("<pre>\n");
1988 &write_data(sprintf "%-35.35s %-20.20s %-10.10s\n",
1989 "Name", "Last Modified", "Size");
1990 &write_data("<hr>\n");
1991 opendir(DIR, $full);
1992 while($df = readdir(DIR)) {
1993 if ($df =~ /^\./) { next; }
1994 $fulldf = $full eq "/" ? $full.$df : $full."/".$df;
1995 (@stbuf = stat($fulldf)) || next;
1996 if (-d _) { $df .= "/"; }
1997 @tm = localtime($stbuf[9]);
1998 $fdate = sprintf "%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d",
1999 $tm[3],$tm[4]+1,$tm[5]+1900,
2000 $tm[0],$tm[1],$tm[2];
2001 $len = length($df); $rest = " "x(35-$len);
2003 "<a href=\"%s\">%-${len}.${len}s</a>$rest %-20.20s %-10.10s\n",
2004 $df, $df, $fdate, $stbuf[7]);
2007 &log_request($acpthost, $authuser, $reqline, $ok_code, &byte_count());
2011 # CGI or normal file
2013 if (&get_type($full) eq "internal/cgi" && $validated != 4) {
2014 # A CGI program to execute
2015 print DEBUG "handle_request: executing CGI\n";
2016 $envtz = $ENV{"TZ"};
2017 $envuser = $ENV{"USER"};
2018 $envpath = $ENV{"PATH"};
2019 $envlang = $ENV{"LANG"};
2020 $envroot = $ENV{"SystemRoot"};
2021 foreach my $k (keys %ENV) {
2024 $ENV{"PATH"} = $envpath if ($envpath);
2025 $ENV{"TZ"} = $envtz if ($envtz);
2026 $ENV{"USER"} = $envuser if ($envuser);
2027 $ENV{"OLD_LANG"} = $envlang if ($envlang);
2028 $ENV{"SystemRoot"} = $envroot if ($envroot);
2029 $ENV{"HOME"} = $user_homedir;
2030 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
2031 $ENV{"SERVER_NAME"} = $host;
2032 $ENV{"SERVER_ADMIN"} = $config{"email"};
2033 $ENV{"SERVER_ROOT"} = $roots[0];
2034 $ENV{"SERVER_REALROOT"} = $realroot;
2035 $ENV{"SERVER_PORT"} = $port;
2036 $ENV{"REMOTE_HOST"} = $acpthost;
2037 $ENV{"REMOTE_ADDR"} = $acptip;
2038 $ENV{"REMOTE_USER"} = $authuser;
2039 $ENV{"BASE_REMOTE_USER"} = $authuser ne $baseauthuser ?
2040 $baseauthuser : undef;
2041 $ENV{"REMOTE_PASS"} = $authpass if (defined($authpass) &&
2042 $config{'pass_password'});
2043 print DEBUG "REMOTE_USER = ",$ENV{"REMOTE_USER"},"\n";
2044 print DEBUG "BASE_REMOTE_USER = ",$ENV{"BASE_REMOTE_USER"},"\n";
2045 $ENV{"SSL_USER"} = $peername if ($validated == 2);
2046 $ENV{"ANONYMOUS_USER"} = "1" if ($validated == 3 || $validated == 4);
2047 $ENV{"DOCUMENT_ROOT"} = $roots[0];
2048 $ENV{"DOCUMENT_REALROOT"} = $realroot;
2049 $ENV{"GATEWAY_INTERFACE"} = "CGI/1.1";
2050 $ENV{"SERVER_PROTOCOL"} = "HTTP/1.0";
2051 $ENV{"REQUEST_METHOD"} = $method;
2052 $ENV{"SCRIPT_NAME"} = $scriptname;
2053 $ENV{"SCRIPT_FILENAME"} = $full;
2054 $ENV{"REQUEST_URI"} = $request_uri;
2055 $ENV{"PATH_INFO"} = $pathinfo;
2057 $ENV{"PATH_TRANSLATED"} = "$roots[0]$pathinfo";
2058 $ENV{"PATH_REALTRANSLATED"} = "$realroot$pathinfo";
2060 $ENV{"QUERY_STRING"} = $querystring;
2061 $ENV{"MINISERV_CONFIG"} = $config_file;
2062 $ENV{"HTTPS"} = "ON" if ($use_ssl || $config{'inetd_ssl'});
2063 $ENV{"SESSION_ID"} = $session_id if ($session_id);
2064 $ENV{"LOCAL_USER"} = $localauth_user if ($localauth_user);
2065 $ENV{"MINISERV_INTERNAL"} = $miniserv_internal if ($miniserv_internal);
2066 if (defined($header{"content-length"})) {
2067 $ENV{"CONTENT_LENGTH"} = $header{"content-length"};
2069 if (defined($header{"content-type"})) {
2070 $ENV{"CONTENT_TYPE"} = $header{"content-type"};
2072 foreach $h (keys %header) {
2073 ($hname = $h) =~ tr/a-z/A-Z/;
2075 $ENV{"HTTP_$hname"} = $header{$h};
2077 $ENV{"PWD"} = $cgi_pwd;
2078 foreach $k (keys %config) {
2079 if ($k =~ /^env_(\S+)$/) {
2080 $ENV{$1} = $config{$k};
2083 delete($ENV{'HTTP_AUTHORIZATION'});
2084 $ENV{'HTTP_COOKIE'} =~ s/;?\s*$sidname=([a-f0-9]+)//;
2085 $ENV{'MOBILE_DEVICE'} = 1 if ($mobile_device);
2087 # Check if the CGI can be handled internally
2089 local $first = <CGI>;
2091 $first =~ s/[#!\r\n]//g;
2092 $nph_script = ($full =~ /\/nph-([^\/]+)$/);
2094 if (!$config{'forkcgis'} &&
2095 ($first eq $perl_path || $first eq $linked_perl_path) &&
2097 $config{'internalcgis'}) {
2098 # setup environment for eval
2100 @ARGV = split(/\s+/, $queryargs);
2103 # Already read the post input
2104 $postinput = $posted_data;
2106 $clen = $header{"content-length"};
2107 $SIG{'CHLD'} = 'DEFAULT';
2109 # Have SOCK closed if the perl exec's something
2111 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
2115 if ($config{'log'}) {
2116 open(MINISERVLOG, ">>$config{'logfile'}");
2117 if ($config{'logperms'}) {
2118 chmod(oct($config{'logperms'}),
2119 $config{'logfile'});
2122 chmod(0600, $config{'logfile'});
2126 $main_process_id = $$;
2128 if ($full =~ /^\Q$foundroot\E\/([^\/]+)\//) {
2129 # Eval in package from Webmin module name
2131 $pkg =~ s/[^A-Za-z0-9]/_/g;
2136 tie(*STDOUT, 'miniserv');
2137 tie(*STDIN, 'miniserv');
2138 do \$miniserv::full;
2144 &http_error(500, "Perl execution failed",
2145 $config{'noshowstderr'} ? undef : $@);
2147 elsif (!$doneheaders && !$nph_script) {
2148 &http_error(500, "Missing Headers");
2155 # fork the process that actually executes the CGI
2156 pipe(CGIINr, CGIINw);
2157 pipe(CGIOUTr, CGIOUTw);
2158 pipe(CGIERRr, CGIERRw);
2159 if (!($cgipid = fork())) {
2160 @execargs = ( $full, split(/\s+/, $queryargs) );
2163 open(STDIN, "<&CGIINr");
2164 open(STDOUT, ">&CGIOUTw");
2165 open(STDERR, ">&CGIERRw");
2166 close(CGIINw); close(CGIOUTr); close(CGIERRr);
2168 die "Failed to exec $full : $!\n";
2171 close(CGIINr); close(CGIOUTw); close(CGIERRw);
2174 # write CGI input to a temp file
2175 $infile = "$config{'tempbase'}.$$";
2176 open(CGIINw, ">$infile");
2177 # NOT binary mode, as CGIs don't read in it!
2182 # already read the posted data
2183 print CGIINw $posted_data;
2185 $clen = $header{"content-length"};
2186 if ($method eq "POST" && $clen_read < $clen) {
2187 $SIG{'PIPE'} = 'IGNORE';
2189 while($got < $clen) {
2190 $buf = &read_data($clen-$got);
2191 if (!length($buf)) {
2192 kill('TERM', $cgipid);
2193 unlink($infile) if ($infile);
2194 &http_error(500, "Failed to read ".
2197 $got += length($buf);
2198 local ($wrote) = (print CGIINw $buf);
2201 # If the CGI terminated early, we still need to read
2202 # from the browser and throw away
2203 while($got < $clen) {
2204 $buf = &read_data($clen-$got);
2205 if (!length($buf)) {
2206 kill('TERM', $cgipid);
2207 unlink($infile) if ($infile);
2208 &http_error(500, "Failed to read ".
2211 $got += length($buf);
2213 $SIG{'PIPE'} = 'DEFAULT';
2219 # Run the CGI program, and feed it input
2221 local $qqueryargs = join(" ", map { "\"$_\"" }
2222 split(/\s+/, $queryargs));
2223 if ($first =~ /(perl|perl.exe)$/i) {
2224 # On Windows, run with Perl
2225 open(CGIOUTr, "$perl_path \"$full\" $qqueryargs <$infile |");
2228 open(CGIOUTr, "\"$full\" $qqueryargs <$infile |");
2234 # read back cgi headers
2235 select(CGIOUTr); $|=1; select(STDOUT);
2239 $line =~ s/\r|\n//g;
2241 if ($got_blank || %cgiheader) { last; }
2245 if ($line !~ /^(\S+):\s+(.*)$/) {
2246 $errs = &read_errors(CGIERRr);
2247 close(CGIOUTr); close(CGIERRr);
2248 unlink($infile) if ($infile);
2249 &http_error(500, "Bad Header", $errs);
2251 $cgiheader{lc($1)} = $2;
2252 push(@cgiheader, [ $1, $2 ]);
2254 if ($cgiheader{"location"}) {
2255 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2256 &write_data("Date: $datestr\r\n");
2257 &write_data("Server: $config{'server'}\r\n");
2258 &write_keep_alive(0);
2259 # ignore the rest of the output. This is a hack,
2260 # but is necessary for IE in some cases :(
2261 close(CGIOUTr); close(CGIERRr);
2263 elsif ($cgiheader{"content-type"} eq "") {
2264 close(CGIOUTr); close(CGIERRr);
2265 unlink($infile) if ($infile);
2266 $errs = &read_errors(CGIERRr);
2267 &http_error(500, "Missing Content-Type Header",
2268 $config{'noshowstderr'} ? undef : $errs);
2271 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2272 &write_data("Date: $datestr\r\n");
2273 &write_data("Server: $config{'server'}\r\n");
2274 &write_keep_alive(0);
2276 foreach $h (@cgiheader) {
2277 &write_data("$h->[0]: $h->[1]\r\n");
2279 &write_data("\r\n");
2281 &reset_byte_count();
2282 while($line = <CGIOUTr>) {
2287 unlink($infile) if ($infile);
2293 print DEBUG "handle_request: outputting file\n";
2294 open(FILE, $full) || &http_error(404, "Failed to open file");
2296 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2297 "Date: $datestr\r\n".
2298 "Server: $config{server}\r\n".
2299 "Content-type: ".&get_type($full)."\r\n".
2300 "Content-length: $stfull[7]\r\n".
2301 "Last-Modified: ".&http_date($stfull[9])."\r\n".
2302 "Expires: ".&http_date(time()+$config{'expires'})."\r\n";
2304 $rv = &write_keep_alive();
2305 &write_data("\r\n");
2306 &reset_byte_count();
2307 while(read(FILE, $buf, 1024) > 0) {
2314 &log_request($acpthost, $authuser, $reqline,
2315 $logged_code ? $logged_code :
2316 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2320 # http_error(code, message, body, [dontexit])
2323 local $eh = $error_handler_recurse ? undef :
2324 $config{"error_handler_$_[0]"} ? $config{"error_handler_$_[0]"} :
2325 $config{'error_handler'} ? $config{'error_handler'} : undef;
2326 print DEBUG "http_error code=$_[0] message=$_[1] body=$_[2]\n";
2328 # Call a CGI program for the error
2330 $querystring = "code=$_[0]&message=".&urlize($_[1]).
2331 "&body=".&urlize($_[2]);
2332 $error_handler_recurse++;
2334 $ok_message = $_[1];
2338 # Use the standard error message display
2339 &write_data("HTTP/1.0 $_[0] $_[1]\r\n");
2340 &write_data("Server: $config{server}\r\n");
2341 &write_data("Date: $datestr\r\n");
2342 &write_data("Content-type: text/html\r\n");
2343 &write_keep_alive(0);
2344 &write_data("\r\n");
2345 &reset_byte_count();
2346 &write_data("<h1>Error - $_[1]</h1>\n");
2348 &write_data("<pre>$_[2]</pre>\n");
2351 &log_request($acpthost, $authuser, $reqline, $_[0], &byte_count())
2353 &log_error($_[1], $_[2] ? " : $_[2]" : "");
2360 if ($_[0] =~ /\.([A-z0-9]+)$/) {
2366 return "text/plain";
2369 # simplify_path(path, bogus)
2370 # Given a path, maybe containing stuff like ".." and "." convert it to a
2371 # clean, absolute form.
2374 local($dir, @bits, @fixedbits, $b);
2376 $dir =~ s/\\/\//g; # fix windows \ in path
2379 $dir =~ s/\0//g; # remove null bytes
2380 @bits = split(/\/+/, $dir);
2383 foreach $b (@bits) {
2387 elsif ($b eq ".." || $b eq "...") {
2389 if (scalar(@fixedbits) == 0) {
2397 push(@fixedbits, $b);
2400 return "/" . join('/', @fixedbits);
2404 # Converts a string from base64 format to normal
2407 local($str) = $_[0];
2409 $str =~ tr|A-Za-z0-9+=/||cd;
2411 $str =~ tr|A-Za-z0-9+/| -_|;
2412 while ($str =~ /(.{1,60})/gs) {
2413 my $len = chr(32 + length($1)*3/4);
2414 $res .= unpack("u", $len . $1 );
2419 # ip_match(remoteip, localip, [match]+)
2420 # Checks an IP address against a list of IPs, networks and networks/masks
2423 local(@io, @mo, @ms, $i, $j, $hn, $needhn);
2424 @io = split(/\./, $_[0]);
2425 for($i=2; $i<@_; $i++) {
2426 $needhn++ if ($_[$i] =~ /^\*(\S+)$/);
2428 if ($needhn && !defined($hn = $ip_match_cache{$_[0]})) {
2429 $hn = gethostbyaddr(inet_aton($_[0]), AF_INET);
2430 $hn = "" if (&to_ipaddress($hn) ne $_[0]);
2431 $ip_match_cache{$_[0]} = $hn;
2433 for($i=2; $i<@_; $i++) {
2434 local $mismatch = 0;
2435 if ($_[$i] =~ /^(\S+)\/(\d+)$/) {
2436 # Convert CIDR to netmask format
2437 $_[$i] = $1."/".&prefix_to_mask($2);
2439 if ($_[$i] =~ /^(\S+)\/(\S+)$/) {
2440 # Compare with network/mask
2441 @mo = split(/\./, $1); @ms = split(/\./, $2);
2442 for($j=0; $j<4; $j++) {
2443 if ((int($io[$j]) & int($ms[$j])) != int($mo[$j])) {
2448 elsif ($_[$i] =~ /^\*(\S+)$/) {
2449 # Compare with hostname regexp
2450 $mismatch = 1 if ($hn !~ /$1$/);
2452 elsif ($_[$i] eq 'LOCAL') {
2453 # Compare with local network
2454 local @lo = split(/\./, $_[1]);
2456 $mismatch = 1 if ($lo[0] != $io[0]);
2458 elsif ($lo[0] < 192) {
2459 $mismatch = 1 if ($lo[0] != $io[0] ||
2463 $mismatch = 1 if ($lo[0] != $io[0] ||
2468 elsif ($_[$i] !~ /^[0-9\.]+$/) {
2469 # Compare with hostname
2470 $mismatch = 1 if ($_[0] ne &to_ipaddress($_[$i]));
2473 # Compare with IP or network
2474 @mo = split(/\./, $_[$i]);
2475 while(@mo && !$mo[$#mo]) { pop(@mo); }
2476 for($j=0; $j<@mo; $j++) {
2477 if ($mo[$j] != $io[$j]) {
2482 return 1 if (!$mismatch);
2487 # users_match(&uinfo, user, ...)
2488 # Returns 1 if a user is in a list of users and groups
2491 local $uinfo = shift(@_);
2493 local @ginfo = getgrgid($uinfo->[3]);
2495 if ($u =~ /^\@(\S+)$/) {
2496 return 1 if (&is_group_member($uinfo, $1));
2498 elsif ($u =~ /^(\d*)-(\d*)$/ && ($1 || $2)) {
2499 return (!$1 || $uinfo[2] >= $1) &&
2500 (!$2 || $uinfo[2] <= $2);
2503 return 1 if ($u eq $uinfo->[0]);
2509 # restart_miniserv()
2510 # Called when a SIGHUP is received to restart the web server. This is done
2511 # by exec()ing perl with the same command line as was originally used
2512 sub restart_miniserv
2514 print STDERR "restarting miniserv\n";
2515 &log_error("Restarting");
2517 &close_all_sockets();
2519 dbmclose(%sessiondb);
2520 kill('KILL', $logclearer) if ($logclearer);
2521 kill('KILL', $extauth) if ($extauth);
2522 exec($perl_path, $miniserv_path, @miniserv_argv);
2523 die "Failed to restart miniserv with $perl_path $miniserv_path";
2540 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2541 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/) { push(@rv, $i); }
2542 else { push(@rv, join('.', unpack("CCCC", inet_aton($i)))); }
2544 return wantarray ? @rv : $rv[0];
2547 # read_line(no-wait, no-limit)
2548 # Reads one line from SOCK or SSL
2551 local ($nowait, $nolimit) = @_;
2552 local($idx, $more, $rv);
2553 while(($idx = index($main::read_buffer, "\n")) < 0) {
2554 if (length($main::read_buffer) > 10000 && !$nolimit) {
2555 &http_error(414, "Request too long",
2556 "Received excessive line <pre>$main::read_buffer</pre>");
2559 # need to read more..
2560 &wait_for_data_error() if (!$nowait);
2562 $more = Net::SSLeay::read($ssl_con);
2565 local $ok = sysread(SOCK, $more, 1024);
2566 $more = undef if ($ok <= 0);
2570 $rv = $main::read_buffer;
2571 undef($main::read_buffer);
2574 $main::read_buffer .= $more;
2576 $rv = substr($main::read_buffer, 0, $idx+1);
2577 $main::read_buffer = substr($main::read_buffer, $idx+1);
2582 # Reads up to some amount of data from SOCK or the SSL connection
2586 if (length($main::read_buffer)) {
2587 if (length($main::read_buffer) > $_[0]) {
2588 # Return the first part of the buffer
2589 $rv = substr($main::read_buffer, 0, $_[0]);
2590 $main::read_buffer = substr($main::read_buffer, $_[0]);
2594 # Return the whole buffer
2595 $rv = $main::read_buffer;
2596 undef($main::read_buffer);
2601 # Call SSL read function
2602 return Net::SSLeay::read($ssl_con, $_[0]);
2605 # Just do a normal read
2607 sysread(SOCK, $buf, $_[0]) || return undef;
2613 # Read a line from a file handle, using sysread to get a byte at a time
2620 $got = sysread($fh, $buf, 1);
2621 last if ($got <= 0);
2623 last if ($buf eq "\n");
2628 # wait_for_data(secs)
2629 # Waits at most the given amount of time for some data on SOCK, returning
2630 # 0 if not found, 1 if some arrived.
2634 vec($rmask, fileno(SOCK), 1) = 1;
2635 local $got = select($rmask, undef, undef, $_[0]);
2636 return $got == 0 ? 0 : 1;
2639 # wait_for_data_error()
2640 # Waits 60 seconds for data on SOCK, and fails if none arrives
2641 sub wait_for_data_error
2643 local $got = &wait_for_data(60);
2645 &http_error(400, "Timeout",
2646 "Waited more than 60 seconds for request data");
2650 # write_data(data, ...)
2651 # Writes a string to SOCK or the SSL connection
2654 local $str = join("", @_);
2656 Net::SSLeay::write($ssl_con, $str);
2659 syswrite(SOCK, $str, length($str));
2661 # Intentionally introduce a small delay to avoid problems where IE reports
2662 # the page as empty / DNS failed when it get a large response too quickly!
2663 select(undef, undef, undef, .01) if ($write_data_count%10 == 0);
2664 $write_data_count += length($str);
2667 # reset_byte_count()
2668 sub reset_byte_count { $write_data_count = 0; }
2671 sub byte_count { return $write_data_count; }
2673 # log_request(hostname, user, request, code, bytes)
2676 if ($config{'log'}) {
2677 local ($user, $ident, $headers);
2678 if ($config{'logident'}) {
2679 # add support for rfc1413 identity checking here
2681 else { $ident = "-"; }
2682 $user = $_[1] ? $_[1] : "-";
2683 local $dstr = &make_datestr();
2684 if (fileno(MINISERVLOG)) {
2685 seek(MINISERVLOG, 0, 2);
2688 open(MINISERVLOG, ">>$config{'logfile'}");
2689 chmod(0600, $config{'logfile'});
2691 if (defined($config{'logheaders'})) {
2692 foreach $h (split(/\s+/, $config{'logheaders'})) {
2693 $headers .= " $h=\"$header{$h}\"";
2696 elsif ($config{'logclf'}) {
2697 $headers = " \"$header{'referer'}\" \"$header{'user-agent'}\"";
2702 print MINISERVLOG "$_[0] $ident $user [$dstr] \"$_[2]\" ",
2703 "$_[3] $_[4]$headers\n";
2711 local @tm = localtime(time());
2712 return sprintf "%2.2d/%s/%4.4d:%2.2d:%2.2d:%2.2d %s",
2713 $tm[3], $month[$tm[4]], $tm[5]+1900,
2714 $tm[2], $tm[1], $tm[0], $timezone;
2717 # log_error(message)
2721 print STDERR "[",&make_datestr(),"] ",
2722 $acpthost ? ( "[",$acpthost,"] " ) : ( ),
2723 $page ? ( $page," : " ) : ( ),
2727 # read_errors(handle)
2728 # Read and return all input from some filehandle
2731 local($fh, $_, $rv);
2733 while(<$fh>) { $rv .= $_; }
2737 sub write_keep_alive
2740 if ($config{'nokeepalive'}) {
2741 # Keep alives have been disabled in config
2744 elsif (@childpids > $config{'maxconns'}*.8) {
2745 # Disable because nearing process limit
2749 # Keep alive specified by caller
2753 # Keep alive determined by browser
2754 $mode = $header{'connection'} =~ /keep-alive/i;
2756 &write_data("Connection: ".($mode ? "Keep-Alive" : "close")."\r\n");
2762 kill('TERM', @childpids) if (@childpids);
2763 kill('KILL', $logclearer) if ($logclearer);
2764 kill('KILL', $extauth) if ($extauth);
2770 local @tm = gmtime($_[0]);
2771 return sprintf "%s, %d %s %d %2.2d:%2.2d:%2.2d GMT",
2772 $weekday[$tm[6]], $tm[3], $month[$tm[4]], $tm[5]+1900,
2773 $tm[2], $tm[1], $tm[0];
2778 my $i; bless \$i, shift;
2784 my($buf,$len,$offset) = @_;
2785 &write_to_sock(substr($buf, $offset, $len));
2792 my $buf = join(defined($,) ? $, : "", @_);
2793 $buf .= $\ if defined($\);
2794 &write_to_sock($buf);
2801 &write_to_sock(sprintf $fmt, @_);
2804 # Send back already read data while we have it, then read from SOCK
2808 my $bufref = \$_[0];
2811 if ($postpos < length($postinput)) {
2812 # Reading from already fetched array
2813 my $left = length($postinput) - $postpos;
2814 my $canread = $len > $left ? $left : $len;
2815 substr($$bufref, $offset, $canread) =
2816 substr($postinput, $postpos, $canread);
2817 $postpos += $canread;
2821 # Read from network socket
2822 local $data = &read_data($len);
2823 if ($data eq '' && $len) {
2825 print STDERR "finished reading - shutting down socket\n";
2828 substr($$bufref, $offset, length($data)) = $data;
2829 return length($data);
2835 #print STDERR "open() called - should never happen!\n";
2838 # Read a line of input
2842 if ($postpos < length($postinput) &&
2843 ($idx = index($postinput, "\n", $postpos)) >= 0) {
2844 # A line exists in the memory buffer .. use it
2845 my $line = substr($postinput, $postpos, $idx-$postpos+1);
2850 # Need to read from the socket
2852 if ($postpos < length($postinput)) {
2853 # Start with in-memory data
2854 $line = substr($postinput, $postpos);
2855 $postpos = length($postinput);
2857 my $nl = &read_line(0, 1);
2860 print STDERR "finished reading - shutting down socket\n";
2863 $line .= $nl if (defined($nl));
2868 # Read one character of input
2873 my $got = READ($r, \$buf, 1, 0);
2874 return $got > 0 ? $buf : undef;
2879 return fileno(SOCK);
2886 # write_to_sock(data, ...)
2891 if ($doneheaders || $miniserv::nph_script) {
2896 while(!$doneheaders && $headers =~ s/^([^\r\n]*)(\r)?\n//) {
2897 if ($1 =~ /^(\S+):\s+(.*)$/) {
2898 $cgiheader{lc($1)} = $2;
2899 push(@cgiheader, [ $1, $2 ]);
2901 elsif ($1 !~ /\S/) {
2905 &http_error(500, "Bad Header");
2909 if ($cgiheader{"location"}) {
2911 "HTTP/1.0 302 Moved Temporarily\r\n");
2912 &write_data("Date: $datestr\r\n");
2913 &write_data("Server: $config{server}\r\n");
2914 &write_keep_alive(0);
2916 elsif ($cgiheader{"content-type"} eq "") {
2917 &http_error(500, "Missing Content-Type Header");
2920 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2921 &write_data("Date: $datestr\r\n");
2922 &write_data("Server: $config{server}\r\n");
2923 &write_keep_alive(0);
2925 foreach $h (@cgiheader) {
2926 &write_data("$h->[0]: $h->[1]\r\n");
2928 &write_data("\r\n");
2929 &reset_byte_count();
2930 &write_data($headers);
2938 local $cert = Net::SSLeay::X509_STORE_CTX_get_current_cert($_[1]);
2940 local $errnum = Net::SSLeay::X509_STORE_CTX_get_error($_[1]);
2941 $verified_client = 1 if (!$errnum);
2948 if ($doing_eval && $$ == $main_process_id) {
2949 # A CGI program called exit! This is a horrible hack to
2950 # finish up before really exiting
2953 close($PASSINw); close($PASSOUTw);
2954 &log_request($acpthost, $authuser, $reqline,
2955 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2960 # Convert a string to a form ok for putting in a URL
2962 local($tmp, $tmp2, $c);
2965 while(($c = chop($tmp)) ne "") {
2966 if ($c !~ /[A-z0-9]/) {
2967 $c = sprintf("%%%2.2X", ord($c));
2974 # validate_user(username, password, host)
2975 # Checks if some username and password are valid. Returns the modified username,
2976 # the expired / temp pass flag, and the non-existence flag
2979 local ($user, $pass, $host) = @_;
2980 return ( ) if (!$user);
2981 print DEBUG "validate_user: user=$user pass=$pass host=$host\n";
2982 local ($canuser, $canmode, $notexist, $webminuser, $sudo) =
2983 &can_user_login($user, undef, $host);
2984 print DEBUG "validate_user: canuser=$canuser canmode=$canmode notexist=$notexist webminuser=$webminuser sudo=$sudo\n";
2986 # User doesn't even exist, so go no further
2987 return ( undef, 0, 1 );
2989 elsif ($canmode == 0) {
2990 # User does exist but cannot login
2991 return ( $canuser, 0, 0 );
2993 elsif ($canmode == 1) {
2994 # Attempt Webmin authentication
2995 if ($users{$webminuser} eq
2996 &password_crypt($pass, $users{$webminuser})) {
2997 # Password is valid .. but check for expiry
2998 local $lc = $lastchanges{$user};
2999 if ($config{'pass_maxdays'} && $lc && !$nochange{$user}) {
3000 local $daysold = (time() - $lc)/(24*60*60);
3001 print DEBUG "maxdays=$config{'pass_maxdays'} daysold=$daysold temppass=$temppass{$user}\n";
3002 if ($config{'pass_lockdays'} &&
3003 $daysold > $config{'pass_lockdays'}) {
3004 # So old that the account is locked
3005 return ( undef, 0, 0 );
3007 elsif ($daysold > $config{'pass_maxdays'}) {
3008 # Password has expired
3009 return ( $user, 1, 0 );
3012 if ($temppass{$user}) {
3013 # Temporary password - force change now
3014 return ( $user, 2, 0 );
3016 return ( $user, 0, 0 );
3019 return ( undef, 0, 0 );
3022 elsif ($canmode == 2 || $canmode == 3) {
3023 # Attempt PAM or passwd file authentication
3024 local $val = &validate_unix_user($canuser, $pass);
3025 print DEBUG "validate_user: unix val=$val\n";
3026 if ($val && $sudo) {
3027 # Need to check if this Unix user can sudo
3028 if (!&check_sudo_permissions($canuser, $pass)) {
3029 print DEBUG "validate_user: sudo failed\n";
3033 print DEBUG "validate_user: sudo passed\n";
3036 return $val == 2 ? ( $canuser, 1, 0 ) :
3037 $val == 1 ? ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3039 elsif ($canmode == 4) {
3040 # Attempt external authentication
3041 return &validate_external_user($canuser, $pass) ?
3042 ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3050 # validate_unix_user(user, password)
3051 # Returns 1 if a username and password are valid under unix, 0 if not,
3052 # or 2 if the account has expired.
3053 # Checks PAM if available, and falls back to reading the system password
3055 sub validate_unix_user
3059 $pam_username = $_[0];
3060 $pam_password = $_[1];
3061 local $pamh = new Authen::PAM($config{'pam'}, $pam_username,
3064 local $pam_ret = $pamh->pam_authenticate();
3065 if ($pam_ret == PAM_SUCCESS()) {
3066 # Logged in OK .. make sure password hasn't expired
3067 local $acct_ret = $pamh->pam_acct_mgmt();
3068 if ($acct_ret == PAM_SUCCESS()) {
3069 $pamh->pam_open_session();
3072 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3073 $acct_ret == PAM_ACCT_EXPIRED()) {
3077 print STDERR "Unknown pam_acct_mgmt return value : $acct_ret\n";
3084 elsif ($config{'pam_only'}) {
3085 # Pam is not available, but configuration forces it's use!
3088 elsif ($config{'passwd_file'}) {
3089 # Check in a password file
3091 open(FILE, $config{'passwd_file'});
3092 if ($config{'passwd_file'} eq '/etc/security/passwd') {
3093 # Assume in AIX format
3096 if (/^\s*(\S+):/ && $1 eq $_[0]) {
3098 if (/^\s*password\s*=\s*(\S+)\s*$/) {
3099 $rv = $1 eq &password_crypt($_[1], $1) ?
3107 # Read the system password or shadow file
3109 local @l = split(/:/, $_, -1);
3110 local $u = $l[$config{'passwd_uindex'}];
3111 local $p = $l[$config{'passwd_pindex'}];
3113 $rv = $p eq &password_crypt($_[1], $p) ? 1 : 0;
3114 if ($config{'passwd_cindex'} ne '' && $rv) {
3115 # Password may have expired!
3116 local $c = $l[$config{'passwd_cindex'}];
3117 local $m = $l[$config{'passwd_mindex'}];
3118 local $day = time()/(24*60*60);
3119 if ($c =~ /^\d+/ && $m =~ /^\d+/ &&
3125 if ($p eq "" && $config{'passwd_blank'}) {
3126 # Force password change
3134 return $rv if ($rv);
3137 # Fallback option - check password returned by getpw*
3138 local @uinfo = getpwnam($_[0]);
3139 if ($uinfo[1] ne '' && &password_crypt($_[1], $uinfo[1]) eq $uinfo[1]) {
3143 return 0; # Totally failed
3146 # validate_external_user(user, pass)
3147 # Validate a user by passing the username and password to an external
3148 # squid-style authentication program
3149 sub validate_external_user
3151 return 0 if (!$config{'extauth'});
3153 local $str = "$_[0] $_[1]\n";
3154 syswrite(EXTAUTH, $str, length($str));
3155 local $resp = <EXTAUTH>;
3157 return $resp =~ /^OK/i ? 1 : 0;
3160 # can_user_login(username, no-append, host)
3161 # Checks if a user can login or not.
3162 # First return value is the username.
3163 # Second is 0 if cannot login, 1 if using Webmin pass, 2 if PAM, 3 if password
3164 # file, 4 if external.
3165 # Third is 1 if the user does not exist at all, 0 if he does.
3166 # Fourth is the Webmin username whose permissions apply, based on unixauth.
3167 # Fifth is a flag indicating if a sudo check is needed.
3170 if (!$users{$_[0]}) {
3171 # See if this user exists in Unix and can be validated by the same
3172 # method as the unixauth webmin user
3173 local $realuser = $unixauth{$_[0]};
3177 eval { @uinfo = getpwnam($_[0]); }; # may fail on windows
3178 if (!$realuser && @uinfo) {
3179 # No unixauth entry for the username .. try his groups
3180 foreach my $ua (keys %unixauth) {
3181 if ($ua =~ /^\@(.*)$/) {
3182 if (&is_group_member(\@uinfo, $1)) {
3183 $realuser = $unixauth{$ua};
3189 if (!$realuser && @uinfo) {
3190 # Fall back to unix auth for all Unix users
3191 $realuser = $unixauth{"*"};
3193 if (!$realuser && $use_sudo && @uinfo) {
3194 # Allow login effectively as root, if sudo permits it
3198 if (!$realuser && !@uinfo && $config{'pamany'}) {
3199 # If the user completely doesn't exist, we can still allow
3200 # him to authenticate via PAM
3201 $realuser = $config{'pamany'};
3205 # For Usermin, always fall back to unix auth for any user,
3206 # so that later checks with domain added / removed are done.
3207 $realuser = $unixauth{"*"};
3209 return (undef, 0, 1, undef) if (!$realuser);
3210 local $up = $users{$realuser};
3211 return (undef, 0, 1, undef) if (!defined($up));
3213 # Work out possible domain names from the hostname
3214 local @doms = ( $_[2] );
3215 if ($_[2] =~ /^([^\.]+)\.(\S+)$/) {
3219 if ($config{'user_mapping'} && !defined(%user_mapping)) {
3220 # Read the user mapping file
3222 open(MAPPING, $config{'user_mapping'});
3226 if (/^(\S+)\s+(\S+)/) {
3227 if ($config{'user_mapping_reverse'}) {
3228 $user_mapping{$1} = $2;
3231 $user_mapping{$2} = $1;
3238 # Check the user mapping file to see if there is an entry for the
3239 # user login in which specifies a new effective user
3241 foreach my $d (@doms) {
3242 $um ||= $user_mapping{"$_[0]\@$d"};
3244 $um ||= $user_mapping{$_[0]};
3245 if (defined($um) && ($_[1]&4) == 0) {
3246 # A mapping exists - use it!
3247 return &can_user_login($um, $_[1]+4, $_[2]);
3250 # Check if a user with the entered login and the domains appended
3251 # or prepended exists, and if so take it to be the effective user
3252 if (!@uinfo && $config{'domainuser'}) {
3253 # Try again with name.domain and name.firstpart
3254 local @firsts = map { /^([^\.]+)/; $1 } @doms;
3255 if (($_[1]&1) == 0) {
3257 foreach $a (@firsts, @doms) {
3258 foreach $p ("$_[0].${a}", "$_[0]-${a}",
3259 "${a}.$_[0]", "${a}-$_[0]",
3260 "$_[0]_${a}", "${a}_$_[0]") {
3261 local @vu = &can_user_login(
3262 $p, $_[1]+1, $_[2]);
3263 return @vu if ($vu[1]);
3269 # Check if the user entered a domain at the end of his username when
3270 # he really shouldn't have, and if so try without it
3271 if (!@uinfo && $config{'domainstrip'} &&
3272 $_[0] =~ /^(\S+)\@(\S+)$/ && ($_[1]&2) == 0) {
3273 local ($stripped, $dom) = ($1, $2);
3274 local @vu = &can_user_login($stripped, $_[1] + 2, $_[2]);
3275 return @vu if ($vu[1]);
3276 local @vu = &can_user_login($stripped, $_[1] + 2, $dom);
3277 return @vu if ($vu[1]);
3280 return ( undef, 0, 1, undef ) if (!@uinfo && !$pamany);
3283 if (defined(@allowusers)) {
3284 # Only allow people on the allow list
3285 return ( undef, 0, 0, undef )
3286 if (!&users_match(\@uinfo, @allowusers));
3288 elsif (defined(@denyusers)) {
3289 # Disallow people on the deny list
3290 return ( undef, 0, 0, undef )
3291 if (&users_match(\@uinfo, @denyusers));
3293 if ($config{'shells_deny'}) {
3295 open(SHELLS, $config{'shells_deny'});
3299 $found++ if ($_ eq $uinfo[8]);
3302 return ( undef, 0, 0, undef ) if (!$found);
3307 # PAM or passwd file authentication
3308 return ( $_[0], $use_pam ? 2 : 3, 0, $realuser, $sudo );
3310 elsif ($up eq 'e') {
3311 # External authentication
3312 return ( $_[0], 4, 0, $realuser, $sudo );
3315 # Fixed Webmin password
3316 return ( $_[0], 1, 0, $realuser, $sudo );
3319 elsif ($users{$_[0]} eq 'x') {
3320 # Webmin user authenticated via PAM or password file
3321 return ( $_[0], $use_pam ? 2 : 3, 0, $_[0] );
3323 elsif ($users{$_[0]} eq 'e') {
3324 # Webmin user authenticated externally
3325 return ( $_[0], 4, 0, $_[0] );
3328 # Normal Webmin user
3329 return ( $_[0], 1, 0, $_[0] );
3333 # the PAM conversation function for interactive logins
3336 $pam_conv_func_called++;
3343 $ans = $pam_username if ($code == PAM_PROMPT_ECHO_ON() );
3344 $ans = $pam_password if ($code == PAM_PROMPT_ECHO_OFF() );
3346 push @res, PAM_SUCCESS();
3349 push @res, PAM_SUCCESS();
3358 # get_socket_name(handle)
3359 # Returns the local hostname or IP address of some connection
3362 return $config{'host'} if ($config{'host'});
3363 local $sn = getsockname($_[0]);
3364 return undef if (!$sn);
3365 local $myaddr = (unpack_sockaddr_in($sn))[1];
3366 if (!$get_socket_name_cache{$myaddr}) {
3368 if (!$config{'no_resolv_myname'}) {
3369 $myname = gethostbyaddr($myaddr, AF_INET);
3371 if ($myname eq "") {
3372 $myname = inet_ntoa($myaddr);
3374 $get_socket_name_cache{$myaddr} = $myname;
3376 return $get_socket_name_cache{$myaddr};
3379 # run_login_script(username, sid, remoteip, localip)
3380 sub run_login_script
3382 if ($config{'login_script'}) {
3383 system($config{'login_script'}.
3384 " ".join(" ", map { quotemeta($_) } @_).
3385 " >/dev/null 2>&1 </dev/null");
3389 # run_logout_script(username, sid, remoteip, localip)
3390 sub run_logout_script
3392 if ($config{'logout_script'}) {
3393 system($config{'logout_script'}.
3394 " ".join(" ", map { quotemeta($_) } @_).
3395 " >/dev/null 2>&1 </dev/null");
3399 # close_all_sockets()
3400 # Closes all the main listening sockets
3401 sub close_all_sockets
3404 foreach $s (@socketfhs) {
3410 # Close all pipes for talking to sub-processes
3414 foreach $p (@passin) { close($p); }
3415 foreach $p (@passout) { close($p); }
3416 foreach $p (values %conversations) {
3417 if ($p->{'PAMOUTr'}) {
3418 close($p->{'PAMOUTr'});
3419 close($p->{'PAMINw'});
3424 # check_user_ip(user)
3425 # Returns 1 if some user is allowed to login from the accepting IP, 0 if not
3429 &ip_match($acptip, $localip, @{$deny{$_[0]}}) ||
3431 !&ip_match($acptip, $localip, @{$allow{$_[0]}})) {
3437 # check_user_time(user)
3438 # Returns 1 if some user is allowed to login at the current date and time
3441 return 1 if (!$allowdays{$_[0]} && !$allowhours{$_[0]});
3442 local @tm = localtime(time());
3443 if ($allowdays{$_[0]}) {
3444 # Make sure day is allowed
3445 return 0 if (&indexof($tm[6], @{$allowdays{$_[0]}}) < 0);
3447 if ($allowhours{$_[0]}) {
3448 # Make sure time is allowed
3449 local $m = $tm[2]*60+$tm[1];
3450 return 0 if ($m < $allowhours{$_[0]}->[0] ||
3451 $m > $allowhours{$_[0]}->[1]);
3456 # generate_random_id(password, [force-urandom])
3457 # Returns a random session ID number
3458 sub generate_random_id
3460 local ($pass, $force_urandom) = @_;
3462 if (!$bad_urandom) {
3463 # First try /dev/urandom, unless we have marked it as bad
3464 $SIG{ALRM} = "miniserv::urandom_timeout";
3466 if (open(RANDOM, "/dev/urandom")) {
3468 if (read(RANDOM, $tmpsid, 16) == 16) {
3469 $sid = lc(unpack('h*',$tmpsid));
3475 if (!$sid && !$force_urandom) {
3478 foreach $c (split(//, &unix_crypt($pass, substr($$, -2)))) {
3479 $sid += ord($c) * $mul;
3486 # handle_login(username, ok, expired, not-exists, password, [no-test-cookie])
3487 # Called from handle_session to either mark a user as logged in, or not
3490 local ($vu, $ok, $expired, $nonexist, $pass, $notest) = @_;
3491 $authuser = $vu if ($ok);
3493 # check if the test cookie is set
3494 if ($header{'cookie'} !~ /testing=1/ && $vu &&
3495 !$config{'no_testing_cookie'} && !$notest) {
3496 &http_error(500, "No cookies",
3497 "Your browser does not support cookies, ".
3498 "which are required for this web server to ".
3499 "work in session authentication mode");
3502 # check with main process for delay
3503 if ($config{'passdelay'} && $vu) {
3504 print $PASSINw "delay $vu $acptip $ok\n";
3505 <$PASSOUTr> =~ /(\d+) (\d+)/;
3510 if ($ok && (!$expired ||
3511 $config{'passwd_mode'} == 1)) {
3512 # Logged in OK! Tell the main process about
3514 local $sid = &generate_random_id($pass);
3515 print $PASSINw "new $sid $authuser $acptip\n";
3517 # Run the post-login script, if any
3518 &run_login_script($authuser, $sid,
3521 # Check for a redirect URL for the user
3522 local $rurl = &login_redirect($authuser, $pass, $host);
3524 # Got one .. go to it
3525 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3526 &write_data("Date: $datestr\r\n");
3527 &write_data("Server: $config{'server'}\r\n");
3528 &write_data("Location: $rurl\r\n");
3529 &write_keep_alive(0);
3530 &write_data("\r\n");
3531 &log_request($acpthost, $authuser, $reqline, 302, 0);
3534 # Set cookie and redirect to originally requested page
3535 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3536 &write_data("Date: $datestr\r\n");
3537 &write_data("Server: $config{'server'}\r\n");
3538 local $ssl = $use_ssl || $config{'inetd_ssl'};
3539 $portstr = $port == 80 && !$ssl ? "" :
3540 $port == 443 && $ssl ? "" : ":$port";
3541 $prot = $ssl ? "https" : "http";
3542 local $sec = $ssl ? "; secure" : "";
3543 #$sec .= "; httpOnly";
3545 &write_data("Set-Cookie: $sidname=$sid; path=/; expires=\"Thu, 31-Dec-2037 00:00:00\"$sec\r\n");
3548 &write_data("Set-Cookie: $sidname=$sid; path=/$sec\r\n");
3550 &write_data("Location: $prot://$host$portstr$in{'page'}\r\n");
3551 &write_keep_alive(0);
3552 &write_data("\r\n");
3553 &log_request($acpthost, $authuser, $reqline, 302, 0);
3554 syslog("info", "%s", "Successful login as $authuser from $acpthost") if ($use_syslog);
3555 &write_login_utmp($authuser, $acpthost);
3559 elsif ($ok && $expired &&
3560 ($config{'passwd_mode'} == 2 || $expired == 2)) {
3561 # Login was ok, but password has expired or was temporary. Need
3562 # to force display of password change form.
3565 $querystring = "&user=".&urlize($vu).
3567 "&expired=".$expired;
3570 $page = $config{'password_form'};
3572 $miniserv_internal = 2;
3573 syslog("crit", "%s",
3574 "Expired login as $vu ".
3575 "from $acpthost") if ($use_syslog);
3578 # Login failed, or password has expired. The login form will be
3579 # displayed again by later code
3581 $request_uri = $in{'page'};
3582 $already_session_id = undef;
3584 $authuser = $baseauthuser = undef;
3585 syslog("crit", "%s",
3586 ($nonexist ? "Non-existent" :
3587 $expired ? "Expired" : "Invalid").
3588 " login as $vu from $acpthost")
3594 # write_login_utmp(user, host)
3595 # Record the login by some user in utmp
3596 sub write_login_utmp
3599 # Write utmp record for login
3600 %utmp = ( 'ut_host' => $_[1],
3601 'ut_time' => time(),
3603 'ut_type' => 7, # user process
3604 'ut_pid' => $main_process_id,
3605 'ut_line' => $config{'pam'},
3607 if (defined(&User::Utmp::putut)) {
3608 User::Utmp::putut(\%utmp);
3611 User::Utmp::pututline(\%utmp);
3616 # write_logout_utmp(user, host)
3617 # Record the logout by some user in utmp
3618 sub write_logout_utmp
3621 # Write utmp record for logout
3622 %utmp = ( 'ut_host' => $_[1],
3623 'ut_time' => time(),
3625 'ut_type' => 8, # dead process
3626 'ut_pid' => $main_process_id,
3627 'ut_line' => $config{'pam'},
3629 if (defined(&User::Utmp::putut)) {
3630 User::Utmp::putut(\%utmp);
3633 User::Utmp::pututline(\%utmp);
3638 # pam_conversation_process(username, write-pipe, read-pipe)
3639 # This function is called inside a sub-process to communicate with PAM. It sends
3640 # questions down one pipe, and reads responses from another
3641 sub pam_conversation_process
3643 local ($user, $writer, $reader) = @_;
3644 $miniserv::pam_conversation_process_writer = $writer;
3645 $miniserv::pam_conversation_process_reader = $reader;
3646 local $convh = new Authen::PAM(
3647 $config{'pam'}, $user, \&miniserv::pam_conversation_process_func);
3648 local $pam_ret = $convh->pam_authenticate();
3649 if ($pam_ret == PAM_SUCCESS()) {
3650 local $acct_ret = $convh->pam_acct_mgmt();
3651 if ($acct_ret == PAM_SUCCESS()) {
3652 $convh->pam_open_session();
3653 print $writer "x2 $user 1 0 0\n";
3655 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3656 $acct_ret == PAM_ACCT_EXPIRED()) {
3657 print $writer "x2 $user 1 1 0\n";
3660 print $writer "x0 Unknown PAM account status $acct_ret\n";
3664 print $writer "x2 $user 0 0 0\n";
3669 # pam_conversation_process_func(type, message, [type, message, ...])
3670 # A pipe that talks to both PAM and the master process
3671 sub pam_conversation_process_func
3674 select($miniserv::pam_conversation_process_writer); $| = 1; select(STDOUT);
3676 local ($type, $msg) = (shift, shift);
3678 local $ok = (print $miniserv::pam_conversation_process_writer "$type $msg\n");
3679 print $miniserv::pam_conversation_process_writer "\n";
3680 local $answer = <$miniserv::pam_conversation_process_reader>;
3681 $answer =~ s/\r|\n//g;
3682 push(@rv, PAM_SUCCESS(), $answer);
3684 push(@rv, PAM_SUCCESS());
3689 # Returns 4 new pipe file handles
3692 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3694 local %taken = ( (map { $_, 1 } @passin),
3695 (map { $_->{'PASSINr'} } values %conversations) );
3696 for($p=0; $taken{"PASSINr$p"}; $p++) { }
3697 $PASSINr = "PASSINr$p";
3698 $PASSINw = "PASSINw$p";
3699 $PASSOUTr = "PASSOUTr$p";
3700 $PASSOUTw = "PASSOUTw$p";
3701 pipe($PASSINr, $PASSINw);
3702 pipe($PASSOUTr, $PASSOUTw);
3703 select($PASSINw); $| = 1;
3704 select($PASSINr); $| = 1;
3705 select($PASSOUTw); $| = 1;
3706 select($PASSOUTw); $| = 1;
3708 return ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3711 # recv_pam_question(&conv, fd)
3712 # Reads one PAM question from the sub-process, and sends it to the HTTP handler.
3713 # Returns 0 if the conversation is over, 1 if not.
3714 sub recv_pam_question
3716 local ($conf, $fh) = @_;
3717 local $pr = $conf->{'PAMOUTr'};
3718 select($pr); $| = 1; select(STDOUT);
3719 local $line = <$pr>;
3720 $line =~ s/\r|\n//g;
3723 $line =~ s/\r|\n//g;
3725 $conf->{'last'} = time();
3728 print $fh "0 PAM conversation error\n";
3732 local ($type, $msg) = split(/\s+/, $line, 2);
3733 if ($type =~ /^x(\d+)/) {
3734 # Pass this status code through
3735 print $fh "$1 $msg\n";
3736 return $1 == 2 || $1 == 0 ? 0 : 1;
3738 elsif ($type == PAM_PROMPT_ECHO_ON()) {
3740 print $fh "1 $msg\n";
3743 elsif ($type == PAM_PROMPT_ECHO_OFF()) {
3745 print $fh "3 $msg\n";
3748 elsif ($type == PAM_ERROR_MSG() || $type == PAM_TEXT_INFO()) {
3749 # A message that does not require a response
3750 print $fh "4 $msg\n";
3755 print $fh "0 Unknown PAM message type $type\n";
3761 # send_pam_answer(&conv, answer)
3762 # Sends a response from the user to the PAM sub-process
3765 local ($conf, $answer) = @_;
3766 local $pw = $conf->{'PAMINw'};
3767 $conf->{'last'} = time();
3768 print $pw "$answer\n";
3771 # end_pam_conversation(&conv)
3772 # Clean up PAM conversation pipes and processes
3773 sub end_pam_conversation
3776 kill('KILL', $conv->{'pid'}) if ($conv->{'pid'});
3777 if ($conv->{'PAMINr'}) {
3778 close($conv->{'PAMINr'});
3779 close($conv->{'PAMOUTr'});
3780 close($conv->{'PAMINw'});
3781 close($conv->{'PAMOUTw'});
3783 delete($conversations{$conv->{'cid'}});
3786 # get_ipkeys(&miniserv)
3787 # Returns a list of IP address to key file mappings from a miniserv.conf entry
3791 foreach $k (keys %{$_[0]}) {
3792 if ($k =~ /^ipkey_(\S+)/) {
3793 local $ipkey = { 'ips' => [ split(/,/, $1) ],
3794 'key' => $_[0]->{$k},
3795 'index' => scalar(@rv) };
3796 $ipkey->{'cert'} = $_[0]->{'ipcert_'.$1};
3803 # create_ssl_context(keyfile, [certfile])
3804 sub create_ssl_context
3806 local ($keyfile, $certfile) = @_;
3808 eval { $ssl_ctx = Net::SSLeay::new_x_ctx() };
3809 $ssl_ctx ||= Net::SSLeay::CTX_new();
3810 $ssl_ctx || die "Failed to create SSL context : $!";
3811 if ($client_certs) {
3812 Net::SSLeay::CTX_load_verify_locations(
3813 $ssl_ctx, $config{'ca'}, "");
3814 Net::SSLeay::CTX_set_verify(
3815 $ssl_ctx, &Net::SSLeay::VERIFY_PEER, \&verify_client);
3817 if ($config{'extracas'}) {
3819 foreach $p (split(/\s+/, $config{'extracas'})) {
3820 Net::SSLeay::CTX_load_verify_locations(
3825 Net::SSLeay::CTX_use_RSAPrivateKey_file(
3827 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL key $keyfile";
3828 Net::SSLeay::CTX_use_certificate_file(
3829 $ssl_ctx, $certfile || $keyfile,
3830 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL cert $certfile";
3835 # ssl_connection_for_ip(socket)
3836 # Returns a new SSL connection object for some socket, or undef if failed
3837 sub ssl_connection_for_ip
3840 local $sn = getsockname($sock);
3842 print STDERR "Failed to get address for socket $sock\n";
3845 local $myip = inet_ntoa((unpack_sockaddr_in($sn))[1]);
3846 local $ssl_ctx = $ssl_contexts{$myip} || $ssl_contexts{"*"};
3847 local $ssl_con = Net::SSLeay::new($ssl_ctx);
3848 if ($config{'ssl_cipher_list'}) {
3849 # Force use of ciphers
3850 eval "Net::SSLeay::set_cipher_list(
3851 \$ssl_con, \$config{'ssl_cipher_list'})";
3853 print STDERR "SSL cipher $config{'ssl_cipher_list'} failed : ",
3859 Net::SSLeay::set_fd($ssl_con, fileno($sock));
3860 if (!Net::SSLeay::accept($ssl_con)) {
3861 print STDERR "Failed to initialize SSL connection\n";
3867 # login_redirect(username, password, host)
3868 # Calls the login redirect script (if configured), which may output a URL to
3869 # re-direct a user to after logging in.
3872 return undef if (!$config{'login_redirect'});
3873 local $quser = quotemeta($_[0]);
3874 local $qpass = quotemeta($_[1]);
3875 local $qhost = quotemeta($_[2]);
3876 local $url = `$config{'login_redirect'} $quser $qpass $qhost`;
3881 # reload_config_file()
3882 # Re-read %config, and call post-config actions
3883 sub reload_config_file
3885 &log_error("Reloading configuration");
3886 %config = &read_config_file($config_file);
3887 &update_vital_config();
3890 &build_config_mappings();
3891 if ($config{'session'}) {
3892 dbmclose(%sessiondb);
3893 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
3897 # read_config_file(file)
3898 # Reads the given config file, and returns a hash of values
3899 sub read_config_file
3902 open(CONF, $_[0]) || die "Failed to open config file $_[0] : $!";
3905 if (/^#/ || !/\S/) { next; }
3907 $name = $1; $val = $2;
3908 $name =~ s/^\s+//g; $name =~ s/\s+$//g;
3909 $val =~ s/^\s+//g; $val =~ s/\s+$//g;
3916 # update_vital_config()
3917 # Updates %config with defaults, and dies if something vital is missing
3918 sub update_vital_config
3920 my %vital = ("port", 80,
3922 "server", "MiniServ/0.01",
3923 "index_docs", "index.html index.htm index.cgi index.php",
3924 "addtype_html", "text/html",
3925 "addtype_txt", "text/plain",
3926 "addtype_gif", "image/gif",
3927 "addtype_jpg", "image/jpeg",
3928 "addtype_jpeg", "image/jpeg",
3929 "realm", "MiniServ",
3930 "session_login", "/session_login.cgi",
3931 "pam_login", "/pam_login.cgi",
3932 "password_form", "/password_form.cgi",
3933 "password_change", "/password_change.cgi",
3937 "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\$",
3939 "expires", 7*24*60*60,
3941 foreach my $v (keys %vital) {
3943 if ($vital{$v} eq "") {
3944 die "Missing config option $v";
3946 $config{$v} = $vital{$v};
3949 if (!$config{'sessiondb'}) {
3950 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3951 $config{'sessiondb'} = "$1/sessiondb";
3953 if (!$config{'errorlog'}) {
3954 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
3955 $config{'errorlog'} = "$1/miniserv.error";
3957 if (!$config{'tempbase'}) {
3958 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3959 $config{'tempbase'} = "$1/cgitemp";
3961 if (!$config{'blockedfile'}) {
3962 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3963 $config{'blockedfile'} = "$1/blocked";
3968 # Fills the %users and %certs hashes from the users file in %config
3977 undef(%lastchanges);
3980 if ($config{'userfile'}) {
3981 open(USERS, $config{'userfile'});
3984 local @user = split(/:/, $_, -1);
3985 $users{$user[0]} = $user[1];
3986 $certs{$user[0]} = $user[3] if ($user[3]);
3987 if ($user[4] =~ /^allow\s+(.*)/) {
3988 $allow{$user[0]} = $config{'alwaysresolve'} ?
3989 [ split(/\s+/, $1) ] :
3990 [ &to_ipaddress(split(/\s+/, $1)) ];
3992 elsif ($user[4] =~ /^deny\s+(.*)/) {
3993 $deny{$user[0]} = $config{'alwaysresolve'} ?
3994 [ split(/\s+/, $1) ] :
3995 [ &to_ipaddress(split(/\s+/, $1)) ];
3997 if ($user[5] =~ /days\s+(\S+)/) {
3998 $allowdays{$user[0]} = [ split(/,/, $1) ];
4000 if ($user[5] =~ /hours\s+(\d+)\.(\d+)-(\d+).(\d+)/) {
4001 $allowhours{$user[0]} = [ $1*60+$2, $3*60+$4 ];
4003 $lastchanges{$user[0]} = $user[6];
4004 $nochange{$user[0]} = $user[9];
4005 $temppass{$user[0]} = $user[10];
4012 # Fills %mime with entries from file in %config and extra settings in %config
4016 if ($config{"mimetypes"} ne "") {
4017 open(MIME, $config{"mimetypes"});
4020 if (/^(\S+)\s+(.*)$/) {
4022 my @exts = split(/\s+/, $2);
4023 foreach my $ext (@exts) {
4024 $mime{$ext} = $type;
4030 foreach my $k (keys %config) {
4031 if ($k !~ /^addtype_(.*)$/) { next; }
4032 $mime{$1} = $config{$k};
4036 # build_config_mappings()
4037 # Build the anonymous access list, IP access list, unauthenticated URLs list,
4038 # redirect mapping and allow and deny lists from %config
4039 sub build_config_mappings
4041 # build anonymous access list
4043 foreach my $a (split(/\s+/, $config{'anonymous'})) {
4044 if ($a =~ /^([^=]+)=(\S+)$/) {
4045 $anonymous{$1} = $2;
4049 # build IP access list
4051 foreach my $a (split(/\s+/, $config{'ipaccess'})) {
4052 if ($a =~ /^([^=]+)=(\S+)$/) {
4057 # build unauthenticated URLs list
4058 @unauth = split(/\s+/, $config{'unauth'});
4060 # build redirect mapping
4062 foreach my $r (split(/\s+/, $config{'redirect'})) {
4063 if ($r =~ /^([^=]+)=(\S+)$/) {
4068 # build prefixes to be stripped
4069 undef(@strip_prefix);
4070 foreach my $r (split(/\s+/, $config{'strip_prefix'})) {
4071 push(@strip_prefix, $r);
4074 # Init allow and deny lists
4075 @deny = split(/\s+/, $config{"deny"});
4076 @deny = &to_ipaddress(@deny) if (!$config{'alwaysresolve'});
4077 @allow = split(/\s+/, $config{"allow"});
4078 @allow = &to_ipaddress(@allow) if (!$config{'alwaysresolve'});
4081 if ($config{'allowusers'}) {
4082 @allowusers = split(/\s+/, $config{'allowusers'});
4084 elsif ($config{'denyusers'}) {
4085 @denyusers = split(/\s+/, $config{'denyusers'});
4088 # Build list of unixauth mappings
4090 foreach my $ua (split(/\s+/, $config{'unixauth'})) {
4091 if ($ua =~ /^(\S+)=(\S+)$/) {
4095 $unixauth{"*"} = $ua;
4099 # Build list of non-session-auth pages
4100 undef(%sessiononly);
4101 foreach my $sp (split(/\s+/, $config{'sessiononly'})) {
4102 $sessiononly{$sp} = 1;
4105 # Build list of logout times
4106 undef(@logouttimes);
4107 foreach my $a (split(/\s+/, $config{'logouttimes'})) {
4108 if ($a =~ /^([^=]+)=(\S+)$/) {
4109 push(@logouttimes, [ $1, $2 ]);
4112 push(@logouttimes, [ undef, $config{'logouttime'} ]);
4114 # Build list of DAV pathss
4116 foreach my $d (split(/\s+/, $config{'davpaths'})) {
4117 push(@davpaths, $d);
4119 @davusers = split(/\s+/, $config{'dav_users'});
4121 # Mobile agent substrings and hostname prefixes
4122 @mobile_agents = split(/\t+/, $config{'mobile_agents'});
4123 @mobile_prefixes = split(/\s+/, $config{'mobile_prefixes'});
4127 if ($config{'debug'}) {
4128 open(DEBUG, ">>$config{'debug'}");
4131 open(DEBUG, ">/dev/null");
4134 # Reset cache of sudo checks
4138 # is_group_member(&uinfo, groupname)
4139 # Returns 1 if some user is a primary or secondary member of a group
4142 local ($uinfo, $group) = @_;
4143 local @ginfo = getgrnam($group);
4144 return 0 if (!@ginfo);
4145 return 1 if ($ginfo[2] == $uinfo->[3]); # primary member
4146 foreach my $m (split(/\s+/, $ginfo[3])) {
4147 return 1 if ($m eq $uinfo->[0]);
4152 # prefix_to_mask(prefix)
4153 # Converts a number like 24 to a mask like 255.255.255.0
4156 return $_[0] >= 24 ? "255.255.255.".(256-(2 ** (32-$_[0]))) :
4157 $_[0] >= 16 ? "255.255.".(256-(2 ** (24-$_[0]))).".0" :
4158 $_[0] >= 8 ? "255.".(256-(2 ** (16-$_[0]))).".0.0" :
4159 (256-(2 ** (8-$_[0]))).".0.0.0";
4162 # get_logout_time(user, session-id)
4163 # Given a username, returns the idle time before he will be logged out
4166 local ($user, $sid) = @_;
4167 if (!defined($logout_time_cache{$user,$sid})) {
4169 foreach my $l (@logouttimes) {
4170 if ($l->[0] =~ /^\@(.*)$/) {
4171 # Check group membership
4172 local @uinfo = getpwnam($user);
4173 if (@uinfo && &is_group_member(\@uinfo, $1)) {
4177 elsif ($l->[0] =~ /^\//) {
4178 # Check file contents
4179 open(FILE, $l->[0]);
4196 if ($l->[0] eq $user) {
4200 last if (defined($time));
4202 $logout_time_cache{$user,$sid} = $time;
4204 return $logout_time_cache{$user,$sid};
4207 # password_crypt(password, salt)
4208 # If the salt looks like MD5 and we have a library for it, perform MD5 hashing
4209 # of a password. Otherwise, do Unix crypt.
4212 local ($pass, $salt) = @_;
4213 if ($salt =~ /^\$1\$/ && $use_md5) {
4214 return &encrypt_md5($pass, $salt);
4217 return &unix_crypt($pass, $salt);
4221 # unix_crypt(password, salt)
4222 # Performs standard Unix hashing for a password
4225 local ($pass, $salt) = @_;
4226 if ($use_perl_crypt) {
4227 return Crypt::UnixCrypt::crypt($pass, $salt);
4230 return crypt($pass, $salt);
4234 # handle_dav_request(davpath)
4235 # Pass a request on to the Net::DAV::Server module
4236 sub handle_dav_request
4239 eval "use Filesys::Virtual::Plain";
4240 eval "use Net::DAV::Server";
4241 eval "use HTTP::Request";
4242 eval "use HTTP::Headers";
4244 if ($Net::DAV::Server::VERSION eq '1.28' && $config{'dav_nolock'}) {
4245 delete $Net::DAV::Server::implemented{lock};
4246 delete $Net::DAV::Server::implemented{unlock};
4249 # Read in request data
4250 if (!$posted_data) {
4251 local $clen = $header{"content-length"};
4252 while(length($posted_data) < $clen) {
4253 $buf = &read_data($clen - length($posted_data));
4254 if (!length($buf)) {
4255 &http_error(500, "Failed to read POST request");
4257 chomp($posted_data);
4258 #$posted_data =~ s/\015$//mg;
4259 $posted_data .= $buf;
4263 # For subsequent logging
4264 open(MINISERVLOG, ">>$config{'logfile'}");
4268 local @u = getpwnam($authuser);
4269 if ($config{'dav_remoteuser'} && !$< && $validated) {
4272 $( = $u[3]; $) = "$u[3] $u[3]";
4273 ($>, $<) = ($u[2], $u[2]);
4275 if ($config{'dav_root'} eq '*') {
4280 &http_error(500, "Unix user $authuser does not exist");
4284 $root ||= $config{'dav_root'};
4287 # Check if this user can use DAV
4289 &users_match(\@u, @davusers) ||
4290 &http_error(500, "You are not allowed to access DAV");
4294 my $filesys = Filesys::Virtual::Plain->new({root_path => $root});
4295 my $webdav = Net::DAV::Server->new();
4296 $webdav->filesys($filesys);
4298 # Make up a request object, and feed to DAV
4299 local $ho = HTTP::Headers->new;
4300 foreach my $h (keys %header) {
4301 next if (lc($h) eq "connection");
4302 $ho->header($h => $header{$h});
4305 $request_uri =~ s/^\Q$path\E//;
4306 $request_uri = "/" if ($request_uri eq "");
4308 my $request = HTTP::Request->new($method, $request_uri, $ho,
4310 if ($config{'dav_debug'}) {
4311 print STDERR "DAV request :\n";
4312 print STDERR "---------------------------------------------\n";
4313 print STDERR $request->as_string();
4314 print STDERR "---------------------------------------------\n";
4316 my $response = $webdav->run($request);
4318 # Send back the reply
4319 &write_data("HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n");
4320 local $content = $response->content();
4322 $content =~ s|href>/(.+)<|href>$path/$1<|g;
4323 $content =~ s|href>/<|href>$path<|g;
4325 foreach my $h ($response->header_field_names) {
4326 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4327 &write_data("$h: ",$response->header($h),"\r\n");
4329 &write_data("Content-length: ",length($content),"\r\n");
4330 local $rv = &write_keep_alive(0);
4331 &write_data("\r\n");
4332 &write_data($content);
4334 if ($config{'dav_debug'}) {
4335 print STDERR "DAV reply :\n";
4336 print STDERR "---------------------------------------------\n";
4337 print STDERR "HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n";
4338 foreach my $h ($response->header_field_names) {
4339 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4340 print STDERR "$h: ",$response->header($h),"\r\n";
4342 print STDERR "Content-length: ",length($content),"\r\n";
4343 print STDERR "\r\n";
4344 print STDERR $content;
4345 print STDERR "---------------------------------------------\n";
4349 &log_request($acpthost, $authuser, $reqline, $response->code(),
4350 length($response->content()));
4353 # get_system_hostname()
4354 # Returns the hostname of this system, for reporting to listeners
4355 sub get_system_hostname
4357 # On Windows, try computername environment variable
4358 return $ENV{'computername'} if ($ENV{'computername'});
4359 return $ENV{'COMPUTERNAME'} if ($ENV{'COMPUTERNAME'});
4361 # If a specific command is set, use it first
4362 if ($config{'hostname_command'}) {
4363 local $out = `($config{'hostname_command'}) 2>&1`;
4370 # First try the hostname command
4371 local $out = `hostname 2>&1`;
4372 if (!$? && $out =~ /\S/) {
4377 # Try the Sys::Hostname module
4378 eval "use Sys::Hostname";
4380 local $rv = eval "hostname()";
4386 # Must use net name on Windows
4387 local $out = `net name 2>&1`;
4388 if ($out =~ /\-+\r?\n(\S+)/) {
4395 # indexof(string, array)
4396 # Returns the index of some value in an array, or -1
4399 for($i=1; $i <= $#_; $i++) {
4400 if ($_[$i] eq $_[0]) { return $i - 1; }
4406 # has_command(command)
4407 # Returns the full path if some command is in the path, undef if not
4411 if (!$_[0]) { return undef; }
4412 if (exists($has_command_cache{$_[0]})) {
4413 return $has_command_cache{$_[0]};
4416 if ($_[0] =~ /^\//) {
4417 $rv = -x $_[0] ? $_[0] : undef;
4420 local $sp = $on_windows ? ';' : ':';
4421 foreach $d (split($sp, $ENV{PATH})) {
4422 if (-x "$d/$_[0]") {
4427 foreach my $sfx (".exe", ".com", ".bat") {
4428 if (-r "$d/$_[0]".$sfx) {
4429 $rv = "$d/$_[0]".$sfx;
4436 $has_command_cache{$_[0]} = $rv;
4440 # check_sudo_permissions(user, pass)
4441 # Returns 1 if some user can run any command via sudo
4442 sub check_sudo_permissions
4444 local ($user, $pass) = @_;
4446 # First try the pipes
4448 print DEBUG "check_sudo_permissions: querying cache for $user\n";
4449 print $PASSINw "readsudo $user\n";
4450 local $can = <$PASSOUTr>;
4452 print DEBUG "check_sudo_permissions: cache said $can\n";
4453 if ($can =~ /^\d+$/ && $can != 2) {
4458 local $ptyfh = new IO::Pty;
4459 print DEBUG "check_sudo_permissions: ptyfh=$ptyfh\n";
4461 print STDERR "Failed to create new PTY with IO::Pty\n";
4464 local @uinfo = getpwnam($user);
4466 print STDERR "Unix user $user does not exist for sudo\n";
4470 # Execute sudo in a sub-process, via a pty
4471 local $ttyfh = $ptyfh->slave();
4472 print DEBUG "check_sudo_permissions: ttyfh=$ttyfh\n";
4473 local $tty = $ptyfh->ttyname();
4474 print DEBUG "check_sudo_permissions: tty=$tty\n";
4475 chown($uinfo[2], $uinfo[3], $tty);
4477 print DEBUG "check_sudo_permissions: about to fork..\n";
4478 local $pid = fork();
4479 print DEBUG "check_sudo_permissions: fork=$pid pid=$$\n";
4481 print STDERR "fork for sudo failed : $!\n";
4486 $ptyfh->make_slave_controlling_terminal();
4487 close(STDIN); close(STDOUT); close(STDERR);
4488 untie(*STDIN); untie(*STDOUT); untie(*STDERR);
4489 close($PASSINw); close($PASSOUTr);
4490 $( = $uinfo[3]; $) = "$uinfo[3] $uinfo[3]";
4491 ($>, $<) = ($uinfo[2], $uinfo[2]);
4496 open(STDIN, "<&SUDOr");
4497 open(STDOUT, ">$tty");
4498 open(STDERR, ">&STDOUT");
4501 print "Exec failed : $!\n";
4504 print DEBUG "check_sudo_permissions: pid=$pid\n";
4506 $ptyfh->close_slave();
4508 # Send password, and get back response
4509 local $oldfh = select(SUDOw);
4512 print DEBUG "check_sudo_permissions: about to send pass\n";
4513 local $SIG{'PIPE'} = 'ignore'; # Sometimes sudo doesn't ask for a password
4514 print SUDOw $pass,"\n";
4515 print DEBUG "check_sudo_permissions: sent pass=$pass\n";
4519 print DEBUG "check_sudo_permissions: got $_";
4525 local ($ok) = ($out =~ /\(ALL\)\s+ALL/ ? 1 : 0);
4529 print $PASSINw "writesudo $user $ok\n";
4535 # is_mobile_useragent(agent)
4536 # Returns 1 if some user agent looks like a cellphone or other mobile device,
4538 sub is_mobile_useragent
4540 local ($agent) = @_;
4542 "UP.Link", # Openwave
4543 "Nokia", # All Nokias start with Nokia
4544 "MOT-", # All Motorola phones start with MOT-
4545 "SAMSUNG", # Samsung browsers
4546 "Samsung", # Samsung browsers
4547 "SEC-", # Samsung browsers
4548 "AU-MIC", # Samsung browsers
4549 "AUDIOVOX", # Audiovox
4550 "BlackBerry", # BlackBerry
4551 "hiptop", # Danger hiptop Sidekick
4552 "SonyEricsson", # Sony Ericsson
4553 "Ericsson", # Old Ericsson browsers , mostly WAP
4554 "Mitsu/1.1.A", # Mitsubishi phones
4555 "Panasonic WAP", # Panasonic old WAP phones
4556 "DoCoMo", # DoCoMo phones
4557 "Lynx", # Lynx text-mode linux browser
4558 "Links", # Another text-mode linux browser
4560 local @substrings = (
4561 "UP.Browser", # Openwave
4562 "MobilePhone", # NetFront
4563 "AU-MIC-A700", # Samsung A700 Obigo browsers
4564 "Danger hiptop", # Danger Sidekick hiptop
4565 "Windows CE", # Windows CE Pocket PC
4566 "IEMobile", # Windows mobile browser
4567 "Blazer", # Palm Treo Blazer
4568 "BlackBerry", # BlackBerries can emulate other browsers, but
4569 # they still keep this string in the UserAgent
4570 "SymbianOS", # New Series60 browser has safari in it and
4571 # SymbianOS is the only distinguishing string
4572 "iPhone", # Apple iPhone KHTML browser
4573 "iPod", # iPod touch browser
4574 "MobileSafari", # HTTP client in iPhone
4576 "Opera Mini", # Opera Mini
4577 "HTC_P3700", # HTC mobile device
4579 foreach my $p (@prefixes) {
4580 return 1 if ($agent =~ /^\Q$p\E/);
4582 foreach my $s (@substrings, @mobile_agents) {
4583 return 1 if ($agent =~ /\Q$s\E/);
4588 # write_blocked_file()
4589 # Writes out a text file of blocked hosts and users
4590 sub write_blocked_file
4592 open(BLOCKED, ">$config{'blockedfile'}");
4593 foreach my $d (grep { $hostfail{$_} } @deny) {
4594 print BLOCKED "host $d $hostfail{$d} $blockhosttime{$d}\n";
4596 foreach my $d (grep { $userfail{$_} } @denyusers) {
4597 print BLOCKED "user $d $userfail{$d} $blockusertime{$d}\n";
4600 chmod(0700, $config{'blockedfile'});
4605 open(PIDFILE, ">$config{'pidfile'}");
4606 printf PIDFILE "%d\n", getpid();
4610 # lock_user_password(user)
4611 # Updates a user's password file entry to lock it, both in memory and on disk.
4612 # Returns 1 if done, -1 if no such user, 0 if already locked
4613 sub lock_user_password
4616 if ($users{$user}) {
4617 if ($users{$user} !~ /^\!/) {
4619 $users{$user} = "!".$users{$user};
4620 open(USERS, $config{'userfile'});
4621 local @ufile = <USERS>;
4623 foreach my $u (@ufile) {
4624 local @uinfo = split(/:/, $u);
4625 if ($uinfo[0] eq $user) {
4626 $uinfo[1] = $users{$user};
4628 $u = join(":", @uinfo);
4630 open(USERS, ">$config{'userfile'}");
4640 # hash_session_id(sid)
4641 # Returns an MD5 or Unix-crypted session ID
4645 if (!$hash_session_id_cache{$sid}) {
4648 $hash_session_id_cache{$sid} = &encrypt_md5($sid);
4652 $hash_session_id_cache{$sid} = &unix_crypt($sid, "XX");
4655 return $hash_session_id_cache{$sid};
4658 # encrypt_md5(string, [salt])
4659 # Returns a string encrypted in MD5 format
4662 local ($passwd, $salt) = @_;
4663 local $magic = '$1$';
4664 if ($salt =~ /^\$1\$([^\$]+)/) {
4665 # Extract actual salt from already encrypted password
4670 local $ctx = eval "new $use_md5";
4677 # Add some more stuff from the hash of the password and salt
4678 local $ctx1 = eval "new $use_md5";
4679 $ctx1->add($passwd);
4683 $ctx1->add($passwd);
4684 local $final = $ctx1->digest();
4685 for($pl=length($passwd); $pl>0; $pl-=16) {
4686 $ctx->add($pl > 16 ? $final : substr($final, 0, $pl));
4689 # This piece of code seems rather pointless, but it's in the C code that
4690 # does MD5 in PAM so it has to go in!
4693 for($i=length($passwd); $i; $i >>= 1) {
4698 $ctx->add(substr($passwd, $j, 1));
4701 $final = $ctx->digest();
4704 # This loop exists only to waste time
4705 for($i=0; $i<1000; $i++) {
4706 $ctx1 = eval "new $use_md5";
4707 $ctx1->add($i & 1 ? $passwd : $final);
4708 $ctx1->add($salt) if ($i % 3);
4709 $ctx1->add($passwd) if ($i % 7);
4710 $ctx1->add($i & 1 ? $final : $passwd);
4711 $final = $ctx1->digest();
4715 # Convert the 16-byte final string into a readable form
4717 local @final = map { ord($_) } split(//, $final);
4718 $l = ($final[ 0]<<16) + ($final[ 6]<<8) + $final[12];
4719 $rv .= &to64($l, 4);
4720 $l = ($final[ 1]<<16) + ($final[ 7]<<8) + $final[13];
4721 $rv .= &to64($l, 4);
4722 $l = ($final[ 2]<<16) + ($final[ 8]<<8) + $final[14];
4723 $rv .= &to64($l, 4);
4724 $l = ($final[ 3]<<16) + ($final[ 9]<<8) + $final[15];
4725 $rv .= &to64($l, 4);
4726 $l = ($final[ 4]<<16) + ($final[10]<<8) + $final[ 5];
4727 $rv .= &to64($l, 4);
4729 $rv .= &to64($l, 2);
4731 # Add salt if needed
4733 return $magic.$salt.'$'.$rv;
4742 local ($v, $n) = @_;
4745 $r .= $itoa64[$v & 0x3f];