2 # A very simple perl web server used by Webmin
4 # Require basic libraries
10 @itoa64 = split(//, "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
12 # Find and read config file
14 die "Usage: miniserv.pl <config file>";
16 if ($ARGV[0] =~ /^([a-z]:)?\//i) {
17 $config_file = $ARGV[0];
21 $config_file = "$pwd/$ARGV[0]";
23 %config = &read_config_file($config_file);
25 # Check is SSL is enabled and available
27 eval "use Net::SSLeay";
30 # These functions only exist for SSLeay 1.0
31 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
32 eval "Net::SSLeay::load_error_strings()";
33 if ($config{'no_ssl2'}) {
34 eval "Net::SSLeay::CTX_set_options($ctx,&Net::SSLeay::OP_NO_SSLv2)";
36 if (defined(&Net::SSLeay::X509_STORE_CTX_get_current_cert) &&
37 defined(&Net::SSLeay::CTX_load_verify_locations) &&
38 defined(&Net::SSLeay::CTX_set_verify)) {
44 # Check if the syslog module is available to log hacking attempts
45 if ($config{'syslog'} && !$config{'inetd'}) {
46 eval "use Sys::Syslog qw(:DEFAULT setlogsock)";
52 # check if the TCP-wrappers module is available
53 if ($config{'libwrap'}) {
54 eval "use Authen::Libwrap qw(hosts_ctl STRING_UNKNOWN)";
60 # Check if the MD5 perl module is available
66 eval "use Digest::MD5";
68 $use_md5 = "Digest::MD5";
72 # Get miniserv's perl path and location
74 open(SOURCE, $miniserv_path);
75 <SOURCE> =~ /^#!(\S+)/;
82 $linked_perl_path = readlink($perl_path);
84 @miniserv_argv = @ARGV;
86 # Check vital config options
87 &update_vital_config();
89 $sidname = $config{'sidname'};
90 die "Session authentication cannot be used in inetd mode"
91 if ($config{'inetd'} && $config{'session'});
93 # check if the PAM module is available to authenticate
94 if (!$config{'no_pam'}) {
95 eval "use Authen::PAM;";
97 # check if the PAM authentication can be used by opening a
100 if (ref($pamh = new Authen::PAM($config{'pam'}, "root",
102 # Now test a login to see if /etc/pam.d/XXX is set
104 $pam_conv_func_called = 0;
105 $pam_username = "test";
106 $pam_password = "test";
107 $pamh->pam_authenticate();
108 if ($pam_conv_func_called) {
109 $pam_msg = "PAM authentication enabled";
113 $pam_msg = "PAM test failed - maybe /etc/pam.d/$config{'pam'} does not exist";
117 $pam_msg = "PAM initialization of Authen::PAM failed";
121 $pam_msg = "Perl module Authen::PAM needed for PAM is not installed : $@";
124 if ($config{'pam_only'} && !$use_pam) {
125 $pam_msg2 = "PAM use is mandatory, but could not be enabled!";
127 elsif ($pam_msg && !$use_pam) {
128 $pam_msg2 = "Continuing without the Authen::PAM perl module";
131 # Check if the User::Utmp perl module is installed
132 if ($config{'utmp'}) {
133 eval "use User::Utmp;";
136 $utmp_msg = "UTMP logging enabled";
139 $utmp_msg = "Perl module User::Utmp needed for Utmp logging is not installed : $@";
143 # See if the crypt function fails
144 eval "crypt('foo', 'xx')";
146 eval "use Crypt::UnixCrypt";
149 $crypt_msg = "Using Crypt::UnixCrypt for password encryption\n";
152 $crypt_msg = "crypt() function un-implemented, and Crypt::UnixCrypt not installed - password authentication will probably fail\n";
156 # Check if /dev/urandom really generates random IDs, by calling it twice
157 local $rand1 = &generate_random_id("foo", 1);
158 local $rand2 = &generate_random_id("foo", 2);
160 if ($rand1 eq $rand2) {
162 $rand_msg = "Random number generator file /dev/urandom is not reliable";
165 # Check if we can call sudo
166 if ($config{'sudo'} && &has_command("sudo")) {
172 $sudo_msg = "Perl module IO::Pty needed for calling sudo is not installed : $@";
176 # init days and months for http_date
177 @weekday = ( "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" );
178 @month = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun",
179 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" );
181 # Change dir to the server root
182 @roots = ( $config{'root'} );
183 for($i=0; defined($config{"extraroot_$i"}); $i++) {
184 push(@roots, $config{"extraroot_$i"});
187 eval { $user_homedir = (getpwuid($<))[7]; };
189 # getpwuid doesn't work on windows
190 $user_homedir = $ENV{"HOME"} || $ENV{"USERPROFILE"} || "/";
197 # Setup SSL if possible and if requested
198 if (!-r $config{'keyfile'} ||
199 $config{'certfile'} && !-r $config{'certfile'}) {
200 # Key file doesn't exist!
203 @ipkeys = &get_ipkeys(\%config);
205 if ($config{'ssl_version'}) {
206 # Force an SSL version
207 $Net::SSLeay::version = $config{'ssl_version'};
208 $Net::SSLeay::ssl_version = $config{'ssl_version'};
210 $client_certs = 0 if (!-r $config{'ca'} || !%certs);
211 $ssl_contexts{"*"} = &create_ssl_context($config{'keyfile'},
212 $config{'certfile'});
213 foreach $ipkey (@ipkeys) {
214 $ctx = &create_ssl_context($ipkey->{'key'}, $ipkey->{'cert'});
215 foreach $ip (@{$ipkey->{'ips'}}) {
216 $ssl_contexts{$ip} = $ctx;
221 # Setup syslog support if possible and if requested
223 open(ERRDUP, ">&STDERR");
224 open(STDERR, ">/dev/null");
225 $log_socket = $config{"logsock"} || "unix";
226 eval 'openlog($config{"pam"}, "cons,pid,ndelay", "authpriv"); setlogsock($log_socket)';
231 local $msg = ucfirst($config{'pam'})." starting";
232 eval { syslog("info", "%s", $msg); };
236 syslog("info", "%s", $msg);
239 # All attempts to use syslog have failed..
244 open(STDERR, ">&ERRDUP");
248 # Read MIME types file and add extra types
252 if ($config{'log'}) {
253 local(@gmt, @lct, $days, $hours, $mins);
254 @gmt = gmtime(time());
255 @lct = localtime(time());
256 $days = $lct[3] - $gmt[3];
257 $hours = ($days < -1 ? 24 : 1 < $days ? -24 : $days * 24) +
259 $mins = $hours * 60 + $lct[1] - $gmt[1];
260 $timezone = ($mins < 0 ? "-" : "+"); $mins = abs($mins);
261 $timezone .= sprintf "%2.2d%2.2d", $mins/60, $mins%60;
264 # Build various maps from the config files
265 &build_config_mappings();
267 # start up external authentication program, if needed
268 if ($config{'extauth'}) {
269 socketpair(EXTAUTH, EXTAUTH2, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
270 if (!($extauth = fork())) {
274 open(STDIN, "<&EXTAUTH2");
275 open(STDOUT, ">&EXTAUTH2");
276 exec($config{'extauth'}) or die "exec failed : $!\n";
279 local $os = select(EXTAUTH);
283 # Pre-load any libraries
284 foreach $pl (split(/\s+/, $config{'preload'})) {
285 ($pkg, $lib) = split(/=/, $pl);
286 $pkg =~ s/[^A-Za-z0-9]/_/g;
287 eval "package $pkg; do '$config{'root'}/$lib'";
289 print STDERR "Failed to pre-load $pkg/$lib : $@\n";
292 print STDERR "Pre-loading $pkg/$lib\n";
296 # Open debug log if set
297 if ($config{'debuglog'}) {
298 open(DEBUG, ">>$config{'debuglog'}");
299 chmod(0700, $config{'debuglog'});
300 select(DEBUG); $| = 1; select(STDOUT);
301 print DEBUG "miniserv.pl starting ..\n";
304 # Write out (empty) blocked hosts file
305 &write_blocked_file();
307 # Re-direct STDERR to a log file
308 if ($config{'errorlog'} ne '-') {
309 open(STDERR, ">>$config{'errorlog'}") || die "failed to open $config{'errorlog'} : $!";
310 if ($config{'logperms'}) {
311 chmod(oct($config{'logperms'}), $config{'errorlog'});
314 select(STDERR); $| = 1; select(STDOUT);
316 if ($config{'inetd'}) {
317 # We are being run from inetd - go direct to handling the request
318 $SIG{'HUP'} = 'IGNORE';
319 $SIG{'TERM'} = 'DEFAULT';
320 $SIG{'PIPE'} = 'DEFAULT';
321 open(SOCK, "+>&STDIN");
323 # Check if it is time for the logfile to be cleared
324 if ($config{'logclear'}) {
325 local $write_logtime = 0;
326 local @st = stat("$config{'logfile'}.time");
328 if ($st[9]+$config{'logtime'}*60*60 < time()){
331 unlink($config{'logfile'});
334 else { $write_logtime = 1; }
335 if ($write_logtime) {
336 open(LOGTIME, ">$config{'logfile'}.time");
337 print LOGTIME time(),"\n";
342 # Initialize SSL for this connection
344 $ssl_con = &ssl_connection_for_ip(SOCK);
348 # Work out the hostname for this web server
349 $host = &get_socket_name(SOCK);
351 $port = $config{'port'};
352 $acptaddr = getpeername(SOCK);
355 print DEBUG "main: Starting handle_request loop pid=$$\n";
356 while(&handle_request($acptaddr, getsockname(SOCK))) { }
357 print DEBUG "main: Done handle_request loop pid=$$\n";
362 # Build list of sockets to listen on
363 if ($config{"bind"} && $config{"bind"} ne "*") {
364 push(@sockets, [ inet_aton($config{'bind'}), $config{'port'} ]);
367 push(@sockets, [ INADDR_ANY, $config{'port'} ]);
369 foreach $s (split(/\s+/, $config{'sockets'})) {
370 if ($s =~ /^(\d+)$/) {
371 # Just listen on another port on the main IP
372 push(@sockets, [ $sockets[0]->[0], $s ]);
374 elsif ($s =~ /^(\S+):(\d+)$/) {
375 # Listen on a specific port and IP
376 push(@sockets, [ $1 eq "*" ? INADDR_ANY : inet_aton($1), $2 ]);
378 elsif ($s =~ /^([0-9\.]+):\*$/ || $s =~ /^([0-9\.]+)$/) {
379 # Listen on the main port on another IP
380 push(@sockets, [ inet_aton($1), $sockets[0]->[1] ]);
384 # Open all the sockets
385 $proto = getprotobyname('tcp');
387 $tried_inaddr_any = 0;
388 for($i=0; $i<@sockets; $i++) {
390 socket($fh, PF_INET, SOCK_STREAM, $proto) ||
391 die "Failed to open socket : $!";
392 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
393 for($j=0; $j<5; $j++) {
394 last if (bind($fh, pack_sockaddr_in($sockets[$i]->[1],
395 $sockets[$i]->[0])));
399 # All attempts failed .. give up
400 if ($sockets[$i]->[0] eq INADDR_ANY) {
401 push(@sockerrs, "Failed to bind to port $sockets[$i]->[1] : $!");
402 $tried_inaddr_any = 1;
405 $ip = inet_ntoa($sockets[$i]->[0]);
406 push(@sockerrs, "Failed to bind to IP $ip port $sockets[$i]->[1] : $!");
410 listen($fh, SOMAXCONN);
411 push(@socketfhs, $fh);
414 foreach $se (@sockerrs) {
415 print STDERR $se,"\n";
418 # If all binds failed, try binding to any address
419 if (!@socketfhs && !$tried_inaddr_any) {
420 print STDERR "Falling back to listening on any address\n";
422 socket($fh, PF_INET, SOCK_STREAM, $proto) ||
423 die "Failed to open socket : $!";
424 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
425 bind($fh, pack_sockaddr_in($sockets[0]->[1], INADDR_ANY)) ||
426 die "Failed to bind to port $sockets[0]->[1] : $!";
427 listen($fh, SOMAXCONN);
428 push(@socketfhs, $fh);
430 elsif (!@socketfhs && $tried_inaddr_any) {
431 die "Could not listen on any ports";
434 if ($config{'listen'}) {
435 # Open the socket that allows other webmin servers to find this one
436 $proto = getprotobyname('udp');
437 if (socket(LISTEN, PF_INET, SOCK_DGRAM, $proto)) {
438 setsockopt(LISTEN, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
439 bind(LISTEN, pack_sockaddr_in($config{'listen'}, INADDR_ANY));
440 listen(LISTEN, SOMAXCONN);
443 $config{'listen'} = 0;
447 # Split from the controlling terminal, unless configured not to
448 if (!$config{'nofork'}) {
449 if (fork()) { exit; }
451 eval { setsid(); }; # may not work on Windows
453 # Close standard file handles
454 open(STDIN, "</dev/null");
455 open(STDOUT, ">/dev/null");
456 &log_error("miniserv.pl started");
457 &log_error($pam_msg) if ($pam_msg);
458 &log_error($pam_msg2) if ($pam_msg2);
459 &log_error($utmp_msg) if ($utmp_msg);
460 &log_error($crypt_msg) if ($crypt_msg);
461 &log_error($sudo_msg) if ($sudo_msg);
462 &log_error($rand_msg) if ($rand_msg);
464 # write out the PID file
467 # Start the log-clearing process, if needed. This checks every minute
468 # to see if the log has passed its reset time, and if so clears it
469 if ($config{'logclear'}) {
470 if (!($logclearer = fork())) {
471 &close_all_sockets();
474 local $write_logtime = 0;
475 local @st = stat("$config{'logfile'}.time");
477 if ($st[9]+$config{'logtime'}*60*60 < time()){
480 unlink($config{'logfile'});
483 else { $write_logtime = 1; }
484 if ($write_logtime) {
485 open(LOGTIME, ">$config{'logfile'}.time");
486 print LOGTIME time(),"\n";
493 push(@childpids, $logclearer);
496 # Setup the logout time dbm if needed
497 if ($config{'session'}) {
498 eval "use SDBM_File";
499 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
500 eval "\$sessiondb{'1111111111'} = 'foo bar';";
502 dbmclose(%sessiondb);
503 eval "use NDBM_File";
504 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
507 delete($sessiondb{'1111111111'});
512 $SIG{'HUP'} = 'miniserv::trigger_restart';
513 $SIG{'TERM'} = 'miniserv::term_handler';
514 $SIG{'USR1'} = 'miniserv::trigger_reload';
515 $SIG{'PIPE'} = 'IGNORE';
516 local $remove_session_count = 0;
517 $need_pipes = $config{'passdelay'} || $config{'session'};
518 $last_pid_time = time();
520 # wait for a new connection, or a message from a child process
522 if (@childpids <= $config{'maxconns'}) {
523 # Only accept new main socket connects when ready
525 foreach $s (@socketfhs) {
526 vec($rmask, fileno($s), 1) = 1;
530 printf STDERR "too many children (%d > %d)\n",
531 scalar(@childpids), $config{'maxconns'};
534 for($i=0; $i<@passin; $i++) {
535 vec($rmask, fileno($passin[$i]), 1) = 1;
538 vec($rmask, fileno(LISTEN), 1) = 1 if ($config{'listen'});
540 # Wait for a connection
541 local $sel = select($rmask, undef, undef, 10);
543 # Check the flag files
544 if ($config{'restartflag'} && -r $config{'restartflag'}) {
545 print STDERR "restart flag file detected\n";
546 unlink($config{'restartflag'});
549 if ($config{'reloadflag'} && -r $config{'reloadflag'}) {
550 unlink($config{'reloadflag'});
555 # Got a HUP signal while in select() .. restart now
559 # Got a USR1 signal while in select() .. re-read config
561 &reload_config_file();
563 local $time_now = time();
565 # Write the PID every 10 seconds
566 if ($time_now - $last_pid_time > 10) {
568 $last_pid_time = $time_now;
571 # Clean up finished processes
573 do { $pid = waitpid(-1, WNOHANG);
574 @childpids = grep { $_ != $pid } @childpids;
575 } while($pid != 0 && $pid != -1);
577 # run the unblocking procedure to check if enough time has passed to
578 # unblock hosts that heve been blocked because of password failures
580 if ($config{'blockhost_failures'}) {
582 while ($i <= $#deny) {
583 if ($blockhosttime{$deny[$i]} &&
584 $config{'blockhost_time'} != 0 &&
585 ($time_now - $blockhosttime{$deny[$i]}) >=
586 $config{'blockhost_time'}) {
587 # the host can be unblocked now
588 $hostfail{$deny[$i]} = 0;
589 splice(@deny, $i, 1);
596 # Do the same for blocked users
597 if ($config{'blockuser_failures'}) {
599 while ($i <= $#deny) {
600 if ($blockusertime{$deny[$i]} &&
601 $config{'blockuser_time'} != 0 &&
602 ($time_now - $blockusertime{$deny[$i]}) >=
603 $config{'blockuser_time'}) {
604 # the user can be unblocked now
605 $userfail{$deny[$i]} = 0;
606 splice(@denyusers, $i, 1);
613 &write_blocked_file();
616 if ($config{'session'} && (++$remove_session_count%50) == 0) {
617 # Remove sessions with more than 7 days of inactivity,
619 foreach $s (keys %sessiondb) {
620 local ($user, $ltime, $lip) =
621 split(/\s+/, $sessiondb{$s});
622 if ($time_now - $ltime > 7*24*60*60) {
623 &run_logout_script($s, $user);
624 &write_logout_utmp($user, $lip);
625 delete($sessiondb{$s});
628 "Timeout of session for $user");
634 if ($use_pam && $config{'pam_conv'}) {
635 # Remove PAM sessions with more than 5 minutes of inactivity
637 foreach $c (values %conversations) {
638 if ($time_now - $c->{'time'} > 5*60) {
639 &end_pam_conversation($c);
641 syslog("info", "%s", "Timeout of PAM ".
642 "session for $c->{'user'}");
648 # Don't check any sockets if there is no activity
651 # Check if any of the main sockets have received a new connection
653 foreach $s (@socketfhs) {
654 if (vec($rmask, fileno($s), 1)) {
656 $acptaddr = accept(SOCK, $s);
657 if (!$acptaddr) { next; }
658 binmode(SOCK); # turn off any Perl IO stuff
661 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
663 ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw) =
667 # Check username of connecting user
668 local ($peerp, $peera) = unpack_sockaddr_in($acptaddr);
669 $localauth_user = undef;
670 if ($config{'localauth'} && inet_ntoa($peera) eq "127.0.0.1") {
671 if (open(TCP, "/proc/net/tcp")) {
672 # Get the info direct from the kernel
675 local @t = split(/[\s:]+/, $_);
676 if ($t[1] eq '0100007F' &&
677 $t[2] eq sprintf("%4.4X", $peerp)) {
678 $localauth_user = getpwuid($t[11]);
684 if (!$localauth_user) {
685 # Call lsof for the info
686 local $lsofpid = open(LSOF,
687 "$config{'localauth'} -i TCP\@127.0.0.1:$peerp |");
689 if (/^(\S+)\s+(\d+)\s+(\S+)/ &&
690 $2 != $$ && $2 != $lsofpid) {
691 $localauth_user = $3;
698 # Work out the hostname for this web server
699 $host = &get_socket_name(SOCK);
701 print STDERR "Failed to get local socket name : $!\n";
705 $port = $sockets[$sn]->[1];
707 # fork the subprocess
709 if (!($handpid = fork())) {
710 # setup signal handlers
711 $SIG{'TERM'} = 'DEFAULT';
712 $SIG{'PIPE'} = 'DEFAULT';
713 #$SIG{'CHLD'} = 'IGNORE';
714 $SIG{'HUP'} = 'IGNORE';
715 $SIG{'USR1'} = 'IGNORE';
717 # Initialize SSL for this connection
719 $ssl_con = &ssl_connection_for_ip(SOCK);
723 # Close the file handle for the session DBM
724 dbmclose(%sessiondb);
726 # close useless pipes
729 close($PASSINr); close($PASSOUTw);
731 &close_all_sockets();
735 "main: Starting handle_request loop pid=$$\n";
736 while(&handle_request($acptaddr,
737 getsockname(SOCK))) { }
739 "main: Done handle_request loop pid=$$\n";
742 close($PASSINw); close($PASSOUTw);
745 push(@childpids, $handpid);
747 close($PASSINw); close($PASSOUTr);
748 push(@passin, $PASSINr);
749 push(@passout, $PASSOUTw);
756 if ($config{'listen'} && vec($rmask, fileno(LISTEN), 1)) {
757 # Got UDP packet from another webmin server
759 local $from = recv(LISTEN, $rcvbuf, 1024, 0);
761 local $fromip = inet_ntoa((unpack_sockaddr_in($from))[1]);
762 local $toip = inet_ntoa((unpack_sockaddr_in(
763 getsockname(LISTEN)))[1]);
764 if ((!@deny || !&ip_match($fromip, $toip, @deny)) &&
765 (!@allow || &ip_match($fromip, $toip, @allow))) {
766 local $listenhost = &get_socket_name(LISTEN);
767 send(LISTEN, "$listenhost:$config{'port'}:".
768 ($use_ssl || $config{'inetd_ssl'} ? 1 : 0).":".
769 ($config{'listenhost'} ?
770 &get_system_hostname() : ""),
776 # check for session, password-timeout and PAM messages from subprocesses
777 for($i=0; $i<@passin; $i++) {
778 if (vec($rmask, fileno($passin[$i]), 1)) {
779 # this sub-process is asking about a password
780 local $infd = $passin[$i];
781 local $outfd = $passout[$i];
782 #local $inline = <$infd>;
783 local $inline = &sysread_line($infd);
785 print DEBUG "main: inline $inline";
788 print DEBUG "main: inline EOF\n";
790 if ($inline =~ /^delay\s+(\S+)\s+(\S+)\s+(\d+)/) {
791 # Got a delay request from a subprocess.. for
792 # valid logins, there is no delay (to prevent
793 # denial of service attacks), but for invalid
794 # logins the delay increases with each failed
797 # login OK.. no delay
798 print $outfd "0 0\n";
799 $wasblocked = $hostfail{$2} ||
804 &write_blocked_file();
813 # add the host to the block list,
815 if ($config{'blockhost_failures'} &&
817 $config{'blockhost_failures'}) {
819 $blockhosttime{$2} = $time_now;
822 local $logtext = "Security alert: Host $2 blocked after $config{'blockhost_failures'} failed logins for user $1";
828 # add the user to the user block list,
830 if ($config{'blockuser_failures'} &&
832 $config{'blockuser_failures'}) {
833 push(@denyusers, $1);
834 $blockusertime{$1} = $time_now;
837 local $logtext = "Security alert: User $1 blocked after $config{'blockuser_failures'} failed logins";
843 # Lock out the user's password, if enabled
844 if ($config{'blocklock'} &&
846 $config{'blockuser_failures'}) {
847 my $lk = &lock_user_password($1);
850 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";
857 $dl = $userdlay{$1} -
858 int(($time_now - $userlast{$1})/50);
859 $dl = $dl < 0 ? 0 : $dl+1;
860 print $outfd "$dl $blocked\n";
863 # Write out blocked status file
865 &write_blocked_file();
868 $userlast{$1} = $time_now;
870 elsif ($inline =~ /^verify\s+(\S+)\s+(\S+)/) {
871 # Verifying a session ID
872 local $session_id = $1;
873 local $notimeout = $2;
874 local $skey = $sessiondb{$session_id} ?
876 &hash_session_id($session_id);
877 if (!defined($sessiondb{$skey})) {
878 # Session doesn't exist
879 print $outfd "0 0\n";
882 local ($user, $ltime) =
883 split(/\s+/, $sessiondb{$skey});
884 local $lot = &get_logout_time($user, $session_id);
886 $time_now - $ltime > $lot*60 &&
888 # Session has timed out
889 print $outfd "1 ",$time_now - $ltime,"\n";
890 #delete($sessiondb{$skey});
894 print $outfd "2 $user\n";
898 $sessiondb{$skey} = "$user $time_now";
903 elsif ($inline =~ /^new\s+(\S+)\s+(\S+)\s+(\S+)/) {
904 # Creating a new session
905 local $session_id = $1;
908 $sessiondb{&hash_session_id($session_id)} =
909 "$user $time_now $ip";
911 elsif ($inline =~ /^delete\s+(\S+)/) {
912 # Logging out a session
913 local $session_id = $1;
914 local $skey = $sessiondb{$session_id} ?
916 &hash_session_id($session_id);
917 local @sdb = split(/\s+/, $sessiondb{$skey});
918 print $outfd $sdb[0],"\n";
919 delete($sessiondb{$skey});
921 elsif ($inline =~ /^pamstart\s+(\S+)\s+(\S+)\s+(.*)/) {
922 # Starting a new PAM conversation
923 local ($cid, $host, $user) = ($1, $2, $3);
925 # Does this user even need PAM?
926 local ($realuser, $canlogin) =
927 &can_user_login($user, undef, $host);
929 if ($canlogin == 0) {
931 print $outfd "0 Invalid username\n";
933 elsif ($canlogin != 2) {
934 # Not using PAM .. so just ask for
936 $conv = { 'user' => $realuser,
941 print $outfd "3 Password\n";
944 # Start the PAM conversation
945 # sub-process, and get a question
946 $conv = { 'user' => $realuser,
950 local ($PAMINr, $PAMINw, $PAMOUTr,
951 $PAMOUTw) = &allocate_pipes();
952 local $pampid = fork();
954 close($PAMOUTr); close($PAMINw);
955 &pam_conversation_process(
959 close($PAMOUTw); close($PAMINr);
960 $conv->{'pid'} = $pampid;
961 $conv->{'PAMOUTr'} = $PAMOUTr;
962 $conv->{'PAMINw'} = $PAMINw;
963 push(@childpids, $pampid);
965 # Get the first PAM question
966 local $pok = &recv_pam_question(
969 &end_pam_conversation($conv);
973 $conversations{$cid} = $conv if ($conv);
975 elsif ($inline =~ /^pamanswer\s+(\S+)\s+(.*)/) {
976 # A response to a PAM question
977 local ($cid, $answer) = ($1, $2);
978 local $conv = $conversations{$cid};
980 # No such conversation?
981 print $outfd "0 Bad login session\n";
983 elsif ($conv->{'pid'}) {
984 # Send the PAM response and get
986 &send_pam_answer($conv, $answer);
987 local $pok = &recv_pam_question($conv, $outfd);
989 &end_pam_conversation($conv);
993 # This must be the password .. try it
994 # and send back the results
995 local ($vu, $expired, $nonexist) =
996 &validate_user($conv->{'user'},
999 local $ok = $vu ? 1 : 0;
1000 print $outfd "2 $conv->{'user'} $ok $expired $notexist\n";
1001 &end_pam_conversation($conv);
1004 elsif ($inline =~ /^writesudo\s+(\S+)\s+(\d+)/) {
1005 # Store the fact that some user can sudo to root
1006 local ($user, $ok) = ($1, $2);
1007 $sudocache{$user} = $ok." ".time();
1009 elsif ($inline =~ /^readsudo\s+(\S+)/) {
1010 # Query the user sudo cache (valid for 1 minute)
1012 local ($ok, $last) =
1013 split(/\s+/, $sudocache{$user});
1014 if ($last < time()-60) {
1019 # Tell client OK or not
1020 print $outfd "$ok\n";
1023 elsif ($inline =~ /\S/) {
1024 # Unknown line from pipe?
1025 print DEBUG "main: Unknown line from pipe $inline\n";
1026 print STDERR "Unknown line from pipe $inline\n";
1030 close($infd); close($outfd);
1031 $passin[$i] = $passout[$i] = undef;
1035 @passin = grep { defined($_) } @passin;
1036 @passout = grep { defined($_) } @passout;
1039 # handle_request(remoteaddress, localaddress)
1040 # Where the real work is done
1043 $acptip = inet_ntoa((unpack_sockaddr_in($_[0]))[1]);
1044 $localip = $_[1] ? inet_ntoa((unpack_sockaddr_in($_[1]))[1]) : undef;
1045 print DEBUG "handle_request: from $acptip to $localip\n";
1046 if ($config{'loghost'}) {
1047 $acpthost = gethostbyaddr(inet_aton($acptip), AF_INET);
1048 $acpthost = $acptip if (!$acpthost);
1051 $acpthost = $acptip;
1053 $datestr = &http_date(time());
1055 $ok_message = "Document follows";
1056 $logged_code = undef;
1057 $reqline = $request_uri = $page = undef;
1061 # check address against access list
1062 if (@deny && &ip_match($acptip, $localip, @deny) ||
1063 @allow && !&ip_match($acptip, $localip, @allow)) {
1064 &http_error(403, "Access denied for $acptip");
1069 # Check address with TCP-wrappers
1070 if (!hosts_ctl($config{'pam'}, STRING_UNKNOWN,
1071 $acptip, STRING_UNKNOWN)) {
1072 &http_error(403, "Access denied for $acptip");
1076 print DEBUG "handle_request: passed IP checks\n";
1078 # Compute a timeout for the start of headers, based on the number of
1079 # child processes. As this increases, we use a shorter timeout to avoid
1080 # an attacker overloading the system.
1081 local $header_timeout = 60 + ($config{'maxconns'} - @childpids) * 10;
1083 # Wait at most 60 secs for start of headers for initial requests, or
1084 # 10 minutes for kept-alive connections
1086 vec($rmask, fileno(SOCK), 1) = 1;
1087 local $to = $checked_timeout ? 10*60 : $header_timeout;
1088 local $sel = select($rmask, undef, undef, $to);
1090 if ($checked_timeout) {
1091 print DEBUG "handle_request: exiting due to timeout of $to\n";
1095 &http_error(400, "Timeout",
1096 "Waited for that $to seconds for start of headers");
1100 print DEBUG "handle_request: passed timeout check\n";
1102 # Read the HTTP request and headers
1103 local $origreqline = &read_line();
1104 ($reqline = $origreqline) =~ s/\r|\n//g;
1105 $method = $page = $request_uri = undef;
1106 print DEBUG "handle_request reqline=$reqline\n";
1107 if (!$reqline && (!$use_ssl || $checked_timeout > 1)) {
1108 # An empty request .. just close the connection
1109 print DEBUG "handle_request: rejecting empty request\n";
1112 elsif ($reqline !~ /^(\S+)\s+(.*)\s+HTTP\/1\..$/) {
1113 print DEBUG "handle_request: invalid reqline=$reqline\n";
1115 # This could be an http request when it should be https
1117 local $url = $config{'musthost'} ?
1118 "https://$config{'musthost'}:$port/" :
1119 "https://$host:$port/";
1120 if ($config{'ssl_redirect'}) {
1121 # Just re-direct to the correct URL
1122 sleep(1); # Give browser a change to finish
1123 # sending its request
1124 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1125 &write_data("Date: $datestr\r\n");
1126 &write_data("Server: $config{'server'}\r\n");
1127 &write_data("Location: $url\r\n");
1128 &write_keep_alive(0);
1129 &write_data("\r\n");
1133 # Tell user the correct URL
1134 &http_error(200, "Bad Request", "This web server is running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1137 elsif (ord(substr($reqline, 0, 1)) == 128 && !$use_ssl) {
1138 # This could be an https request when it should be http ..
1139 # need to fake a HTTP response
1142 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
1143 eval "Net::SSLeay::load_error_strings()";
1144 $ssl_ctx = Net::SSLeay::CTX_new();
1145 Net::SSLeay::CTX_use_RSAPrivateKey_file(
1146 $ssl_ctx, $config{'keyfile'},
1147 &Net::SSLeay::FILETYPE_PEM);
1148 Net::SSLeay::CTX_use_certificate_file(
1150 $config{'certfile'} || $config{'keyfile'},
1151 &Net::SSLeay::FILETYPE_PEM);
1152 $ssl_con = Net::SSLeay::new($ssl_ctx);
1156 select(SSLw); $| = 1; select(STDOUT);
1157 print SSLw $origreqline;
1159 while(sysread(SOCK, $buf, 1) > 0) {
1166 Net::SSLeay::set_wfd($ssl_con, fileno(SOCK));
1167 Net::SSLeay::set_rfd($ssl_con, fileno(SSLr));
1168 Net::SSLeay::accept($ssl_con) || die "accept() failed";
1170 local $url = $config{'musthost'} ?
1171 "https://$config{'musthost'}:$port/" :
1172 "https://$host:$port/";
1173 if ($config{'ssl_redirect'}) {
1174 # Just re-direct to the correct URL
1175 sleep(1); # Give browser a change to
1176 # finish sending its request
1177 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1178 &write_data("Date: $datestr\r\n");
1179 &write_data("Server: $config{'server'}\r\n");
1180 &write_data("Location: $url\r\n");
1181 &write_keep_alive(0);
1182 &write_data("\r\n");
1186 # Tell user the correct URL
1187 &http_error(200, "Bad Request", "This web server is not running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1191 &http_error(400, "Bad Request");
1195 &http_error(400, "Bad Request");
1199 $request_uri = $page = $2;
1203 ($headline = &read_line()) =~ s/\r|\n//g;
1204 last if ($headline eq "");
1205 print DEBUG "handle_request: got headline $headline\n";
1206 if ($headline =~ /^(\S+):\s*(.*)$/) {
1207 $header{$lastheader = lc($1)} = $2;
1209 elsif ($headline =~ /^\s+(.*)$/) {
1210 $header{$lastheader} .= $headline;
1213 &http_error(400, "Bad Header $headline");
1216 if (defined($header{'host'})) {
1217 if ($header{'host'} =~ /^([^:]+):([0-9]+)$/) {
1218 ($host, $port) = ($1, $2);
1221 $host = $header{'host'};
1223 if ($config{'musthost'} && $host ne $config{'musthost'}) {
1224 # Disallowed hostname used
1225 &http_error(400, "Invalid HTTP hostname");
1229 if ($page =~ /^([^\?]+)\?(.*)$/) {
1230 # There is some query string information
1233 print DEBUG "handle_request: querystring=$querystring\n";
1234 if ($querystring !~ /=/) {
1235 $queryargs = $querystring;
1236 $queryargs =~ s/\+/ /g;
1237 $queryargs =~ s/%(..)/pack("c",hex($1))/ge;
1241 # Parse query-string parameters
1242 local @in = split(/\&/, $querystring);
1244 local ($k, $v) = split(/=/, $i, 2);
1245 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1246 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1251 $posted_data = undef;
1252 if ($method eq 'POST' &&
1253 $header{'content-type'} eq 'application/x-www-form-urlencoded') {
1254 # Read in posted query string information, up the configured maximum
1255 # post request length
1256 $clen = $header{"content-length"};
1257 $clen_read = $clen > $config{'max_post'} ? $config{'max_post'} : $clen;
1258 while(length($posted_data) < $clen_read) {
1259 $buf = &read_data($clen_read - length($posted_data));
1260 if (!length($buf)) {
1261 &http_error(500, "Failed to read POST request");
1263 chomp($posted_data);
1264 $posted_data =~ s/\015$//mg;
1265 $posted_data .= $buf;
1267 print DEBUG "clen_read=$clen_read clen=$clen posted_data=",length($posted_data),"\n";
1268 if ($clen_read != $clen && length($posted_data) > $clen) {
1269 # If the client sent more data than we asked for, chop the
1271 $posted_data = substr($posted_data, 0, $clen);
1273 if (length($posted_data) > $clen) {
1274 # When the client sent too much, delay so that it gets headers
1277 if ($header{'user-agent'} =~ /MSIE/ &&
1278 $header{'user-agent'} !~ /Opera/i) {
1279 # MSIE includes an extra newline in the data
1280 $posted_data =~ s/\r|\n//g;
1282 local @in = split(/\&/, $posted_data);
1284 local ($k, $v) = split(/=/, $i, 2);
1286 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1287 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1290 print DEBUG "handle_request: posted_data=$posted_data\n";
1293 # replace %XX sequences in page
1294 $page =~ s/%(..)/pack("c",hex($1))/ge;
1296 # Check if the browser's user agent indicates a mobile device
1297 $mobile_device = &is_mobile_useragent($header{'user-agent'});
1299 # Check if Host: header is for a mobile URL
1300 foreach my $m (@mobile_prefixes) {
1301 if ($header{'host'} =~ /^\Q$m\E/i) {
1306 # check for the logout flag file, and if existant deny authentication
1307 if ($config{'logout'} && -r $config{'logout'}.$in{'miniserv_logout_id'}) {
1308 print DEBUG "handle_request: logout flag set\n";
1309 $deny_authentication++;
1310 open(LOGOUT, $config{'logout'}.$in{'miniserv_logout_id'});
1311 chop($count = <LOGOUT>);
1315 open(LOGOUT, ">$config{'logout'}$in{'miniserv_logout_id'}");
1316 print LOGOUT "$count\n";
1320 unlink($config{'logout'}.$in{'miniserv_logout_id'});
1324 # check for any redirect for the requested URL
1325 foreach my $pfx (@strip_prefix) {
1326 my $l = length($pfx);
1327 if(length($page) >= $l &&
1328 substr($page,0,$l) eq $pfx) {
1329 $page=substr($page,$l);
1333 $simple = &simplify_path($page, $bogus);
1335 $rpath .= "&".$querystring if (defined($querystring));
1336 $redir = $redirect{$rpath};
1337 if (defined($redir)) {
1338 print DEBUG "handle_request: redir=$redir\n";
1339 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1340 &write_data("Date: $datestr\r\n");
1341 &write_data("Server: $config{'server'}\r\n");
1342 local $ssl = $use_ssl || $config{'inetd_ssl'};
1343 $portstr = $port == 80 && !$ssl ? "" :
1344 $port == 443 && $ssl ? "" : ":$port";
1345 $prot = $ssl ? "https" : "http";
1346 &write_data("Location: $prot://$host$portstr$redir\r\n");
1347 &write_keep_alive(0);
1348 &write_data("\r\n");
1352 # Check for a DAV request
1354 foreach my $d (@davpaths) {
1355 if ($simple eq $d || $simple =~ /^\Q$d\E\//) {
1360 if (!$davpath && ($method eq "SEARCH" || $method eq "PUT")) {
1361 &http_error(400, "Bad Request method $method");
1364 # Check for password if needed
1366 print DEBUG "handle_request: Need authentication\n";
1370 # Session authentication is never used for connections by
1371 # another webmin server, or for specified pages, or for DAV, or XMLRPC,
1372 # or mobile browsers if requested.
1373 if ($header{'user-agent'} =~ /webmin/i ||
1374 $header{'user-agent'} =~ /$config{'agents_nosession'}/i ||
1375 $sessiononly{$simple} || $davpath ||
1376 $simple eq "/xmlrpc.cgi" ||
1377 $acptip eq $config{'host_nosession'} ||
1378 $mobile_device && $config{'mobile_nosession'}) {
1379 print DEBUG "handle_request: Forcing HTTP authentication\n";
1380 $config{'session'} = 0;
1383 # check for SSL authentication
1384 if ($use_ssl && $verified_client) {
1385 $peername = Net::SSLeay::X509_NAME_oneline(
1386 Net::SSLeay::X509_get_subject_name(
1387 Net::SSLeay::get_peer_certificate(
1389 local $peername2 = $peername;
1390 $peername2 =~ s/Email=/emailAddress=/ ||
1391 $peername2 =~ s/emailAddress=/Email=/;
1392 foreach $u (keys %certs) {
1393 if ($certs{$u} eq $peername ||
1394 $certs{$u} eq $peername2) {
1397 #syslog("info", "%s", "SSL login as $authuser from $acpthost") if ($use_syslog);
1401 if ($use_syslog && !$validated) {
1402 syslog("crit", "%s",
1403 "Unknown SSL certificate $peername");
1407 if (!$validated && !$deny_authentication) {
1408 # check for IP-based authentication
1410 foreach $a (keys %ipaccess) {
1411 if ($acptip eq $a) {
1412 # It does! Auth as the user
1414 $baseauthuser = $authuser =
1420 # Check for normal HTTP authentication
1421 if (!$validated && !$deny_authentication && !$config{'session'} &&
1422 $header{authorization} =~ /^basic\s+(\S+)$/i) {
1423 # authorization given..
1424 ($authuser, $authpass) = split(/:/, &b64decode($1), 2);
1425 print DEBUG "handle_request: doing basic auth check authuser=$authuser authpass=$authpass\n";
1426 local ($vu, $expired, $nonexist) =
1427 &validate_user($authuser, $authpass, $host);
1428 print DEBUG "handle_request: vu=$vu expired=$expired nonexist=$nonexist\n";
1429 if ($vu && (!$expired || $config{'passwd_mode'} == 1)) {
1436 if ($use_syslog && !$validated) {
1437 syslog("crit", "%s",
1438 ($nonexist ? "Non-existent" :
1439 $expired ? "Expired" : "Invalid").
1440 " login as $authuser from $acpthost");
1442 if ($authuser =~ /\r|\n|\s/) {
1443 &http_error(500, "Invalid username",
1444 "Username contains invalid characters");
1446 if ($authpass =~ /\r|\n/) {
1447 &http_error(500, "Invalid password",
1448 "Password contains invalid characters");
1451 if ($config{'passdelay'} && !$config{'inetd'}) {
1452 # check with main process for delay
1453 print DEBUG "handle_request: about to ask for password delay\n";
1454 print $PASSINw "delay $authuser $acptip $validated\n";
1455 <$PASSOUTr> =~ /(\d+) (\d+)/;
1457 print DEBUG "handle_request: password delay $1 $2\n";
1462 # Check for a visit to the special session login page
1463 if ($config{'session'} && !$deny_authentication &&
1464 $page eq $config{'session_login'}) {
1465 if ($in{'logout'} && $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1466 # Logout clicked .. remove the session
1468 print $PASSINw "delete $sid\n";
1469 local $louser = <$PASSOUTr>;
1472 $already_session_id = undef;
1473 $authuser = $baseauthuser = undef;
1476 syslog("info", "%s", "Logout by $louser from $acpthost");
1478 &run_logout_script($louser, $sid,
1480 &write_logout_utmp($louser, $actphost);
1485 if ($in{'user'} =~ /\r|\n|\s/) {
1486 &http_error(500, "Invalid username",
1487 "Username contains invalid characters");
1489 if ($in{'pass'} =~ /\r|\n/) {
1490 &http_error(500, "Invalid password",
1491 "Password contains invalid characters");
1494 local ($vu, $expired, $nonexist) =
1495 &validate_user($in{'user'}, $in{'pass'}, $host);
1496 local $hrv = &handle_login(
1497 $vu || $in{'user'}, $vu ? 1 : 0,
1498 $expired, $nonexist, $in{'pass'},
1499 $in{'notestingcookie'});
1500 return $hrv if (defined($hrv));
1504 # Check for a visit to the special PAM login page
1505 if ($config{'session'} && !$deny_authentication &&
1506 $use_pam && $config{'pam_conv'} && $page eq $config{'pam_login'} &&
1508 # A question has been entered .. submit it to the main process
1509 print DEBUG "handle_request: Got call to $page ($in{'cid'})\n";
1510 print DEBUG "handle_request: For PAM, authuser=$authuser\n";
1511 if ($in{'answer'} =~ /\r|\n/ || $in{'cid'} =~ /\r|\n|\s/) {
1512 &http_error(500, "Invalid response",
1513 "Response contains invalid characters");
1517 # Start of a new conversation - answer must be username
1518 $cid = &generate_random_id($in{'answer'});
1519 print $PASSINw "pamstart $cid $host $in{'answer'}\n";
1522 # A response to a previous question
1524 print $PASSINw "pamanswer $cid $in{'answer'}\n";
1527 # Read back the response, and the next question (if any)
1528 local $line = <$PASSOUTr>;
1529 $line =~ s/\r|\n//g;
1530 local ($rv, $question) = split(/\s+/, $line, 2);
1533 local $hrv = &handle_login(
1534 $in{'answer'} || "unknown", 0, 0, 1, undef);
1535 return $hrv if (defined($hrv));
1537 elsif ($rv == 1 || $rv == 3) {
1538 # Another question .. force use of PAM CGI
1541 $querystring .= "&cid=$cid&question=".
1543 $querystring .= "&password=1" if ($rv == 3);
1545 $page = $config{'pam_login'};
1546 $miniserv_internal = 1;
1550 # Got back a final ok or failure
1551 local ($user, $ok, $expired, $nonexist) =
1552 split(/\s+/, $question);
1553 local $hrv = &handle_login(
1554 $user, $ok, $expired, $nonexist, undef,
1555 $in{'notestingcookie'});
1556 return $hrv if (defined($hrv));
1559 # A message from PAM .. tell the user
1562 $querystring .= "&cid=$cid&message=".
1565 $page = $config{'pam_login'};
1566 $miniserv_internal = 1;
1571 # Check for a visit to the special password change page
1572 if ($config{'session'} && !$deny_authentication &&
1573 $page eq $config{'password_change'} && !$validated) {
1574 # Just let this slide ..
1576 $miniserv_internal = 3;
1579 # Check for an existing session
1580 if ($config{'session'} && !$validated) {
1581 if ($already_session_id) {
1582 $session_id = $already_session_id;
1583 $authuser = $already_authuser;
1586 elsif (!$deny_authentication &&
1587 $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1589 local $notimeout = $in{'webmin_notimeout'} ? 1 : 0;
1590 print $PASSINw "verify $session_id $notimeout\n";
1591 <$PASSOUTr> =~ /(\d+)\s+(\S+)/;
1593 # Valid session continuation
1596 #$already_session_id = $session_id;
1597 $already_authuser = $authuser;
1604 # Invalid session ID .. don't set verified
1609 # Check for local authentication
1610 if ($localauth_user && !$header{'x-forwarded-for'} && !$header{'via'}) {
1611 if (defined($users{$localauth_user})) {
1612 # Local user exists in webmin users file
1614 $authuser = $localauth_user;
1617 # Check if local user is allowed by unixauth
1618 local @can = &can_user_login($localauth_user,
1622 $authuser = $localauth_user;
1625 $localauth_user = undef;
1631 # Check if this path allows anonymous access
1633 foreach $a (keys %anonymous) {
1634 if (substr($simple, 0, length($a)) eq $a) {
1635 # It does! Auth as the user, if IP access
1636 # control allows him.
1637 if (&check_user_ip($anonymous{$a}) &&
1638 &check_user_time($anonymous{$a})) {
1640 $baseauthuser = $authuser =
1648 # Check if this path allows unauthenticated access
1649 local ($u, $unauth);
1650 foreach $u (@unauth) {
1651 $unauth++ if ($simple =~ /$u/);
1653 if (!$bogus && $unauth) {
1654 # Unauthenticated directory or file request - approve it
1656 $baseauthuser = $authuser = undef;
1661 if ($blocked == 0) {
1662 # No password given.. ask
1663 if ($config{'pam_conv'} && $use_pam) {
1664 # Force CGI for PAM question, starting with
1665 # the username which is always needed
1668 $querystring .= "&initial=1&question=".
1669 &urlize("Username");
1670 $querystring .= "&failed=$failed_user" if ($failed_user);
1671 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1673 $page = $config{'pam_login'};
1674 $miniserv_internal = 1;
1677 elsif ($config{'session'}) {
1678 # Force CGI for session login
1681 $querystring .= "&logout=1&page=/";
1684 # Re-direct to current module only
1685 local $rpage = $request_uri;
1686 if (!$config{'loginkeeppage'}) {
1687 $rpage =~ s/\?.*$//;
1688 $rpage =~ s/[^\/]+$//
1690 $querystring = "page=".&urlize($rpage);
1693 $querystring .= "&failed=$failed_user" if ($failed_user);
1694 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1696 $page = $config{'session_login'};
1697 $miniserv_internal = 1;
1701 # Ask for login with HTTP authentication
1702 &write_data("HTTP/1.0 401 Unauthorized\r\n");
1703 &write_data("Date: $datestr\r\n");
1704 &write_data("Server: $config{'server'}\r\n");
1705 &write_data("WWW-authenticate: Basic ".
1706 "realm=\"$config{'realm'}\"\r\n");
1707 &write_keep_alive(0);
1708 &write_data("Content-type: text/html\r\n");
1709 &write_data("\r\n");
1710 &reset_byte_count();
1711 &write_data("<html>\n");
1712 &write_data("<head><title>Unauthorized</title></head>\n");
1713 &write_data("<body><h1>Unauthorized</h1>\n");
1714 &write_data("A password is required to access this\n");
1715 &write_data("web server. Please try again. <p>\n");
1716 &write_data("</body></html>\n");
1717 &log_request($acpthost, undef, $reqline, 401, &byte_count());
1721 elsif ($blocked == 1) {
1722 # when the host has been blocked, give it an error
1723 &http_error(403, "Access denied for $acptip. The host ".
1724 "has been blocked because of too ".
1725 "many authentication failures.");
1727 elsif ($blocked == 2) {
1728 # when the user has been blocked, give it an error
1729 &http_error(403, "Access denied. The user ".
1730 "has been blocked because of too ".
1731 "many authentication failures.");
1735 # Get the real Webmin username
1736 local @can = &can_user_login($authuser, undef, $host);
1737 $baseauthuser = $can[3] || $authuser;
1739 if ($config{'remoteuser'} && !$< && $validated) {
1740 # Switch to the UID of the remote user (if he exists)
1741 local @u = getpwnam($authuser);
1742 if (@u && $< != $u[2]) {
1743 $( = $u[3]; $) = "$u[3] $u[3]";
1744 ($>, $<) = ($u[2], $u[2]);
1747 &http_error(500, "Unix user $authuser does not exist");
1753 # Check per-user IP access control
1754 if (!&check_user_ip($baseauthuser)) {
1755 &http_error(403, "Access denied for $acptip");
1759 # Check per-user allowed times
1760 if (!&check_user_time($baseauthuser)) {
1761 &http_error(403, "Access denied at the current time");
1766 # Validate the path, and convert to canonical form
1768 $simple = &simplify_path($page, $bogus);
1769 print DEBUG "handle_request: page=$page simple=$simple\n";
1771 &http_error(400, "Invalid path");
1774 # Check for a DAV request
1776 return &handle_dav_request($davpath);
1779 # Work out the active theme(s)
1780 local $preroots = $mobile_device && defined($config{'mobile_preroot'}) ?
1781 $config{'mobile_preroot'} :
1782 $authuser && defined($config{'preroot_'.$authuser}) ?
1783 $config{'preroot_'.$authuser} :
1784 $authuser && $baseauthuser &&
1785 defined($config{'preroot_'.$baseauthuser}) ?
1786 $config{'preroot_'.$baseauthuser} :
1788 local @preroots = reverse(split(/\s+/, $preroots));
1790 # Canonicalize the directories
1791 foreach my $preroot (@preroots) {
1792 # Always under the current webmin root
1793 $preroot =~ s/^.*\///g;
1794 $preroot = $roots[0].'/'.$preroot;
1797 # Look in the theme root directories first
1798 local ($full, @stfull);
1800 foreach my $preroot (@preroots) {
1803 $full = $preroot.$sofar;
1804 $scriptname = $simple;
1805 foreach $b (split(/\//, $simple)) {
1806 if ($b ne "") { $sofar .= "/$b"; }
1807 $full = $preroot.$sofar;
1808 @stfull = stat($full);
1809 if (!@stfull) { undef($full); last; }
1811 # Check if this is a directory
1813 # It is.. go on parsing
1821 # Check if this is a CGI program
1822 if (&get_type($full) eq "internal/cgi") {
1823 $pathinfo = substr($simple, length($sofar));
1824 $pathinfo .= "/" if ($page =~ /\/$/);
1825 $scriptname = $sofar;
1830 # Don't stop at a directory unless this is the last theme, which
1831 # is the 'real' one that provides the .cgi scripts
1832 if ($is_directory && $preroot ne $preroots[$#preroots]) {
1839 $cgi_pwd = $roots[0];
1841 elsif ($is_directory) {
1842 $cgi_pwd = "$roots[0]$sofar";
1845 "$roots[0]$sofar" =~ /^(.*\/)[^\/]+$/;
1848 $foundroot = $preroot;
1849 if ($is_directory) {
1850 # Check for index files in the directory
1852 foreach $idx (split(/\s+/, $config{"index_docs"})) {
1853 $idxfull = "$full/$idx";
1854 local @stidxfull = stat($idxfull);
1855 if (-r _ && !-d _) {
1857 @stfull = @stidxfull;
1860 if ($scriptname ne "/");
1865 @stfull = stat($full) if (!$foundidx);
1868 last if ($foundroot);
1870 print DEBUG "handle_request: initial full=$full\n";
1872 # Look in the real root directories, stopping when we find a file or directory
1873 if (!$full || $is_directory) {
1874 ROOT: foreach $root (@roots) {
1876 $full = $root.$sofar;
1877 $scriptname = $simple;
1878 foreach $b ($simple eq "/" ? ( "" ) : split(/\//, $simple)) {
1879 if ($b ne "") { $sofar .= "/$b"; }
1880 $full = $root.$sofar;
1881 @stfull = stat($full);
1886 # Check if this is a directory
1888 # It is.. go on parsing
1892 # Check if this is a CGI program
1893 if (&get_type($full) eq "internal/cgi") {
1894 $pathinfo = substr($simple, length($sofar));
1895 $pathinfo .= "/" if ($page =~ /\/$/);
1896 $scriptname = $sofar;
1901 # Run CGI in the same directory as whatever file
1903 $full =~ /^(.*\/)[^\/]+$/; $cgi_pwd = $1;
1912 if (!@stfull) { &http_error(404, "File not found"); }
1914 print DEBUG "handle_request: full=$full\n";
1915 @stfull = stat($full) if (!@stfull);
1917 # check filename against denyfile regexp
1918 local $denyfile = $config{'denyfile'};
1919 if ($denyfile && $full =~ /$denyfile/) {
1920 &http_error(403, "Access denied to $page");
1924 # Reached the end of the path OK.. see what we've got
1926 # See if the URL ends with a / as it should
1927 print DEBUG "handle_request: found a directory\n";
1928 if ($page !~ /\/$/) {
1929 # It doesn't.. redirect
1930 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1931 $ssl = $use_ssl || $config{'inetd_ssl'};
1932 $portstr = $port == 80 && !$ssl ? "" :
1933 $port == 443 && $ssl ? "" : ":$port";
1934 &write_data("Date: $datestr\r\n");
1935 &write_data("Server: $config{server}\r\n");
1936 $prot = $ssl ? "https" : "http";
1937 &write_data("Location: $prot://$host$portstr$page/\r\n");
1938 &write_keep_alive(0);
1939 &write_data("\r\n");
1940 &log_request($acpthost, $authuser, $reqline, 302, 0);
1943 # A directory.. check for index files
1945 foreach $idx (split(/\s+/, $config{"index_docs"})) {
1946 $idxfull = "$full/$idx";
1947 @stidxfull = stat($idxfull);
1948 if (-r _ && !-d _) {
1951 @stfull = @stidxfull;
1952 $scriptname .= "/" if ($scriptname ne "/");
1957 @stfull = stat($full) if (!$foundidx);
1960 # This is definately a directory.. list it
1961 print DEBUG "handle_request: listing directory\n";
1962 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
1963 "Date: $datestr\r\n".
1964 "Server: $config{server}\r\n".
1965 "Content-type: text/html\r\n";
1967 &write_keep_alive(0);
1968 &write_data("\r\n");
1969 &reset_byte_count();
1970 &write_data("<h1>Index of $simple</h1>\n");
1971 &write_data("<pre>\n");
1972 &write_data(sprintf "%-35.35s %-20.20s %-10.10s\n",
1973 "Name", "Last Modified", "Size");
1974 &write_data("<hr>\n");
1975 opendir(DIR, $full);
1976 while($df = readdir(DIR)) {
1977 if ($df =~ /^\./) { next; }
1978 $fulldf = $full eq "/" ? $full.$df : $full."/".$df;
1979 (@stbuf = stat($fulldf)) || next;
1980 if (-d _) { $df .= "/"; }
1981 @tm = localtime($stbuf[9]);
1982 $fdate = sprintf "%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d",
1983 $tm[3],$tm[4]+1,$tm[5]+1900,
1984 $tm[0],$tm[1],$tm[2];
1985 $len = length($df); $rest = " "x(35-$len);
1987 "<a href=\"%s\">%-${len}.${len}s</a>$rest %-20.20s %-10.10s\n",
1988 $df, $df, $fdate, $stbuf[7]);
1991 &log_request($acpthost, $authuser, $reqline, $ok_code, &byte_count());
1995 # CGI or normal file
1997 if (&get_type($full) eq "internal/cgi" && $validated != 4) {
1998 # A CGI program to execute
1999 print DEBUG "handle_request: executing CGI\n";
2000 $envtz = $ENV{"TZ"};
2001 $envuser = $ENV{"USER"};
2002 $envpath = $ENV{"PATH"};
2003 $envlang = $ENV{"LANG"};
2004 $envroot = $ENV{"SystemRoot"};
2005 foreach my $k (keys %ENV) {
2008 $ENV{"PATH"} = $envpath if ($envpath);
2009 $ENV{"TZ"} = $envtz if ($envtz);
2010 $ENV{"USER"} = $envuser if ($envuser);
2011 $ENV{"OLD_LANG"} = $envlang if ($envlang);
2012 $ENV{"SystemRoot"} = $envroot if ($envroot);
2013 $ENV{"HOME"} = $user_homedir;
2014 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
2015 $ENV{"SERVER_NAME"} = $host;
2016 $ENV{"SERVER_ADMIN"} = $config{"email"};
2017 $ENV{"SERVER_ROOT"} = $roots[0];
2018 $ENV{"SERVER_REALROOT"} = $realroot;
2019 $ENV{"SERVER_PORT"} = $port;
2020 $ENV{"REMOTE_HOST"} = $acpthost;
2021 $ENV{"REMOTE_ADDR"} = $acptip;
2022 $ENV{"REMOTE_USER"} = $authuser;
2023 $ENV{"BASE_REMOTE_USER"} = $authuser ne $baseauthuser ?
2024 $baseauthuser : undef;
2025 $ENV{"REMOTE_PASS"} = $authpass if (defined($authpass) &&
2026 $config{'pass_password'});
2027 print DEBUG "REMOTE_USER = ",$ENV{"REMOTE_USER"},"\n";
2028 print DEBUG "BASE_REMOTE_USER = ",$ENV{"BASE_REMOTE_USER"},"\n";
2029 $ENV{"SSL_USER"} = $peername if ($validated == 2);
2030 $ENV{"ANONYMOUS_USER"} = "1" if ($validated == 3 || $validated == 4);
2031 $ENV{"DOCUMENT_ROOT"} = $roots[0];
2032 $ENV{"DOCUMENT_REALROOT"} = $realroot;
2033 $ENV{"GATEWAY_INTERFACE"} = "CGI/1.1";
2034 $ENV{"SERVER_PROTOCOL"} = "HTTP/1.0";
2035 $ENV{"REQUEST_METHOD"} = $method;
2036 $ENV{"SCRIPT_NAME"} = $scriptname;
2037 $ENV{"SCRIPT_FILENAME"} = $full;
2038 $ENV{"REQUEST_URI"} = $request_uri;
2039 $ENV{"PATH_INFO"} = $pathinfo;
2041 $ENV{"PATH_TRANSLATED"} = "$roots[0]$pathinfo";
2042 $ENV{"PATH_REALTRANSLATED"} = "$realroot$pathinfo";
2044 $ENV{"QUERY_STRING"} = $querystring;
2045 $ENV{"MINISERV_CONFIG"} = $config_file;
2046 $ENV{"HTTPS"} = "ON" if ($use_ssl || $config{'inetd_ssl'});
2047 $ENV{"SESSION_ID"} = $session_id if ($session_id);
2048 $ENV{"LOCAL_USER"} = $localauth_user if ($localauth_user);
2049 $ENV{"MINISERV_INTERNAL"} = $miniserv_internal if ($miniserv_internal);
2050 if (defined($header{"content-length"})) {
2051 $ENV{"CONTENT_LENGTH"} = $header{"content-length"};
2053 if (defined($header{"content-type"})) {
2054 $ENV{"CONTENT_TYPE"} = $header{"content-type"};
2056 foreach $h (keys %header) {
2057 ($hname = $h) =~ tr/a-z/A-Z/;
2059 $ENV{"HTTP_$hname"} = $header{$h};
2061 $ENV{"PWD"} = $cgi_pwd;
2062 foreach $k (keys %config) {
2063 if ($k =~ /^env_(\S+)$/) {
2064 $ENV{$1} = $config{$k};
2067 delete($ENV{'HTTP_AUTHORIZATION'});
2068 $ENV{'HTTP_COOKIE'} =~ s/;?\s*$sidname=([a-f0-9]+)//;
2069 $ENV{'MOBILE_DEVICE'} = 1 if ($mobile_device);
2071 # Check if the CGI can be handled internally
2073 local $first = <CGI>;
2075 $first =~ s/[#!\r\n]//g;
2076 $nph_script = ($full =~ /\/nph-([^\/]+)$/);
2078 if (!$config{'forkcgis'} &&
2079 ($first eq $perl_path || $first eq $linked_perl_path) &&
2081 $config{'internalcgis'}) {
2082 # setup environment for eval
2084 @ARGV = split(/\s+/, $queryargs);
2087 # Already read the post input
2088 $postinput = $posted_data;
2090 $clen = $header{"content-length"};
2091 $SIG{'CHLD'} = 'DEFAULT';
2093 # Have SOCK closed if the perl exec's something
2095 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
2099 if ($config{'log'}) {
2100 open(MINISERVLOG, ">>$config{'logfile'}");
2101 if ($config{'logperms'}) {
2102 chmod(oct($config{'logperms'}),
2103 $config{'logfile'});
2106 chmod(0600, $config{'logfile'});
2110 $main_process_id = $$;
2112 if ($full =~ /^\Q$foundroot\E\/([^\/]+)\//) {
2113 # Eval in package from Webmin module name
2115 $pkg =~ s/[^A-Za-z0-9]/_/g;
2120 tie(*STDOUT, 'miniserv');
2121 tie(*STDIN, 'miniserv');
2122 do \$miniserv::full;
2128 &http_error(500, "Perl execution failed",
2129 $config{'noshowstderr'} ? undef : $@);
2131 elsif (!$doneheaders && !$nph_script) {
2132 &http_error(500, "Missing Headers");
2139 # fork the process that actually executes the CGI
2140 pipe(CGIINr, CGIINw);
2141 pipe(CGIOUTr, CGIOUTw);
2142 pipe(CGIERRr, CGIERRw);
2143 if (!($cgipid = fork())) {
2144 @execargs = ( $full, split(/\s+/, $queryargs) );
2147 open(STDIN, "<&CGIINr");
2148 open(STDOUT, ">&CGIOUTw");
2149 open(STDERR, ">&CGIERRw");
2150 close(CGIINw); close(CGIOUTr); close(CGIERRr);
2152 die "Failed to exec $full : $!\n";
2155 close(CGIINr); close(CGIOUTw); close(CGIERRw);
2158 # write CGI input to a temp file
2159 $infile = "$config{'tempbase'}.$$";
2160 open(CGIINw, ">$infile");
2161 # NOT binary mode, as CGIs don't read in it!
2166 # already read the posted data
2167 print CGIINw $posted_data;
2169 $clen = $header{"content-length"};
2170 if ($method eq "POST" && $clen_read < $clen) {
2171 $SIG{'PIPE'} = 'IGNORE';
2173 while($got < $clen) {
2174 $buf = &read_data($clen-$got);
2175 if (!length($buf)) {
2176 kill('TERM', $cgipid);
2177 unlink($infile) if ($infile);
2178 &http_error(500, "Failed to read ".
2181 $got += length($buf);
2182 local ($wrote) = (print CGIINw $buf);
2185 # If the CGI terminated early, we still need to read
2186 # from the browser and throw away
2187 while($got < $clen) {
2188 $buf = &read_data($clen-$got);
2189 if (!length($buf)) {
2190 kill('TERM', $cgipid);
2191 unlink($infile) if ($infile);
2192 &http_error(500, "Failed to read ".
2195 $got += length($buf);
2197 $SIG{'PIPE'} = 'DEFAULT';
2203 # Run the CGI program, and feed it input
2205 local $qqueryargs = join(" ", map { "\"$_\"" }
2206 split(/\s+/, $queryargs));
2207 if ($first =~ /(perl|perl.exe)$/i) {
2208 # On Windows, run with Perl
2209 open(CGIOUTr, "$perl_path \"$full\" $qqueryargs <$infile |");
2212 open(CGIOUTr, "\"$full\" $qqueryargs <$infile |");
2218 # read back cgi headers
2219 select(CGIOUTr); $|=1; select(STDOUT);
2223 $line =~ s/\r|\n//g;
2225 if ($got_blank || %cgiheader) { last; }
2229 if ($line !~ /^(\S+):\s+(.*)$/) {
2230 $errs = &read_errors(CGIERRr);
2231 close(CGIOUTr); close(CGIERRr);
2232 unlink($infile) if ($infile);
2233 &http_error(500, "Bad Header", $errs);
2235 $cgiheader{lc($1)} = $2;
2236 push(@cgiheader, [ $1, $2 ]);
2238 if ($cgiheader{"location"}) {
2239 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2240 &write_data("Date: $datestr\r\n");
2241 &write_data("Server: $config{'server'}\r\n");
2242 &write_keep_alive(0);
2243 # ignore the rest of the output. This is a hack,
2244 # but is necessary for IE in some cases :(
2245 close(CGIOUTr); close(CGIERRr);
2247 elsif ($cgiheader{"content-type"} eq "") {
2248 close(CGIOUTr); close(CGIERRr);
2249 unlink($infile) if ($infile);
2250 $errs = &read_errors(CGIERRr);
2251 &http_error(500, "Missing Content-Type Header",
2252 $config{'noshowstderr'} ? undef : $errs);
2255 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2256 &write_data("Date: $datestr\r\n");
2257 &write_data("Server: $config{'server'}\r\n");
2258 &write_keep_alive(0);
2260 foreach $h (@cgiheader) {
2261 &write_data("$h->[0]: $h->[1]\r\n");
2263 &write_data("\r\n");
2265 &reset_byte_count();
2266 while($line = <CGIOUTr>) {
2271 unlink($infile) if ($infile);
2277 print DEBUG "handle_request: outputting file\n";
2278 open(FILE, $full) || &http_error(404, "Failed to open file");
2280 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2281 "Date: $datestr\r\n".
2282 "Server: $config{server}\r\n".
2283 "Content-type: ".&get_type($full)."\r\n".
2284 "Content-length: $stfull[7]\r\n".
2285 "Last-Modified: ".&http_date($stfull[9])."\r\n".
2286 "Expires: ".&http_date(time()+$config{'expires'})."\r\n";
2288 $rv = &write_keep_alive();
2289 &write_data("\r\n");
2290 &reset_byte_count();
2291 while(read(FILE, $buf, 1024) > 0) {
2298 &log_request($acpthost, $authuser, $reqline,
2299 $logged_code ? $logged_code :
2300 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2304 # http_error(code, message, body, [dontexit])
2307 local $eh = $error_handler_recurse ? undef :
2308 $config{"error_handler_$_[0]"} ? $config{"error_handler_$_[0]"} :
2309 $config{'error_handler'} ? $config{'error_handler'} : undef;
2310 print DEBUG "http_error code=$_[0] message=$_[1] body=$_[2]\n";
2312 # Call a CGI program for the error
2314 $querystring = "code=$_[0]&message=".&urlize($_[1]).
2315 "&body=".&urlize($_[2]);
2316 $error_handler_recurse++;
2318 $ok_message = $_[1];
2322 # Use the standard error message display
2323 &write_data("HTTP/1.0 $_[0] $_[1]\r\n");
2324 &write_data("Server: $config{server}\r\n");
2325 &write_data("Date: $datestr\r\n");
2326 &write_data("Content-type: text/html\r\n");
2327 &write_keep_alive(0);
2328 &write_data("\r\n");
2329 &reset_byte_count();
2330 &write_data("<h1>Error - $_[1]</h1>\n");
2332 &write_data("<pre>$_[2]</pre>\n");
2335 &log_request($acpthost, $authuser, $reqline, $_[0], &byte_count())
2337 &log_error($_[1], $_[2] ? " : $_[2]" : "");
2344 if ($_[0] =~ /\.([A-z0-9]+)$/) {
2350 return "text/plain";
2353 # simplify_path(path, bogus)
2354 # Given a path, maybe containing stuff like ".." and "." convert it to a
2355 # clean, absolute form.
2358 local($dir, @bits, @fixedbits, $b);
2360 $dir =~ s/\\/\//g; # fix windows \ in path
2363 $dir =~ s/\0//g; # remove null bytes
2364 @bits = split(/\/+/, $dir);
2367 foreach $b (@bits) {
2371 elsif ($b eq ".." || $b eq "...") {
2373 if (scalar(@fixedbits) == 0) {
2381 push(@fixedbits, $b);
2384 return "/" . join('/', @fixedbits);
2388 # Converts a string from base64 format to normal
2391 local($str) = $_[0];
2393 $str =~ tr|A-Za-z0-9+=/||cd;
2395 $str =~ tr|A-Za-z0-9+/| -_|;
2396 while ($str =~ /(.{1,60})/gs) {
2397 my $len = chr(32 + length($1)*3/4);
2398 $res .= unpack("u", $len . $1 );
2403 # ip_match(remoteip, localip, [match]+)
2404 # Checks an IP address against a list of IPs, networks and networks/masks
2407 local(@io, @mo, @ms, $i, $j, $hn, $needhn);
2408 @io = split(/\./, $_[0]);
2409 for($i=2; $i<@_; $i++) {
2410 $needhn++ if ($_[$i] =~ /^\*(\S+)$/);
2412 if ($needhn && !defined($hn = $ip_match_cache{$_[0]})) {
2413 $hn = gethostbyaddr(inet_aton($_[0]), AF_INET);
2414 $hn = "" if (&to_ipaddress($hn) ne $_[0]);
2415 $ip_match_cache{$_[0]} = $hn;
2417 for($i=2; $i<@_; $i++) {
2418 local $mismatch = 0;
2419 if ($_[$i] =~ /^(\S+)\/(\d+)$/) {
2420 # Convert CIDR to netmask format
2421 $_[$i] = $1."/".&prefix_to_mask($2);
2423 if ($_[$i] =~ /^(\S+)\/(\S+)$/) {
2424 # Compare with network/mask
2425 @mo = split(/\./, $1); @ms = split(/\./, $2);
2426 for($j=0; $j<4; $j++) {
2427 if ((int($io[$j]) & int($ms[$j])) != int($mo[$j])) {
2432 elsif ($_[$i] =~ /^\*(\S+)$/) {
2433 # Compare with hostname regexp
2434 $mismatch = 1 if ($hn !~ /$1$/);
2436 elsif ($_[$i] eq 'LOCAL') {
2437 # Compare with local network
2438 local @lo = split(/\./, $_[1]);
2440 $mismatch = 1 if ($lo[0] != $io[0]);
2442 elsif ($lo[0] < 192) {
2443 $mismatch = 1 if ($lo[0] != $io[0] ||
2447 $mismatch = 1 if ($lo[0] != $io[0] ||
2452 elsif ($_[$i] !~ /^[0-9\.]+$/) {
2453 # Compare with hostname
2454 $mismatch = 1 if ($_[0] ne &to_ipaddress($_[$i]));
2457 # Compare with IP or network
2458 @mo = split(/\./, $_[$i]);
2459 while(@mo && !$mo[$#mo]) { pop(@mo); }
2460 for($j=0; $j<@mo; $j++) {
2461 if ($mo[$j] != $io[$j]) {
2466 return 1 if (!$mismatch);
2471 # users_match(&uinfo, user, ...)
2472 # Returns 1 if a user is in a list of users and groups
2475 local $uinfo = shift(@_);
2477 local @ginfo = getgrgid($uinfo->[3]);
2479 if ($u =~ /^\@(\S+)$/) {
2480 return 1 if (&is_group_member($uinfo, $1));
2482 elsif ($u =~ /^(\d*)-(\d*)$/ && ($1 || $2)) {
2483 return (!$1 || $uinfo[2] >= $1) &&
2484 (!$2 || $uinfo[2] <= $2);
2487 return 1 if ($u eq $uinfo->[0]);
2493 # restart_miniserv()
2494 # Called when a SIGHUP is received to restart the web server. This is done
2495 # by exec()ing perl with the same command line as was originally used
2496 sub restart_miniserv
2498 print STDERR "restarting miniserv\n";
2499 &log_error("Restarting");
2501 &close_all_sockets();
2503 dbmclose(%sessiondb);
2504 kill('KILL', $logclearer) if ($logclearer);
2505 kill('KILL', $extauth) if ($extauth);
2506 exec($perl_path, $miniserv_path, @miniserv_argv);
2507 die "Failed to restart miniserv with $perl_path $miniserv_path";
2524 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2525 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/) { push(@rv, $i); }
2526 else { push(@rv, join('.', unpack("CCCC", inet_aton($i)))); }
2528 return wantarray ? @rv : $rv[0];
2531 # read_line(no-wait, no-limit)
2532 # Reads one line from SOCK or SSL
2535 local ($nowait, $nolimit) = @_;
2536 local($idx, $more, $rv);
2537 while(($idx = index($main::read_buffer, "\n")) < 0) {
2538 if (length($main::read_buffer) > 10000 && !$nolimit) {
2539 &http_error(414, "Request too long",
2540 "Received excessive line <pre>$main::read_buffer</pre>");
2543 # need to read more..
2544 &wait_for_data_error() if (!$nowait);
2546 $more = Net::SSLeay::read($ssl_con);
2549 local $ok = sysread(SOCK, $more, 1024);
2550 $more = undef if ($ok <= 0);
2554 $rv = $main::read_buffer;
2555 undef($main::read_buffer);
2558 $main::read_buffer .= $more;
2560 $rv = substr($main::read_buffer, 0, $idx+1);
2561 $main::read_buffer = substr($main::read_buffer, $idx+1);
2566 # Reads up to some amount of data from SOCK or the SSL connection
2570 if (length($main::read_buffer)) {
2571 if (length($main::read_buffer) > $_[0]) {
2572 # Return the first part of the buffer
2573 $rv = substr($main::read_buffer, 0, $_[0]);
2574 $main::read_buffer = substr($main::read_buffer, $_[0]);
2578 # Return the whole buffer
2579 $rv = $main::read_buffer;
2580 undef($main::read_buffer);
2585 # Call SSL read function
2586 return Net::SSLeay::read($ssl_con, $_[0]);
2589 # Just do a normal read
2591 sysread(SOCK, $buf, $_[0]) || return undef;
2597 # Read a line from a file handle, using sysread to get a byte at a time
2604 $got = sysread($fh, $buf, 1);
2605 last if ($got <= 0);
2607 last if ($buf eq "\n");
2612 # wait_for_data(secs)
2613 # Waits at most the given amount of time for some data on SOCK, returning
2614 # 0 if not found, 1 if some arrived.
2618 vec($rmask, fileno(SOCK), 1) = 1;
2619 local $got = select($rmask, undef, undef, $_[0]);
2620 return $got == 0 ? 0 : 1;
2623 # wait_for_data_error()
2624 # Waits 60 seconds for data on SOCK, and fails if none arrives
2625 sub wait_for_data_error
2627 local $got = &wait_for_data(60);
2629 &http_error(400, "Timeout",
2630 "Waited more than 60 seconds for request data");
2634 # write_data(data, ...)
2635 # Writes a string to SOCK or the SSL connection
2638 local $str = join("", @_);
2640 Net::SSLeay::write($ssl_con, $str);
2643 syswrite(SOCK, $str, length($str));
2645 # Intentionally introduce a small delay to avoid problems where IE reports
2646 # the page as empty / DNS failed when it get a large response too quickly!
2647 select(undef, undef, undef, .01) if ($write_data_count%10 == 0);
2648 $write_data_count += length($str);
2651 # reset_byte_count()
2652 sub reset_byte_count { $write_data_count = 0; }
2655 sub byte_count { return $write_data_count; }
2657 # log_request(hostname, user, request, code, bytes)
2660 if ($config{'log'}) {
2661 local ($user, $ident, $headers);
2662 if ($config{'logident'}) {
2663 # add support for rfc1413 identity checking here
2665 else { $ident = "-"; }
2666 $user = $_[1] ? $_[1] : "-";
2667 local $dstr = &make_datestr();
2668 if (fileno(MINISERVLOG)) {
2669 seek(MINISERVLOG, 0, 2);
2672 open(MINISERVLOG, ">>$config{'logfile'}");
2673 chmod(0600, $config{'logfile'});
2675 if (defined($config{'logheaders'})) {
2676 foreach $h (split(/\s+/, $config{'logheaders'})) {
2677 $headers .= " $h=\"$header{$h}\"";
2680 elsif ($config{'logclf'}) {
2681 $headers = " \"$header{'referer'}\" \"$header{'user-agent'}\"";
2686 print MINISERVLOG "$_[0] $ident $user [$dstr] \"$_[2]\" ",
2687 "$_[3] $_[4]$headers\n";
2695 local @tm = localtime(time());
2696 return sprintf "%2.2d/%s/%4.4d:%2.2d:%2.2d:%2.2d %s",
2697 $tm[3], $month[$tm[4]], $tm[5]+1900,
2698 $tm[2], $tm[1], $tm[0], $timezone;
2701 # log_error(message)
2705 print STDERR "[",&make_datestr(),"] ",
2706 $acpthost ? ( "[",$acpthost,"] " ) : ( ),
2707 $page ? ( $page," : " ) : ( ),
2711 # read_errors(handle)
2712 # Read and return all input from some filehandle
2715 local($fh, $_, $rv);
2717 while(<$fh>) { $rv .= $_; }
2721 sub write_keep_alive
2724 if ($config{'nokeepalive'}) {
2725 # Keep alives have been disabled in config
2728 elsif (@childpids > $config{'maxconns'}*.8) {
2729 # Disable because nearing process limit
2733 # Keep alive specified by caller
2737 # Keep alive determined by browser
2738 $mode = $header{'connection'} =~ /keep-alive/i;
2740 &write_data("Connection: ".($mode ? "Keep-Alive" : "close")."\r\n");
2746 kill('TERM', @childpids) if (@childpids);
2747 kill('KILL', $logclearer) if ($logclearer);
2748 kill('KILL', $extauth) if ($extauth);
2754 local @tm = gmtime($_[0]);
2755 return sprintf "%s, %d %s %d %2.2d:%2.2d:%2.2d GMT",
2756 $weekday[$tm[6]], $tm[3], $month[$tm[4]], $tm[5]+1900,
2757 $tm[2], $tm[1], $tm[0];
2762 my $i; bless \$i, shift;
2768 my($buf,$len,$offset) = @_;
2769 &write_to_sock(substr($buf, $offset, $len));
2776 my $buf = join(defined($,) ? $, : "", @_);
2777 $buf .= $\ if defined($\);
2778 &write_to_sock($buf);
2785 &write_to_sock(sprintf $fmt, @_);
2788 # Send back already read data while we have it, then read from SOCK
2792 my $bufref = \$_[0];
2795 if ($postpos < length($postinput)) {
2796 # Reading from already fetched array
2797 my $left = length($postinput) - $postpos;
2798 my $canread = $len > $left ? $left : $len;
2799 substr($$bufref, $offset, $canread) =
2800 substr($postinput, $postpos, $canread);
2801 $postpos += $canread;
2805 # Read from network socket
2806 local $data = &read_data($len);
2807 if ($data eq '' && $len) {
2809 print STDERR "finished reading - shutting down socket\n";
2812 substr($$bufref, $offset, length($data)) = $data;
2813 return length($data);
2819 #print STDERR "open() called - should never happen!\n";
2822 # Read a line of input
2826 if ($postpos < length($postinput) &&
2827 ($idx = index($postinput, "\n", $postpos)) >= 0) {
2828 # A line exists in the memory buffer .. use it
2829 my $line = substr($postinput, $postpos, $idx-$postpos+1);
2834 # Need to read from the socket
2836 if ($postpos < length($postinput)) {
2837 # Start with in-memory data
2838 $line = substr($postinput, $postpos);
2839 $postpos = length($postinput);
2841 my $nl = &read_line(0, 1);
2844 print STDERR "finished reading - shutting down socket\n";
2847 $line .= $nl if (defined($nl));
2852 # Read one character of input
2857 my $got = READ($r, \$buf, 1, 0);
2858 return $got > 0 ? $buf : undef;
2863 return fileno(SOCK);
2870 # write_to_sock(data, ...)
2875 if ($doneheaders || $miniserv::nph_script) {
2880 while(!$doneheaders && $headers =~ s/^([^\r\n]*)(\r)?\n//) {
2881 if ($1 =~ /^(\S+):\s+(.*)$/) {
2882 $cgiheader{lc($1)} = $2;
2883 push(@cgiheader, [ $1, $2 ]);
2885 elsif ($1 !~ /\S/) {
2889 &http_error(500, "Bad Header");
2893 if ($cgiheader{"location"}) {
2895 "HTTP/1.0 302 Moved Temporarily\r\n");
2896 &write_data("Date: $datestr\r\n");
2897 &write_data("Server: $config{server}\r\n");
2898 &write_keep_alive(0);
2900 elsif ($cgiheader{"content-type"} eq "") {
2901 &http_error(500, "Missing Content-Type Header");
2904 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2905 &write_data("Date: $datestr\r\n");
2906 &write_data("Server: $config{server}\r\n");
2907 &write_keep_alive(0);
2909 foreach $h (@cgiheader) {
2910 &write_data("$h->[0]: $h->[1]\r\n");
2912 &write_data("\r\n");
2913 &reset_byte_count();
2914 &write_data($headers);
2922 local $cert = Net::SSLeay::X509_STORE_CTX_get_current_cert($_[1]);
2924 local $errnum = Net::SSLeay::X509_STORE_CTX_get_error($_[1]);
2925 $verified_client = 1 if (!$errnum);
2932 if ($doing_eval && $$ == $main_process_id) {
2933 # A CGI program called exit! This is a horrible hack to
2934 # finish up before really exiting
2937 close($PASSINw); close($PASSOUTw);
2938 &log_request($acpthost, $authuser, $reqline,
2939 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2944 # Convert a string to a form ok for putting in a URL
2946 local($tmp, $tmp2, $c);
2949 while(($c = chop($tmp)) ne "") {
2950 if ($c !~ /[A-z0-9]/) {
2951 $c = sprintf("%%%2.2X", ord($c));
2958 # validate_user(username, password, host)
2959 # Checks if some username and password are valid. Returns the modified username,
2960 # the expired / temp pass flag, and the non-existence flag
2963 local ($user, $pass, $host) = @_;
2964 return ( ) if (!$user);
2965 print DEBUG "validate_user: user=$user pass=$pass host=$host\n";
2966 local ($canuser, $canmode, $notexist, $webminuser, $sudo) =
2967 &can_user_login($user, undef, $host);
2968 print DEBUG "validate_user: canuser=$canuser canmode=$canmode notexist=$notexist webminuser=$webminuser sudo=$sudo\n";
2970 # User doesn't even exist, so go no further
2971 return ( undef, 0, 1 );
2973 elsif ($canmode == 0) {
2974 # User does exist but cannot login
2975 return ( $canuser, 0, 0 );
2977 elsif ($canmode == 1) {
2978 # Attempt Webmin authentication
2979 if ($users{$webminuser} eq
2980 &password_crypt($pass, $users{$webminuser})) {
2981 # Password is valid .. but check for expiry
2982 local $lc = $lastchanges{$user};
2983 if ($config{'pass_maxdays'} && $lc && !$nochange{$user}) {
2984 local $daysold = (time() - $lc)/(24*60*60);
2985 print DEBUG "maxdays=$config{'pass_maxdays'} daysold=$daysold temppass=$temppass{$user}\n";
2986 if ($config{'pass_lockdays'} &&
2987 $daysold > $config{'pass_lockdays'}) {
2988 # So old that the account is locked
2989 return ( undef, 0, 0 );
2991 elsif ($daysold > $config{'pass_maxdays'}) {
2992 # Password has expired
2993 return ( $user, 1, 0 );
2996 if ($temppass{$user}) {
2997 # Temporary password - force change now
2998 return ( $user, 2, 0 );
3000 return ( $user, 0, 0 );
3003 return ( undef, 0, 0 );
3006 elsif ($canmode == 2 || $canmode == 3) {
3007 # Attempt PAM or passwd file authentication
3008 local $val = &validate_unix_user($canuser, $pass);
3009 print DEBUG "validate_user: unix val=$val\n";
3010 if ($val && $sudo) {
3011 # Need to check if this Unix user can sudo
3012 if (!&check_sudo_permissions($canuser, $pass)) {
3013 print DEBUG "validate_user: sudo failed\n";
3017 print DEBUG "validate_user: sudo passed\n";
3020 return $val == 2 ? ( $canuser, 1, 0 ) :
3021 $val == 1 ? ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3023 elsif ($canmode == 4) {
3024 # Attempt external authentication
3025 return &validate_external_user($canuser, $pass) ?
3026 ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3034 # validate_unix_user(user, password)
3035 # Returns 1 if a username and password are valid under unix, 0 if not,
3036 # or 2 if the account has expired.
3037 # Checks PAM if available, and falls back to reading the system password
3039 sub validate_unix_user
3043 $pam_username = $_[0];
3044 $pam_password = $_[1];
3045 local $pamh = new Authen::PAM($config{'pam'}, $pam_username,
3048 local $pam_ret = $pamh->pam_authenticate();
3049 if ($pam_ret == PAM_SUCCESS()) {
3050 # Logged in OK .. make sure password hasn't expired
3051 local $acct_ret = $pamh->pam_acct_mgmt();
3052 if ($acct_ret == PAM_SUCCESS()) {
3053 $pamh->pam_open_session();
3056 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3057 $acct_ret == PAM_ACCT_EXPIRED()) {
3061 print STDERR "Unknown pam_acct_mgmt return value : $acct_ret\n";
3068 elsif ($config{'pam_only'}) {
3069 # Pam is not available, but configuration forces it's use!
3072 elsif ($config{'passwd_file'}) {
3073 # Check in a password file
3075 open(FILE, $config{'passwd_file'});
3076 if ($config{'passwd_file'} eq '/etc/security/passwd') {
3077 # Assume in AIX format
3080 if (/^\s*(\S+):/ && $1 eq $_[0]) {
3082 if (/^\s*password\s*=\s*(\S+)\s*$/) {
3083 $rv = $1 eq &password_crypt($_[1], $1) ?
3091 # Read the system password or shadow file
3093 local @l = split(/:/, $_, -1);
3094 local $u = $l[$config{'passwd_uindex'}];
3095 local $p = $l[$config{'passwd_pindex'}];
3097 $rv = $p eq &password_crypt($_[1], $p) ? 1 : 0;
3098 if ($config{'passwd_cindex'} ne '' && $rv) {
3099 # Password may have expired!
3100 local $c = $l[$config{'passwd_cindex'}];
3101 local $m = $l[$config{'passwd_mindex'}];
3102 local $day = time()/(24*60*60);
3103 if ($c =~ /^\d+/ && $m =~ /^\d+/ &&
3109 if ($p eq "" && $config{'passwd_blank'}) {
3110 # Force password change
3118 return $rv if ($rv);
3121 # Fallback option - check password returned by getpw*
3122 local @uinfo = getpwnam($_[0]);
3123 if ($uinfo[1] ne '' && &password_crypt($_[1], $uinfo[1]) eq $uinfo[1]) {
3127 return 0; # Totally failed
3130 # validate_external_user(user, pass)
3131 # Validate a user by passing the username and password to an external
3132 # squid-style authentication program
3133 sub validate_external_user
3135 return 0 if (!$config{'extauth'});
3137 local $str = "$_[0] $_[1]\n";
3138 syswrite(EXTAUTH, $str, length($str));
3139 local $resp = <EXTAUTH>;
3141 return $resp =~ /^OK/i ? 1 : 0;
3144 # can_user_login(username, no-append, host)
3145 # Checks if a user can login or not.
3146 # First return value is the username.
3147 # Second is 0 if cannot login, 1 if using Webmin pass, 2 if PAM, 3 if password
3148 # file, 4 if external.
3149 # Third is 1 if the user does not exist at all, 0 if he does.
3150 # Fourth is the Webmin username whose permissions apply, based on unixauth.
3151 # Fifth is a flag indicating if a sudo check is needed.
3154 if (!$users{$_[0]}) {
3155 # See if this user exists in Unix and can be validated by the same
3156 # method as the unixauth webmin user
3157 local $realuser = $unixauth{$_[0]};
3161 eval { @uinfo = getpwnam($_[0]); }; # may fail on windows
3162 if (!$realuser && @uinfo) {
3163 # No unixauth entry for the username .. try his groups
3164 foreach my $ua (keys %unixauth) {
3165 if ($ua =~ /^\@(.*)$/) {
3166 if (&is_group_member(\@uinfo, $1)) {
3167 $realuser = $unixauth{$ua};
3173 if (!$realuser && @uinfo) {
3174 # Fall back to unix auth for all Unix users
3175 $realuser = $unixauth{"*"};
3177 if (!$realuser && $use_sudo && @uinfo) {
3178 # Allow login effectively as root, if sudo permits it
3182 if (!$realuser && !@uinfo && $config{'pamany'}) {
3183 # If the user completely doesn't exist, we can still allow
3184 # him to authenticate via PAM
3185 $realuser = $config{'pamany'};
3189 # For Usermin, always fall back to unix auth for any user,
3190 # so that later checks with domain added / removed are done.
3191 $realuser = $unixauth{"*"};
3193 return (undef, 0, 1, undef) if (!$realuser);
3194 local $up = $users{$realuser};
3195 return (undef, 0, 1, undef) if (!defined($up));
3197 # Work out possible domain names from the hostname
3198 local @doms = ( $_[2] );
3199 if ($_[2] =~ /^([^\.]+)\.(\S+)$/) {
3203 if ($config{'user_mapping'} && !defined(%user_mapping)) {
3204 # Read the user mapping file
3206 open(MAPPING, $config{'user_mapping'});
3210 if (/^(\S+)\s+(\S+)/) {
3211 if ($config{'user_mapping_reverse'}) {
3212 $user_mapping{$1} = $2;
3215 $user_mapping{$2} = $1;
3222 # Check the user mapping file to see if there is an entry for the
3223 # user login in which specifies a new effective user
3225 foreach my $d (@doms) {
3226 $um ||= $user_mapping{"$_[0]\@$d"};
3228 $um ||= $user_mapping{$_[0]};
3229 if (defined($um) && ($_[1]&4) == 0) {
3230 # A mapping exists - use it!
3231 return &can_user_login($um, $_[1]+4, $_[2]);
3234 # Check if a user with the entered login and the domains appended
3235 # or prepended exists, and if so take it to be the effective user
3236 if (!@uinfo && $config{'domainuser'}) {
3237 # Try again with name.domain and name.firstpart
3238 local @firsts = map { /^([^\.]+)/; $1 } @doms;
3239 if (($_[1]&1) == 0) {
3241 foreach $a (@firsts, @doms) {
3242 foreach $p ("$_[0].${a}", "$_[0]-${a}",
3243 "${a}.$_[0]", "${a}-$_[0]",
3244 "$_[0]_${a}", "${a}_$_[0]") {
3245 local @vu = &can_user_login(
3246 $p, $_[1]+1, $_[2]);
3247 return @vu if ($vu[1]);
3253 # Check if the user entered a domain at the end of his username when
3254 # he really shouldn't have, and if so try without it
3255 if (!@uinfo && $config{'domainstrip'} &&
3256 $_[0] =~ /^(\S+)\@(\S+)$/ && ($_[1]&2) == 0) {
3257 local ($stripped, $dom) = ($1, $2);
3258 local @vu = &can_user_login($stripped, $_[1] + 2, $_[2]);
3259 return @vu if ($vu[1]);
3260 local @vu = &can_user_login($stripped, $_[1] + 2, $dom);
3261 return @vu if ($vu[1]);
3264 return ( undef, 0, 1, undef ) if (!@uinfo && !$pamany);
3267 if (defined(@allowusers)) {
3268 # Only allow people on the allow list
3269 return ( undef, 0, 0, undef )
3270 if (!&users_match(\@uinfo, @allowusers));
3272 elsif (defined(@denyusers)) {
3273 # Disallow people on the deny list
3274 return ( undef, 0, 0, undef )
3275 if (&users_match(\@uinfo, @denyusers));
3277 if ($config{'shells_deny'}) {
3279 open(SHELLS, $config{'shells_deny'});
3283 $found++ if ($_ eq $uinfo[8]);
3286 return ( undef, 0, 0, undef ) if (!$found);
3291 # PAM or passwd file authentication
3292 return ( $_[0], $use_pam ? 2 : 3, 0, $realuser, $sudo );
3294 elsif ($up eq 'e') {
3295 # External authentication
3296 return ( $_[0], 4, 0, $realuser, $sudo );
3299 # Fixed Webmin password
3300 return ( $_[0], 1, 0, $realuser, $sudo );
3303 elsif ($users{$_[0]} eq 'x') {
3304 # Webmin user authenticated via PAM or password file
3305 return ( $_[0], $use_pam ? 2 : 3, 0, $_[0] );
3307 elsif ($users{$_[0]} eq 'e') {
3308 # Webmin user authenticated externally
3309 return ( $_[0], 4, 0, $_[0] );
3312 # Normal Webmin user
3313 return ( $_[0], 1, 0, $_[0] );
3317 # the PAM conversation function for interactive logins
3320 $pam_conv_func_called++;
3327 $ans = $pam_username if ($code == PAM_PROMPT_ECHO_ON() );
3328 $ans = $pam_password if ($code == PAM_PROMPT_ECHO_OFF() );
3330 push @res, PAM_SUCCESS();
3333 push @res, PAM_SUCCESS();
3342 # get_socket_name(handle)
3343 # Returns the local hostname or IP address of some connection
3346 return $config{'host'} if ($config{'host'});
3347 local $sn = getsockname($_[0]);
3348 return undef if (!$sn);
3349 local $myaddr = (unpack_sockaddr_in($sn))[1];
3350 if (!$get_socket_name_cache{$myaddr}) {
3352 if (!$config{'no_resolv_myname'}) {
3353 $myname = gethostbyaddr($myaddr, AF_INET);
3355 if ($myname eq "") {
3356 $myname = inet_ntoa($myaddr);
3358 $get_socket_name_cache{$myaddr} = $myname;
3360 return $get_socket_name_cache{$myaddr};
3363 # run_login_script(username, sid, remoteip, localip)
3364 sub run_login_script
3366 if ($config{'login_script'}) {
3367 system($config{'login_script'}.
3368 " ".join(" ", map { quotemeta($_) } @_).
3369 " >/dev/null 2>&1 </dev/null");
3373 # run_logout_script(username, sid, remoteip, localip)
3374 sub run_logout_script
3376 if ($config{'logout_script'}) {
3377 system($config{'logout_script'}.
3378 " ".join(" ", map { quotemeta($_) } @_).
3379 " >/dev/null 2>&1 </dev/null");
3383 # close_all_sockets()
3384 # Closes all the main listening sockets
3385 sub close_all_sockets
3388 foreach $s (@socketfhs) {
3394 # Close all pipes for talking to sub-processes
3398 foreach $p (@passin) { close($p); }
3399 foreach $p (@passout) { close($p); }
3400 foreach $p (values %conversations) {
3401 if ($p->{'PAMOUTr'}) {
3402 close($p->{'PAMOUTr'});
3403 close($p->{'PAMINw'});
3408 # check_user_ip(user)
3409 # Returns 1 if some user is allowed to login from the accepting IP, 0 if not
3413 &ip_match($acptip, $localip, @{$deny{$_[0]}}) ||
3415 !&ip_match($acptip, $localip, @{$allow{$_[0]}})) {
3421 # check_user_time(user)
3422 # Returns 1 if some user is allowed to login at the current date and time
3425 return 1 if (!$allowdays{$_[0]} && !$allowhours{$_[0]});
3426 local @tm = localtime(time());
3427 if ($allowdays{$_[0]}) {
3428 # Make sure day is allowed
3429 return 0 if (&indexof($tm[6], @{$allowdays{$_[0]}}) < 0);
3431 if ($allowhours{$_[0]}) {
3432 # Make sure time is allowed
3433 local $m = $tm[2]*60+$tm[1];
3434 return 0 if ($m < $allowhours{$_[0]}->[0] ||
3435 $m > $allowhours{$_[0]}->[1]);
3440 # generate_random_id(password, [force-urandom])
3441 # Returns a random session ID number
3442 sub generate_random_id
3444 local ($pass, $force_urandom) = @_;
3446 if (!$bad_urandom) {
3447 # First try /dev/urandom, unless we have marked it as bad
3448 $SIG{ALRM} = "miniserv::urandom_timeout";
3450 if (open(RANDOM, "/dev/urandom")) {
3452 if (read(RANDOM, $tmpsid, 16) == 16) {
3453 $sid = lc(unpack('h*',$tmpsid));
3459 if (!$sid && !$force_urandom) {
3462 foreach $c (split(//, &unix_crypt($pass, substr($$, -2)))) {
3463 $sid += ord($c) * $mul;
3470 # handle_login(username, ok, expired, not-exists, password, [no-test-cookie])
3471 # Called from handle_session to either mark a user as logged in, or not
3474 local ($vu, $ok, $expired, $nonexist, $pass, $notest) = @_;
3475 $authuser = $vu if ($ok);
3477 # check if the test cookie is set
3478 if ($header{'cookie'} !~ /testing=1/ && $vu &&
3479 !$config{'no_testing_cookie'} && !$notest) {
3480 &http_error(500, "No cookies",
3481 "Your browser does not support cookies, ".
3482 "which are required for this web server to ".
3483 "work in session authentication mode");
3486 # check with main process for delay
3487 if ($config{'passdelay'} && $vu) {
3488 print $PASSINw "delay $vu $acptip $ok\n";
3489 <$PASSOUTr> =~ /(\d+) (\d+)/;
3494 if ($ok && (!$expired ||
3495 $config{'passwd_mode'} == 1)) {
3496 # Logged in OK! Tell the main process about
3498 local $sid = &generate_random_id($pass);
3499 print $PASSINw "new $sid $authuser $acptip\n";
3501 # Run the post-login script, if any
3502 &run_login_script($authuser, $sid,
3505 # Check for a redirect URL for the user
3506 local $rurl = &login_redirect($authuser, $pass, $host);
3508 # Got one .. go to it
3509 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3510 &write_data("Date: $datestr\r\n");
3511 &write_data("Server: $config{'server'}\r\n");
3512 &write_data("Location: $rurl\r\n");
3513 &write_keep_alive(0);
3514 &write_data("\r\n");
3515 &log_request($acpthost, $authuser, $reqline, 302, 0);
3518 # Set cookie and redirect to originally requested page
3519 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3520 &write_data("Date: $datestr\r\n");
3521 &write_data("Server: $config{'server'}\r\n");
3522 local $ssl = $use_ssl || $config{'inetd_ssl'};
3523 $portstr = $port == 80 && !$ssl ? "" :
3524 $port == 443 && $ssl ? "" : ":$port";
3525 $prot = $ssl ? "https" : "http";
3526 local $sec = $ssl ? "; secure" : "";
3527 #$sec .= "; httpOnly";
3529 &write_data("Set-Cookie: $sidname=$sid; path=/; expires=\"Thu, 31-Dec-2037 00:00:00\"$sec\r\n");
3532 &write_data("Set-Cookie: $sidname=$sid; path=/$sec\r\n");
3534 &write_data("Location: $prot://$host$portstr$in{'page'}\r\n");
3535 &write_keep_alive(0);
3536 &write_data("\r\n");
3537 &log_request($acpthost, $authuser, $reqline, 302, 0);
3538 syslog("info", "%s", "Successful login as $authuser from $acpthost") if ($use_syslog);
3539 &write_login_utmp($authuser, $acpthost);
3543 elsif ($ok && $expired &&
3544 ($config{'passwd_mode'} == 2 || $expired == 2)) {
3545 # Login was ok, but password has expired or was temporary. Need
3546 # to force display of password change form.
3549 $querystring = "&user=".&urlize($vu).
3551 "&expired=".$expired;
3554 $page = $config{'password_form'};
3556 $miniserv_internal = 2;
3557 syslog("crit", "%s",
3558 "Expired login as $vu ".
3559 "from $acpthost") if ($use_syslog);
3562 # Login failed, or password has expired. The login form will be
3563 # displayed again by later code
3565 $request_uri = $in{'page'};
3566 $already_session_id = undef;
3568 $authuser = $baseauthuser = undef;
3569 syslog("crit", "%s",
3570 ($nonexist ? "Non-existent" :
3571 $expired ? "Expired" : "Invalid").
3572 " login as $vu from $acpthost")
3578 # write_login_utmp(user, host)
3579 # Record the login by some user in utmp
3580 sub write_login_utmp
3583 # Write utmp record for login
3584 %utmp = ( 'ut_host' => $_[1],
3585 'ut_time' => time(),
3587 'ut_type' => 7, # user process
3588 'ut_pid' => $main_process_id,
3589 'ut_line' => $config{'pam'},
3591 if (defined(&User::Utmp::putut)) {
3592 User::Utmp::putut(\%utmp);
3595 User::Utmp::pututline(\%utmp);
3600 # write_logout_utmp(user, host)
3601 # Record the logout by some user in utmp
3602 sub write_logout_utmp
3605 # Write utmp record for logout
3606 %utmp = ( 'ut_host' => $_[1],
3607 'ut_time' => time(),
3609 'ut_type' => 8, # dead process
3610 'ut_pid' => $main_process_id,
3611 'ut_line' => $config{'pam'},
3613 if (defined(&User::Utmp::putut)) {
3614 User::Utmp::putut(\%utmp);
3617 User::Utmp::pututline(\%utmp);
3622 # pam_conversation_process(username, write-pipe, read-pipe)
3623 # This function is called inside a sub-process to communicate with PAM. It sends
3624 # questions down one pipe, and reads responses from another
3625 sub pam_conversation_process
3627 local ($user, $writer, $reader) = @_;
3628 $miniserv::pam_conversation_process_writer = $writer;
3629 $miniserv::pam_conversation_process_reader = $reader;
3630 local $convh = new Authen::PAM(
3631 $config{'pam'}, $user, \&miniserv::pam_conversation_process_func);
3632 local $pam_ret = $convh->pam_authenticate();
3633 if ($pam_ret == PAM_SUCCESS()) {
3634 local $acct_ret = $convh->pam_acct_mgmt();
3635 if ($acct_ret == PAM_SUCCESS()) {
3636 $convh->pam_open_session();
3637 print $writer "x2 $user 1 0 0\n";
3639 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3640 $acct_ret == PAM_ACCT_EXPIRED()) {
3641 print $writer "x2 $user 1 1 0\n";
3644 print $writer "x0 Unknown PAM account status $acct_ret\n";
3648 print $writer "x2 $user 0 0 0\n";
3653 # pam_conversation_process_func(type, message, [type, message, ...])
3654 # A pipe that talks to both PAM and the master process
3655 sub pam_conversation_process_func
3658 select($miniserv::pam_conversation_process_writer); $| = 1; select(STDOUT);
3660 local ($type, $msg) = (shift, shift);
3662 local $ok = (print $miniserv::pam_conversation_process_writer "$type $msg\n");
3663 print $miniserv::pam_conversation_process_writer "\n";
3664 local $answer = <$miniserv::pam_conversation_process_reader>;
3665 $answer =~ s/\r|\n//g;
3666 push(@rv, PAM_SUCCESS(), $answer);
3668 push(@rv, PAM_SUCCESS());
3673 # Returns 4 new pipe file handles
3676 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3678 local %taken = ( (map { $_, 1 } @passin),
3679 (map { $_->{'PASSINr'} } values %conversations) );
3680 for($p=0; $taken{"PASSINr$p"}; $p++) { }
3681 $PASSINr = "PASSINr$p";
3682 $PASSINw = "PASSINw$p";
3683 $PASSOUTr = "PASSOUTr$p";
3684 $PASSOUTw = "PASSOUTw$p";
3685 pipe($PASSINr, $PASSINw);
3686 pipe($PASSOUTr, $PASSOUTw);
3687 select($PASSINw); $| = 1;
3688 select($PASSINr); $| = 1;
3689 select($PASSOUTw); $| = 1;
3690 select($PASSOUTw); $| = 1;
3692 return ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3695 # recv_pam_question(&conv, fd)
3696 # Reads one PAM question from the sub-process, and sends it to the HTTP handler.
3697 # Returns 0 if the conversation is over, 1 if not.
3698 sub recv_pam_question
3700 local ($conf, $fh) = @_;
3701 local $pr = $conf->{'PAMOUTr'};
3702 select($pr); $| = 1; select(STDOUT);
3703 local $line = <$pr>;
3704 $line =~ s/\r|\n//g;
3707 $line =~ s/\r|\n//g;
3709 $conf->{'last'} = time();
3712 print $fh "0 PAM conversation error\n";
3716 local ($type, $msg) = split(/\s+/, $line, 2);
3717 if ($type =~ /^x(\d+)/) {
3718 # Pass this status code through
3719 print $fh "$1 $msg\n";
3720 return $1 == 2 || $1 == 0 ? 0 : 1;
3722 elsif ($type == PAM_PROMPT_ECHO_ON()) {
3724 print $fh "1 $msg\n";
3727 elsif ($type == PAM_PROMPT_ECHO_OFF()) {
3729 print $fh "3 $msg\n";
3732 elsif ($type == PAM_ERROR_MSG() || $type == PAM_TEXT_INFO()) {
3733 # A message that does not require a response
3734 print $fh "4 $msg\n";
3739 print $fh "0 Unknown PAM message type $type\n";
3745 # send_pam_answer(&conv, answer)
3746 # Sends a response from the user to the PAM sub-process
3749 local ($conf, $answer) = @_;
3750 local $pw = $conf->{'PAMINw'};
3751 $conf->{'last'} = time();
3752 print $pw "$answer\n";
3755 # end_pam_conversation(&conv)
3756 # Clean up PAM conversation pipes and processes
3757 sub end_pam_conversation
3760 kill('KILL', $conv->{'pid'}) if ($conv->{'pid'});
3761 if ($conv->{'PAMINr'}) {
3762 close($conv->{'PAMINr'});
3763 close($conv->{'PAMOUTr'});
3764 close($conv->{'PAMINw'});
3765 close($conv->{'PAMOUTw'});
3767 delete($conversations{$conv->{'cid'}});
3770 # get_ipkeys(&miniserv)
3771 # Returns a list of IP address to key file mappings from a miniserv.conf entry
3775 foreach $k (keys %{$_[0]}) {
3776 if ($k =~ /^ipkey_(\S+)/) {
3777 local $ipkey = { 'ips' => [ split(/,/, $1) ],
3778 'key' => $_[0]->{$k},
3779 'index' => scalar(@rv) };
3780 $ipkey->{'cert'} = $_[0]->{'ipcert_'.$1};
3787 # create_ssl_context(keyfile, [certfile])
3788 sub create_ssl_context
3790 local ($keyfile, $certfile) = @_;
3792 eval { $ssl_ctx = Net::SSLeay::new_x_ctx() };
3793 $ssl_ctx ||= Net::SSLeay::CTX_new();
3794 $ssl_ctx || die "Failed to create SSL context : $!";
3795 if ($client_certs) {
3796 Net::SSLeay::CTX_load_verify_locations(
3797 $ssl_ctx, $config{'ca'}, "");
3798 Net::SSLeay::CTX_set_verify(
3799 $ssl_ctx, &Net::SSLeay::VERIFY_PEER, \&verify_client);
3801 if ($config{'extracas'}) {
3803 foreach $p (split(/\s+/, $config{'extracas'})) {
3804 Net::SSLeay::CTX_load_verify_locations(
3809 Net::SSLeay::CTX_use_RSAPrivateKey_file(
3811 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL key $keyfile";
3812 Net::SSLeay::CTX_use_certificate_file(
3813 $ssl_ctx, $certfile || $keyfile,
3814 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL cert $certfile";
3819 # ssl_connection_for_ip(socket)
3820 # Returns a new SSL connection object for some socket, or undef if failed
3821 sub ssl_connection_for_ip
3824 local $sn = getsockname($sock);
3826 print STDERR "Failed to get address for socket $sock\n";
3829 local $myip = inet_ntoa((unpack_sockaddr_in($sn))[1]);
3830 local $ssl_ctx = $ssl_contexts{$myip} || $ssl_contexts{"*"};
3831 local $ssl_con = Net::SSLeay::new($ssl_ctx);
3832 if ($config{'ssl_cipher_list'}) {
3833 # Force use of ciphers
3834 eval "Net::SSLeay::set_cipher_list(
3835 \$ssl_con, \$config{'ssl_cipher_list'})";
3837 print STDERR "SSL cipher $config{'ssl_cipher_list'} failed : ",
3843 Net::SSLeay::set_fd($ssl_con, fileno($sock));
3844 if (!Net::SSLeay::accept($ssl_con)) {
3845 print STDERR "Failed to initialize SSL connection\n";
3851 # login_redirect(username, password, host)
3852 # Calls the login redirect script (if configured), which may output a URL to
3853 # re-direct a user to after logging in.
3856 return undef if (!$config{'login_redirect'});
3857 local $quser = quotemeta($_[0]);
3858 local $qpass = quotemeta($_[1]);
3859 local $qhost = quotemeta($_[2]);
3860 local $url = `$config{'login_redirect'} $quser $qpass $qhost`;
3865 # reload_config_file()
3866 # Re-read %config, and call post-config actions
3867 sub reload_config_file
3869 &log_error("Reloading configuration");
3870 %config = &read_config_file($config_file);
3871 &update_vital_config();
3874 &build_config_mappings();
3875 if ($config{'session'}) {
3876 dbmclose(%sessiondb);
3877 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
3881 # read_config_file(file)
3882 # Reads the given config file, and returns a hash of values
3883 sub read_config_file
3886 open(CONF, $_[0]) || die "Failed to open config file $_[0] : $!";
3889 if (/^#/ || !/\S/) { next; }
3891 $name = $1; $val = $2;
3892 $name =~ s/^\s+//g; $name =~ s/\s+$//g;
3893 $val =~ s/^\s+//g; $val =~ s/\s+$//g;
3900 # update_vital_config()
3901 # Updates %config with defaults, and dies if something vital is missing
3902 sub update_vital_config
3904 my %vital = ("port", 80,
3906 "server", "MiniServ/0.01",
3907 "index_docs", "index.html index.htm index.cgi index.php",
3908 "addtype_html", "text/html",
3909 "addtype_txt", "text/plain",
3910 "addtype_gif", "image/gif",
3911 "addtype_jpg", "image/jpeg",
3912 "addtype_jpeg", "image/jpeg",
3913 "realm", "MiniServ",
3914 "session_login", "/session_login.cgi",
3915 "pam_login", "/pam_login.cgi",
3916 "password_form", "/password_form.cgi",
3917 "password_change", "/password_change.cgi",
3921 "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\$",
3923 "expires", 7*24*60*60,
3925 foreach my $v (keys %vital) {
3927 if ($vital{$v} eq "") {
3928 die "Missing config option $v";
3930 $config{$v} = $vital{$v};
3933 if (!$config{'sessiondb'}) {
3934 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3935 $config{'sessiondb'} = "$1/sessiondb";
3937 if (!$config{'errorlog'}) {
3938 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
3939 $config{'errorlog'} = "$1/miniserv.error";
3941 if (!$config{'tempbase'}) {
3942 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3943 $config{'tempbase'} = "$1/cgitemp";
3945 if (!$config{'blockedfile'}) {
3946 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3947 $config{'blockedfile'} = "$1/blocked";
3952 # Fills the %users and %certs hashes from the users file in %config
3961 undef(%lastchanges);
3964 if ($config{'userfile'}) {
3965 open(USERS, $config{'userfile'});
3968 local @user = split(/:/, $_, -1);
3969 $users{$user[0]} = $user[1];
3970 $certs{$user[0]} = $user[3] if ($user[3]);
3971 if ($user[4] =~ /^allow\s+(.*)/) {
3972 $allow{$user[0]} = $config{'alwaysresolve'} ?
3973 [ split(/\s+/, $1) ] :
3974 [ &to_ipaddress(split(/\s+/, $1)) ];
3976 elsif ($user[4] =~ /^deny\s+(.*)/) {
3977 $deny{$user[0]} = $config{'alwaysresolve'} ?
3978 [ split(/\s+/, $1) ] :
3979 [ &to_ipaddress(split(/\s+/, $1)) ];
3981 if ($user[5] =~ /days\s+(\S+)/) {
3982 $allowdays{$user[0]} = [ split(/,/, $1) ];
3984 if ($user[5] =~ /hours\s+(\d+)\.(\d+)-(\d+).(\d+)/) {
3985 $allowhours{$user[0]} = [ $1*60+$2, $3*60+$4 ];
3987 $lastchanges{$user[0]} = $user[6];
3988 $nochange{$user[0]} = $user[9];
3989 $temppass{$user[0]} = $user[10];
3996 # Fills %mime with entries from file in %config and extra settings in %config
4000 if ($config{"mimetypes"} ne "") {
4001 open(MIME, $config{"mimetypes"});
4004 if (/^(\S+)\s+(.*)$/) {
4006 my @exts = split(/\s+/, $2);
4007 foreach my $ext (@exts) {
4008 $mime{$ext} = $type;
4014 foreach my $k (keys %config) {
4015 if ($k !~ /^addtype_(.*)$/) { next; }
4016 $mime{$1} = $config{$k};
4020 # build_config_mappings()
4021 # Build the anonymous access list, IP access list, unauthenticated URLs list,
4022 # redirect mapping and allow and deny lists from %config
4023 sub build_config_mappings
4025 # build anonymous access list
4027 foreach my $a (split(/\s+/, $config{'anonymous'})) {
4028 if ($a =~ /^([^=]+)=(\S+)$/) {
4029 $anonymous{$1} = $2;
4033 # build IP access list
4035 foreach my $a (split(/\s+/, $config{'ipaccess'})) {
4036 if ($a =~ /^([^=]+)=(\S+)$/) {
4041 # build unauthenticated URLs list
4042 @unauth = split(/\s+/, $config{'unauth'});
4044 # build redirect mapping
4046 foreach my $r (split(/\s+/, $config{'redirect'})) {
4047 if ($r =~ /^([^=]+)=(\S+)$/) {
4052 # build prefixes to be stripped
4053 undef(@strip_prefix);
4054 foreach my $r (split(/\s+/, $config{'strip_prefix'})) {
4055 push(@strip_prefix, $r);
4058 # Init allow and deny lists
4059 @deny = split(/\s+/, $config{"deny"});
4060 @deny = &to_ipaddress(@deny) if (!$config{'alwaysresolve'});
4061 @allow = split(/\s+/, $config{"allow"});
4062 @allow = &to_ipaddress(@allow) if (!$config{'alwaysresolve'});
4065 if ($config{'allowusers'}) {
4066 @allowusers = split(/\s+/, $config{'allowusers'});
4068 elsif ($config{'denyusers'}) {
4069 @denyusers = split(/\s+/, $config{'denyusers'});
4072 # Build list of unixauth mappings
4074 foreach my $ua (split(/\s+/, $config{'unixauth'})) {
4075 if ($ua =~ /^(\S+)=(\S+)$/) {
4079 $unixauth{"*"} = $ua;
4083 # Build list of non-session-auth pages
4084 undef(%sessiononly);
4085 foreach my $sp (split(/\s+/, $config{'sessiononly'})) {
4086 $sessiononly{$sp} = 1;
4089 # Build list of logout times
4090 undef(@logouttimes);
4091 foreach my $a (split(/\s+/, $config{'logouttimes'})) {
4092 if ($a =~ /^([^=]+)=(\S+)$/) {
4093 push(@logouttimes, [ $1, $2 ]);
4096 push(@logouttimes, [ undef, $config{'logouttime'} ]);
4098 # Build list of DAV pathss
4100 foreach my $d (split(/\s+/, $config{'davpaths'})) {
4101 push(@davpaths, $d);
4103 @davusers = split(/\s+/, $config{'dav_users'});
4105 # Mobile agent substrings and hostname prefixes
4106 @mobile_agents = split(/\t+/, $config{'mobile_agents'});
4107 @mobile_prefixes = split(/\s+/, $config{'mobile_prefixes'});
4111 if ($config{'debug'}) {
4112 open(DEBUG, ">>$config{'debug'}");
4115 open(DEBUG, ">/dev/null");
4118 # Reset cache of sudo checks
4122 # is_group_member(&uinfo, groupname)
4123 # Returns 1 if some user is a primary or secondary member of a group
4126 local ($uinfo, $group) = @_;
4127 local @ginfo = getgrnam($group);
4128 return 0 if (!@ginfo);
4129 return 1 if ($ginfo[2] == $uinfo->[3]); # primary member
4130 foreach my $m (split(/\s+/, $ginfo[3])) {
4131 return 1 if ($m eq $uinfo->[0]);
4136 # prefix_to_mask(prefix)
4137 # Converts a number like 24 to a mask like 255.255.255.0
4140 return $_[0] >= 24 ? "255.255.255.".(256-(2 ** (32-$_[0]))) :
4141 $_[0] >= 16 ? "255.255.".(256-(2 ** (24-$_[0]))).".0" :
4142 $_[0] >= 8 ? "255.".(256-(2 ** (16-$_[0]))).".0.0" :
4143 (256-(2 ** (8-$_[0]))).".0.0.0";
4146 # get_logout_time(user, session-id)
4147 # Given a username, returns the idle time before he will be logged out
4150 local ($user, $sid) = @_;
4151 if (!defined($logout_time_cache{$user,$sid})) {
4153 foreach my $l (@logouttimes) {
4154 if ($l->[0] =~ /^\@(.*)$/) {
4155 # Check group membership
4156 local @uinfo = getpwnam($user);
4157 if (@uinfo && &is_group_member(\@uinfo, $1)) {
4161 elsif ($l->[0] =~ /^\//) {
4162 # Check file contents
4163 open(FILE, $l->[0]);
4180 if ($l->[0] eq $user) {
4184 last if (defined($time));
4186 $logout_time_cache{$user,$sid} = $time;
4188 return $logout_time_cache{$user,$sid};
4191 # password_crypt(password, salt)
4192 # If the salt looks like MD5 and we have a library for it, perform MD5 hashing
4193 # of a password. Otherwise, do Unix crypt.
4196 local ($pass, $salt) = @_;
4197 if ($salt =~ /^\$1\$/ && $use_md5) {
4198 return &encrypt_md5($pass, $salt);
4201 return &unix_crypt($pass, $salt);
4205 # unix_crypt(password, salt)
4206 # Performs standard Unix hashing for a password
4209 local ($pass, $salt) = @_;
4210 if ($use_perl_crypt) {
4211 return Crypt::UnixCrypt::crypt($pass, $salt);
4214 return crypt($pass, $salt);
4218 # handle_dav_request(davpath)
4219 # Pass a request on to the Net::DAV::Server module
4220 sub handle_dav_request
4223 eval "use Filesys::Virtual::Plain";
4224 eval "use Net::DAV::Server";
4225 eval "use HTTP::Request";
4226 eval "use HTTP::Headers";
4228 if ($Net::DAV::Server::VERSION eq '1.28' && $config{'dav_nolock'}) {
4229 delete $Net::DAV::Server::implemented{lock};
4230 delete $Net::DAV::Server::implemented{unlock};
4233 # Read in request data
4234 if (!$posted_data) {
4235 local $clen = $header{"content-length"};
4236 while(length($posted_data) < $clen) {
4237 $buf = &read_data($clen - length($posted_data));
4238 if (!length($buf)) {
4239 &http_error(500, "Failed to read POST request");
4241 chomp($posted_data);
4242 #$posted_data =~ s/\015$//mg;
4243 $posted_data .= $buf;
4247 # For subsequent logging
4248 open(MINISERVLOG, ">>$config{'logfile'}");
4252 local @u = getpwnam($authuser);
4253 if ($config{'dav_remoteuser'} && !$< && $validated) {
4256 $( = $u[3]; $) = "$u[3] $u[3]";
4257 ($>, $<) = ($u[2], $u[2]);
4259 if ($config{'dav_root'} eq '*') {
4264 &http_error(500, "Unix user $authuser does not exist");
4268 $root ||= $config{'dav_root'};
4271 # Check if this user can use DAV
4273 &users_match(\@u, @davusers) ||
4274 &http_error(500, "You are not allowed to access DAV");
4278 my $filesys = Filesys::Virtual::Plain->new({root_path => $root});
4279 my $webdav = Net::DAV::Server->new();
4280 $webdav->filesys($filesys);
4282 # Make up a request object, and feed to DAV
4283 local $ho = HTTP::Headers->new;
4284 foreach my $h (keys %header) {
4285 next if (lc($h) eq "connection");
4286 $ho->header($h => $header{$h});
4289 $request_uri =~ s/^\Q$path\E//;
4290 $request_uri = "/" if ($request_uri eq "");
4292 my $request = HTTP::Request->new($method, $request_uri, $ho,
4294 if ($config{'dav_debug'}) {
4295 print STDERR "DAV request :\n";
4296 print STDERR "---------------------------------------------\n";
4297 print STDERR $request->as_string();
4298 print STDERR "---------------------------------------------\n";
4300 my $response = $webdav->run($request);
4302 # Send back the reply
4303 &write_data("HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n");
4304 local $content = $response->content();
4306 $content =~ s|href>/(.+)<|href>$path/$1<|g;
4307 $content =~ s|href>/<|href>$path<|g;
4309 foreach my $h ($response->header_field_names) {
4310 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4311 &write_data("$h: ",$response->header($h),"\r\n");
4313 &write_data("Content-length: ",length($content),"\r\n");
4314 local $rv = &write_keep_alive(0);
4315 &write_data("\r\n");
4316 &write_data($content);
4318 if ($config{'dav_debug'}) {
4319 print STDERR "DAV reply :\n";
4320 print STDERR "---------------------------------------------\n";
4321 print STDERR "HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n";
4322 foreach my $h ($response->header_field_names) {
4323 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4324 print STDERR "$h: ",$response->header($h),"\r\n";
4326 print STDERR "Content-length: ",length($content),"\r\n";
4327 print STDERR "\r\n";
4328 print STDERR $content;
4329 print STDERR "---------------------------------------------\n";
4333 &log_request($acpthost, $authuser, $reqline, $response->code(),
4334 length($response->content()));
4337 # get_system_hostname()
4338 # Returns the hostname of this system, for reporting to listeners
4339 sub get_system_hostname
4341 # On Windows, try computername environment variable
4342 return $ENV{'computername'} if ($ENV{'computername'});
4343 return $ENV{'COMPUTERNAME'} if ($ENV{'COMPUTERNAME'});
4345 # If a specific command is set, use it first
4346 if ($config{'hostname_command'}) {
4347 local $out = `($config{'hostname_command'}) 2>&1`;
4354 # First try the hostname command
4355 local $out = `hostname 2>&1`;
4356 if (!$? && $out =~ /\S/) {
4361 # Try the Sys::Hostname module
4362 eval "use Sys::Hostname";
4364 local $rv = eval "hostname()";
4370 # Must use net name on Windows
4371 local $out = `net name 2>&1`;
4372 if ($out =~ /\-+\r?\n(\S+)/) {
4379 # indexof(string, array)
4380 # Returns the index of some value in an array, or -1
4383 for($i=1; $i <= $#_; $i++) {
4384 if ($_[$i] eq $_[0]) { return $i - 1; }
4390 # has_command(command)
4391 # Returns the full path if some command is in the path, undef if not
4395 if (!$_[0]) { return undef; }
4396 if (exists($has_command_cache{$_[0]})) {
4397 return $has_command_cache{$_[0]};
4400 if ($_[0] =~ /^\//) {
4401 $rv = -x $_[0] ? $_[0] : undef;
4404 local $sp = $on_windows ? ';' : ':';
4405 foreach $d (split($sp, $ENV{PATH})) {
4406 if (-x "$d/$_[0]") {
4411 foreach my $sfx (".exe", ".com", ".bat") {
4412 if (-r "$d/$_[0]".$sfx) {
4413 $rv = "$d/$_[0]".$sfx;
4420 $has_command_cache{$_[0]} = $rv;
4424 # check_sudo_permissions(user, pass)
4425 # Returns 1 if some user can run any command via sudo
4426 sub check_sudo_permissions
4428 local ($user, $pass) = @_;
4430 # First try the pipes
4432 print DEBUG "check_sudo_permissions: querying cache for $user\n";
4433 print $PASSINw "readsudo $user\n";
4434 local $can = <$PASSOUTr>;
4436 print DEBUG "check_sudo_permissions: cache said $can\n";
4437 if ($can =~ /^\d+$/ && $can != 2) {
4442 local $ptyfh = new IO::Pty;
4443 print DEBUG "check_sudo_permissions: ptyfh=$ptyfh\n";
4445 print STDERR "Failed to create new PTY with IO::Pty\n";
4448 local @uinfo = getpwnam($user);
4450 print STDERR "Unix user $user does not exist for sudo\n";
4454 # Execute sudo in a sub-process, via a pty
4455 local $ttyfh = $ptyfh->slave();
4456 print DEBUG "check_sudo_permissions: ttyfh=$ttyfh\n";
4457 local $tty = $ptyfh->ttyname();
4458 print DEBUG "check_sudo_permissions: tty=$tty\n";
4459 chown($uinfo[2], $uinfo[3], $tty);
4461 print DEBUG "check_sudo_permissions: about to fork..\n";
4462 local $pid = fork();
4463 print DEBUG "check_sudo_permissions: fork=$pid pid=$$\n";
4465 print STDERR "fork for sudo failed : $!\n";
4470 $ptyfh->make_slave_controlling_terminal();
4471 close(STDIN); close(STDOUT); close(STDERR);
4472 untie(*STDIN); untie(*STDOUT); untie(*STDERR);
4473 close($PASSINw); close($PASSOUTr);
4474 $( = $uinfo[3]; $) = "$uinfo[3] $uinfo[3]";
4475 ($>, $<) = ($uinfo[2], $uinfo[2]);
4480 open(STDIN, "<&SUDOr");
4481 open(STDOUT, ">$tty");
4482 open(STDERR, ">&STDOUT");
4485 print "Exec failed : $!\n";
4488 print DEBUG "check_sudo_permissions: pid=$pid\n";
4490 $ptyfh->close_slave();
4492 # Send password, and get back response
4493 local $oldfh = select(SUDOw);
4496 print DEBUG "check_sudo_permissions: about to send pass\n";
4497 local $SIG{'PIPE'} = 'ignore'; # Sometimes sudo doesn't ask for a password
4498 print SUDOw $pass,"\n";
4499 print DEBUG "check_sudo_permissions: sent pass=$pass\n";
4503 print DEBUG "check_sudo_permissions: got $_";
4509 local ($ok) = ($out =~ /\(ALL\)\s+ALL/ ? 1 : 0);
4513 print $PASSINw "writesudo $user $ok\n";
4519 # is_mobile_useragent(agent)
4520 # Returns 1 if some user agent looks like a cellphone or other mobile device,
4522 sub is_mobile_useragent
4524 local ($agent) = @_;
4526 "UP.Link", # Openwave
4527 "Nokia", # All Nokias start with Nokia
4528 "MOT-", # All Motorola phones start with MOT-
4529 "SAMSUNG", # Samsung browsers
4530 "Samsung", # Samsung browsers
4531 "SEC-", # Samsung browsers
4532 "AU-MIC", # Samsung browsers
4533 "AUDIOVOX", # Audiovox
4534 "BlackBerry", # BlackBerry
4535 "hiptop", # Danger hiptop Sidekick
4536 "SonyEricsson", # Sony Ericsson
4537 "Ericsson", # Old Ericsson browsers , mostly WAP
4538 "Mitsu/1.1.A", # Mitsubishi phones
4539 "Panasonic WAP", # Panasonic old WAP phones
4540 "DoCoMo", # DoCoMo phones
4541 "Lynx", # Lynx text-mode linux browser
4542 "Links", # Another text-mode linux browser
4544 local @substrings = (
4545 "UP.Browser", # Openwave
4546 "MobilePhone", # NetFront
4547 "AU-MIC-A700", # Samsung A700 Obigo browsers
4548 "Danger hiptop", # Danger Sidekick hiptop
4549 "Windows CE", # Windows CE Pocket PC
4550 "IEMobile", # Windows mobile browser
4551 "Blazer", # Palm Treo Blazer
4552 "BlackBerry", # BlackBerries can emulate other browsers, but
4553 # they still keep this string in the UserAgent
4554 "SymbianOS", # New Series60 browser has safari in it and
4555 # SymbianOS is the only distinguishing string
4556 "iPhone", # Apple iPhone KHTML browser
4557 "iPod", # iPod touch browser
4558 "MobileSafari", # HTTP client in iPhone
4560 "Opera Mini", # Opera Mini
4561 "HTC_P3700", # HTC mobile device
4563 foreach my $p (@prefixes) {
4564 return 1 if ($agent =~ /^\Q$p\E/);
4566 foreach my $s (@substrings, @mobile_agents) {
4567 return 1 if ($agent =~ /\Q$s\E/);
4572 # write_blocked_file()
4573 # Writes out a text file of blocked hosts and users
4574 sub write_blocked_file
4576 open(BLOCKED, ">$config{'blockedfile'}");
4577 foreach my $d (grep { $hostfail{$_} } @deny) {
4578 print BLOCKED "host $d $hostfail{$d} $blockhosttime{$d}\n";
4580 foreach my $d (grep { $userfail{$_} } @denyusers) {
4581 print BLOCKED "user $d $userfail{$d} $blockusertime{$d}\n";
4584 chmod(0700, $config{'blockedfile'});
4589 open(PIDFILE, ">$config{'pidfile'}");
4590 printf PIDFILE "%d\n", getpid();
4594 # lock_user_password(user)
4595 # Updates a user's password file entry to lock it, both in memory and on disk.
4596 # Returns 1 if done, -1 if no such user, 0 if already locked
4597 sub lock_user_password
4600 if ($users{$user}) {
4601 if ($users{$user} !~ /^\!/) {
4603 $users{$user} = "!".$users{$user};
4604 open(USERS, $config{'userfile'});
4605 local @ufile = <USERS>;
4607 foreach my $u (@ufile) {
4608 local @uinfo = split(/:/, $u);
4609 if ($uinfo[0] eq $user) {
4610 $uinfo[1] = $users{$user};
4612 $u = join(":", @uinfo);
4614 open(USERS, ">$config{'userfile'}");
4624 # hash_session_id(sid)
4625 # Returns an MD5 or Unix-crypted session ID
4629 if (!$hash_session_id_cache{$sid}) {
4632 $hash_session_id_cache{$sid} = &encrypt_md5($sid);
4636 $hash_session_id_cache{$sid} = &unix_crypt($sid, "XX");
4639 return $hash_session_id_cache{$sid};
4642 # encrypt_md5(string, [salt])
4643 # Returns a string encrypted in MD5 format
4646 local ($passwd, $salt) = @_;
4647 local $magic = '$1$';
4648 if ($salt =~ /^\$1\$([^\$]+)/) {
4649 # Extract actual salt from already encrypted password
4654 local $ctx = eval "new $use_md5";
4661 # Add some more stuff from the hash of the password and salt
4662 local $ctx1 = eval "new $use_md5";
4663 $ctx1->add($passwd);
4667 $ctx1->add($passwd);
4668 local $final = $ctx1->digest();
4669 for($pl=length($passwd); $pl>0; $pl-=16) {
4670 $ctx->add($pl > 16 ? $final : substr($final, 0, $pl));
4673 # This piece of code seems rather pointless, but it's in the C code that
4674 # does MD5 in PAM so it has to go in!
4677 for($i=length($passwd); $i; $i >>= 1) {
4682 $ctx->add(substr($passwd, $j, 1));
4685 $final = $ctx->digest();
4688 # This loop exists only to waste time
4689 for($i=0; $i<1000; $i++) {
4690 $ctx1 = eval "new $use_md5";
4691 $ctx1->add($i & 1 ? $passwd : $final);
4692 $ctx1->add($salt) if ($i % 3);
4693 $ctx1->add($passwd) if ($i % 7);
4694 $ctx1->add($i & 1 ? $final : $passwd);
4695 $final = $ctx1->digest();
4699 # Convert the 16-byte final string into a readable form
4701 local @final = map { ord($_) } split(//, $final);
4702 $l = ($final[ 0]<<16) + ($final[ 6]<<8) + $final[12];
4703 $rv .= &to64($l, 4);
4704 $l = ($final[ 1]<<16) + ($final[ 7]<<8) + $final[13];
4705 $rv .= &to64($l, 4);
4706 $l = ($final[ 2]<<16) + ($final[ 8]<<8) + $final[14];
4707 $rv .= &to64($l, 4);
4708 $l = ($final[ 3]<<16) + ($final[ 9]<<8) + $final[15];
4709 $rv .= &to64($l, 4);
4710 $l = ($final[ 4]<<16) + ($final[10]<<8) + $final[ 5];
4711 $rv .= &to64($l, 4);
4713 $rv .= &to64($l, 2);
4715 # Add salt if needed
4717 return $magic.$salt.'$'.$rv;
4726 local ($v, $n) = @_;
4729 $r .= $itoa64[$v & 0x3f];