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!";
128 # Check if the User::Utmp perl module is installed
129 if ($config{'utmp'}) {
130 eval "use User::Utmp;";
133 $utmp_msg = "UTMP logging enabled";
136 $utmp_msg = "Perl module User::Utmp needed for Utmp logging is not installed : $@";
140 # See if the crypt function fails
141 eval "crypt('foo', 'xx')";
143 eval "use Crypt::UnixCrypt";
146 $crypt_msg = "Using Crypt::UnixCrypt for password encryption\n";
149 $crypt_msg = "crypt() function un-implemented, and Crypt::UnixCrypt not installed - password authentication will probably fail\n";
153 # Check if /dev/urandom really generates random IDs, by calling it twice
154 local $rand1 = &generate_random_id("foo", 1);
155 local $rand2 = &generate_random_id("foo", 2);
157 if ($rand1 eq $rand2) {
159 $rand_msg = "Random number generator file /dev/urandom is not reliable";
162 # Check if we can call sudo
163 if ($config{'sudo'} && &has_command("sudo")) {
169 $sudo_msg = "Perl module IO::Pty needed for calling sudo is not installed : $@";
173 # init days and months for http_date
174 @weekday = ( "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" );
175 @month = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun",
176 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" );
178 # Change dir to the server root
179 @roots = ( $config{'root'} );
180 for($i=0; defined($config{"extraroot_$i"}); $i++) {
181 push(@roots, $config{"extraroot_$i"});
184 eval { $user_homedir = (getpwuid($<))[7]; };
186 # getpwuid doesn't work on windows
187 $user_homedir = $ENV{"HOME"} || $ENV{"USERPROFILE"} || "/";
194 # Setup SSL if possible and if requested
195 if (!-r $config{'keyfile'} ||
196 $config{'certfile'} && !-r $config{'certfile'}) {
197 # Key file doesn't exist!
200 @ipkeys = &get_ipkeys(\%config);
202 if ($config{'ssl_version'}) {
203 # Force an SSL version
204 $Net::SSLeay::version = $config{'ssl_version'};
205 $Net::SSLeay::ssl_version = $config{'ssl_version'};
207 $client_certs = 0 if (!-r $config{'ca'} || !%certs);
208 $ssl_contexts{"*"} = &create_ssl_context($config{'keyfile'},
209 $config{'certfile'});
210 foreach $ipkey (@ipkeys) {
211 $ctx = &create_ssl_context($ipkey->{'key'}, $ipkey->{'cert'});
212 foreach $ip (@{$ipkey->{'ips'}}) {
213 $ssl_contexts{$ip} = $ctx;
218 # Setup syslog support if possible and if requested
220 open(ERRDUP, ">&STDERR");
221 open(STDERR, ">/dev/null");
222 $log_socket = $config{"logsock"} || "unix";
223 eval 'openlog($config{"pam"}, "cons,pid,ndelay", "authpriv"); setlogsock($log_socket)';
228 local $msg = ucfirst($config{'pam'})." starting";
229 eval { syslog("info", "%s", $msg); };
233 syslog("info", "%s", $msg);
236 # All attempts to use syslog have failed..
241 open(STDERR, ">&ERRDUP");
245 # Read MIME types file and add extra types
249 if ($config{'log'}) {
250 local(@gmt, @lct, $days, $hours, $mins);
251 @gmt = gmtime(time());
252 @lct = localtime(time());
253 $days = $lct[3] - $gmt[3];
254 $hours = ($days < -1 ? 24 : 1 < $days ? -24 : $days * 24) +
256 $mins = $hours * 60 + $lct[1] - $gmt[1];
257 $timezone = ($mins < 0 ? "-" : "+"); $mins = abs($mins);
258 $timezone .= sprintf "%2.2d%2.2d", $mins/60, $mins%60;
261 # Build various maps from the config files
262 &build_config_mappings();
264 # start up external authentication program, if needed
265 if ($config{'extauth'}) {
266 socketpair(EXTAUTH, EXTAUTH2, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
267 if (!($extauth = fork())) {
271 open(STDIN, "<&EXTAUTH2");
272 open(STDOUT, ">&EXTAUTH2");
273 exec($config{'extauth'}) or die "exec failed : $!\n";
276 local $os = select(EXTAUTH);
280 # Pre-load any libraries
281 foreach $pl (split(/\s+/, $config{'preload'})) {
282 ($pkg, $lib) = split(/=/, $pl);
283 $pkg =~ s/[^A-Za-z0-9]/_/g;
284 eval "package $pkg; do '$config{'root'}/$lib'";
286 print STDERR "Failed to pre-load $pkg/$lib : $@\n";
289 print STDERR "Pre-loading $pkg/$lib\n";
293 # Open debug log if set
294 if ($config{'debuglog'}) {
295 open(DEBUG, ">>$config{'debuglog'}");
296 chmod(0700, $config{'debuglog'});
297 select(DEBUG); $| = 1; select(STDOUT);
298 print DEBUG "miniserv.pl starting ..\n";
301 # Write out (empty) blocked hosts file
302 &write_blocked_file();
304 # Re-direct STDERR to a log file
305 if ($config{'errorlog'} ne '-') {
306 open(STDERR, ">>$config{'errorlog'}") || die "failed to open $config{'errorlog'} : $!";
307 if ($config{'logperms'}) {
308 chmod(oct($config{'logperms'}), $config{'errorlog'});
311 select(STDERR); $| = 1; select(STDOUT);
313 if ($config{'inetd'}) {
314 # We are being run from inetd - go direct to handling the request
315 $SIG{'HUP'} = 'IGNORE';
316 $SIG{'TERM'} = 'DEFAULT';
317 $SIG{'PIPE'} = 'DEFAULT';
318 open(SOCK, "+>&STDIN");
320 # Check if it is time for the logfile to be cleared
321 if ($config{'logclear'}) {
322 local $write_logtime = 0;
323 local @st = stat("$config{'logfile'}.time");
325 if ($st[9]+$config{'logtime'}*60*60 < time()){
328 unlink($config{'logfile'});
331 else { $write_logtime = 1; }
332 if ($write_logtime) {
333 open(LOGTIME, ">$config{'logfile'}.time");
334 print LOGTIME time(),"\n";
339 # Initialize SSL for this connection
341 $ssl_con = &ssl_connection_for_ip(SOCK);
345 # Work out the hostname for this web server
346 $host = &get_socket_name(SOCK);
348 $port = $config{'port'};
349 $acptaddr = getpeername(SOCK);
352 print DEBUG "main: Starting handle_request loop pid=$$\n";
353 while(&handle_request($acptaddr, getsockname(SOCK))) { }
354 print DEBUG "main: Done handle_request loop pid=$$\n";
359 # Build list of sockets to listen on
360 if ($config{"bind"} && $config{"bind"} ne "*") {
361 push(@sockets, [ inet_aton($config{'bind'}), $config{'port'} ]);
364 push(@sockets, [ INADDR_ANY, $config{'port'} ]);
366 foreach $s (split(/\s+/, $config{'sockets'})) {
367 if ($s =~ /^(\d+)$/) {
368 # Just listen on another port on the main IP
369 push(@sockets, [ $sockets[0]->[0], $s ]);
371 elsif ($s =~ /^(\S+):(\d+)$/) {
372 # Listen on a specific port and IP
373 push(@sockets, [ $1 eq "*" ? INADDR_ANY : inet_aton($1), $2 ]);
375 elsif ($s =~ /^([0-9\.]+):\*$/ || $s =~ /^([0-9\.]+)$/) {
376 # Listen on the main port on another IP
377 push(@sockets, [ inet_aton($1), $sockets[0]->[1] ]);
381 # Open all the sockets
382 $proto = getprotobyname('tcp');
384 $tried_inaddr_any = 0;
385 for($i=0; $i<@sockets; $i++) {
387 socket($fh, PF_INET, SOCK_STREAM, $proto) ||
388 die "Failed to open socket : $!";
389 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
390 for($j=0; $j<5; $j++) {
391 last if (bind($fh, pack_sockaddr_in($sockets[$i]->[1],
392 $sockets[$i]->[0])));
396 # All attempts failed .. give up
397 if ($sockets[$i]->[0] eq INADDR_ANY) {
398 push(@sockerrs, "Failed to bind to port $sockets[$i]->[1] : $!");
399 $tried_inaddr_any = 1;
402 $ip = inet_ntoa($sockets[$i]->[0]);
403 push(@sockerrs, "Failed to bind to IP $ip port $sockets[$i]->[1] : $!");
407 listen($fh, SOMAXCONN);
408 push(@socketfhs, $fh);
411 foreach $se (@sockerrs) {
412 print STDERR $se,"\n";
415 # If all binds failed, try binding to any address
416 if (!@socketfhs && !$tried_inaddr_any) {
417 print STDERR "Falling back to listening on any address\n";
419 socket($fh, PF_INET, SOCK_STREAM, $proto) ||
420 die "Failed to open socket : $!";
421 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
422 bind($fh, pack_sockaddr_in($sockets[0]->[1], INADDR_ANY)) ||
423 die "Failed to bind to port $sockets[0]->[1] : $!";
424 listen($fh, SOMAXCONN);
425 push(@socketfhs, $fh);
427 elsif (!@socketfhs && $tried_inaddr_any) {
428 die "Could not listen on any ports";
431 if ($config{'listen'}) {
432 # Open the socket that allows other webmin servers to find this one
433 $proto = getprotobyname('udp');
434 if (socket(LISTEN, PF_INET, SOCK_DGRAM, $proto)) {
435 setsockopt(LISTEN, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
436 bind(LISTEN, pack_sockaddr_in($config{'listen'}, INADDR_ANY));
437 listen(LISTEN, SOMAXCONN);
440 $config{'listen'} = 0;
444 # Split from the controlling terminal, unless configured not to
445 if (!$config{'nofork'}) {
446 if (fork()) { exit; }
448 eval { setsid(); }; # may not work on Windows
450 # Close standard file handles
451 open(STDIN, "</dev/null");
452 open(STDOUT, ">/dev/null");
453 &log_error("miniserv.pl started");
454 &log_error($pam_msg) if ($pam_msg);
455 &log_error($pam_msg2) if ($pam_msg2);
456 &log_error($utmp_msg) if ($utmp_msg);
457 &log_error($crypt_msg) if ($crypt_msg);
458 &log_error($sudo_msg) if ($sudo_msg);
459 &log_error($rand_msg) if ($rand_msg);
461 # write out the PID file
464 # Start the log-clearing process, if needed. This checks every minute
465 # to see if the log has passed its reset time, and if so clears it
466 if ($config{'logclear'}) {
467 if (!($logclearer = fork())) {
468 &close_all_sockets();
471 local $write_logtime = 0;
472 local @st = stat("$config{'logfile'}.time");
474 if ($st[9]+$config{'logtime'}*60*60 < time()){
477 unlink($config{'logfile'});
480 else { $write_logtime = 1; }
481 if ($write_logtime) {
482 open(LOGTIME, ">$config{'logfile'}.time");
483 print LOGTIME time(),"\n";
490 push(@childpids, $logclearer);
493 # Setup the logout time dbm if needed
494 if ($config{'session'}) {
495 eval "use SDBM_File";
496 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
497 eval "\$sessiondb{'1111111111'} = 'foo bar';";
499 dbmclose(%sessiondb);
500 eval "use NDBM_File";
501 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
504 delete($sessiondb{'1111111111'});
509 $SIG{'HUP'} = 'miniserv::trigger_restart';
510 $SIG{'TERM'} = 'miniserv::term_handler';
511 $SIG{'USR1'} = 'miniserv::trigger_reload';
512 $SIG{'PIPE'} = 'IGNORE';
513 local $remove_session_count = 0;
514 $need_pipes = $config{'passdelay'} || $config{'session'};
515 $last_pid_time = time();
517 # wait for a new connection, or a message from a child process
519 if (@childpids <= $config{'maxconns'}) {
520 # Only accept new main socket connects when ready
522 foreach $s (@socketfhs) {
523 vec($rmask, fileno($s), 1) = 1;
527 printf STDERR "too many children (%d > %d)\n",
528 scalar(@childpids), $config{'maxconns'};
531 for($i=0; $i<@passin; $i++) {
532 vec($rmask, fileno($passin[$i]), 1) = 1;
535 vec($rmask, fileno(LISTEN), 1) = 1 if ($config{'listen'});
537 # Wait for a connection
538 local $sel = select($rmask, undef, undef, 10);
540 # Check the flag files
541 if ($config{'restartflag'} && -r $config{'restartflag'}) {
542 print STDERR "restart flag file detected\n";
543 unlink($config{'restartflag'});
546 if ($config{'reloadflag'} && -r $config{'reloadflag'}) {
547 unlink($config{'reloadflag'});
552 # Got a HUP signal while in select() .. restart now
556 # Got a USR1 signal while in select() .. re-read config
558 &reload_config_file();
560 local $time_now = time();
562 # Write the PID every 10 seconds
563 if ($time_now - $last_pid_time > 10) {
565 $last_pid_time = $time_now;
568 # Clean up finished processes
570 do { $pid = waitpid(-1, WNOHANG);
571 @childpids = grep { $_ != $pid } @childpids;
572 } while($pid != 0 && $pid != -1);
574 # run the unblocking procedure to check if enough time has passed to
575 # unblock hosts that heve been blocked because of password failures
577 if ($config{'blockhost_failures'}) {
579 while ($i <= $#deny) {
580 if ($blockhosttime{$deny[$i]} &&
581 $config{'blockhost_time'} != 0 &&
582 ($time_now - $blockhosttime{$deny[$i]}) >=
583 $config{'blockhost_time'}) {
584 # the host can be unblocked now
585 $hostfail{$deny[$i]} = 0;
586 splice(@deny, $i, 1);
593 # Do the same for blocked users
594 if ($config{'blockuser_failures'}) {
596 while ($i <= $#deny) {
597 if ($blockusertime{$deny[$i]} &&
598 $config{'blockuser_time'} != 0 &&
599 ($time_now - $blockusertime{$deny[$i]}) >=
600 $config{'blockuser_time'}) {
601 # the user can be unblocked now
602 $userfail{$deny[$i]} = 0;
603 splice(@denyusers, $i, 1);
610 &write_blocked_file();
613 if ($config{'session'} && (++$remove_session_count%50) == 0) {
614 # Remove sessions with more than 7 days of inactivity,
616 foreach $s (keys %sessiondb) {
617 local ($user, $ltime, $lip) =
618 split(/\s+/, $sessiondb{$s});
619 if ($time_now - $ltime > 7*24*60*60) {
620 &run_logout_script($s, $user);
621 &write_logout_utmp($user, $lip);
622 delete($sessiondb{$s});
625 "Timeout of session for $user");
631 if ($use_pam && $config{'pam_conv'}) {
632 # Remove PAM sessions with more than 5 minutes of inactivity
634 foreach $c (values %conversations) {
635 if ($time_now - $c->{'time'} > 5*60) {
636 &end_pam_conversation($c);
638 syslog("info", "%s", "Timeout of PAM ".
639 "session for $c->{'user'}");
645 # Don't check any sockets if there is no activity
648 # Check if any of the main sockets have received a new connection
650 foreach $s (@socketfhs) {
651 if (vec($rmask, fileno($s), 1)) {
653 $acptaddr = accept(SOCK, $s);
654 if (!$acptaddr) { next; }
655 binmode(SOCK); # turn off any Perl IO stuff
658 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
660 ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw) =
664 # Check username of connecting user
665 local ($peerp, $peera) = unpack_sockaddr_in($acptaddr);
666 $localauth_user = undef;
667 if ($config{'localauth'} && inet_ntoa($peera) eq "127.0.0.1") {
668 if (open(TCP, "/proc/net/tcp")) {
669 # Get the info direct from the kernel
672 local @t = split(/[\s:]+/, $_);
673 if ($t[1] eq '0100007F' &&
674 $t[2] eq sprintf("%4.4X", $peerp)) {
675 $localauth_user = getpwuid($t[11]);
681 if (!$localauth_user) {
682 # Call lsof for the info
683 local $lsofpid = open(LSOF,
684 "$config{'localauth'} -i TCP\@127.0.0.1:$peerp |");
686 if (/^(\S+)\s+(\d+)\s+(\S+)/ &&
687 $2 != $$ && $2 != $lsofpid) {
688 $localauth_user = $3;
695 # Work out the hostname for this web server
696 $host = &get_socket_name(SOCK);
698 print STDERR "Failed to get local socket name : $!\n";
702 $port = $sockets[$sn]->[1];
704 # fork the subprocess
706 if (!($handpid = fork())) {
707 # setup signal handlers
708 $SIG{'TERM'} = 'DEFAULT';
709 $SIG{'PIPE'} = 'DEFAULT';
710 #$SIG{'CHLD'} = 'IGNORE';
711 $SIG{'HUP'} = 'IGNORE';
712 $SIG{'USR1'} = 'IGNORE';
714 # Initialize SSL for this connection
716 $ssl_con = &ssl_connection_for_ip(SOCK);
720 # Close the file handle for the session DBM
721 dbmclose(%sessiondb);
723 # close useless pipes
726 close($PASSINr); close($PASSOUTw);
728 &close_all_sockets();
732 "main: Starting handle_request loop pid=$$\n";
733 while(&handle_request($acptaddr,
734 getsockname(SOCK))) { }
736 "main: Done handle_request loop pid=$$\n";
739 close($PASSINw); close($PASSOUTw);
742 push(@childpids, $handpid);
744 close($PASSINw); close($PASSOUTr);
745 push(@passin, $PASSINr);
746 push(@passout, $PASSOUTw);
753 if ($config{'listen'} && vec($rmask, fileno(LISTEN), 1)) {
754 # Got UDP packet from another webmin server
756 local $from = recv(LISTEN, $rcvbuf, 1024, 0);
758 local $fromip = inet_ntoa((unpack_sockaddr_in($from))[1]);
759 local $toip = inet_ntoa((unpack_sockaddr_in(
760 getsockname(LISTEN)))[1]);
761 if ((!@deny || !&ip_match($fromip, $toip, @deny)) &&
762 (!@allow || &ip_match($fromip, $toip, @allow))) {
763 local $listenhost = &get_socket_name(LISTEN);
764 send(LISTEN, "$listenhost:$config{'port'}:".
765 ($use_ssl || $config{'inetd_ssl'} ? 1 : 0).":".
766 ($config{'listenhost'} ?
767 &get_system_hostname() : ""),
773 # check for session, password-timeout and PAM messages from subprocesses
774 for($i=0; $i<@passin; $i++) {
775 if (vec($rmask, fileno($passin[$i]), 1)) {
776 # this sub-process is asking about a password
777 local $infd = $passin[$i];
778 local $outfd = $passout[$i];
779 #local $inline = <$infd>;
780 local $inline = &sysread_line($infd);
782 print DEBUG "main: inline $inline";
785 print DEBUG "main: inline EOF\n";
787 if ($inline =~ /^delay\s+(\S+)\s+(\S+)\s+(\d+)/) {
788 # Got a delay request from a subprocess.. for
789 # valid logins, there is no delay (to prevent
790 # denial of service attacks), but for invalid
791 # logins the delay increases with each failed
794 # login OK.. no delay
795 print $outfd "0 0\n";
796 $wasblocked = $hostfail{$2} ||
801 &write_blocked_file();
810 # add the host to the block list,
812 if ($config{'blockhost_failures'} &&
814 $config{'blockhost_failures'}) {
816 $blockhosttime{$2} = $time_now;
819 local $logtext = "Security alert: Host $2 blocked after $config{'blockhost_failures'} failed logins for user $1";
825 # add the user to the user block list,
827 if ($config{'blockuser_failures'} &&
829 $config{'blockuser_failures'}) {
830 push(@denyusers, $1);
831 $blockusertime{$1} = $time_now;
834 local $logtext = "Security alert: User $1 blocked after $config{'blockuser_failures'} failed logins";
840 # Lock out the user's password, if enabled
841 if ($config{'blocklock'} &&
843 $config{'blockuser_failures'}) {
844 my $lk = &lock_user_password($1);
847 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";
854 $dl = $userdlay{$1} -
855 int(($time_now - $userlast{$1})/50);
856 $dl = $dl < 0 ? 0 : $dl+1;
857 print $outfd "$dl $blocked\n";
860 # Write out blocked status file
862 &write_blocked_file();
865 $userlast{$1} = $time_now;
867 elsif ($inline =~ /^verify\s+(\S+)\s+(\S+)/) {
868 # Verifying a session ID
869 local $session_id = $1;
870 local $notimeout = $2;
871 local $skey = $sessiondb{$session_id} ?
873 &hash_session_id($session_id);
874 if (!defined($sessiondb{$skey})) {
875 # Session doesn't exist
876 print $outfd "0 0\n";
879 local ($user, $ltime) =
880 split(/\s+/, $sessiondb{$skey});
881 local $lot = &get_logout_time($user, $session_id);
883 $time_now - $ltime > $lot*60 &&
885 # Session has timed out
886 print $outfd "1 ",$time_now - $ltime,"\n";
887 #delete($sessiondb{$skey});
891 print $outfd "2 $user\n";
895 $sessiondb{$skey} = "$user $time_now";
900 elsif ($inline =~ /^new\s+(\S+)\s+(\S+)\s+(\S+)/) {
901 # Creating a new session
902 local $session_id = $1;
905 $sessiondb{&hash_session_id($session_id)} =
906 "$user $time_now $ip";
908 elsif ($inline =~ /^delete\s+(\S+)/) {
909 # Logging out a session
910 local $session_id = $1;
911 local $skey = $sessiondb{$session_id} ?
913 &hash_session_id($session_id);
914 local @sdb = split(/\s+/, $sessiondb{$skey});
915 print $outfd $sdb[0],"\n";
916 delete($sessiondb{$skey});
918 elsif ($inline =~ /^pamstart\s+(\S+)\s+(\S+)\s+(.*)/) {
919 # Starting a new PAM conversation
920 local ($cid, $host, $user) = ($1, $2, $3);
922 # Does this user even need PAM?
923 local ($realuser, $canlogin) =
924 &can_user_login($user, undef, $host);
926 if ($canlogin == 0) {
928 print $outfd "0 Invalid username\n";
930 elsif ($canlogin != 2) {
931 # Not using PAM .. so just ask for
933 $conv = { 'user' => $realuser,
938 print $outfd "3 Password\n";
941 # Start the PAM conversation
942 # sub-process, and get a question
943 $conv = { 'user' => $realuser,
947 local ($PAMINr, $PAMINw, $PAMOUTr,
948 $PAMOUTw) = &allocate_pipes();
949 local $pampid = fork();
951 close($PAMOUTr); close($PAMINw);
952 &pam_conversation_process(
956 close($PAMOUTw); close($PAMINr);
957 $conv->{'pid'} = $pampid;
958 $conv->{'PAMOUTr'} = $PAMOUTr;
959 $conv->{'PAMINw'} = $PAMINw;
960 push(@childpids, $pampid);
962 # Get the first PAM question
963 local $pok = &recv_pam_question(
966 &end_pam_conversation($conv);
970 $conversations{$cid} = $conv if ($conv);
972 elsif ($inline =~ /^pamanswer\s+(\S+)\s+(.*)/) {
973 # A response to a PAM question
974 local ($cid, $answer) = ($1, $2);
975 local $conv = $conversations{$cid};
977 # No such conversation?
978 print $outfd "0 Bad login session\n";
980 elsif ($conv->{'pid'}) {
981 # Send the PAM response and get
983 &send_pam_answer($conv, $answer);
984 local $pok = &recv_pam_question($conv, $outfd);
986 &end_pam_conversation($conv);
990 # This must be the password .. try it
991 # and send back the results
992 local ($vu, $expired, $nonexist) =
993 &validate_user($conv->{'user'},
996 local $ok = $vu ? 1 : 0;
997 print $outfd "2 $conv->{'user'} $ok $expired $notexist\n";
998 &end_pam_conversation($conv);
1001 elsif ($inline =~ /^writesudo\s+(\S+)\s+(\d+)/) {
1002 # Store the fact that some user can sudo to root
1003 local ($user, $ok) = ($1, $2);
1004 $sudocache{$user} = $ok." ".time();
1006 elsif ($inline =~ /^readsudo\s+(\S+)/) {
1007 # Query the user sudo cache (valid for 1 minute)
1009 local ($ok, $last) =
1010 split(/\s+/, $sudocache{$user});
1011 if ($last < time()-60) {
1016 # Tell client OK or not
1017 print $outfd "$ok\n";
1020 elsif ($inline =~ /\S/) {
1021 # Unknown line from pipe?
1022 print DEBUG "main: Unknown line from pipe $inline\n";
1023 print STDERR "Unknown line from pipe $inline\n";
1027 close($infd); close($outfd);
1028 $passin[$i] = $passout[$i] = undef;
1032 @passin = grep { defined($_) } @passin;
1033 @passout = grep { defined($_) } @passout;
1036 # handle_request(remoteaddress, localaddress)
1037 # Where the real work is done
1040 $acptip = inet_ntoa((unpack_sockaddr_in($_[0]))[1]);
1041 $localip = $_[1] ? inet_ntoa((unpack_sockaddr_in($_[1]))[1]) : undef;
1042 print DEBUG "handle_request: from $acptip to $localip\n";
1043 if ($config{'loghost'}) {
1044 $acpthost = gethostbyaddr(inet_aton($acptip), AF_INET);
1045 $acpthost = $acptip if (!$acpthost);
1048 $acpthost = $acptip;
1050 $datestr = &http_date(time());
1052 $ok_message = "Document follows";
1053 $logged_code = undef;
1054 $reqline = $request_uri = $page = undef;
1058 # check address against access list
1059 if (@deny && &ip_match($acptip, $localip, @deny) ||
1060 @allow && !&ip_match($acptip, $localip, @allow)) {
1061 &http_error(403, "Access denied for $acptip");
1066 # Check address with TCP-wrappers
1067 if (!hosts_ctl($config{'pam'}, STRING_UNKNOWN,
1068 $acptip, STRING_UNKNOWN)) {
1069 &http_error(403, "Access denied for $acptip");
1073 print DEBUG "handle_request: passed IP checks\n";
1075 # Compute a timeout for the start of headers, based on the number of
1076 # child processes. As this increases, we use a shorter timeout to avoid
1077 # an attacker overloading the system.
1078 local $header_timeout = 60 + ($config{'maxconns'} - @childpids) * 10;
1080 # Wait at most 60 secs for start of headers for initial requests, or
1081 # 10 minutes for kept-alive connections
1083 vec($rmask, fileno(SOCK), 1) = 1;
1084 local $to = $checked_timeout ? 10*60 : $header_timeout;
1085 local $sel = select($rmask, undef, undef, $to);
1087 if ($checked_timeout) {
1088 print DEBUG "handle_request: exiting due to timeout of $to\n";
1092 &http_error(400, "Timeout",
1093 "Waited for that $to seconds for start of headers");
1097 print DEBUG "handle_request: passed timeout check\n";
1099 # Read the HTTP request and headers
1100 local $origreqline = &read_line();
1101 ($reqline = $origreqline) =~ s/\r|\n//g;
1102 $method = $page = $request_uri = undef;
1103 print DEBUG "handle_request reqline=$reqline\n";
1104 if (!$reqline && (!$use_ssl || $checked_timeout > 1)) {
1105 # An empty request .. just close the connection
1106 print DEBUG "handle_request: rejecting empty request\n";
1109 elsif ($reqline !~ /^(\S+)\s+(.*)\s+HTTP\/1\..$/) {
1110 print DEBUG "handle_request: invalid reqline=$reqline\n";
1112 # This could be an http request when it should be https
1114 local $url = $config{'musthost'} ?
1115 "https://$config{'musthost'}:$port/" :
1116 "https://$host:$port/";
1117 if ($config{'ssl_redirect'}) {
1118 # Just re-direct to the correct URL
1119 sleep(1); # Give browser a change to finish
1120 # sending its request
1121 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1122 &write_data("Date: $datestr\r\n");
1123 &write_data("Server: $config{'server'}\r\n");
1124 &write_data("Location: $url\r\n");
1125 &write_keep_alive(0);
1126 &write_data("\r\n");
1130 # Tell user the correct URL
1131 &http_error(200, "Bad Request", "This web server is running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1134 elsif (ord(substr($reqline, 0, 1)) == 128 && !$use_ssl) {
1135 # This could be an https request when it should be http ..
1136 # need to fake a HTTP response
1139 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
1140 eval "Net::SSLeay::load_error_strings()";
1141 $ssl_ctx = Net::SSLeay::CTX_new();
1142 Net::SSLeay::CTX_use_RSAPrivateKey_file(
1143 $ssl_ctx, $config{'keyfile'},
1144 &Net::SSLeay::FILETYPE_PEM);
1145 Net::SSLeay::CTX_use_certificate_file(
1147 $config{'certfile'} || $config{'keyfile'},
1148 &Net::SSLeay::FILETYPE_PEM);
1149 $ssl_con = Net::SSLeay::new($ssl_ctx);
1153 select(SSLw); $| = 1; select(STDOUT);
1154 print SSLw $origreqline;
1156 while(sysread(SOCK, $buf, 1) > 0) {
1163 Net::SSLeay::set_wfd($ssl_con, fileno(SOCK));
1164 Net::SSLeay::set_rfd($ssl_con, fileno(SSLr));
1165 Net::SSLeay::accept($ssl_con) || die "accept() failed";
1167 local $url = $config{'musthost'} ?
1168 "https://$config{'musthost'}:$port/" :
1169 "https://$host:$port/";
1170 if ($config{'ssl_redirect'}) {
1171 # Just re-direct to the correct URL
1172 sleep(1); # Give browser a change to
1173 # finish sending its request
1174 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1175 &write_data("Date: $datestr\r\n");
1176 &write_data("Server: $config{'server'}\r\n");
1177 &write_data("Location: $url\r\n");
1178 &write_keep_alive(0);
1179 &write_data("\r\n");
1183 # Tell user the correct URL
1184 &http_error(200, "Bad Request", "This web server is not running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1188 &http_error(400, "Bad Request");
1192 &http_error(400, "Bad Request");
1196 $request_uri = $page = $2;
1200 ($headline = &read_line()) =~ s/\r|\n//g;
1201 last if ($headline eq "");
1202 print DEBUG "handle_request: got headline $headline\n";
1203 if ($headline =~ /^(\S+):\s*(.*)$/) {
1204 $header{$lastheader = lc($1)} = $2;
1206 elsif ($headline =~ /^\s+(.*)$/) {
1207 $header{$lastheader} .= $headline;
1210 &http_error(400, "Bad Header $headline");
1213 if (defined($header{'host'})) {
1214 if ($header{'host'} =~ /^([^:]+):([0-9]+)$/) {
1215 ($host, $port) = ($1, $2);
1218 $host = $header{'host'};
1220 if ($config{'musthost'} && $host ne $config{'musthost'}) {
1221 # Disallowed hostname used
1222 &http_error(400, "Invalid HTTP hostname");
1226 if ($page =~ /^([^\?]+)\?(.*)$/) {
1227 # There is some query string information
1230 print DEBUG "handle_request: querystring=$querystring\n";
1231 if ($querystring !~ /=/) {
1232 $queryargs = $querystring;
1233 $queryargs =~ s/\+/ /g;
1234 $queryargs =~ s/%(..)/pack("c",hex($1))/ge;
1238 # Parse query-string parameters
1239 local @in = split(/\&/, $querystring);
1241 local ($k, $v) = split(/=/, $i, 2);
1242 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1243 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1248 $posted_data = undef;
1249 if ($method eq 'POST' &&
1250 $header{'content-type'} eq 'application/x-www-form-urlencoded') {
1251 # Read in posted query string information, up the configured maximum
1252 # post request length
1253 $clen = $header{"content-length"};
1254 $clen_read = $clen > $config{'max_post'} ? $config{'max_post'} : $clen;
1255 while(length($posted_data) < $clen_read) {
1256 $buf = &read_data($clen_read - length($posted_data));
1257 if (!length($buf)) {
1258 &http_error(500, "Failed to read POST request");
1260 chomp($posted_data);
1261 $posted_data =~ s/\015$//mg;
1262 $posted_data .= $buf;
1264 print DEBUG "clen_read=$clen_read clen=$clen posted_data=",length($posted_data),"\n";
1265 if ($clen_read != $clen && length($posted_data) > $clen) {
1266 # If the client sent more data than we asked for, chop the
1268 $posted_data = substr($posted_data, 0, $clen);
1270 if (length($posted_data) > $clen) {
1271 # When the client sent too much, delay so that it gets headers
1274 if ($header{'user-agent'} =~ /MSIE/ &&
1275 $header{'user-agent'} !~ /Opera/i) {
1276 # MSIE includes an extra newline in the data
1277 $posted_data =~ s/\r|\n//g;
1279 local @in = split(/\&/, $posted_data);
1281 local ($k, $v) = split(/=/, $i, 2);
1283 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1284 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1287 print DEBUG "handle_request: posted_data=$posted_data\n";
1290 # replace %XX sequences in page
1291 $page =~ s/%(..)/pack("c",hex($1))/ge;
1293 # Check if the browser's user agent indicates a mobile device
1294 $mobile_device = &is_mobile_useragent($header{'user-agent'});
1296 # Check if Host: header is for a mobile URL
1297 foreach my $m (@mobile_prefixes) {
1298 if ($header{'host'} =~ /^\Q$m\E/i) {
1303 # check for the logout flag file, and if existant deny authentication
1304 if ($config{'logout'} && -r $config{'logout'}.$in{'miniserv_logout_id'}) {
1305 print DEBUG "handle_request: logout flag set\n";
1306 $deny_authentication++;
1307 open(LOGOUT, $config{'logout'}.$in{'miniserv_logout_id'});
1308 chop($count = <LOGOUT>);
1312 open(LOGOUT, ">$config{'logout'}$in{'miniserv_logout_id'}");
1313 print LOGOUT "$count\n";
1317 unlink($config{'logout'}.$in{'miniserv_logout_id'});
1321 # check for any redirect for the requested URL
1322 foreach my $pfx (@strip_prefix) {
1323 my $l = length($pfx);
1324 if(length($page) >= $l &&
1325 substr($page,0,$l) eq $pfx) {
1326 $page=substr($page,$l);
1330 $simple = &simplify_path($page, $bogus);
1332 $rpath .= "&".$querystring if (defined($querystring));
1333 $redir = $redirect{$rpath};
1334 if (defined($redir)) {
1335 print DEBUG "handle_request: redir=$redir\n";
1336 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1337 &write_data("Date: $datestr\r\n");
1338 &write_data("Server: $config{'server'}\r\n");
1339 local $ssl = $use_ssl || $config{'inetd_ssl'};
1340 $portstr = $port == 80 && !$ssl ? "" :
1341 $port == 443 && $ssl ? "" : ":$port";
1342 $prot = $ssl ? "https" : "http";
1343 &write_data("Location: $prot://$host$portstr$redir\r\n");
1344 &write_keep_alive(0);
1345 &write_data("\r\n");
1349 # Check for a DAV request
1351 foreach my $d (@davpaths) {
1352 if ($simple eq $d || $simple =~ /^\Q$d\E\//) {
1357 if (!$davpath && ($method eq "SEARCH" || $method eq "PUT")) {
1358 &http_error(400, "Bad Request method $method");
1361 # Check for password if needed
1363 print DEBUG "handle_request: Need authentication\n";
1367 # Session authentication is never used for connections by
1368 # another webmin server, or for specified pages, or for DAV, or XMLRPC,
1369 # or mobile browsers if requested.
1370 if ($header{'user-agent'} =~ /webmin/i ||
1371 $header{'user-agent'} =~ /$config{'agents_nosession'}/i ||
1372 $sessiononly{$simple} || $davpath ||
1373 $simple eq "/xmlrpc.cgi" ||
1374 $acptip eq $config{'host_nosession'} ||
1375 $mobile_device && $config{'mobile_nosession'}) {
1376 print DEBUG "handle_request: Forcing HTTP authentication\n";
1377 $config{'session'} = 0;
1380 # check for SSL authentication
1381 if ($use_ssl && $verified_client) {
1382 $peername = Net::SSLeay::X509_NAME_oneline(
1383 Net::SSLeay::X509_get_subject_name(
1384 Net::SSLeay::get_peer_certificate(
1386 local $peername2 = $peername;
1387 $peername2 =~ s/Email=/emailAddress=/ ||
1388 $peername2 =~ s/emailAddress=/Email=/;
1389 foreach $u (keys %certs) {
1390 if ($certs{$u} eq $peername ||
1391 $certs{$u} eq $peername2) {
1394 #syslog("info", "%s", "SSL login as $authuser from $acpthost") if ($use_syslog);
1398 if ($use_syslog && !$validated) {
1399 syslog("crit", "%s",
1400 "Unknown SSL certificate $peername");
1404 if (!$validated && !$deny_authentication) {
1405 # check for IP-based authentication
1407 foreach $a (keys %ipaccess) {
1408 if ($acptip eq $a) {
1409 # It does! Auth as the user
1411 $baseauthuser = $authuser =
1417 # Check for normal HTTP authentication
1418 if (!$validated && !$deny_authentication && !$config{'session'} &&
1419 $header{authorization} =~ /^basic\s+(\S+)$/i) {
1420 # authorization given..
1421 ($authuser, $authpass) = split(/:/, &b64decode($1), 2);
1422 print DEBUG "handle_request: doing basic auth check authuser=$authuser authpass=$authpass\n";
1423 local ($vu, $expired, $nonexist) =
1424 &validate_user($authuser, $authpass, $host);
1425 print DEBUG "handle_request: vu=$vu expired=$expired nonexist=$nonexist\n";
1426 if ($vu && (!$expired || $config{'passwd_mode'} == 1)) {
1433 if ($use_syslog && !$validated) {
1434 syslog("crit", "%s",
1435 ($nonexist ? "Non-existent" :
1436 $expired ? "Expired" : "Invalid").
1437 " login as $authuser from $acpthost");
1439 if ($authuser =~ /\r|\n|\s/) {
1440 &http_error(500, "Invalid username",
1441 "Username contains invalid characters");
1443 if ($authpass =~ /\r|\n/) {
1444 &http_error(500, "Invalid password",
1445 "Password contains invalid characters");
1448 if ($config{'passdelay'} && !$config{'inetd'}) {
1449 # check with main process for delay
1450 print DEBUG "handle_request: about to ask for password delay\n";
1451 print $PASSINw "delay $authuser $acptip $validated\n";
1452 <$PASSOUTr> =~ /(\d+) (\d+)/;
1454 print DEBUG "handle_request: password delay $1 $2\n";
1459 # Check for a visit to the special session login page
1460 if ($config{'session'} && !$deny_authentication &&
1461 $page eq $config{'session_login'}) {
1462 if ($in{'logout'} && $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1463 # Logout clicked .. remove the session
1465 print $PASSINw "delete $sid\n";
1466 local $louser = <$PASSOUTr>;
1469 $already_session_id = undef;
1470 $authuser = $baseauthuser = undef;
1473 syslog("info", "%s", "Logout by $louser from $acpthost");
1475 &run_logout_script($louser, $sid,
1477 &write_logout_utmp($louser, $actphost);
1482 if ($in{'user'} =~ /\r|\n|\s/) {
1483 &http_error(500, "Invalid username",
1484 "Username contains invalid characters");
1486 if ($in{'pass'} =~ /\r|\n/) {
1487 &http_error(500, "Invalid password",
1488 "Password contains invalid characters");
1491 local ($vu, $expired, $nonexist) =
1492 &validate_user($in{'user'}, $in{'pass'}, $host);
1493 local $hrv = &handle_login(
1494 $vu || $in{'user'}, $vu ? 1 : 0,
1495 $expired, $nonexist, $in{'pass'},
1496 $in{'notestingcookie'});
1497 return $hrv if (defined($hrv));
1501 # Check for a visit to the special PAM login page
1502 if ($config{'session'} && !$deny_authentication &&
1503 $use_pam && $config{'pam_conv'} && $page eq $config{'pam_login'} &&
1505 # A question has been entered .. submit it to the main process
1506 print DEBUG "handle_request: Got call to $page ($in{'cid'})\n";
1507 print DEBUG "handle_request: For PAM, authuser=$authuser\n";
1508 if ($in{'answer'} =~ /\r|\n/ || $in{'cid'} =~ /\r|\n|\s/) {
1509 &http_error(500, "Invalid response",
1510 "Response contains invalid characters");
1514 # Start of a new conversation - answer must be username
1515 $cid = &generate_random_id($in{'answer'});
1516 print $PASSINw "pamstart $cid $host $in{'answer'}\n";
1519 # A response to a previous question
1521 print $PASSINw "pamanswer $cid $in{'answer'}\n";
1524 # Read back the response, and the next question (if any)
1525 local $line = <$PASSOUTr>;
1526 $line =~ s/\r|\n//g;
1527 local ($rv, $question) = split(/\s+/, $line, 2);
1530 local $hrv = &handle_login(
1531 $in{'answer'} || "unknown", 0, 0, 1, undef);
1532 return $hrv if (defined($hrv));
1534 elsif ($rv == 1 || $rv == 3) {
1535 # Another question .. force use of PAM CGI
1538 $querystring .= "&cid=$cid&question=".
1540 $querystring .= "&password=1" if ($rv == 3);
1542 $page = $config{'pam_login'};
1543 $miniserv_internal = 1;
1547 # Got back a final ok or failure
1548 local ($user, $ok, $expired, $nonexist) =
1549 split(/\s+/, $question);
1550 local $hrv = &handle_login(
1551 $user, $ok, $expired, $nonexist, undef,
1552 $in{'notestingcookie'});
1553 return $hrv if (defined($hrv));
1556 # A message from PAM .. tell the user
1559 $querystring .= "&cid=$cid&message=".
1562 $page = $config{'pam_login'};
1563 $miniserv_internal = 1;
1568 # Check for a visit to the special password change page
1569 if ($config{'session'} && !$deny_authentication &&
1570 $page eq $config{'password_change'} && !$validated) {
1571 # Just let this slide ..
1573 $miniserv_internal = 3;
1576 # Check for an existing session
1577 if ($config{'session'} && !$validated) {
1578 if ($already_session_id) {
1579 $session_id = $already_session_id;
1580 $authuser = $already_authuser;
1583 elsif (!$deny_authentication &&
1584 $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1586 local $notimeout = $in{'webmin_notimeout'} ? 1 : 0;
1587 print $PASSINw "verify $session_id $notimeout\n";
1588 <$PASSOUTr> =~ /(\d+)\s+(\S+)/;
1590 # Valid session continuation
1593 #$already_session_id = $session_id;
1594 $already_authuser = $authuser;
1601 # Invalid session ID .. don't set verified
1606 # Check for local authentication
1607 if ($localauth_user && !$header{'x-forwarded-for'} && !$header{'via'}) {
1608 if (defined($users{$localauth_user})) {
1609 # Local user exists in webmin users file
1611 $authuser = $localauth_user;
1614 # Check if local user is allowed by unixauth
1615 local @can = &can_user_login($localauth_user,
1619 $authuser = $localauth_user;
1622 $localauth_user = undef;
1628 # Check if this path allows anonymous access
1630 foreach $a (keys %anonymous) {
1631 if (substr($simple, 0, length($a)) eq $a) {
1632 # It does! Auth as the user, if IP access
1633 # control allows him.
1634 if (&check_user_ip($anonymous{$a}) &&
1635 &check_user_time($anonymous{$a})) {
1637 $baseauthuser = $authuser =
1645 # Check if this path allows unauthenticated access
1646 local ($u, $unauth);
1647 foreach $u (@unauth) {
1648 $unauth++ if ($simple =~ /$u/);
1650 if (!$bogus && $unauth) {
1651 # Unauthenticated directory or file request - approve it
1653 $baseauthuser = $authuser = undef;
1658 if ($blocked == 0) {
1659 # No password given.. ask
1660 if ($config{'pam_conv'} && $use_pam) {
1661 # Force CGI for PAM question, starting with
1662 # the username which is always needed
1665 $querystring .= "&initial=1&question=".
1666 &urlize("Username");
1667 $querystring .= "&failed=$failed_user" if ($failed_user);
1668 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1670 $page = $config{'pam_login'};
1671 $miniserv_internal = 1;
1674 elsif ($config{'session'}) {
1675 # Force CGI for session login
1678 $querystring .= "&logout=1&page=/";
1681 # Re-direct to current module only
1682 local $rpage = $request_uri;
1683 if (!$config{'loginkeeppage'}) {
1684 $rpage =~ s/\?.*$//;
1685 $rpage =~ s/[^\/]+$//
1687 $querystring = "page=".&urlize($rpage);
1690 $querystring .= "&failed=$failed_user" if ($failed_user);
1691 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1693 $page = $config{'session_login'};
1694 $miniserv_internal = 1;
1698 # Ask for login with HTTP authentication
1699 &write_data("HTTP/1.0 401 Unauthorized\r\n");
1700 &write_data("Date: $datestr\r\n");
1701 &write_data("Server: $config{'server'}\r\n");
1702 &write_data("WWW-authenticate: Basic ".
1703 "realm=\"$config{'realm'}\"\r\n");
1704 &write_keep_alive(0);
1705 &write_data("Content-type: text/html\r\n");
1706 &write_data("\r\n");
1707 &reset_byte_count();
1708 &write_data("<html>\n");
1709 &write_data("<head><title>Unauthorized</title></head>\n");
1710 &write_data("<body><h1>Unauthorized</h1>\n");
1711 &write_data("A password is required to access this\n");
1712 &write_data("web server. Please try again. <p>\n");
1713 &write_data("</body></html>\n");
1714 &log_request($acpthost, undef, $reqline, 401, &byte_count());
1718 elsif ($blocked == 1) {
1719 # when the host has been blocked, give it an error
1720 &http_error(403, "Access denied for $acptip. The host ".
1721 "has been blocked because of too ".
1722 "many authentication failures.");
1724 elsif ($blocked == 2) {
1725 # when the user has been blocked, give it an error
1726 &http_error(403, "Access denied. The user ".
1727 "has been blocked because of too ".
1728 "many authentication failures.");
1732 # Get the real Webmin username
1733 local @can = &can_user_login($authuser, undef, $host);
1734 $baseauthuser = $can[3] || $authuser;
1736 if ($config{'remoteuser'} && !$< && $validated) {
1737 # Switch to the UID of the remote user (if he exists)
1738 local @u = getpwnam($authuser);
1739 if (@u && $< != $u[2]) {
1740 $( = $u[3]; $) = "$u[3] $u[3]";
1741 ($>, $<) = ($u[2], $u[2]);
1744 &http_error(500, "Unix user $authuser does not exist");
1750 # Check per-user IP access control
1751 if (!&check_user_ip($baseauthuser)) {
1752 &http_error(403, "Access denied for $acptip");
1756 # Check per-user allowed times
1757 if (!&check_user_time($baseauthuser)) {
1758 &http_error(403, "Access denied at the current time");
1763 # Validate the path, and convert to canonical form
1765 $simple = &simplify_path($page, $bogus);
1766 print DEBUG "handle_request: page=$page simple=$simple\n";
1768 &http_error(400, "Invalid path");
1771 # Check for a DAV request
1773 return &handle_dav_request($davpath);
1776 # Work out the active theme(s)
1777 local $preroots = $mobile_device && defined($config{'mobile_preroot'}) ?
1778 $config{'mobile_preroot'} :
1779 $authuser && defined($config{'preroot_'.$authuser}) ?
1780 $config{'preroot_'.$authuser} :
1781 $authuser && $baseauthuser &&
1782 defined($config{'preroot_'.$baseauthuser}) ?
1783 $config{'preroot_'.$baseauthuser} :
1785 local @preroots = reverse(split(/\s+/, $preroots));
1787 # Canonicalize the directories
1788 foreach my $preroot (@preroots) {
1789 # Always under the current webmin root
1790 $preroot =~ s/^.*\///g;
1791 $preroot = $roots[0].'/'.$preroot;
1794 # Look in the theme root directories first
1795 local ($full, @stfull);
1797 foreach my $preroot (@preroots) {
1800 $full = $preroot.$sofar;
1801 $scriptname = $simple;
1802 foreach $b (split(/\//, $simple)) {
1803 if ($b ne "") { $sofar .= "/$b"; }
1804 $full = $preroot.$sofar;
1805 @stfull = stat($full);
1806 if (!@stfull) { undef($full); last; }
1808 # Check if this is a directory
1810 # It is.. go on parsing
1818 # Check if this is a CGI program
1819 if (&get_type($full) eq "internal/cgi") {
1820 $pathinfo = substr($simple, length($sofar));
1821 $pathinfo .= "/" if ($page =~ /\/$/);
1822 $scriptname = $sofar;
1827 # Don't stop at a directory unless this is the last theme, which
1828 # is the 'real' one that provides the .cgi scripts
1829 if ($is_directory && $preroot ne $preroots[$#preroots]) {
1836 $cgi_pwd = $roots[0];
1838 elsif ($is_directory) {
1839 $cgi_pwd = "$roots[0]$sofar";
1842 "$roots[0]$sofar" =~ /^(.*\/)[^\/]+$/;
1845 $foundroot = $preroot;
1846 if ($is_directory) {
1847 # Check for index files in the directory
1849 foreach $idx (split(/\s+/, $config{"index_docs"})) {
1850 $idxfull = "$full/$idx";
1851 local @stidxfull = stat($idxfull);
1852 if (-r _ && !-d _) {
1854 @stfull = @stidxfull;
1857 if ($scriptname ne "/");
1862 @stfull = stat($full) if (!$foundidx);
1865 last if ($foundroot);
1867 print DEBUG "handle_request: initial full=$full\n";
1869 # Look in the real root directories, stopping when we find a file or directory
1870 if (!$full || $is_directory) {
1871 ROOT: foreach $root (@roots) {
1873 $full = $root.$sofar;
1874 $scriptname = $simple;
1875 foreach $b ($simple eq "/" ? ( "" ) : split(/\//, $simple)) {
1876 if ($b ne "") { $sofar .= "/$b"; }
1877 $full = $root.$sofar;
1878 @stfull = stat($full);
1883 # Check if this is a directory
1885 # It is.. go on parsing
1889 # Check if this is a CGI program
1890 if (&get_type($full) eq "internal/cgi") {
1891 $pathinfo = substr($simple, length($sofar));
1892 $pathinfo .= "/" if ($page =~ /\/$/);
1893 $scriptname = $sofar;
1898 # Run CGI in the same directory as whatever file
1900 $full =~ /^(.*\/)[^\/]+$/; $cgi_pwd = $1;
1909 if (!@stfull) { &http_error(404, "File not found"); }
1911 print DEBUG "handle_request: full=$full\n";
1912 @stfull = stat($full) if (!@stfull);
1914 # check filename against denyfile regexp
1915 local $denyfile = $config{'denyfile'};
1916 if ($denyfile && $full =~ /$denyfile/) {
1917 &http_error(403, "Access denied to $page");
1921 # Reached the end of the path OK.. see what we've got
1923 # See if the URL ends with a / as it should
1924 print DEBUG "handle_request: found a directory\n";
1925 if ($page !~ /\/$/) {
1926 # It doesn't.. redirect
1927 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1928 $ssl = $use_ssl || $config{'inetd_ssl'};
1929 $portstr = $port == 80 && !$ssl ? "" :
1930 $port == 443 && $ssl ? "" : ":$port";
1931 &write_data("Date: $datestr\r\n");
1932 &write_data("Server: $config{server}\r\n");
1933 $prot = $ssl ? "https" : "http";
1934 &write_data("Location: $prot://$host$portstr$page/\r\n");
1935 &write_keep_alive(0);
1936 &write_data("\r\n");
1937 &log_request($acpthost, $authuser, $reqline, 302, 0);
1940 # A directory.. check for index files
1942 foreach $idx (split(/\s+/, $config{"index_docs"})) {
1943 $idxfull = "$full/$idx";
1944 @stidxfull = stat($idxfull);
1945 if (-r _ && !-d _) {
1948 @stfull = @stidxfull;
1949 $scriptname .= "/" if ($scriptname ne "/");
1954 @stfull = stat($full) if (!$foundidx);
1957 # This is definately a directory.. list it
1958 print DEBUG "handle_request: listing directory\n";
1959 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
1960 "Date: $datestr\r\n".
1961 "Server: $config{server}\r\n".
1962 "Content-type: text/html\r\n";
1964 &write_keep_alive(0);
1965 &write_data("\r\n");
1966 &reset_byte_count();
1967 &write_data("<h1>Index of $simple</h1>\n");
1968 &write_data("<pre>\n");
1969 &write_data(sprintf "%-35.35s %-20.20s %-10.10s\n",
1970 "Name", "Last Modified", "Size");
1971 &write_data("<hr>\n");
1972 opendir(DIR, $full);
1973 while($df = readdir(DIR)) {
1974 if ($df =~ /^\./) { next; }
1975 $fulldf = $full eq "/" ? $full.$df : $full."/".$df;
1976 (@stbuf = stat($fulldf)) || next;
1977 if (-d _) { $df .= "/"; }
1978 @tm = localtime($stbuf[9]);
1979 $fdate = sprintf "%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d",
1980 $tm[3],$tm[4]+1,$tm[5]+1900,
1981 $tm[0],$tm[1],$tm[2];
1982 $len = length($df); $rest = " "x(35-$len);
1984 "<a href=\"%s\">%-${len}.${len}s</a>$rest %-20.20s %-10.10s\n",
1985 $df, $df, $fdate, $stbuf[7]);
1988 &log_request($acpthost, $authuser, $reqline, $ok_code, &byte_count());
1992 # CGI or normal file
1994 if (&get_type($full) eq "internal/cgi" && $validated != 4) {
1995 # A CGI program to execute
1996 print DEBUG "handle_request: executing CGI\n";
1997 $envtz = $ENV{"TZ"};
1998 $envuser = $ENV{"USER"};
1999 $envpath = $ENV{"PATH"};
2000 $envlang = $ENV{"LANG"};
2001 $envroot = $ENV{"SystemRoot"};
2002 foreach my $k (keys %ENV) {
2005 $ENV{"PATH"} = $envpath if ($envpath);
2006 $ENV{"TZ"} = $envtz if ($envtz);
2007 $ENV{"USER"} = $envuser if ($envuser);
2008 $ENV{"OLD_LANG"} = $envlang if ($envlang);
2009 $ENV{"SystemRoot"} = $envroot if ($envroot);
2010 $ENV{"HOME"} = $user_homedir;
2011 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
2012 $ENV{"SERVER_NAME"} = $host;
2013 $ENV{"SERVER_ADMIN"} = $config{"email"};
2014 $ENV{"SERVER_ROOT"} = $roots[0];
2015 $ENV{"SERVER_REALROOT"} = $realroot;
2016 $ENV{"SERVER_PORT"} = $port;
2017 $ENV{"REMOTE_HOST"} = $acpthost;
2018 $ENV{"REMOTE_ADDR"} = $acptip;
2019 $ENV{"REMOTE_USER"} = $authuser;
2020 $ENV{"BASE_REMOTE_USER"} = $authuser ne $baseauthuser ?
2021 $baseauthuser : undef;
2022 $ENV{"REMOTE_PASS"} = $authpass if (defined($authpass) &&
2023 $config{'pass_password'});
2024 print DEBUG "REMOTE_USER = ",$ENV{"REMOTE_USER"},"\n";
2025 print DEBUG "BASE_REMOTE_USER = ",$ENV{"BASE_REMOTE_USER"},"\n";
2026 $ENV{"SSL_USER"} = $peername if ($validated == 2);
2027 $ENV{"ANONYMOUS_USER"} = "1" if ($validated == 3 || $validated == 4);
2028 $ENV{"DOCUMENT_ROOT"} = $roots[0];
2029 $ENV{"DOCUMENT_REALROOT"} = $realroot;
2030 $ENV{"GATEWAY_INTERFACE"} = "CGI/1.1";
2031 $ENV{"SERVER_PROTOCOL"} = "HTTP/1.0";
2032 $ENV{"REQUEST_METHOD"} = $method;
2033 $ENV{"SCRIPT_NAME"} = $scriptname;
2034 $ENV{"SCRIPT_FILENAME"} = $full;
2035 $ENV{"REQUEST_URI"} = $request_uri;
2036 $ENV{"PATH_INFO"} = $pathinfo;
2038 $ENV{"PATH_TRANSLATED"} = "$roots[0]$pathinfo";
2039 $ENV{"PATH_REALTRANSLATED"} = "$realroot$pathinfo";
2041 $ENV{"QUERY_STRING"} = $querystring;
2042 $ENV{"MINISERV_CONFIG"} = $config_file;
2043 $ENV{"HTTPS"} = "ON" if ($use_ssl || $config{'inetd_ssl'});
2044 $ENV{"SESSION_ID"} = $session_id if ($session_id);
2045 $ENV{"LOCAL_USER"} = $localauth_user if ($localauth_user);
2046 $ENV{"MINISERV_INTERNAL"} = $miniserv_internal if ($miniserv_internal);
2047 if (defined($header{"content-length"})) {
2048 $ENV{"CONTENT_LENGTH"} = $header{"content-length"};
2050 if (defined($header{"content-type"})) {
2051 $ENV{"CONTENT_TYPE"} = $header{"content-type"};
2053 foreach $h (keys %header) {
2054 ($hname = $h) =~ tr/a-z/A-Z/;
2056 $ENV{"HTTP_$hname"} = $header{$h};
2058 $ENV{"PWD"} = $cgi_pwd;
2059 foreach $k (keys %config) {
2060 if ($k =~ /^env_(\S+)$/) {
2061 $ENV{$1} = $config{$k};
2064 delete($ENV{'HTTP_AUTHORIZATION'});
2065 $ENV{'HTTP_COOKIE'} =~ s/;?\s*$sidname=([a-f0-9]+)//;
2066 $ENV{'MOBILE_DEVICE'} = 1 if ($mobile_device);
2068 # Check if the CGI can be handled internally
2070 local $first = <CGI>;
2072 $first =~ s/[#!\r\n]//g;
2073 $nph_script = ($full =~ /\/nph-([^\/]+)$/);
2075 if (!$config{'forkcgis'} &&
2076 ($first eq $perl_path || $first eq $linked_perl_path) &&
2078 $config{'internalcgis'}) {
2079 # setup environment for eval
2081 @ARGV = split(/\s+/, $queryargs);
2084 # Already read the post input
2085 $postinput = $posted_data;
2087 $clen = $header{"content-length"};
2088 $SIG{'CHLD'} = 'DEFAULT';
2090 # Have SOCK closed if the perl exec's something
2092 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
2096 if ($config{'log'}) {
2097 open(MINISERVLOG, ">>$config{'logfile'}");
2098 if ($config{'logperms'}) {
2099 chmod(oct($config{'logperms'}),
2100 $config{'logfile'});
2103 chmod(0600, $config{'logfile'});
2107 $main_process_id = $$;
2109 if ($config{'eval_package'}) {
2110 # Eval in package from Webmin module name
2111 if ($full =~ /^\Q$foundroot\E\/([^\/]+)\//) {
2113 $pkg =~ s/[^A-Za-z0-9]/_/g;
2119 tie(*STDOUT, 'miniserv');
2120 tie(*STDIN, 'miniserv');
2121 do \$miniserv::full;
2127 &http_error(500, "Perl execution failed",
2128 $config{'noshowstderr'} ? undef : $@);
2130 elsif (!$doneheaders && !$nph_script) {
2131 &http_error(500, "Missing Headers");
2138 # fork the process that actually executes the CGI
2139 pipe(CGIINr, CGIINw);
2140 pipe(CGIOUTr, CGIOUTw);
2141 pipe(CGIERRr, CGIERRw);
2142 if (!($cgipid = fork())) {
2143 @execargs = ( $full, split(/\s+/, $queryargs) );
2146 open(STDIN, "<&CGIINr");
2147 open(STDOUT, ">&CGIOUTw");
2148 open(STDERR, ">&CGIERRw");
2149 close(CGIINw); close(CGIOUTr); close(CGIERRr);
2151 die "Failed to exec $full : $!\n";
2154 close(CGIINr); close(CGIOUTw); close(CGIERRw);
2157 # write CGI input to a temp file
2158 $infile = "$config{'tempbase'}.$$";
2159 open(CGIINw, ">$infile");
2160 # NOT binary mode, as CGIs don't read in it!
2165 # already read the posted data
2166 print CGIINw $posted_data;
2168 $clen = $header{"content-length"};
2169 if ($method eq "POST" && $clen_read < $clen) {
2170 $SIG{'PIPE'} = 'IGNORE';
2172 while($got < $clen) {
2173 $buf = &read_data($clen-$got);
2174 if (!length($buf)) {
2175 kill('TERM', $cgipid);
2176 unlink($infile) if ($infile);
2177 &http_error(500, "Failed to read ".
2180 $got += length($buf);
2181 local ($wrote) = (print CGIINw $buf);
2184 # If the CGI terminated early, we still need to read
2185 # from the browser and throw away
2186 while($got < $clen) {
2187 $buf = &read_data($clen-$got);
2188 if (!length($buf)) {
2189 kill('TERM', $cgipid);
2190 unlink($infile) if ($infile);
2191 &http_error(500, "Failed to read ".
2194 $got += length($buf);
2196 $SIG{'PIPE'} = 'DEFAULT';
2202 # Run the CGI program, and feed it input
2204 local $qqueryargs = join(" ", map { "\"$_\"" }
2205 split(/\s+/, $queryargs));
2206 if ($first =~ /(perl|perl.exe)$/i) {
2207 # On Windows, run with Perl
2208 open(CGIOUTr, "$perl_path \"$full\" $qqueryargs <$infile |");
2211 open(CGIOUTr, "\"$full\" $qqueryargs <$infile |");
2217 # read back cgi headers
2218 select(CGIOUTr); $|=1; select(STDOUT);
2222 $line =~ s/\r|\n//g;
2224 if ($got_blank || %cgiheader) { last; }
2228 if ($line !~ /^(\S+):\s+(.*)$/) {
2229 $errs = &read_errors(CGIERRr);
2230 close(CGIOUTr); close(CGIERRr);
2231 unlink($infile) if ($infile);
2232 &http_error(500, "Bad Header", $errs);
2234 $cgiheader{lc($1)} = $2;
2235 push(@cgiheader, [ $1, $2 ]);
2237 if ($cgiheader{"location"}) {
2238 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2239 &write_data("Date: $datestr\r\n");
2240 &write_data("Server: $config{'server'}\r\n");
2241 &write_keep_alive(0);
2242 # ignore the rest of the output. This is a hack,
2243 # but is necessary for IE in some cases :(
2244 close(CGIOUTr); close(CGIERRr);
2246 elsif ($cgiheader{"content-type"} eq "") {
2247 close(CGIOUTr); close(CGIERRr);
2248 unlink($infile) if ($infile);
2249 $errs = &read_errors(CGIERRr);
2250 &http_error(500, "Missing Content-Type Header",
2251 $config{'noshowstderr'} ? undef : $errs);
2254 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2255 &write_data("Date: $datestr\r\n");
2256 &write_data("Server: $config{'server'}\r\n");
2257 &write_keep_alive(0);
2259 foreach $h (@cgiheader) {
2260 &write_data("$h->[0]: $h->[1]\r\n");
2262 &write_data("\r\n");
2264 &reset_byte_count();
2265 while($line = <CGIOUTr>) {
2270 unlink($infile) if ($infile);
2276 print DEBUG "handle_request: outputting file\n";
2277 open(FILE, $full) || &http_error(404, "Failed to open file");
2279 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2280 "Date: $datestr\r\n".
2281 "Server: $config{server}\r\n".
2282 "Content-type: ".&get_type($full)."\r\n".
2283 "Content-length: $stfull[7]\r\n".
2284 "Last-Modified: ".&http_date($stfull[9])."\r\n".
2285 "Expires: ".&http_date(time()+$config{'expires'})."\r\n";
2287 $rv = &write_keep_alive();
2288 &write_data("\r\n");
2289 &reset_byte_count();
2290 while(read(FILE, $buf, 1024) > 0) {
2297 &log_request($acpthost, $authuser, $reqline,
2298 $logged_code ? $logged_code :
2299 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2303 # http_error(code, message, body, [dontexit])
2306 local $eh = $error_handler_recurse ? undef :
2307 $config{"error_handler_$_[0]"} ? $config{"error_handler_$_[0]"} :
2308 $config{'error_handler'} ? $config{'error_handler'} : undef;
2309 print DEBUG "http_error code=$_[0] message=$_[1] body=$_[2]\n";
2311 # Call a CGI program for the error
2313 $querystring = "code=$_[0]&message=".&urlize($_[1]).
2314 "&body=".&urlize($_[2]);
2315 $error_handler_recurse++;
2317 $ok_message = $_[1];
2321 # Use the standard error message display
2322 &write_data("HTTP/1.0 $_[0] $_[1]\r\n");
2323 &write_data("Server: $config{server}\r\n");
2324 &write_data("Date: $datestr\r\n");
2325 &write_data("Content-type: text/html\r\n");
2326 &write_keep_alive(0);
2327 &write_data("\r\n");
2328 &reset_byte_count();
2329 &write_data("<h1>Error - $_[1]</h1>\n");
2331 &write_data("<pre>$_[2]</pre>\n");
2334 &log_request($acpthost, $authuser, $reqline, $_[0], &byte_count())
2336 &log_error($_[1], $_[2] ? " : $_[2]" : "");
2343 if ($_[0] =~ /\.([A-z0-9]+)$/) {
2349 return "text/plain";
2352 # simplify_path(path, bogus)
2353 # Given a path, maybe containing stuff like ".." and "." convert it to a
2354 # clean, absolute form.
2357 local($dir, @bits, @fixedbits, $b);
2359 $dir =~ s/\\/\//g; # fix windows \ in path
2362 $dir =~ s/\0//g; # remove null bytes
2363 @bits = split(/\/+/, $dir);
2366 foreach $b (@bits) {
2370 elsif ($b eq ".." || $b eq "...") {
2372 if (scalar(@fixedbits) == 0) {
2380 push(@fixedbits, $b);
2383 return "/" . join('/', @fixedbits);
2387 # Converts a string from base64 format to normal
2390 local($str) = $_[0];
2392 $str =~ tr|A-Za-z0-9+=/||cd;
2394 $str =~ tr|A-Za-z0-9+/| -_|;
2395 while ($str =~ /(.{1,60})/gs) {
2396 my $len = chr(32 + length($1)*3/4);
2397 $res .= unpack("u", $len . $1 );
2402 # ip_match(remoteip, localip, [match]+)
2403 # Checks an IP address against a list of IPs, networks and networks/masks
2406 local(@io, @mo, @ms, $i, $j, $hn, $needhn);
2407 @io = split(/\./, $_[0]);
2408 for($i=2; $i<@_; $i++) {
2409 $needhn++ if ($_[$i] =~ /^\*(\S+)$/);
2411 if ($needhn && !defined($hn = $ip_match_cache{$_[0]})) {
2412 $hn = gethostbyaddr(inet_aton($_[0]), AF_INET);
2413 $hn = "" if (&to_ipaddress($hn) ne $_[0]);
2414 $ip_match_cache{$_[0]} = $hn;
2416 for($i=2; $i<@_; $i++) {
2417 local $mismatch = 0;
2418 if ($_[$i] =~ /^(\S+)\/(\d+)$/) {
2419 # Convert CIDR to netmask format
2420 $_[$i] = $1."/".&prefix_to_mask($2);
2422 if ($_[$i] =~ /^(\S+)\/(\S+)$/) {
2423 # Compare with network/mask
2424 @mo = split(/\./, $1); @ms = split(/\./, $2);
2425 for($j=0; $j<4; $j++) {
2426 if ((int($io[$j]) & int($ms[$j])) != int($mo[$j])) {
2431 elsif ($_[$i] =~ /^\*(\S+)$/) {
2432 # Compare with hostname regexp
2433 $mismatch = 1 if ($hn !~ /$1$/);
2435 elsif ($_[$i] eq 'LOCAL') {
2436 # Compare with local network
2437 local @lo = split(/\./, $_[1]);
2439 $mismatch = 1 if ($lo[0] != $io[0]);
2441 elsif ($lo[0] < 192) {
2442 $mismatch = 1 if ($lo[0] != $io[0] ||
2446 $mismatch = 1 if ($lo[0] != $io[0] ||
2451 elsif ($_[$i] !~ /^[0-9\.]+$/) {
2452 # Compare with hostname
2453 $mismatch = 1 if ($_[0] ne &to_ipaddress($_[$i]));
2456 # Compare with IP or network
2457 @mo = split(/\./, $_[$i]);
2458 while(@mo && !$mo[$#mo]) { pop(@mo); }
2459 for($j=0; $j<@mo; $j++) {
2460 if ($mo[$j] != $io[$j]) {
2465 return 1 if (!$mismatch);
2470 # users_match(&uinfo, user, ...)
2471 # Returns 1 if a user is in a list of users and groups
2474 local $uinfo = shift(@_);
2476 local @ginfo = getgrgid($uinfo->[3]);
2478 if ($u =~ /^\@(\S+)$/) {
2479 return 1 if (&is_group_member($uinfo, $1));
2481 elsif ($u =~ /^(\d*)-(\d*)$/ && ($1 || $2)) {
2482 return (!$1 || $uinfo[2] >= $1) &&
2483 (!$2 || $uinfo[2] <= $2);
2486 return 1 if ($u eq $uinfo->[0]);
2492 # restart_miniserv()
2493 # Called when a SIGHUP is received to restart the web server. This is done
2494 # by exec()ing perl with the same command line as was originally used
2495 sub restart_miniserv
2497 print STDERR "restarting miniserv\n";
2498 &log_error("Restarting");
2500 &close_all_sockets();
2502 dbmclose(%sessiondb);
2503 kill('KILL', $logclearer) if ($logclearer);
2504 kill('KILL', $extauth) if ($extauth);
2505 exec($perl_path, $miniserv_path, @miniserv_argv);
2506 die "Failed to restart miniserv with $perl_path $miniserv_path";
2523 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2524 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/) { push(@rv, $i); }
2525 else { push(@rv, join('.', unpack("CCCC", inet_aton($i)))); }
2527 return wantarray ? @rv : $rv[0];
2530 # read_line(no-wait, no-limit)
2531 # Reads one line from SOCK or SSL
2534 local ($nowait, $nolimit) = @_;
2535 local($idx, $more, $rv);
2536 while(($idx = index($main::read_buffer, "\n")) < 0) {
2537 if (length($main::read_buffer) > 10000 && !$nolimit) {
2538 &http_error(414, "Request too long",
2539 "Received excessive line <pre>$main::read_buffer</pre>");
2542 # need to read more..
2543 &wait_for_data_error() if (!$nowait);
2545 $more = Net::SSLeay::read($ssl_con);
2548 local $ok = sysread(SOCK, $more, 1024);
2549 $more = undef if ($ok <= 0);
2553 $rv = $main::read_buffer;
2554 undef($main::read_buffer);
2557 $main::read_buffer .= $more;
2559 $rv = substr($main::read_buffer, 0, $idx+1);
2560 $main::read_buffer = substr($main::read_buffer, $idx+1);
2565 # Reads up to some amount of data from SOCK or the SSL connection
2569 if (length($main::read_buffer)) {
2570 if (length($main::read_buffer) > $_[0]) {
2571 # Return the first part of the buffer
2572 $rv = substr($main::read_buffer, 0, $_[0]);
2573 $main::read_buffer = substr($main::read_buffer, $_[0]);
2577 # Return the whole buffer
2578 $rv = $main::read_buffer;
2579 undef($main::read_buffer);
2584 # Call SSL read function
2585 return Net::SSLeay::read($ssl_con, $_[0]);
2588 # Just do a normal read
2590 sysread(SOCK, $buf, $_[0]) || return undef;
2596 # Read a line from a file handle, using sysread to get a byte at a time
2603 $got = sysread($fh, $buf, 1);
2604 last if ($got <= 0);
2606 last if ($buf eq "\n");
2611 # wait_for_data(secs)
2612 # Waits at most the given amount of time for some data on SOCK, returning
2613 # 0 if not found, 1 if some arrived.
2617 vec($rmask, fileno(SOCK), 1) = 1;
2618 local $got = select($rmask, undef, undef, $_[0]);
2619 return $got == 0 ? 0 : 1;
2622 # wait_for_data_error()
2623 # Waits 60 seconds for data on SOCK, and fails if none arrives
2624 sub wait_for_data_error
2626 local $got = &wait_for_data(60);
2628 &http_error(400, "Timeout",
2629 "Waited more than 60 seconds for request data");
2633 # write_data(data, ...)
2634 # Writes a string to SOCK or the SSL connection
2637 local $str = join("", @_);
2639 Net::SSLeay::write($ssl_con, $str);
2642 syswrite(SOCK, $str, length($str));
2644 # Intentionally introduce a small delay to avoid problems where IE reports
2645 # the page as empty / DNS failed when it get a large response too quickly!
2646 select(undef, undef, undef, .01) if ($write_data_count%10 == 0);
2647 $write_data_count += length($str);
2650 # reset_byte_count()
2651 sub reset_byte_count { $write_data_count = 0; }
2654 sub byte_count { return $write_data_count; }
2656 # log_request(hostname, user, request, code, bytes)
2659 if ($config{'log'}) {
2660 local ($user, $ident, $headers);
2661 if ($config{'logident'}) {
2662 # add support for rfc1413 identity checking here
2664 else { $ident = "-"; }
2665 $user = $_[1] ? $_[1] : "-";
2666 local $dstr = &make_datestr();
2667 if (fileno(MINISERVLOG)) {
2668 seek(MINISERVLOG, 0, 2);
2671 open(MINISERVLOG, ">>$config{'logfile'}");
2672 chmod(0600, $config{'logfile'});
2674 if (defined($config{'logheaders'})) {
2675 foreach $h (split(/\s+/, $config{'logheaders'})) {
2676 $headers .= " $h=\"$header{$h}\"";
2679 elsif ($config{'logclf'}) {
2680 $headers = " \"$header{'referer'}\" \"$header{'user-agent'}\"";
2685 print MINISERVLOG "$_[0] $ident $user [$dstr] \"$_[2]\" ",
2686 "$_[3] $_[4]$headers\n";
2694 local @tm = localtime(time());
2695 return sprintf "%2.2d/%s/%4.4d:%2.2d:%2.2d:%2.2d %s",
2696 $tm[3], $month[$tm[4]], $tm[5]+1900,
2697 $tm[2], $tm[1], $tm[0], $timezone;
2700 # log_error(message)
2704 print STDERR "[",&make_datestr(),"] ",
2705 $acpthost ? ( "[",$acpthost,"] " ) : ( ),
2706 $page ? ( $page," : " ) : ( ),
2710 # read_errors(handle)
2711 # Read and return all input from some filehandle
2714 local($fh, $_, $rv);
2716 while(<$fh>) { $rv .= $_; }
2720 sub write_keep_alive
2723 if ($config{'nokeepalive'}) {
2724 # Keep alives have been disabled in config
2727 elsif (@childpids > $config{'maxconns'}*.8) {
2728 # Disable because nearing process limit
2732 # Keep alive specified by caller
2736 # Keep alive determined by browser
2737 $mode = $header{'connection'} =~ /keep-alive/i;
2739 &write_data("Connection: ".($mode ? "Keep-Alive" : "close")."\r\n");
2745 kill('TERM', @childpids) if (@childpids);
2746 kill('KILL', $logclearer) if ($logclearer);
2747 kill('KILL', $extauth) if ($extauth);
2753 local @tm = gmtime($_[0]);
2754 return sprintf "%s, %d %s %d %2.2d:%2.2d:%2.2d GMT",
2755 $weekday[$tm[6]], $tm[3], $month[$tm[4]], $tm[5]+1900,
2756 $tm[2], $tm[1], $tm[0];
2761 my $i; bless \$i, shift;
2767 my($buf,$len,$offset) = @_;
2768 &write_to_sock(substr($buf, $offset, $len));
2775 my $buf = join(defined($,) ? $, : "", @_);
2776 $buf .= $\ if defined($\);
2777 &write_to_sock($buf);
2784 &write_to_sock(sprintf $fmt, @_);
2787 # Send back already read data while we have it, then read from SOCK
2791 my $bufref = \$_[0];
2794 if ($postpos < length($postinput)) {
2795 # Reading from already fetched array
2796 my $left = length($postinput) - $postpos;
2797 my $canread = $len > $left ? $left : $len;
2798 substr($$bufref, $offset, $canread) =
2799 substr($postinput, $postpos, $canread);
2800 $postpos += $canread;
2804 # Read from network socket
2805 local $data = &read_data($len);
2806 if ($data eq '' && $len) {
2808 print STDERR "finished reading - shutting down socket\n";
2811 substr($$bufref, $offset, length($data)) = $data;
2812 return length($data);
2818 #print STDERR "open() called - should never happen!\n";
2821 # Read a line of input
2825 if ($postpos < length($postinput) &&
2826 ($idx = index($postinput, "\n", $postpos)) >= 0) {
2827 # A line exists in the memory buffer .. use it
2828 my $line = substr($postinput, $postpos, $idx-$postpos+1);
2833 # Need to read from the socket
2835 if ($postpos < length($postinput)) {
2836 # Start with in-memory data
2837 $line = substr($postinput, $postpos);
2838 $postpos = length($postinput);
2840 my $nl = &read_line(0, 1);
2843 print STDERR "finished reading - shutting down socket\n";
2846 $line .= $nl if (defined($nl));
2851 # Read one character of input
2856 my $got = READ($r, \$buf, 1, 0);
2857 return $got > 0 ? $buf : undef;
2862 return fileno(SOCK);
2869 # write_to_sock(data, ...)
2874 if ($doneheaders || $miniserv::nph_script) {
2879 while(!$doneheaders && $headers =~ s/^([^\r\n]*)(\r)?\n//) {
2880 if ($1 =~ /^(\S+):\s+(.*)$/) {
2881 $cgiheader{lc($1)} = $2;
2882 push(@cgiheader, [ $1, $2 ]);
2884 elsif ($1 !~ /\S/) {
2888 &http_error(500, "Bad Header");
2892 if ($cgiheader{"location"}) {
2894 "HTTP/1.0 302 Moved Temporarily\r\n");
2895 &write_data("Date: $datestr\r\n");
2896 &write_data("Server: $config{server}\r\n");
2897 &write_keep_alive(0);
2899 elsif ($cgiheader{"content-type"} eq "") {
2900 &http_error(500, "Missing Content-Type Header");
2903 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2904 &write_data("Date: $datestr\r\n");
2905 &write_data("Server: $config{server}\r\n");
2906 &write_keep_alive(0);
2908 foreach $h (@cgiheader) {
2909 &write_data("$h->[0]: $h->[1]\r\n");
2911 &write_data("\r\n");
2912 &reset_byte_count();
2913 &write_data($headers);
2921 local $cert = Net::SSLeay::X509_STORE_CTX_get_current_cert($_[1]);
2923 local $errnum = Net::SSLeay::X509_STORE_CTX_get_error($_[1]);
2924 $verified_client = 1 if (!$errnum);
2931 if ($doing_eval && $$ == $main_process_id) {
2932 # A CGI program called exit! This is a horrible hack to
2933 # finish up before really exiting
2936 close($PASSINw); close($PASSOUTw);
2937 &log_request($acpthost, $authuser, $reqline,
2938 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2943 # Convert a string to a form ok for putting in a URL
2945 local($tmp, $tmp2, $c);
2948 while(($c = chop($tmp)) ne "") {
2949 if ($c !~ /[A-z0-9]/) {
2950 $c = sprintf("%%%2.2X", ord($c));
2957 # validate_user(username, password, host)
2958 # Checks if some username and password are valid. Returns the modified username,
2959 # the expired / temp pass flag, and the non-existence flag
2962 local ($user, $pass, $host) = @_;
2963 return ( ) if (!$user);
2964 print DEBUG "validate_user: user=$user pass=$pass host=$host\n";
2965 local ($canuser, $canmode, $notexist, $webminuser, $sudo) =
2966 &can_user_login($user, undef, $host);
2967 print DEBUG "validate_user: canuser=$canuser canmode=$canmode notexist=$notexist webminuser=$webminuser sudo=$sudo\n";
2969 # User doesn't even exist, so go no further
2970 return ( undef, 0, 1 );
2972 elsif ($canmode == 0) {
2973 # User does exist but cannot login
2974 return ( $canuser, 0, 0 );
2976 elsif ($canmode == 1) {
2977 # Attempt Webmin authentication
2978 if ($users{$webminuser} eq
2979 &password_crypt($pass, $users{$webminuser})) {
2980 # Password is valid .. but check for expiry
2981 local $lc = $lastchanges{$user};
2982 if ($config{'pass_maxdays'} && $lc && !$nochange{$user}) {
2983 local $daysold = (time() - $lc)/(24*60*60);
2984 print DEBUG "maxdays=$config{'pass_maxdays'} daysold=$daysold temppass=$temppass{$user}\n";
2985 if ($config{'pass_lockdays'} &&
2986 $daysold > $config{'pass_lockdays'}) {
2987 # So old that the account is locked
2988 return ( undef, 0, 0 );
2990 elsif ($daysold > $config{'pass_maxdays'}) {
2991 # Password has expired
2992 return ( $user, 1, 0 );
2995 if ($temppass{$user}) {
2996 # Temporary password - force change now
2997 return ( $user, 2, 0 );
2999 return ( $user, 0, 0 );
3002 return ( undef, 0, 0 );
3005 elsif ($canmode == 2 || $canmode == 3) {
3006 # Attempt PAM or passwd file authentication
3007 local $val = &validate_unix_user($canuser, $pass);
3008 print DEBUG "validate_user: unix val=$val\n";
3009 if ($val && $sudo) {
3010 # Need to check if this Unix user can sudo
3011 if (!&check_sudo_permissions($canuser, $pass)) {
3012 print DEBUG "validate_user: sudo failed\n";
3016 print DEBUG "validate_user: sudo passed\n";
3019 return $val == 2 ? ( $canuser, 1, 0 ) :
3020 $val == 1 ? ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3022 elsif ($canmode == 4) {
3023 # Attempt external authentication
3024 return &validate_external_user($canuser, $pass) ?
3025 ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3033 # validate_unix_user(user, password)
3034 # Returns 1 if a username and password are valid under unix, 0 if not,
3035 # or 2 if the account has expired.
3036 # Checks PAM if available, and falls back to reading the system password
3038 sub validate_unix_user
3042 $pam_username = $_[0];
3043 $pam_password = $_[1];
3044 local $pamh = new Authen::PAM($config{'pam'}, $pam_username,
3047 local $pam_ret = $pamh->pam_authenticate();
3048 if ($pam_ret == PAM_SUCCESS()) {
3049 # Logged in OK .. make sure password hasn't expired
3050 local $acct_ret = $pamh->pam_acct_mgmt();
3051 if ($acct_ret == PAM_SUCCESS()) {
3052 $pamh->pam_open_session();
3055 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3056 $acct_ret == PAM_ACCT_EXPIRED()) {
3060 print STDERR "Unknown pam_acct_mgmt return value : $acct_ret\n";
3067 elsif ($config{'pam_only'}) {
3068 # Pam is not available, but configuration forces it's use!
3071 elsif ($config{'passwd_file'}) {
3072 # Check in a password file
3074 open(FILE, $config{'passwd_file'});
3075 if ($config{'passwd_file'} eq '/etc/security/passwd') {
3076 # Assume in AIX format
3079 if (/^\s*(\S+):/ && $1 eq $_[0]) {
3081 if (/^\s*password\s*=\s*(\S+)\s*$/) {
3082 $rv = $1 eq &password_crypt($_[1], $1) ?
3090 # Read the system password or shadow file
3092 local @l = split(/:/, $_, -1);
3093 local $u = $l[$config{'passwd_uindex'}];
3094 local $p = $l[$config{'passwd_pindex'}];
3096 $rv = $p eq &password_crypt($_[1], $p) ? 1 : 0;
3097 if ($config{'passwd_cindex'} ne '' && $rv) {
3098 # Password may have expired!
3099 local $c = $l[$config{'passwd_cindex'}];
3100 local $m = $l[$config{'passwd_mindex'}];
3101 local $day = time()/(24*60*60);
3102 if ($c =~ /^\d+/ && $m =~ /^\d+/ &&
3108 if ($p eq "" && $config{'passwd_blank'}) {
3109 # Force password change
3117 return $rv if ($rv);
3120 # Fallback option - check password returned by getpw*
3121 local @uinfo = getpwnam($_[0]);
3122 if ($uinfo[1] ne '' && &password_crypt($_[1], $uinfo[1]) eq $uinfo[1]) {
3126 return 0; # Totally failed
3129 # validate_external_user(user, pass)
3130 # Validate a user by passing the username and password to an external
3131 # squid-style authentication program
3132 sub validate_external_user
3134 return 0 if (!$config{'extauth'});
3136 local $str = "$_[0] $_[1]\n";
3137 syswrite(EXTAUTH, $str, length($str));
3138 local $resp = <EXTAUTH>;
3140 return $resp =~ /^OK/i ? 1 : 0;
3143 # can_user_login(username, no-append, host)
3144 # Checks if a user can login or not.
3145 # First return value is the username.
3146 # Second is 0 if cannot login, 1 if using Webmin pass, 2 if PAM, 3 if password
3147 # file, 4 if external.
3148 # Third is 1 if the user does not exist at all, 0 if he does.
3149 # Fourth is the Webmin username whose permissions apply, based on unixauth.
3150 # Fifth is a flag indicating if a sudo check is needed.
3153 if (!$users{$_[0]}) {
3154 # See if this user exists in Unix and can be validated by the same
3155 # method as the unixauth webmin user
3156 local $realuser = $unixauth{$_[0]};
3160 eval { @uinfo = getpwnam($_[0]); }; # may fail on windows
3161 if (!$realuser && @uinfo) {
3162 # No unixauth entry for the username .. try his groups
3163 foreach my $ua (keys %unixauth) {
3164 if ($ua =~ /^\@(.*)$/) {
3165 if (&is_group_member(\@uinfo, $1)) {
3166 $realuser = $unixauth{$ua};
3172 if (!$realuser && @uinfo) {
3173 # Fall back to unix auth for all Unix users
3174 $realuser = $unixauth{"*"};
3176 if (!$realuser && $use_sudo && @uinfo) {
3177 # Allow login effectively as root, if sudo permits it
3181 if (!$realuser && !@uinfo && $config{'pamany'}) {
3182 # If the user completely doesn't exist, we can still allow
3183 # him to authenticate via PAM
3184 $realuser = $config{'pamany'};
3188 # For Usermin, always fall back to unix auth for any user,
3189 # so that later checks with domain added / removed are done.
3190 $realuser = $unixauth{"*"};
3192 return (undef, 0, 1, undef) if (!$realuser);
3193 local $up = $users{$realuser};
3194 return (undef, 0, 1, undef) if (!defined($up));
3196 # Work out possible domain names from the hostname
3197 local @doms = ( $_[2] );
3198 if ($_[2] =~ /^([^\.]+)\.(\S+)$/) {
3202 if ($config{'user_mapping'} && !defined(%user_mapping)) {
3203 # Read the user mapping file
3205 open(MAPPING, $config{'user_mapping'});
3209 if (/^(\S+)\s+(\S+)/) {
3210 if ($config{'user_mapping_reverse'}) {
3211 $user_mapping{$1} = $2;
3214 $user_mapping{$2} = $1;
3221 # Check the user mapping file to see if there is an entry for the
3222 # user login in which specifies a new effective user
3224 foreach my $d (@doms) {
3225 $um ||= $user_mapping{"$_[0]\@$d"};
3227 $um ||= $user_mapping{$_[0]};
3228 if (defined($um) && ($_[1]&4) == 0) {
3229 # A mapping exists - use it!
3230 return &can_user_login($um, $_[1]+4, $_[2]);
3233 # Check if a user with the entered login and the domains appended
3234 # or prepended exists, and if so take it to be the effective user
3235 if (!@uinfo && $config{'domainuser'}) {
3236 # Try again with name.domain and name.firstpart
3237 local @firsts = map { /^([^\.]+)/; $1 } @doms;
3238 if (($_[1]&1) == 0) {
3240 foreach $a (@firsts, @doms) {
3241 foreach $p ("$_[0].${a}", "$_[0]-${a}",
3242 "${a}.$_[0]", "${a}-$_[0]",
3243 "$_[0]_${a}", "${a}_$_[0]") {
3244 local @vu = &can_user_login(
3245 $p, $_[1]+1, $_[2]);
3246 return @vu if ($vu[1]);
3252 # Check if the user entered a domain at the end of his username when
3253 # he really shouldn't have, and if so try without it
3254 if (!@uinfo && $config{'domainstrip'} &&
3255 $_[0] =~ /^(\S+)\@(\S+)$/ && ($_[1]&2) == 0) {
3256 local ($stripped, $dom) = ($1, $2);
3257 local @vu = &can_user_login($stripped, $_[1] + 2, $_[2]);
3258 return @vu if ($vu[1]);
3259 local @vu = &can_user_login($stripped, $_[1] + 2, $dom);
3260 return @vu if ($vu[1]);
3263 return ( undef, 0, 1, undef ) if (!@uinfo && !$pamany);
3266 if (defined(@allowusers)) {
3267 # Only allow people on the allow list
3268 return ( undef, 0, 0, undef )
3269 if (!&users_match(\@uinfo, @allowusers));
3271 elsif (defined(@denyusers)) {
3272 # Disallow people on the deny list
3273 return ( undef, 0, 0, undef )
3274 if (&users_match(\@uinfo, @denyusers));
3276 if ($config{'shells_deny'}) {
3278 open(SHELLS, $config{'shells_deny'});
3282 $found++ if ($_ eq $uinfo[8]);
3285 return ( undef, 0, 0, undef ) if (!$found);
3290 # PAM or passwd file authentication
3291 return ( $_[0], $use_pam ? 2 : 3, 0, $realuser, $sudo );
3293 elsif ($up eq 'e') {
3294 # External authentication
3295 return ( $_[0], 4, 0, $realuser, $sudo );
3298 # Fixed Webmin password
3299 return ( $_[0], 1, 0, $realuser, $sudo );
3302 elsif ($users{$_[0]} eq 'x') {
3303 # Webmin user authenticated via PAM or password file
3304 return ( $_[0], $use_pam ? 2 : 3, 0, $_[0] );
3306 elsif ($users{$_[0]} eq 'e') {
3307 # Webmin user authenticated externally
3308 return ( $_[0], 4, 0, $_[0] );
3311 # Normal Webmin user
3312 return ( $_[0], 1, 0, $_[0] );
3316 # the PAM conversation function for interactive logins
3319 $pam_conv_func_called++;
3326 $ans = $pam_username if ($code == PAM_PROMPT_ECHO_ON() );
3327 $ans = $pam_password if ($code == PAM_PROMPT_ECHO_OFF() );
3329 push @res, PAM_SUCCESS();
3332 push @res, PAM_SUCCESS();
3341 # get_socket_name(handle)
3342 # Returns the local hostname or IP address of some connection
3345 return $config{'host'} if ($config{'host'});
3346 local $sn = getsockname($_[0]);
3347 return undef if (!$sn);
3348 local $myaddr = (unpack_sockaddr_in($sn))[1];
3349 if (!$get_socket_name_cache{$myaddr}) {
3351 if (!$config{'no_resolv_myname'}) {
3352 $myname = gethostbyaddr($myaddr, AF_INET);
3354 if ($myname eq "") {
3355 $myname = inet_ntoa($myaddr);
3357 $get_socket_name_cache{$myaddr} = $myname;
3359 return $get_socket_name_cache{$myaddr};
3362 # run_login_script(username, sid, remoteip, localip)
3363 sub run_login_script
3365 if ($config{'login_script'}) {
3366 system($config{'login_script'}.
3367 " ".join(" ", map { quotemeta($_) } @_).
3368 " >/dev/null 2>&1 </dev/null");
3372 # run_logout_script(username, sid, remoteip, localip)
3373 sub run_logout_script
3375 if ($config{'logout_script'}) {
3376 system($config{'logout_script'}.
3377 " ".join(" ", map { quotemeta($_) } @_).
3378 " >/dev/null 2>&1 </dev/null");
3382 # close_all_sockets()
3383 # Closes all the main listening sockets
3384 sub close_all_sockets
3387 foreach $s (@socketfhs) {
3393 # Close all pipes for talking to sub-processes
3397 foreach $p (@passin) { close($p); }
3398 foreach $p (@passout) { close($p); }
3399 foreach $p (values %conversations) {
3400 if ($p->{'PAMOUTr'}) {
3401 close($p->{'PAMOUTr'});
3402 close($p->{'PAMINw'});
3407 # check_user_ip(user)
3408 # Returns 1 if some user is allowed to login from the accepting IP, 0 if not
3412 &ip_match($acptip, $localip, @{$deny{$_[0]}}) ||
3414 !&ip_match($acptip, $localip, @{$allow{$_[0]}})) {
3420 # check_user_time(user)
3421 # Returns 1 if some user is allowed to login at the current date and time
3424 return 1 if (!$allowdays{$_[0]} && !$allowhours{$_[0]});
3425 local @tm = localtime(time());
3426 if ($allowdays{$_[0]}) {
3427 # Make sure day is allowed
3428 return 0 if (&indexof($tm[6], @{$allowdays{$_[0]}}) < 0);
3430 if ($allowhours{$_[0]}) {
3431 # Make sure time is allowed
3432 local $m = $tm[2]*60+$tm[1];
3433 return 0 if ($m < $allowhours{$_[0]}->[0] ||
3434 $m > $allowhours{$_[0]}->[1]);
3439 # generate_random_id(password, [force-urandom])
3440 # Returns a random session ID number
3441 sub generate_random_id
3443 local ($pass, $force_urandom) = @_;
3445 if (!$bad_urandom) {
3446 # First try /dev/urandom, unless we have marked it as bad
3447 $SIG{ALRM} = "miniserv::urandom_timeout";
3449 if (open(RANDOM, "/dev/urandom")) {
3451 if (read(RANDOM, $tmpsid, 16) == 16) {
3452 $sid = lc(unpack('h*',$tmpsid));
3458 if (!$sid && !$force_urandom) {
3461 foreach $c (split(//, &unix_crypt($pass, substr($$, -2)))) {
3462 $sid += ord($c) * $mul;
3469 # handle_login(username, ok, expired, not-exists, password, [no-test-cookie])
3470 # Called from handle_session to either mark a user as logged in, or not
3473 local ($vu, $ok, $expired, $nonexist, $pass, $notest) = @_;
3474 $authuser = $vu if ($ok);
3476 # check if the test cookie is set
3477 if ($header{'cookie'} !~ /testing=1/ && $vu &&
3478 !$config{'no_testing_cookie'} && !$notest) {
3479 &http_error(500, "No cookies",
3480 "Your browser does not support cookies, ".
3481 "which are required for this web server to ".
3482 "work in session authentication mode");
3485 # check with main process for delay
3486 if ($config{'passdelay'} && $vu) {
3487 print $PASSINw "delay $vu $acptip $ok\n";
3488 <$PASSOUTr> =~ /(\d+) (\d+)/;
3493 if ($ok && (!$expired ||
3494 $config{'passwd_mode'} == 1)) {
3495 # Logged in OK! Tell the main process about
3497 local $sid = &generate_random_id($pass);
3498 print $PASSINw "new $sid $authuser $acptip\n";
3500 # Run the post-login script, if any
3501 &run_login_script($authuser, $sid,
3504 # Check for a redirect URL for the user
3505 local $rurl = &login_redirect($authuser, $pass, $host);
3507 # Got one .. go to it
3508 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3509 &write_data("Date: $datestr\r\n");
3510 &write_data("Server: $config{'server'}\r\n");
3511 &write_data("Location: $rurl\r\n");
3512 &write_keep_alive(0);
3513 &write_data("\r\n");
3514 &log_request($acpthost, $authuser, $reqline, 302, 0);
3517 # Set cookie and redirect to originally requested page
3518 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3519 &write_data("Date: $datestr\r\n");
3520 &write_data("Server: $config{'server'}\r\n");
3521 local $ssl = $use_ssl || $config{'inetd_ssl'};
3522 $portstr = $port == 80 && !$ssl ? "" :
3523 $port == 443 && $ssl ? "" : ":$port";
3524 $prot = $ssl ? "https" : "http";
3525 local $sec = $ssl ? "; secure" : "";
3526 #$sec .= "; httpOnly";
3528 &write_data("Set-Cookie: $sidname=$sid; path=/; expires=\"Thu, 31-Dec-2037 00:00:00\"$sec\r\n");
3531 &write_data("Set-Cookie: $sidname=$sid; path=/$sec\r\n");
3533 &write_data("Location: $prot://$host$portstr$in{'page'}\r\n");
3534 &write_keep_alive(0);
3535 &write_data("\r\n");
3536 &log_request($acpthost, $authuser, $reqline, 302, 0);
3537 syslog("info", "%s", "Successful login as $authuser from $acpthost") if ($use_syslog);
3538 &write_login_utmp($authuser, $acpthost);
3542 elsif ($ok && $expired &&
3543 ($config{'passwd_mode'} == 2 || $expired == 2)) {
3544 # Login was ok, but password has expired or was temporary. Need
3545 # to force display of password change form.
3548 $querystring = "&user=".&urlize($vu).
3550 "&expired=".$expired;
3553 $page = $config{'password_form'};
3555 $miniserv_internal = 2;
3556 syslog("crit", "%s",
3557 "Expired login as $vu ".
3558 "from $acpthost") if ($use_syslog);
3561 # Login failed, or password has expired. The login form will be
3562 # displayed again by later code
3564 $request_uri = $in{'page'};
3565 $already_session_id = undef;
3567 $authuser = $baseauthuser = undef;
3568 syslog("crit", "%s",
3569 ($nonexist ? "Non-existent" :
3570 $expired ? "Expired" : "Invalid").
3571 " login as $vu from $acpthost")
3577 # write_login_utmp(user, host)
3578 # Record the login by some user in utmp
3579 sub write_login_utmp
3582 # Write utmp record for login
3583 %utmp = ( 'ut_host' => $_[1],
3584 'ut_time' => time(),
3586 'ut_type' => 7, # user process
3587 'ut_pid' => $main_process_id,
3588 'ut_line' => $config{'pam'},
3590 if (defined(&User::Utmp::putut)) {
3591 User::Utmp::putut(\%utmp);
3594 User::Utmp::pututline(\%utmp);
3599 # write_logout_utmp(user, host)
3600 # Record the logout by some user in utmp
3601 sub write_logout_utmp
3604 # Write utmp record for logout
3605 %utmp = ( 'ut_host' => $_[1],
3606 'ut_time' => time(),
3608 'ut_type' => 8, # dead process
3609 'ut_pid' => $main_process_id,
3610 'ut_line' => $config{'pam'},
3612 if (defined(&User::Utmp::putut)) {
3613 User::Utmp::putut(\%utmp);
3616 User::Utmp::pututline(\%utmp);
3621 # pam_conversation_process(username, write-pipe, read-pipe)
3622 # This function is called inside a sub-process to communicate with PAM. It sends
3623 # questions down one pipe, and reads responses from another
3624 sub pam_conversation_process
3626 local ($user, $writer, $reader) = @_;
3627 $miniserv::pam_conversation_process_writer = $writer;
3628 $miniserv::pam_conversation_process_reader = $reader;
3629 local $convh = new Authen::PAM(
3630 $config{'pam'}, $user, \&miniserv::pam_conversation_process_func);
3631 local $pam_ret = $convh->pam_authenticate();
3632 if ($pam_ret == PAM_SUCCESS()) {
3633 local $acct_ret = $convh->pam_acct_mgmt();
3634 if ($acct_ret == PAM_SUCCESS()) {
3635 $convh->pam_open_session();
3636 print $writer "x2 $user 1 0 0\n";
3638 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3639 $acct_ret == PAM_ACCT_EXPIRED()) {
3640 print $writer "x2 $user 1 1 0\n";
3643 print $writer "x0 Unknown PAM account status $acct_ret\n";
3647 print $writer "x2 $user 0 0 0\n";
3652 # pam_conversation_process_func(type, message, [type, message, ...])
3653 # A pipe that talks to both PAM and the master process
3654 sub pam_conversation_process_func
3657 select($miniserv::pam_conversation_process_writer); $| = 1; select(STDOUT);
3659 local ($type, $msg) = (shift, shift);
3661 local $ok = (print $miniserv::pam_conversation_process_writer "$type $msg\n");
3662 print $miniserv::pam_conversation_process_writer "\n";
3663 local $answer = <$miniserv::pam_conversation_process_reader>;
3664 $answer =~ s/\r|\n//g;
3665 push(@rv, PAM_SUCCESS(), $answer);
3667 push(@rv, PAM_SUCCESS());
3672 # Returns 4 new pipe file handles
3675 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3677 local %taken = ( (map { $_, 1 } @passin),
3678 (map { $_->{'PASSINr'} } values %conversations) );
3679 for($p=0; $taken{"PASSINr$p"}; $p++) { }
3680 $PASSINr = "PASSINr$p";
3681 $PASSINw = "PASSINw$p";
3682 $PASSOUTr = "PASSOUTr$p";
3683 $PASSOUTw = "PASSOUTw$p";
3684 pipe($PASSINr, $PASSINw);
3685 pipe($PASSOUTr, $PASSOUTw);
3686 select($PASSINw); $| = 1;
3687 select($PASSINr); $| = 1;
3688 select($PASSOUTw); $| = 1;
3689 select($PASSOUTw); $| = 1;
3691 return ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3694 # recv_pam_question(&conv, fd)
3695 # Reads one PAM question from the sub-process, and sends it to the HTTP handler.
3696 # Returns 0 if the conversation is over, 1 if not.
3697 sub recv_pam_question
3699 local ($conf, $fh) = @_;
3700 local $pr = $conf->{'PAMOUTr'};
3701 select($pr); $| = 1; select(STDOUT);
3702 local $line = <$pr>;
3703 $line =~ s/\r|\n//g;
3706 $line =~ s/\r|\n//g;
3708 $conf->{'last'} = time();
3711 print $fh "0 PAM conversation error\n";
3715 local ($type, $msg) = split(/\s+/, $line, 2);
3716 if ($type =~ /^x(\d+)/) {
3717 # Pass this status code through
3718 print $fh "$1 $msg\n";
3719 return $1 == 2 || $1 == 0 ? 0 : 1;
3721 elsif ($type == PAM_PROMPT_ECHO_ON()) {
3723 print $fh "1 $msg\n";
3726 elsif ($type == PAM_PROMPT_ECHO_OFF()) {
3728 print $fh "3 $msg\n";
3731 elsif ($type == PAM_ERROR_MSG() || $type == PAM_TEXT_INFO()) {
3732 # A message that does not require a response
3733 print $fh "4 $msg\n";
3738 print $fh "0 Unknown PAM message type $type\n";
3744 # send_pam_answer(&conv, answer)
3745 # Sends a response from the user to the PAM sub-process
3748 local ($conf, $answer) = @_;
3749 local $pw = $conf->{'PAMINw'};
3750 $conf->{'last'} = time();
3751 print $pw "$answer\n";
3754 # end_pam_conversation(&conv)
3755 # Clean up PAM conversation pipes and processes
3756 sub end_pam_conversation
3759 kill('KILL', $conv->{'pid'}) if ($conv->{'pid'});
3760 if ($conv->{'PAMINr'}) {
3761 close($conv->{'PAMINr'});
3762 close($conv->{'PAMOUTr'});
3763 close($conv->{'PAMINw'});
3764 close($conv->{'PAMOUTw'});
3766 delete($conversations{$conv->{'cid'}});
3769 # get_ipkeys(&miniserv)
3770 # Returns a list of IP address to key file mappings from a miniserv.conf entry
3774 foreach $k (keys %{$_[0]}) {
3775 if ($k =~ /^ipkey_(\S+)/) {
3776 local $ipkey = { 'ips' => [ split(/,/, $1) ],
3777 'key' => $_[0]->{$k},
3778 'index' => scalar(@rv) };
3779 $ipkey->{'cert'} = $_[0]->{'ipcert_'.$1};
3786 # create_ssl_context(keyfile, [certfile])
3787 sub create_ssl_context
3789 local ($keyfile, $certfile) = @_;
3791 eval { $ssl_ctx = Net::SSLeay::new_x_ctx() };
3792 $ssl_ctx ||= Net::SSLeay::CTX_new();
3793 $ssl_ctx || die "Failed to create SSL context : $!";
3794 if ($client_certs) {
3795 Net::SSLeay::CTX_load_verify_locations(
3796 $ssl_ctx, $config{'ca'}, "");
3797 Net::SSLeay::CTX_set_verify(
3798 $ssl_ctx, &Net::SSLeay::VERIFY_PEER, \&verify_client);
3800 if ($config{'extracas'}) {
3802 foreach $p (split(/\s+/, $config{'extracas'})) {
3803 Net::SSLeay::CTX_load_verify_locations(
3808 Net::SSLeay::CTX_use_RSAPrivateKey_file(
3810 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL key $keyfile";
3811 Net::SSLeay::CTX_use_certificate_file(
3812 $ssl_ctx, $certfile || $keyfile,
3813 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL cert $certfile";
3818 # ssl_connection_for_ip(socket)
3819 # Returns a new SSL connection object for some socket, or undef if failed
3820 sub ssl_connection_for_ip
3823 local $sn = getsockname($sock);
3825 print STDERR "Failed to get address for socket $sock\n";
3828 local $myip = inet_ntoa((unpack_sockaddr_in($sn))[1]);
3829 local $ssl_ctx = $ssl_contexts{$myip} || $ssl_contexts{"*"};
3830 local $ssl_con = Net::SSLeay::new($ssl_ctx);
3831 if ($config{'ssl_cipher_list'}) {
3832 # Force use of ciphers
3833 eval "Net::SSLeay::set_cipher_list(
3834 \$ssl_con, \$config{'ssl_cipher_list'})";
3836 print STDERR "SSL cipher $config{'ssl_cipher_list'} failed : ",
3842 Net::SSLeay::set_fd($ssl_con, fileno($sock));
3843 if (!Net::SSLeay::accept($ssl_con)) {
3844 print STDERR "Failed to initialize SSL connection\n";
3850 # login_redirect(username, password, host)
3851 # Calls the login redirect script (if configured), which may output a URL to
3852 # re-direct a user to after logging in.
3855 return undef if (!$config{'login_redirect'});
3856 local $quser = quotemeta($_[0]);
3857 local $qpass = quotemeta($_[1]);
3858 local $qhost = quotemeta($_[2]);
3859 local $url = `$config{'login_redirect'} $quser $qpass $qhost`;
3864 # reload_config_file()
3865 # Re-read %config, and call post-config actions
3866 sub reload_config_file
3868 &log_error("Reloading configuration");
3869 %config = &read_config_file($config_file);
3870 &update_vital_config();
3873 &build_config_mappings();
3874 if ($config{'session'}) {
3875 dbmclose(%sessiondb);
3876 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
3880 # read_config_file(file)
3881 # Reads the given config file, and returns a hash of values
3882 sub read_config_file
3885 open(CONF, $_[0]) || die "Failed to open config file $_[0] : $!";
3888 if (/^#/ || !/\S/) { next; }
3890 $name = $1; $val = $2;
3891 $name =~ s/^\s+//g; $name =~ s/\s+$//g;
3892 $val =~ s/^\s+//g; $val =~ s/\s+$//g;
3899 # update_vital_config()
3900 # Updates %config with defaults, and dies if something vital is missing
3901 sub update_vital_config
3903 my %vital = ("port", 80,
3905 "server", "MiniServ/0.01",
3906 "index_docs", "index.html index.htm index.cgi index.php",
3907 "addtype_html", "text/html",
3908 "addtype_txt", "text/plain",
3909 "addtype_gif", "image/gif",
3910 "addtype_jpg", "image/jpeg",
3911 "addtype_jpeg", "image/jpeg",
3912 "realm", "MiniServ",
3913 "session_login", "/session_login.cgi",
3914 "pam_login", "/pam_login.cgi",
3915 "password_form", "/password_form.cgi",
3916 "password_change", "/password_change.cgi",
3920 "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\$",
3922 "expires", 7*24*60*60,
3924 foreach my $v (keys %vital) {
3926 if ($vital{$v} eq "") {
3927 die "Missing config option $v";
3929 $config{$v} = $vital{$v};
3932 if (!$config{'sessiondb'}) {
3933 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3934 $config{'sessiondb'} = "$1/sessiondb";
3936 if (!$config{'errorlog'}) {
3937 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
3938 $config{'errorlog'} = "$1/miniserv.error";
3940 if (!$config{'tempbase'}) {
3941 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3942 $config{'tempbase'} = "$1/cgitemp";
3944 if (!$config{'blockedfile'}) {
3945 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3946 $config{'blockedfile'} = "$1/blocked";
3951 # Fills the %users and %certs hashes from the users file in %config
3960 undef(%lastchanges);
3963 if ($config{'userfile'}) {
3964 open(USERS, $config{'userfile'});
3967 local @user = split(/:/, $_, -1);
3968 $users{$user[0]} = $user[1];
3969 $certs{$user[0]} = $user[3] if ($user[3]);
3970 if ($user[4] =~ /^allow\s+(.*)/) {
3971 $allow{$user[0]} = $config{'alwaysresolve'} ?
3972 [ split(/\s+/, $1) ] :
3973 [ &to_ipaddress(split(/\s+/, $1)) ];
3975 elsif ($user[4] =~ /^deny\s+(.*)/) {
3976 $deny{$user[0]} = $config{'alwaysresolve'} ?
3977 [ split(/\s+/, $1) ] :
3978 [ &to_ipaddress(split(/\s+/, $1)) ];
3980 if ($user[5] =~ /days\s+(\S+)/) {
3981 $allowdays{$user[0]} = [ split(/,/, $1) ];
3983 if ($user[5] =~ /hours\s+(\d+)\.(\d+)-(\d+).(\d+)/) {
3984 $allowhours{$user[0]} = [ $1*60+$2, $3*60+$4 ];
3986 $lastchanges{$user[0]} = $user[6];
3987 $nochange{$user[0]} = $user[9];
3988 $temppass{$user[0]} = $user[10];
3995 # Fills %mime with entries from file in %config and extra settings in %config
3999 if ($config{"mimetypes"} ne "") {
4000 open(MIME, $config{"mimetypes"});
4003 if (/^(\S+)\s+(.*)$/) {
4005 my @exts = split(/\s+/, $2);
4006 foreach my $ext (@exts) {
4007 $mime{$ext} = $type;
4013 foreach my $k (keys %config) {
4014 if ($k !~ /^addtype_(.*)$/) { next; }
4015 $mime{$1} = $config{$k};
4019 # build_config_mappings()
4020 # Build the anonymous access list, IP access list, unauthenticated URLs list,
4021 # redirect mapping and allow and deny lists from %config
4022 sub build_config_mappings
4024 # build anonymous access list
4026 foreach my $a (split(/\s+/, $config{'anonymous'})) {
4027 if ($a =~ /^([^=]+)=(\S+)$/) {
4028 $anonymous{$1} = $2;
4032 # build IP access list
4034 foreach my $a (split(/\s+/, $config{'ipaccess'})) {
4035 if ($a =~ /^([^=]+)=(\S+)$/) {
4040 # build unauthenticated URLs list
4041 @unauth = split(/\s+/, $config{'unauth'});
4043 # build redirect mapping
4045 foreach my $r (split(/\s+/, $config{'redirect'})) {
4046 if ($r =~ /^([^=]+)=(\S+)$/) {
4051 # build prefixes to be stripped
4052 undef(@strip_prefix);
4053 foreach my $r (split(/\s+/, $config{'strip_prefix'})) {
4054 push(@strip_prefix, $r);
4057 # Init allow and deny lists
4058 @deny = split(/\s+/, $config{"deny"});
4059 @deny = &to_ipaddress(@deny) if (!$config{'alwaysresolve'});
4060 @allow = split(/\s+/, $config{"allow"});
4061 @allow = &to_ipaddress(@allow) if (!$config{'alwaysresolve'});
4064 if ($config{'allowusers'}) {
4065 @allowusers = split(/\s+/, $config{'allowusers'});
4067 elsif ($config{'denyusers'}) {
4068 @denyusers = split(/\s+/, $config{'denyusers'});
4071 # Build list of unixauth mappings
4073 foreach my $ua (split(/\s+/, $config{'unixauth'})) {
4074 if ($ua =~ /^(\S+)=(\S+)$/) {
4078 $unixauth{"*"} = $ua;
4082 # Build list of non-session-auth pages
4083 undef(%sessiononly);
4084 foreach my $sp (split(/\s+/, $config{'sessiononly'})) {
4085 $sessiononly{$sp} = 1;
4088 # Build list of logout times
4089 undef(@logouttimes);
4090 foreach my $a (split(/\s+/, $config{'logouttimes'})) {
4091 if ($a =~ /^([^=]+)=(\S+)$/) {
4092 push(@logouttimes, [ $1, $2 ]);
4095 push(@logouttimes, [ undef, $config{'logouttime'} ]);
4097 # Build list of DAV pathss
4099 foreach my $d (split(/\s+/, $config{'davpaths'})) {
4100 push(@davpaths, $d);
4102 @davusers = split(/\s+/, $config{'dav_users'});
4104 # Mobile agent substrings and hostname prefixes
4105 @mobile_agents = split(/\t+/, $config{'mobile_agents'});
4106 @mobile_prefixes = split(/\s+/, $config{'mobile_prefixes'});
4110 if ($config{'debug'}) {
4111 open(DEBUG, ">>$config{'debug'}");
4114 open(DEBUG, ">/dev/null");
4117 # Reset cache of sudo checks
4121 # is_group_member(&uinfo, groupname)
4122 # Returns 1 if some user is a primary or secondary member of a group
4125 local ($uinfo, $group) = @_;
4126 local @ginfo = getgrnam($group);
4127 return 0 if (!@ginfo);
4128 return 1 if ($ginfo[2] == $uinfo->[3]); # primary member
4129 foreach my $m (split(/\s+/, $ginfo[3])) {
4130 return 1 if ($m eq $uinfo->[0]);
4135 # prefix_to_mask(prefix)
4136 # Converts a number like 24 to a mask like 255.255.255.0
4139 return $_[0] >= 24 ? "255.255.255.".(256-(2 ** (32-$_[0]))) :
4140 $_[0] >= 16 ? "255.255.".(256-(2 ** (24-$_[0]))).".0" :
4141 $_[0] >= 8 ? "255.".(256-(2 ** (16-$_[0]))).".0.0" :
4142 (256-(2 ** (8-$_[0]))).".0.0.0";
4145 # get_logout_time(user, session-id)
4146 # Given a username, returns the idle time before he will be logged out
4149 local ($user, $sid) = @_;
4150 if (!defined($logout_time_cache{$user,$sid})) {
4152 foreach my $l (@logouttimes) {
4153 if ($l->[0] =~ /^\@(.*)$/) {
4154 # Check group membership
4155 local @uinfo = getpwnam($user);
4156 if (@uinfo && &is_group_member(\@uinfo, $1)) {
4160 elsif ($l->[0] =~ /^\//) {
4161 # Check file contents
4162 open(FILE, $l->[0]);
4179 if ($l->[0] eq $user) {
4183 last if (defined($time));
4185 $logout_time_cache{$user,$sid} = $time;
4187 return $logout_time_cache{$user,$sid};
4190 # password_crypt(password, salt)
4191 # If the salt looks like MD5 and we have a library for it, perform MD5 hashing
4192 # of a password. Otherwise, do Unix crypt.
4195 local ($pass, $salt) = @_;
4196 if ($salt =~ /^\$1\$/ && $use_md5) {
4197 return &encrypt_md5($pass, $salt);
4200 return &unix_crypt($pass, $salt);
4204 # unix_crypt(password, salt)
4205 # Performs standard Unix hashing for a password
4208 local ($pass, $salt) = @_;
4209 if ($use_perl_crypt) {
4210 return Crypt::UnixCrypt::crypt($pass, $salt);
4213 return crypt($pass, $salt);
4217 # handle_dav_request(davpath)
4218 # Pass a request on to the Net::DAV::Server module
4219 sub handle_dav_request
4222 eval "use Filesys::Virtual::Plain";
4223 eval "use Net::DAV::Server";
4224 eval "use HTTP::Request";
4225 eval "use HTTP::Headers";
4227 if ($Net::DAV::Server::VERSION eq '1.28' && $config{'dav_nolock'}) {
4228 delete $Net::DAV::Server::implemented{lock};
4229 delete $Net::DAV::Server::implemented{unlock};
4232 # Read in request data
4233 if (!$posted_data) {
4234 local $clen = $header{"content-length"};
4235 while(length($posted_data) < $clen) {
4236 $buf = &read_data($clen - length($posted_data));
4237 if (!length($buf)) {
4238 &http_error(500, "Failed to read POST request");
4240 chomp($posted_data);
4241 #$posted_data =~ s/\015$//mg;
4242 $posted_data .= $buf;
4246 # For subsequent logging
4247 open(MINISERVLOG, ">>$config{'logfile'}");
4251 local @u = getpwnam($authuser);
4252 if ($config{'dav_remoteuser'} && !$< && $validated) {
4255 $( = $u[3]; $) = "$u[3] $u[3]";
4256 ($>, $<) = ($u[2], $u[2]);
4258 if ($config{'dav_root'} eq '*') {
4263 &http_error(500, "Unix user $authuser does not exist");
4267 $root ||= $config{'dav_root'};
4270 # Check if this user can use DAV
4272 &users_match(\@u, @davusers) ||
4273 &http_error(500, "You are not allowed to access DAV");
4277 my $filesys = Filesys::Virtual::Plain->new({root_path => $root});
4278 my $webdav = Net::DAV::Server->new();
4279 $webdav->filesys($filesys);
4281 # Make up a request object, and feed to DAV
4282 local $ho = HTTP::Headers->new;
4283 foreach my $h (keys %header) {
4284 next if (lc($h) eq "connection");
4285 $ho->header($h => $header{$h});
4288 $request_uri =~ s/^\Q$path\E//;
4289 $request_uri = "/" if ($request_uri eq "");
4291 my $request = HTTP::Request->new($method, $request_uri, $ho,
4293 if ($config{'dav_debug'}) {
4294 print STDERR "DAV request :\n";
4295 print STDERR "---------------------------------------------\n";
4296 print STDERR $request->as_string();
4297 print STDERR "---------------------------------------------\n";
4299 my $response = $webdav->run($request);
4301 # Send back the reply
4302 &write_data("HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n");
4303 local $content = $response->content();
4305 $content =~ s|href>/(.+)<|href>$path/$1<|g;
4306 $content =~ s|href>/<|href>$path<|g;
4308 foreach my $h ($response->header_field_names) {
4309 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4310 &write_data("$h: ",$response->header($h),"\r\n");
4312 &write_data("Content-length: ",length($content),"\r\n");
4313 local $rv = &write_keep_alive(0);
4314 &write_data("\r\n");
4315 &write_data($content);
4317 if ($config{'dav_debug'}) {
4318 print STDERR "DAV reply :\n";
4319 print STDERR "---------------------------------------------\n";
4320 print STDERR "HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n";
4321 foreach my $h ($response->header_field_names) {
4322 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4323 print STDERR "$h: ",$response->header($h),"\r\n";
4325 print STDERR "Content-length: ",length($content),"\r\n";
4326 print STDERR "\r\n";
4327 print STDERR $content;
4328 print STDERR "---------------------------------------------\n";
4332 &log_request($acpthost, $authuser, $reqline, $response->code(),
4333 length($response->content()));
4336 # get_system_hostname()
4337 # Returns the hostname of this system, for reporting to listeners
4338 sub get_system_hostname
4340 # On Windows, try computername environment variable
4341 return $ENV{'computername'} if ($ENV{'computername'});
4342 return $ENV{'COMPUTERNAME'} if ($ENV{'COMPUTERNAME'});
4344 # If a specific command is set, use it first
4345 if ($config{'hostname_command'}) {
4346 local $out = `($config{'hostname_command'}) 2>&1`;
4353 # First try the hostname command
4354 local $out = `hostname 2>&1`;
4355 if (!$? && $out =~ /\S/) {
4360 # Try the Sys::Hostname module
4361 eval "use Sys::Hostname";
4363 local $rv = eval "hostname()";
4369 # Must use net name on Windows
4370 local $out = `net name 2>&1`;
4371 if ($out =~ /\-+\r?\n(\S+)/) {
4378 # indexof(string, array)
4379 # Returns the index of some value in an array, or -1
4382 for($i=1; $i <= $#_; $i++) {
4383 if ($_[$i] eq $_[0]) { return $i - 1; }
4389 # has_command(command)
4390 # Returns the full path if some command is in the path, undef if not
4394 if (!$_[0]) { return undef; }
4395 if (exists($has_command_cache{$_[0]})) {
4396 return $has_command_cache{$_[0]};
4399 if ($_[0] =~ /^\//) {
4400 $rv = -x $_[0] ? $_[0] : undef;
4403 local $sp = $on_windows ? ';' : ':';
4404 foreach $d (split($sp, $ENV{PATH})) {
4405 if (-x "$d/$_[0]") {
4410 foreach my $sfx (".exe", ".com", ".bat") {
4411 if (-r "$d/$_[0]".$sfx) {
4412 $rv = "$d/$_[0]".$sfx;
4419 $has_command_cache{$_[0]} = $rv;
4423 # check_sudo_permissions(user, pass)
4424 # Returns 1 if some user can run any command via sudo
4425 sub check_sudo_permissions
4427 local ($user, $pass) = @_;
4429 # First try the pipes
4431 print DEBUG "check_sudo_permissions: querying cache for $user\n";
4432 print $PASSINw "readsudo $user\n";
4433 local $can = <$PASSOUTr>;
4435 print DEBUG "check_sudo_permissions: cache said $can\n";
4436 if ($can =~ /^\d+$/ && $can != 2) {
4441 local $ptyfh = new IO::Pty;
4442 print DEBUG "check_sudo_permissions: ptyfh=$ptyfh\n";
4444 print STDERR "Failed to create new PTY with IO::Pty\n";
4447 local @uinfo = getpwnam($user);
4449 print STDERR "Unix user $user does not exist for sudo\n";
4453 # Execute sudo in a sub-process, via a pty
4454 local $ttyfh = $ptyfh->slave();
4455 print DEBUG "check_sudo_permissions: ttyfh=$ttyfh\n";
4456 local $tty = $ptyfh->ttyname();
4457 print DEBUG "check_sudo_permissions: tty=$tty\n";
4458 chown($uinfo[2], $uinfo[3], $tty);
4460 print DEBUG "check_sudo_permissions: about to fork..\n";
4461 local $pid = fork();
4462 print DEBUG "check_sudo_permissions: fork=$pid pid=$$\n";
4464 print STDERR "fork for sudo failed : $!\n";
4469 $ptyfh->make_slave_controlling_terminal();
4470 close(STDIN); close(STDOUT); close(STDERR);
4471 untie(*STDIN); untie(*STDOUT); untie(*STDERR);
4472 close($PASSINw); close($PASSOUTr);
4473 $( = $uinfo[3]; $) = "$uinfo[3] $uinfo[3]";
4474 ($>, $<) = ($uinfo[2], $uinfo[2]);
4479 open(STDIN, "<&SUDOr");
4480 open(STDOUT, ">$tty");
4481 open(STDERR, ">&STDOUT");
4484 print "Exec failed : $!\n";
4487 print DEBUG "check_sudo_permissions: pid=$pid\n";
4489 $ptyfh->close_slave();
4491 # Send password, and get back response
4492 local $oldfh = select(SUDOw);
4495 print DEBUG "check_sudo_permissions: about to send pass\n";
4496 local $SIG{'PIPE'} = 'ignore'; # Sometimes sudo doesn't ask for a password
4497 print SUDOw $pass,"\n";
4498 print DEBUG "check_sudo_permissions: sent pass=$pass\n";
4502 print DEBUG "check_sudo_permissions: got $_";
4508 local ($ok) = ($out =~ /\(ALL\)\s+ALL/ ? 1 : 0);
4512 print $PASSINw "writesudo $user $ok\n";
4518 # is_mobile_useragent(agent)
4519 # Returns 1 if some user agent looks like a cellphone or other mobile device,
4521 sub is_mobile_useragent
4523 local ($agent) = @_;
4525 "UP.Link", # Openwave
4526 "Nokia", # All Nokias start with Nokia
4527 "MOT-", # All Motorola phones start with MOT-
4528 "SAMSUNG", # Samsung browsers
4529 "Samsung", # Samsung browsers
4530 "SEC-", # Samsung browsers
4531 "AU-MIC", # Samsung browsers
4532 "AUDIOVOX", # Audiovox
4533 "BlackBerry", # BlackBerry
4534 "hiptop", # Danger hiptop Sidekick
4535 "SonyEricsson", # Sony Ericsson
4536 "Ericsson", # Old Ericsson browsers , mostly WAP
4537 "Mitsu/1.1.A", # Mitsubishi phones
4538 "Panasonic WAP", # Panasonic old WAP phones
4539 "DoCoMo", # DoCoMo phones
4540 "Lynx", # Lynx text-mode linux browser
4541 "Links", # Another text-mode linux browser
4543 local @substrings = (
4544 "UP.Browser", # Openwave
4545 "MobilePhone", # NetFront
4546 "AU-MIC-A700", # Samsung A700 Obigo browsers
4547 "Danger hiptop", # Danger Sidekick hiptop
4548 "Windows CE", # Windows CE Pocket PC
4549 "IEMobile", # Windows mobile browser
4550 "Blazer", # Palm Treo Blazer
4551 "BlackBerry", # BlackBerries can emulate other browsers, but
4552 # they still keep this string in the UserAgent
4553 "SymbianOS", # New Series60 browser has safari in it and
4554 # SymbianOS is the only distinguishing string
4555 "iPhone", # Apple iPhone KHTML browser
4556 "iPod", # iPod touch browser
4557 "MobileSafari", # HTTP client in iPhone
4559 "Opera Mini", # Opera Mini
4561 foreach my $p (@prefixes) {
4562 return 1 if ($agent =~ /^\Q$p\E/);
4564 foreach my $s (@substrings, @mobile_agents) {
4565 return 1 if ($agent =~ /\Q$s\E/);
4570 # write_blocked_file()
4571 # Writes out a text file of blocked hosts and users
4572 sub write_blocked_file
4574 open(BLOCKED, ">$config{'blockedfile'}");
4575 foreach my $d (grep { $hostfail{$_} } @deny) {
4576 print BLOCKED "host $d $hostfail{$d} $blockhosttime{$d}\n";
4578 foreach my $d (grep { $userfail{$_} } @denyusers) {
4579 print BLOCKED "user $d $userfail{$d} $blockusertime{$d}\n";
4582 chmod(0700, $config{'blockedfile'});
4587 open(PIDFILE, ">$config{'pidfile'}");
4588 printf PIDFILE "%d\n", getpid();
4592 # lock_user_password(user)
4593 # Updates a user's password file entry to lock it, both in memory and on disk.
4594 # Returns 1 if done, -1 if no such user, 0 if already locked
4595 sub lock_user_password
4598 if ($users{$user}) {
4599 if ($users{$user} !~ /^\!/) {
4601 $users{$user} = "!".$users{$user};
4602 open(USERS, $config{'userfile'});
4603 local @ufile = <USERS>;
4605 foreach my $u (@ufile) {
4606 local @uinfo = split(/:/, $u);
4607 if ($uinfo[0] eq $user) {
4608 $uinfo[1] = $users{$user};
4610 $u = join(":", @uinfo);
4612 open(USERS, ">$config{'userfile'}");
4622 # hash_session_id(sid)
4623 # Returns an MD5 or Unix-crypted session ID
4627 if (!$hash_session_id_cache{$sid}) {
4630 $hash_session_id_cache{$sid} = &encrypt_md5($sid);
4634 $hash_session_id_cache{$sid} = &unix_crypt($sid, "XX");
4637 return $hash_session_id_cache{$sid};
4640 # encrypt_md5(string, [salt])
4641 # Returns a string encrypted in MD5 format
4644 local ($passwd, $salt) = @_;
4645 local $magic = '$1$';
4646 if ($salt =~ /^\$1\$([^\$]+)/) {
4647 # Extract actual salt from already encrypted password
4652 local $ctx = eval "new $use_md5";
4659 # Add some more stuff from the hash of the password and salt
4660 local $ctx1 = eval "new $use_md5";
4661 $ctx1->add($passwd);
4665 $ctx1->add($passwd);
4666 local $final = $ctx1->digest();
4667 for($pl=length($passwd); $pl>0; $pl-=16) {
4668 $ctx->add($pl > 16 ? $final : substr($final, 0, $pl));
4671 # This piece of code seems rather pointless, but it's in the C code that
4672 # does MD5 in PAM so it has to go in!
4675 for($i=length($passwd); $i; $i >>= 1) {
4680 $ctx->add(substr($passwd, $j, 1));
4683 $final = $ctx->digest();
4686 # This loop exists only to waste time
4687 for($i=0; $i<1000; $i++) {
4688 $ctx1 = eval "new $use_md5";
4689 $ctx1->add($i & 1 ? $passwd : $final);
4690 $ctx1->add($salt) if ($i % 3);
4691 $ctx1->add($passwd) if ($i % 7);
4692 $ctx1->add($i & 1 ? $final : $passwd);
4693 $final = $ctx1->digest();
4697 # Convert the 16-byte final string into a readable form
4699 local @final = map { ord($_) } split(//, $final);
4700 $l = ($final[ 0]<<16) + ($final[ 6]<<8) + $final[12];
4701 $rv .= &to64($l, 4);
4702 $l = ($final[ 1]<<16) + ($final[ 7]<<8) + $final[13];
4703 $rv .= &to64($l, 4);
4704 $l = ($final[ 2]<<16) + ($final[ 8]<<8) + $final[14];
4705 $rv .= &to64($l, 4);
4706 $l = ($final[ 3]<<16) + ($final[ 9]<<8) + $final[15];
4707 $rv .= &to64($l, 4);
4708 $l = ($final[ 4]<<16) + ($final[10]<<8) + $final[ 5];
4709 $rv .= &to64($l, 4);
4711 $rv .= &to64($l, 2);
4713 # Add salt if needed
4715 return $magic.$salt.'$'.$rv;
4724 local ($v, $n) = @_;
4727 $r .= $itoa64[$v & 0x3f];