2 # A very simple perl web server used by Webmin
4 # Require basic libraries
10 @itoa64 = split(//, "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
12 # Find and read config file
14 die "Usage: miniserv.pl <config file>";
16 if ($ARGV[0] =~ /^([a-z]:)?\//i) {
17 $config_file = $ARGV[0];
21 $config_file = "$pwd/$ARGV[0]";
23 %config = &read_config_file($config_file);
24 if ($config{'perllib'}) {
25 push(@INC, split(/:/, $config{'perllib'}));
26 $ENV{'PERLLIB'} .= ':'.$config{'perllib'};
29 # Check is SSL is enabled and available
31 eval "use Net::SSLeay";
34 # These functions only exist for SSLeay 1.0
35 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
36 eval "Net::SSLeay::load_error_strings()";
37 if ($config{'no_ssl2'}) {
38 eval "Net::SSLeay::CTX_set_options($ctx,&Net::SSLeay::OP_NO_SSLv2)";
40 if (defined(&Net::SSLeay::X509_STORE_CTX_get_current_cert) &&
41 defined(&Net::SSLeay::CTX_load_verify_locations) &&
42 defined(&Net::SSLeay::CTX_set_verify)) {
48 # Check if the syslog module is available to log hacking attempts
49 if ($config{'syslog'} && !$config{'inetd'}) {
50 eval "use Sys::Syslog qw(:DEFAULT setlogsock)";
56 # check if the TCP-wrappers module is available
57 if ($config{'libwrap'}) {
58 eval "use Authen::Libwrap qw(hosts_ctl STRING_UNKNOWN)";
64 # Check if the MD5 perl module is available
70 eval "use Digest::MD5";
72 $use_md5 = "Digest::MD5";
76 # Get miniserv's perl path and location
78 open(SOURCE, $miniserv_path);
79 <SOURCE> =~ /^#!(\S+)/;
86 $linked_perl_path = readlink($perl_path);
88 @miniserv_argv = @ARGV;
90 # Check vital config options
91 &update_vital_config();
93 $sidname = $config{'sidname'};
94 die "Session authentication cannot be used in inetd mode"
95 if ($config{'inetd'} && $config{'session'});
97 # check if the PAM module is available to authenticate
98 if (!$config{'no_pam'}) {
99 eval "use Authen::PAM;";
101 # check if the PAM authentication can be used by opening a
104 if (ref($pamh = new Authen::PAM($config{'pam'},
105 $config{'pam_test_user'},
107 # Now test a login to see if /etc/pam.d/XXX is set
109 $pam_conv_func_called = 0;
110 $pam_username = "test";
111 $pam_password = "test";
112 $pamh->pam_authenticate();
113 if ($pam_conv_func_called) {
114 $pam_msg = "PAM authentication enabled";
118 $pam_msg = "PAM test failed - maybe /etc/pam.d/$config{'pam'} does not exist";
122 $pam_msg = "PAM initialization of Authen::PAM failed";
126 $pam_msg = "Perl module Authen::PAM needed for PAM is not installed : $@";
129 if ($config{'pam_only'} && !$use_pam) {
130 print STDERR $pam_msg;
131 print STDERR "PAM use is mandatory, but could not be enabled!\n";
134 elsif ($pam_msg && !$use_pam) {
135 $pam_msg2 = "Continuing without the Authen::PAM perl module";
138 # Check if the User::Utmp perl module is installed
139 if ($config{'utmp'}) {
140 eval "use User::Utmp;";
143 $utmp_msg = "UTMP logging enabled";
146 $utmp_msg = "Perl module User::Utmp needed for Utmp logging is not installed : $@";
150 # See if the crypt function fails
151 eval "crypt('foo', 'xx')";
153 eval "use Crypt::UnixCrypt";
156 $crypt_msg = "Using Crypt::UnixCrypt for password encryption\n";
159 $crypt_msg = "crypt() function un-implemented, and Crypt::UnixCrypt not installed - password authentication will probably fail\n";
163 # Check if /dev/urandom really generates random IDs, by calling it twice
164 local $rand1 = &generate_random_id("foo", 1);
165 local $rand2 = &generate_random_id("foo", 2);
167 if ($rand1 eq $rand2) {
169 $rand_msg = "Random number generator file /dev/urandom is not reliable";
172 # Check if we can call sudo
173 if ($config{'sudo'} && &has_command("sudo")) {
179 $sudo_msg = "Perl module IO::Pty needed for calling sudo is not installed : $@";
183 # init days and months for http_date
184 @weekday = ( "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" );
185 @month = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun",
186 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" );
188 # Change dir to the server root
189 @roots = ( $config{'root'} );
190 for($i=0; defined($config{"extraroot_$i"}); $i++) {
191 push(@roots, $config{"extraroot_$i"});
194 eval { $user_homedir = (getpwuid($<))[7]; };
196 # getpwuid doesn't work on windows
197 $user_homedir = $ENV{"HOME"} || $ENV{"USERPROFILE"} || "/";
204 # Setup SSL if possible and if requested
205 if (!-r $config{'keyfile'} ||
206 $config{'certfile'} && !-r $config{'certfile'}) {
207 # Key file doesn't exist!
210 @ipkeys = &get_ipkeys(\%config);
212 if ($config{'ssl_version'}) {
213 # Force an SSL version
214 $Net::SSLeay::version = $config{'ssl_version'};
215 $Net::SSLeay::ssl_version = $config{'ssl_version'};
217 $client_certs = 0 if (!-r $config{'ca'} || !%certs);
218 $ssl_contexts{"*"} = &create_ssl_context($config{'keyfile'},
219 $config{'certfile'});
220 foreach $ipkey (@ipkeys) {
221 $ctx = &create_ssl_context($ipkey->{'key'}, $ipkey->{'cert'});
222 foreach $ip (@{$ipkey->{'ips'}}) {
223 $ssl_contexts{$ip} = $ctx;
228 # Setup syslog support if possible and if requested
230 open(ERRDUP, ">&STDERR");
231 open(STDERR, ">/dev/null");
232 $log_socket = $config{"logsock"} || "unix";
233 eval 'openlog($config{"pam"}, "cons,pid,ndelay", "authpriv"); setlogsock($log_socket)';
238 local $msg = ucfirst($config{'pam'})." starting";
239 eval { syslog("info", "%s", $msg); };
243 syslog("info", "%s", $msg);
246 # All attempts to use syslog have failed..
251 open(STDERR, ">&ERRDUP");
255 # Read MIME types file and add extra types
259 if ($config{'log'}) {
260 local(@gmt, @lct, $days, $hours, $mins);
261 @gmt = gmtime(time());
262 @lct = localtime(time());
263 $days = $lct[3] - $gmt[3];
264 $hours = ($days < -1 ? 24 : 1 < $days ? -24 : $days * 24) +
266 $mins = $hours * 60 + $lct[1] - $gmt[1];
267 $timezone = ($mins < 0 ? "-" : "+"); $mins = abs($mins);
268 $timezone .= sprintf "%2.2d%2.2d", $mins/60, $mins%60;
271 # Build various maps from the config files
272 &build_config_mappings();
274 # start up external authentication program, if needed
275 if ($config{'extauth'}) {
276 socketpair(EXTAUTH, EXTAUTH2, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
277 if (!($extauth = fork())) {
281 open(STDIN, "<&EXTAUTH2");
282 open(STDOUT, ">&EXTAUTH2");
283 exec($config{'extauth'}) or die "exec failed : $!\n";
286 local $os = select(EXTAUTH);
290 # Pre-load any libraries
291 if (!$config{'inetd'}) {
292 foreach $pl (split(/\s+/, $config{'preload'})) {
293 ($pkg, $lib) = split(/=/, $pl);
294 $pkg =~ s/[^A-Za-z0-9]/_/g;
295 eval "package $pkg; do '$config{'root'}/$lib'";
297 print STDERR "Failed to pre-load $lib in $pkg : $@\n";
300 print STDERR "Pre-loaded $lib in $pkg\n";
303 foreach $pl (split(/\s+/, $config{'premodules'})) {
305 ($dir, $mod) = split(/\//, $pl);
308 ($dir, $mod) = (undef, $pl);
310 push(@INC, "$config{'root'}/$dir");
311 eval "package $mod; use $mod ()";
313 print STDERR "Failed to pre-load $mod : $@\n";
316 print STDERR "Pre-loaded $mod\n";
321 # Open debug log if set
322 if ($config{'debuglog'}) {
323 open(DEBUG, ">>$config{'debuglog'}");
324 chmod(0700, $config{'debuglog'});
325 select(DEBUG); $| = 1; select(STDOUT);
326 print DEBUG "miniserv.pl starting ..\n";
329 # Write out (empty) blocked hosts file
330 &write_blocked_file();
332 # Re-direct STDERR to a log file
333 if ($config{'errorlog'} ne '-') {
334 open(STDERR, ">>$config{'errorlog'}") || die "failed to open $config{'errorlog'} : $!";
335 if ($config{'logperms'}) {
336 chmod(oct($config{'logperms'}), $config{'errorlog'});
339 select(STDERR); $| = 1; select(STDOUT);
341 if ($config{'inetd'}) {
342 # We are being run from inetd - go direct to handling the request
343 $SIG{'HUP'} = 'IGNORE';
344 $SIG{'TERM'} = 'DEFAULT';
345 $SIG{'PIPE'} = 'DEFAULT';
346 open(SOCK, "+>&STDIN");
348 # Check if it is time for the logfile to be cleared
349 if ($config{'logclear'}) {
350 local $write_logtime = 0;
351 local @st = stat("$config{'logfile'}.time");
353 if ($st[9]+$config{'logtime'}*60*60 < time()){
356 unlink($config{'logfile'});
359 else { $write_logtime = 1; }
360 if ($write_logtime) {
361 open(LOGTIME, ">$config{'logfile'}.time");
362 print LOGTIME time(),"\n";
367 # Initialize SSL for this connection
369 $ssl_con = &ssl_connection_for_ip(SOCK);
373 # Work out the hostname for this web server
374 $host = &get_socket_name(SOCK);
376 $port = $config{'port'};
377 $acptaddr = getpeername(SOCK);
380 print DEBUG "main: Starting handle_request loop pid=$$\n";
381 while(&handle_request($acptaddr, getsockname(SOCK))) { }
382 print DEBUG "main: Done handle_request loop pid=$$\n";
387 # Build list of sockets to listen on
388 if ($config{"bind"} && $config{"bind"} ne "*") {
389 push(@sockets, [ inet_aton($config{'bind'}), $config{'port'} ]);
392 push(@sockets, [ INADDR_ANY, $config{'port'} ]);
394 foreach $s (split(/\s+/, $config{'sockets'})) {
395 if ($s =~ /^(\d+)$/) {
396 # Just listen on another port on the main IP
397 push(@sockets, [ $sockets[0]->[0], $s ]);
399 elsif ($s =~ /^(\S+):(\d+)$/) {
400 # Listen on a specific port and IP
401 push(@sockets, [ $1 eq "*" ? INADDR_ANY : inet_aton($1), $2 ]);
403 elsif ($s =~ /^([0-9\.]+):\*$/ || $s =~ /^([0-9\.]+)$/) {
404 # Listen on the main port on another IP
405 push(@sockets, [ inet_aton($1), $sockets[0]->[1] ]);
409 # Open all the sockets
410 $proto = getprotobyname('tcp');
412 $tried_inaddr_any = 0;
413 for($i=0; $i<@sockets; $i++) {
415 socket($fh, PF_INET, SOCK_STREAM, $proto) ||
416 die "Failed to open socket : $!";
417 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
418 for($j=0; $j<5; $j++) {
419 last if (bind($fh, pack_sockaddr_in($sockets[$i]->[1],
420 $sockets[$i]->[0])));
424 # All attempts failed .. give up
425 if ($sockets[$i]->[0] eq INADDR_ANY) {
426 push(@sockerrs, "Failed to bind to port $sockets[$i]->[1] : $!");
427 $tried_inaddr_any = 1;
430 $ip = inet_ntoa($sockets[$i]->[0]);
431 push(@sockerrs, "Failed to bind to IP $ip port $sockets[$i]->[1] : $!");
435 listen($fh, SOMAXCONN);
436 push(@socketfhs, $fh);
439 foreach $se (@sockerrs) {
440 print STDERR $se,"\n";
443 # If all binds failed, try binding to any address
444 if (!@socketfhs && !$tried_inaddr_any) {
445 print STDERR "Falling back to listening on any address\n";
447 socket($fh, PF_INET, SOCK_STREAM, $proto) ||
448 die "Failed to open socket : $!";
449 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
450 bind($fh, pack_sockaddr_in($sockets[0]->[1], INADDR_ANY)) ||
451 die "Failed to bind to port $sockets[0]->[1] : $!";
452 listen($fh, SOMAXCONN);
453 push(@socketfhs, $fh);
455 elsif (!@socketfhs && $tried_inaddr_any) {
456 die "Could not listen on any ports";
459 if ($config{'listen'}) {
460 # Open the socket that allows other webmin servers to find this one
461 $proto = getprotobyname('udp');
462 if (socket(LISTEN, PF_INET, SOCK_DGRAM, $proto)) {
463 setsockopt(LISTEN, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
464 bind(LISTEN, pack_sockaddr_in($config{'listen'}, INADDR_ANY));
465 listen(LISTEN, SOMAXCONN);
468 $config{'listen'} = 0;
472 # Split from the controlling terminal, unless configured not to
473 if (!$config{'nofork'}) {
474 if (fork()) { exit; }
476 eval { setsid(); }; # may not work on Windows
478 # Close standard file handles
479 open(STDIN, "</dev/null");
480 open(STDOUT, ">/dev/null");
481 &log_error("miniserv.pl started");
482 &log_error($pam_msg) if ($pam_msg);
483 &log_error($pam_msg2) if ($pam_msg2);
484 &log_error($utmp_msg) if ($utmp_msg);
485 &log_error($crypt_msg) if ($crypt_msg);
486 &log_error($sudo_msg) if ($sudo_msg);
487 &log_error($rand_msg) if ($rand_msg);
489 # write out the PID file
492 # Start the log-clearing process, if needed. This checks every minute
493 # to see if the log has passed its reset time, and if so clears it
494 if ($config{'logclear'}) {
495 if (!($logclearer = fork())) {
496 &close_all_sockets();
499 local $write_logtime = 0;
500 local @st = stat("$config{'logfile'}.time");
502 if ($st[9]+$config{'logtime'}*60*60 < time()){
505 unlink($config{'logfile'});
508 else { $write_logtime = 1; }
509 if ($write_logtime) {
510 open(LOGTIME, ">$config{'logfile'}.time");
511 print LOGTIME time(),"\n";
518 push(@childpids, $logclearer);
521 # Setup the logout time dbm if needed
522 if ($config{'session'}) {
523 eval "use SDBM_File";
524 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
525 eval "\$sessiondb{'1111111111'} = 'foo bar';";
527 dbmclose(%sessiondb);
528 eval "use NDBM_File";
529 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
532 delete($sessiondb{'1111111111'});
537 $SIG{'HUP'} = 'miniserv::trigger_restart';
538 $SIG{'TERM'} = 'miniserv::term_handler';
539 $SIG{'USR1'} = 'miniserv::trigger_reload';
540 $SIG{'PIPE'} = 'IGNORE';
541 local $remove_session_count = 0;
542 $need_pipes = $config{'passdelay'} || $config{'session'};
544 # wait for a new connection, or a message from a child process
546 if (@childpids <= $config{'maxconns'}) {
547 # Only accept new main socket connects when ready
549 foreach $s (@socketfhs) {
550 vec($rmask, fileno($s), 1) = 1;
554 printf STDERR "too many children (%d > %d)\n",
555 scalar(@childpids), $config{'maxconns'};
558 for($i=0; $i<@passin; $i++) {
559 vec($rmask, fileno($passin[$i]), 1) = 1;
562 vec($rmask, fileno(LISTEN), 1) = 1 if ($config{'listen'});
564 # Wait for a connection
565 local $sel = select($rmask, undef, undef, 10);
567 # Check the flag files
568 if ($config{'restartflag'} && -r $config{'restartflag'}) {
569 print STDERR "restart flag file detected\n";
570 unlink($config{'restartflag'});
573 if ($config{'reloadflag'} && -r $config{'reloadflag'}) {
574 unlink($config{'reloadflag'});
579 # Got a HUP signal while in select() .. restart now
583 # Got a USR1 signal while in select() .. re-read config
585 &reload_config_file();
587 local $time_now = time();
589 # Clean up finished processes
591 do { $pid = waitpid(-1, WNOHANG);
592 @childpids = grep { $_ != $pid } @childpids;
593 } while($pid != 0 && $pid != -1);
595 # run the unblocking procedure to check if enough time has passed to
596 # unblock hosts that heve been blocked because of password failures
598 if ($config{'blockhost_failures'}) {
600 while ($i <= $#deny) {
601 if ($blockhosttime{$deny[$i]} &&
602 $config{'blockhost_time'} != 0 &&
603 ($time_now - $blockhosttime{$deny[$i]}) >=
604 $config{'blockhost_time'}) {
605 # the host can be unblocked now
606 $hostfail{$deny[$i]} = 0;
607 splice(@deny, $i, 1);
614 # Do the same for blocked users
615 if ($config{'blockuser_failures'}) {
617 while ($i <= $#deny) {
618 if ($blockusertime{$deny[$i]} &&
619 $config{'blockuser_time'} != 0 &&
620 ($time_now - $blockusertime{$deny[$i]}) >=
621 $config{'blockuser_time'}) {
622 # the user can be unblocked now
623 $userfail{$deny[$i]} = 0;
624 splice(@denyusers, $i, 1);
631 &write_blocked_file();
634 if ($config{'session'} && (++$remove_session_count%50) == 0) {
635 # Remove sessions with more than 7 days of inactivity,
637 foreach $s (keys %sessiondb) {
638 local ($user, $ltime, $lip) =
639 split(/\s+/, $sessiondb{$s});
640 if ($time_now - $ltime > 7*24*60*60) {
641 &run_logout_script($s, $user);
642 &write_logout_utmp($user, $lip);
643 delete($sessiondb{$s});
646 "Timeout of session for $user");
652 if ($use_pam && $config{'pam_conv'}) {
653 # Remove PAM sessions with more than 5 minutes of inactivity
655 foreach $c (values %conversations) {
656 if ($time_now - $c->{'time'} > 5*60) {
657 &end_pam_conversation($c);
659 syslog("info", "%s", "Timeout of PAM ".
660 "session for $c->{'user'}");
666 # Don't check any sockets if there is no activity
669 # Check if any of the main sockets have received a new connection
671 foreach $s (@socketfhs) {
672 if (vec($rmask, fileno($s), 1)) {
674 $acptaddr = accept(SOCK, $s);
675 if (!$acptaddr) { next; }
676 binmode(SOCK); # turn off any Perl IO stuff
679 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
681 ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw) =
685 # Check username of connecting user
686 local ($peerp, $peera) = unpack_sockaddr_in($acptaddr);
687 $localauth_user = undef;
688 if ($config{'localauth'} && inet_ntoa($peera) eq "127.0.0.1") {
689 if (open(TCP, "/proc/net/tcp")) {
690 # Get the info direct from the kernel
693 local @t = split(/[\s:]+/, $_);
694 if ($t[1] eq '0100007F' &&
695 $t[2] eq sprintf("%4.4X", $peerp)) {
696 $localauth_user = getpwuid($t[11]);
702 if (!$localauth_user) {
703 # Call lsof for the info
704 local $lsofpid = open(LSOF,
705 "$config{'localauth'} -i TCP\@127.0.0.1:$peerp |");
707 if (/^(\S+)\s+(\d+)\s+(\S+)/ &&
708 $2 != $$ && $2 != $lsofpid) {
709 $localauth_user = $3;
716 # Work out the hostname for this web server
717 $host = &get_socket_name(SOCK);
719 print STDERR "Failed to get local socket name : $!\n";
723 $port = $sockets[$sn]->[1];
725 # fork the subprocess
727 if (!($handpid = fork())) {
728 # setup signal handlers
729 $SIG{'TERM'} = 'DEFAULT';
730 $SIG{'PIPE'} = 'DEFAULT';
731 #$SIG{'CHLD'} = 'IGNORE';
732 $SIG{'HUP'} = 'IGNORE';
733 $SIG{'USR1'} = 'IGNORE';
735 # Initialize SSL for this connection
737 $ssl_con = &ssl_connection_for_ip(SOCK);
741 # Close the file handle for the session DBM
742 dbmclose(%sessiondb);
744 # close useless pipes
747 close($PASSINr); close($PASSOUTw);
749 &close_all_sockets();
753 "main: Starting handle_request loop pid=$$\n";
754 while(&handle_request($acptaddr,
755 getsockname(SOCK))) { }
757 "main: Done handle_request loop pid=$$\n";
760 close($PASSINw); close($PASSOUTw);
763 push(@childpids, $handpid);
765 close($PASSINw); close($PASSOUTr);
766 push(@passin, $PASSINr);
767 push(@passout, $PASSOUTw);
774 if ($config{'listen'} && vec($rmask, fileno(LISTEN), 1)) {
775 # Got UDP packet from another webmin server
777 local $from = recv(LISTEN, $rcvbuf, 1024, 0);
779 local $fromip = inet_ntoa((unpack_sockaddr_in($from))[1]);
780 local $toip = inet_ntoa((unpack_sockaddr_in(
781 getsockname(LISTEN)))[1]);
782 if ((!@deny || !&ip_match($fromip, $toip, @deny)) &&
783 (!@allow || &ip_match($fromip, $toip, @allow))) {
784 local $listenhost = &get_socket_name(LISTEN);
785 send(LISTEN, "$listenhost:$config{'port'}:".
786 ($use_ssl || $config{'inetd_ssl'} ? 1 : 0).":".
787 ($config{'listenhost'} ?
788 &get_system_hostname() : ""),
794 # check for session, password-timeout and PAM messages from subprocesses
795 for($i=0; $i<@passin; $i++) {
796 if (vec($rmask, fileno($passin[$i]), 1)) {
797 # this sub-process is asking about a password
798 local $infd = $passin[$i];
799 local $outfd = $passout[$i];
800 #local $inline = <$infd>;
801 local $inline = &sysread_line($infd);
803 print DEBUG "main: inline $inline";
806 print DEBUG "main: inline EOF\n";
808 if ($inline =~ /^delay\s+(\S+)\s+(\S+)\s+(\d+)/) {
809 # Got a delay request from a subprocess.. for
810 # valid logins, there is no delay (to prevent
811 # denial of service attacks), but for invalid
812 # logins the delay increases with each failed
815 # login OK.. no delay
816 print $outfd "0 0\n";
817 $wasblocked = $hostfail{$2} ||
822 &write_blocked_file();
831 # add the host to the block list,
833 if ($config{'blockhost_failures'} &&
835 $config{'blockhost_failures'}) {
837 $blockhosttime{$2} = $time_now;
840 local $logtext = "Security alert: Host $2 blocked after $config{'blockhost_failures'} failed logins for user $1";
846 # add the user to the user block list,
848 if ($config{'blockuser_failures'} &&
850 $config{'blockuser_failures'}) {
851 push(@denyusers, $1);
852 $blockusertime{$1} = $time_now;
855 local $logtext = "Security alert: User $1 blocked after $config{'blockuser_failures'} failed logins";
861 # Lock out the user's password, if enabled
862 if ($config{'blocklock'} &&
864 $config{'blockuser_failures'}) {
865 my $lk = &lock_user_password($1);
868 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";
875 $dl = $userdlay{$1} -
876 int(($time_now - $userlast{$1})/50);
877 $dl = $dl < 0 ? 0 : $dl+1;
878 print $outfd "$dl $blocked\n";
881 # Write out blocked status file
883 &write_blocked_file();
886 $userlast{$1} = $time_now;
888 elsif ($inline =~ /^verify\s+(\S+)\s+(\S+)/) {
889 # Verifying a session ID
890 local $session_id = $1;
891 local $notimeout = $2;
892 local $skey = $sessiondb{$session_id} ?
894 &hash_session_id($session_id);
895 if (!defined($sessiondb{$skey})) {
896 # Session doesn't exist
897 print $outfd "0 0\n";
900 local ($user, $ltime) =
901 split(/\s+/, $sessiondb{$skey});
902 local $lot = &get_logout_time($user, $session_id);
904 $time_now - $ltime > $lot*60 &&
906 # Session has timed out
907 print $outfd "1 ",$time_now - $ltime,"\n";
908 #delete($sessiondb{$skey});
912 print $outfd "2 $user\n";
916 $sessiondb{$skey} = "$user $time_now";
921 elsif ($inline =~ /^new\s+(\S+)\s+(\S+)\s+(\S+)/) {
922 # Creating a new session
923 local $session_id = $1;
926 $sessiondb{&hash_session_id($session_id)} =
927 "$user $time_now $ip";
929 elsif ($inline =~ /^delete\s+(\S+)/) {
930 # Logging out a session
931 local $session_id = $1;
932 local $skey = $sessiondb{$session_id} ?
934 &hash_session_id($session_id);
935 local @sdb = split(/\s+/, $sessiondb{$skey});
936 print $outfd $sdb[0],"\n";
937 delete($sessiondb{$skey});
939 elsif ($inline =~ /^pamstart\s+(\S+)\s+(\S+)\s+(.*)/) {
940 # Starting a new PAM conversation
941 local ($cid, $host, $user) = ($1, $2, $3);
943 # Does this user even need PAM?
944 local ($realuser, $canlogin) =
945 &can_user_login($user, undef, $host);
947 if ($canlogin == 0) {
949 print $outfd "0 Invalid username\n";
951 elsif ($canlogin != 2) {
952 # Not using PAM .. so just ask for
954 $conv = { 'user' => $realuser,
959 print $outfd "3 Password\n";
962 # Start the PAM conversation
963 # sub-process, and get a question
964 $conv = { 'user' => $realuser,
968 local ($PAMINr, $PAMINw, $PAMOUTr,
969 $PAMOUTw) = &allocate_pipes();
970 local $pampid = fork();
972 close($PAMOUTr); close($PAMINw);
973 &pam_conversation_process(
977 close($PAMOUTw); close($PAMINr);
978 $conv->{'pid'} = $pampid;
979 $conv->{'PAMOUTr'} = $PAMOUTr;
980 $conv->{'PAMINw'} = $PAMINw;
981 push(@childpids, $pampid);
983 # Get the first PAM question
984 local $pok = &recv_pam_question(
987 &end_pam_conversation($conv);
991 $conversations{$cid} = $conv if ($conv);
993 elsif ($inline =~ /^pamanswer\s+(\S+)\s+(.*)/) {
994 # A response to a PAM question
995 local ($cid, $answer) = ($1, $2);
996 local $conv = $conversations{$cid};
998 # No such conversation?
999 print $outfd "0 Bad login session\n";
1001 elsif ($conv->{'pid'}) {
1002 # Send the PAM response and get
1004 &send_pam_answer($conv, $answer);
1005 local $pok = &recv_pam_question($conv, $outfd);
1007 &end_pam_conversation($conv);
1011 # This must be the password .. try it
1012 # and send back the results
1013 local ($vu, $expired, $nonexist) =
1014 &validate_user($conv->{'user'},
1017 local $ok = $vu ? 1 : 0;
1018 print $outfd "2 $conv->{'user'} $ok $expired $notexist\n";
1019 &end_pam_conversation($conv);
1022 elsif ($inline =~ /^writesudo\s+(\S+)\s+(\d+)/) {
1023 # Store the fact that some user can sudo to root
1024 local ($user, $ok) = ($1, $2);
1025 $sudocache{$user} = $ok." ".time();
1027 elsif ($inline =~ /^readsudo\s+(\S+)/) {
1028 # Query the user sudo cache (valid for 1 minute)
1030 local ($ok, $last) =
1031 split(/\s+/, $sudocache{$user});
1032 if ($last < time()-60) {
1037 # Tell client OK or not
1038 print $outfd "$ok\n";
1041 elsif ($inline =~ /\S/) {
1042 # Unknown line from pipe?
1043 print DEBUG "main: Unknown line from pipe $inline\n";
1044 print STDERR "Unknown line from pipe $inline\n";
1048 close($infd); close($outfd);
1049 $passin[$i] = $passout[$i] = undef;
1053 @passin = grep { defined($_) } @passin;
1054 @passout = grep { defined($_) } @passout;
1057 # handle_request(remoteaddress, localaddress)
1058 # Where the real work is done
1061 $acptip = inet_ntoa((unpack_sockaddr_in($_[0]))[1]);
1062 $localip = $_[1] ? inet_ntoa((unpack_sockaddr_in($_[1]))[1]) : undef;
1063 print DEBUG "handle_request: from $acptip to $localip\n";
1064 if ($config{'loghost'}) {
1065 $acpthost = gethostbyaddr(inet_aton($acptip), AF_INET);
1066 $acpthost = $acptip if (!$acpthost);
1069 $acpthost = $acptip;
1071 $datestr = &http_date(time());
1073 $ok_message = "Document follows";
1074 $logged_code = undef;
1075 $reqline = $request_uri = $page = undef;
1079 # check address against access list
1080 if (@deny && &ip_match($acptip, $localip, @deny) ||
1081 @allow && !&ip_match($acptip, $localip, @allow)) {
1082 &http_error(403, "Access denied for $acptip");
1087 # Check address with TCP-wrappers
1088 if (!hosts_ctl($config{'pam'}, STRING_UNKNOWN,
1089 $acptip, STRING_UNKNOWN)) {
1090 &http_error(403, "Access denied for $acptip by TCP wrappers");
1094 print DEBUG "handle_request: passed IP checks\n";
1096 # Compute a timeout for the start of headers, based on the number of
1097 # child processes. As this increases, we use a shorter timeout to avoid
1098 # an attacker overloading the system.
1099 local $header_timeout = 60 + ($config{'maxconns'} - @childpids) * 10;
1101 # Wait at most 60 secs for start of headers for initial requests, or
1102 # 10 minutes for kept-alive connections
1104 vec($rmask, fileno(SOCK), 1) = 1;
1105 local $to = $checked_timeout ? 10*60 : $header_timeout;
1106 local $sel = select($rmask, undef, undef, $to);
1108 if ($checked_timeout) {
1109 print DEBUG "handle_request: exiting due to timeout of $to\n";
1113 &http_error(400, "Timeout",
1114 "Waited for that $to seconds for start of headers");
1118 print DEBUG "handle_request: passed timeout check\n";
1120 # Read the HTTP request and headers
1121 local $origreqline = &read_line();
1122 ($reqline = $origreqline) =~ s/\r|\n//g;
1123 $method = $page = $request_uri = undef;
1124 print DEBUG "handle_request reqline=$reqline\n";
1125 if (!$reqline && (!$use_ssl || $checked_timeout > 1)) {
1126 # An empty request .. just close the connection
1127 print DEBUG "handle_request: rejecting empty request\n";
1130 elsif ($reqline !~ /^(\S+)\s+(.*)\s+HTTP\/1\..$/) {
1131 print DEBUG "handle_request: invalid reqline=$reqline\n";
1133 # This could be an http request when it should be https
1135 local $url = $config{'musthost'} ?
1136 "https://$config{'musthost'}:$port/" :
1137 "https://$host:$port/";
1138 if ($config{'ssl_redirect'}) {
1139 # Just re-direct to the correct URL
1140 sleep(1); # Give browser a change to finish
1141 # sending its request
1142 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1143 &write_data("Date: $datestr\r\n");
1144 &write_data("Server: $config{'server'}\r\n");
1145 &write_data("Location: $url\r\n");
1146 &write_keep_alive(0);
1147 &write_data("\r\n");
1151 # Tell user the correct URL
1152 &http_error(200, "Bad Request", "This web server is running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1155 elsif (ord(substr($reqline, 0, 1)) == 128 && !$use_ssl) {
1156 # This could be an https request when it should be http ..
1157 # need to fake a HTTP response
1160 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
1161 eval "Net::SSLeay::load_error_strings()";
1162 $ssl_ctx = Net::SSLeay::CTX_new();
1163 Net::SSLeay::CTX_use_RSAPrivateKey_file(
1164 $ssl_ctx, $config{'keyfile'},
1165 &Net::SSLeay::FILETYPE_PEM);
1166 Net::SSLeay::CTX_use_certificate_file(
1168 $config{'certfile'} || $config{'keyfile'},
1169 &Net::SSLeay::FILETYPE_PEM);
1170 $ssl_con = Net::SSLeay::new($ssl_ctx);
1174 select(SSLw); $| = 1; select(STDOUT);
1175 print SSLw $origreqline;
1177 while(sysread(SOCK, $buf, 1) > 0) {
1184 Net::SSLeay::set_wfd($ssl_con, fileno(SOCK));
1185 Net::SSLeay::set_rfd($ssl_con, fileno(SSLr));
1186 Net::SSLeay::accept($ssl_con) || die "accept() failed";
1188 local $url = $config{'musthost'} ?
1189 "https://$config{'musthost'}:$port/" :
1190 "https://$host:$port/";
1191 if ($config{'ssl_redirect'}) {
1192 # Just re-direct to the correct URL
1193 sleep(1); # Give browser a change to
1194 # finish sending its request
1195 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1196 &write_data("Date: $datestr\r\n");
1197 &write_data("Server: $config{'server'}\r\n");
1198 &write_data("Location: $url\r\n");
1199 &write_keep_alive(0);
1200 &write_data("\r\n");
1204 # Tell user the correct URL
1205 &http_error(200, "Bad Request", "This web server is not running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1209 &http_error(400, "Bad Request");
1213 &http_error(400, "Bad Request");
1217 $request_uri = $page = $2;
1221 ($headline = &read_line()) =~ s/\r|\n//g;
1222 last if ($headline eq "");
1223 print DEBUG "handle_request: got headline $headline\n";
1224 if ($headline =~ /^(\S+):\s*(.*)$/) {
1225 $header{$lastheader = lc($1)} = $2;
1227 elsif ($headline =~ /^\s+(.*)$/) {
1228 $header{$lastheader} .= $headline;
1231 &http_error(400, "Bad Header $headline");
1234 if (defined($header{'host'})) {
1235 if ($header{'host'} =~ /^([^:]+):([0-9]+)$/) {
1236 ($host, $port) = ($1, $2);
1239 $host = $header{'host'};
1241 if ($config{'musthost'} && $host ne $config{'musthost'}) {
1242 # Disallowed hostname used
1243 &http_error(400, "Invalid HTTP hostname");
1247 if ($page =~ /^([^\?]+)\?(.*)$/) {
1248 # There is some query string information
1251 print DEBUG "handle_request: querystring=$querystring\n";
1252 if ($querystring !~ /=/) {
1253 $queryargs = $querystring;
1254 $queryargs =~ s/\+/ /g;
1255 $queryargs =~ s/%(..)/pack("c",hex($1))/ge;
1259 # Parse query-string parameters
1260 local @in = split(/\&/, $querystring);
1262 local ($k, $v) = split(/=/, $i, 2);
1263 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1264 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1269 $posted_data = undef;
1270 if ($method eq 'POST' &&
1271 $header{'content-type'} eq 'application/x-www-form-urlencoded') {
1272 # Read in posted query string information, up the configured maximum
1273 # post request length
1274 $clen = $header{"content-length"};
1275 $clen_read = $clen > $config{'max_post'} ? $config{'max_post'} : $clen;
1276 while(length($posted_data) < $clen_read) {
1277 $buf = &read_data($clen_read - length($posted_data));
1278 if (!length($buf)) {
1279 &http_error(500, "Failed to read POST request");
1281 chomp($posted_data);
1282 $posted_data =~ s/\015$//mg;
1283 $posted_data .= $buf;
1285 print DEBUG "clen_read=$clen_read clen=$clen posted_data=",length($posted_data),"\n";
1286 if ($clen_read != $clen && length($posted_data) > $clen) {
1287 # If the client sent more data than we asked for, chop the
1289 $posted_data = substr($posted_data, 0, $clen);
1291 if (length($posted_data) > $clen) {
1292 # When the client sent too much, delay so that it gets headers
1295 if ($header{'user-agent'} =~ /MSIE/ &&
1296 $header{'user-agent'} !~ /Opera/i) {
1297 # MSIE includes an extra newline in the data
1298 $posted_data =~ s/\r|\n//g;
1300 local @in = split(/\&/, $posted_data);
1302 local ($k, $v) = split(/=/, $i, 2);
1304 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1305 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1308 print DEBUG "handle_request: posted_data=$posted_data\n";
1311 # replace %XX sequences in page
1312 $page =~ s/%(..)/pack("c",hex($1))/ge;
1314 # Check if the browser's user agent indicates a mobile device
1315 $mobile_device = &is_mobile_useragent($header{'user-agent'});
1317 # Check if Host: header is for a mobile URL
1318 foreach my $m (@mobile_prefixes) {
1319 if ($header{'host'} =~ /^\Q$m\E/i) {
1324 # check for the logout flag file, and if existant deny authentication
1325 if ($config{'logout'} && -r $config{'logout'}.$in{'miniserv_logout_id'}) {
1326 print DEBUG "handle_request: logout flag set\n";
1327 $deny_authentication++;
1328 open(LOGOUT, $config{'logout'}.$in{'miniserv_logout_id'});
1329 chop($count = <LOGOUT>);
1333 open(LOGOUT, ">$config{'logout'}$in{'miniserv_logout_id'}");
1334 print LOGOUT "$count\n";
1338 unlink($config{'logout'}.$in{'miniserv_logout_id'});
1342 # check for any redirect for the requested URL
1343 foreach my $pfx (@strip_prefix) {
1344 my $l = length($pfx);
1345 if(length($page) >= $l &&
1346 substr($page,0,$l) eq $pfx) {
1347 $page=substr($page,$l);
1351 $simple = &simplify_path($page, $bogus);
1353 $rpath .= "&".$querystring if (defined($querystring));
1354 $redir = $redirect{$rpath};
1355 if (defined($redir)) {
1356 print DEBUG "handle_request: redir=$redir\n";
1357 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1358 &write_data("Date: $datestr\r\n");
1359 &write_data("Server: $config{'server'}\r\n");
1360 local $ssl = $use_ssl || $config{'inetd_ssl'};
1361 $portstr = $port == 80 && !$ssl ? "" :
1362 $port == 443 && $ssl ? "" : ":$port";
1363 $prot = $ssl ? "https" : "http";
1364 &write_data("Location: $prot://$host$portstr$redir\r\n");
1365 &write_keep_alive(0);
1366 &write_data("\r\n");
1370 # Check for a DAV request
1372 foreach my $d (@davpaths) {
1373 if ($simple eq $d || $simple =~ /^\Q$d\E\//) {
1378 if (!$davpath && ($method eq "SEARCH" || $method eq "PUT")) {
1379 &http_error(400, "Bad Request method $method");
1382 # Check for password if needed
1384 print DEBUG "handle_request: Need authentication\n";
1388 # Session authentication is never used for connections by
1389 # another webmin server, or for specified pages, or for DAV, or XMLRPC,
1390 # or mobile browsers if requested.
1391 if ($header{'user-agent'} =~ /webmin/i ||
1392 $header{'user-agent'} =~ /$config{'agents_nosession'}/i ||
1393 $sessiononly{$simple} || $davpath ||
1394 $simple eq "/xmlrpc.cgi" ||
1395 $acptip eq $config{'host_nosession'} ||
1396 $mobile_device && $config{'mobile_nosession'}) {
1397 print DEBUG "handle_request: Forcing HTTP authentication\n";
1398 $config{'session'} = 0;
1401 # check for SSL authentication
1402 if ($use_ssl && $verified_client) {
1403 $peername = Net::SSLeay::X509_NAME_oneline(
1404 Net::SSLeay::X509_get_subject_name(
1405 Net::SSLeay::get_peer_certificate(
1407 local $peername2 = $peername;
1408 $peername2 =~ s/Email=/emailAddress=/ ||
1409 $peername2 =~ s/emailAddress=/Email=/;
1410 foreach $u (keys %certs) {
1411 if ($certs{$u} eq $peername ||
1412 $certs{$u} eq $peername2) {
1415 #syslog("info", "%s", "SSL login as $authuser from $acpthost") if ($use_syslog);
1419 if ($use_syslog && !$validated) {
1420 syslog("crit", "%s",
1421 "Unknown SSL certificate $peername");
1425 if (!$validated && !$deny_authentication) {
1426 # check for IP-based authentication
1428 foreach $a (keys %ipaccess) {
1429 if ($acptip eq $a) {
1430 # It does! Auth as the user
1432 $baseauthuser = $authuser =
1438 # Check for normal HTTP authentication
1439 if (!$validated && !$deny_authentication && !$config{'session'} &&
1440 $header{authorization} =~ /^basic\s+(\S+)$/i) {
1441 # authorization given..
1442 ($authuser, $authpass) = split(/:/, &b64decode($1), 2);
1443 print DEBUG "handle_request: doing basic auth check authuser=$authuser authpass=$authpass\n";
1444 local ($vu, $expired, $nonexist) =
1445 &validate_user($authuser, $authpass, $host);
1446 print DEBUG "handle_request: vu=$vu expired=$expired nonexist=$nonexist\n";
1447 if ($vu && (!$expired || $config{'passwd_mode'} == 1)) {
1454 if ($use_syslog && !$validated) {
1455 syslog("crit", "%s",
1456 ($nonexist ? "Non-existent" :
1457 $expired ? "Expired" : "Invalid").
1458 " login as $authuser from $acpthost");
1460 if ($authuser =~ /\r|\n|\s/) {
1461 &http_error(500, "Invalid username",
1462 "Username contains invalid characters");
1464 if ($authpass =~ /\r|\n/) {
1465 &http_error(500, "Invalid password",
1466 "Password contains invalid characters");
1469 if ($config{'passdelay'} && !$config{'inetd'}) {
1470 # check with main process for delay
1471 print DEBUG "handle_request: about to ask for password delay\n";
1472 print $PASSINw "delay $authuser $acptip $validated\n";
1473 <$PASSOUTr> =~ /(\d+) (\d+)/;
1475 print DEBUG "handle_request: password delay $1 $2\n";
1480 # Check for a visit to the special session login page
1481 if ($config{'session'} && !$deny_authentication &&
1482 $page eq $config{'session_login'}) {
1483 if ($in{'logout'} && $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1484 # Logout clicked .. remove the session
1486 print $PASSINw "delete $sid\n";
1487 local $louser = <$PASSOUTr>;
1490 $already_session_id = undef;
1491 $authuser = $baseauthuser = undef;
1494 syslog("info", "%s", "Logout by $louser from $acpthost");
1496 &run_logout_script($louser, $sid,
1498 &write_logout_utmp($louser, $actphost);
1503 if ($in{'user'} =~ /\r|\n|\s/) {
1504 &http_error(500, "Invalid username",
1505 "Username contains invalid characters");
1507 if ($in{'pass'} =~ /\r|\n/) {
1508 &http_error(500, "Invalid password",
1509 "Password contains invalid characters");
1512 local ($vu, $expired, $nonexist) =
1513 &validate_user($in{'user'}, $in{'pass'}, $host);
1514 local $hrv = &handle_login(
1515 $vu || $in{'user'}, $vu ? 1 : 0,
1516 $expired, $nonexist, $in{'pass'},
1517 $in{'notestingcookie'});
1518 return $hrv if (defined($hrv));
1522 # Check for a visit to the special PAM login page
1523 if ($config{'session'} && !$deny_authentication &&
1524 $use_pam && $config{'pam_conv'} && $page eq $config{'pam_login'} &&
1526 # A question has been entered .. submit it to the main process
1527 print DEBUG "handle_request: Got call to $page ($in{'cid'})\n";
1528 print DEBUG "handle_request: For PAM, authuser=$authuser\n";
1529 if ($in{'answer'} =~ /\r|\n/ || $in{'cid'} =~ /\r|\n|\s/) {
1530 &http_error(500, "Invalid response",
1531 "Response contains invalid characters");
1535 # Start of a new conversation - answer must be username
1536 $cid = &generate_random_id($in{'answer'});
1537 print $PASSINw "pamstart $cid $host $in{'answer'}\n";
1540 # A response to a previous question
1542 print $PASSINw "pamanswer $cid $in{'answer'}\n";
1545 # Read back the response, and the next question (if any)
1546 local $line = <$PASSOUTr>;
1547 $line =~ s/\r|\n//g;
1548 local ($rv, $question) = split(/\s+/, $line, 2);
1551 local $hrv = &handle_login(
1552 !$in{'cid'} && $in{'answer'} ? $in{'answer'}
1555 return $hrv if (defined($hrv));
1557 elsif ($rv == 1 || $rv == 3) {
1558 # Another question .. force use of PAM CGI
1561 $querystring .= "&cid=$cid&question=".
1563 $querystring .= "&password=1" if ($rv == 3);
1565 $page = $config{'pam_login'};
1566 $miniserv_internal = 1;
1570 # Got back a final ok or failure
1571 local ($user, $ok, $expired, $nonexist) =
1572 split(/\s+/, $question);
1573 local $hrv = &handle_login(
1574 $user, $ok, $expired, $nonexist, undef,
1575 $in{'notestingcookie'});
1576 return $hrv if (defined($hrv));
1579 # A message from PAM .. tell the user
1582 $querystring .= "&cid=$cid&message=".
1585 $page = $config{'pam_login'};
1586 $miniserv_internal = 1;
1591 # Check for a visit to the special password change page
1592 if ($config{'session'} && !$deny_authentication &&
1593 $page eq $config{'password_change'} && !$validated) {
1594 # Just let this slide ..
1596 $miniserv_internal = 3;
1599 # Check for an existing session
1600 if ($config{'session'} && !$validated) {
1601 if ($already_session_id) {
1602 $session_id = $already_session_id;
1603 $authuser = $already_authuser;
1606 elsif (!$deny_authentication &&
1607 $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1608 # Try all session cookies
1609 local $cookie = $header{'cookie'};
1610 while($cookie =~ s/(^|\s)$sidname=([a-f0-9]+)//) {
1613 $in{'webmin_notimeout'} ? 1 : 0;
1614 print $PASSINw "verify $session_id $notimeout\n";
1615 <$PASSOUTr> =~ /(\d+)\s+(\S+)/;
1617 # Valid session continuation
1620 $already_authuser = $authuser;
1629 # Invalid session ID .. don't set
1636 # Check for local authentication
1637 if ($localauth_user && !$header{'x-forwarded-for'} && !$header{'via'}) {
1638 if (defined($users{$localauth_user})) {
1639 # Local user exists in webmin users file
1641 $authuser = $localauth_user;
1644 # Check if local user is allowed by unixauth
1645 local @can = &can_user_login($localauth_user,
1649 $authuser = $localauth_user;
1652 $localauth_user = undef;
1658 # Check if this path allows anonymous access
1660 foreach $a (keys %anonymous) {
1661 if (substr($simple, 0, length($a)) eq $a) {
1662 # It does! Auth as the user, if IP access
1663 # control allows him.
1664 if (&check_user_ip($anonymous{$a}) &&
1665 &check_user_time($anonymous{$a})) {
1667 $baseauthuser = $authuser =
1675 # Check if this path allows unauthenticated access
1676 local ($u, $unauth);
1677 foreach $u (@unauth) {
1678 $unauth++ if ($simple =~ /$u/);
1680 if (!$bogus && $unauth) {
1681 # Unauthenticated directory or file request - approve it
1683 $baseauthuser = $authuser = undef;
1688 if ($blocked == 0) {
1689 # No password given.. ask
1690 if ($config{'pam_conv'} && $use_pam) {
1691 # Force CGI for PAM question, starting with
1692 # the username which is always needed
1695 $querystring .= "&initial=1&question=".
1696 &urlize("Username");
1697 $querystring .= "&failed=$failed_user" if ($failed_user);
1698 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1700 $page = $config{'pam_login'};
1701 $miniserv_internal = 1;
1704 elsif ($config{'session'}) {
1705 # Force CGI for session login
1708 $querystring .= "&logout=1&page=/";
1711 # Re-direct to current module only
1712 local $rpage = $request_uri;
1713 if (!$config{'loginkeeppage'}) {
1714 $rpage =~ s/\?.*$//;
1715 $rpage =~ s/[^\/]+$//
1717 $querystring = "page=".&urlize($rpage);
1720 $querystring .= "&failed=$failed_user" if ($failed_user);
1721 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1723 $page = $config{'session_login'};
1724 $miniserv_internal = 1;
1728 # Ask for login with HTTP authentication
1729 &write_data("HTTP/1.0 401 Unauthorized\r\n");
1730 &write_data("Date: $datestr\r\n");
1731 &write_data("Server: $config{'server'}\r\n");
1732 &write_data("WWW-authenticate: Basic ".
1733 "realm=\"$config{'realm'}\"\r\n");
1734 &write_keep_alive(0);
1735 &write_data("Content-type: text/html\r\n");
1736 &write_data("\r\n");
1737 &reset_byte_count();
1738 &write_data("<html>\n");
1739 &write_data("<head><title>Unauthorized</title></head>\n");
1740 &write_data("<body><h1>Unauthorized</h1>\n");
1741 &write_data("A password is required to access this\n");
1742 &write_data("web server. Please try again. <p>\n");
1743 &write_data("</body></html>\n");
1744 &log_request($acpthost, undef, $reqline, 401, &byte_count());
1748 elsif ($blocked == 1) {
1749 # when the host has been blocked, give it an error
1750 &http_error(403, "Access denied for $acptip. The host ".
1751 "has been blocked because of too ".
1752 "many authentication failures.");
1754 elsif ($blocked == 2) {
1755 # when the user has been blocked, give it an error
1756 &http_error(403, "Access denied. The user ".
1757 "has been blocked because of too ".
1758 "many authentication failures.");
1762 # Get the real Webmin username
1763 local @can = &can_user_login($authuser, undef, $host);
1764 $baseauthuser = $can[3] || $authuser;
1766 if ($config{'remoteuser'} && !$< && $validated) {
1767 # Switch to the UID of the remote user (if he exists)
1768 local @u = getpwnam($authuser);
1769 if (@u && $< != $u[2]) {
1770 $( = $u[3]; $) = "$u[3] $u[3]";
1771 ($>, $<) = ($u[2], $u[2]);
1774 &http_error(500, "Unix user $authuser does not exist");
1780 # Check per-user IP access control
1781 if (!&check_user_ip($baseauthuser)) {
1782 &http_error(403, "Access denied for $acptip for $baseauthuser");
1786 # Check per-user allowed times
1787 if (!&check_user_time($baseauthuser)) {
1788 &http_error(403, "Access denied at the current time");
1793 # Validate the path, and convert to canonical form
1795 $simple = &simplify_path($page, $bogus);
1796 print DEBUG "handle_request: page=$page simple=$simple\n";
1798 &http_error(400, "Invalid path");
1801 # Check for a DAV request
1803 return &handle_dav_request($davpath);
1806 # Work out the active theme(s)
1807 local $preroots = $mobile_device && defined($config{'mobile_preroot'}) ?
1808 $config{'mobile_preroot'} :
1809 $authuser && defined($config{'preroot_'.$authuser}) ?
1810 $config{'preroot_'.$authuser} :
1811 $authuser && $baseauthuser &&
1812 defined($config{'preroot_'.$baseauthuser}) ?
1813 $config{'preroot_'.$baseauthuser} :
1815 local @preroots = reverse(split(/\s+/, $preroots));
1817 # Canonicalize the directories
1818 foreach my $preroot (@preroots) {
1819 # Always under the current webmin root
1820 $preroot =~ s/^.*\///g;
1821 $preroot = $roots[0].'/'.$preroot;
1824 # Look in the theme root directories first
1825 local ($full, @stfull);
1827 foreach my $preroot (@preroots) {
1830 $full = $preroot.$sofar;
1831 $scriptname = $simple;
1832 foreach $b (split(/\//, $simple)) {
1833 if ($b ne "") { $sofar .= "/$b"; }
1834 $full = $preroot.$sofar;
1835 @stfull = stat($full);
1836 if (!@stfull) { undef($full); last; }
1838 # Check if this is a directory
1840 # It is.. go on parsing
1848 # Check if this is a CGI program
1849 if (&get_type($full) eq "internal/cgi") {
1850 $pathinfo = substr($simple, length($sofar));
1851 $pathinfo .= "/" if ($page =~ /\/$/);
1852 $scriptname = $sofar;
1857 # Don't stop at a directory unless this is the last theme, which
1858 # is the 'real' one that provides the .cgi scripts
1859 if ($is_directory && $preroot ne $preroots[$#preroots]) {
1866 $cgi_pwd = $roots[0];
1868 elsif ($is_directory) {
1869 $cgi_pwd = "$roots[0]$sofar";
1872 "$roots[0]$sofar" =~ /^(.*\/)[^\/]+$/;
1875 $foundroot = $preroot;
1876 if ($is_directory) {
1877 # Check for index files in the directory
1879 foreach $idx (split(/\s+/, $config{"index_docs"})) {
1880 $idxfull = "$full/$idx";
1881 local @stidxfull = stat($idxfull);
1882 if (-r _ && !-d _) {
1884 @stfull = @stidxfull;
1887 if ($scriptname ne "/");
1892 @stfull = stat($full) if (!$foundidx);
1895 last if ($foundroot);
1897 print DEBUG "handle_request: initial full=$full\n";
1899 # Look in the real root directories, stopping when we find a file or directory
1900 if (!$full || $is_directory) {
1901 ROOT: foreach $root (@roots) {
1903 $full = $root.$sofar;
1904 $scriptname = $simple;
1905 foreach $b ($simple eq "/" ? ( "" ) : split(/\//, $simple)) {
1906 if ($b ne "") { $sofar .= "/$b"; }
1907 $full = $root.$sofar;
1908 @stfull = stat($full);
1913 # Check if this is a directory
1915 # It is.. go on parsing
1919 # Check if this is a CGI program
1920 if (&get_type($full) eq "internal/cgi") {
1921 $pathinfo = substr($simple, length($sofar));
1922 $pathinfo .= "/" if ($page =~ /\/$/);
1923 $scriptname = $sofar;
1928 # Run CGI in the same directory as whatever file
1930 $full =~ /^(.*\/)[^\/]+$/; $cgi_pwd = $1;
1939 if (!@stfull) { &http_error(404, "File not found"); }
1941 print DEBUG "handle_request: full=$full\n";
1942 @stfull = stat($full) if (!@stfull);
1944 # check filename against denyfile regexp
1945 local $denyfile = $config{'denyfile'};
1946 if ($denyfile && $full =~ /$denyfile/) {
1947 &http_error(403, "Access denied to $page");
1951 # Reached the end of the path OK.. see what we've got
1953 # See if the URL ends with a / as it should
1954 print DEBUG "handle_request: found a directory\n";
1955 if ($page !~ /\/$/) {
1956 # It doesn't.. redirect
1957 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1958 $ssl = $use_ssl || $config{'inetd_ssl'};
1959 $portstr = $port == 80 && !$ssl ? "" :
1960 $port == 443 && $ssl ? "" : ":$port";
1961 &write_data("Date: $datestr\r\n");
1962 &write_data("Server: $config{server}\r\n");
1963 $prot = $ssl ? "https" : "http";
1964 &write_data("Location: $prot://$host$portstr$page/\r\n");
1965 &write_keep_alive(0);
1966 &write_data("\r\n");
1967 &log_request($acpthost, $authuser, $reqline, 302, 0);
1970 # A directory.. check for index files
1972 foreach $idx (split(/\s+/, $config{"index_docs"})) {
1973 $idxfull = "$full/$idx";
1974 @stidxfull = stat($idxfull);
1975 if (-r _ && !-d _) {
1978 @stfull = @stidxfull;
1979 $scriptname .= "/" if ($scriptname ne "/");
1984 @stfull = stat($full) if (!$foundidx);
1987 # This is definately a directory.. list it
1988 print DEBUG "handle_request: listing directory\n";
1989 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
1990 "Date: $datestr\r\n".
1991 "Server: $config{server}\r\n".
1992 "Content-type: text/html\r\n";
1994 &write_keep_alive(0);
1995 &write_data("\r\n");
1996 &reset_byte_count();
1997 &write_data("<h1>Index of $simple</h1>\n");
1998 &write_data("<pre>\n");
1999 &write_data(sprintf "%-35.35s %-20.20s %-10.10s\n",
2000 "Name", "Last Modified", "Size");
2001 &write_data("<hr>\n");
2002 opendir(DIR, $full);
2003 while($df = readdir(DIR)) {
2004 if ($df =~ /^\./) { next; }
2005 $fulldf = $full eq "/" ? $full.$df : $full."/".$df;
2006 (@stbuf = stat($fulldf)) || next;
2007 if (-d _) { $df .= "/"; }
2008 @tm = localtime($stbuf[9]);
2009 $fdate = sprintf "%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d",
2010 $tm[3],$tm[4]+1,$tm[5]+1900,
2011 $tm[0],$tm[1],$tm[2];
2012 $len = length($df); $rest = " "x(35-$len);
2014 "<a href=\"%s\">%-${len}.${len}s</a>$rest %-20.20s %-10.10s\n",
2015 $df, $df, $fdate, $stbuf[7]);
2018 &log_request($acpthost, $authuser, $reqline, $ok_code, &byte_count());
2022 # CGI or normal file
2024 if (&get_type($full) eq "internal/cgi" && $validated != 4) {
2025 # A CGI program to execute
2026 print DEBUG "handle_request: executing CGI\n";
2027 $envtz = $ENV{"TZ"};
2028 $envuser = $ENV{"USER"};
2029 $envpath = $ENV{"PATH"};
2030 $envlang = $ENV{"LANG"};
2031 $envroot = $ENV{"SystemRoot"};
2032 $envperllib = $ENV{'PERLLIB'};
2033 foreach my $k (keys %ENV) {
2036 $ENV{"PATH"} = $envpath if ($envpath);
2037 $ENV{"TZ"} = $envtz if ($envtz);
2038 $ENV{"USER"} = $envuser if ($envuser);
2039 $ENV{"OLD_LANG"} = $envlang if ($envlang);
2040 $ENV{"SystemRoot"} = $envroot if ($envroot);
2041 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
2042 $ENV{"HOME"} = $user_homedir;
2043 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
2044 $ENV{"SERVER_NAME"} = $host;
2045 $ENV{"SERVER_ADMIN"} = $config{"email"};
2046 $ENV{"SERVER_ROOT"} = $roots[0];
2047 $ENV{"SERVER_REALROOT"} = $realroot;
2048 $ENV{"SERVER_PORT"} = $port;
2049 $ENV{"REMOTE_HOST"} = $acpthost;
2050 $ENV{"REMOTE_ADDR"} = $acptip;
2051 $ENV{"REMOTE_USER"} = $authuser;
2052 $ENV{"BASE_REMOTE_USER"} = $authuser ne $baseauthuser ?
2053 $baseauthuser : undef;
2054 $ENV{"REMOTE_PASS"} = $authpass if (defined($authpass) &&
2055 $config{'pass_password'});
2056 print DEBUG "REMOTE_USER = ",$ENV{"REMOTE_USER"},"\n";
2057 print DEBUG "BASE_REMOTE_USER = ",$ENV{"BASE_REMOTE_USER"},"\n";
2058 $ENV{"SSL_USER"} = $peername if ($validated == 2);
2059 $ENV{"ANONYMOUS_USER"} = "1" if ($validated == 3 || $validated == 4);
2060 $ENV{"DOCUMENT_ROOT"} = $roots[0];
2061 $ENV{"DOCUMENT_REALROOT"} = $realroot;
2062 $ENV{"GATEWAY_INTERFACE"} = "CGI/1.1";
2063 $ENV{"SERVER_PROTOCOL"} = "HTTP/1.0";
2064 $ENV{"REQUEST_METHOD"} = $method;
2065 $ENV{"SCRIPT_NAME"} = $scriptname;
2066 $ENV{"SCRIPT_FILENAME"} = $full;
2067 $ENV{"REQUEST_URI"} = $request_uri;
2068 $ENV{"PATH_INFO"} = $pathinfo;
2070 $ENV{"PATH_TRANSLATED"} = "$roots[0]$pathinfo";
2071 $ENV{"PATH_REALTRANSLATED"} = "$realroot$pathinfo";
2073 $ENV{"QUERY_STRING"} = $querystring;
2074 $ENV{"MINISERV_CONFIG"} = $config_file;
2075 $ENV{"HTTPS"} = "ON" if ($use_ssl || $config{'inetd_ssl'});
2076 $ENV{"SESSION_ID"} = $session_id if ($session_id);
2077 $ENV{"LOCAL_USER"} = $localauth_user if ($localauth_user);
2078 $ENV{"MINISERV_INTERNAL"} = $miniserv_internal if ($miniserv_internal);
2079 if (defined($header{"content-length"})) {
2080 $ENV{"CONTENT_LENGTH"} = $header{"content-length"};
2082 if (defined($header{"content-type"})) {
2083 $ENV{"CONTENT_TYPE"} = $header{"content-type"};
2085 foreach $h (keys %header) {
2086 ($hname = $h) =~ tr/a-z/A-Z/;
2088 $ENV{"HTTP_$hname"} = $header{$h};
2090 $ENV{"PWD"} = $cgi_pwd;
2091 foreach $k (keys %config) {
2092 if ($k =~ /^env_(\S+)$/) {
2093 $ENV{$1} = $config{$k};
2096 delete($ENV{'HTTP_AUTHORIZATION'});
2097 $ENV{'HTTP_COOKIE'} =~ s/;?\s*$sidname=([a-f0-9]+)//;
2098 $ENV{'MOBILE_DEVICE'} = 1 if ($mobile_device);
2100 # Check if the CGI can be handled internally
2102 local $first = <CGI>;
2104 $first =~ s/[#!\r\n]//g;
2105 $nph_script = ($full =~ /\/nph-([^\/]+)$/);
2107 if (!$config{'forkcgis'} &&
2108 ($first eq $perl_path || $first eq $linked_perl_path) &&
2110 $config{'internalcgis'}) {
2111 # setup environment for eval
2113 @ARGV = split(/\s+/, $queryargs);
2116 # Already read the post input
2117 $postinput = $posted_data;
2119 $clen = $header{"content-length"};
2120 $SIG{'CHLD'} = 'DEFAULT';
2122 # Have SOCK closed if the perl exec's something
2124 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
2128 if ($config{'log'}) {
2129 open(MINISERVLOG, ">>$config{'logfile'}");
2130 if ($config{'logperms'}) {
2131 chmod(oct($config{'logperms'}),
2132 $config{'logfile'});
2135 chmod(0600, $config{'logfile'});
2139 $main_process_id = $$;
2141 if ($full =~ /^\Q$foundroot\E\/([^\/]+)\//) {
2142 # Eval in package from Webmin module name
2144 $pkg =~ s/[^A-Za-z0-9]/_/g;
2149 tie(*STDOUT, 'miniserv');
2150 tie(*STDIN, 'miniserv');
2151 do \$miniserv::full;
2157 &http_error(500, "Perl execution failed",
2158 $config{'noshowstderr'} ? undef : $@);
2160 elsif (!$doneheaders && !$nph_script) {
2161 &http_error(500, "Missing Headers");
2168 # fork the process that actually executes the CGI
2169 pipe(CGIINr, CGIINw);
2170 pipe(CGIOUTr, CGIOUTw);
2171 pipe(CGIERRr, CGIERRw);
2172 if (!($cgipid = fork())) {
2173 @execargs = ( $full, split(/\s+/, $queryargs) );
2176 open(STDIN, "<&CGIINr");
2177 open(STDOUT, ">&CGIOUTw");
2178 open(STDERR, ">&CGIERRw");
2179 close(CGIINw); close(CGIOUTr); close(CGIERRr);
2181 die "Failed to exec $full : $!\n";
2184 close(CGIINr); close(CGIOUTw); close(CGIERRw);
2187 # write CGI input to a temp file
2188 $infile = "$config{'tempbase'}.$$";
2189 open(CGIINw, ">$infile");
2190 # NOT binary mode, as CGIs don't read in it!
2195 # already read the posted data
2196 print CGIINw $posted_data;
2198 $clen = $header{"content-length"};
2199 if ($method eq "POST" && $clen_read < $clen) {
2200 $SIG{'PIPE'} = 'IGNORE';
2202 while($got < $clen) {
2203 $buf = &read_data($clen-$got);
2204 if (!length($buf)) {
2205 kill('TERM', $cgipid);
2206 unlink($infile) if ($infile);
2207 &http_error(500, "Failed to read ".
2210 $got += length($buf);
2211 local ($wrote) = (print CGIINw $buf);
2214 # If the CGI terminated early, we still need to read
2215 # from the browser and throw away
2216 while($got < $clen) {
2217 $buf = &read_data($clen-$got);
2218 if (!length($buf)) {
2219 kill('TERM', $cgipid);
2220 unlink($infile) if ($infile);
2221 &http_error(500, "Failed to read ".
2224 $got += length($buf);
2226 $SIG{'PIPE'} = 'DEFAULT';
2232 # Run the CGI program, and feed it input
2234 local $qqueryargs = join(" ", map { "\"$_\"" }
2235 split(/\s+/, $queryargs));
2236 if ($first =~ /(perl|perl.exe)$/i) {
2237 # On Windows, run with Perl
2238 open(CGIOUTr, "$perl_path \"$full\" $qqueryargs <$infile |");
2241 open(CGIOUTr, "\"$full\" $qqueryargs <$infile |");
2247 # read back cgi headers
2248 select(CGIOUTr); $|=1; select(STDOUT);
2252 $line =~ s/\r|\n//g;
2254 if ($got_blank || %cgiheader) { last; }
2258 if ($line !~ /^(\S+):\s+(.*)$/) {
2259 $errs = &read_errors(CGIERRr);
2260 close(CGIOUTr); close(CGIERRr);
2261 unlink($infile) if ($infile);
2262 &http_error(500, "Bad Header", $errs);
2264 $cgiheader{lc($1)} = $2;
2265 push(@cgiheader, [ $1, $2 ]);
2267 if ($cgiheader{"location"}) {
2268 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2269 &write_data("Date: $datestr\r\n");
2270 &write_data("Server: $config{'server'}\r\n");
2271 &write_keep_alive(0);
2272 # ignore the rest of the output. This is a hack,
2273 # but is necessary for IE in some cases :(
2274 close(CGIOUTr); close(CGIERRr);
2276 elsif ($cgiheader{"content-type"} eq "") {
2277 close(CGIOUTr); close(CGIERRr);
2278 unlink($infile) if ($infile);
2279 $errs = &read_errors(CGIERRr);
2280 &http_error(500, "Missing Content-Type Header",
2281 $config{'noshowstderr'} ? undef : $errs);
2284 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2285 &write_data("Date: $datestr\r\n");
2286 &write_data("Server: $config{'server'}\r\n");
2287 &write_keep_alive(0);
2289 foreach $h (@cgiheader) {
2290 &write_data("$h->[0]: $h->[1]\r\n");
2292 &write_data("\r\n");
2294 &reset_byte_count();
2295 while($line = <CGIOUTr>) {
2300 unlink($infile) if ($infile);
2306 print DEBUG "handle_request: outputting file\n";
2307 open(FILE, $full) || &http_error(404, "Failed to open file");
2309 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2310 "Date: $datestr\r\n".
2311 "Server: $config{server}\r\n".
2312 "Content-type: ".&get_type($full)."\r\n".
2313 "Content-length: $stfull[7]\r\n".
2314 "Last-Modified: ".&http_date($stfull[9])."\r\n".
2315 "Expires: ".&http_date(time()+$config{'expires'})."\r\n";
2317 $rv = &write_keep_alive();
2318 &write_data("\r\n");
2319 &reset_byte_count();
2320 while(read(FILE, $buf, 1024) > 0) {
2327 &log_request($acpthost, $authuser, $reqline,
2328 $logged_code ? $logged_code :
2329 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2333 # http_error(code, message, body, [dontexit])
2336 local $eh = $error_handler_recurse ? undef :
2337 $config{"error_handler_$_[0]"} ? $config{"error_handler_$_[0]"} :
2338 $config{'error_handler'} ? $config{'error_handler'} : undef;
2339 print DEBUG "http_error code=$_[0] message=$_[1] body=$_[2]\n";
2341 # Call a CGI program for the error
2343 $querystring = "code=$_[0]&message=".&urlize($_[1]).
2344 "&body=".&urlize($_[2]);
2345 $error_handler_recurse++;
2347 $ok_message = $_[1];
2351 # Use the standard error message display
2352 &write_data("HTTP/1.0 $_[0] $_[1]\r\n");
2353 &write_data("Server: $config{server}\r\n");
2354 &write_data("Date: $datestr\r\n");
2355 &write_data("Content-type: text/html\r\n");
2356 &write_keep_alive(0);
2357 &write_data("\r\n");
2358 &reset_byte_count();
2359 &write_data("<h1>Error - $_[1]</h1>\n");
2361 &write_data("<pre>$_[2]</pre>\n");
2364 &log_request($acpthost, $authuser, $reqline, $_[0], &byte_count())
2366 &log_error($_[1], $_[2] ? " : $_[2]" : "");
2373 if ($_[0] =~ /\.([A-z0-9]+)$/) {
2379 return "text/plain";
2382 # simplify_path(path, bogus)
2383 # Given a path, maybe containing stuff like ".." and "." convert it to a
2384 # clean, absolute form.
2387 local($dir, @bits, @fixedbits, $b);
2389 $dir =~ s/\\/\//g; # fix windows \ in path
2392 $dir =~ s/\0//g; # remove null bytes
2393 @bits = split(/\/+/, $dir);
2396 foreach $b (@bits) {
2400 elsif ($b eq ".." || $b eq "...") {
2402 if (scalar(@fixedbits) == 0) {
2410 push(@fixedbits, $b);
2413 return "/" . join('/', @fixedbits);
2417 # Converts a string from base64 format to normal
2420 local($str) = $_[0];
2422 $str =~ tr|A-Za-z0-9+=/||cd;
2424 $str =~ tr|A-Za-z0-9+/| -_|;
2425 while ($str =~ /(.{1,60})/gs) {
2426 my $len = chr(32 + length($1)*3/4);
2427 $res .= unpack("u", $len . $1 );
2432 # ip_match(remoteip, localip, [match]+)
2433 # Checks an IP address against a list of IPs, networks and networks/masks
2436 local(@io, @mo, @ms, $i, $j, $hn, $needhn);
2437 @io = split(/\./, $_[0]);
2438 for($i=2; $i<@_; $i++) {
2439 $needhn++ if ($_[$i] =~ /^\*(\S+)$/);
2441 if ($needhn && !defined($hn = $ip_match_cache{$_[0]})) {
2442 $hn = gethostbyaddr(inet_aton($_[0]), AF_INET);
2443 $hn = "" if (&to_ipaddress($hn) ne $_[0]);
2444 $ip_match_cache{$_[0]} = $hn;
2446 for($i=2; $i<@_; $i++) {
2447 local $mismatch = 0;
2448 if ($_[$i] =~ /^(\S+)\/(\d+)$/) {
2449 # Convert CIDR to netmask format
2450 $_[$i] = $1."/".&prefix_to_mask($2);
2452 if ($_[$i] =~ /^(\S+)\/(\S+)$/) {
2453 # Compare with network/mask
2454 @mo = split(/\./, $1); @ms = split(/\./, $2);
2455 for($j=0; $j<4; $j++) {
2456 if ((int($io[$j]) & int($ms[$j])) != int($mo[$j])) {
2461 elsif ($_[$i] =~ /^\*(\S+)$/) {
2462 # Compare with hostname regexp
2463 $mismatch = 1 if ($hn !~ /$1$/);
2465 elsif ($_[$i] eq 'LOCAL') {
2466 # Compare with local network
2467 local @lo = split(/\./, $_[1]);
2469 $mismatch = 1 if ($lo[0] != $io[0]);
2471 elsif ($lo[0] < 192) {
2472 $mismatch = 1 if ($lo[0] != $io[0] ||
2476 $mismatch = 1 if ($lo[0] != $io[0] ||
2481 elsif ($_[$i] !~ /^[0-9\.]+$/) {
2482 # Compare with hostname
2483 $mismatch = 1 if ($_[0] ne &to_ipaddress($_[$i]));
2486 # Compare with IP or network
2487 @mo = split(/\./, $_[$i]);
2488 while(@mo && !$mo[$#mo]) { pop(@mo); }
2489 for($j=0; $j<@mo; $j++) {
2490 if ($mo[$j] != $io[$j]) {
2495 return 1 if (!$mismatch);
2500 # users_match(&uinfo, user, ...)
2501 # Returns 1 if a user is in a list of users and groups
2504 local $uinfo = shift(@_);
2506 local @ginfo = getgrgid($uinfo->[3]);
2508 if ($u =~ /^\@(\S+)$/) {
2509 return 1 if (&is_group_member($uinfo, $1));
2511 elsif ($u =~ /^(\d*)-(\d*)$/ && ($1 || $2)) {
2512 return (!$1 || $uinfo[2] >= $1) &&
2513 (!$2 || $uinfo[2] <= $2);
2516 return 1 if ($u eq $uinfo->[0]);
2522 # restart_miniserv()
2523 # Called when a SIGHUP is received to restart the web server. This is done
2524 # by exec()ing perl with the same command line as was originally used
2525 sub restart_miniserv
2527 print STDERR "restarting miniserv\n";
2528 &log_error("Restarting");
2530 &close_all_sockets();
2532 dbmclose(%sessiondb);
2533 kill('KILL', $logclearer) if ($logclearer);
2534 kill('KILL', $extauth) if ($extauth);
2535 exec($perl_path, $miniserv_path, @miniserv_argv);
2536 die "Failed to restart miniserv with $perl_path $miniserv_path";
2553 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2554 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/) { push(@rv, $i); }
2555 else { push(@rv, join('.', unpack("CCCC", inet_aton($i)))); }
2557 return wantarray ? @rv : $rv[0];
2560 # read_line(no-wait, no-limit)
2561 # Reads one line from SOCK or SSL
2564 local ($nowait, $nolimit) = @_;
2565 local($idx, $more, $rv);
2566 while(($idx = index($main::read_buffer, "\n")) < 0) {
2567 if (length($main::read_buffer) > 10000 && !$nolimit) {
2568 &http_error(414, "Request too long",
2569 "Received excessive line <pre>$main::read_buffer</pre>");
2572 # need to read more..
2573 &wait_for_data_error() if (!$nowait);
2575 $more = Net::SSLeay::read($ssl_con);
2578 local $ok = sysread(SOCK, $more, 1024);
2579 $more = undef if ($ok <= 0);
2583 $rv = $main::read_buffer;
2584 undef($main::read_buffer);
2587 $main::read_buffer .= $more;
2589 $rv = substr($main::read_buffer, 0, $idx+1);
2590 $main::read_buffer = substr($main::read_buffer, $idx+1);
2595 # Reads up to some amount of data from SOCK or the SSL connection
2599 if (length($main::read_buffer)) {
2600 if (length($main::read_buffer) > $_[0]) {
2601 # Return the first part of the buffer
2602 $rv = substr($main::read_buffer, 0, $_[0]);
2603 $main::read_buffer = substr($main::read_buffer, $_[0]);
2607 # Return the whole buffer
2608 $rv = $main::read_buffer;
2609 undef($main::read_buffer);
2614 # Call SSL read function
2615 return Net::SSLeay::read($ssl_con, $_[0]);
2618 # Just do a normal read
2620 sysread(SOCK, $buf, $_[0]) || return undef;
2626 # Read a line from a file handle, using sysread to get a byte at a time
2633 $got = sysread($fh, $buf, 1);
2634 last if ($got <= 0);
2636 last if ($buf eq "\n");
2641 # wait_for_data(secs)
2642 # Waits at most the given amount of time for some data on SOCK, returning
2643 # 0 if not found, 1 if some arrived.
2647 vec($rmask, fileno(SOCK), 1) = 1;
2648 local $got = select($rmask, undef, undef, $_[0]);
2649 return $got == 0 ? 0 : 1;
2652 # wait_for_data_error()
2653 # Waits 60 seconds for data on SOCK, and fails if none arrives
2654 sub wait_for_data_error
2656 local $got = &wait_for_data(60);
2658 &http_error(400, "Timeout",
2659 "Waited more than 60 seconds for request data");
2663 # write_data(data, ...)
2664 # Writes a string to SOCK or the SSL connection
2667 local $str = join("", @_);
2669 Net::SSLeay::write($ssl_con, $str);
2672 syswrite(SOCK, $str, length($str));
2674 # Intentionally introduce a small delay to avoid problems where IE reports
2675 # the page as empty / DNS failed when it get a large response too quickly!
2676 select(undef, undef, undef, .01) if ($write_data_count%10 == 0);
2677 $write_data_count += length($str);
2680 # reset_byte_count()
2681 sub reset_byte_count { $write_data_count = 0; }
2684 sub byte_count { return $write_data_count; }
2686 # log_request(hostname, user, request, code, bytes)
2689 if ($config{'log'}) {
2690 local ($user, $ident, $headers);
2691 if ($config{'logident'}) {
2692 # add support for rfc1413 identity checking here
2694 else { $ident = "-"; }
2695 $user = $_[1] ? $_[1] : "-";
2696 local $dstr = &make_datestr();
2697 if (fileno(MINISERVLOG)) {
2698 seek(MINISERVLOG, 0, 2);
2701 open(MINISERVLOG, ">>$config{'logfile'}");
2702 chmod(0600, $config{'logfile'});
2704 if (defined($config{'logheaders'})) {
2705 foreach $h (split(/\s+/, $config{'logheaders'})) {
2706 $headers .= " $h=\"$header{$h}\"";
2709 elsif ($config{'logclf'}) {
2710 $headers = " \"$header{'referer'}\" \"$header{'user-agent'}\"";
2715 print MINISERVLOG "$_[0] $ident $user [$dstr] \"$_[2]\" ",
2716 "$_[3] $_[4]$headers\n";
2724 local @tm = localtime(time());
2725 return sprintf "%2.2d/%s/%4.4d:%2.2d:%2.2d:%2.2d %s",
2726 $tm[3], $month[$tm[4]], $tm[5]+1900,
2727 $tm[2], $tm[1], $tm[0], $timezone;
2730 # log_error(message)
2734 print STDERR "[",&make_datestr(),"] ",
2735 $acpthost ? ( "[",$acpthost,"] " ) : ( ),
2736 $page ? ( $page," : " ) : ( ),
2740 # read_errors(handle)
2741 # Read and return all input from some filehandle
2744 local($fh, $_, $rv);
2746 while(<$fh>) { $rv .= $_; }
2750 sub write_keep_alive
2753 if ($config{'nokeepalive'}) {
2754 # Keep alives have been disabled in config
2757 elsif (@childpids > $config{'maxconns'}*.8) {
2758 # Disable because nearing process limit
2762 # Keep alive specified by caller
2766 # Keep alive determined by browser
2767 $mode = $header{'connection'} =~ /keep-alive/i;
2769 &write_data("Connection: ".($mode ? "Keep-Alive" : "close")."\r\n");
2775 kill('TERM', @childpids) if (@childpids);
2776 kill('KILL', $logclearer) if ($logclearer);
2777 kill('KILL', $extauth) if ($extauth);
2783 local @tm = gmtime($_[0]);
2784 return sprintf "%s, %d %s %d %2.2d:%2.2d:%2.2d GMT",
2785 $weekday[$tm[6]], $tm[3], $month[$tm[4]], $tm[5]+1900,
2786 $tm[2], $tm[1], $tm[0];
2791 my $i; bless \$i, shift;
2797 my($buf,$len,$offset) = @_;
2798 &write_to_sock(substr($buf, $offset, $len));
2805 my $buf = join(defined($,) ? $, : "", @_);
2806 $buf .= $\ if defined($\);
2807 &write_to_sock($buf);
2814 &write_to_sock(sprintf $fmt, @_);
2817 # Send back already read data while we have it, then read from SOCK
2821 my $bufref = \$_[0];
2824 if ($postpos < length($postinput)) {
2825 # Reading from already fetched array
2826 my $left = length($postinput) - $postpos;
2827 my $canread = $len > $left ? $left : $len;
2828 substr($$bufref, $offset, $canread) =
2829 substr($postinput, $postpos, $canread);
2830 $postpos += $canread;
2834 # Read from network socket
2835 local $data = &read_data($len);
2836 if ($data eq '' && $len) {
2838 print STDERR "finished reading - shutting down socket\n";
2841 substr($$bufref, $offset, length($data)) = $data;
2842 return length($data);
2848 #print STDERR "open() called - should never happen!\n";
2851 # Read a line of input
2855 if ($postpos < length($postinput) &&
2856 ($idx = index($postinput, "\n", $postpos)) >= 0) {
2857 # A line exists in the memory buffer .. use it
2858 my $line = substr($postinput, $postpos, $idx-$postpos+1);
2863 # Need to read from the socket
2865 if ($postpos < length($postinput)) {
2866 # Start with in-memory data
2867 $line = substr($postinput, $postpos);
2868 $postpos = length($postinput);
2870 my $nl = &read_line(0, 1);
2873 print STDERR "finished reading - shutting down socket\n";
2876 $line .= $nl if (defined($nl));
2881 # Read one character of input
2886 my $got = READ($r, \$buf, 1, 0);
2887 return $got > 0 ? $buf : undef;
2892 return fileno(SOCK);
2899 # write_to_sock(data, ...)
2904 if ($doneheaders || $miniserv::nph_script) {
2909 while(!$doneheaders && $headers =~ s/^([^\r\n]*)(\r)?\n//) {
2910 if ($1 =~ /^(\S+):\s+(.*)$/) {
2911 $cgiheader{lc($1)} = $2;
2912 push(@cgiheader, [ $1, $2 ]);
2914 elsif ($1 !~ /\S/) {
2918 &http_error(500, "Bad Header");
2922 if ($cgiheader{"location"}) {
2924 "HTTP/1.0 302 Moved Temporarily\r\n");
2925 &write_data("Date: $datestr\r\n");
2926 &write_data("Server: $config{server}\r\n");
2927 &write_keep_alive(0);
2929 elsif ($cgiheader{"content-type"} eq "") {
2930 &http_error(500, "Missing Content-Type Header");
2933 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2934 &write_data("Date: $datestr\r\n");
2935 &write_data("Server: $config{server}\r\n");
2936 &write_keep_alive(0);
2938 foreach $h (@cgiheader) {
2939 &write_data("$h->[0]: $h->[1]\r\n");
2941 &write_data("\r\n");
2942 &reset_byte_count();
2943 &write_data($headers);
2951 local $cert = Net::SSLeay::X509_STORE_CTX_get_current_cert($_[1]);
2953 local $errnum = Net::SSLeay::X509_STORE_CTX_get_error($_[1]);
2954 $verified_client = 1 if (!$errnum);
2961 if ($doing_eval && $$ == $main_process_id) {
2962 # A CGI program called exit! This is a horrible hack to
2963 # finish up before really exiting
2966 close($PASSINw); close($PASSOUTw);
2967 &log_request($acpthost, $authuser, $reqline,
2968 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2973 # Convert a string to a form ok for putting in a URL
2975 local($tmp, $tmp2, $c);
2978 while(($c = chop($tmp)) ne "") {
2979 if ($c !~ /[A-z0-9]/) {
2980 $c = sprintf("%%%2.2X", ord($c));
2987 # validate_user(username, password, host)
2988 # Checks if some username and password are valid. Returns the modified username,
2989 # the expired / temp pass flag, and the non-existence flag
2992 local ($user, $pass, $host) = @_;
2993 return ( ) if (!$user);
2994 print DEBUG "validate_user: user=$user pass=$pass host=$host\n";
2995 local ($canuser, $canmode, $notexist, $webminuser, $sudo) =
2996 &can_user_login($user, undef, $host);
2997 print DEBUG "validate_user: canuser=$canuser canmode=$canmode notexist=$notexist webminuser=$webminuser sudo=$sudo\n";
2999 # User doesn't even exist, so go no further
3000 return ( undef, 0, 1 );
3002 elsif ($canmode == 0) {
3003 # User does exist but cannot login
3004 return ( $canuser, 0, 0 );
3006 elsif ($canmode == 1) {
3007 # Attempt Webmin authentication
3008 if ($users{$webminuser} eq
3009 &password_crypt($pass, $users{$webminuser})) {
3010 # Password is valid .. but check for expiry
3011 local $lc = $lastchanges{$user};
3012 if ($config{'pass_maxdays'} && $lc && !$nochange{$user}) {
3013 local $daysold = (time() - $lc)/(24*60*60);
3014 print DEBUG "maxdays=$config{'pass_maxdays'} daysold=$daysold temppass=$temppass{$user}\n";
3015 if ($config{'pass_lockdays'} &&
3016 $daysold > $config{'pass_lockdays'}) {
3017 # So old that the account is locked
3018 return ( undef, 0, 0 );
3020 elsif ($daysold > $config{'pass_maxdays'}) {
3021 # Password has expired
3022 return ( $user, 1, 0 );
3025 if ($temppass{$user}) {
3026 # Temporary password - force change now
3027 return ( $user, 2, 0 );
3029 return ( $user, 0, 0 );
3032 return ( undef, 0, 0 );
3035 elsif ($canmode == 2 || $canmode == 3) {
3036 # Attempt PAM or passwd file authentication
3037 local $val = &validate_unix_user($canuser, $pass);
3038 print DEBUG "validate_user: unix val=$val\n";
3039 if ($val && $sudo) {
3040 # Need to check if this Unix user can sudo
3041 if (!&check_sudo_permissions($canuser, $pass)) {
3042 print DEBUG "validate_user: sudo failed\n";
3046 print DEBUG "validate_user: sudo passed\n";
3049 return $val == 2 ? ( $canuser, 1, 0 ) :
3050 $val == 1 ? ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3052 elsif ($canmode == 4) {
3053 # Attempt external authentication
3054 return &validate_external_user($canuser, $pass) ?
3055 ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3063 # validate_unix_user(user, password)
3064 # Returns 1 if a username and password are valid under unix, 0 if not,
3065 # or 2 if the account has expired.
3066 # Checks PAM if available, and falls back to reading the system password
3068 sub validate_unix_user
3072 $pam_username = $_[0];
3073 $pam_password = $_[1];
3074 local $pamh = new Authen::PAM($config{'pam'}, $pam_username,
3077 local $pam_ret = $pamh->pam_authenticate();
3078 if ($pam_ret == PAM_SUCCESS()) {
3079 # Logged in OK .. make sure password hasn't expired
3080 local $acct_ret = $pamh->pam_acct_mgmt();
3081 if ($acct_ret == PAM_SUCCESS()) {
3082 $pamh->pam_open_session();
3085 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3086 $acct_ret == PAM_ACCT_EXPIRED()) {
3090 print STDERR "Unknown pam_acct_mgmt return value : $acct_ret\n";
3097 elsif ($config{'pam_only'}) {
3098 # Pam is not available, but configuration forces it's use!
3101 elsif ($config{'passwd_file'}) {
3102 # Check in a password file
3104 open(FILE, $config{'passwd_file'});
3105 if ($config{'passwd_file'} eq '/etc/security/passwd') {
3106 # Assume in AIX format
3109 if (/^\s*(\S+):/ && $1 eq $_[0]) {
3111 if (/^\s*password\s*=\s*(\S+)\s*$/) {
3112 $rv = $1 eq &password_crypt($_[1], $1) ?
3120 # Read the system password or shadow file
3122 local @l = split(/:/, $_, -1);
3123 local $u = $l[$config{'passwd_uindex'}];
3124 local $p = $l[$config{'passwd_pindex'}];
3126 $rv = $p eq &password_crypt($_[1], $p) ? 1 : 0;
3127 if ($config{'passwd_cindex'} ne '' && $rv) {
3128 # Password may have expired!
3129 local $c = $l[$config{'passwd_cindex'}];
3130 local $m = $l[$config{'passwd_mindex'}];
3131 local $day = time()/(24*60*60);
3132 if ($c =~ /^\d+/ && $m =~ /^\d+/ &&
3138 if ($p eq "" && $config{'passwd_blank'}) {
3139 # Force password change
3147 return $rv if ($rv);
3150 # Fallback option - check password returned by getpw*
3151 local @uinfo = getpwnam($_[0]);
3152 if ($uinfo[1] ne '' && &password_crypt($_[1], $uinfo[1]) eq $uinfo[1]) {
3156 return 0; # Totally failed
3159 # validate_external_user(user, pass)
3160 # Validate a user by passing the username and password to an external
3161 # squid-style authentication program
3162 sub validate_external_user
3164 return 0 if (!$config{'extauth'});
3166 local $str = "$_[0] $_[1]\n";
3167 syswrite(EXTAUTH, $str, length($str));
3168 local $resp = <EXTAUTH>;
3170 return $resp =~ /^OK/i ? 1 : 0;
3173 # can_user_login(username, no-append, host)
3174 # Checks if a user can login or not.
3175 # First return value is the username.
3176 # Second is 0 if cannot login, 1 if using Webmin pass, 2 if PAM, 3 if password
3177 # file, 4 if external.
3178 # Third is 1 if the user does not exist at all, 0 if he does.
3179 # Fourth is the Webmin username whose permissions apply, based on unixauth.
3180 # Fifth is a flag indicating if a sudo check is needed.
3183 if (!$users{$_[0]}) {
3184 # See if this user exists in Unix and can be validated by the same
3185 # method as the unixauth webmin user
3186 local $realuser = $unixauth{$_[0]};
3190 eval { @uinfo = getpwnam($_[0]); }; # may fail on windows
3191 if (!$realuser && @uinfo) {
3192 # No unixauth entry for the username .. try his groups
3193 foreach my $ua (keys %unixauth) {
3194 if ($ua =~ /^\@(.*)$/) {
3195 if (&is_group_member(\@uinfo, $1)) {
3196 $realuser = $unixauth{$ua};
3202 if (!$realuser && @uinfo) {
3203 # Fall back to unix auth for all Unix users
3204 $realuser = $unixauth{"*"};
3206 if (!$realuser && $use_sudo && @uinfo) {
3207 # Allow login effectively as root, if sudo permits it
3211 if (!$realuser && !@uinfo && $config{'pamany'}) {
3212 # If the user completely doesn't exist, we can still allow
3213 # him to authenticate via PAM
3214 $realuser = $config{'pamany'};
3218 # For Usermin, always fall back to unix auth for any user,
3219 # so that later checks with domain added / removed are done.
3220 $realuser = $unixauth{"*"};
3222 return (undef, 0, 1, undef) if (!$realuser);
3223 local $up = $users{$realuser};
3224 return (undef, 0, 1, undef) if (!defined($up));
3226 # Work out possible domain names from the hostname
3227 local @doms = ( $_[2] );
3228 if ($_[2] =~ /^([^\.]+)\.(\S+)$/) {
3232 if ($config{'user_mapping'} && !defined(%user_mapping)) {
3233 # Read the user mapping file
3235 open(MAPPING, $config{'user_mapping'});
3239 if (/^(\S+)\s+(\S+)/) {
3240 if ($config{'user_mapping_reverse'}) {
3241 $user_mapping{$1} = $2;
3244 $user_mapping{$2} = $1;
3251 # Check the user mapping file to see if there is an entry for the
3252 # user login in which specifies a new effective user
3254 foreach my $d (@doms) {
3255 $um ||= $user_mapping{"$_[0]\@$d"};
3257 $um ||= $user_mapping{$_[0]};
3258 if (defined($um) && ($_[1]&4) == 0) {
3259 # A mapping exists - use it!
3260 return &can_user_login($um, $_[1]+4, $_[2]);
3263 # Check if a user with the entered login and the domains appended
3264 # or prepended exists, and if so take it to be the effective user
3265 if (!@uinfo && $config{'domainuser'}) {
3266 # Try again with name.domain and name.firstpart
3267 local @firsts = map { /^([^\.]+)/; $1 } @doms;
3268 if (($_[1]&1) == 0) {
3270 foreach $a (@firsts, @doms) {
3271 foreach $p ("$_[0].${a}", "$_[0]-${a}",
3272 "${a}.$_[0]", "${a}-$_[0]",
3273 "$_[0]_${a}", "${a}_$_[0]") {
3274 local @vu = &can_user_login(
3275 $p, $_[1]+1, $_[2]);
3276 return @vu if ($vu[1]);
3282 # Check if the user entered a domain at the end of his username when
3283 # he really shouldn't have, and if so try without it
3284 if (!@uinfo && $config{'domainstrip'} &&
3285 $_[0] =~ /^(\S+)\@(\S+)$/ && ($_[1]&2) == 0) {
3286 local ($stripped, $dom) = ($1, $2);
3287 local @vu = &can_user_login($stripped, $_[1] + 2, $_[2]);
3288 return @vu if ($vu[1]);
3289 local @vu = &can_user_login($stripped, $_[1] + 2, $dom);
3290 return @vu if ($vu[1]);
3293 return ( undef, 0, 1, undef ) if (!@uinfo && !$pamany);
3296 if (defined(@allowusers)) {
3297 # Only allow people on the allow list
3298 return ( undef, 0, 0, undef )
3299 if (!&users_match(\@uinfo, @allowusers));
3301 elsif (defined(@denyusers)) {
3302 # Disallow people on the deny list
3303 return ( undef, 0, 0, undef )
3304 if (&users_match(\@uinfo, @denyusers));
3306 if ($config{'shells_deny'}) {
3308 open(SHELLS, $config{'shells_deny'});
3312 $found++ if ($_ eq $uinfo[8]);
3315 return ( undef, 0, 0, undef ) if (!$found);
3320 # PAM or passwd file authentication
3321 return ( $_[0], $use_pam ? 2 : 3, 0, $realuser, $sudo );
3323 elsif ($up eq 'e') {
3324 # External authentication
3325 return ( $_[0], 4, 0, $realuser, $sudo );
3328 # Fixed Webmin password
3329 return ( $_[0], 1, 0, $realuser, $sudo );
3332 elsif ($users{$_[0]} eq 'x') {
3333 # Webmin user authenticated via PAM or password file
3334 return ( $_[0], $use_pam ? 2 : 3, 0, $_[0] );
3336 elsif ($users{$_[0]} eq 'e') {
3337 # Webmin user authenticated externally
3338 return ( $_[0], 4, 0, $_[0] );
3341 # Normal Webmin user
3342 return ( $_[0], 1, 0, $_[0] );
3346 # the PAM conversation function for interactive logins
3349 $pam_conv_func_called++;
3356 $ans = $pam_username if ($code == PAM_PROMPT_ECHO_ON() );
3357 $ans = $pam_password if ($code == PAM_PROMPT_ECHO_OFF() );
3359 push @res, PAM_SUCCESS();
3362 push @res, PAM_SUCCESS();
3371 # get_socket_name(handle)
3372 # Returns the local hostname or IP address of some connection
3375 return $config{'host'} if ($config{'host'});
3376 local $sn = getsockname($_[0]);
3377 return undef if (!$sn);
3378 local $myaddr = (unpack_sockaddr_in($sn))[1];
3379 if (!$get_socket_name_cache{$myaddr}) {
3381 if (!$config{'no_resolv_myname'}) {
3382 $myname = gethostbyaddr($myaddr, AF_INET);
3384 if ($myname eq "") {
3385 $myname = inet_ntoa($myaddr);
3387 $get_socket_name_cache{$myaddr} = $myname;
3389 return $get_socket_name_cache{$myaddr};
3392 # run_login_script(username, sid, remoteip, localip)
3393 sub run_login_script
3395 if ($config{'login_script'}) {
3396 system($config{'login_script'}.
3397 " ".join(" ", map { quotemeta($_) || '""' } @_).
3398 " >/dev/null 2>&1 </dev/null");
3402 # run_logout_script(username, sid, remoteip, localip)
3403 sub run_logout_script
3405 if ($config{'logout_script'}) {
3406 system($config{'logout_script'}.
3407 " ".join(" ", map { quotemeta($_) || '""' } @_).
3408 " >/dev/null 2>&1 </dev/null");
3412 # close_all_sockets()
3413 # Closes all the main listening sockets
3414 sub close_all_sockets
3417 foreach $s (@socketfhs) {
3423 # Close all pipes for talking to sub-processes
3427 foreach $p (@passin) { close($p); }
3428 foreach $p (@passout) { close($p); }
3429 foreach $p (values %conversations) {
3430 if ($p->{'PAMOUTr'}) {
3431 close($p->{'PAMOUTr'});
3432 close($p->{'PAMINw'});
3437 # check_user_ip(user)
3438 # Returns 1 if some user is allowed to login from the accepting IP, 0 if not
3442 &ip_match($acptip, $localip, @{$deny{$_[0]}}) ||
3444 !&ip_match($acptip, $localip, @{$allow{$_[0]}})) {
3450 # check_user_time(user)
3451 # Returns 1 if some user is allowed to login at the current date and time
3454 return 1 if (!$allowdays{$_[0]} && !$allowhours{$_[0]});
3455 local @tm = localtime(time());
3456 if ($allowdays{$_[0]}) {
3457 # Make sure day is allowed
3458 return 0 if (&indexof($tm[6], @{$allowdays{$_[0]}}) < 0);
3460 if ($allowhours{$_[0]}) {
3461 # Make sure time is allowed
3462 local $m = $tm[2]*60+$tm[1];
3463 return 0 if ($m < $allowhours{$_[0]}->[0] ||
3464 $m > $allowhours{$_[0]}->[1]);
3469 # generate_random_id(password, [force-urandom])
3470 # Returns a random session ID number
3471 sub generate_random_id
3473 local ($pass, $force_urandom) = @_;
3475 if (!$bad_urandom) {
3476 # First try /dev/urandom, unless we have marked it as bad
3477 $SIG{ALRM} = "miniserv::urandom_timeout";
3479 if (open(RANDOM, "/dev/urandom")) {
3481 if (read(RANDOM, $tmpsid, 16) == 16) {
3482 $sid = lc(unpack('h*',$tmpsid));
3488 if (!$sid && !$force_urandom) {
3491 foreach $c (split(//, &unix_crypt($pass, substr($$, -2)))) {
3492 $sid += ord($c) * $mul;
3499 # handle_login(username, ok, expired, not-exists, password, [no-test-cookie])
3500 # Called from handle_session to either mark a user as logged in, or not
3503 local ($vu, $ok, $expired, $nonexist, $pass, $notest) = @_;
3504 $authuser = $vu if ($ok);
3506 # check if the test cookie is set
3507 if ($header{'cookie'} !~ /testing=1/ && $vu &&
3508 !$config{'no_testing_cookie'} && !$notest) {
3509 &http_error(500, "No cookies",
3510 "Your browser does not support cookies, ".
3511 "which are required for this web server to ".
3512 "work in session authentication mode");
3515 # check with main process for delay
3516 if ($config{'passdelay'} && $vu) {
3517 print $PASSINw "delay $vu $acptip $ok\n";
3518 <$PASSOUTr> =~ /(\d+) (\d+)/;
3523 if ($ok && (!$expired ||
3524 $config{'passwd_mode'} == 1)) {
3525 # Logged in OK! Tell the main process about
3527 local $sid = &generate_random_id($pass);
3528 print $PASSINw "new $sid $authuser $acptip\n";
3530 # Run the post-login script, if any
3531 &run_login_script($authuser, $sid,
3534 # Check for a redirect URL for the user
3535 local $rurl = &login_redirect($authuser, $pass, $host);
3537 # Got one .. go to it
3538 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3539 &write_data("Date: $datestr\r\n");
3540 &write_data("Server: $config{'server'}\r\n");
3541 &write_data("Location: $rurl\r\n");
3542 &write_keep_alive(0);
3543 &write_data("\r\n");
3544 &log_request($acpthost, $authuser, $reqline, 302, 0);
3547 # Set cookie and redirect to originally requested page
3548 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3549 &write_data("Date: $datestr\r\n");
3550 &write_data("Server: $config{'server'}\r\n");
3551 local $ssl = $use_ssl || $config{'inetd_ssl'};
3552 $portstr = $port == 80 && !$ssl ? "" :
3553 $port == 443 && $ssl ? "" : ":$port";
3554 $prot = $ssl ? "https" : "http";
3555 local $sec = $ssl ? "; secure" : "";
3556 #$sec .= "; httpOnly";
3558 &write_data("Set-Cookie: $sidname=$sid; path=/; expires=\"Thu, 31-Dec-2037 00:00:00\"$sec\r\n");
3561 &write_data("Set-Cookie: $sidname=$sid; path=/$sec\r\n");
3563 &write_data("Location: $prot://$host$portstr$in{'page'}\r\n");
3564 &write_keep_alive(0);
3565 &write_data("\r\n");
3566 &log_request($acpthost, $authuser, $reqline, 302, 0);
3567 syslog("info", "%s", "Successful login as $authuser from $acpthost") if ($use_syslog);
3568 &write_login_utmp($authuser, $acpthost);
3572 elsif ($ok && $expired &&
3573 ($config{'passwd_mode'} == 2 || $expired == 2)) {
3574 # Login was ok, but password has expired or was temporary. Need
3575 # to force display of password change form.
3578 $querystring = "&user=".&urlize($vu).
3580 "&expired=".$expired;
3583 $page = $config{'password_form'};
3585 $miniserv_internal = 2;
3586 syslog("crit", "%s",
3587 "Expired login as $vu ".
3588 "from $acpthost") if ($use_syslog);
3591 # Login failed, or password has expired. The login form will be
3592 # displayed again by later code
3594 $request_uri = $in{'page'};
3595 $already_session_id = undef;
3597 $authuser = $baseauthuser = undef;
3598 syslog("crit", "%s",
3599 ($nonexist ? "Non-existent" :
3600 $expired ? "Expired" : "Invalid").
3601 " login as $vu from $acpthost")
3607 # write_login_utmp(user, host)
3608 # Record the login by some user in utmp
3609 sub write_login_utmp
3612 # Write utmp record for login
3613 %utmp = ( 'ut_host' => $_[1],
3614 'ut_time' => time(),
3616 'ut_type' => 7, # user process
3617 'ut_pid' => $main_process_id,
3618 'ut_line' => $config{'pam'},
3620 if (defined(&User::Utmp::putut)) {
3621 User::Utmp::putut(\%utmp);
3624 User::Utmp::pututline(\%utmp);
3629 # write_logout_utmp(user, host)
3630 # Record the logout by some user in utmp
3631 sub write_logout_utmp
3634 # Write utmp record for logout
3635 %utmp = ( 'ut_host' => $_[1],
3636 'ut_time' => time(),
3638 'ut_type' => 8, # dead process
3639 'ut_pid' => $main_process_id,
3640 'ut_line' => $config{'pam'},
3642 if (defined(&User::Utmp::putut)) {
3643 User::Utmp::putut(\%utmp);
3646 User::Utmp::pututline(\%utmp);
3651 # pam_conversation_process(username, write-pipe, read-pipe)
3652 # This function is called inside a sub-process to communicate with PAM. It sends
3653 # questions down one pipe, and reads responses from another
3654 sub pam_conversation_process
3656 local ($user, $writer, $reader) = @_;
3657 $miniserv::pam_conversation_process_writer = $writer;
3658 $miniserv::pam_conversation_process_reader = $reader;
3659 local $convh = new Authen::PAM(
3660 $config{'pam'}, $user, \&miniserv::pam_conversation_process_func);
3661 local $pam_ret = $convh->pam_authenticate();
3662 if ($pam_ret == PAM_SUCCESS()) {
3663 local $acct_ret = $convh->pam_acct_mgmt();
3664 if ($acct_ret == PAM_SUCCESS()) {
3665 $convh->pam_open_session();
3666 print $writer "x2 $user 1 0 0\n";
3668 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3669 $acct_ret == PAM_ACCT_EXPIRED()) {
3670 print $writer "x2 $user 1 1 0\n";
3673 print $writer "x0 Unknown PAM account status $acct_ret\n";
3677 print $writer "x2 $user 0 0 0\n";
3682 # pam_conversation_process_func(type, message, [type, message, ...])
3683 # A pipe that talks to both PAM and the master process
3684 sub pam_conversation_process_func
3687 select($miniserv::pam_conversation_process_writer); $| = 1; select(STDOUT);
3689 local ($type, $msg) = (shift, shift);
3691 local $ok = (print $miniserv::pam_conversation_process_writer "$type $msg\n");
3692 print $miniserv::pam_conversation_process_writer "\n";
3693 local $answer = <$miniserv::pam_conversation_process_reader>;
3694 $answer =~ s/\r|\n//g;
3695 push(@rv, PAM_SUCCESS(), $answer);
3697 push(@rv, PAM_SUCCESS());
3702 # Returns 4 new pipe file handles
3705 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3707 local %taken = ( (map { $_, 1 } @passin),
3708 (map { $_->{'PASSINr'} } values %conversations) );
3709 for($p=0; $taken{"PASSINr$p"}; $p++) { }
3710 $PASSINr = "PASSINr$p";
3711 $PASSINw = "PASSINw$p";
3712 $PASSOUTr = "PASSOUTr$p";
3713 $PASSOUTw = "PASSOUTw$p";
3714 pipe($PASSINr, $PASSINw);
3715 pipe($PASSOUTr, $PASSOUTw);
3716 select($PASSINw); $| = 1;
3717 select($PASSINr); $| = 1;
3718 select($PASSOUTw); $| = 1;
3719 select($PASSOUTw); $| = 1;
3721 return ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3724 # recv_pam_question(&conv, fd)
3725 # Reads one PAM question from the sub-process, and sends it to the HTTP handler.
3726 # Returns 0 if the conversation is over, 1 if not.
3727 sub recv_pam_question
3729 local ($conf, $fh) = @_;
3730 local $pr = $conf->{'PAMOUTr'};
3731 select($pr); $| = 1; select(STDOUT);
3732 local $line = <$pr>;
3733 $line =~ s/\r|\n//g;
3736 $line =~ s/\r|\n//g;
3738 $conf->{'last'} = time();
3741 print $fh "0 PAM conversation error\n";
3745 local ($type, $msg) = split(/\s+/, $line, 2);
3746 if ($type =~ /^x(\d+)/) {
3747 # Pass this status code through
3748 print $fh "$1 $msg\n";
3749 return $1 == 2 || $1 == 0 ? 0 : 1;
3751 elsif ($type == PAM_PROMPT_ECHO_ON()) {
3753 print $fh "1 $msg\n";
3756 elsif ($type == PAM_PROMPT_ECHO_OFF()) {
3758 print $fh "3 $msg\n";
3761 elsif ($type == PAM_ERROR_MSG() || $type == PAM_TEXT_INFO()) {
3762 # A message that does not require a response
3763 print $fh "4 $msg\n";
3768 print $fh "0 Unknown PAM message type $type\n";
3774 # send_pam_answer(&conv, answer)
3775 # Sends a response from the user to the PAM sub-process
3778 local ($conf, $answer) = @_;
3779 local $pw = $conf->{'PAMINw'};
3780 $conf->{'last'} = time();
3781 print $pw "$answer\n";
3784 # end_pam_conversation(&conv)
3785 # Clean up PAM conversation pipes and processes
3786 sub end_pam_conversation
3789 kill('KILL', $conv->{'pid'}) if ($conv->{'pid'});
3790 if ($conv->{'PAMINr'}) {
3791 close($conv->{'PAMINr'});
3792 close($conv->{'PAMOUTr'});
3793 close($conv->{'PAMINw'});
3794 close($conv->{'PAMOUTw'});
3796 delete($conversations{$conv->{'cid'}});
3799 # get_ipkeys(&miniserv)
3800 # Returns a list of IP address to key file mappings from a miniserv.conf entry
3804 foreach $k (keys %{$_[0]}) {
3805 if ($k =~ /^ipkey_(\S+)/) {
3806 local $ipkey = { 'ips' => [ split(/,/, $1) ],
3807 'key' => $_[0]->{$k},
3808 'index' => scalar(@rv) };
3809 $ipkey->{'cert'} = $_[0]->{'ipcert_'.$1};
3816 # create_ssl_context(keyfile, [certfile])
3817 sub create_ssl_context
3819 local ($keyfile, $certfile) = @_;
3821 eval { $ssl_ctx = Net::SSLeay::new_x_ctx() };
3822 $ssl_ctx ||= Net::SSLeay::CTX_new();
3823 $ssl_ctx || die "Failed to create SSL context : $!";
3824 if ($client_certs) {
3825 Net::SSLeay::CTX_load_verify_locations(
3826 $ssl_ctx, $config{'ca'}, "");
3827 Net::SSLeay::CTX_set_verify(
3828 $ssl_ctx, &Net::SSLeay::VERIFY_PEER, \&verify_client);
3830 if ($config{'extracas'}) {
3832 foreach $p (split(/\s+/, $config{'extracas'})) {
3833 Net::SSLeay::CTX_load_verify_locations(
3838 Net::SSLeay::CTX_use_RSAPrivateKey_file(
3840 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL key $keyfile";
3841 Net::SSLeay::CTX_use_certificate_file(
3842 $ssl_ctx, $certfile || $keyfile,
3843 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL cert $certfile";
3848 # ssl_connection_for_ip(socket)
3849 # Returns a new SSL connection object for some socket, or undef if failed
3850 sub ssl_connection_for_ip
3853 local $sn = getsockname($sock);
3855 print STDERR "Failed to get address for socket $sock\n";
3858 local $myip = inet_ntoa((unpack_sockaddr_in($sn))[1]);
3859 local $ssl_ctx = $ssl_contexts{$myip} || $ssl_contexts{"*"};
3860 local $ssl_con = Net::SSLeay::new($ssl_ctx);
3861 if ($config{'ssl_cipher_list'}) {
3862 # Force use of ciphers
3863 eval "Net::SSLeay::set_cipher_list(
3864 \$ssl_con, \$config{'ssl_cipher_list'})";
3866 print STDERR "SSL cipher $config{'ssl_cipher_list'} failed : ",
3872 Net::SSLeay::set_fd($ssl_con, fileno($sock));
3873 if (!Net::SSLeay::accept($ssl_con)) {
3874 print STDERR "Failed to initialize SSL connection\n";
3880 # login_redirect(username, password, host)
3881 # Calls the login redirect script (if configured), which may output a URL to
3882 # re-direct a user to after logging in.
3885 return undef if (!$config{'login_redirect'});
3886 local $quser = quotemeta($_[0]);
3887 local $qpass = quotemeta($_[1]);
3888 local $qhost = quotemeta($_[2]);
3889 local $url = `$config{'login_redirect'} $quser $qpass $qhost`;
3894 # reload_config_file()
3895 # Re-read %config, and call post-config actions
3896 sub reload_config_file
3898 &log_error("Reloading configuration");
3899 %config = &read_config_file($config_file);
3900 &update_vital_config();
3903 &build_config_mappings();
3904 if ($config{'session'}) {
3905 dbmclose(%sessiondb);
3906 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
3910 # read_config_file(file)
3911 # Reads the given config file, and returns a hash of values
3912 sub read_config_file
3915 open(CONF, $_[0]) || die "Failed to open config file $_[0] : $!";
3918 if (/^#/ || !/\S/) { next; }
3920 $name = $1; $val = $2;
3921 $name =~ s/^\s+//g; $name =~ s/\s+$//g;
3922 $val =~ s/^\s+//g; $val =~ s/\s+$//g;
3929 # update_vital_config()
3930 # Updates %config with defaults, and dies if something vital is missing
3931 sub update_vital_config
3933 my %vital = ("port", 80,
3935 "server", "MiniServ/0.01",
3936 "index_docs", "index.html index.htm index.cgi index.php",
3937 "addtype_html", "text/html",
3938 "addtype_txt", "text/plain",
3939 "addtype_gif", "image/gif",
3940 "addtype_jpg", "image/jpeg",
3941 "addtype_jpeg", "image/jpeg",
3942 "realm", "MiniServ",
3943 "session_login", "/session_login.cgi",
3944 "pam_login", "/pam_login.cgi",
3945 "password_form", "/password_form.cgi",
3946 "password_change", "/password_change.cgi",
3950 "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\$",
3952 "expires", 7*24*60*60,
3953 "pam_test_user", "root",
3955 foreach my $v (keys %vital) {
3957 if ($vital{$v} eq "") {
3958 die "Missing config option $v";
3960 $config{$v} = $vital{$v};
3963 if (!$config{'sessiondb'}) {
3964 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3965 $config{'sessiondb'} = "$1/sessiondb";
3967 if (!$config{'errorlog'}) {
3968 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
3969 $config{'errorlog'} = "$1/miniserv.error";
3971 if (!$config{'tempbase'}) {
3972 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3973 $config{'tempbase'} = "$1/cgitemp";
3975 if (!$config{'blockedfile'}) {
3976 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3977 $config{'blockedfile'} = "$1/blocked";
3982 # Fills the %users and %certs hashes from the users file in %config
3991 undef(%lastchanges);
3994 if ($config{'userfile'}) {
3995 open(USERS, $config{'userfile'});
3998 local @user = split(/:/, $_, -1);
3999 $users{$user[0]} = $user[1];
4000 $certs{$user[0]} = $user[3] if ($user[3]);
4001 if ($user[4] =~ /^allow\s+(.*)/) {
4002 $allow{$user[0]} = $config{'alwaysresolve'} ?
4003 [ split(/\s+/, $1) ] :
4004 [ &to_ipaddress(split(/\s+/, $1)) ];
4006 elsif ($user[4] =~ /^deny\s+(.*)/) {
4007 $deny{$user[0]} = $config{'alwaysresolve'} ?
4008 [ split(/\s+/, $1) ] :
4009 [ &to_ipaddress(split(/\s+/, $1)) ];
4011 if ($user[5] =~ /days\s+(\S+)/) {
4012 $allowdays{$user[0]} = [ split(/,/, $1) ];
4014 if ($user[5] =~ /hours\s+(\d+)\.(\d+)-(\d+).(\d+)/) {
4015 $allowhours{$user[0]} = [ $1*60+$2, $3*60+$4 ];
4017 $lastchanges{$user[0]} = $user[6];
4018 $nochange{$user[0]} = $user[9];
4019 $temppass{$user[0]} = $user[10];
4026 # Fills %mime with entries from file in %config and extra settings in %config
4030 if ($config{"mimetypes"} ne "") {
4031 open(MIME, $config{"mimetypes"});
4034 if (/^(\S+)\s+(.*)$/) {
4036 my @exts = split(/\s+/, $2);
4037 foreach my $ext (@exts) {
4038 $mime{$ext} = $type;
4044 foreach my $k (keys %config) {
4045 if ($k !~ /^addtype_(.*)$/) { next; }
4046 $mime{$1} = $config{$k};
4050 # build_config_mappings()
4051 # Build the anonymous access list, IP access list, unauthenticated URLs list,
4052 # redirect mapping and allow and deny lists from %config
4053 sub build_config_mappings
4055 # build anonymous access list
4057 foreach my $a (split(/\s+/, $config{'anonymous'})) {
4058 if ($a =~ /^([^=]+)=(\S+)$/) {
4059 $anonymous{$1} = $2;
4063 # build IP access list
4065 foreach my $a (split(/\s+/, $config{'ipaccess'})) {
4066 if ($a =~ /^([^=]+)=(\S+)$/) {
4071 # build unauthenticated URLs list
4072 @unauth = split(/\s+/, $config{'unauth'});
4074 # build redirect mapping
4076 foreach my $r (split(/\s+/, $config{'redirect'})) {
4077 if ($r =~ /^([^=]+)=(\S+)$/) {
4082 # build prefixes to be stripped
4083 undef(@strip_prefix);
4084 foreach my $r (split(/\s+/, $config{'strip_prefix'})) {
4085 push(@strip_prefix, $r);
4088 # Init allow and deny lists
4089 @deny = split(/\s+/, $config{"deny"});
4090 @deny = &to_ipaddress(@deny) if (!$config{'alwaysresolve'});
4091 @allow = split(/\s+/, $config{"allow"});
4092 @allow = &to_ipaddress(@allow) if (!$config{'alwaysresolve'});
4095 if ($config{'allowusers'}) {
4096 @allowusers = split(/\s+/, $config{'allowusers'});
4098 elsif ($config{'denyusers'}) {
4099 @denyusers = split(/\s+/, $config{'denyusers'});
4102 # Build list of unixauth mappings
4104 foreach my $ua (split(/\s+/, $config{'unixauth'})) {
4105 if ($ua =~ /^(\S+)=(\S+)$/) {
4109 $unixauth{"*"} = $ua;
4113 # Build list of non-session-auth pages
4114 undef(%sessiononly);
4115 foreach my $sp (split(/\s+/, $config{'sessiononly'})) {
4116 $sessiononly{$sp} = 1;
4119 # Build list of logout times
4120 undef(@logouttimes);
4121 foreach my $a (split(/\s+/, $config{'logouttimes'})) {
4122 if ($a =~ /^([^=]+)=(\S+)$/) {
4123 push(@logouttimes, [ $1, $2 ]);
4126 push(@logouttimes, [ undef, $config{'logouttime'} ]);
4128 # Build list of DAV pathss
4130 foreach my $d (split(/\s+/, $config{'davpaths'})) {
4131 push(@davpaths, $d);
4133 @davusers = split(/\s+/, $config{'dav_users'});
4135 # Mobile agent substrings and hostname prefixes
4136 @mobile_agents = split(/\t+/, $config{'mobile_agents'});
4137 @mobile_prefixes = split(/\s+/, $config{'mobile_prefixes'});
4141 if ($config{'debug'}) {
4142 open(DEBUG, ">>$config{'debug'}");
4145 open(DEBUG, ">/dev/null");
4148 # Reset cache of sudo checks
4152 # is_group_member(&uinfo, groupname)
4153 # Returns 1 if some user is a primary or secondary member of a group
4156 local ($uinfo, $group) = @_;
4157 local @ginfo = getgrnam($group);
4158 return 0 if (!@ginfo);
4159 return 1 if ($ginfo[2] == $uinfo->[3]); # primary member
4160 foreach my $m (split(/\s+/, $ginfo[3])) {
4161 return 1 if ($m eq $uinfo->[0]);
4166 # prefix_to_mask(prefix)
4167 # Converts a number like 24 to a mask like 255.255.255.0
4170 return $_[0] >= 24 ? "255.255.255.".(256-(2 ** (32-$_[0]))) :
4171 $_[0] >= 16 ? "255.255.".(256-(2 ** (24-$_[0]))).".0" :
4172 $_[0] >= 8 ? "255.".(256-(2 ** (16-$_[0]))).".0.0" :
4173 (256-(2 ** (8-$_[0]))).".0.0.0";
4176 # get_logout_time(user, session-id)
4177 # Given a username, returns the idle time before he will be logged out
4180 local ($user, $sid) = @_;
4181 if (!defined($logout_time_cache{$user,$sid})) {
4183 foreach my $l (@logouttimes) {
4184 if ($l->[0] =~ /^\@(.*)$/) {
4185 # Check group membership
4186 local @uinfo = getpwnam($user);
4187 if (@uinfo && &is_group_member(\@uinfo, $1)) {
4191 elsif ($l->[0] =~ /^\//) {
4192 # Check file contents
4193 open(FILE, $l->[0]);
4210 if ($l->[0] eq $user) {
4214 last if (defined($time));
4216 $logout_time_cache{$user,$sid} = $time;
4218 return $logout_time_cache{$user,$sid};
4221 # password_crypt(password, salt)
4222 # If the salt looks like MD5 and we have a library for it, perform MD5 hashing
4223 # of a password. Otherwise, do Unix crypt.
4226 local ($pass, $salt) = @_;
4227 if ($salt =~ /^\$1\$/ && $use_md5) {
4228 return &encrypt_md5($pass, $salt);
4231 return &unix_crypt($pass, $salt);
4235 # unix_crypt(password, salt)
4236 # Performs standard Unix hashing for a password
4239 local ($pass, $salt) = @_;
4240 if ($use_perl_crypt) {
4241 return Crypt::UnixCrypt::crypt($pass, $salt);
4244 return crypt($pass, $salt);
4248 # handle_dav_request(davpath)
4249 # Pass a request on to the Net::DAV::Server module
4250 sub handle_dav_request
4253 eval "use Filesys::Virtual::Plain";
4254 eval "use Net::DAV::Server";
4255 eval "use HTTP::Request";
4256 eval "use HTTP::Headers";
4258 if ($Net::DAV::Server::VERSION eq '1.28' && $config{'dav_nolock'}) {
4259 delete $Net::DAV::Server::implemented{lock};
4260 delete $Net::DAV::Server::implemented{unlock};
4263 # Read in request data
4264 if (!$posted_data) {
4265 local $clen = $header{"content-length"};
4266 while(length($posted_data) < $clen) {
4267 $buf = &read_data($clen - length($posted_data));
4268 if (!length($buf)) {
4269 &http_error(500, "Failed to read POST request");
4271 $posted_data .= $buf;
4275 # For subsequent logging
4276 open(MINISERVLOG, ">>$config{'logfile'}");
4280 local @u = getpwnam($authuser);
4281 if ($config{'dav_remoteuser'} && !$< && $validated) {
4284 $( = $u[3]; $) = "$u[3] $u[3]";
4285 ($>, $<) = ($u[2], $u[2]);
4287 if ($config{'dav_root'} eq '*') {
4292 &http_error(500, "Unix user $authuser does not exist");
4296 $root ||= $config{'dav_root'};
4299 # Check if this user can use DAV
4301 &users_match(\@u, @davusers) ||
4302 &http_error(500, "You are not allowed to access DAV");
4306 my $filesys = Filesys::Virtual::Plain->new({root_path => $root});
4307 my $webdav = Net::DAV::Server->new();
4308 $webdav->filesys($filesys);
4310 # Make up a request object, and feed to DAV
4311 local $ho = HTTP::Headers->new;
4312 foreach my $h (keys %header) {
4313 next if (lc($h) eq "connection");
4314 $ho->header($h => $header{$h});
4317 $request_uri =~ s/^\Q$path\E//;
4318 $request_uri = "/" if ($request_uri eq "");
4320 my $request = HTTP::Request->new($method, $request_uri, $ho,
4322 if ($config{'dav_debug'}) {
4323 print STDERR "DAV request :\n";
4324 print STDERR "---------------------------------------------\n";
4325 print STDERR $request->as_string();
4326 print STDERR "---------------------------------------------\n";
4328 my $response = $webdav->run($request);
4330 # Send back the reply
4331 &write_data("HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n");
4332 local $content = $response->content();
4334 $content =~ s|href>/(.+)<|href>$path/$1<|g;
4335 $content =~ s|href>/<|href>$path<|g;
4337 foreach my $h ($response->header_field_names) {
4338 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4339 &write_data("$h: ",$response->header($h),"\r\n");
4341 &write_data("Content-length: ",length($content),"\r\n");
4342 local $rv = &write_keep_alive(0);
4343 &write_data("\r\n");
4344 &write_data($content);
4346 if ($config{'dav_debug'}) {
4347 print STDERR "DAV reply :\n";
4348 print STDERR "---------------------------------------------\n";
4349 print STDERR "HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n";
4350 foreach my $h ($response->header_field_names) {
4351 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4352 print STDERR "$h: ",$response->header($h),"\r\n";
4354 print STDERR "Content-length: ",length($content),"\r\n";
4355 print STDERR "\r\n";
4356 print STDERR $content;
4357 print STDERR "---------------------------------------------\n";
4361 &log_request($acpthost, $authuser, $reqline, $response->code(),
4362 length($response->content()));
4365 # get_system_hostname()
4366 # Returns the hostname of this system, for reporting to listeners
4367 sub get_system_hostname
4369 # On Windows, try computername environment variable
4370 return $ENV{'computername'} if ($ENV{'computername'});
4371 return $ENV{'COMPUTERNAME'} if ($ENV{'COMPUTERNAME'});
4373 # If a specific command is set, use it first
4374 if ($config{'hostname_command'}) {
4375 local $out = `($config{'hostname_command'}) 2>&1`;
4382 # First try the hostname command
4383 local $out = `hostname 2>&1`;
4384 if (!$? && $out =~ /\S/) {
4389 # Try the Sys::Hostname module
4390 eval "use Sys::Hostname";
4392 local $rv = eval "hostname()";
4398 # Must use net name on Windows
4399 local $out = `net name 2>&1`;
4400 if ($out =~ /\-+\r?\n(\S+)/) {
4407 # indexof(string, array)
4408 # Returns the index of some value in an array, or -1
4411 for($i=1; $i <= $#_; $i++) {
4412 if ($_[$i] eq $_[0]) { return $i - 1; }
4418 # has_command(command)
4419 # Returns the full path if some command is in the path, undef if not
4423 if (!$_[0]) { return undef; }
4424 if (exists($has_command_cache{$_[0]})) {
4425 return $has_command_cache{$_[0]};
4428 if ($_[0] =~ /^\//) {
4429 $rv = -x $_[0] ? $_[0] : undef;
4432 local $sp = $on_windows ? ';' : ':';
4433 foreach $d (split($sp, $ENV{PATH})) {
4434 if (-x "$d/$_[0]") {
4439 foreach my $sfx (".exe", ".com", ".bat") {
4440 if (-r "$d/$_[0]".$sfx) {
4441 $rv = "$d/$_[0]".$sfx;
4448 $has_command_cache{$_[0]} = $rv;
4452 # check_sudo_permissions(user, pass)
4453 # Returns 1 if some user can run any command via sudo
4454 sub check_sudo_permissions
4456 local ($user, $pass) = @_;
4458 # First try the pipes
4460 print DEBUG "check_sudo_permissions: querying cache for $user\n";
4461 print $PASSINw "readsudo $user\n";
4462 local $can = <$PASSOUTr>;
4464 print DEBUG "check_sudo_permissions: cache said $can\n";
4465 if ($can =~ /^\d+$/ && $can != 2) {
4470 local $ptyfh = new IO::Pty;
4471 print DEBUG "check_sudo_permissions: ptyfh=$ptyfh\n";
4473 print STDERR "Failed to create new PTY with IO::Pty\n";
4476 local @uinfo = getpwnam($user);
4478 print STDERR "Unix user $user does not exist for sudo\n";
4482 # Execute sudo in a sub-process, via a pty
4483 local $ttyfh = $ptyfh->slave();
4484 print DEBUG "check_sudo_permissions: ttyfh=$ttyfh\n";
4485 local $tty = $ptyfh->ttyname();
4486 print DEBUG "check_sudo_permissions: tty=$tty\n";
4487 chown($uinfo[2], $uinfo[3], $tty);
4489 print DEBUG "check_sudo_permissions: about to fork..\n";
4490 local $pid = fork();
4491 print DEBUG "check_sudo_permissions: fork=$pid pid=$$\n";
4493 print STDERR "fork for sudo failed : $!\n";
4498 $ptyfh->make_slave_controlling_terminal();
4499 close(STDIN); close(STDOUT); close(STDERR);
4500 untie(*STDIN); untie(*STDOUT); untie(*STDERR);
4501 close($PASSINw); close($PASSOUTr);
4502 $( = $uinfo[3]; $) = "$uinfo[3] $uinfo[3]";
4503 ($>, $<) = ($uinfo[2], $uinfo[2]);
4508 open(STDIN, "<&SUDOr");
4509 open(STDOUT, ">$tty");
4510 open(STDERR, ">&STDOUT");
4513 print "Exec failed : $!\n";
4516 print DEBUG "check_sudo_permissions: pid=$pid\n";
4518 $ptyfh->close_slave();
4520 # Send password, and get back response
4521 local $oldfh = select(SUDOw);
4524 print DEBUG "check_sudo_permissions: about to send pass\n";
4525 local $SIG{'PIPE'} = 'ignore'; # Sometimes sudo doesn't ask for a password
4526 print SUDOw $pass,"\n";
4527 print DEBUG "check_sudo_permissions: sent pass=$pass\n";
4531 print DEBUG "check_sudo_permissions: got $_";
4537 local ($ok) = ($out =~ /\(ALL\)\s+ALL/ ? 1 : 0);
4541 print $PASSINw "writesudo $user $ok\n";
4547 # is_mobile_useragent(agent)
4548 # Returns 1 if some user agent looks like a cellphone or other mobile device,
4550 sub is_mobile_useragent
4552 local ($agent) = @_;
4554 "UP.Link", # Openwave
4555 "Nokia", # All Nokias start with Nokia
4556 "MOT-", # All Motorola phones start with MOT-
4557 "SAMSUNG", # Samsung browsers
4558 "Samsung", # Samsung browsers
4559 "SEC-", # Samsung browsers
4560 "AU-MIC", # Samsung browsers
4561 "AUDIOVOX", # Audiovox
4562 "BlackBerry", # BlackBerry
4563 "hiptop", # Danger hiptop Sidekick
4564 "SonyEricsson", # Sony Ericsson
4565 "Ericsson", # Old Ericsson browsers , mostly WAP
4566 "Mitsu/1.1.A", # Mitsubishi phones
4567 "Panasonic WAP", # Panasonic old WAP phones
4568 "DoCoMo", # DoCoMo phones
4569 "Lynx", # Lynx text-mode linux browser
4570 "Links", # Another text-mode linux browser
4572 local @substrings = (
4573 "UP.Browser", # Openwave
4574 "MobilePhone", # NetFront
4575 "AU-MIC-A700", # Samsung A700 Obigo browsers
4576 "Danger hiptop", # Danger Sidekick hiptop
4577 "Windows CE", # Windows CE Pocket PC
4578 "IEMobile", # Windows mobile browser
4579 "Blazer", # Palm Treo Blazer
4580 "BlackBerry", # BlackBerries can emulate other browsers, but
4581 # they still keep this string in the UserAgent
4582 "SymbianOS", # New Series60 browser has safari in it and
4583 # SymbianOS is the only distinguishing string
4584 "iPhone", # Apple iPhone KHTML browser
4585 "iPod", # iPod touch browser
4586 "MobileSafari", # HTTP client in iPhone
4588 "Opera Mini", # Opera Mini
4589 "HTC_P3700", # HTC mobile device
4591 "webOS/", # Palm WebOS
4593 foreach my $p (@prefixes) {
4594 return 1 if ($agent =~ /^\Q$p\E/);
4596 foreach my $s (@substrings, @mobile_agents) {
4597 return 1 if ($agent =~ /\Q$s\E/);
4602 # write_blocked_file()
4603 # Writes out a text file of blocked hosts and users
4604 sub write_blocked_file
4606 open(BLOCKED, ">$config{'blockedfile'}");
4607 foreach my $d (grep { $hostfail{$_} } @deny) {
4608 print BLOCKED "host $d $hostfail{$d} $blockhosttime{$d}\n";
4610 foreach my $d (grep { $userfail{$_} } @denyusers) {
4611 print BLOCKED "user $d $userfail{$d} $blockusertime{$d}\n";
4614 chmod(0700, $config{'blockedfile'});
4619 open(PIDFILE, ">$config{'pidfile'}");
4620 printf PIDFILE "%d\n", getpid();
4624 # lock_user_password(user)
4625 # Updates a user's password file entry to lock it, both in memory and on disk.
4626 # Returns 1 if done, -1 if no such user, 0 if already locked
4627 sub lock_user_password
4630 if ($users{$user}) {
4631 if ($users{$user} !~ /^\!/) {
4633 $users{$user} = "!".$users{$user};
4634 open(USERS, $config{'userfile'});
4635 local @ufile = <USERS>;
4637 foreach my $u (@ufile) {
4638 local @uinfo = split(/:/, $u);
4639 if ($uinfo[0] eq $user) {
4640 $uinfo[1] = $users{$user};
4642 $u = join(":", @uinfo);
4644 open(USERS, ">$config{'userfile'}");
4654 # hash_session_id(sid)
4655 # Returns an MD5 or Unix-crypted session ID
4659 if (!$hash_session_id_cache{$sid}) {
4662 $hash_session_id_cache{$sid} = &encrypt_md5($sid);
4666 $hash_session_id_cache{$sid} = &unix_crypt($sid, "XX");
4669 return $hash_session_id_cache{$sid};
4672 # encrypt_md5(string, [salt])
4673 # Returns a string encrypted in MD5 format
4676 local ($passwd, $salt) = @_;
4677 local $magic = '$1$';
4678 if ($salt =~ /^\$1\$([^\$]+)/) {
4679 # Extract actual salt from already encrypted password
4684 local $ctx = eval "new $use_md5";
4691 # Add some more stuff from the hash of the password and salt
4692 local $ctx1 = eval "new $use_md5";
4693 $ctx1->add($passwd);
4697 $ctx1->add($passwd);
4698 local $final = $ctx1->digest();
4699 for($pl=length($passwd); $pl>0; $pl-=16) {
4700 $ctx->add($pl > 16 ? $final : substr($final, 0, $pl));
4703 # This piece of code seems rather pointless, but it's in the C code that
4704 # does MD5 in PAM so it has to go in!
4707 for($i=length($passwd); $i; $i >>= 1) {
4712 $ctx->add(substr($passwd, $j, 1));
4715 $final = $ctx->digest();
4718 # This loop exists only to waste time
4719 for($i=0; $i<1000; $i++) {
4720 $ctx1 = eval "new $use_md5";
4721 $ctx1->add($i & 1 ? $passwd : $final);
4722 $ctx1->add($salt) if ($i % 3);
4723 $ctx1->add($passwd) if ($i % 7);
4724 $ctx1->add($i & 1 ? $final : $passwd);
4725 $final = $ctx1->digest();
4729 # Convert the 16-byte final string into a readable form
4731 local @final = map { ord($_) } split(//, $final);
4732 $l = ($final[ 0]<<16) + ($final[ 6]<<8) + $final[12];
4733 $rv .= &to64($l, 4);
4734 $l = ($final[ 1]<<16) + ($final[ 7]<<8) + $final[13];
4735 $rv .= &to64($l, 4);
4736 $l = ($final[ 2]<<16) + ($final[ 8]<<8) + $final[14];
4737 $rv .= &to64($l, 4);
4738 $l = ($final[ 3]<<16) + ($final[ 9]<<8) + $final[15];
4739 $rv .= &to64($l, 4);
4740 $l = ($final[ 4]<<16) + ($final[10]<<8) + $final[ 5];
4741 $rv .= &to64($l, 4);
4743 $rv .= &to64($l, 2);
4745 # Add salt if needed
4747 return $magic.$salt.'$'.$rv;
4756 local ($v, $n) = @_;
4759 $r .= $itoa64[$v & 0x3f];