2 # A very simple perl web server used by Webmin
4 # Require basic libraries
9 eval "use Time::HiRes;";
11 @itoa64 = split(//, "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
13 # Find and read config file
15 die "Usage: miniserv.pl <config file>";
17 if ($ARGV[0] =~ /^([a-z]:)?\//i) {
18 $config_file = $ARGV[0];
22 $config_file = "$pwd/$ARGV[0]";
24 %config = &read_config_file($config_file);
25 if ($config{'perllib'}) {
26 push(@INC, split(/:/, $config{'perllib'}));
27 $ENV{'PERLLIB'} .= ':'.$config{'perllib'};
31 # Check if SSL is enabled and available
33 eval "use Net::SSLeay";
36 # These functions only exist for SSLeay 1.0
37 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
38 eval "Net::SSLeay::load_error_strings()";
39 if ($config{'no_ssl2'}) {
40 eval "Net::SSLeay::CTX_set_options($ctx,&Net::SSLeay::OP_NO_SSLv2)";
42 if (defined(&Net::SSLeay::X509_STORE_CTX_get_current_cert) &&
43 defined(&Net::SSLeay::CTX_load_verify_locations) &&
44 defined(&Net::SSLeay::CTX_set_verify)) {
50 # Check if IPv6 is enabled and available
51 if ($config{'ipv6'}) {
54 push(@startup_msg, "IPv6 support enabled");
58 push(@startup_msg, "IPv6 support cannot be enabled without ".
59 "the Socket6 perl module");
63 # Check if the syslog module is available to log hacking attempts
64 if ($config{'syslog'} && !$config{'inetd'}) {
65 eval "use Sys::Syslog qw(:DEFAULT setlogsock)";
71 # check if the TCP-wrappers module is available
72 if ($config{'libwrap'}) {
73 eval "use Authen::Libwrap qw(hosts_ctl STRING_UNKNOWN)";
79 # Check if the MD5 perl module is available
85 eval "use Digest::MD5";
87 $use_md5 = "Digest::MD5";
91 # Get miniserv's perl path and location
93 open(SOURCE, $miniserv_path);
94 <SOURCE> =~ /^#!(\S+)/;
101 $linked_perl_path = readlink($perl_path);
103 @miniserv_argv = @ARGV;
105 # Check vital config options
106 &update_vital_config();
108 $sidname = $config{'sidname'};
109 die "Session authentication cannot be used in inetd mode"
110 if ($config{'inetd'} && $config{'session'});
112 # check if the PAM module is available to authenticate
113 if ($config{'assume_pam'}) {
114 # Just assume that it will work. This can also be used to work around
115 # a Solaris bug in which using PAM before forking caused it to fail
119 elsif (!$config{'no_pam'}) {
120 eval "use Authen::PAM;";
122 # check if the PAM authentication can be used by opening a
125 if (ref($pamh = new Authen::PAM($config{'pam'},
126 $config{'pam_test_user'},
128 # Now test a login to see if /etc/pam.d/webmin is set
130 $pam_conv_func_called = 0;
131 $pam_username = "test";
132 $pam_password = "test";
133 $pamh->pam_authenticate();
134 if ($pam_conv_func_called) {
136 "PAM authentication enabled");
141 "PAM test failed - maybe ".
142 "/etc/pam.d/$config{'pam'} does not exist");
147 "PAM initialization of Authen::PAM failed");
152 "Perl module Authen::PAM needed for PAM is ".
153 "not installed : $@");
156 if ($config{'pam_only'} && !$use_pam) {
157 print STDERR $startup_msg[0],"\n";
158 print STDERR "PAM use is mandatory, but could not be enabled!\n";
161 elsif ($pam_msg && !$use_pam) {
163 "Continuing without the Authen::PAM perl module");
166 # Check if the User::Utmp perl module is installed
167 if ($config{'utmp'}) {
168 eval "use User::Utmp;";
171 push(@startup_msg, "UTMP logging enabled");
175 "Perl module User::Utmp needed for Utmp logging is ".
176 "not installed : $@");
180 # See if the crypt function fails
181 eval "crypt('foo', 'xx')";
183 eval "use Crypt::UnixCrypt";
187 "Using Crypt::UnixCrypt for password encryption");
191 "crypt() function un-implemented, and Crypt::UnixCrypt ".
192 "not installed - password authentication will fail");
196 # Check if /dev/urandom really generates random IDs, by calling it twice
197 local $rand1 = &generate_random_id("foo", 1);
198 local $rand2 = &generate_random_id("foo", 2);
199 if ($rand1 eq $rand2) {
202 "Random number generator file /dev/urandom is not reliable");
205 # Check if we can call sudo
206 if ($config{'sudo'} && &has_command("sudo")) {
213 "Perl module IO::Pty needed for calling sudo is not ".
218 # init days and months for http_date
219 @weekday = ( "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" );
220 @month = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun",
221 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" );
223 # Change dir to the server root
224 @roots = ( $config{'root'} );
225 for($i=0; defined($config{"extraroot_$i"}); $i++) {
226 push(@roots, $config{"extraroot_$i"});
229 eval { $user_homedir = (getpwuid($<))[7]; };
231 # getpwuid doesn't work on windows
232 $user_homedir = $ENV{"HOME"} || $ENV{"USERPROFILE"} || "/";
239 # Setup SSL if possible and if requested
240 if (!-r $config{'keyfile'}) {
241 # Key file doesn't exist!
242 if ($config{'keyfile'}) {
243 print STDERR "SSL key file $config{'keyfile'} does not exist\n";
247 elsif ($config{'certfile'} && !-r $config{'certfile'}) {
248 # Cert file doesn't exist!
249 print STDERR "SSL cert file $config{'certfile'} does not exist\n";
252 @ipkeys = &get_ipkeys(\%config);
254 if ($config{'ssl_version'}) {
255 # Force an SSL version
256 $Net::SSLeay::version = $config{'ssl_version'};
257 $Net::SSLeay::ssl_version = $config{'ssl_version'};
259 $client_certs = 0 if (!-r $config{'ca'} || !%certs);
260 $ssl_contexts{"*"} = &create_ssl_context($config{'keyfile'},
261 $config{'certfile'});
262 foreach $ipkey (@ipkeys) {
263 $ctx = &create_ssl_context($ipkey->{'key'}, $ipkey->{'cert'});
264 foreach $ip (@{$ipkey->{'ips'}}) {
265 $ssl_contexts{$ip} = $ctx;
270 # Setup syslog support if possible and if requested
272 open(ERRDUP, ">&STDERR");
273 open(STDERR, ">/dev/null");
274 $log_socket = $config{"logsock"} || "unix";
275 eval 'openlog($config{"pam"}, "cons,pid,ndelay", "authpriv"); setlogsock($log_socket)';
280 local $msg = ucfirst($config{'pam'})." starting";
281 eval { syslog("info", "%s", $msg); };
285 syslog("info", "%s", $msg);
288 # All attempts to use syslog have failed..
293 open(STDERR, ">&ERRDUP");
297 # Read MIME types file and add extra types
301 if ($config{'log'}) {
302 local(@gmt, @lct, $days, $hours, $mins);
303 @gmt = gmtime(time());
304 @lct = localtime(time());
305 $days = $lct[3] - $gmt[3];
306 $hours = ($days < -1 ? 24 : 1 < $days ? -24 : $days * 24) +
308 $mins = $hours * 60 + $lct[1] - $gmt[1];
309 $timezone = ($mins < 0 ? "-" : "+"); $mins = abs($mins);
310 $timezone .= sprintf "%2.2d%2.2d", $mins/60, $mins%60;
313 # Build various maps from the config files
314 &build_config_mappings();
316 # start up external authentication program, if needed
317 if ($config{'extauth'}) {
318 socketpair(EXTAUTH, EXTAUTH2, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
319 if (!($extauth = fork())) {
323 open(STDIN, "<&EXTAUTH2");
324 open(STDOUT, ">&EXTAUTH2");
325 exec($config{'extauth'}) or die "exec failed : $!\n";
328 local $os = select(EXTAUTH);
332 # Pre-load any libraries
333 if (!$config{'inetd'}) {
334 foreach $pl (split(/\s+/, $config{'preload'})) {
335 ($pkg, $lib) = split(/=/, $pl);
336 $pkg =~ s/[^A-Za-z0-9]/_/g;
337 eval "package $pkg; do '$config{'root'}/$lib'";
339 print STDERR "Failed to pre-load $lib in $pkg : $@\n";
342 print STDERR "Pre-loaded $lib in $pkg\n";
345 foreach $pl (split(/\s+/, $config{'premodules'})) {
347 ($dir, $mod) = split(/\//, $pl);
350 ($dir, $mod) = (undef, $pl);
352 push(@INC, "$config{'root'}/$dir");
353 eval "package $mod; use $mod ()";
355 print STDERR "Failed to pre-load $mod : $@\n";
358 print STDERR "Pre-loaded $mod\n";
363 # Open debug log if set
364 if ($config{'debuglog'}) {
365 open(DEBUG, ">>$config{'debuglog'}");
366 chmod(0700, $config{'debuglog'});
367 select(DEBUG); $| = 1; select(STDOUT);
368 print DEBUG "miniserv.pl starting ..\n";
371 # Write out (empty) blocked hosts file
372 &write_blocked_file();
374 # Initially read webmin cron functions and last execution times
375 &read_webmin_crons();
376 %webmincron_last = ( );
377 &read_file($config{'webmincron_last'}, \%webmincron_last);
379 # Pre-cache lang files
382 if ($config{'inetd'}) {
383 # We are being run from inetd - go direct to handling the request
384 &redirect_stderr_to_log();
385 $SIG{'HUP'} = 'IGNORE';
386 $SIG{'TERM'} = 'DEFAULT';
387 $SIG{'PIPE'} = 'DEFAULT';
388 open(SOCK, "+>&STDIN");
390 # Check if it is time for the logfile to be cleared
391 if ($config{'logclear'}) {
392 local $write_logtime = 0;
393 local @st = stat("$config{'logfile'}.time");
395 if ($st[9]+$config{'logtime'}*60*60 < time()){
398 unlink($config{'logfile'});
401 else { $write_logtime = 1; }
402 if ($write_logtime) {
403 open(LOGTIME, ">$config{'logfile'}.time");
404 print LOGTIME time(),"\n";
409 # Initialize SSL for this connection
411 $ssl_con = &ssl_connection_for_ip(SOCK, 0);
415 # Work out the hostname for this web server
416 $host = &get_socket_name(SOCK, 0);
418 $port = $config{'port'};
419 $acptaddr = getpeername(SOCK);
422 # Work out remote and local IPs
423 (undef, $peera, undef) = &get_address_ip($acptaddr, 0);
424 (undef, $locala) = &get_socket_ip(SOCK, 0);
426 print DEBUG "main: Starting handle_request loop pid=$$\n";
427 while(&handle_request($peera, $locala, 0)) { }
428 print DEBUG "main: Done handle_request loop pid=$$\n";
433 # Build list of sockets to listen on
434 $config{'bind'} = '' if ($config{'bind'} eq '*');
435 if ($config{'bind'}) {
436 # Listening on a specific IP
437 if (&check_ip6address($config{'bind'})) {
439 $use_ipv6 || die "Cannot bind to $config{'bind'} without IPv6";
440 push(@sockets, [ inet_pton(Socket6::AF_INET6(),$config{'bind'}),
442 Socket6::PF_INET6() ]);
446 push(@sockets, [ inet_aton($config{'bind'}),
452 # Listening on all IPs
453 push(@sockets, [ INADDR_ANY, $config{'port'}, PF_INET() ]);
456 push(@sockets, [ in6addr_any(), $config{'port'},
457 Socket6::PF_INET6() ]);
460 foreach $s (split(/\s+/, $config{'sockets'})) {
461 if ($s =~ /^(\d+)$/) {
462 # Just listen on another port on the main IP
463 push(@sockets, [ $sockets[0]->[0], $s, $sockets[0]->[2] ]);
464 if ($use_ipv6 && !$config{'bind'}) {
465 # Also listen on that port on the main IPv6 address
466 push(@sockets, [ $sockets[1]->[0], $s,
470 elsif ($s =~ /^\*:(\d+)$/) {
471 # Listening on all IPs on some port
472 push(@sockets, [ INADDR_ANY, $1,
475 push(@sockets, [ in6addr_any(), $1,
476 Socket6::PF_INET6() ]);
479 elsif ($s =~ /^(\S+):(\d+)$/) {
480 # Listen on a specific port and IP
481 my ($ip, $port) = ($1, $2);
482 if (&check_ip6address($ip)) {
483 $use_ipv6 || die "Cannot bind to $ip without IPv6";
484 push(@sockets, [ inet_pton(Socket6::AF_INET6(),
486 $port, Socket6::PF_INET6() ]);
489 push(@sockets, [ inet_aton($ip), $port,
493 elsif ($s =~ /^([0-9\.]+):\*$/ || $s =~ /^([0-9\.]+)$/) {
494 # Listen on the main port on another IPv4 address
495 push(@sockets, [ inet_aton($1), $sockets[0]->[1],
498 elsif (($s =~ /^([0-9a-f\:]+):\*$/ || $s =~ /^([0-9a-f\:]+)$/) &&
500 # Listen on the main port on another IPv6 address
501 push(@sockets, [ inet_pton(Socket6::AF_INET6(), $1),
503 Socket6::PF_INET6() ]);
507 # Open all the sockets
508 $proto = getprotobyname('tcp');
510 $tried_inaddr_any = 0;
511 for($i=0; $i<@sockets; $i++) {
513 socket($fh, $sockets[$i]->[2], SOCK_STREAM, $proto) ||
514 die "Failed to open socket family $sockets[$i]->[2] : $!";
515 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
516 if ($sockets[$i]->[2] eq PF_INET()) {
517 $pack = pack_sockaddr_in($sockets[$i]->[1], $sockets[$i]->[0]);
520 $pack = pack_sockaddr_in6($sockets[$i]->[1], $sockets[$i]->[0]);
521 setsockopt($fh, 41, 26, pack("l", 1)); # IPv6 only
523 for($j=0; $j<5; $j++) {
524 last if (bind($fh, $pack));
528 # All attempts failed .. give up
529 if ($sockets[$i]->[0] eq INADDR_ANY ||
530 $use_ipv6 && $sockets[$i]->[0] eq in6addr_any()) {
532 "Failed to bind to port $sockets[$i]->[1] : $!");
533 $tried_inaddr_any = 1;
536 $ip = &network_to_address($sockets[$i]->[0]);
538 "Failed to bind to IP $ip port ".
539 "$sockets[$i]->[1] : $!");
543 listen($fh, SOMAXCONN);
544 push(@socketfhs, $fh);
545 $ipv6fhs{$fh} = $sockets[$i]->[2] eq PF_INET() ? 0 : 1;
548 foreach $se (@sockerrs) {
549 print STDERR $se,"\n";
552 # If all binds failed, try binding to any address
553 if (!@socketfhs && !$tried_inaddr_any) {
554 print STDERR "Falling back to listening on any address\n";
556 socket($fh, PF_INET(), SOCK_STREAM, $proto) ||
557 die "Failed to open socket : $!";
558 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
559 if (!bind($fh, pack_sockaddr_in($sockets[0]->[1], INADDR_ANY))) {
560 print STDERR "Failed to bind to port $sockets[0]->[1] : $!\n";
563 listen($fh, SOMAXCONN);
564 push(@socketfhs, $fh);
566 elsif (!@socketfhs && $tried_inaddr_any) {
567 print STDERR "Could not listen on any ports";
571 if ($config{'listen'}) {
572 # Open the socket that allows other webmin servers to find this one
573 $proto = getprotobyname('udp');
574 if (socket(LISTEN, PF_INET(), SOCK_DGRAM, $proto)) {
575 setsockopt(LISTEN, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
576 bind(LISTEN, pack_sockaddr_in($config{'listen'}, INADDR_ANY));
577 listen(LISTEN, SOMAXCONN);
580 $config{'listen'} = 0;
584 # Split from the controlling terminal, unless configured not to
585 if (!$config{'nofork'}) {
586 if (fork()) { exit; }
588 eval { setsid(); }; # may not work on Windows
590 # Close standard file handles
591 open(STDIN, "</dev/null");
592 open(STDOUT, ">/dev/null");
593 &redirect_stderr_to_log();
594 &log_error("miniserv.pl started");
595 foreach $msg (@startup_msg) {
599 # write out the PID file
602 # Start the log-clearing process, if needed. This checks every minute
603 # to see if the log has passed its reset time, and if so clears it
604 if ($config{'logclear'}) {
605 if (!($logclearer = fork())) {
606 &close_all_sockets();
609 local $write_logtime = 0;
610 local @st = stat("$config{'logfile'}.time");
612 if ($st[9]+$config{'logtime'}*60*60 < time()){
615 unlink($config{'logfile'});
618 else { $write_logtime = 1; }
619 if ($write_logtime) {
620 open(LOGTIME, ">$config{'logfile'}.time");
621 print LOGTIME time(),"\n";
628 push(@childpids, $logclearer);
631 # Setup the logout time dbm if needed
632 if ($config{'session'}) {
633 eval "use SDBM_File";
634 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
635 eval "\$sessiondb{'1111111111'} = 'foo bar';";
637 dbmclose(%sessiondb);
638 eval "use NDBM_File";
639 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
642 delete($sessiondb{'1111111111'});
647 $SIG{'HUP'} = 'miniserv::trigger_restart';
648 $SIG{'TERM'} = 'miniserv::term_handler';
649 $SIG{'USR1'} = 'miniserv::trigger_reload';
650 $SIG{'PIPE'} = 'IGNORE';
651 local $remove_session_count = 0;
652 $need_pipes = $config{'passdelay'} || $config{'session'};
654 # wait for a new connection, or a message from a child process
656 if (@childpids <= $config{'maxconns'}) {
657 # Only accept new main socket connects when ready
659 foreach $s (@socketfhs) {
660 vec($rmask, fileno($s), 1) = 1;
664 printf STDERR "too many children (%d > %d)\n",
665 scalar(@childpids), $config{'maxconns'};
668 for($i=0; $i<@passin; $i++) {
669 vec($rmask, fileno($passin[$i]), 1) = 1;
672 vec($rmask, fileno(LISTEN), 1) = 1 if ($config{'listen'});
674 # Wait for a connection
675 local $sel = select($rmask, undef, undef, 10);
677 # Check the flag files
678 if ($config{'restartflag'} && -r $config{'restartflag'}) {
679 print STDERR "restart flag file detected\n";
680 unlink($config{'restartflag'});
683 if ($config{'reloadflag'} && -r $config{'reloadflag'}) {
684 unlink($config{'reloadflag'});
689 # Got a HUP signal while in select() .. restart now
693 # Got a USR1 signal while in select() .. re-read config
695 &reload_config_file();
697 local $time_now = time();
699 # Clean up finished processes
701 do { $pid = waitpid(-1, WNOHANG);
702 @childpids = grep { $_ != $pid } @childpids;
703 } while($pid != 0 && $pid != -1);
705 # run the unblocking procedure to check if enough time has passed to
706 # unblock hosts that heve been blocked because of password failures
708 if ($config{'blockhost_failures'}) {
710 while ($i <= $#deny) {
711 if ($blockhosttime{$deny[$i]} &&
712 $config{'blockhost_time'} != 0 &&
713 ($time_now - $blockhosttime{$deny[$i]}) >=
714 $config{'blockhost_time'}) {
715 # the host can be unblocked now
716 $hostfail{$deny[$i]} = 0;
717 splice(@deny, $i, 1);
724 # Do the same for blocked users
725 if ($config{'blockuser_failures'}) {
727 while ($i <= $#deny) {
728 if ($blockusertime{$deny[$i]} &&
729 $config{'blockuser_time'} != 0 &&
730 ($time_now - $blockusertime{$deny[$i]}) >=
731 $config{'blockuser_time'}) {
732 # the user can be unblocked now
733 $userfail{$deny[$i]} = 0;
734 splice(@denyusers, $i, 1);
741 &write_blocked_file();
744 # Check if any webmin cron jobs are ready to run
745 &execute_ready_webmin_crons();
747 if ($config{'session'} && (++$remove_session_count%50) == 0) {
748 # Remove sessions with more than 7 days of inactivity,
750 foreach $s (keys %sessiondb) {
751 local ($user, $ltime, $lip) =
752 split(/\s+/, $sessiondb{$s});
753 if ($time_now - $ltime > 7*24*60*60) {
754 &run_logout_script($s, $user);
755 &write_logout_utmp($user, $lip);
756 delete($sessiondb{$s});
759 "Timeout of session for $user");
765 if ($use_pam && $config{'pam_conv'}) {
766 # Remove PAM sessions with more than 5 minutes of inactivity
768 foreach $c (values %conversations) {
769 if ($time_now - $c->{'time'} > 5*60) {
770 &end_pam_conversation($c);
772 syslog("info", "%s", "Timeout of PAM ".
773 "session for $c->{'user'}");
779 # Don't check any sockets if there is no activity
782 # Check if any of the main sockets have received a new connection
784 foreach $s (@socketfhs) {
785 if (vec($rmask, fileno($s), 1)) {
787 $acptaddr = accept(SOCK, $s);
788 if (!$acptaddr) { next; }
789 binmode(SOCK); # turn off any Perl IO stuff
792 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
794 ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw) =
798 # Work out IP and port of client
799 local ($peerb, $peera, $peerp) =
800 &get_address_ip($acptaddr, $ipv6fhs{$s});
802 # Work out the local IP
803 (undef, $locala) = &get_socket_ip(SOCK, $ipv6fhs{$s});
805 # Check username of connecting user
806 $localauth_user = undef;
807 if ($config{'localauth'} && $peera eq "127.0.0.1") {
808 if (open(TCP, "/proc/net/tcp")) {
809 # Get the info direct from the kernel
810 $peerh = sprintf("%4.4X", $peerp);
813 local @t = split(/[\s:]+/, $_);
814 if ($t[1] eq '0100007F' &&
823 if (!$localauth_user) {
824 # Call lsof for the info
825 local $lsofpid = open(LSOF,
826 "$config{'localauth'} -i ".
827 "TCP\@127.0.0.1:$peerp |");
829 if (/^(\S+)\s+(\d+)\s+(\S+)/ &&
830 $2 != $$ && $2 != $lsofpid){
831 $localauth_user = $3;
838 # Work out the hostname for this web server
839 $host = &get_socket_name(SOCK, $ipv6fhs{$s});
842 "Failed to get local socket name : $!\n";
846 $port = $sockets[$sn]->[1];
848 # fork the subprocess
850 if (!($handpid = fork())) {
851 # setup signal handlers
852 $SIG{'TERM'} = 'DEFAULT';
853 $SIG{'PIPE'} = 'DEFAULT';
854 #$SIG{'CHLD'} = 'IGNORE';
855 $SIG{'HUP'} = 'IGNORE';
856 $SIG{'USR1'} = 'IGNORE';
858 # Initialize SSL for this connection
860 $ssl_con = &ssl_connection_for_ip(
865 # Close the file handle for the session DBM
866 dbmclose(%sessiondb);
868 # close useless pipes
871 close($PASSINr); close($PASSOUTw);
873 &close_all_sockets();
877 "main: Starting handle_request loop pid=$$\n";
878 while(&handle_request($peera, $locala,
880 # Loop until keepalive stops
883 "main: Done handle_request loop pid=$$\n";
886 close($PASSINw); close($PASSOUTw);
889 push(@childpids, $handpid);
891 close($PASSINw); close($PASSOUTr);
892 push(@passin, $PASSINr);
893 push(@passout, $PASSOUTw);
900 if ($config{'listen'} && vec($rmask, fileno(LISTEN), 1)) {
901 # Got UDP packet from another webmin server
903 local $from = recv(LISTEN, $rcvbuf, 1024, 0);
905 local $fromip = inet_ntoa((unpack_sockaddr_in($from))[1]);
906 local $toip = inet_ntoa((unpack_sockaddr_in(
907 getsockname(LISTEN)))[1]);
908 if ((!@deny || !&ip_match($fromip, $toip, @deny)) &&
909 (!@allow || &ip_match($fromip, $toip, @allow))) {
910 local $listenhost = &get_socket_name(LISTEN, 0);
911 send(LISTEN, "$listenhost:$config{'port'}:".
912 ($use_ssl || $config{'inetd_ssl'} ? 1 : 0).":".
913 ($config{'listenhost'} ?
914 &get_system_hostname() : ""),
920 # check for session, password-timeout and PAM messages from subprocesses
921 for($i=0; $i<@passin; $i++) {
922 if (vec($rmask, fileno($passin[$i]), 1)) {
923 # this sub-process is asking about a password
924 local $infd = $passin[$i];
925 local $outfd = $passout[$i];
926 #local $inline = <$infd>;
927 local $inline = &sysread_line($infd);
929 print DEBUG "main: inline $inline";
932 print DEBUG "main: inline EOF\n";
934 if ($inline =~ /^delay\s+(\S+)\s+(\S+)\s+(\d+)/) {
935 # Got a delay request from a subprocess.. for
936 # valid logins, there is no delay (to prevent
937 # denial of service attacks), but for invalid
938 # logins the delay increases with each failed
941 # login OK.. no delay
942 print $outfd "0 0\n";
943 $wasblocked = $hostfail{$2} ||
948 &write_blocked_file();
957 # add the host to the block list,
959 if ($config{'blockhost_failures'} &&
961 $config{'blockhost_failures'}) {
963 $blockhosttime{$2} = $time_now;
966 local $logtext = "Security alert: Host $2 blocked after $config{'blockhost_failures'} failed logins for user $1";
972 # add the user to the user block list,
974 if ($config{'blockuser_failures'} &&
976 $config{'blockuser_failures'}) {
977 push(@denyusers, $1);
978 $blockusertime{$1} = $time_now;
981 local $logtext = "Security alert: User $1 blocked after $config{'blockuser_failures'} failed logins";
987 # Lock out the user's password, if enabled
988 if ($config{'blocklock'} &&
990 $config{'blockuser_failures'}) {
991 my $lk = &lock_user_password($1);
994 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";
1001 $dl = $userdlay{$1} -
1002 int(($time_now - $userlast{$1})/50);
1003 $dl = $dl < 0 ? 0 : $dl+1;
1004 print $outfd "$dl $blocked\n";
1005 $userdlay{$1} = $dl;
1007 # Write out blocked status file
1009 &write_blocked_file();
1012 $userlast{$1} = $time_now;
1014 elsif ($inline =~ /^verify\s+(\S+)\s+(\S+)/) {
1015 # Verifying a session ID
1016 local $session_id = $1;
1017 local $notimeout = $2;
1018 local $skey = $sessiondb{$session_id} ?
1020 &hash_session_id($session_id);
1021 if (!defined($sessiondb{$skey})) {
1022 # Session doesn't exist
1023 print $outfd "0 0\n";
1026 local ($user, $ltime) =
1027 split(/\s+/, $sessiondb{$skey});
1028 local $lot = &get_logout_time($user, $session_id);
1030 $time_now - $ltime > $lot*60 &&
1032 # Session has timed out
1033 print $outfd "1 ",$time_now - $ltime,"\n";
1034 #delete($sessiondb{$skey});
1038 print $outfd "2 $user\n";
1040 $time_now - $ltime >
1042 $sessiondb{$skey} = "$user $time_now";
1047 elsif ($inline =~ /^new\s+(\S+)\s+(\S+)\s+(\S+)/) {
1048 # Creating a new session
1049 local $session_id = $1;
1052 $sessiondb{&hash_session_id($session_id)} =
1053 "$user $time_now $ip";
1055 elsif ($inline =~ /^delete\s+(\S+)/) {
1056 # Logging out a session
1057 local $session_id = $1;
1058 local $skey = $sessiondb{$session_id} ?
1060 &hash_session_id($session_id);
1061 local @sdb = split(/\s+/, $sessiondb{$skey});
1062 print $outfd $sdb[0],"\n";
1063 delete($sessiondb{$skey});
1065 elsif ($inline =~ /^pamstart\s+(\S+)\s+(\S+)\s+(.*)/) {
1066 # Starting a new PAM conversation
1067 local ($cid, $host, $user) = ($1, $2, $3);
1069 # Does this user even need PAM?
1070 local ($realuser, $canlogin) =
1071 &can_user_login($user, undef, $host);
1073 if ($canlogin == 0) {
1074 # Cannot even login!
1075 print $outfd "0 Invalid username\n";
1077 elsif ($canlogin != 2) {
1078 # Not using PAM .. so just ask for
1080 $conv = { 'user' => $realuser,
1085 print $outfd "3 Password\n";
1088 # Start the PAM conversation
1089 # sub-process, and get a question
1090 $conv = { 'user' => $realuser,
1094 local ($PAMINr, $PAMINw, $PAMOUTr,
1095 $PAMOUTw) = &allocate_pipes();
1096 local $pampid = fork();
1098 close($PAMOUTr); close($PAMINw);
1099 &pam_conversation_process(
1103 close($PAMOUTw); close($PAMINr);
1104 $conv->{'pid'} = $pampid;
1105 $conv->{'PAMOUTr'} = $PAMOUTr;
1106 $conv->{'PAMINw'} = $PAMINw;
1107 push(@childpids, $pampid);
1109 # Get the first PAM question
1110 local $pok = &recv_pam_question(
1113 &end_pam_conversation($conv);
1117 $conversations{$cid} = $conv if ($conv);
1119 elsif ($inline =~ /^pamanswer\s+(\S+)\s+(.*)/) {
1120 # A response to a PAM question
1121 local ($cid, $answer) = ($1, $2);
1122 local $conv = $conversations{$cid};
1124 # No such conversation?
1125 print $outfd "0 Bad login session\n";
1127 elsif ($conv->{'pid'}) {
1128 # Send the PAM response and get
1130 &send_pam_answer($conv, $answer);
1131 local $pok = &recv_pam_question($conv, $outfd);
1133 &end_pam_conversation($conv);
1137 # This must be the password .. try it
1138 # and send back the results
1139 local ($vu, $expired, $nonexist) =
1140 &validate_user($conv->{'user'},
1143 local $ok = $vu ? 1 : 0;
1144 print $outfd "2 $conv->{'user'} $ok $expired $notexist\n";
1145 &end_pam_conversation($conv);
1148 elsif ($inline =~ /^writesudo\s+(\S+)\s+(\d+)/) {
1149 # Store the fact that some user can sudo to root
1150 local ($user, $ok) = ($1, $2);
1151 $sudocache{$user} = $ok." ".time();
1153 elsif ($inline =~ /^readsudo\s+(\S+)/) {
1154 # Query the user sudo cache (valid for 1 minute)
1156 local ($ok, $last) =
1157 split(/\s+/, $sudocache{$user});
1158 if ($last < time()-60) {
1163 # Tell client OK or not
1164 print $outfd "$ok\n";
1167 elsif ($inline =~ /\S/) {
1168 # Unknown line from pipe?
1169 print DEBUG "main: Unknown line from pipe $inline\n";
1170 print STDERR "Unknown line from pipe $inline\n";
1174 close($infd); close($outfd);
1175 $passin[$i] = $passout[$i] = undef;
1179 @passin = grep { defined($_) } @passin;
1180 @passout = grep { defined($_) } @passout;
1183 # handle_request(remoteaddress, localaddress, ipv6-flag)
1184 # Where the real work is done
1187 local ($acptip, $localip, $ipv6) = @_;
1188 print DEBUG "handle_request: from $acptip to $localip ipv6=$ipv6\n";
1189 if ($config{'loghost'}) {
1190 $acpthost = &to_hostname($acptip);
1191 $acpthost = $acptip if (!$acpthost);
1194 $acpthost = $acptip;
1196 $datestr = &http_date(time());
1198 $ok_message = "Document follows";
1199 $logged_code = undef;
1200 $reqline = $request_uri = $page = undef;
1204 # check address against access list
1205 if (@deny && &ip_match($acptip, $localip, @deny) ||
1206 @allow && !&ip_match($acptip, $localip, @allow)) {
1207 &http_error(403, "Access denied for $acptip");
1212 # Check address with TCP-wrappers
1213 if (!hosts_ctl($config{'pam'}, STRING_UNKNOWN,
1214 $acptip, STRING_UNKNOWN)) {
1215 &http_error(403, "Access denied for $acptip by TCP wrappers");
1219 print DEBUG "handle_request: passed IP checks\n";
1221 # Compute a timeout for the start of headers, based on the number of
1222 # child processes. As this increases, we use a shorter timeout to avoid
1223 # an attacker overloading the system.
1224 local $header_timeout = 60 + ($config{'maxconns'} - @childpids) * 10;
1226 # Wait at most 60 secs for start of headers for initial requests, or
1227 # 10 minutes for kept-alive connections
1229 vec($rmask, fileno(SOCK), 1) = 1;
1230 local $to = $checked_timeout ? 10*60 : $header_timeout;
1231 local $sel = select($rmask, undef, undef, $to);
1233 if ($checked_timeout) {
1234 print DEBUG "handle_request: exiting due to timeout of $to\n";
1238 &http_error(400, "Timeout",
1239 "Waited for that $to seconds for start of headers");
1243 print DEBUG "handle_request: passed timeout check\n";
1245 # Read the HTTP request and headers
1246 local $origreqline = &read_line();
1247 ($reqline = $origreqline) =~ s/\r|\n//g;
1248 $method = $page = $request_uri = undef;
1249 print DEBUG "handle_request reqline=$reqline\n";
1250 if (!$reqline && (!$use_ssl || $checked_timeout > 1)) {
1251 # An empty request .. just close the connection
1252 print DEBUG "handle_request: rejecting empty request\n";
1255 elsif ($reqline !~ /^(\S+)\s+(.*)\s+HTTP\/1\..$/) {
1256 print DEBUG "handle_request: invalid reqline=$reqline\n";
1258 # This could be an http request when it should be https
1260 local $url = $config{'musthost'} ?
1261 "https://$config{'musthost'}:$port/" :
1262 "https://$host:$port/";
1263 if ($config{'ssl_redirect'}) {
1264 # Just re-direct to the correct URL
1265 sleep(1); # Give browser a change to finish
1266 # sending its request
1267 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1268 &write_data("Date: $datestr\r\n");
1269 &write_data("Server: $config{'server'}\r\n");
1270 &write_data("Location: $url\r\n");
1271 &write_keep_alive(0);
1272 &write_data("\r\n");
1276 # Tell user the correct URL
1277 &http_error(200, "Bad Request", "This web server is running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1280 elsif (ord(substr($reqline, 0, 1)) == 128 && !$use_ssl) {
1281 # This could be an https request when it should be http ..
1282 # need to fake a HTTP response
1285 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
1286 eval "Net::SSLeay::load_error_strings()";
1287 $ssl_ctx = Net::SSLeay::CTX_new();
1288 Net::SSLeay::CTX_use_RSAPrivateKey_file(
1289 $ssl_ctx, $config{'keyfile'},
1290 &Net::SSLeay::FILETYPE_PEM);
1291 Net::SSLeay::CTX_use_certificate_file(
1293 $config{'certfile'} || $config{'keyfile'},
1294 &Net::SSLeay::FILETYPE_PEM);
1295 $ssl_con = Net::SSLeay::new($ssl_ctx);
1299 select(SSLw); $| = 1; select(STDOUT);
1300 print SSLw $origreqline;
1302 while(sysread(SOCK, $buf, 1) > 0) {
1309 Net::SSLeay::set_wfd($ssl_con, fileno(SOCK));
1310 Net::SSLeay::set_rfd($ssl_con, fileno(SSLr));
1311 Net::SSLeay::accept($ssl_con) || die "accept() failed";
1313 local $url = $config{'musthost'} ?
1314 "https://$config{'musthost'}:$port/" :
1315 "https://$host:$port/";
1316 if ($config{'ssl_redirect'}) {
1317 # Just re-direct to the correct URL
1318 sleep(1); # Give browser a change to
1319 # finish sending its request
1320 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1321 &write_data("Date: $datestr\r\n");
1322 &write_data("Server: $config{'server'}\r\n");
1323 &write_data("Location: $url\r\n");
1324 &write_keep_alive(0);
1325 &write_data("\r\n");
1329 # Tell user the correct URL
1330 &http_error(200, "Bad Request", "This web server is not running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1334 &http_error(400, "Bad Request");
1338 &http_error(400, "Bad Request");
1342 $request_uri = $page = $2;
1346 ($headline = &read_line()) =~ s/\r|\n//g;
1347 last if ($headline eq "");
1348 print DEBUG "handle_request: got headline $headline\n";
1349 if ($headline =~ /^(\S+):\s*(.*)$/) {
1350 $header{$lastheader = lc($1)} = $2;
1352 elsif ($headline =~ /^\s+(.*)$/) {
1353 $header{$lastheader} .= $headline;
1356 &http_error(400, "Bad Header $headline");
1359 if (defined($header{'host'})) {
1360 if ($header{'host'} =~ /^([^:]+):([0-9]+)$/) {
1361 ($host, $port) = ($1, $2);
1364 $host = $header{'host'};
1366 if ($config{'musthost'} && $host ne $config{'musthost'}) {
1367 # Disallowed hostname used
1368 &http_error(400, "Invalid HTTP hostname");
1372 if ($page =~ /^([^\?]+)\?(.*)$/) {
1373 # There is some query string information
1376 print DEBUG "handle_request: querystring=$querystring\n";
1377 if ($querystring !~ /=/) {
1378 $queryargs = $querystring;
1379 $queryargs =~ s/\+/ /g;
1380 $queryargs =~ s/%(..)/pack("c",hex($1))/ge;
1384 # Parse query-string parameters
1385 local @in = split(/\&/, $querystring);
1387 local ($k, $v) = split(/=/, $i, 2);
1388 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1389 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1394 $posted_data = undef;
1395 if ($method eq 'POST' &&
1396 $header{'content-type'} eq 'application/x-www-form-urlencoded') {
1397 # Read in posted query string information, up the configured maximum
1398 # post request length
1399 $clen = $header{"content-length"};
1400 $clen_read = $clen > $config{'max_post'} ? $config{'max_post'} : $clen;
1401 while(length($posted_data) < $clen_read) {
1402 $buf = &read_data($clen_read - length($posted_data));
1403 if (!length($buf)) {
1404 &http_error(500, "Failed to read POST request");
1406 chomp($posted_data);
1407 $posted_data =~ s/\015$//mg;
1408 $posted_data .= $buf;
1410 print DEBUG "clen_read=$clen_read clen=$clen posted_data=",length($posted_data),"\n";
1411 if ($clen_read != $clen && length($posted_data) > $clen) {
1412 # If the client sent more data than we asked for, chop the
1414 $posted_data = substr($posted_data, 0, $clen);
1416 if (length($posted_data) > $clen) {
1417 # When the client sent too much, delay so that it gets headers
1420 if ($header{'user-agent'} =~ /MSIE/ &&
1421 $header{'user-agent'} !~ /Opera/i) {
1422 # MSIE includes an extra newline in the data
1423 $posted_data =~ s/\r|\n//g;
1425 local @in = split(/\&/, $posted_data);
1427 local ($k, $v) = split(/=/, $i, 2);
1429 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1430 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1433 print DEBUG "handle_request: posted_data=$posted_data\n";
1436 # work out accepted encodings
1437 %acceptenc = map { $_, 1 } split(/,/, $header{'accept-encoding'});
1439 # replace %XX sequences in page
1440 $page =~ s/%(..)/pack("c",hex($1))/ge;
1442 # Check if the browser's user agent indicates a mobile device
1443 $mobile_device = &is_mobile_useragent($header{'user-agent'});
1445 # Check if Host: header is for a mobile URL
1446 foreach my $m (@mobile_prefixes) {
1447 if ($header{'host'} =~ /^\Q$m\E/i) {
1452 # check for the logout flag file, and if existant deny authentication
1453 if ($config{'logout'} && -r $config{'logout'}.$in{'miniserv_logout_id'}) {
1454 print DEBUG "handle_request: logout flag set\n";
1455 $deny_authentication++;
1456 open(LOGOUT, $config{'logout'}.$in{'miniserv_logout_id'});
1457 chop($count = <LOGOUT>);
1461 open(LOGOUT, ">$config{'logout'}$in{'miniserv_logout_id'}");
1462 print LOGOUT "$count\n";
1466 unlink($config{'logout'}.$in{'miniserv_logout_id'});
1470 # check for any redirect for the requested URL
1471 foreach my $pfx (@strip_prefix) {
1472 my $l = length($pfx);
1473 if(length($page) >= $l &&
1474 substr($page,0,$l) eq $pfx) {
1475 $page=substr($page,$l);
1479 $simple = &simplify_path($page, $bogus);
1481 $rpath .= "&".$querystring if (defined($querystring));
1482 $redir = $redirect{$rpath};
1483 if (defined($redir)) {
1484 print DEBUG "handle_request: redir=$redir\n";
1485 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1486 &write_data("Date: $datestr\r\n");
1487 &write_data("Server: $config{'server'}\r\n");
1488 local $ssl = $use_ssl || $config{'inetd_ssl'};
1489 $portstr = $port == 80 && !$ssl ? "" :
1490 $port == 443 && $ssl ? "" : ":$port";
1491 $prot = $ssl ? "https" : "http";
1492 &write_data("Location: $prot://$host$portstr$redir\r\n");
1493 &write_keep_alive(0);
1494 &write_data("\r\n");
1498 # Check for a DAV request
1500 foreach my $d (@davpaths) {
1501 if ($simple eq $d || $simple =~ /^\Q$d\E\//) {
1506 if (!$davpath && ($method eq "SEARCH" || $method eq "PUT")) {
1507 &http_error(400, "Bad Request method $method");
1510 # Check for password if needed
1511 if ($config{'userfile'}) {
1512 print DEBUG "handle_request: Need authentication\n";
1516 # Session authentication is never used for connections by
1517 # another webmin server, or for specified pages, or for DAV, or XMLRPC,
1518 # or mobile browsers if requested.
1519 if ($header{'user-agent'} =~ /webmin/i ||
1520 $header{'user-agent'} =~ /$config{'agents_nosession'}/i ||
1521 $sessiononly{$simple} || $davpath ||
1522 $simple eq "/xmlrpc.cgi" ||
1523 $acptip eq $config{'host_nosession'} ||
1524 $mobile_device && $config{'mobile_nosession'}) {
1525 print DEBUG "handle_request: Forcing HTTP authentication\n";
1526 $config{'session'} = 0;
1529 # Check for SSL authentication
1530 if ($use_ssl && $verified_client) {
1531 $peername = Net::SSLeay::X509_NAME_oneline(
1532 Net::SSLeay::X509_get_subject_name(
1533 Net::SSLeay::get_peer_certificate(
1535 $u = &find_user_by_cert($peername);
1540 if ($use_syslog && !$validated) {
1541 syslog("crit", "%s",
1542 "Unknown SSL certificate $peername");
1546 if (!$validated && !$deny_authentication) {
1547 # check for IP-based authentication
1549 foreach $a (keys %ipaccess) {
1550 if ($acptip eq $a) {
1551 # It does! Auth as the user
1553 $baseauthuser = $authuser =
1559 # Check for normal HTTP authentication
1560 if (!$validated && !$deny_authentication && !$config{'session'} &&
1561 $header{authorization} =~ /^basic\s+(\S+)$/i) {
1562 # authorization given..
1563 ($authuser, $authpass) = split(/:/, &b64decode($1), 2);
1564 print DEBUG "handle_request: doing basic auth check authuser=$authuser authpass=$authpass\n";
1565 local ($vu, $expired, $nonexist) =
1566 &validate_user($authuser, $authpass, $host);
1567 print DEBUG "handle_request: vu=$vu expired=$expired nonexist=$nonexist\n";
1568 if ($vu && (!$expired || $config{'passwd_mode'} == 1)) {
1575 if ($use_syslog && !$validated) {
1576 syslog("crit", "%s",
1577 ($nonexist ? "Non-existent" :
1578 $expired ? "Expired" : "Invalid").
1579 " login as $authuser from $acpthost");
1581 if ($authuser =~ /\r|\n|\s/) {
1582 &http_error(500, "Invalid username",
1583 "Username contains invalid characters");
1585 if ($authpass =~ /\r|\n/) {
1586 &http_error(500, "Invalid password",
1587 "Password contains invalid characters");
1590 if ($config{'passdelay'} && !$config{'inetd'} && $authuser) {
1591 # check with main process for delay
1592 print DEBUG "handle_request: about to ask for password delay\n";
1593 print $PASSINw "delay $authuser $acptip $validated\n";
1594 <$PASSOUTr> =~ /(\d+) (\d+)/;
1596 print DEBUG "handle_request: password delay $1 $2\n";
1601 # Check for a visit to the special session login page
1602 if ($config{'session'} && !$deny_authentication &&
1603 $page eq $config{'session_login'}) {
1604 if ($in{'logout'} && $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1605 # Logout clicked .. remove the session
1607 print $PASSINw "delete $sid\n";
1608 local $louser = <$PASSOUTr>;
1611 $already_session_id = undef;
1612 $authuser = $baseauthuser = undef;
1615 syslog("info", "%s", "Logout by $louser from $acpthost");
1617 &run_logout_script($louser, $sid,
1619 &write_logout_utmp($louser, $actphost);
1624 if ($in{'user'} =~ /\r|\n|\s/) {
1625 &http_error(500, "Invalid username",
1626 "Username contains invalid characters");
1628 if ($in{'pass'} =~ /\r|\n/) {
1629 &http_error(500, "Invalid password",
1630 "Password contains invalid characters");
1633 local ($vu, $expired, $nonexist) =
1634 &validate_user($in{'user'}, $in{'pass'}, $host);
1635 local $hrv = &handle_login(
1636 $vu || $in{'user'}, $vu ? 1 : 0,
1637 $expired, $nonexist, $in{'pass'},
1638 $in{'notestingcookie'});
1639 return $hrv if (defined($hrv));
1643 # Check for a visit to the special PAM login page
1644 if ($config{'session'} && !$deny_authentication &&
1645 $use_pam && $config{'pam_conv'} && $page eq $config{'pam_login'} &&
1647 # A question has been entered .. submit it to the main process
1648 print DEBUG "handle_request: Got call to $page ($in{'cid'})\n";
1649 print DEBUG "handle_request: For PAM, authuser=$authuser\n";
1650 if ($in{'answer'} =~ /\r|\n/ || $in{'cid'} =~ /\r|\n|\s/) {
1651 &http_error(500, "Invalid response",
1652 "Response contains invalid characters");
1656 # Start of a new conversation - answer must be username
1657 $cid = &generate_random_id($in{'answer'});
1658 print $PASSINw "pamstart $cid $host $in{'answer'}\n";
1661 # A response to a previous question
1663 print $PASSINw "pamanswer $cid $in{'answer'}\n";
1666 # Read back the response, and the next question (if any)
1667 local $line = <$PASSOUTr>;
1668 $line =~ s/\r|\n//g;
1669 local ($rv, $question) = split(/\s+/, $line, 2);
1672 local $hrv = &handle_login(
1673 !$in{'cid'} && $in{'answer'} ? $in{'answer'}
1676 return $hrv if (defined($hrv));
1678 elsif ($rv == 1 || $rv == 3) {
1679 # Another question .. force use of PAM CGI
1682 $querystring .= "&cid=$cid&question=".
1684 $querystring .= "&password=1" if ($rv == 3);
1686 $page = $config{'pam_login'};
1687 $miniserv_internal = 1;
1691 # Got back a final ok or failure
1692 local ($user, $ok, $expired, $nonexist) =
1693 split(/\s+/, $question);
1694 local $hrv = &handle_login(
1695 $user, $ok, $expired, $nonexist, undef,
1696 $in{'notestingcookie'});
1697 return $hrv if (defined($hrv));
1700 # A message from PAM .. tell the user
1703 $querystring .= "&cid=$cid&message=".
1706 $page = $config{'pam_login'};
1707 $miniserv_internal = 1;
1712 # Check for a visit to the special password change page
1713 if ($config{'session'} && !$deny_authentication &&
1714 $page eq $config{'password_change'} && !$validated) {
1715 # Just let this slide ..
1717 $miniserv_internal = 3;
1720 # Check for an existing session
1721 if ($config{'session'} && !$validated) {
1722 if ($already_session_id) {
1723 $session_id = $already_session_id;
1724 $authuser = $already_authuser;
1727 elsif (!$deny_authentication &&
1728 $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1729 # Try all session cookies
1730 local $cookie = $header{'cookie'};
1731 while($cookie =~ s/(^|\s)$sidname=([a-f0-9]+)//) {
1734 $in{'webmin_notimeout'} ? 1 : 0;
1735 print $PASSINw "verify $session_id $notimeout\n";
1736 <$PASSOUTr> =~ /(\d+)\s+(\S+)/;
1738 # Valid session continuation
1741 $already_authuser = $authuser;
1750 # Invalid session ID .. don't set
1757 # Check for local authentication
1758 if ($localauth_user && !$header{'x-forwarded-for'} && !$header{'via'}) {
1759 my $luser = &get_user_details($localauth_user);
1761 # Local user exists in webmin users file
1763 $authuser = $localauth_user;
1766 # Check if local user is allowed by unixauth
1767 local @can = &can_user_login($localauth_user,
1771 $authuser = $localauth_user;
1774 $localauth_user = undef;
1780 # Check if this path allows anonymous access
1782 foreach $a (keys %anonymous) {
1783 if (substr($simple, 0, length($a)) eq $a) {
1784 # It does! Auth as the user, if IP access
1785 # control allows him.
1786 if (&check_user_ip($anonymous{$a}) &&
1787 &check_user_time($anonymous{$a})) {
1789 $baseauthuser = $authuser =
1797 # Check if this path allows unauthenticated access
1798 local ($u, $unauth);
1799 foreach $u (@unauth) {
1800 $unauth++ if ($simple =~ /$u/);
1802 if (!$bogus && $unauth) {
1803 # Unauthenticated directory or file request - approve it
1805 $baseauthuser = $authuser = undef;
1810 if ($blocked == 0) {
1811 # No password given.. ask
1812 if ($config{'pam_conv'} && $use_pam) {
1813 # Force CGI for PAM question, starting with
1814 # the username which is always needed
1817 $querystring .= "&initial=1&question=".
1818 &urlize("Username");
1819 $querystring .= "&failed=$failed_user" if ($failed_user);
1820 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1822 $page = $config{'pam_login'};
1823 $miniserv_internal = 1;
1826 elsif ($config{'session'}) {
1827 # Force CGI for session login
1830 $querystring .= "&logout=1&page=/";
1833 # Re-direct to current module only
1834 local $rpage = $request_uri;
1835 if (!$config{'loginkeeppage'}) {
1836 $rpage =~ s/\?.*$//;
1837 $rpage =~ s/[^\/]+$//
1839 $querystring = "page=".&urlize($rpage);
1842 $querystring .= "&failed=$failed_user" if ($failed_user);
1843 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1845 $page = $config{'session_login'};
1846 $miniserv_internal = 1;
1850 # Ask for login with HTTP authentication
1851 &write_data("HTTP/1.0 401 Unauthorized\r\n");
1852 &write_data("Date: $datestr\r\n");
1853 &write_data("Server: $config{'server'}\r\n");
1854 &write_data("WWW-authenticate: Basic ".
1855 "realm=\"$config{'realm'}\"\r\n");
1856 &write_keep_alive(0);
1857 &write_data("Content-type: text/html\r\n");
1858 &write_data("\r\n");
1859 &reset_byte_count();
1860 &write_data("<html>\n");
1861 &write_data("<head><title>Unauthorized</title></head>\n");
1862 &write_data("<body><h1>Unauthorized</h1>\n");
1863 &write_data("A password is required to access this\n");
1864 &write_data("web server. Please try again. <p>\n");
1865 &write_data("</body></html>\n");
1866 &log_request($acpthost, undef, $reqline, 401, &byte_count());
1870 elsif ($blocked == 1) {
1871 # when the host has been blocked, give it an error
1872 &http_error(403, "Access denied for $acptip. The host ".
1873 "has been blocked because of too ".
1874 "many authentication failures.");
1876 elsif ($blocked == 2) {
1877 # when the user has been blocked, give it an error
1878 &http_error(403, "Access denied. The user ".
1879 "has been blocked because of too ".
1880 "many authentication failures.");
1884 # Get the real Webmin username
1885 local @can = &can_user_login($authuser, undef, $host);
1886 $baseauthuser = $can[3] || $authuser;
1888 if ($config{'remoteuser'} && !$< && $validated) {
1889 # Switch to the UID of the remote user (if he exists)
1890 local @u = getpwnam($authuser);
1891 if (@u && $< != $u[2]) {
1892 $( = $u[3]; $) = "$u[3] $u[3]";
1893 ($>, $<) = ($u[2], $u[2]);
1896 &http_error(500, "Unix user $authuser does not exist");
1902 # Check per-user IP access control
1903 if (!&check_user_ip($baseauthuser)) {
1904 &http_error(403, "Access denied for $acptip for $baseauthuser");
1908 # Check per-user allowed times
1909 if (!&check_user_time($baseauthuser)) {
1910 &http_error(403, "Access denied at the current time");
1914 $uinfo = &get_user_details($baseauthuser);
1916 # Validate the path, and convert to canonical form
1918 $simple = &simplify_path($page, $bogus);
1919 print DEBUG "handle_request: page=$page simple=$simple\n";
1921 &http_error(400, "Invalid path");
1924 # Check for a DAV request
1926 return &handle_dav_request($davpath);
1929 # Work out the active theme(s)
1930 local $preroots = $mobile_device && defined($config{'mobile_preroot'}) ?
1931 $config{'mobile_preroot'} :
1932 $authuser && defined($config{'preroot_'.$authuser}) ?
1933 $config{'preroot_'.$authuser} :
1934 $uinfo && defined($uinfo->{'preroot'}) ?
1935 $uinfo->{'preroot'} :
1937 local @preroots = reverse(split(/\s+/, $preroots));
1939 # Canonicalize the directories
1940 foreach my $preroot (@preroots) {
1941 # Always under the current webmin root
1942 $preroot =~ s/^.*\///g;
1943 $preroot = $roots[0].'/'.$preroot;
1946 # Look in the theme root directories first
1947 local ($full, @stfull);
1949 foreach my $preroot (@preroots) {
1952 $full = $preroot.$sofar;
1953 $scriptname = $simple;
1954 foreach $b (split(/\//, $simple)) {
1955 if ($b ne "") { $sofar .= "/$b"; }
1956 $full = $preroot.$sofar;
1957 @stfull = stat($full);
1958 if (!@stfull) { undef($full); last; }
1960 # Check if this is a directory
1962 # It is.. go on parsing
1970 # Check if this is a CGI program
1971 if (&get_type($full) eq "internal/cgi") {
1972 $pathinfo = substr($simple, length($sofar));
1973 $pathinfo .= "/" if ($page =~ /\/$/);
1974 $scriptname = $sofar;
1979 # Don't stop at a directory unless this is the last theme, which
1980 # is the 'real' one that provides the .cgi scripts
1981 if ($is_directory && $preroot ne $preroots[$#preroots]) {
1988 $cgi_pwd = $roots[0];
1990 elsif ($is_directory) {
1991 $cgi_pwd = "$roots[0]$sofar";
1994 "$roots[0]$sofar" =~ /^(.*\/)[^\/]+$/;
1997 $foundroot = $preroot;
1998 if ($is_directory) {
1999 # Check for index files in the directory
2001 foreach $idx (split(/\s+/, $config{"index_docs"})) {
2002 $idxfull = "$full/$idx";
2003 local @stidxfull = stat($idxfull);
2004 if (-r _ && !-d _) {
2006 @stfull = @stidxfull;
2009 if ($scriptname ne "/");
2014 @stfull = stat($full) if (!$foundidx);
2017 last if ($foundroot);
2019 print DEBUG "handle_request: initial full=$full\n";
2021 # Look in the real root directories, stopping when we find a file or directory
2022 if (!$full || $is_directory) {
2023 ROOT: foreach $root (@roots) {
2025 $full = $root.$sofar;
2026 $scriptname = $simple;
2027 foreach $b ($simple eq "/" ? ( "" ) : split(/\//, $simple)) {
2028 if ($b ne "") { $sofar .= "/$b"; }
2029 $full = $root.$sofar;
2030 @stfull = stat($full);
2035 # Check if this is a directory
2037 # It is.. go on parsing
2041 # Check if this is a CGI program
2042 if (&get_type($full) eq "internal/cgi") {
2043 $pathinfo = substr($simple, length($sofar));
2044 $pathinfo .= "/" if ($page =~ /\/$/);
2045 $scriptname = $sofar;
2050 # Run CGI in the same directory as whatever file
2052 $full =~ /^(.*\/)[^\/]+$/; $cgi_pwd = $1;
2061 if (!@stfull) { &http_error(404, "File not found"); }
2063 print DEBUG "handle_request: full=$full\n";
2064 @stfull = stat($full) if (!@stfull);
2066 # check filename against denyfile regexp
2067 local $denyfile = $config{'denyfile'};
2068 if ($denyfile && $full =~ /$denyfile/) {
2069 &http_error(403, "Access denied to $page");
2073 # Reached the end of the path OK.. see what we've got
2075 # See if the URL ends with a / as it should
2076 print DEBUG "handle_request: found a directory\n";
2077 if ($page !~ /\/$/) {
2078 # It doesn't.. redirect
2079 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2080 $ssl = $use_ssl || $config{'inetd_ssl'};
2081 $portstr = $port == 80 && !$ssl ? "" :
2082 $port == 443 && $ssl ? "" : ":$port";
2083 &write_data("Date: $datestr\r\n");
2084 &write_data("Server: $config{server}\r\n");
2085 $prot = $ssl ? "https" : "http";
2086 &write_data("Location: $prot://$host$portstr$page/\r\n");
2087 &write_keep_alive(0);
2088 &write_data("\r\n");
2089 &log_request($acpthost, $authuser, $reqline, 302, 0);
2092 # A directory.. check for index files
2094 foreach $idx (split(/\s+/, $config{"index_docs"})) {
2095 $idxfull = "$full/$idx";
2096 @stidxfull = stat($idxfull);
2097 if (-r _ && !-d _) {
2100 @stfull = @stidxfull;
2101 $scriptname .= "/" if ($scriptname ne "/");
2106 @stfull = stat($full) if (!$foundidx);
2109 # This is definately a directory.. list it
2110 print DEBUG "handle_request: listing directory\n";
2111 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2112 "Date: $datestr\r\n".
2113 "Server: $config{server}\r\n".
2114 "Content-type: text/html\r\n";
2116 &write_keep_alive(0);
2117 &write_data("\r\n");
2118 &reset_byte_count();
2119 &write_data("<h1>Index of $simple</h1>\n");
2120 &write_data("<pre>\n");
2121 &write_data(sprintf "%-35.35s %-20.20s %-10.10s\n",
2122 "Name", "Last Modified", "Size");
2123 &write_data("<hr>\n");
2124 opendir(DIR, $full);
2125 while($df = readdir(DIR)) {
2126 if ($df =~ /^\./) { next; }
2127 $fulldf = $full eq "/" ? $full.$df : $full."/".$df;
2128 (@stbuf = stat($fulldf)) || next;
2129 if (-d _) { $df .= "/"; }
2130 @tm = localtime($stbuf[9]);
2131 $fdate = sprintf "%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d",
2132 $tm[3],$tm[4]+1,$tm[5]+1900,
2133 $tm[0],$tm[1],$tm[2];
2134 $len = length($df); $rest = " "x(35-$len);
2136 "<a href=\"%s\">%-${len}.${len}s</a>$rest %-20.20s %-10.10s\n",
2137 $df, $df, $fdate, $stbuf[7]);
2140 &log_request($acpthost, $authuser, $reqline, $ok_code, &byte_count());
2144 # CGI or normal file
2146 if (&get_type($full) eq "internal/cgi" && $validated != 4) {
2147 # A CGI program to execute
2148 print DEBUG "handle_request: executing CGI\n";
2149 $envtz = $ENV{"TZ"};
2150 $envuser = $ENV{"USER"};
2151 $envpath = $ENV{"PATH"};
2152 $envlang = $ENV{"LANG"};
2153 $envroot = $ENV{"SystemRoot"};
2154 $envperllib = $ENV{'PERLLIB'};
2155 foreach my $k (keys %ENV) {
2158 $ENV{"PATH"} = $envpath if ($envpath);
2159 $ENV{"TZ"} = $envtz if ($envtz);
2160 $ENV{"USER"} = $envuser if ($envuser);
2161 $ENV{"OLD_LANG"} = $envlang if ($envlang);
2162 $ENV{"SystemRoot"} = $envroot if ($envroot);
2163 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
2164 $ENV{"HOME"} = $user_homedir;
2165 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
2166 $ENV{"SERVER_NAME"} = $host;
2167 $ENV{"SERVER_ADMIN"} = $config{"email"};
2168 $ENV{"SERVER_ROOT"} = $roots[0];
2169 $ENV{"SERVER_REALROOT"} = $realroot;
2170 $ENV{"SERVER_PORT"} = $port;
2171 $ENV{"REMOTE_HOST"} = $acpthost;
2172 $ENV{"REMOTE_ADDR"} = $acptip;
2173 $ENV{"REMOTE_ADDR_PROTOCOL"} = $ipv6 ? 6 : 4;
2174 $ENV{"REMOTE_USER"} = $authuser;
2175 $ENV{"BASE_REMOTE_USER"} = $authuser ne $baseauthuser ?
2176 $baseauthuser : undef;
2177 $ENV{"REMOTE_PASS"} = $authpass if (defined($authpass) &&
2178 $config{'pass_password'});
2179 if ($uinfo && $uinfo->{'proto'}) {
2180 $ENV{"REMOTE_USER_PROTO"} = $uinfo->{'proto'};
2181 $ENV{"REMOTE_USER_ID"} = $uinfo->{'id'};
2183 print DEBUG "REMOTE_USER = ",$ENV{"REMOTE_USER"},"\n";
2184 print DEBUG "BASE_REMOTE_USER = ",$ENV{"BASE_REMOTE_USER"},"\n";
2185 print DEBUG "proto=$uinfo->{'proto'} id=$uinfo->{'id'}\n" if ($uinfo);
2186 $ENV{"SSL_USER"} = $peername if ($validated == 2);
2187 $ENV{"ANONYMOUS_USER"} = "1" if ($validated == 3 || $validated == 4);
2188 $ENV{"DOCUMENT_ROOT"} = $roots[0];
2189 $ENV{"DOCUMENT_REALROOT"} = $realroot;
2190 $ENV{"GATEWAY_INTERFACE"} = "CGI/1.1";
2191 $ENV{"SERVER_PROTOCOL"} = "HTTP/1.0";
2192 $ENV{"REQUEST_METHOD"} = $method;
2193 $ENV{"SCRIPT_NAME"} = $scriptname;
2194 $ENV{"SCRIPT_FILENAME"} = $full;
2195 $ENV{"REQUEST_URI"} = $request_uri;
2196 $ENV{"PATH_INFO"} = $pathinfo;
2198 $ENV{"PATH_TRANSLATED"} = "$roots[0]$pathinfo";
2199 $ENV{"PATH_REALTRANSLATED"} = "$realroot$pathinfo";
2201 $ENV{"QUERY_STRING"} = $querystring;
2202 $ENV{"MINISERV_CONFIG"} = $config_file;
2203 $ENV{"HTTPS"} = "ON" if ($use_ssl || $config{'inetd_ssl'});
2204 $ENV{"MINISERV_PID"} = $miniserv_main_pid;
2205 $ENV{"SESSION_ID"} = $session_id if ($session_id);
2206 $ENV{"LOCAL_USER"} = $localauth_user if ($localauth_user);
2207 $ENV{"MINISERV_INTERNAL"} = $miniserv_internal if ($miniserv_internal);
2208 if (defined($header{"content-length"})) {
2209 $ENV{"CONTENT_LENGTH"} = $header{"content-length"};
2211 if (defined($header{"content-type"})) {
2212 $ENV{"CONTENT_TYPE"} = $header{"content-type"};
2214 foreach $h (keys %header) {
2215 ($hname = $h) =~ tr/a-z/A-Z/;
2217 $ENV{"HTTP_$hname"} = $header{$h};
2219 $ENV{"PWD"} = $cgi_pwd;
2220 foreach $k (keys %config) {
2221 if ($k =~ /^env_(\S+)$/) {
2222 $ENV{$1} = $config{$k};
2225 delete($ENV{'HTTP_AUTHORIZATION'});
2226 $ENV{'HTTP_COOKIE'} =~ s/;?\s*$sidname=([a-f0-9]+)//;
2227 $ENV{'MOBILE_DEVICE'} = 1 if ($mobile_device);
2229 # Check if the CGI can be handled internally
2231 local $first = <CGI>;
2233 $first =~ s/[#!\r\n]//g;
2234 $nph_script = ($full =~ /\/nph-([^\/]+)$/);
2236 if (!$config{'forkcgis'} &&
2237 ($first eq $perl_path || $first eq $linked_perl_path) &&
2239 $config{'internalcgis'}) {
2240 # setup environment for eval
2242 @ARGV = split(/\s+/, $queryargs);
2245 # Already read the post input
2246 $postinput = $posted_data;
2248 $clen = $header{"content-length"};
2249 $SIG{'CHLD'} = 'DEFAULT';
2251 # Have SOCK closed if the perl exec's something
2253 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
2257 if ($config{'log'}) {
2258 open(MINISERVLOG, ">>$config{'logfile'}");
2259 if ($config{'logperms'}) {
2260 chmod(oct($config{'logperms'}),
2261 $config{'logfile'});
2264 chmod(0600, $config{'logfile'});
2267 $doing_cgi_eval = 1;
2268 $main_process_id = $$;
2270 if ($full =~ /^\Q$foundroot\E\/([^\/]+)\//) {
2271 # Eval in package from Webmin module name
2273 $pkg =~ s/[^A-Za-z0-9]/_/g;
2278 tie(*STDOUT, 'miniserv');
2279 tie(*STDIN, 'miniserv');
2280 do \$miniserv::full;
2283 $doing_cgi_eval = 0;
2286 &http_error(500, "Perl execution failed",
2287 $config{'noshowstderr'} ? undef : $@);
2289 elsif (!$doneheaders && !$nph_script) {
2290 &http_error(500, "Missing Headers");
2297 # fork the process that actually executes the CGI
2298 pipe(CGIINr, CGIINw);
2299 pipe(CGIOUTr, CGIOUTw);
2300 pipe(CGIERRr, CGIERRw);
2301 if (!($cgipid = fork())) {
2302 @execargs = ( $full, split(/\s+/, $queryargs) );
2305 open(STDIN, "<&CGIINr");
2306 open(STDOUT, ">&CGIOUTw");
2307 open(STDERR, ">&CGIERRw");
2308 close(CGIINw); close(CGIOUTr); close(CGIERRr);
2310 die "Failed to exec $full : $!\n";
2313 close(CGIINr); close(CGIOUTw); close(CGIERRw);
2316 # write CGI input to a temp file
2317 $infile = "$config{'tempbase'}.$$";
2318 open(CGIINw, ">$infile");
2319 # NOT binary mode, as CGIs don't read in it!
2324 # already read the posted data
2325 print CGIINw $posted_data;
2327 $clen = $header{"content-length"};
2328 if ($method eq "POST" && $clen_read < $clen) {
2329 $SIG{'PIPE'} = 'IGNORE';
2331 while($got < $clen) {
2332 $buf = &read_data($clen-$got);
2333 if (!length($buf)) {
2334 kill('TERM', $cgipid);
2335 unlink($infile) if ($infile);
2336 &http_error(500, "Failed to read ".
2339 $got += length($buf);
2340 local ($wrote) = (print CGIINw $buf);
2343 # If the CGI terminated early, we still need to read
2344 # from the browser and throw away
2345 while($got < $clen) {
2346 $buf = &read_data($clen-$got);
2347 if (!length($buf)) {
2348 kill('TERM', $cgipid);
2349 unlink($infile) if ($infile);
2350 &http_error(500, "Failed to read ".
2353 $got += length($buf);
2355 $SIG{'PIPE'} = 'DEFAULT';
2361 # Run the CGI program, and feed it input
2363 local $qqueryargs = join(" ", map { "\"$_\"" }
2364 split(/\s+/, $queryargs));
2365 if ($first =~ /(perl|perl.exe)$/i) {
2366 # On Windows, run with Perl
2367 open(CGIOUTr, "$perl_path \"$full\" $qqueryargs <$infile |");
2370 open(CGIOUTr, "\"$full\" $qqueryargs <$infile |");
2376 # read back cgi headers
2377 select(CGIOUTr); $|=1; select(STDOUT);
2381 $line =~ s/\r|\n//g;
2383 if ($got_blank || %cgiheader) { last; }
2387 if ($line !~ /^(\S+):\s+(.*)$/) {
2388 $errs = &read_errors(CGIERRr);
2389 close(CGIOUTr); close(CGIERRr);
2390 unlink($infile) if ($infile);
2391 &http_error(500, "Bad Header", $errs);
2393 $cgiheader{lc($1)} = $2;
2394 push(@cgiheader, [ $1, $2 ]);
2396 if ($cgiheader{"location"}) {
2397 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2398 &write_data("Date: $datestr\r\n");
2399 &write_data("Server: $config{'server'}\r\n");
2400 &write_keep_alive(0);
2401 # ignore the rest of the output. This is a hack,
2402 # but is necessary for IE in some cases :(
2403 close(CGIOUTr); close(CGIERRr);
2405 elsif ($cgiheader{"content-type"} eq "") {
2406 close(CGIOUTr); close(CGIERRr);
2407 unlink($infile) if ($infile);
2408 $errs = &read_errors(CGIERRr);
2409 &http_error(500, "Missing Content-Type Header",
2410 $config{'noshowstderr'} ? undef : $errs);
2413 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2414 &write_data("Date: $datestr\r\n");
2415 &write_data("Server: $config{'server'}\r\n");
2416 &write_keep_alive(0);
2418 foreach $h (@cgiheader) {
2419 &write_data("$h->[0]: $h->[1]\r\n");
2421 &write_data("\r\n");
2423 &reset_byte_count();
2424 while($line = <CGIOUTr>) {
2429 unlink($infile) if ($infile);
2435 print DEBUG "handle_request: outputting file $full\n";
2436 $gzfile = $full.".gz";
2438 if ($config{'gzip'} ne '0' && -r $gzfile && $acceptenc{'gzip'}) {
2439 # Using gzipped version
2440 @stopen = stat($gzfile);
2441 if ($stopen[9] >= $stfull[9] && open(FILE, $gzfile)) {
2442 print DEBUG "handle_request: using gzipped $gzfile\n";
2447 # Using original file
2449 open(FILE, $full) || &http_error(404, "Failed to open file");
2452 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2453 "Date: $datestr\r\n".
2454 "Server: $config{server}\r\n".
2455 "Content-type: ".&get_type($full)."\r\n".
2456 "Content-length: $stopen[7]\r\n".
2457 "Last-Modified: ".&http_date($stopen[9])."\r\n".
2458 ($gzipped ? "Content-Encoding: gzip\r\n" : "").
2459 "Expires: ".&http_date(time()+$config{'expires'})."\r\n";
2461 $rv = &write_keep_alive();
2462 &write_data("\r\n");
2463 &reset_byte_count();
2464 while(read(FILE, $buf, 1024) > 0) {
2471 &log_request($acpthost, $authuser, $reqline,
2472 $logged_code ? $logged_code :
2473 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2477 # http_error(code, message, body, [dontexit])
2480 local $eh = $error_handler_recurse ? undef :
2481 $config{"error_handler_$_[0]"} ? $config{"error_handler_$_[0]"} :
2482 $config{'error_handler'} ? $config{'error_handler'} : undef;
2483 print DEBUG "http_error code=$_[0] message=$_[1] body=$_[2]\n";
2485 # Call a CGI program for the error
2487 $querystring = "code=$_[0]&message=".&urlize($_[1]).
2488 "&body=".&urlize($_[2]);
2489 $error_handler_recurse++;
2491 $ok_message = $_[1];
2495 # Use the standard error message display
2496 &write_data("HTTP/1.0 $_[0] $_[1]\r\n");
2497 &write_data("Server: $config{server}\r\n");
2498 &write_data("Date: $datestr\r\n");
2499 &write_data("Content-type: text/html\r\n");
2500 &write_keep_alive(0);
2501 &write_data("\r\n");
2502 &reset_byte_count();
2503 &write_data("<h1>Error - $_[1]</h1>\n");
2505 &write_data("<pre>$_[2]</pre>\n");
2508 &log_request($acpthost, $authuser, $reqline, $_[0], &byte_count())
2510 &log_error($_[1], $_[2] ? " : $_[2]" : "");
2517 if ($_[0] =~ /\.([A-z0-9]+)$/) {
2523 return "text/plain";
2526 # simplify_path(path, bogus)
2527 # Given a path, maybe containing stuff like ".." and "." convert it to a
2528 # clean, absolute form.
2531 local($dir, @bits, @fixedbits, $b);
2533 $dir =~ s/\\/\//g; # fix windows \ in path
2536 $dir =~ s/\0//g; # remove null bytes
2537 @bits = split(/\/+/, $dir);
2540 foreach $b (@bits) {
2544 elsif ($b eq ".." || $b eq "...") {
2546 if (scalar(@fixedbits) == 0) {
2554 push(@fixedbits, $b);
2557 return "/" . join('/', @fixedbits);
2561 # Converts a string from base64 format to normal
2564 local($str) = $_[0];
2566 $str =~ tr|A-Za-z0-9+=/||cd;
2568 $str =~ tr|A-Za-z0-9+/| -_|;
2569 while ($str =~ /(.{1,60})/gs) {
2570 my $len = chr(32 + length($1)*3/4);
2571 $res .= unpack("u", $len . $1 );
2576 # ip_match(remoteip, localip, [match]+)
2577 # Checks an IP address against a list of IPs, networks and networks/masks
2580 local(@io, @mo, @ms, $i, $j, $hn, $needhn);
2581 @io = &check_ip6address($_[0]) ? split(/:/, $_[0])
2582 : split(/\./, $_[0]);
2583 for($i=2; $i<@_; $i++) {
2584 $needhn++ if ($_[$i] =~ /^\*(\S+)$/);
2586 if ($needhn && !defined($hn = $ip_match_cache{$_[0]})) {
2587 # Reverse-lookup hostname if any rules match based on it
2588 $hn = &to_hostname($_[0]);
2589 if (&check_ip6address($_[0])) {
2590 $hn = "" if (&to_ip6address($hn) ne $_[0]);
2593 $hn = "" if (&to_ipaddress($hn) ne $_[0]);
2595 $ip_match_cache{$_[0]} = $hn;
2597 for($i=2; $i<@_; $i++) {
2598 local $mismatch = 0;
2599 if ($_[$i] =~ /^(\S+)\/(\d+)$/) {
2600 # Convert CIDR to netmask format
2601 $_[$i] = $1."/".&prefix_to_mask($2);
2603 if ($_[$i] =~ /^(\S+)\/(\S+)$/) {
2604 # Compare with IPv4 network/mask
2605 @mo = split(/\./, $1); @ms = split(/\./, $2);
2606 for($j=0; $j<4; $j++) {
2607 if ((int($io[$j]) & int($ms[$j])) != int($mo[$j])) {
2612 elsif ($_[$i] =~ /^\*(\S+)$/) {
2613 # Compare with hostname regexp
2614 $mismatch = 1 if ($hn !~ /$1$/);
2616 elsif ($_[$i] eq 'LOCAL' && &check_ipaddress($_[1])) {
2617 # Compare with local IPv4 network
2618 local @lo = split(/\./, $_[1]);
2620 $mismatch = 1 if ($lo[0] != $io[0]);
2622 elsif ($lo[0] < 192) {
2623 $mismatch = 1 if ($lo[0] != $io[0] ||
2627 $mismatch = 1 if ($lo[0] != $io[0] ||
2632 elsif ($_[$i] eq 'LOCAL' && &check_ip6address($_[1])) {
2633 # Compare with local IPv6 network, which is always first 4 words
2634 local @lo = split(/:/, $_[1]);
2635 for(my $i=0; $i<4; $i++) {
2636 $mismatch = 1 if ($lo[$i] ne $io[$i]);
2639 elsif ($_[$i] =~ /^[0-9\.]+$/) {
2640 # Compare with IPv4 address or network
2641 @mo = split(/\./, $_[$i]);
2642 while(@mo && !$mo[$#mo]) { pop(@mo); }
2643 for($j=0; $j<@mo; $j++) {
2644 if ($mo[$j] != $io[$j]) {
2649 elsif ($_[$i] =~ /^[a-f0-9:]+$/) {
2650 # Compare with IPv6 address or network
2651 @mo = split(/:/, $_[$i]);
2652 while(@mo && !$mo[$#mo]) { pop(@mo); }
2653 for($j=0; $j<@mo; $j++) {
2654 if ($mo[$j] ne $io[$j]) {
2659 elsif ($_[$i] !~ /^[0-9\.]+$/) {
2660 # Compare with hostname
2661 $mismatch = 1 if ($_[0] ne &to_ipaddress($_[$i]));
2663 return 1 if (!$mismatch);
2668 # users_match(&uinfo, user, ...)
2669 # Returns 1 if a user is in a list of users and groups
2672 local $uinfo = shift(@_);
2674 local @ginfo = getgrgid($uinfo->[3]);
2676 if ($u =~ /^\@(\S+)$/) {
2677 return 1 if (&is_group_member($uinfo, $1));
2679 elsif ($u =~ /^(\d*)-(\d*)$/ && ($1 || $2)) {
2680 return (!$1 || $uinfo[2] >= $1) &&
2681 (!$2 || $uinfo[2] <= $2);
2684 return 1 if ($u eq $uinfo->[0]);
2690 # restart_miniserv()
2691 # Called when a SIGHUP is received to restart the web server. This is done
2692 # by exec()ing perl with the same command line as was originally used
2693 sub restart_miniserv
2695 print STDERR "restarting miniserv\n";
2696 &log_error("Restarting");
2698 &close_all_sockets();
2700 dbmclose(%sessiondb);
2701 kill('KILL', $logclearer) if ($logclearer);
2702 kill('KILL', $extauth) if ($extauth);
2703 exec($perl_path, $miniserv_path, @miniserv_argv);
2704 die "Failed to restart miniserv with $perl_path $miniserv_path";
2717 # to_ipaddress(address, ...)
2722 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2723 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/ || $i =~ /^[a-f0-9:]+$/) {
2724 # A pattern or IP, not a hostname, so don't change
2729 push(@rv, join('.', unpack("CCCC", inet_aton($i))));
2732 return wantarray ? @rv : $rv[0];
2735 # to_ip6address(address, ...)
2740 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2741 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/ || $i =~ /^[a-f0-9:]+$/) {
2742 # A pattern, not a hostname, so don't change
2746 # Lookup IPv6 address
2747 local ($inaddr, $addr);
2748 (undef, undef, undef, $inaddr) =
2749 getaddrinfo($i, undef, Socket6::AF_INET6(), SOCK_STREAM);
2754 (undef, $addr) = unpack_sockaddr_in6($inaddr);
2755 push(@rv, inet_ntop(Socket6::AF_INET6(), $addr));
2759 return wantarray ? @rv : $rv[0];
2762 # to_hostname(ipv4|ipv6-address)
2763 # Reverse-resolves an IPv4 or 6 address to a hostname
2767 if (&check_ip6address($_[0])) {
2768 return gethostbyaddr(inet_pton(Socket6::AF_INET6(), $addr),
2769 Socket6::AF_INET6());
2772 return gethostbyaddr(inet_aton($addr), AF_INET);
2776 # read_line(no-wait, no-limit)
2777 # Reads one line from SOCK or SSL
2780 local ($nowait, $nolimit) = @_;
2781 local($idx, $more, $rv);
2782 while(($idx = index($main::read_buffer, "\n")) < 0) {
2783 if (length($main::read_buffer) > 10000 && !$nolimit) {
2784 &http_error(414, "Request too long",
2785 "Received excessive line <pre>$main::read_buffer</pre>");
2788 # need to read more..
2789 &wait_for_data_error() if (!$nowait);
2791 $more = Net::SSLeay::read($ssl_con);
2794 local $ok = sysread(SOCK, $more, 1024);
2795 $more = undef if ($ok <= 0);
2799 $rv = $main::read_buffer;
2800 undef($main::read_buffer);
2803 $main::read_buffer .= $more;
2805 $rv = substr($main::read_buffer, 0, $idx+1);
2806 $main::read_buffer = substr($main::read_buffer, $idx+1);
2811 # Reads up to some amount of data from SOCK or the SSL connection
2815 if (length($main::read_buffer)) {
2816 if (length($main::read_buffer) > $_[0]) {
2817 # Return the first part of the buffer
2818 $rv = substr($main::read_buffer, 0, $_[0]);
2819 $main::read_buffer = substr($main::read_buffer, $_[0]);
2823 # Return the whole buffer
2824 $rv = $main::read_buffer;
2825 undef($main::read_buffer);
2830 # Call SSL read function
2831 return Net::SSLeay::read($ssl_con, $_[0]);
2834 # Just do a normal read
2836 sysread(SOCK, $buf, $_[0]) || return undef;
2842 # Read a line from a file handle, using sysread to get a byte at a time
2849 $got = sysread($fh, $buf, 1);
2850 last if ($got <= 0);
2852 last if ($buf eq "\n");
2857 # wait_for_data(secs)
2858 # Waits at most the given amount of time for some data on SOCK, returning
2859 # 0 if not found, 1 if some arrived.
2863 vec($rmask, fileno(SOCK), 1) = 1;
2864 local $got = select($rmask, undef, undef, $_[0]);
2865 return $got == 0 ? 0 : 1;
2868 # wait_for_data_error()
2869 # Waits 60 seconds for data on SOCK, and fails if none arrives
2870 sub wait_for_data_error
2872 local $got = &wait_for_data(60);
2874 &http_error(400, "Timeout",
2875 "Waited more than 60 seconds for request data");
2879 # write_data(data, ...)
2880 # Writes a string to SOCK or the SSL connection
2883 local $str = join("", @_);
2885 Net::SSLeay::write($ssl_con, $str);
2888 syswrite(SOCK, $str, length($str));
2890 # Intentionally introduce a small delay to avoid problems where IE reports
2891 # the page as empty / DNS failed when it get a large response too quickly!
2892 select(undef, undef, undef, .01) if ($write_data_count%10 == 0);
2893 $write_data_count += length($str);
2896 # reset_byte_count()
2897 sub reset_byte_count { $write_data_count = 0; }
2900 sub byte_count { return $write_data_count; }
2902 # log_request(hostname, user, request, code, bytes)
2905 if ($config{'log'}) {
2906 local ($user, $ident, $headers);
2907 if ($config{'logident'}) {
2908 # add support for rfc1413 identity checking here
2910 else { $ident = "-"; }
2911 $user = $_[1] ? $_[1] : "-";
2912 local $dstr = &make_datestr();
2913 if (fileno(MINISERVLOG)) {
2914 seek(MINISERVLOG, 0, 2);
2917 open(MINISERVLOG, ">>$config{'logfile'}");
2918 chmod(0600, $config{'logfile'});
2920 if (defined($config{'logheaders'})) {
2921 foreach $h (split(/\s+/, $config{'logheaders'})) {
2922 $headers .= " $h=\"$header{$h}\"";
2925 elsif ($config{'logclf'}) {
2926 $headers = " \"$header{'referer'}\" \"$header{'user-agent'}\"";
2931 print MINISERVLOG "$_[0] $ident $user [$dstr] \"$_[2]\" ",
2932 "$_[3] $_[4]$headers\n";
2940 local @tm = localtime(time());
2941 return sprintf "%2.2d/%s/%4.4d:%2.2d:%2.2d:%2.2d %s",
2942 $tm[3], $month[$tm[4]], $tm[5]+1900,
2943 $tm[2], $tm[1], $tm[0], $timezone;
2946 # log_error(message)
2950 print STDERR "[",&make_datestr(),"] ",
2951 $acpthost ? ( "[",$acpthost,"] " ) : ( ),
2952 $page ? ( $page," : " ) : ( ),
2956 # read_errors(handle)
2957 # Read and return all input from some filehandle
2960 local($fh, $_, $rv);
2962 while(<$fh>) { $rv .= $_; }
2966 sub write_keep_alive
2969 if ($config{'nokeepalive'}) {
2970 # Keep alives have been disabled in config
2973 elsif (@childpids > $config{'maxconns'}*.8) {
2974 # Disable because nearing process limit
2978 # Keep alive specified by caller
2982 # Keep alive determined by browser
2983 $mode = $header{'connection'} =~ /keep-alive/i;
2985 &write_data("Connection: ".($mode ? "Keep-Alive" : "close")."\r\n");
2991 kill('TERM', @childpids) if (@childpids);
2992 kill('KILL', $logclearer) if ($logclearer);
2993 kill('KILL', $extauth) if ($extauth);
2999 local @tm = gmtime($_[0]);
3000 return sprintf "%s, %d %s %d %2.2d:%2.2d:%2.2d GMT",
3001 $weekday[$tm[6]], $tm[3], $month[$tm[4]], $tm[5]+1900,
3002 $tm[2], $tm[1], $tm[0];
3007 my $i; bless \$i, shift;
3013 my($buf,$len,$offset) = @_;
3014 &write_to_sock(substr($buf, $offset, $len));
3015 $miniserv::page_capture_out .= substr($buf, $offset, $len)
3016 if ($miniserv::page_capture);
3023 my $buf = join(defined($,) ? $, : "", @_);
3024 $buf .= $\ if defined($\);
3025 &write_to_sock($buf);
3026 $miniserv::page_capture_out .= $buf
3027 if ($miniserv::page_capture);
3034 my $buf = sprintf $fmt, @_;
3035 &write_to_sock($buf);
3036 $miniserv::page_capture_out .= $buf
3037 if ($miniserv::page_capture);
3040 # Send back already read data while we have it, then read from SOCK
3044 my $bufref = \$_[0];
3047 if ($postpos < length($postinput)) {
3048 # Reading from already fetched array
3049 my $left = length($postinput) - $postpos;
3050 my $canread = $len > $left ? $left : $len;
3051 substr($$bufref, $offset, $canread) =
3052 substr($postinput, $postpos, $canread);
3053 $postpos += $canread;
3057 # Read from network socket
3058 local $data = &read_data($len);
3059 if ($data eq '' && $len) {
3061 print STDERR "finished reading - shutting down socket\n";
3064 substr($$bufref, $offset, length($data)) = $data;
3065 return length($data);
3071 #print STDERR "open() called - should never happen!\n";
3074 # Read a line of input
3078 if ($postpos < length($postinput) &&
3079 ($idx = index($postinput, "\n", $postpos)) >= 0) {
3080 # A line exists in the memory buffer .. use it
3081 my $line = substr($postinput, $postpos, $idx-$postpos+1);
3086 # Need to read from the socket
3088 if ($postpos < length($postinput)) {
3089 # Start with in-memory data
3090 $line = substr($postinput, $postpos);
3091 $postpos = length($postinput);
3093 my $nl = &read_line(0, 1);
3096 print STDERR "finished reading - shutting down socket\n";
3099 $line .= $nl if (defined($nl));
3104 # Read one character of input
3109 my $got = READ($r, \$buf, 1, 0);
3110 return $got > 0 ? $buf : undef;
3115 return fileno(SOCK);
3122 # write_to_sock(data, ...)
3127 if ($doneheaders || $miniserv::nph_script) {
3132 while(!$doneheaders && $headers =~ s/^([^\r\n]*)(\r)?\n//) {
3133 if ($1 =~ /^(\S+):\s+(.*)$/) {
3134 $cgiheader{lc($1)} = $2;
3135 push(@cgiheader, [ $1, $2 ]);
3137 elsif ($1 !~ /\S/) {
3141 &http_error(500, "Bad Header");
3145 if ($cgiheader{"location"}) {
3147 "HTTP/1.0 302 Moved Temporarily\r\n");
3148 &write_data("Date: $datestr\r\n");
3149 &write_data("Server: $config{server}\r\n");
3150 &write_keep_alive(0);
3152 elsif ($cgiheader{"content-type"} eq "") {
3153 &http_error(500, "Missing Content-Type Header");
3156 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
3157 &write_data("Date: $datestr\r\n");
3158 &write_data("Server: $config{server}\r\n");
3159 &write_keep_alive(0);
3161 foreach $h (@cgiheader) {
3162 &write_data("$h->[0]: $h->[1]\r\n");
3164 &write_data("\r\n");
3165 &reset_byte_count();
3166 &write_data($headers);
3174 local $cert = Net::SSLeay::X509_STORE_CTX_get_current_cert($_[1]);
3176 local $errnum = Net::SSLeay::X509_STORE_CTX_get_error($_[1]);
3177 $verified_client = 1 if (!$errnum);
3184 if ($doing_cgi_eval && $$ == $main_process_id) {
3185 # A CGI program called exit! This is a horrible hack to
3186 # finish up before really exiting
3189 close($PASSINw); close($PASSOUTw);
3190 &log_request($acpthost, $authuser, $reqline,
3191 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
3196 # Convert a string to a form ok for putting in a URL
3198 local($tmp, $tmp2, $c);
3201 while(($c = chop($tmp)) ne "") {
3202 if ($c !~ /[A-z0-9]/) {
3203 $c = sprintf("%%%2.2X", ord($c));
3210 # validate_user(username, password, host)
3211 # Checks if some username and password are valid. Returns the modified username,
3212 # the expired / temp pass flag, and the non-existence flag
3215 local ($user, $pass, $host) = @_;
3216 return ( ) if (!$user);
3217 print DEBUG "validate_user: user=$user pass=$pass host=$host\n";
3218 local ($canuser, $canmode, $notexist, $webminuser, $sudo) =
3219 &can_user_login($user, undef, $host);
3220 print DEBUG "validate_user: canuser=$canuser canmode=$canmode notexist=$notexist webminuser=$webminuser sudo=$sudo\n";
3222 # User doesn't even exist, so go no further
3223 return ( undef, 0, 1 );
3225 elsif ($canmode == 0) {
3226 # User does exist but cannot login
3227 return ( $canuser, 0, 0 );
3229 elsif ($canmode == 1) {
3230 # Attempt Webmin authentication
3231 my $uinfo = &get_user_details($webminuser);
3233 &password_crypt($pass, $uinfo->{'pass'}) eq $uinfo->{'pass'}) {
3234 # Password is valid .. but check for expiry
3235 local $lc = $uinfo->{'lastchanges'};
3236 print DEBUG "validate_user: Password is valid lc=$lc pass_maxdays=$config{'pass_maxdays'}\n";
3237 if ($config{'pass_maxdays'} && $lc && !$uinfo->{'nochange'}) {
3238 local $daysold = (time() - $lc)/(24*60*60);
3239 print DEBUG "maxdays=$config{'pass_maxdays'} daysold=$daysold temppass=$uinfo->{'temppass'}\n";
3240 if ($config{'pass_lockdays'} &&
3241 $daysold > $config{'pass_lockdays'}) {
3242 # So old that the account is locked
3243 return ( undef, 0, 0 );
3245 elsif ($daysold > $config{'pass_maxdays'}) {
3246 # Password has expired
3247 return ( $user, 1, 0 );
3250 if ($uinfo->{'temppass'}) {
3251 # Temporary password - force change now
3252 return ( $user, 2, 0 );
3254 return ( $user, 0, 0 );
3257 print DEBUG "validate_user: User $webminuser not found\n";
3258 return ( undef, 0, 0 );
3261 print DEBUG "validate_user: User $webminuser password mismatch $pass != $uinfo->{'pass'}\n";
3262 return ( undef, 0, 0 );
3265 elsif ($canmode == 2 || $canmode == 3) {
3266 # Attempt PAM or passwd file authentication
3267 local $val = &validate_unix_user($canuser, $pass);
3268 print DEBUG "validate_user: unix val=$val\n";
3269 if ($val && $sudo) {
3270 # Need to check if this Unix user can sudo
3271 if (!&check_sudo_permissions($canuser, $pass)) {
3272 print DEBUG "validate_user: sudo failed\n";
3276 print DEBUG "validate_user: sudo passed\n";
3279 return $val == 2 ? ( $canuser, 1, 0 ) :
3280 $val == 1 ? ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3282 elsif ($canmode == 4) {
3283 # Attempt external authentication
3284 return &validate_external_user($canuser, $pass) ?
3285 ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3293 # validate_unix_user(user, password)
3294 # Returns 1 if a username and password are valid under unix, 0 if not,
3295 # or 2 if the account has expired.
3296 # Checks PAM if available, and falls back to reading the system password
3298 sub validate_unix_user
3302 $pam_username = $_[0];
3303 $pam_password = $_[1];
3304 eval "use Authen::PAM;";
3305 local $pamh = new Authen::PAM($config{'pam'}, $pam_username,
3308 local $pam_ret = $pamh->pam_authenticate();
3309 if ($pam_ret == PAM_SUCCESS()) {
3310 # Logged in OK .. make sure password hasn't expired
3311 local $acct_ret = $pamh->pam_acct_mgmt();
3312 if ($acct_ret == PAM_SUCCESS()) {
3313 $pamh->pam_open_session();
3316 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3317 $acct_ret == PAM_ACCT_EXPIRED()) {
3321 print STDERR "Unknown pam_acct_mgmt return value : $acct_ret\n";
3328 elsif ($config{'pam_only'}) {
3329 # Pam is not available, but configuration forces it's use!
3332 elsif ($config{'passwd_file'}) {
3333 # Check in a password file
3335 open(FILE, $config{'passwd_file'});
3336 if ($config{'passwd_file'} eq '/etc/security/passwd') {
3337 # Assume in AIX format
3340 if (/^\s*(\S+):/ && $1 eq $_[0]) {
3342 if (/^\s*password\s*=\s*(\S+)\s*$/) {
3343 $rv = $1 eq &password_crypt($_[1], $1) ?
3351 # Read the system password or shadow file
3353 local @l = split(/:/, $_, -1);
3354 local $u = $l[$config{'passwd_uindex'}];
3355 local $p = $l[$config{'passwd_pindex'}];
3357 $rv = $p eq &password_crypt($_[1], $p) ? 1 : 0;
3358 if ($config{'passwd_cindex'} ne '' && $rv) {
3359 # Password may have expired!
3360 local $c = $l[$config{'passwd_cindex'}];
3361 local $m = $l[$config{'passwd_mindex'}];
3362 local $day = time()/(24*60*60);
3363 if ($c =~ /^\d+/ && $m =~ /^\d+/ &&
3369 if ($p eq "" && $config{'passwd_blank'}) {
3370 # Force password change
3378 return $rv if ($rv);
3381 # Fallback option - check password returned by getpw*
3382 local @uinfo = getpwnam($_[0]);
3383 if ($uinfo[1] ne '' && &password_crypt($_[1], $uinfo[1]) eq $uinfo[1]) {
3387 return 0; # Totally failed
3390 # validate_external_user(user, pass)
3391 # Validate a user by passing the username and password to an external
3392 # squid-style authentication program
3393 sub validate_external_user
3395 return 0 if (!$config{'extauth'});
3397 local $str = "$_[0] $_[1]\n";
3398 syswrite(EXTAUTH, $str, length($str));
3399 local $resp = <EXTAUTH>;
3401 return $resp =~ /^OK/i ? 1 : 0;
3404 # can_user_login(username, no-append, host)
3405 # Checks if a user can login or not.
3406 # First return value is the username.
3407 # Second is 0 if cannot login, 1 if using Webmin pass, 2 if PAM, 3 if password
3408 # file, 4 if external.
3409 # Third is 1 if the user does not exist at all, 0 if he does.
3410 # Fourth is the Webmin username whose permissions apply, based on unixauth.
3411 # Fifth is a flag indicating if a sudo check is needed.
3414 local $uinfo = &get_user_details($_[0]);
3416 # See if this user exists in Unix and can be validated by the same
3417 # method as the unixauth webmin user
3418 local $realuser = $unixauth{$_[0]};
3422 eval { @uinfo = getpwnam($_[0]); }; # may fail on windows
3423 if (!$realuser && @uinfo) {
3424 # No unixauth entry for the username .. try his groups
3425 foreach my $ua (keys %unixauth) {
3426 if ($ua =~ /^\@(.*)$/) {
3427 if (&is_group_member(\@uinfo, $1)) {
3428 $realuser = $unixauth{$ua};
3434 if (!$realuser && @uinfo) {
3435 # Fall back to unix auth for all Unix users
3436 $realuser = $unixauth{"*"};
3438 if (!$realuser && $use_sudo && @uinfo) {
3439 # Allow login effectively as root, if sudo permits it
3443 if (!$realuser && !@uinfo && $config{'pamany'}) {
3444 # If the user completely doesn't exist, we can still allow
3445 # him to authenticate via PAM
3446 $realuser = $config{'pamany'};
3450 # For Usermin, always fall back to unix auth for any user,
3451 # so that later checks with domain added / removed are done.
3452 $realuser = $unixauth{"*"};
3454 return (undef, 0, 1, undef) if (!$realuser);
3455 local $uinfo = &get_user_details($realuser);
3456 return (undef, 0, 1, undef) if (!$uinfo);
3457 local $up = $uinfo->{'pass'};
3459 # Work out possible domain names from the hostname
3460 local @doms = ( $_[2] );
3461 if ($_[2] =~ /^([^\.]+)\.(\S+)$/) {
3465 if ($config{'user_mapping'} && !%user_mapping) {
3466 # Read the user mapping file
3468 open(MAPPING, $config{'user_mapping'});
3472 if (/^(\S+)\s+(\S+)/) {
3473 if ($config{'user_mapping_reverse'}) {
3474 $user_mapping{$1} = $2;
3477 $user_mapping{$2} = $1;
3484 # Check the user mapping file to see if there is an entry for the
3485 # user login in which specifies a new effective user
3487 foreach my $d (@doms) {
3488 $um ||= $user_mapping{"$_[0]\@$d"};
3490 $um ||= $user_mapping{$_[0]};
3491 if (defined($um) && ($_[1]&4) == 0) {
3492 # A mapping exists - use it!
3493 return &can_user_login($um, $_[1]+4, $_[2]);
3496 # Check if a user with the entered login and the domains appended
3497 # or prepended exists, and if so take it to be the effective user
3498 if (!@uinfo && $config{'domainuser'}) {
3499 # Try again with name.domain and name.firstpart
3500 local @firsts = map { /^([^\.]+)/; $1 } @doms;
3501 if (($_[1]&1) == 0) {
3503 foreach $a (@firsts, @doms) {
3504 foreach $p ("$_[0].${a}", "$_[0]-${a}",
3505 "${a}.$_[0]", "${a}-$_[0]",
3506 "$_[0]_${a}", "${a}_$_[0]") {
3507 local @vu = &can_user_login(
3508 $p, $_[1]+1, $_[2]);
3509 return @vu if ($vu[1]);
3515 # Check if the user entered a domain at the end of his username when
3516 # he really shouldn't have, and if so try without it
3517 if (!@uinfo && $config{'domainstrip'} &&
3518 $_[0] =~ /^(\S+)\@(\S+)$/ && ($_[1]&2) == 0) {
3519 local ($stripped, $dom) = ($1, $2);
3520 local @vu = &can_user_login($stripped, $_[1] + 2, $_[2]);
3521 return @vu if ($vu[1]);
3522 local @vu = &can_user_login($stripped, $_[1] + 2, $dom);
3523 return @vu if ($vu[1]);
3526 return ( undef, 0, 1, undef ) if (!@uinfo && !$pamany);
3529 if (scalar(@allowusers)) {
3530 # Only allow people on the allow list
3531 return ( undef, 0, 0, undef )
3532 if (!&users_match(\@uinfo, @allowusers));
3534 elsif (scalar(@denyusers)) {
3535 # Disallow people on the deny list
3536 return ( undef, 0, 0, undef )
3537 if (&users_match(\@uinfo, @denyusers));
3539 if ($config{'shells_deny'}) {
3541 open(SHELLS, $config{'shells_deny'});
3545 $found++ if ($_ eq $uinfo[8]);
3548 return ( undef, 0, 0, undef ) if (!$found);
3553 # PAM or passwd file authentication
3554 print DEBUG "can_user_login: Validate with PAM\n";
3555 return ( $_[0], $use_pam ? 2 : 3, 0, $realuser, $sudo );
3557 elsif ($up eq 'e') {
3558 # External authentication
3559 print DEBUG "can_user_login: Validate externally\n";
3560 return ( $_[0], 4, 0, $realuser, $sudo );
3563 # Fixed Webmin password
3564 print DEBUG "can_user_login: Validate by Webmin\n";
3565 return ( $_[0], 1, 0, $realuser, $sudo );
3568 elsif ($uinfo->{'pass'} eq 'x') {
3569 # Webmin user authenticated via PAM or password file
3570 return ( $_[0], $use_pam ? 2 : 3, 0, $_[0] );
3572 elsif ($uinfo->{'pass'} eq 'e') {
3573 # Webmin user authenticated externally
3574 return ( $_[0], 4, 0, $_[0] );
3577 # Normal Webmin user
3578 return ( $_[0], 1, 0, $_[0] );
3582 # the PAM conversation function for interactive logins
3585 $pam_conv_func_called++;
3592 $ans = $pam_username if ($code == PAM_PROMPT_ECHO_ON() );
3593 $ans = $pam_password if ($code == PAM_PROMPT_ECHO_OFF() );
3595 push @res, PAM_SUCCESS();
3598 push @res, PAM_SUCCESS();
3607 # get_socket_ip(handle, ipv6-flag)
3608 # Returns the local IP address of some connection, as both a string and in
3612 local ($fh, $ipv6) = @_;
3613 local $sn = getsockname($fh);
3614 return undef if (!$sn);
3615 return &get_address_ip($sn, $ipv6);
3618 # get_address_ip(address, ipv6-flag)
3619 # Given a sockaddr object in binary format, return the binary address, text
3620 # address and port number
3623 local ($sn, $ipv6) = @_;
3625 local ($p, $b) = unpack_sockaddr_in6($sn);
3626 return ($b, inet_ntop(Socket6::AF_INET6(), $b), $p);
3629 local ($p, $b) = unpack_sockaddr_in($sn);
3630 return ($b, inet_ntoa($b), $p);
3634 # get_socket_name(handle, ipv6-flag)
3635 # Returns the local hostname or IP address of some connection
3638 local ($fh, $ipv6) = @_;
3639 return $config{'host'} if ($config{'host'});
3640 local ($mybin, $myaddr) = &get_socket_ip($fh, $ipv6);
3641 if (!$get_socket_name_cache{$myaddr}) {
3643 if (!$config{'no_resolv_myname'}) {
3644 $myname = gethostbyaddr($mybin,
3645 $ipv6 ? Socket6::AF_INET6() : AF_INET);
3647 $myname ||= $myaddr;
3648 $get_socket_name_cache{$myaddr} = $myname;
3650 return $get_socket_name_cache{$myaddr};
3653 # run_login_script(username, sid, remoteip, localip)
3654 sub run_login_script
3656 if ($config{'login_script'}) {
3657 system($config{'login_script'}.
3658 " ".join(" ", map { quotemeta($_) || '""' } @_).
3659 " >/dev/null 2>&1 </dev/null");
3663 # run_logout_script(username, sid, remoteip, localip)
3664 sub run_logout_script
3666 if ($config{'logout_script'}) {
3667 system($config{'logout_script'}.
3668 " ".join(" ", map { quotemeta($_) || '""' } @_).
3669 " >/dev/null 2>&1 </dev/null");
3673 # close_all_sockets()
3674 # Closes all the main listening sockets
3675 sub close_all_sockets
3678 foreach $s (@socketfhs) {
3684 # Close all pipes for talking to sub-processes
3688 foreach $p (@passin) { close($p); }
3689 foreach $p (@passout) { close($p); }
3690 foreach $p (values %conversations) {
3691 if ($p->{'PAMOUTr'}) {
3692 close($p->{'PAMOUTr'});
3693 close($p->{'PAMINw'});
3698 # check_user_ip(user)
3699 # Returns 1 if some user is allowed to login from the accepting IP, 0 if not
3702 local ($username) = @_;
3703 local $uinfo = &get_user_details($username);
3704 return 1 if (!$uinfo);
3705 if ($uinfo->{'deny'} &&
3706 &ip_match($acptip, $localip, @{$uinfo->{'deny'}}) ||
3707 $uinfo->{'allow'} &&
3708 !&ip_match($acptip, $localip, @{$uinfo->{'allow'}})) {
3714 # check_user_time(user)
3715 # Returns 1 if some user is allowed to login at the current date and time
3718 local ($username) = @_;
3719 local $uinfo = &get_user_details($username);
3720 return 1 if (!$uinfo || !$uinfo->{'allowdays'} && !$uinfo->{'allowhours'});
3721 local @tm = localtime(time());
3722 if ($uinfo->{'allowdays'}) {
3723 # Make sure day is allowed
3724 return 0 if (&indexof($tm[6], @{$uinfo->{'allowdays'}}) < 0);
3726 if ($uinfo->{'allowhours'}) {
3727 # Make sure time is allowed
3728 local $m = $tm[2]*60+$tm[1];
3729 return 0 if ($m < $uinfo->{'allowhours'}->[0] ||
3730 $m > $uinfo->{'allowhours'}->[1]);
3735 # generate_random_id(password, [force-urandom])
3736 # Returns a random session ID number
3737 sub generate_random_id
3739 local ($pass, $force_urandom) = @_;
3741 if (!$bad_urandom) {
3742 # First try /dev/urandom, unless we have marked it as bad
3743 $SIG{ALRM} = "miniserv::urandom_timeout";
3745 if (open(RANDOM, "/dev/urandom")) {
3747 if (read(RANDOM, $tmpsid, 16) == 16) {
3748 $sid = lc(unpack('h*',$tmpsid));
3754 if (!$sid && !$force_urandom) {
3757 foreach $c (split(//, &unix_crypt($pass, substr($$, -2)))) {
3758 $sid += ord($c) * $mul;
3765 # handle_login(username, ok, expired, not-exists, password, [no-test-cookie])
3766 # Called from handle_session to either mark a user as logged in, or not
3769 local ($vu, $ok, $expired, $nonexist, $pass, $notest) = @_;
3770 $authuser = $vu if ($ok);
3772 # check if the test cookie is set
3773 if ($header{'cookie'} !~ /testing=1/ && $vu &&
3774 !$config{'no_testing_cookie'} && !$notest) {
3775 &http_error(500, "No cookies",
3776 "Your browser does not support cookies, ".
3777 "which are required for this web server to ".
3778 "work in session authentication mode");
3781 # check with main process for delay
3782 if ($config{'passdelay'} && $vu) {
3783 print DEBUG "handle_login: requesting delay vu=$vu acptip=$acptip ok=$ok\n";
3784 print $PASSINw "delay $vu $acptip $ok\n";
3785 <$PASSOUTr> =~ /(\d+) (\d+)/;
3788 print DEBUG "handle_login: delay=$1 blocked=$2\n";
3791 if ($ok && (!$expired ||
3792 $config{'passwd_mode'} == 1)) {
3793 # Logged in OK! Tell the main process about
3795 local $sid = &generate_random_id($pass);
3796 print DEBUG "handle_login: sid=$sid\n";
3797 print $PASSINw "new $sid $authuser $acptip\n";
3799 # Run the post-login script, if any
3800 &run_login_script($authuser, $sid,
3803 # Check for a redirect URL for the user
3804 local $rurl = &login_redirect($authuser, $pass, $host);
3805 print DEBUG "handle_login: redirect URL rurl=$rurl\n";
3807 # Got one .. go to it
3808 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3809 &write_data("Date: $datestr\r\n");
3810 &write_data("Server: $config{'server'}\r\n");
3811 &write_data("Location: $rurl\r\n");
3812 &write_keep_alive(0);
3813 &write_data("\r\n");
3814 &log_request($acpthost, $authuser, $reqline, 302, 0);
3817 # Set cookie and redirect to originally requested page
3818 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3819 &write_data("Date: $datestr\r\n");
3820 &write_data("Server: $config{'server'}\r\n");
3821 local $ssl = $use_ssl || $config{'inetd_ssl'};
3822 $portstr = $port == 80 && !$ssl ? "" :
3823 $port == 443 && $ssl ? "" : ":$port";
3824 $prot = $ssl ? "https" : "http";
3825 local $sec = $ssl ? "; secure" : "";
3826 #$sec .= "; httpOnly";
3827 if ($in{'page'} !~ /^\/[A-Za-z0-9\/\.\-\_]+$/) {
3828 # Make redirect URL safe
3832 &write_data("Set-Cookie: $sidname=$sid; path=/; expires=\"Thu, 31-Dec-2037 00:00:00\"$sec\r\n");
3835 &write_data("Set-Cookie: $sidname=$sid; path=/$sec\r\n");
3837 &write_data("Location: $prot://$host$portstr$in{'page'}\r\n");
3838 &write_keep_alive(0);
3839 &write_data("\r\n");
3840 &log_request($acpthost, $authuser, $reqline, 302, 0);
3841 syslog("info", "%s", "Successful login as $authuser from $acpthost") if ($use_syslog);
3842 &write_login_utmp($authuser, $acpthost);
3846 elsif ($ok && $expired &&
3847 ($config{'passwd_mode'} == 2 || $expired == 2)) {
3848 # Login was ok, but password has expired or was temporary. Need
3849 # to force display of password change form.
3852 $querystring = "&user=".&urlize($vu).
3854 "&expired=".$expired;
3857 $page = $config{'password_form'};
3859 $miniserv_internal = 2;
3860 syslog("crit", "%s",
3861 "Expired login as $vu ".
3862 "from $acpthost") if ($use_syslog);
3865 # Login failed, or password has expired. The login form will be
3866 # displayed again by later code
3868 $request_uri = $in{'page'};
3869 $already_session_id = undef;
3871 $authuser = $baseauthuser = undef;
3872 syslog("crit", "%s",
3873 ($nonexist ? "Non-existent" :
3874 $expired ? "Expired" : "Invalid").
3875 " login as $vu from $acpthost")
3881 # write_login_utmp(user, host)
3882 # Record the login by some user in utmp
3883 sub write_login_utmp
3886 # Write utmp record for login
3887 %utmp = ( 'ut_host' => $_[1],
3888 'ut_time' => time(),
3890 'ut_type' => 7, # user process
3891 'ut_pid' => $main_process_id,
3892 'ut_line' => $config{'pam'},
3894 if (defined(&User::Utmp::putut)) {
3895 User::Utmp::putut(\%utmp);
3898 User::Utmp::pututline(\%utmp);
3903 # write_logout_utmp(user, host)
3904 # Record the logout by some user in utmp
3905 sub write_logout_utmp
3908 # Write utmp record for logout
3909 %utmp = ( 'ut_host' => $_[1],
3910 'ut_time' => time(),
3912 'ut_type' => 8, # dead process
3913 'ut_pid' => $main_process_id,
3914 'ut_line' => $config{'pam'},
3916 if (defined(&User::Utmp::putut)) {
3917 User::Utmp::putut(\%utmp);
3920 User::Utmp::pututline(\%utmp);
3925 # pam_conversation_process(username, write-pipe, read-pipe)
3926 # This function is called inside a sub-process to communicate with PAM. It sends
3927 # questions down one pipe, and reads responses from another
3928 sub pam_conversation_process
3930 local ($user, $writer, $reader) = @_;
3931 $miniserv::pam_conversation_process_writer = $writer;
3932 $miniserv::pam_conversation_process_reader = $reader;
3933 eval "use Authen::PAM;";
3934 local $convh = new Authen::PAM(
3935 $config{'pam'}, $user, \&miniserv::pam_conversation_process_func);
3936 local $pam_ret = $convh->pam_authenticate();
3937 if ($pam_ret == PAM_SUCCESS()) {
3938 local $acct_ret = $convh->pam_acct_mgmt();
3939 if ($acct_ret == PAM_SUCCESS()) {
3940 $convh->pam_open_session();
3941 print $writer "x2 $user 1 0 0\n";
3943 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3944 $acct_ret == PAM_ACCT_EXPIRED()) {
3945 print $writer "x2 $user 1 1 0\n";
3948 print $writer "x0 Unknown PAM account status $acct_ret\n";
3952 print $writer "x2 $user 0 0 0\n";
3957 # pam_conversation_process_func(type, message, [type, message, ...])
3958 # A pipe that talks to both PAM and the master process
3959 sub pam_conversation_process_func
3962 select($miniserv::pam_conversation_process_writer); $| = 1; select(STDOUT);
3964 local ($type, $msg) = (shift, shift);
3966 local $ok = (print $miniserv::pam_conversation_process_writer "$type $msg\n");
3967 print $miniserv::pam_conversation_process_writer "\n";
3968 local $answer = <$miniserv::pam_conversation_process_reader>;
3969 $answer =~ s/\r|\n//g;
3970 push(@rv, PAM_SUCCESS(), $answer);
3972 push(@rv, PAM_SUCCESS());
3977 # Returns 4 new pipe file handles
3980 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3982 local %taken = ( (map { $_, 1 } @passin),
3983 (map { $_->{'PASSINr'} } values %conversations) );
3984 for($p=0; $taken{"PASSINr$p"}; $p++) { }
3985 $PASSINr = "PASSINr$p";
3986 $PASSINw = "PASSINw$p";
3987 $PASSOUTr = "PASSOUTr$p";
3988 $PASSOUTw = "PASSOUTw$p";
3989 pipe($PASSINr, $PASSINw);
3990 pipe($PASSOUTr, $PASSOUTw);
3991 select($PASSINw); $| = 1;
3992 select($PASSINr); $| = 1;
3993 select($PASSOUTw); $| = 1;
3994 select($PASSOUTw); $| = 1;
3996 return ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3999 # recv_pam_question(&conv, fd)
4000 # Reads one PAM question from the sub-process, and sends it to the HTTP handler.
4001 # Returns 0 if the conversation is over, 1 if not.
4002 sub recv_pam_question
4004 local ($conf, $fh) = @_;
4005 local $pr = $conf->{'PAMOUTr'};
4006 select($pr); $| = 1; select(STDOUT);
4007 local $line = <$pr>;
4008 $line =~ s/\r|\n//g;
4011 $line =~ s/\r|\n//g;
4013 $conf->{'last'} = time();
4016 print $fh "0 PAM conversation error\n";
4020 local ($type, $msg) = split(/\s+/, $line, 2);
4021 if ($type =~ /^x(\d+)/) {
4022 # Pass this status code through
4023 print $fh "$1 $msg\n";
4024 return $1 == 2 || $1 == 0 ? 0 : 1;
4026 elsif ($type == PAM_PROMPT_ECHO_ON()) {
4028 print $fh "1 $msg\n";
4031 elsif ($type == PAM_PROMPT_ECHO_OFF()) {
4033 print $fh "3 $msg\n";
4036 elsif ($type == PAM_ERROR_MSG() || $type == PAM_TEXT_INFO()) {
4037 # A message that does not require a response
4038 print $fh "4 $msg\n";
4043 print $fh "0 Unknown PAM message type $type\n";
4049 # send_pam_answer(&conv, answer)
4050 # Sends a response from the user to the PAM sub-process
4053 local ($conf, $answer) = @_;
4054 local $pw = $conf->{'PAMINw'};
4055 $conf->{'last'} = time();
4056 print $pw "$answer\n";
4059 # end_pam_conversation(&conv)
4060 # Clean up PAM conversation pipes and processes
4061 sub end_pam_conversation
4064 kill('KILL', $conv->{'pid'}) if ($conv->{'pid'});
4065 if ($conv->{'PAMINr'}) {
4066 close($conv->{'PAMINr'});
4067 close($conv->{'PAMOUTr'});
4068 close($conv->{'PAMINw'});
4069 close($conv->{'PAMOUTw'});
4071 delete($conversations{$conv->{'cid'}});
4074 # get_ipkeys(&miniserv)
4075 # Returns a list of IP address to key file mappings from a miniserv.conf entry
4079 foreach $k (keys %{$_[0]}) {
4080 if ($k =~ /^ipkey_(\S+)/) {
4081 local $ipkey = { 'ips' => [ split(/,/, $1) ],
4082 'key' => $_[0]->{$k},
4083 'index' => scalar(@rv) };
4084 $ipkey->{'cert'} = $_[0]->{'ipcert_'.$1};
4091 # create_ssl_context(keyfile, [certfile])
4092 sub create_ssl_context
4094 local ($keyfile, $certfile) = @_;
4096 eval { $ssl_ctx = Net::SSLeay::new_x_ctx() };
4097 $ssl_ctx ||= Net::SSLeay::CTX_new();
4098 $ssl_ctx || die "Failed to create SSL context : $!";
4099 if ($client_certs) {
4100 Net::SSLeay::CTX_load_verify_locations(
4101 $ssl_ctx, $config{'ca'}, "");
4102 Net::SSLeay::CTX_set_verify(
4103 $ssl_ctx, &Net::SSLeay::VERIFY_PEER, \&verify_client);
4105 if ($config{'extracas'}) {
4107 foreach $p (split(/\s+/, $config{'extracas'})) {
4108 Net::SSLeay::CTX_load_verify_locations(
4113 Net::SSLeay::CTX_use_RSAPrivateKey_file(
4115 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL key $keyfile";
4116 Net::SSLeay::CTX_use_certificate_file(
4117 $ssl_ctx, $certfile || $keyfile,
4118 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL cert $certfile";
4123 # ssl_connection_for_ip(socket, ipv6-flag)
4124 # Returns a new SSL connection object for some socket, or undef if failed
4125 sub ssl_connection_for_ip
4127 local ($sock, $ipv6) = @_;
4128 local $sn = getsockname($sock);
4130 print STDERR "Failed to get address for socket $sock\n";
4133 local (undef, $myip, undef) = &get_address_ip($sn, $ipv6);
4134 local $ssl_ctx = $ssl_contexts{$myip} || $ssl_contexts{"*"};
4135 local $ssl_con = Net::SSLeay::new($ssl_ctx);
4136 if ($config{'ssl_cipher_list'}) {
4137 # Force use of ciphers
4138 eval "Net::SSLeay::set_cipher_list(
4139 \$ssl_con, \$config{'ssl_cipher_list'})";
4141 print STDERR "SSL cipher $config{'ssl_cipher_list'} failed : ",
4147 Net::SSLeay::set_fd($ssl_con, fileno($sock));
4148 if (!Net::SSLeay::accept($ssl_con)) {
4149 print STDERR "Failed to initialize SSL connection\n";
4155 # login_redirect(username, password, host)
4156 # Calls the login redirect script (if configured), which may output a URL to
4157 # re-direct a user to after logging in.
4160 return undef if (!$config{'login_redirect'});
4161 local $quser = quotemeta($_[0]);
4162 local $qpass = quotemeta($_[1]);
4163 local $qhost = quotemeta($_[2]);
4164 local $url = `$config{'login_redirect'} $quser $qpass $qhost`;
4169 # reload_config_file()
4170 # Re-read %config, and call post-config actions
4171 sub reload_config_file
4173 &log_error("Reloading configuration");
4174 %config = &read_config_file($config_file);
4175 &update_vital_config();
4178 &build_config_mappings();
4179 &read_webmin_crons();
4181 if ($config{'session'}) {
4182 dbmclose(%sessiondb);
4183 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
4187 # read_config_file(file)
4188 # Reads the given config file, and returns a hash of values
4189 sub read_config_file
4192 open(CONF, $_[0]) || die "Failed to open config file $_[0] : $!";
4195 if (/^#/ || !/\S/) { next; }
4197 $name = $1; $val = $2;
4198 $name =~ s/^\s+//g; $name =~ s/\s+$//g;
4199 $val =~ s/^\s+//g; $val =~ s/\s+$//g;
4206 # update_vital_config()
4207 # Updates %config with defaults, and dies if something vital is missing
4208 sub update_vital_config
4210 my %vital = ("port", 80,
4212 "server", "MiniServ/0.01",
4213 "index_docs", "index.html index.htm index.cgi index.php",
4214 "addtype_html", "text/html",
4215 "addtype_txt", "text/plain",
4216 "addtype_gif", "image/gif",
4217 "addtype_jpg", "image/jpeg",
4218 "addtype_jpeg", "image/jpeg",
4219 "realm", "MiniServ",
4220 "session_login", "/session_login.cgi",
4221 "pam_login", "/pam_login.cgi",
4222 "password_form", "/password_form.cgi",
4223 "password_change", "/password_change.cgi",
4227 "unauth", "^/unauthenticated/ ^/robots.txt\$ ^[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\$ ^/robots.txt\$",
4229 "expires", 7*24*60*60,
4230 "pam_test_user", "root",
4231 "precache", "lang/en */lang/en",
4233 foreach my $v (keys %vital) {
4235 if ($vital{$v} eq "") {
4236 die "Missing config option $v";
4238 $config{$v} = $vital{$v};
4241 if (!$config{'sessiondb'}) {
4242 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4243 $config{'sessiondb'} = "$1/sessiondb";
4245 if (!$config{'errorlog'}) {
4246 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
4247 $config{'errorlog'} = "$1/miniserv.error";
4249 if (!$config{'tempbase'}) {
4250 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4251 $config{'tempbase'} = "$1/cgitemp";
4253 if (!$config{'blockedfile'}) {
4254 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4255 $config{'blockedfile'} = "$1/blocked";
4257 if (!$config{'webmincron_dir'}) {
4258 $config_file =~ /^(.*)\/[^\/]+$/;
4259 $config{'webmincron_dir'} = "$1/webmincron/crons";
4261 if (!$config{'webmincron_last'}) {
4262 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
4263 $config{'webmincron_last'} = "$1/miniserv.lastcrons";
4265 if (!$config{'webmincron_wrapper'}) {
4266 $config{'webmincron_wrapper'} = $config{'root'}.
4267 "/webmincron/webmincron.pl";
4272 # Fills the %users and %certs hashes from the users file in %config
4281 undef(%lastchanges);
4284 if ($config{'userfile'}) {
4285 open(USERS, $config{'userfile'});
4288 local @user = split(/:/, $_, -1);
4289 $users{$user[0]} = $user[1];
4290 $certs{$user[0]} = $user[3] if ($user[3]);
4291 if ($user[4] =~ /^allow\s+(.*)/) {
4292 $allow{$user[0]} = $config{'alwaysresolve'} ?
4293 [ split(/\s+/, $1) ] :
4294 [ &to_ipaddress(split(/\s+/, $1)) ];
4296 elsif ($user[4] =~ /^deny\s+(.*)/) {
4297 $deny{$user[0]} = $config{'alwaysresolve'} ?
4298 [ split(/\s+/, $1) ] :
4299 [ &to_ipaddress(split(/\s+/, $1)) ];
4301 if ($user[5] =~ /days\s+(\S+)/) {
4302 $allowdays{$user[0]} = [ split(/,/, $1) ];
4304 if ($user[5] =~ /hours\s+(\d+)\.(\d+)-(\d+).(\d+)/) {
4305 $allowhours{$user[0]} = [ $1*60+$2, $3*60+$4 ];
4307 $lastchanges{$user[0]} = $user[6];
4308 $nochange{$user[0]} = $user[9];
4309 $temppass{$user[0]} = $user[10];
4314 # Test user DB, if configured
4315 if ($config{'userdb'}) {
4316 my $dbh = &connect_userdb($config{'userdb'});
4318 print STDERR "Failed to open users database : $dbh\n"
4321 &disconnect_userdb($config{'userdb'}, $dbh);
4326 # get_user_details(username)
4327 # Returns a hash ref of user details, either from config files or the user DB
4328 sub get_user_details
4330 my ($username) = @_;
4331 if (exists($users{$username})) {
4333 return { 'name' => $username,
4334 'pass' => $users{$username},
4335 'certs' => $certs{$username},
4336 'allow' => $allow{$username},
4337 'deny' => $deny{$username},
4338 'allowdays' => $allowdays{$username},
4339 'allowhours' => $allowhours{$username},
4340 'lastchanges' => $lastchanges{$username},
4341 'nochange' => $nochange{$username},
4342 'temppass' => $temppass{$username},
4343 'preroot' => $config{'preroot_'.$username},
4346 if ($config{'userdb'}) {
4347 # Try querying user database
4348 if (exists($get_user_details_cache{$username})) {
4350 return $get_user_details_cache{$username};
4352 print DEBUG "get_user_details: Connecting to user database\n";
4353 my ($dbh, $proto, $prefix, $args) = &connect_userdb($config{'userdb'});
4357 print DEBUG "get_user_details: Failed : $dbh\n";
4358 print STDERR "Failed to connect to user database : $dbh\n";
4360 elsif ($proto eq "mysql" || $proto eq "postgresql") {
4361 # Fetch user ID and password with SQL
4362 print DEBUG "get_user_details: Looking for $username in SQL\n";
4363 my $cmd = $dbh->prepare(
4364 "select id,pass from webmin_user where name = ?");
4365 if (!$cmd || !$cmd->execute($username)) {
4366 print STDERR "Failed to lookup user : ",
4370 my ($id, $pass) = $cmd->fetchrow();
4373 &disconnect_userdb($config{'userdb'}, $dbh);
4374 $get_user_details_cache{$username} = undef;
4375 print DEBUG "get_user_details: User not found\n";
4378 print DEBUG "get_user_details: id=$id pass=$pass\n";
4380 # Fetch attributes and add to user object
4381 print DEBUG "get_user_details: finding user attributes\n";
4382 my $cmd = $dbh->prepare(
4383 "select attr,value from webmin_user_attr where id = ?");
4384 if (!$cmd || !$cmd->execute($id)) {
4385 print STDERR "Failed to lookup user attrs : ",
4389 $user = { 'name' => $username,
4392 'proto' => $proto };
4393 while(my ($attr, $value) = $cmd->fetchrow()) {
4394 $attrs{$attr} = $value;
4398 elsif ($proto eq "ldap") {
4399 # Fetch user DN with LDAP
4400 print DEBUG "get_user_details: Looking for $username in LDAP\n";
4401 my $rv = $dbh->search(
4403 filter => '(&(cn='.$username.')(objectClass='.
4404 $args->{'userclass'}.'))',
4406 if (!$rv || $rv->code) {
4407 print STDERR "Failed to lookup user : ",
4408 ($rv ? $rv->error : "Unknown error"),"\n";
4411 my ($u) = $rv->all_entries();
4413 &disconnect_userdb($config{'userdb'}, $dbh);
4414 $get_user_details_cache{$username} = undef;
4415 print DEBUG "get_user_details: User not found\n";
4419 # Extract attributes
4420 my $pass = $u->get_value('webminPass');
4421 $user = { 'name' => $username,
4424 'proto' => $proto };
4425 foreach my $la ($u->get_value('webminAttr')) {
4426 my ($attr, $value) = split(/=/, $la, 2);
4427 $attrs{$attr} = $value;
4431 # Convert DB attributes into user object fields
4433 print DEBUG "get_user_details: got ",scalar(keys %attrs),
4435 $user->{'certs'} = $attrs{'cert'};
4436 if ($attrs{'allow'}) {
4437 $user->{'allow'} = $config{'alwaysresolve'} ?
4438 [ split(/\s+/, $attrs{'allow'}) ] :
4439 [ &to_ipaddress(split(/\s+/,$attrs{'allow'})) ];
4441 if ($attrs{'deny'}) {
4442 $user->{'deny'} = $config{'alwaysresolve'} ?
4443 [ split(/\s+/, $attrs{'deny'}) ] :
4444 [ &to_ipaddress(split(/\s+/,$attrs{'deny'})) ];
4446 if ($attrs{'days'}) {
4447 $user->{'allowdays'} = [ split(/,/, $attrs{'days'}) ];
4449 if ($attrs{'hoursfrom'} && $attrs{'hoursto'}) {
4450 my ($hf, $mf) = split(/\./, $attrs{'hoursfrom'});
4451 my ($ht, $mt) = split(/\./, $attrs{'hoursto'});
4452 $user->{'allowhours'} = [ $hf*60+$ht, $ht*60+$mt ];
4454 $user->{'lastchanges'} = $attrs{'lastchange'};
4455 $user->{'nochange'} = $attrs{'nochange'};
4456 $user->{'temppass'} = $attrs{'temppass'};
4457 $user->{'preroot'} = $attrs{'theme'};
4459 &disconnect_userdb($config{'userdb'}, $dbh);
4460 $get_user_details_cache{$user->{'name'}} = $user;
4466 # find_user_by_cert(cert)
4467 # Returns a username looked up by certificate
4468 sub find_user_by_cert
4470 my ($peername) = @_;
4471 my $peername2 = $peername;
4472 $peername2 =~ s/Email=/emailAddress=/ || $peername2 =~ s/emailAddress=/Email=/;
4474 # First check users in local files
4475 foreach my $username (keys %certs) {
4476 if ($certs{$username} eq $peername ||
4477 $certs{$username} eq $peername2) {
4483 if ($config{'userdb'}) {
4484 my ($dbh, $proto) = &connect_userdb($config{'userdb'});
4488 elsif ($proto eq "mysql" || $proto eq "postgresql") {
4490 my $cmd = $dbh->prepare("select webmin_user.name from webmin_user,webmin_user_attr where webmin_user.id = webmin_user_attr.id and webmin_user_attr.attr = 'cert' and webmin_user_attr.value = ?");
4491 return undef if (!$cmd);
4492 foreach my $p ($peername, $peername2) {
4494 if ($cmd->execute($p)) {
4495 ($username) = $cmd->fetchrow();
4498 return $username if ($username);
4501 elsif ($proto eq "ldap") {
4503 my $rv = $dbh->search(
4505 filter => '(objectClass='.
4506 $args->{'userclass'}.')',
4508 attrs => [ 'cn', 'webminAttr' ]);
4509 if ($rv && !$rv->code) {
4510 foreach my $u ($rv->all_entries) {
4511 my @attrs = $u->get_value('webminAttr');
4512 foreach my $la (@attrs) {
4513 my ($attr, $value) = split(/=/, $la, 2);
4514 if ($attr eq "cert" &&
4515 ($value eq $peername ||
4516 $value eq $peername2)) {
4517 return $u->get_value('cn');
4527 # connect_userdb(string)
4528 # Returns a handle for talking to a user database - may be a DBI or LDAP handle.
4529 # On failure returns an error message string. In an array context, returns the
4530 # protocol type too.
4534 my ($proto, $user, $pass, $host, $prefix, $args) = &split_userdb_string($str);
4535 if ($proto eq "mysql") {
4536 # Connect to MySQL with DBI
4537 my $drh = eval "use DBI; DBI->install_driver('mysql');";
4538 $drh || return $text{'sql_emysqldriver'};
4539 my ($host, $port) = split(/:/, $host);
4540 my $cstr = "database=$prefix;host=$host";
4541 $cstr .= ";port=$port" if ($port);
4542 print DEBUG "connect_userdb: Connecting to MySQL $cstr as $user\n";
4543 my $dbh = $drh->connect($cstr, $user, $pass, { });
4544 $dbh || return &text('sql_emysqlconnect', $drh->errstr);
4545 print DEBUG "connect_userdb: Connected OK\n";
4546 return wantarray ? ($dbh, $proto, $prefix, $args) : $dbh;
4548 elsif ($proto eq "postgresql") {
4549 # Connect to PostgreSQL with DBI
4550 my $drh = eval "use DBI; DBI->install_driver('Pg');";
4551 $drh || return $text{'sql_epostgresqldriver'};
4552 my ($host, $port) = split(/:/, $host);
4553 my $cstr = "dbname=$prefix;host=$host";
4554 $cstr .= ";port=$port" if ($port);
4555 print DEBUG "connect_userdb: Connecting to PostgreSQL $cstr as $user\n";
4556 my $dbh = $drh->connect($cstr, $user, $pass);
4557 $dbh || return &text('sql_epostgresqlconnect', $drh->errstr);
4558 print DEBUG "connect_userdb: Connected OK\n";
4559 return wantarray ? ($dbh, $proto, $prefix, $args) : $dbh;
4561 elsif ($proto eq "ldap") {
4562 # Connect with perl LDAP module
4563 eval "use Net::LDAP";
4564 $@ && return $text{'sql_eldapdriver'};
4565 my ($host, $port) = split(/:/, $host);
4566 my $scheme = $args->{'scheme'} || 'ldap';
4568 $port = $scheme eq 'ldaps' ? 636 : 389;
4570 my $ldap = Net::LDAP->new($host,
4572 'scheme' => $scheme);
4573 $ldap || return &text('sql_eldapconnect', $host);
4575 if ($args->{'tls'}) {
4576 # Switch to TLS mode
4577 eval { $mesg = $ldap->start_tls(); };
4578 if ($@ || !$mesg || $mesg->code) {
4579 return &text('sql_eldaptls',
4580 $@ ? $@ : $mesg ? $mesg->error : "Unknown error");
4583 # Login to the server
4585 $mesg = $ldap->bind(dn => $user, password => $pass);
4588 $mesg = $ldap->bind(dn => $user, anonymous => 1);
4590 if (!$mesg || $mesg->code) {
4591 return &text('sql_eldaplogin', $user,
4592 $mesg ? $mesg->error : "Unknown error");
4594 return wantarray ? ($ldap, $proto, $prefix, $args) : $ldap;
4597 return "Unknown protocol $proto";
4601 # split_userdb_string(string)
4602 # Converts a string like mysql://user:pass@host/db into separate parts
4603 sub split_userdb_string
4606 if ($str =~ /^([a-z]+):\/\/([^:]*):([^\@]*)\@([a-z0-9\.\-\_]+)\/([^\?]+)(\?(.*))?$/) {
4607 my ($proto, $user, $pass, $host, $prefix, $argstr) =
4608 ($1, $2, $3, $4, $5, $7);
4609 my %args = map { split(/=/, $_, 2) } split(/\&/, $argstr);
4610 return ($proto, $user, $pass, $host, $prefix, \%args);
4615 # disconnect_userdb(string, &handle)
4616 # Closes a handle opened by connect_userdb
4617 sub disconnect_userdb
4620 if ($str =~ /^(mysql|postgresql):/) {
4624 elsif ($str =~ /^ldap:/) {
4631 # Fills %mime with entries from file in %config and extra settings in %config
4635 if ($config{"mimetypes"} ne "") {
4636 open(MIME, $config{"mimetypes"});
4639 if (/^(\S+)\s+(.*)$/) {
4641 my @exts = split(/\s+/, $2);
4642 foreach my $ext (@exts) {
4643 $mime{$ext} = $type;
4649 foreach my $k (keys %config) {
4650 if ($k !~ /^addtype_(.*)$/) { next; }
4651 $mime{$1} = $config{$k};
4655 # build_config_mappings()
4656 # Build the anonymous access list, IP access list, unauthenticated URLs list,
4657 # redirect mapping and allow and deny lists from %config
4658 sub build_config_mappings
4660 # build anonymous access list
4662 foreach my $a (split(/\s+/, $config{'anonymous'})) {
4663 if ($a =~ /^([^=]+)=(\S+)$/) {
4664 $anonymous{$1} = $2;
4668 # build IP access list
4670 foreach my $a (split(/\s+/, $config{'ipaccess'})) {
4671 if ($a =~ /^([^=]+)=(\S+)$/) {
4676 # build unauthenticated URLs list
4677 @unauth = split(/\s+/, $config{'unauth'});
4679 # build redirect mapping
4681 foreach my $r (split(/\s+/, $config{'redirect'})) {
4682 if ($r =~ /^([^=]+)=(\S+)$/) {
4687 # build prefixes to be stripped
4688 undef(@strip_prefix);
4689 foreach my $r (split(/\s+/, $config{'strip_prefix'})) {
4690 push(@strip_prefix, $r);
4693 # Init allow and deny lists
4694 @deny = split(/\s+/, $config{"deny"});
4695 @deny = &to_ipaddress(@deny) if (!$config{'alwaysresolve'});
4696 @allow = split(/\s+/, $config{"allow"});
4697 @allow = &to_ipaddress(@allow) if (!$config{'alwaysresolve'});
4700 if ($config{'allowusers'}) {
4701 @allowusers = split(/\s+/, $config{'allowusers'});
4703 elsif ($config{'denyusers'}) {
4704 @denyusers = split(/\s+/, $config{'denyusers'});
4707 # Build list of unixauth mappings
4709 foreach my $ua (split(/\s+/, $config{'unixauth'})) {
4710 if ($ua =~ /^(\S+)=(\S+)$/) {
4714 $unixauth{"*"} = $ua;
4718 # Build list of non-session-auth pages
4719 undef(%sessiononly);
4720 foreach my $sp (split(/\s+/, $config{'sessiononly'})) {
4721 $sessiononly{$sp} = 1;
4724 # Build list of logout times
4725 undef(@logouttimes);
4726 foreach my $a (split(/\s+/, $config{'logouttimes'})) {
4727 if ($a =~ /^([^=]+)=(\S+)$/) {
4728 push(@logouttimes, [ $1, $2 ]);
4731 push(@logouttimes, [ undef, $config{'logouttime'} ]);
4733 # Build list of DAV pathss
4735 foreach my $d (split(/\s+/, $config{'davpaths'})) {
4736 push(@davpaths, $d);
4738 @davusers = split(/\s+/, $config{'dav_users'});
4740 # Mobile agent substrings and hostname prefixes
4741 @mobile_agents = split(/\t+/, $config{'mobile_agents'});
4742 @mobile_prefixes = split(/\s+/, $config{'mobile_prefixes'});
4746 if ($config{'debug'}) {
4747 open(DEBUG, ">>$config{'debug'}");
4750 open(DEBUG, ">/dev/null");
4753 # Reset cache of sudo checks
4757 # is_group_member(&uinfo, groupname)
4758 # Returns 1 if some user is a primary or secondary member of a group
4761 local ($uinfo, $group) = @_;
4762 local @ginfo = getgrnam($group);
4763 return 0 if (!@ginfo);
4764 return 1 if ($ginfo[2] == $uinfo->[3]); # primary member
4765 foreach my $m (split(/\s+/, $ginfo[3])) {
4766 return 1 if ($m eq $uinfo->[0]);
4771 # prefix_to_mask(prefix)
4772 # Converts a number like 24 to a mask like 255.255.255.0
4775 return $_[0] >= 24 ? "255.255.255.".(256-(2 ** (32-$_[0]))) :
4776 $_[0] >= 16 ? "255.255.".(256-(2 ** (24-$_[0]))).".0" :
4777 $_[0] >= 8 ? "255.".(256-(2 ** (16-$_[0]))).".0.0" :
4778 (256-(2 ** (8-$_[0]))).".0.0.0";
4781 # get_logout_time(user, session-id)
4782 # Given a username, returns the idle time before he will be logged out
4785 local ($user, $sid) = @_;
4786 if (!defined($logout_time_cache{$user,$sid})) {
4788 foreach my $l (@logouttimes) {
4789 if ($l->[0] =~ /^\@(.*)$/) {
4790 # Check group membership
4791 local @uinfo = getpwnam($user);
4792 if (@uinfo && &is_group_member(\@uinfo, $1)) {
4796 elsif ($l->[0] =~ /^\//) {
4797 # Check file contents
4798 open(FILE, $l->[0]);
4815 if ($l->[0] eq $user) {
4819 last if (defined($time));
4821 $logout_time_cache{$user,$sid} = $time;
4823 return $logout_time_cache{$user,$sid};
4826 # password_crypt(password, salt)
4827 # If the salt looks like MD5 and we have a library for it, perform MD5 hashing
4828 # of a password. Otherwise, do Unix crypt.
4831 local ($pass, $salt) = @_;
4832 if ($salt =~ /^\$1\$/ && $use_md5) {
4833 return &encrypt_md5($pass, $salt);
4836 return &unix_crypt($pass, $salt);
4840 # unix_crypt(password, salt)
4841 # Performs standard Unix hashing for a password
4844 local ($pass, $salt) = @_;
4845 if ($use_perl_crypt) {
4846 return Crypt::UnixCrypt::crypt($pass, $salt);
4849 return crypt($pass, $salt);
4853 # handle_dav_request(davpath)
4854 # Pass a request on to the Net::DAV::Server module
4855 sub handle_dav_request
4858 eval "use Filesys::Virtual::Plain";
4859 eval "use Net::DAV::Server";
4860 eval "use HTTP::Request";
4861 eval "use HTTP::Headers";
4863 if ($Net::DAV::Server::VERSION eq '1.28' && $config{'dav_nolock'}) {
4864 delete $Net::DAV::Server::implemented{lock};
4865 delete $Net::DAV::Server::implemented{unlock};
4868 # Read in request data
4869 if (!$posted_data) {
4870 local $clen = $header{"content-length"};
4871 while(length($posted_data) < $clen) {
4872 $buf = &read_data($clen - length($posted_data));
4873 if (!length($buf)) {
4874 &http_error(500, "Failed to read POST request");
4876 $posted_data .= $buf;
4880 # For subsequent logging
4881 open(MINISERVLOG, ">>$config{'logfile'}");
4885 local @u = getpwnam($authuser);
4886 if ($config{'dav_remoteuser'} && !$< && $validated) {
4889 $( = $u[3]; $) = "$u[3] $u[3]";
4890 ($>, $<) = ($u[2], $u[2]);
4892 if ($config{'dav_root'} eq '*') {
4897 &http_error(500, "Unix user $authuser does not exist");
4901 $root ||= $config{'dav_root'};
4904 # Check if this user can use DAV
4906 &users_match(\@u, @davusers) ||
4907 &http_error(500, "You are not allowed to access DAV");
4911 my $filesys = Filesys::Virtual::Plain->new({root_path => $root});
4912 my $webdav = Net::DAV::Server->new();
4913 $webdav->filesys($filesys);
4915 # Make up a request object, and feed to DAV
4916 local $ho = HTTP::Headers->new;
4917 foreach my $h (keys %header) {
4918 next if (lc($h) eq "connection");
4919 $ho->header($h => $header{$h});
4922 $request_uri =~ s/^\Q$path\E//;
4923 $request_uri = "/" if ($request_uri eq "");
4925 my $request = HTTP::Request->new($method, $request_uri, $ho,
4927 if ($config{'dav_debug'}) {
4928 print STDERR "DAV request :\n";
4929 print STDERR "---------------------------------------------\n";
4930 print STDERR $request->as_string();
4931 print STDERR "---------------------------------------------\n";
4933 my $response = $webdav->run($request);
4935 # Send back the reply
4936 &write_data("HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n");
4937 local $content = $response->content();
4939 $content =~ s|href>/(.+)<|href>$path/$1<|g;
4940 $content =~ s|href>/<|href>$path<|g;
4942 foreach my $h ($response->header_field_names) {
4943 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4944 &write_data("$h: ",$response->header($h),"\r\n");
4946 &write_data("Content-length: ",length($content),"\r\n");
4947 local $rv = &write_keep_alive(0);
4948 &write_data("\r\n");
4949 &write_data($content);
4951 if ($config{'dav_debug'}) {
4952 print STDERR "DAV reply :\n";
4953 print STDERR "---------------------------------------------\n";
4954 print STDERR "HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n";
4955 foreach my $h ($response->header_field_names) {
4956 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4957 print STDERR "$h: ",$response->header($h),"\r\n";
4959 print STDERR "Content-length: ",length($content),"\r\n";
4960 print STDERR "\r\n";
4961 print STDERR $content;
4962 print STDERR "---------------------------------------------\n";
4966 &log_request($acpthost, $authuser, $reqline, $response->code(),
4967 length($response->content()));
4970 # get_system_hostname()
4971 # Returns the hostname of this system, for reporting to listeners
4972 sub get_system_hostname
4974 # On Windows, try computername environment variable
4975 return $ENV{'computername'} if ($ENV{'computername'});
4976 return $ENV{'COMPUTERNAME'} if ($ENV{'COMPUTERNAME'});
4978 # If a specific command is set, use it first
4979 if ($config{'hostname_command'}) {
4980 local $out = `($config{'hostname_command'}) 2>&1`;
4987 # First try the hostname command
4988 local $out = `hostname 2>&1`;
4989 if (!$? && $out =~ /\S/) {
4994 # Try the Sys::Hostname module
4995 eval "use Sys::Hostname";
4997 local $rv = eval "hostname()";
5003 # Must use net name on Windows
5004 local $out = `net name 2>&1`;
5005 if ($out =~ /\-+\r?\n(\S+)/) {
5012 # indexof(string, array)
5013 # Returns the index of some value in an array, or -1
5016 for($i=1; $i <= $#_; $i++) {
5017 if ($_[$i] eq $_[0]) { return $i - 1; }
5023 # has_command(command)
5024 # Returns the full path if some command is in the path, undef if not
5028 if (!$_[0]) { return undef; }
5029 if (exists($has_command_cache{$_[0]})) {
5030 return $has_command_cache{$_[0]};
5033 if ($_[0] =~ /^\//) {
5034 $rv = -x $_[0] ? $_[0] : undef;
5037 local $sp = $on_windows ? ';' : ':';
5038 foreach $d (split($sp, $ENV{PATH})) {
5039 if (-x "$d/$_[0]") {
5044 foreach my $sfx (".exe", ".com", ".bat") {
5045 if (-r "$d/$_[0]".$sfx) {
5046 $rv = "$d/$_[0]".$sfx;
5053 $has_command_cache{$_[0]} = $rv;
5057 # check_sudo_permissions(user, pass)
5058 # Returns 1 if some user can run any command via sudo
5059 sub check_sudo_permissions
5061 local ($user, $pass) = @_;
5063 # First try the pipes
5065 print DEBUG "check_sudo_permissions: querying cache for $user\n";
5066 print $PASSINw "readsudo $user\n";
5067 local $can = <$PASSOUTr>;
5069 print DEBUG "check_sudo_permissions: cache said $can\n";
5070 if ($can =~ /^\d+$/ && $can != 2) {
5075 local $ptyfh = new IO::Pty;
5076 print DEBUG "check_sudo_permissions: ptyfh=$ptyfh\n";
5078 print STDERR "Failed to create new PTY with IO::Pty\n";
5081 local @uinfo = getpwnam($user);
5083 print STDERR "Unix user $user does not exist for sudo\n";
5087 # Execute sudo in a sub-process, via a pty
5088 local $ttyfh = $ptyfh->slave();
5089 print DEBUG "check_sudo_permissions: ttyfh=$ttyfh\n";
5090 local $tty = $ptyfh->ttyname();
5091 print DEBUG "check_sudo_permissions: tty=$tty\n";
5092 chown($uinfo[2], $uinfo[3], $tty);
5094 print DEBUG "check_sudo_permissions: about to fork..\n";
5095 local $pid = fork();
5096 print DEBUG "check_sudo_permissions: fork=$pid pid=$$\n";
5098 print STDERR "fork for sudo failed : $!\n";
5103 $ptyfh->make_slave_controlling_terminal();
5104 close(STDIN); close(STDOUT); close(STDERR);
5105 untie(*STDIN); untie(*STDOUT); untie(*STDERR);
5106 close($PASSINw); close($PASSOUTr);
5107 $( = $uinfo[3]; $) = "$uinfo[3] $uinfo[3]";
5108 ($>, $<) = ($uinfo[2], $uinfo[2]);
5113 open(STDIN, "<&SUDOr");
5114 open(STDOUT, ">$tty");
5115 open(STDERR, ">&STDOUT");
5118 print "Exec failed : $!\n";
5121 print DEBUG "check_sudo_permissions: pid=$pid\n";
5123 $ptyfh->close_slave();
5125 # Send password, and get back response
5126 local $oldfh = select(SUDOw);
5129 print DEBUG "check_sudo_permissions: about to send pass\n";
5130 local $SIG{'PIPE'} = 'ignore'; # Sometimes sudo doesn't ask for a password
5131 print SUDOw $pass,"\n";
5132 print DEBUG "check_sudo_permissions: sent pass=$pass\n";
5136 print DEBUG "check_sudo_permissions: got $_";
5142 local ($ok) = ($out =~ /\(ALL\)\s+ALL|\(ALL\)\s+NOPASSWD:\s+ALL/ ? 1 : 0);
5146 print $PASSINw "writesudo $user $ok\n";
5152 # is_mobile_useragent(agent)
5153 # Returns 1 if some user agent looks like a cellphone or other mobile device,
5155 sub is_mobile_useragent
5157 local ($agent) = @_;
5159 "UP.Link", # Openwave
5160 "Nokia", # All Nokias start with Nokia
5161 "MOT-", # All Motorola phones start with MOT-
5162 "SAMSUNG", # Samsung browsers
5163 "Samsung", # Samsung browsers
5164 "SEC-", # Samsung browsers
5165 "AU-MIC", # Samsung browsers
5166 "AUDIOVOX", # Audiovox
5167 "BlackBerry", # BlackBerry
5168 "hiptop", # Danger hiptop Sidekick
5169 "SonyEricsson", # Sony Ericsson
5170 "Ericsson", # Old Ericsson browsers , mostly WAP
5171 "Mitsu/1.1.A", # Mitsubishi phones
5172 "Panasonic WAP", # Panasonic old WAP phones
5173 "DoCoMo", # DoCoMo phones
5174 "Lynx", # Lynx text-mode linux browser
5175 "Links", # Another text-mode linux browser
5177 local @substrings = (
5178 "UP.Browser", # Openwave
5179 "MobilePhone", # NetFront
5180 "AU-MIC-A700", # Samsung A700 Obigo browsers
5181 "Danger hiptop", # Danger Sidekick hiptop
5182 "Windows CE", # Windows CE Pocket PC
5183 "IEMobile", # Windows mobile browser
5184 "Blazer", # Palm Treo Blazer
5185 "BlackBerry", # BlackBerries can emulate other browsers, but
5186 # they still keep this string in the UserAgent
5187 "SymbianOS", # New Series60 browser has safari in it and
5188 # SymbianOS is the only distinguishing string
5189 "iPhone", # Apple iPhone KHTML browser
5190 "iPod", # iPod touch browser
5191 "MobileSafari", # HTTP client in iPhone
5193 "Opera Mini", # Opera Mini
5194 "HTC_P3700", # HTC mobile device
5196 "webOS/", # Palm WebOS
5197 "Nintendo DS", # DSi / DSi-XL
5199 foreach my $p (@prefixes) {
5200 return 1 if ($agent =~ /^\Q$p\E/);
5202 foreach my $s (@substrings, @mobile_agents) {
5203 return 1 if ($agent =~ /\Q$s\E/);
5208 # write_blocked_file()
5209 # Writes out a text file of blocked hosts and users
5210 sub write_blocked_file
5212 open(BLOCKED, ">$config{'blockedfile'}");
5213 foreach my $d (grep { $hostfail{$_} } @deny) {
5214 print BLOCKED "host $d $hostfail{$d} $blockhosttime{$d}\n";
5216 foreach my $d (grep { $userfail{$_} } @denyusers) {
5217 print BLOCKED "user $d $userfail{$d} $blockusertime{$d}\n";
5220 chmod(0700, $config{'blockedfile'});
5225 open(PIDFILE, ">$config{'pidfile'}");
5226 printf PIDFILE "%d\n", getpid();
5228 $miniserv_main_pid = getpid();
5231 # lock_user_password(user)
5232 # Updates a user's password file entry to lock it, both in memory and on disk.
5233 # Returns 1 if done, -1 if no such user, 0 if already locked
5234 sub lock_user_password
5237 local $uinfo = &get_user_details($user);
5242 if ($uinfo->{'pass'} =~ /^\!/) {
5246 if (!$uinfo->{'proto'}) {
5247 # Write to users file
5248 $users{$user} = "!".$users{$user};
5249 open(USERS, $config{'userfile'});
5250 local @ufile = <USERS>;
5252 foreach my $u (@ufile) {
5253 local @uinfo = split(/:/, $u);
5254 if ($uinfo[0] eq $user) {
5255 $uinfo[1] = $users{$user};
5257 $u = join(":", @uinfo);
5259 open(USERS, ">$config{'userfile'}");
5265 if ($config{'userdb'}) {
5267 my ($dbh, $proto, $prefix, $args) = &connect_userdb($config{'userdb'});
5271 elsif ($proto eq "mysql" || $proto eq "postgresql") {
5272 # Update user attribute
5273 my $cmd = $dbh->prepare(
5274 "update webmin_user set pass = ? where id = ?");
5275 if (!$cmd || !$cmd->execute("!".$uinfo->{'pass'},
5278 print STDERR "Failed to lock password : ",
5282 $cmd->finish() if ($cmd);
5284 elsif ($proto eq "ldap") {
5285 # Update LDAP object
5286 my $rv = $dbh->modify($uinfo->{'id'},
5287 replace => { 'webminPass' => '!'.$uinfo->{'pass'} });
5288 if (!$rv || $rv->code) {
5289 print STDERR "Failed to lock password : ",
5290 ($rv ? $rv->error : "Unknown error"),"\n";
5294 &disconnect_userdb($config{'userdb'}, $dbh);
5298 return -1; # This should never be reached
5301 # hash_session_id(sid)
5302 # Returns an MD5 or Unix-crypted session ID
5306 if (!$hash_session_id_cache{$sid}) {
5309 $hash_session_id_cache{$sid} = &encrypt_md5($sid);
5313 $hash_session_id_cache{$sid} = &unix_crypt($sid, "XX");
5316 return $hash_session_id_cache{$sid};
5319 # encrypt_md5(string, [salt])
5320 # Returns a string encrypted in MD5 format
5323 local ($passwd, $salt) = @_;
5324 local $magic = '$1$';
5325 if ($salt =~ /^\$1\$([^\$]+)/) {
5326 # Extract actual salt from already encrypted password
5331 local $ctx = eval "new $use_md5";
5338 # Add some more stuff from the hash of the password and salt
5339 local $ctx1 = eval "new $use_md5";
5340 $ctx1->add($passwd);
5344 $ctx1->add($passwd);
5345 local $final = $ctx1->digest();
5346 for($pl=length($passwd); $pl>0; $pl-=16) {
5347 $ctx->add($pl > 16 ? $final : substr($final, 0, $pl));
5350 # This piece of code seems rather pointless, but it's in the C code that
5351 # does MD5 in PAM so it has to go in!
5354 for($i=length($passwd); $i; $i >>= 1) {
5359 $ctx->add(substr($passwd, $j, 1));
5362 $final = $ctx->digest();
5365 # This loop exists only to waste time
5366 for($i=0; $i<1000; $i++) {
5367 $ctx1 = eval "new $use_md5";
5368 $ctx1->add($i & 1 ? $passwd : $final);
5369 $ctx1->add($salt) if ($i % 3);
5370 $ctx1->add($passwd) if ($i % 7);
5371 $ctx1->add($i & 1 ? $final : $passwd);
5372 $final = $ctx1->digest();
5376 # Convert the 16-byte final string into a readable form
5378 local @final = map { ord($_) } split(//, $final);
5379 $l = ($final[ 0]<<16) + ($final[ 6]<<8) + $final[12];
5380 $rv .= &to64($l, 4);
5381 $l = ($final[ 1]<<16) + ($final[ 7]<<8) + $final[13];
5382 $rv .= &to64($l, 4);
5383 $l = ($final[ 2]<<16) + ($final[ 8]<<8) + $final[14];
5384 $rv .= &to64($l, 4);
5385 $l = ($final[ 3]<<16) + ($final[ 9]<<8) + $final[15];
5386 $rv .= &to64($l, 4);
5387 $l = ($final[ 4]<<16) + ($final[10]<<8) + $final[ 5];
5388 $rv .= &to64($l, 4);
5390 $rv .= &to64($l, 2);
5392 # Add salt if needed
5394 return $magic.$salt.'$'.$rv;
5403 local ($v, $n) = @_;
5406 $r .= $itoa64[$v & 0x3f];
5412 # read_file(file, &assoc, [&order], [lowercase])
5413 # Fill an associative array with name=value pairs from a file
5416 open(ARFILE, $_[0]) || return 0;
5419 if (!/^#/ && /^([^=]*)=(.*)$/) {
5420 $_[1]->{$_[3] ? lc($1) : $1} = $2;
5421 push(@{$_[2]}, $1) if ($_[2]);
5428 # write_file(file, array)
5429 # Write out the contents of an associative array as name=value lines
5432 local(%old, @order);
5433 &read_file($_[0], \%old, \@order);
5434 open(ARFILE, ">$_[0]");
5435 foreach $k (@order) {
5436 print ARFILE $k,"=",$_[1]->{$k},"\n" if (exists($_[1]->{$k}));
5438 foreach $k (keys %{$_[1]}) {
5439 print ARFILE $k,"=",$_[1]->{$k},"\n" if (!exists($old{$k}));
5444 # execute_ready_webmin_crons()
5445 # Find and run any cron jobs that are due, based on their last run time and
5446 # execution interval
5447 sub execute_ready_webmin_crons
5451 foreach my $cron (@webmincrons) {
5453 if (!$webmincron_last{$cron->{'id'}}) {
5454 # If not ever run before, don't run right away
5455 $webmincron_last{$cron->{'id'}} = $now;
5458 elsif ($cron->{'interval'} &&
5459 $now - $webmincron_last{$cron->{'id'}} > $cron->{'interval'}) {
5460 # Older than interval .. time to run
5463 elsif ($cron->{'mins'}) {
5464 # Check if current time matches spec, and we haven't run in the
5466 my @tm = localtime($now);
5467 if (&matches_cron($cron->{'mins'}, $tm[1]) &&
5468 &matches_cron($cron->{'hours'}, $tm[2]) &&
5469 &matches_cron($cron->{'days'}, $tm[3]) &&
5470 &matches_cron($cron->{'months'}, $tm[4]+1) &&
5471 &matches_cron($cron->{'weekdays'}, $tm[6]) &&
5472 $now - $webmincron_last{$cron->{'id'}} > 60) {
5478 print DEBUG "Running cron id=$cron->{'id'} ".
5479 "module=$cron->{'module'} func=$cron->{'func'}\n";
5480 $webmincron_last{$cron->{'id'}} = $now;
5484 # Run via a wrapper command, which we run like a CGI
5485 dbmclose(%sessiondb);
5487 # Setup CGI-like environment
5488 $envtz = $ENV{"TZ"};
5489 $envuser = $ENV{"USER"};
5490 $envpath = $ENV{"PATH"};
5491 $envlang = $ENV{"LANG"};
5492 $envroot = $ENV{"SystemRoot"};
5493 $envperllib = $ENV{'PERLLIB'};
5494 foreach my $k (keys %ENV) {
5497 $ENV{"PATH"} = $envpath if ($envpath);
5498 $ENV{"TZ"} = $envtz if ($envtz);
5499 $ENV{"USER"} = $envuser if ($envuser);
5500 $ENV{"OLD_LANG"} = $envlang if ($envlang);
5501 $ENV{"SystemRoot"} = $envroot if ($envroot);
5502 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
5503 $ENV{"HOME"} = $user_homedir;
5504 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
5505 $ENV{"SERVER_ADMIN"} = $config{"email"};
5507 $ENV{"SERVER_ROOT"} = $root0;
5508 $ENV{"SERVER_REALROOT"} = $root0;
5509 $ENV{"SERVER_PORT"} = $config{'port'};
5510 $ENV{"WEBMIN_CRON"} = 1;
5511 $ENV{"DOCUMENT_ROOT"} = $root0;
5512 $ENV{"DOCUMENT_REALROOT"} = $root0;
5513 $ENV{"MINISERV_CONFIG"} = $config_file;
5514 $ENV{"HTTPS"} = "ON" if ($use_ssl);
5515 $ENV{"MINISERV_PID"} = $miniserv_main_pid;
5516 $ENV{"SCRIPT_FILENAME"} = $config{'webmincron_wrapper'};
5517 if ($ENV{"SCRIPT_FILENAME"} =~ /^\Q$root0\E(\/.*)$/) {
5518 $ENV{"SCRIPT_NAME"} = $1;
5520 $config{'webmincron_wrapper'} =~ /^(.*)\//;
5522 foreach $k (keys %config) {
5523 if ($k =~ /^env_(\S+)$/) {
5524 $ENV{$1} = $config{$k};
5528 $SIG{'CHLD'} = 'DEFAULT';
5530 # Have SOCK closed if the perl exec's something
5532 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
5535 # Run the wrapper script by evaling it
5536 $pkg = "webmincron";
5537 $0 = $config{'webmincron_wrapper'};
5539 $main_process_id = $$;
5543 do \$miniserv::config{'webmincron_wrapper'};
5547 print STDERR "Perl cron failure : $@\n";
5552 push(@childpids, $pid);
5556 # Write out file containing last run times
5557 &write_file($config{'webmincron_last'}, \%webmincron_last);
5561 # matches_cron(cron-spec, time)
5562 # Checks if some minute or hour matches some cron spec, which can be * or a list
5566 my ($spec, $tm) = @_;
5571 foreach my $s (split(/,/, $spec)) {
5573 $s =~ /^(\d+)\-(\d+)$/ && $tm >= $1 && $tm <= $2) {
5581 # read_webmin_crons()
5582 # Read all scheduled webmin cron functions and store them in the @webmincrons
5584 sub read_webmin_crons
5587 opendir(CRONS, $config{'webmincron_dir'});
5588 print DEBUG "Reading crons from $config{'webmincron_dir'}\n";
5589 foreach my $f (readdir(CRONS)) {
5590 if ($f =~ /^(\d+)\.cron$/) {
5592 &read_file("$config{'webmincron_dir'}/$f", \%cron);
5595 foreach my $n ('module', 'func') {
5597 print STDERR "Cron $1 missing $n\n";
5601 if (!$cron{'interval'} && !$cron{'mins'} && !$cron{'special'}) {
5602 print STDERR "Cron $1 missing any time spec\n";
5605 if ($cron{'special'} eq 'hourly') {
5606 # Run every hour on the hour
5608 $cron{'hours'} = '*';
5609 $cron{'days'} = '*';
5610 $cron{'months'} = '*';
5611 $cron{'weekdays'} = '*';
5613 elsif ($cron{'special'} eq 'daily') {
5614 # Run every day at midnight
5616 $cron{'hours'} = '0';
5617 $cron{'days'} = '*';
5618 $cron{'months'} = '*';
5619 $cron{'weekdays'} = '*';
5621 elsif ($cron{'special'} eq 'monthly') {
5622 # Run every month on the 1st
5624 $cron{'hours'} = '0';
5625 $cron{'days'} = '1';
5626 $cron{'months'} = '*';
5627 $cron{'weekdays'} = '*';
5629 elsif ($cron{'special'} eq 'weekly') {
5630 # Run every month on the 1st
5632 $cron{'hours'} = '0';
5633 $cron{'days'} = '*';
5634 $cron{'months'} = '*';
5635 $cron{'weekdays'} = '0';
5637 elsif ($cron{'special'} eq 'yearly' ||
5638 $cron{'special'} eq 'annually') {
5639 # Run every year on 1st january
5641 $cron{'hours'} = '0';
5642 $cron{'days'} = '1';
5643 $cron{'months'} = '1';
5644 $cron{'weekdays'} = '*';
5646 elsif ($cron{'special'}) {
5647 print STDERR "Cron $1 invalid special time $cron{'special'}\n";
5650 if ($cron{'special'}) {
5651 delete($cron{'special'});
5654 print DEBUG "adding cron id=$cron{'id'} module=$cron{'module'} func=$cron{'func'}\n";
5655 push(@webmincrons, \%cron);
5662 # Read into the Webmin cache all files marked for pre-caching
5665 undef(%main::read_file_cache);
5666 foreach my $g (split(/\s+/, $config{'precache'})) {
5667 next if ($g eq "none");
5668 foreach my $f (glob("$config{'root'}/$g")) {
5671 $main::read_file_cache{$f} = { };
5672 &read_file($f, $main::read_file_cache{$f});
5673 $main::read_file_cache_time{$f} = $st[9];
5678 # Check if some address is valid IPv4, returns 1 if so.
5681 return $_[0] =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/ &&
5682 $1 >= 0 && $1 <= 255 &&
5683 $2 >= 0 && $2 <= 255 &&
5684 $3 >= 0 && $3 <= 255 &&
5685 $4 >= 0 && $4 <= 255;
5688 # Check if some IPv6 address is properly formatted, and returns 1 if so.
5689 sub check_ip6address
5691 my @blocks = split(/:/, $_[0]);
5692 return 0 if (@blocks == 0 || @blocks > 8);
5694 my $where = index($blocks[$ib],"/");
5697 my $b = substr($blocks[$ib],0,$where);
5698 $m = substr($blocks[$ib],$where+1,length($blocks[$ib])-($where+1));
5701 return 0 if ($m <0 || $m >128);
5704 foreach $b (@blocks) {
5705 return 0 if ($b ne "" && $b !~ /^[0-9a-f]{1,4}$/i);
5706 $empty++ if ($b eq "");
5708 return 0 if ($empty > 1 && !($_[0] =~ /^::/ && $empty == 2));
5712 # network_to_address(binary)
5713 # Given a network address in binary IPv4 or v4 format, return the string form
5714 sub network_to_address
5717 if (length($addr) == 4 || !$use_ipv6) {
5718 return inet_ntoa($addr);
5721 return Socket6::inet_ntop(Socket6::AF_INET6(), $addr);
5725 # redirect_stderr_to_log()
5726 # Re-direct STDERR to error log file
5727 sub redirect_stderr_to_log
5729 if ($config{'errorlog'} ne '-') {
5730 open(STDERR, ">>$config{'errorlog'}") ||
5731 die "failed to open $config{'errorlog'} : $!";
5732 if ($config{'logperms'}) {
5733 chmod(oct($config{'logperms'}), $config{'errorlog'});
5736 select(STDERR); $| = 1; select(STDOUT);