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 if ($config{'inetd'}) {
380 # We are being run from inetd - go direct to handling the request
381 &redirect_stderr_to_log();
382 $SIG{'HUP'} = 'IGNORE';
383 $SIG{'TERM'} = 'DEFAULT';
384 $SIG{'PIPE'} = 'DEFAULT';
385 open(SOCK, "+>&STDIN");
387 # Check if it is time for the logfile to be cleared
388 if ($config{'logclear'}) {
389 local $write_logtime = 0;
390 local @st = stat("$config{'logfile'}.time");
392 if ($st[9]+$config{'logtime'}*60*60 < time()){
395 unlink($config{'logfile'});
398 else { $write_logtime = 1; }
399 if ($write_logtime) {
400 open(LOGTIME, ">$config{'logfile'}.time");
401 print LOGTIME time(),"\n";
406 # Initialize SSL for this connection
408 $ssl_con = &ssl_connection_for_ip(SOCK, 0);
412 # Work out the hostname for this web server
413 $host = &get_socket_name(SOCK, 0);
415 $port = $config{'port'};
416 $acptaddr = getpeername(SOCK);
419 # Work out remote and local IPs
420 (undef, $peera, undef) = &get_address_ip($acptaddr, 0);
421 (undef, $locala) = &get_socket_ip(SOCK, 0);
423 print DEBUG "main: Starting handle_request loop pid=$$\n";
424 while(&handle_request($peera, $locala, 0)) { }
425 print DEBUG "main: Done handle_request loop pid=$$\n";
430 # Build list of sockets to listen on
431 $config{'bind'} = '' if ($config{'bind'} eq '*');
432 if ($config{'bind'}) {
433 # Listening on a specific IP
434 if (&check_ip6address($config{'bind'})) {
436 $use_ipv6 || die "Cannot bind to $config{'bind'} without IPv6";
437 push(@sockets, [ inet_pton(Socket6::AF_INET6(),$config{'bind'}),
439 Socket6::PF_INET6() ]);
443 push(@sockets, [ inet_aton($config{'bind'}),
449 # Listening on all IPs
450 push(@sockets, [ INADDR_ANY, $config{'port'}, PF_INET() ]);
453 push(@sockets, [ in6addr_any(), $config{'port'},
454 Socket6::PF_INET6() ]);
457 foreach $s (split(/\s+/, $config{'sockets'})) {
458 if ($s =~ /^(\d+)$/) {
459 # Just listen on another port on the main IP
460 push(@sockets, [ $sockets[0]->[0], $s, $sockets[0]->[2] ]);
461 if ($use_ipv6 && !$config{'bind'}) {
462 # Also listen on that port on the main IPv6 address
463 push(@sockets, [ $sockets[1]->[0], $s,
467 elsif ($s =~ /^\*:(\d+)$/) {
468 # Listening on all IPs on some port
469 push(@sockets, [ INADDR_ANY, $config{'port'},
472 push(@sockets, [ in6addr_any(), $config{'port'},
473 Socket6::PF_INET6() ]);
476 elsif ($s =~ /^(\S+):(\d+)$/) {
477 # Listen on a specific port and IP
478 my ($ip, $port) = ($1, $2);
479 if (&check_ip6address($ip)) {
480 $use_ipv6 || die "Cannot bind to $ip without IPv6";
481 push(@sockets, [ inet_pton(Socket6::AF_INET6(),
483 $port, Socket6::PF_INET6() ]);
486 push(@sockets, [ inet_aton($ip), $port,
490 elsif ($s =~ /^([0-9\.]+):\*$/ || $s =~ /^([0-9\.]+)$/) {
491 # Listen on the main port on another IPv4 address
492 push(@sockets, [ inet_aton($1), $sockets[0]->[1],
495 elsif (($s =~ /^([0-9a-f\:]+):\*$/ || $s =~ /^([0-9a-f\:]+)$/) &&
497 # Listen on the main port on another IPv6 address
498 push(@sockets, [ inet_pton(Socket6::AF_INET6(), $1),
500 Socket6::PF_INET6() ]);
504 # Open all the sockets
505 $proto = getprotobyname('tcp');
507 $tried_inaddr_any = 0;
508 for($i=0; $i<@sockets; $i++) {
510 socket($fh, $sockets[$i]->[2], SOCK_STREAM, $proto) ||
511 die "Failed to open socket family $sockets[$i]->[2] : $!";
512 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
513 if ($sockets[$i]->[2] eq PF_INET()) {
514 $pack = pack_sockaddr_in($sockets[$i]->[1], $sockets[$i]->[0]);
517 $pack = pack_sockaddr_in6($sockets[$i]->[1], $sockets[$i]->[0]);
518 setsockopt($fh, 41, 26, pack("l", 1)); # IPv6 only
520 for($j=0; $j<5; $j++) {
521 last if (bind($fh, $pack));
525 # All attempts failed .. give up
526 if ($sockets[$i]->[0] eq INADDR_ANY ||
527 $use_ipv6 && $sockets[$i]->[0] eq in6addr_any()) {
529 "Failed to bind to port $sockets[$i]->[1] : $!");
530 $tried_inaddr_any = 1;
533 $ip = &network_to_address($sockets[$i]->[0]);
535 "Failed to bind to IP $ip port ".
536 "$sockets[$i]->[1] : $!");
540 listen($fh, SOMAXCONN);
541 push(@socketfhs, $fh);
542 $ipv6fhs{$fh} = $sockets[$i]->[2] eq PF_INET() ? 0 : 1;
545 foreach $se (@sockerrs) {
546 print STDERR $se,"\n";
549 # If all binds failed, try binding to any address
550 if (!@socketfhs && !$tried_inaddr_any) {
551 print STDERR "Falling back to listening on any address\n";
553 socket($fh, PF_INET(), SOCK_STREAM, $proto) ||
554 die "Failed to open socket : $!";
555 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
556 if (!bind($fh, pack_sockaddr_in($sockets[0]->[1], INADDR_ANY))) {
557 print STDERR "Failed to bind to port $sockets[0]->[1] : $!\n";
560 listen($fh, SOMAXCONN);
561 push(@socketfhs, $fh);
563 elsif (!@socketfhs && $tried_inaddr_any) {
564 print STDERR "Could not listen on any ports";
568 if ($config{'listen'}) {
569 # Open the socket that allows other webmin servers to find this one
570 $proto = getprotobyname('udp');
571 if (socket(LISTEN, PF_INET(), SOCK_DGRAM, $proto)) {
572 setsockopt(LISTEN, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
573 bind(LISTEN, pack_sockaddr_in($config{'listen'}, INADDR_ANY));
574 listen(LISTEN, SOMAXCONN);
577 $config{'listen'} = 0;
581 # Split from the controlling terminal, unless configured not to
582 if (!$config{'nofork'}) {
583 if (fork()) { exit; }
585 eval { setsid(); }; # may not work on Windows
587 # Close standard file handles
588 open(STDIN, "</dev/null");
589 open(STDOUT, ">/dev/null");
590 &redirect_stderr_to_log();
591 &log_error("miniserv.pl started");
592 foreach $msg (@startup_msg) {
596 # write out the PID file
599 # Start the log-clearing process, if needed. This checks every minute
600 # to see if the log has passed its reset time, and if so clears it
601 if ($config{'logclear'}) {
602 if (!($logclearer = fork())) {
603 &close_all_sockets();
606 local $write_logtime = 0;
607 local @st = stat("$config{'logfile'}.time");
609 if ($st[9]+$config{'logtime'}*60*60 < time()){
612 unlink($config{'logfile'});
615 else { $write_logtime = 1; }
616 if ($write_logtime) {
617 open(LOGTIME, ">$config{'logfile'}.time");
618 print LOGTIME time(),"\n";
625 push(@childpids, $logclearer);
628 # Setup the logout time dbm if needed
629 if ($config{'session'}) {
630 eval "use SDBM_File";
631 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
632 eval "\$sessiondb{'1111111111'} = 'foo bar';";
634 dbmclose(%sessiondb);
635 eval "use NDBM_File";
636 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
639 delete($sessiondb{'1111111111'});
644 $SIG{'HUP'} = 'miniserv::trigger_restart';
645 $SIG{'TERM'} = 'miniserv::term_handler';
646 $SIG{'USR1'} = 'miniserv::trigger_reload';
647 $SIG{'PIPE'} = 'IGNORE';
648 local $remove_session_count = 0;
649 $need_pipes = $config{'passdelay'} || $config{'session'};
651 # wait for a new connection, or a message from a child process
653 if (@childpids <= $config{'maxconns'}) {
654 # Only accept new main socket connects when ready
656 foreach $s (@socketfhs) {
657 vec($rmask, fileno($s), 1) = 1;
661 printf STDERR "too many children (%d > %d)\n",
662 scalar(@childpids), $config{'maxconns'};
665 for($i=0; $i<@passin; $i++) {
666 vec($rmask, fileno($passin[$i]), 1) = 1;
669 vec($rmask, fileno(LISTEN), 1) = 1 if ($config{'listen'});
671 # Wait for a connection
672 local $sel = select($rmask, undef, undef, 10);
674 # Check the flag files
675 if ($config{'restartflag'} && -r $config{'restartflag'}) {
676 print STDERR "restart flag file detected\n";
677 unlink($config{'restartflag'});
680 if ($config{'reloadflag'} && -r $config{'reloadflag'}) {
681 unlink($config{'reloadflag'});
686 # Got a HUP signal while in select() .. restart now
690 # Got a USR1 signal while in select() .. re-read config
692 &reload_config_file();
694 local $time_now = time();
696 # Clean up finished processes
698 do { $pid = waitpid(-1, WNOHANG);
699 @childpids = grep { $_ != $pid } @childpids;
700 } while($pid != 0 && $pid != -1);
702 # run the unblocking procedure to check if enough time has passed to
703 # unblock hosts that heve been blocked because of password failures
705 if ($config{'blockhost_failures'}) {
707 while ($i <= $#deny) {
708 if ($blockhosttime{$deny[$i]} &&
709 $config{'blockhost_time'} != 0 &&
710 ($time_now - $blockhosttime{$deny[$i]}) >=
711 $config{'blockhost_time'}) {
712 # the host can be unblocked now
713 $hostfail{$deny[$i]} = 0;
714 splice(@deny, $i, 1);
721 # Do the same for blocked users
722 if ($config{'blockuser_failures'}) {
724 while ($i <= $#deny) {
725 if ($blockusertime{$deny[$i]} &&
726 $config{'blockuser_time'} != 0 &&
727 ($time_now - $blockusertime{$deny[$i]}) >=
728 $config{'blockuser_time'}) {
729 # the user can be unblocked now
730 $userfail{$deny[$i]} = 0;
731 splice(@denyusers, $i, 1);
738 &write_blocked_file();
741 # Check if any webmin cron jobs are ready to run
742 &execute_ready_webmin_crons();
744 if ($config{'session'} && (++$remove_session_count%50) == 0) {
745 # Remove sessions with more than 7 days of inactivity,
747 foreach $s (keys %sessiondb) {
748 local ($user, $ltime, $lip) =
749 split(/\s+/, $sessiondb{$s});
750 if ($time_now - $ltime > 7*24*60*60) {
751 &run_logout_script($s, $user);
752 &write_logout_utmp($user, $lip);
753 delete($sessiondb{$s});
756 "Timeout of session for $user");
762 if ($use_pam && $config{'pam_conv'}) {
763 # Remove PAM sessions with more than 5 minutes of inactivity
765 foreach $c (values %conversations) {
766 if ($time_now - $c->{'time'} > 5*60) {
767 &end_pam_conversation($c);
769 syslog("info", "%s", "Timeout of PAM ".
770 "session for $c->{'user'}");
776 # Don't check any sockets if there is no activity
779 # Check if any of the main sockets have received a new connection
781 foreach $s (@socketfhs) {
782 if (vec($rmask, fileno($s), 1)) {
784 $acptaddr = accept(SOCK, $s);
785 if (!$acptaddr) { next; }
786 binmode(SOCK); # turn off any Perl IO stuff
789 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
791 ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw) =
795 # Work out IP and port of client
796 local ($peerb, $peera, $peerp) =
797 &get_address_ip($acptaddr, $ipv6fhs{$s});
799 # Work out the local IP
800 (undef, $locala) = &get_socket_ip(SOCK, $ipv6fhs{$s});
802 # Check username of connecting user
803 $localauth_user = undef;
804 if ($config{'localauth'} && $peera eq "127.0.0.1") {
805 if (open(TCP, "/proc/net/tcp")) {
806 # Get the info direct from the kernel
807 $peerh = sprintf("%4.4X", $peerp);
810 local @t = split(/[\s:]+/, $_);
811 if ($t[1] eq '0100007F' &&
820 if (!$localauth_user) {
821 # Call lsof for the info
822 local $lsofpid = open(LSOF,
823 "$config{'localauth'} -i ".
824 "TCP\@127.0.0.1:$peerp |");
826 if (/^(\S+)\s+(\d+)\s+(\S+)/ &&
827 $2 != $$ && $2 != $lsofpid){
828 $localauth_user = $3;
835 # Work out the hostname for this web server
836 $host = &get_socket_name(SOCK, $ipv6fhs{$s});
839 "Failed to get local socket name : $!\n";
843 $port = $sockets[$sn]->[1];
845 # fork the subprocess
847 if (!($handpid = fork())) {
848 # setup signal handlers
849 $SIG{'TERM'} = 'DEFAULT';
850 $SIG{'PIPE'} = 'DEFAULT';
851 #$SIG{'CHLD'} = 'IGNORE';
852 $SIG{'HUP'} = 'IGNORE';
853 $SIG{'USR1'} = 'IGNORE';
855 # Initialize SSL for this connection
857 $ssl_con = &ssl_connection_for_ip(
862 # Close the file handle for the session DBM
863 dbmclose(%sessiondb);
865 # close useless pipes
868 close($PASSINr); close($PASSOUTw);
870 &close_all_sockets();
874 "main: Starting handle_request loop pid=$$\n";
875 while(&handle_request($peera, $locala,
877 # Loop until keepalive stops
880 "main: Done handle_request loop pid=$$\n";
883 close($PASSINw); close($PASSOUTw);
886 push(@childpids, $handpid);
888 close($PASSINw); close($PASSOUTr);
889 push(@passin, $PASSINr);
890 push(@passout, $PASSOUTw);
897 if ($config{'listen'} && vec($rmask, fileno(LISTEN), 1)) {
898 # Got UDP packet from another webmin server
900 local $from = recv(LISTEN, $rcvbuf, 1024, 0);
902 local $fromip = inet_ntoa((unpack_sockaddr_in($from))[1]);
903 local $toip = inet_ntoa((unpack_sockaddr_in(
904 getsockname(LISTEN)))[1]);
905 if ((!@deny || !&ip_match($fromip, $toip, @deny)) &&
906 (!@allow || &ip_match($fromip, $toip, @allow))) {
907 local $listenhost = &get_socket_name(LISTEN, 0);
908 send(LISTEN, "$listenhost:$config{'port'}:".
909 ($use_ssl || $config{'inetd_ssl'} ? 1 : 0).":".
910 ($config{'listenhost'} ?
911 &get_system_hostname() : ""),
917 # check for session, password-timeout and PAM messages from subprocesses
918 for($i=0; $i<@passin; $i++) {
919 if (vec($rmask, fileno($passin[$i]), 1)) {
920 # this sub-process is asking about a password
921 local $infd = $passin[$i];
922 local $outfd = $passout[$i];
923 #local $inline = <$infd>;
924 local $inline = &sysread_line($infd);
926 print DEBUG "main: inline $inline";
929 print DEBUG "main: inline EOF\n";
931 if ($inline =~ /^delay\s+(\S+)\s+(\S+)\s+(\d+)/) {
932 # Got a delay request from a subprocess.. for
933 # valid logins, there is no delay (to prevent
934 # denial of service attacks), but for invalid
935 # logins the delay increases with each failed
938 # login OK.. no delay
939 print $outfd "0 0\n";
940 $wasblocked = $hostfail{$2} ||
945 &write_blocked_file();
954 # add the host to the block list,
956 if ($config{'blockhost_failures'} &&
958 $config{'blockhost_failures'}) {
960 $blockhosttime{$2} = $time_now;
963 local $logtext = "Security alert: Host $2 blocked after $config{'blockhost_failures'} failed logins for user $1";
969 # add the user to the user block list,
971 if ($config{'blockuser_failures'} &&
973 $config{'blockuser_failures'}) {
974 push(@denyusers, $1);
975 $blockusertime{$1} = $time_now;
978 local $logtext = "Security alert: User $1 blocked after $config{'blockuser_failures'} failed logins";
984 # Lock out the user's password, if enabled
985 if ($config{'blocklock'} &&
987 $config{'blockuser_failures'}) {
988 my $lk = &lock_user_password($1);
991 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";
998 $dl = $userdlay{$1} -
999 int(($time_now - $userlast{$1})/50);
1000 $dl = $dl < 0 ? 0 : $dl+1;
1001 print $outfd "$dl $blocked\n";
1002 $userdlay{$1} = $dl;
1004 # Write out blocked status file
1006 &write_blocked_file();
1009 $userlast{$1} = $time_now;
1011 elsif ($inline =~ /^verify\s+(\S+)\s+(\S+)/) {
1012 # Verifying a session ID
1013 local $session_id = $1;
1014 local $notimeout = $2;
1015 local $skey = $sessiondb{$session_id} ?
1017 &hash_session_id($session_id);
1018 if (!defined($sessiondb{$skey})) {
1019 # Session doesn't exist
1020 print $outfd "0 0\n";
1023 local ($user, $ltime) =
1024 split(/\s+/, $sessiondb{$skey});
1025 local $lot = &get_logout_time($user, $session_id);
1027 $time_now - $ltime > $lot*60 &&
1029 # Session has timed out
1030 print $outfd "1 ",$time_now - $ltime,"\n";
1031 #delete($sessiondb{$skey});
1035 print $outfd "2 $user\n";
1037 $time_now - $ltime >
1039 $sessiondb{$skey} = "$user $time_now";
1044 elsif ($inline =~ /^new\s+(\S+)\s+(\S+)\s+(\S+)/) {
1045 # Creating a new session
1046 local $session_id = $1;
1049 $sessiondb{&hash_session_id($session_id)} =
1050 "$user $time_now $ip";
1052 elsif ($inline =~ /^delete\s+(\S+)/) {
1053 # Logging out a session
1054 local $session_id = $1;
1055 local $skey = $sessiondb{$session_id} ?
1057 &hash_session_id($session_id);
1058 local @sdb = split(/\s+/, $sessiondb{$skey});
1059 print $outfd $sdb[0],"\n";
1060 delete($sessiondb{$skey});
1062 elsif ($inline =~ /^pamstart\s+(\S+)\s+(\S+)\s+(.*)/) {
1063 # Starting a new PAM conversation
1064 local ($cid, $host, $user) = ($1, $2, $3);
1066 # Does this user even need PAM?
1067 local ($realuser, $canlogin) =
1068 &can_user_login($user, undef, $host);
1070 if ($canlogin == 0) {
1071 # Cannot even login!
1072 print $outfd "0 Invalid username\n";
1074 elsif ($canlogin != 2) {
1075 # Not using PAM .. so just ask for
1077 $conv = { 'user' => $realuser,
1082 print $outfd "3 Password\n";
1085 # Start the PAM conversation
1086 # sub-process, and get a question
1087 $conv = { 'user' => $realuser,
1091 local ($PAMINr, $PAMINw, $PAMOUTr,
1092 $PAMOUTw) = &allocate_pipes();
1093 local $pampid = fork();
1095 close($PAMOUTr); close($PAMINw);
1096 &pam_conversation_process(
1100 close($PAMOUTw); close($PAMINr);
1101 $conv->{'pid'} = $pampid;
1102 $conv->{'PAMOUTr'} = $PAMOUTr;
1103 $conv->{'PAMINw'} = $PAMINw;
1104 push(@childpids, $pampid);
1106 # Get the first PAM question
1107 local $pok = &recv_pam_question(
1110 &end_pam_conversation($conv);
1114 $conversations{$cid} = $conv if ($conv);
1116 elsif ($inline =~ /^pamanswer\s+(\S+)\s+(.*)/) {
1117 # A response to a PAM question
1118 local ($cid, $answer) = ($1, $2);
1119 local $conv = $conversations{$cid};
1121 # No such conversation?
1122 print $outfd "0 Bad login session\n";
1124 elsif ($conv->{'pid'}) {
1125 # Send the PAM response and get
1127 &send_pam_answer($conv, $answer);
1128 local $pok = &recv_pam_question($conv, $outfd);
1130 &end_pam_conversation($conv);
1134 # This must be the password .. try it
1135 # and send back the results
1136 local ($vu, $expired, $nonexist) =
1137 &validate_user($conv->{'user'},
1140 local $ok = $vu ? 1 : 0;
1141 print $outfd "2 $conv->{'user'} $ok $expired $notexist\n";
1142 &end_pam_conversation($conv);
1145 elsif ($inline =~ /^writesudo\s+(\S+)\s+(\d+)/) {
1146 # Store the fact that some user can sudo to root
1147 local ($user, $ok) = ($1, $2);
1148 $sudocache{$user} = $ok." ".time();
1150 elsif ($inline =~ /^readsudo\s+(\S+)/) {
1151 # Query the user sudo cache (valid for 1 minute)
1153 local ($ok, $last) =
1154 split(/\s+/, $sudocache{$user});
1155 if ($last < time()-60) {
1160 # Tell client OK or not
1161 print $outfd "$ok\n";
1164 elsif ($inline =~ /\S/) {
1165 # Unknown line from pipe?
1166 print DEBUG "main: Unknown line from pipe $inline\n";
1167 print STDERR "Unknown line from pipe $inline\n";
1171 close($infd); close($outfd);
1172 $passin[$i] = $passout[$i] = undef;
1176 @passin = grep { defined($_) } @passin;
1177 @passout = grep { defined($_) } @passout;
1180 # handle_request(remoteaddress, localaddress, ipv6-flag)
1181 # Where the real work is done
1184 local ($acptip, $localip, $ipv6) = @_;
1185 print DEBUG "handle_request: from $acptip to $localip ipv6=$ipv6\n";
1186 if ($config{'loghost'}) {
1187 $acpthost = &to_hostname($acptip);
1188 $acpthost = $acptip if (!$acpthost);
1191 $acpthost = $acptip;
1193 $datestr = &http_date(time());
1195 $ok_message = "Document follows";
1196 $logged_code = undef;
1197 $reqline = $request_uri = $page = undef;
1201 # check address against access list
1202 if (@deny && &ip_match($acptip, $localip, @deny) ||
1203 @allow && !&ip_match($acptip, $localip, @allow)) {
1204 &http_error(403, "Access denied for $acptip");
1209 # Check address with TCP-wrappers
1210 if (!hosts_ctl($config{'pam'}, STRING_UNKNOWN,
1211 $acptip, STRING_UNKNOWN)) {
1212 &http_error(403, "Access denied for $acptip by TCP wrappers");
1216 print DEBUG "handle_request: passed IP checks\n";
1218 # Compute a timeout for the start of headers, based on the number of
1219 # child processes. As this increases, we use a shorter timeout to avoid
1220 # an attacker overloading the system.
1221 local $header_timeout = 60 + ($config{'maxconns'} - @childpids) * 10;
1223 # Wait at most 60 secs for start of headers for initial requests, or
1224 # 10 minutes for kept-alive connections
1226 vec($rmask, fileno(SOCK), 1) = 1;
1227 local $to = $checked_timeout ? 10*60 : $header_timeout;
1228 local $sel = select($rmask, undef, undef, $to);
1230 if ($checked_timeout) {
1231 print DEBUG "handle_request: exiting due to timeout of $to\n";
1235 &http_error(400, "Timeout",
1236 "Waited for that $to seconds for start of headers");
1240 print DEBUG "handle_request: passed timeout check\n";
1242 # Read the HTTP request and headers
1243 local $origreqline = &read_line();
1244 ($reqline = $origreqline) =~ s/\r|\n//g;
1245 $method = $page = $request_uri = undef;
1246 print DEBUG "handle_request reqline=$reqline\n";
1247 if (!$reqline && (!$use_ssl || $checked_timeout > 1)) {
1248 # An empty request .. just close the connection
1249 print DEBUG "handle_request: rejecting empty request\n";
1252 elsif ($reqline !~ /^(\S+)\s+(.*)\s+HTTP\/1\..$/) {
1253 print DEBUG "handle_request: invalid reqline=$reqline\n";
1255 # This could be an http request when it should be https
1257 local $url = $config{'musthost'} ?
1258 "https://$config{'musthost'}:$port/" :
1259 "https://$host:$port/";
1260 if ($config{'ssl_redirect'}) {
1261 # Just re-direct to the correct URL
1262 sleep(1); # Give browser a change to finish
1263 # sending its request
1264 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1265 &write_data("Date: $datestr\r\n");
1266 &write_data("Server: $config{'server'}\r\n");
1267 &write_data("Location: $url\r\n");
1268 &write_keep_alive(0);
1269 &write_data("\r\n");
1273 # Tell user the correct URL
1274 &http_error(200, "Bad Request", "This web server is running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1277 elsif (ord(substr($reqline, 0, 1)) == 128 && !$use_ssl) {
1278 # This could be an https request when it should be http ..
1279 # need to fake a HTTP response
1282 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
1283 eval "Net::SSLeay::load_error_strings()";
1284 $ssl_ctx = Net::SSLeay::CTX_new();
1285 Net::SSLeay::CTX_use_RSAPrivateKey_file(
1286 $ssl_ctx, $config{'keyfile'},
1287 &Net::SSLeay::FILETYPE_PEM);
1288 Net::SSLeay::CTX_use_certificate_file(
1290 $config{'certfile'} || $config{'keyfile'},
1291 &Net::SSLeay::FILETYPE_PEM);
1292 $ssl_con = Net::SSLeay::new($ssl_ctx);
1296 select(SSLw); $| = 1; select(STDOUT);
1297 print SSLw $origreqline;
1299 while(sysread(SOCK, $buf, 1) > 0) {
1306 Net::SSLeay::set_wfd($ssl_con, fileno(SOCK));
1307 Net::SSLeay::set_rfd($ssl_con, fileno(SSLr));
1308 Net::SSLeay::accept($ssl_con) || die "accept() failed";
1310 local $url = $config{'musthost'} ?
1311 "https://$config{'musthost'}:$port/" :
1312 "https://$host:$port/";
1313 if ($config{'ssl_redirect'}) {
1314 # Just re-direct to the correct URL
1315 sleep(1); # Give browser a change to
1316 # finish sending its request
1317 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1318 &write_data("Date: $datestr\r\n");
1319 &write_data("Server: $config{'server'}\r\n");
1320 &write_data("Location: $url\r\n");
1321 &write_keep_alive(0);
1322 &write_data("\r\n");
1326 # Tell user the correct URL
1327 &http_error(200, "Bad Request", "This web server is not running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1331 &http_error(400, "Bad Request");
1335 &http_error(400, "Bad Request");
1339 $request_uri = $page = $2;
1343 ($headline = &read_line()) =~ s/\r|\n//g;
1344 last if ($headline eq "");
1345 print DEBUG "handle_request: got headline $headline\n";
1346 if ($headline =~ /^(\S+):\s*(.*)$/) {
1347 $header{$lastheader = lc($1)} = $2;
1349 elsif ($headline =~ /^\s+(.*)$/) {
1350 $header{$lastheader} .= $headline;
1353 &http_error(400, "Bad Header $headline");
1356 if (defined($header{'host'})) {
1357 if ($header{'host'} =~ /^([^:]+):([0-9]+)$/) {
1358 ($host, $port) = ($1, $2);
1361 $host = $header{'host'};
1363 if ($config{'musthost'} && $host ne $config{'musthost'}) {
1364 # Disallowed hostname used
1365 &http_error(400, "Invalid HTTP hostname");
1369 if ($page =~ /^([^\?]+)\?(.*)$/) {
1370 # There is some query string information
1373 print DEBUG "handle_request: querystring=$querystring\n";
1374 if ($querystring !~ /=/) {
1375 $queryargs = $querystring;
1376 $queryargs =~ s/\+/ /g;
1377 $queryargs =~ s/%(..)/pack("c",hex($1))/ge;
1381 # Parse query-string parameters
1382 local @in = split(/\&/, $querystring);
1384 local ($k, $v) = split(/=/, $i, 2);
1385 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1386 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1391 $posted_data = undef;
1392 if ($method eq 'POST' &&
1393 $header{'content-type'} eq 'application/x-www-form-urlencoded') {
1394 # Read in posted query string information, up the configured maximum
1395 # post request length
1396 $clen = $header{"content-length"};
1397 $clen_read = $clen > $config{'max_post'} ? $config{'max_post'} : $clen;
1398 while(length($posted_data) < $clen_read) {
1399 $buf = &read_data($clen_read - length($posted_data));
1400 if (!length($buf)) {
1401 &http_error(500, "Failed to read POST request");
1403 chomp($posted_data);
1404 $posted_data =~ s/\015$//mg;
1405 $posted_data .= $buf;
1407 print DEBUG "clen_read=$clen_read clen=$clen posted_data=",length($posted_data),"\n";
1408 if ($clen_read != $clen && length($posted_data) > $clen) {
1409 # If the client sent more data than we asked for, chop the
1411 $posted_data = substr($posted_data, 0, $clen);
1413 if (length($posted_data) > $clen) {
1414 # When the client sent too much, delay so that it gets headers
1417 if ($header{'user-agent'} =~ /MSIE/ &&
1418 $header{'user-agent'} !~ /Opera/i) {
1419 # MSIE includes an extra newline in the data
1420 $posted_data =~ s/\r|\n//g;
1422 local @in = split(/\&/, $posted_data);
1424 local ($k, $v) = split(/=/, $i, 2);
1426 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1427 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1430 print DEBUG "handle_request: posted_data=$posted_data\n";
1433 # replace %XX sequences in page
1434 $page =~ s/%(..)/pack("c",hex($1))/ge;
1436 # Check if the browser's user agent indicates a mobile device
1437 $mobile_device = &is_mobile_useragent($header{'user-agent'});
1439 # Check if Host: header is for a mobile URL
1440 foreach my $m (@mobile_prefixes) {
1441 if ($header{'host'} =~ /^\Q$m\E/i) {
1446 # check for the logout flag file, and if existant deny authentication
1447 if ($config{'logout'} && -r $config{'logout'}.$in{'miniserv_logout_id'}) {
1448 print DEBUG "handle_request: logout flag set\n";
1449 $deny_authentication++;
1450 open(LOGOUT, $config{'logout'}.$in{'miniserv_logout_id'});
1451 chop($count = <LOGOUT>);
1455 open(LOGOUT, ">$config{'logout'}$in{'miniserv_logout_id'}");
1456 print LOGOUT "$count\n";
1460 unlink($config{'logout'}.$in{'miniserv_logout_id'});
1464 # check for any redirect for the requested URL
1465 foreach my $pfx (@strip_prefix) {
1466 my $l = length($pfx);
1467 if(length($page) >= $l &&
1468 substr($page,0,$l) eq $pfx) {
1469 $page=substr($page,$l);
1473 $simple = &simplify_path($page, $bogus);
1475 $rpath .= "&".$querystring if (defined($querystring));
1476 $redir = $redirect{$rpath};
1477 if (defined($redir)) {
1478 print DEBUG "handle_request: redir=$redir\n";
1479 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1480 &write_data("Date: $datestr\r\n");
1481 &write_data("Server: $config{'server'}\r\n");
1482 local $ssl = $use_ssl || $config{'inetd_ssl'};
1483 $portstr = $port == 80 && !$ssl ? "" :
1484 $port == 443 && $ssl ? "" : ":$port";
1485 $prot = $ssl ? "https" : "http";
1486 &write_data("Location: $prot://$host$portstr$redir\r\n");
1487 &write_keep_alive(0);
1488 &write_data("\r\n");
1492 # Check for a DAV request
1494 foreach my $d (@davpaths) {
1495 if ($simple eq $d || $simple =~ /^\Q$d\E\//) {
1500 if (!$davpath && ($method eq "SEARCH" || $method eq "PUT")) {
1501 &http_error(400, "Bad Request method $method");
1504 # Check for password if needed
1505 if ($config{'userfile'}) {
1506 print DEBUG "handle_request: Need authentication\n";
1510 # Session authentication is never used for connections by
1511 # another webmin server, or for specified pages, or for DAV, or XMLRPC,
1512 # or mobile browsers if requested.
1513 if ($header{'user-agent'} =~ /webmin/i ||
1514 $header{'user-agent'} =~ /$config{'agents_nosession'}/i ||
1515 $sessiononly{$simple} || $davpath ||
1516 $simple eq "/xmlrpc.cgi" ||
1517 $acptip eq $config{'host_nosession'} ||
1518 $mobile_device && $config{'mobile_nosession'}) {
1519 print DEBUG "handle_request: Forcing HTTP authentication\n";
1520 $config{'session'} = 0;
1523 # Check for SSL authentication
1524 if ($use_ssl && $verified_client) {
1525 $peername = Net::SSLeay::X509_NAME_oneline(
1526 Net::SSLeay::X509_get_subject_name(
1527 Net::SSLeay::get_peer_certificate(
1529 $u = &find_user_by_cert($peername);
1534 if ($use_syslog && !$validated) {
1535 syslog("crit", "%s",
1536 "Unknown SSL certificate $peername");
1540 if (!$validated && !$deny_authentication) {
1541 # check for IP-based authentication
1543 foreach $a (keys %ipaccess) {
1544 if ($acptip eq $a) {
1545 # It does! Auth as the user
1547 $baseauthuser = $authuser =
1553 # Check for normal HTTP authentication
1554 if (!$validated && !$deny_authentication && !$config{'session'} &&
1555 $header{authorization} =~ /^basic\s+(\S+)$/i) {
1556 # authorization given..
1557 ($authuser, $authpass) = split(/:/, &b64decode($1), 2);
1558 print DEBUG "handle_request: doing basic auth check authuser=$authuser authpass=$authpass\n";
1559 local ($vu, $expired, $nonexist) =
1560 &validate_user($authuser, $authpass, $host);
1561 print DEBUG "handle_request: vu=$vu expired=$expired nonexist=$nonexist\n";
1562 if ($vu && (!$expired || $config{'passwd_mode'} == 1)) {
1569 if ($use_syslog && !$validated) {
1570 syslog("crit", "%s",
1571 ($nonexist ? "Non-existent" :
1572 $expired ? "Expired" : "Invalid").
1573 " login as $authuser from $acpthost");
1575 if ($authuser =~ /\r|\n|\s/) {
1576 &http_error(500, "Invalid username",
1577 "Username contains invalid characters");
1579 if ($authpass =~ /\r|\n/) {
1580 &http_error(500, "Invalid password",
1581 "Password contains invalid characters");
1584 if ($config{'passdelay'} && !$config{'inetd'} && $authuser) {
1585 # check with main process for delay
1586 print DEBUG "handle_request: about to ask for password delay\n";
1587 print $PASSINw "delay $authuser $acptip $validated\n";
1588 <$PASSOUTr> =~ /(\d+) (\d+)/;
1590 print DEBUG "handle_request: password delay $1 $2\n";
1595 # Check for a visit to the special session login page
1596 if ($config{'session'} && !$deny_authentication &&
1597 $page eq $config{'session_login'}) {
1598 if ($in{'logout'} && $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1599 # Logout clicked .. remove the session
1601 print $PASSINw "delete $sid\n";
1602 local $louser = <$PASSOUTr>;
1605 $already_session_id = undef;
1606 $authuser = $baseauthuser = undef;
1609 syslog("info", "%s", "Logout by $louser from $acpthost");
1611 &run_logout_script($louser, $sid,
1613 &write_logout_utmp($louser, $actphost);
1618 if ($in{'user'} =~ /\r|\n|\s/) {
1619 &http_error(500, "Invalid username",
1620 "Username contains invalid characters");
1622 if ($in{'pass'} =~ /\r|\n/) {
1623 &http_error(500, "Invalid password",
1624 "Password contains invalid characters");
1627 local ($vu, $expired, $nonexist) =
1628 &validate_user($in{'user'}, $in{'pass'}, $host);
1629 local $hrv = &handle_login(
1630 $vu || $in{'user'}, $vu ? 1 : 0,
1631 $expired, $nonexist, $in{'pass'},
1632 $in{'notestingcookie'});
1633 return $hrv if (defined($hrv));
1637 # Check for a visit to the special PAM login page
1638 if ($config{'session'} && !$deny_authentication &&
1639 $use_pam && $config{'pam_conv'} && $page eq $config{'pam_login'} &&
1641 # A question has been entered .. submit it to the main process
1642 print DEBUG "handle_request: Got call to $page ($in{'cid'})\n";
1643 print DEBUG "handle_request: For PAM, authuser=$authuser\n";
1644 if ($in{'answer'} =~ /\r|\n/ || $in{'cid'} =~ /\r|\n|\s/) {
1645 &http_error(500, "Invalid response",
1646 "Response contains invalid characters");
1650 # Start of a new conversation - answer must be username
1651 $cid = &generate_random_id($in{'answer'});
1652 print $PASSINw "pamstart $cid $host $in{'answer'}\n";
1655 # A response to a previous question
1657 print $PASSINw "pamanswer $cid $in{'answer'}\n";
1660 # Read back the response, and the next question (if any)
1661 local $line = <$PASSOUTr>;
1662 $line =~ s/\r|\n//g;
1663 local ($rv, $question) = split(/\s+/, $line, 2);
1666 local $hrv = &handle_login(
1667 !$in{'cid'} && $in{'answer'} ? $in{'answer'}
1670 return $hrv if (defined($hrv));
1672 elsif ($rv == 1 || $rv == 3) {
1673 # Another question .. force use of PAM CGI
1676 $querystring .= "&cid=$cid&question=".
1678 $querystring .= "&password=1" if ($rv == 3);
1680 $page = $config{'pam_login'};
1681 $miniserv_internal = 1;
1685 # Got back a final ok or failure
1686 local ($user, $ok, $expired, $nonexist) =
1687 split(/\s+/, $question);
1688 local $hrv = &handle_login(
1689 $user, $ok, $expired, $nonexist, undef,
1690 $in{'notestingcookie'});
1691 return $hrv if (defined($hrv));
1694 # A message from PAM .. tell the user
1697 $querystring .= "&cid=$cid&message=".
1700 $page = $config{'pam_login'};
1701 $miniserv_internal = 1;
1706 # Check for a visit to the special password change page
1707 if ($config{'session'} && !$deny_authentication &&
1708 $page eq $config{'password_change'} && !$validated) {
1709 # Just let this slide ..
1711 $miniserv_internal = 3;
1714 # Check for an existing session
1715 if ($config{'session'} && !$validated) {
1716 if ($already_session_id) {
1717 $session_id = $already_session_id;
1718 $authuser = $already_authuser;
1721 elsif (!$deny_authentication &&
1722 $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1723 # Try all session cookies
1724 local $cookie = $header{'cookie'};
1725 while($cookie =~ s/(^|\s)$sidname=([a-f0-9]+)//) {
1728 $in{'webmin_notimeout'} ? 1 : 0;
1729 print $PASSINw "verify $session_id $notimeout\n";
1730 <$PASSOUTr> =~ /(\d+)\s+(\S+)/;
1732 # Valid session continuation
1735 $already_authuser = $authuser;
1744 # Invalid session ID .. don't set
1751 # Check for local authentication
1752 if ($localauth_user && !$header{'x-forwarded-for'} && !$header{'via'}) {
1753 my $luser = &get_user_details($localauth_user);
1755 # Local user exists in webmin users file
1757 $authuser = $localauth_user;
1760 # Check if local user is allowed by unixauth
1761 local @can = &can_user_login($localauth_user,
1765 $authuser = $localauth_user;
1768 $localauth_user = undef;
1774 # Check if this path allows anonymous access
1776 foreach $a (keys %anonymous) {
1777 if (substr($simple, 0, length($a)) eq $a) {
1778 # It does! Auth as the user, if IP access
1779 # control allows him.
1780 if (&check_user_ip($anonymous{$a}) &&
1781 &check_user_time($anonymous{$a})) {
1783 $baseauthuser = $authuser =
1791 # Check if this path allows unauthenticated access
1792 local ($u, $unauth);
1793 foreach $u (@unauth) {
1794 $unauth++ if ($simple =~ /$u/);
1796 if (!$bogus && $unauth) {
1797 # Unauthenticated directory or file request - approve it
1799 $baseauthuser = $authuser = undef;
1804 if ($blocked == 0) {
1805 # No password given.. ask
1806 if ($config{'pam_conv'} && $use_pam) {
1807 # Force CGI for PAM question, starting with
1808 # the username which is always needed
1811 $querystring .= "&initial=1&question=".
1812 &urlize("Username");
1813 $querystring .= "&failed=$failed_user" if ($failed_user);
1814 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1816 $page = $config{'pam_login'};
1817 $miniserv_internal = 1;
1820 elsif ($config{'session'}) {
1821 # Force CGI for session login
1824 $querystring .= "&logout=1&page=/";
1827 # Re-direct to current module only
1828 local $rpage = $request_uri;
1829 if (!$config{'loginkeeppage'}) {
1830 $rpage =~ s/\?.*$//;
1831 $rpage =~ s/[^\/]+$//
1833 $querystring = "page=".&urlize($rpage);
1836 $querystring .= "&failed=$failed_user" if ($failed_user);
1837 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1839 $page = $config{'session_login'};
1840 $miniserv_internal = 1;
1844 # Ask for login with HTTP authentication
1845 &write_data("HTTP/1.0 401 Unauthorized\r\n");
1846 &write_data("Date: $datestr\r\n");
1847 &write_data("Server: $config{'server'}\r\n");
1848 &write_data("WWW-authenticate: Basic ".
1849 "realm=\"$config{'realm'}\"\r\n");
1850 &write_keep_alive(0);
1851 &write_data("Content-type: text/html\r\n");
1852 &write_data("\r\n");
1853 &reset_byte_count();
1854 &write_data("<html>\n");
1855 &write_data("<head><title>Unauthorized</title></head>\n");
1856 &write_data("<body><h1>Unauthorized</h1>\n");
1857 &write_data("A password is required to access this\n");
1858 &write_data("web server. Please try again. <p>\n");
1859 &write_data("</body></html>\n");
1860 &log_request($acpthost, undef, $reqline, 401, &byte_count());
1864 elsif ($blocked == 1) {
1865 # when the host has been blocked, give it an error
1866 &http_error(403, "Access denied for $acptip. The host ".
1867 "has been blocked because of too ".
1868 "many authentication failures.");
1870 elsif ($blocked == 2) {
1871 # when the user has been blocked, give it an error
1872 &http_error(403, "Access denied. The user ".
1873 "has been blocked because of too ".
1874 "many authentication failures.");
1878 # Get the real Webmin username
1879 local @can = &can_user_login($authuser, undef, $host);
1880 $baseauthuser = $can[3] || $authuser;
1882 if ($config{'remoteuser'} && !$< && $validated) {
1883 # Switch to the UID of the remote user (if he exists)
1884 local @u = getpwnam($authuser);
1885 if (@u && $< != $u[2]) {
1886 $( = $u[3]; $) = "$u[3] $u[3]";
1887 ($>, $<) = ($u[2], $u[2]);
1890 &http_error(500, "Unix user $authuser does not exist");
1896 # Check per-user IP access control
1897 if (!&check_user_ip($baseauthuser)) {
1898 &http_error(403, "Access denied for $acptip for $baseauthuser");
1902 # Check per-user allowed times
1903 if (!&check_user_time($baseauthuser)) {
1904 &http_error(403, "Access denied at the current time");
1908 $uinfo = &get_user_details($baseauthuser);
1910 # Validate the path, and convert to canonical form
1912 $simple = &simplify_path($page, $bogus);
1913 print DEBUG "handle_request: page=$page simple=$simple\n";
1915 &http_error(400, "Invalid path");
1918 # Check for a DAV request
1920 return &handle_dav_request($davpath);
1923 # Work out the active theme(s)
1924 local $preroots = $mobile_device && defined($config{'mobile_preroot'}) ?
1925 $config{'mobile_preroot'} :
1926 $authuser && defined($config{'preroot_'.$authuser}) ?
1927 $config{'preroot_'.$authuser} :
1928 $uinfo && defined($uinfo->{'preroot'}) ?
1929 $uinfo->{'preroot'} :
1931 local @preroots = reverse(split(/\s+/, $preroots));
1933 # Canonicalize the directories
1934 foreach my $preroot (@preroots) {
1935 # Always under the current webmin root
1936 $preroot =~ s/^.*\///g;
1937 $preroot = $roots[0].'/'.$preroot;
1940 # Look in the theme root directories first
1941 local ($full, @stfull);
1943 foreach my $preroot (@preroots) {
1946 $full = $preroot.$sofar;
1947 $scriptname = $simple;
1948 foreach $b (split(/\//, $simple)) {
1949 if ($b ne "") { $sofar .= "/$b"; }
1950 $full = $preroot.$sofar;
1951 @stfull = stat($full);
1952 if (!@stfull) { undef($full); last; }
1954 # Check if this is a directory
1956 # It is.. go on parsing
1964 # Check if this is a CGI program
1965 if (&get_type($full) eq "internal/cgi") {
1966 $pathinfo = substr($simple, length($sofar));
1967 $pathinfo .= "/" if ($page =~ /\/$/);
1968 $scriptname = $sofar;
1973 # Don't stop at a directory unless this is the last theme, which
1974 # is the 'real' one that provides the .cgi scripts
1975 if ($is_directory && $preroot ne $preroots[$#preroots]) {
1982 $cgi_pwd = $roots[0];
1984 elsif ($is_directory) {
1985 $cgi_pwd = "$roots[0]$sofar";
1988 "$roots[0]$sofar" =~ /^(.*\/)[^\/]+$/;
1991 $foundroot = $preroot;
1992 if ($is_directory) {
1993 # Check for index files in the directory
1995 foreach $idx (split(/\s+/, $config{"index_docs"})) {
1996 $idxfull = "$full/$idx";
1997 local @stidxfull = stat($idxfull);
1998 if (-r _ && !-d _) {
2000 @stfull = @stidxfull;
2003 if ($scriptname ne "/");
2008 @stfull = stat($full) if (!$foundidx);
2011 last if ($foundroot);
2013 print DEBUG "handle_request: initial full=$full\n";
2015 # Look in the real root directories, stopping when we find a file or directory
2016 if (!$full || $is_directory) {
2017 ROOT: foreach $root (@roots) {
2019 $full = $root.$sofar;
2020 $scriptname = $simple;
2021 foreach $b ($simple eq "/" ? ( "" ) : split(/\//, $simple)) {
2022 if ($b ne "") { $sofar .= "/$b"; }
2023 $full = $root.$sofar;
2024 @stfull = stat($full);
2029 # Check if this is a directory
2031 # It is.. go on parsing
2035 # Check if this is a CGI program
2036 if (&get_type($full) eq "internal/cgi") {
2037 $pathinfo = substr($simple, length($sofar));
2038 $pathinfo .= "/" if ($page =~ /\/$/);
2039 $scriptname = $sofar;
2044 # Run CGI in the same directory as whatever file
2046 $full =~ /^(.*\/)[^\/]+$/; $cgi_pwd = $1;
2055 if (!@stfull) { &http_error(404, "File not found"); }
2057 print DEBUG "handle_request: full=$full\n";
2058 @stfull = stat($full) if (!@stfull);
2060 # check filename against denyfile regexp
2061 local $denyfile = $config{'denyfile'};
2062 if ($denyfile && $full =~ /$denyfile/) {
2063 &http_error(403, "Access denied to $page");
2067 # Reached the end of the path OK.. see what we've got
2069 # See if the URL ends with a / as it should
2070 print DEBUG "handle_request: found a directory\n";
2071 if ($page !~ /\/$/) {
2072 # It doesn't.. redirect
2073 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2074 $ssl = $use_ssl || $config{'inetd_ssl'};
2075 $portstr = $port == 80 && !$ssl ? "" :
2076 $port == 443 && $ssl ? "" : ":$port";
2077 &write_data("Date: $datestr\r\n");
2078 &write_data("Server: $config{server}\r\n");
2079 $prot = $ssl ? "https" : "http";
2080 &write_data("Location: $prot://$host$portstr$page/\r\n");
2081 &write_keep_alive(0);
2082 &write_data("\r\n");
2083 &log_request($acpthost, $authuser, $reqline, 302, 0);
2086 # A directory.. check for index files
2088 foreach $idx (split(/\s+/, $config{"index_docs"})) {
2089 $idxfull = "$full/$idx";
2090 @stidxfull = stat($idxfull);
2091 if (-r _ && !-d _) {
2094 @stfull = @stidxfull;
2095 $scriptname .= "/" if ($scriptname ne "/");
2100 @stfull = stat($full) if (!$foundidx);
2103 # This is definately a directory.. list it
2104 print DEBUG "handle_request: listing directory\n";
2105 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2106 "Date: $datestr\r\n".
2107 "Server: $config{server}\r\n".
2108 "Content-type: text/html\r\n";
2110 &write_keep_alive(0);
2111 &write_data("\r\n");
2112 &reset_byte_count();
2113 &write_data("<h1>Index of $simple</h1>\n");
2114 &write_data("<pre>\n");
2115 &write_data(sprintf "%-35.35s %-20.20s %-10.10s\n",
2116 "Name", "Last Modified", "Size");
2117 &write_data("<hr>\n");
2118 opendir(DIR, $full);
2119 while($df = readdir(DIR)) {
2120 if ($df =~ /^\./) { next; }
2121 $fulldf = $full eq "/" ? $full.$df : $full."/".$df;
2122 (@stbuf = stat($fulldf)) || next;
2123 if (-d _) { $df .= "/"; }
2124 @tm = localtime($stbuf[9]);
2125 $fdate = sprintf "%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d",
2126 $tm[3],$tm[4]+1,$tm[5]+1900,
2127 $tm[0],$tm[1],$tm[2];
2128 $len = length($df); $rest = " "x(35-$len);
2130 "<a href=\"%s\">%-${len}.${len}s</a>$rest %-20.20s %-10.10s\n",
2131 $df, $df, $fdate, $stbuf[7]);
2134 &log_request($acpthost, $authuser, $reqline, $ok_code, &byte_count());
2138 # CGI or normal file
2140 if (&get_type($full) eq "internal/cgi" && $validated != 4) {
2141 # A CGI program to execute
2142 print DEBUG "handle_request: executing CGI\n";
2143 $envtz = $ENV{"TZ"};
2144 $envuser = $ENV{"USER"};
2145 $envpath = $ENV{"PATH"};
2146 $envlang = $ENV{"LANG"};
2147 $envroot = $ENV{"SystemRoot"};
2148 $envperllib = $ENV{'PERLLIB'};
2149 foreach my $k (keys %ENV) {
2152 $ENV{"PATH"} = $envpath if ($envpath);
2153 $ENV{"TZ"} = $envtz if ($envtz);
2154 $ENV{"USER"} = $envuser if ($envuser);
2155 $ENV{"OLD_LANG"} = $envlang if ($envlang);
2156 $ENV{"SystemRoot"} = $envroot if ($envroot);
2157 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
2158 $ENV{"HOME"} = $user_homedir;
2159 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
2160 $ENV{"SERVER_NAME"} = $host;
2161 $ENV{"SERVER_ADMIN"} = $config{"email"};
2162 $ENV{"SERVER_ROOT"} = $roots[0];
2163 $ENV{"SERVER_REALROOT"} = $realroot;
2164 $ENV{"SERVER_PORT"} = $port;
2165 $ENV{"REMOTE_HOST"} = $acpthost;
2166 $ENV{"REMOTE_ADDR"} = $acptip;
2167 $ENV{"REMOTE_ADDR_PROTOCOL"} = $ipv6 ? 6 : 4;
2168 $ENV{"REMOTE_USER"} = $authuser;
2169 $ENV{"BASE_REMOTE_USER"} = $authuser ne $baseauthuser ?
2170 $baseauthuser : undef;
2171 $ENV{"REMOTE_PASS"} = $authpass if (defined($authpass) &&
2172 $config{'pass_password'});
2173 if ($uinfo && $uinfo->{'proto'}) {
2174 $ENV{"REMOTE_USER_PROTO"} = $uinfo->{'proto'};
2175 $ENV{"REMOTE_USER_ID"} = $uinfo->{'id'};
2177 print DEBUG "REMOTE_USER = ",$ENV{"REMOTE_USER"},"\n";
2178 print DEBUG "BASE_REMOTE_USER = ",$ENV{"BASE_REMOTE_USER"},"\n";
2179 print DEBUG "proto=$uinfo->{'proto'} id=$uinfo->{'id'}\n" if ($uinfo);
2180 $ENV{"SSL_USER"} = $peername if ($validated == 2);
2181 $ENV{"ANONYMOUS_USER"} = "1" if ($validated == 3 || $validated == 4);
2182 $ENV{"DOCUMENT_ROOT"} = $roots[0];
2183 $ENV{"DOCUMENT_REALROOT"} = $realroot;
2184 $ENV{"GATEWAY_INTERFACE"} = "CGI/1.1";
2185 $ENV{"SERVER_PROTOCOL"} = "HTTP/1.0";
2186 $ENV{"REQUEST_METHOD"} = $method;
2187 $ENV{"SCRIPT_NAME"} = $scriptname;
2188 $ENV{"SCRIPT_FILENAME"} = $full;
2189 $ENV{"REQUEST_URI"} = $request_uri;
2190 $ENV{"PATH_INFO"} = $pathinfo;
2192 $ENV{"PATH_TRANSLATED"} = "$roots[0]$pathinfo";
2193 $ENV{"PATH_REALTRANSLATED"} = "$realroot$pathinfo";
2195 $ENV{"QUERY_STRING"} = $querystring;
2196 $ENV{"MINISERV_CONFIG"} = $config_file;
2197 $ENV{"HTTPS"} = "ON" if ($use_ssl || $config{'inetd_ssl'});
2198 $ENV{"MINISERV_PID"} = $miniserv_main_pid;
2199 $ENV{"SESSION_ID"} = $session_id if ($session_id);
2200 $ENV{"LOCAL_USER"} = $localauth_user if ($localauth_user);
2201 $ENV{"MINISERV_INTERNAL"} = $miniserv_internal if ($miniserv_internal);
2202 if (defined($header{"content-length"})) {
2203 $ENV{"CONTENT_LENGTH"} = $header{"content-length"};
2205 if (defined($header{"content-type"})) {
2206 $ENV{"CONTENT_TYPE"} = $header{"content-type"};
2208 foreach $h (keys %header) {
2209 ($hname = $h) =~ tr/a-z/A-Z/;
2211 $ENV{"HTTP_$hname"} = $header{$h};
2213 $ENV{"PWD"} = $cgi_pwd;
2214 foreach $k (keys %config) {
2215 if ($k =~ /^env_(\S+)$/) {
2216 $ENV{$1} = $config{$k};
2219 delete($ENV{'HTTP_AUTHORIZATION'});
2220 $ENV{'HTTP_COOKIE'} =~ s/;?\s*$sidname=([a-f0-9]+)//;
2221 $ENV{'MOBILE_DEVICE'} = 1 if ($mobile_device);
2223 # Check if the CGI can be handled internally
2225 local $first = <CGI>;
2227 $first =~ s/[#!\r\n]//g;
2228 $nph_script = ($full =~ /\/nph-([^\/]+)$/);
2230 if (!$config{'forkcgis'} &&
2231 ($first eq $perl_path || $first eq $linked_perl_path) &&
2233 $config{'internalcgis'}) {
2234 # setup environment for eval
2236 @ARGV = split(/\s+/, $queryargs);
2239 # Already read the post input
2240 $postinput = $posted_data;
2242 $clen = $header{"content-length"};
2243 $SIG{'CHLD'} = 'DEFAULT';
2245 # Have SOCK closed if the perl exec's something
2247 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
2251 if ($config{'log'}) {
2252 open(MINISERVLOG, ">>$config{'logfile'}");
2253 if ($config{'logperms'}) {
2254 chmod(oct($config{'logperms'}),
2255 $config{'logfile'});
2258 chmod(0600, $config{'logfile'});
2261 $doing_cgi_eval = 1;
2262 $main_process_id = $$;
2264 if ($full =~ /^\Q$foundroot\E\/([^\/]+)\//) {
2265 # Eval in package from Webmin module name
2267 $pkg =~ s/[^A-Za-z0-9]/_/g;
2272 tie(*STDOUT, 'miniserv');
2273 tie(*STDIN, 'miniserv');
2274 do \$miniserv::full;
2277 $doing_cgi_eval = 0;
2280 &http_error(500, "Perl execution failed",
2281 $config{'noshowstderr'} ? undef : $@);
2283 elsif (!$doneheaders && !$nph_script) {
2284 &http_error(500, "Missing Headers");
2291 # fork the process that actually executes the CGI
2292 pipe(CGIINr, CGIINw);
2293 pipe(CGIOUTr, CGIOUTw);
2294 pipe(CGIERRr, CGIERRw);
2295 if (!($cgipid = fork())) {
2296 @execargs = ( $full, split(/\s+/, $queryargs) );
2299 open(STDIN, "<&CGIINr");
2300 open(STDOUT, ">&CGIOUTw");
2301 open(STDERR, ">&CGIERRw");
2302 close(CGIINw); close(CGIOUTr); close(CGIERRr);
2304 die "Failed to exec $full : $!\n";
2307 close(CGIINr); close(CGIOUTw); close(CGIERRw);
2310 # write CGI input to a temp file
2311 $infile = "$config{'tempbase'}.$$";
2312 open(CGIINw, ">$infile");
2313 # NOT binary mode, as CGIs don't read in it!
2318 # already read the posted data
2319 print CGIINw $posted_data;
2321 $clen = $header{"content-length"};
2322 if ($method eq "POST" && $clen_read < $clen) {
2323 $SIG{'PIPE'} = 'IGNORE';
2325 while($got < $clen) {
2326 $buf = &read_data($clen-$got);
2327 if (!length($buf)) {
2328 kill('TERM', $cgipid);
2329 unlink($infile) if ($infile);
2330 &http_error(500, "Failed to read ".
2333 $got += length($buf);
2334 local ($wrote) = (print CGIINw $buf);
2337 # If the CGI terminated early, we still need to read
2338 # from the browser and throw away
2339 while($got < $clen) {
2340 $buf = &read_data($clen-$got);
2341 if (!length($buf)) {
2342 kill('TERM', $cgipid);
2343 unlink($infile) if ($infile);
2344 &http_error(500, "Failed to read ".
2347 $got += length($buf);
2349 $SIG{'PIPE'} = 'DEFAULT';
2355 # Run the CGI program, and feed it input
2357 local $qqueryargs = join(" ", map { "\"$_\"" }
2358 split(/\s+/, $queryargs));
2359 if ($first =~ /(perl|perl.exe)$/i) {
2360 # On Windows, run with Perl
2361 open(CGIOUTr, "$perl_path \"$full\" $qqueryargs <$infile |");
2364 open(CGIOUTr, "\"$full\" $qqueryargs <$infile |");
2370 # read back cgi headers
2371 select(CGIOUTr); $|=1; select(STDOUT);
2375 $line =~ s/\r|\n//g;
2377 if ($got_blank || %cgiheader) { last; }
2381 if ($line !~ /^(\S+):\s+(.*)$/) {
2382 $errs = &read_errors(CGIERRr);
2383 close(CGIOUTr); close(CGIERRr);
2384 unlink($infile) if ($infile);
2385 &http_error(500, "Bad Header", $errs);
2387 $cgiheader{lc($1)} = $2;
2388 push(@cgiheader, [ $1, $2 ]);
2390 if ($cgiheader{"location"}) {
2391 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2392 &write_data("Date: $datestr\r\n");
2393 &write_data("Server: $config{'server'}\r\n");
2394 &write_keep_alive(0);
2395 # ignore the rest of the output. This is a hack,
2396 # but is necessary for IE in some cases :(
2397 close(CGIOUTr); close(CGIERRr);
2399 elsif ($cgiheader{"content-type"} eq "") {
2400 close(CGIOUTr); close(CGIERRr);
2401 unlink($infile) if ($infile);
2402 $errs = &read_errors(CGIERRr);
2403 &http_error(500, "Missing Content-Type Header",
2404 $config{'noshowstderr'} ? undef : $errs);
2407 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2408 &write_data("Date: $datestr\r\n");
2409 &write_data("Server: $config{'server'}\r\n");
2410 &write_keep_alive(0);
2412 foreach $h (@cgiheader) {
2413 &write_data("$h->[0]: $h->[1]\r\n");
2415 &write_data("\r\n");
2417 &reset_byte_count();
2418 while($line = <CGIOUTr>) {
2423 unlink($infile) if ($infile);
2429 print DEBUG "handle_request: outputting file\n";
2430 open(FILE, $full) || &http_error(404, "Failed to open file");
2432 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2433 "Date: $datestr\r\n".
2434 "Server: $config{server}\r\n".
2435 "Content-type: ".&get_type($full)."\r\n".
2436 "Content-length: $stfull[7]\r\n".
2437 "Last-Modified: ".&http_date($stfull[9])."\r\n".
2438 "Expires: ".&http_date(time()+$config{'expires'})."\r\n";
2440 $rv = &write_keep_alive();
2441 &write_data("\r\n");
2442 &reset_byte_count();
2443 while(read(FILE, $buf, 1024) > 0) {
2450 &log_request($acpthost, $authuser, $reqline,
2451 $logged_code ? $logged_code :
2452 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2456 # http_error(code, message, body, [dontexit])
2459 local $eh = $error_handler_recurse ? undef :
2460 $config{"error_handler_$_[0]"} ? $config{"error_handler_$_[0]"} :
2461 $config{'error_handler'} ? $config{'error_handler'} : undef;
2462 print DEBUG "http_error code=$_[0] message=$_[1] body=$_[2]\n";
2464 # Call a CGI program for the error
2466 $querystring = "code=$_[0]&message=".&urlize($_[1]).
2467 "&body=".&urlize($_[2]);
2468 $error_handler_recurse++;
2470 $ok_message = $_[1];
2474 # Use the standard error message display
2475 &write_data("HTTP/1.0 $_[0] $_[1]\r\n");
2476 &write_data("Server: $config{server}\r\n");
2477 &write_data("Date: $datestr\r\n");
2478 &write_data("Content-type: text/html\r\n");
2479 &write_keep_alive(0);
2480 &write_data("\r\n");
2481 &reset_byte_count();
2482 &write_data("<h1>Error - $_[1]</h1>\n");
2484 &write_data("<pre>$_[2]</pre>\n");
2487 &log_request($acpthost, $authuser, $reqline, $_[0], &byte_count())
2489 &log_error($_[1], $_[2] ? " : $_[2]" : "");
2496 if ($_[0] =~ /\.([A-z0-9]+)$/) {
2502 return "text/plain";
2505 # simplify_path(path, bogus)
2506 # Given a path, maybe containing stuff like ".." and "." convert it to a
2507 # clean, absolute form.
2510 local($dir, @bits, @fixedbits, $b);
2512 $dir =~ s/\\/\//g; # fix windows \ in path
2515 $dir =~ s/\0//g; # remove null bytes
2516 @bits = split(/\/+/, $dir);
2519 foreach $b (@bits) {
2523 elsif ($b eq ".." || $b eq "...") {
2525 if (scalar(@fixedbits) == 0) {
2533 push(@fixedbits, $b);
2536 return "/" . join('/', @fixedbits);
2540 # Converts a string from base64 format to normal
2543 local($str) = $_[0];
2545 $str =~ tr|A-Za-z0-9+=/||cd;
2547 $str =~ tr|A-Za-z0-9+/| -_|;
2548 while ($str =~ /(.{1,60})/gs) {
2549 my $len = chr(32 + length($1)*3/4);
2550 $res .= unpack("u", $len . $1 );
2555 # ip_match(remoteip, localip, [match]+)
2556 # Checks an IP address against a list of IPs, networks and networks/masks
2559 local(@io, @mo, @ms, $i, $j, $hn, $needhn);
2560 @io = &check_ip6address($_[0]) ? split(/:/, $_[0])
2561 : split(/\./, $_[0]);
2562 for($i=2; $i<@_; $i++) {
2563 $needhn++ if ($_[$i] =~ /^\*(\S+)$/);
2565 if ($needhn && !defined($hn = $ip_match_cache{$_[0]})) {
2566 # Reverse-lookup hostname if any rules match based on it
2567 $hn = &to_hostname($_[0]);
2568 if (&check_ip6address($_[0])) {
2569 $hn = "" if (&to_ip6address($hn) ne $_[0]);
2572 $hn = "" if (&to_ipaddress($hn) ne $_[0]);
2574 $ip_match_cache{$_[0]} = $hn;
2576 for($i=2; $i<@_; $i++) {
2577 local $mismatch = 0;
2578 if ($_[$i] =~ /^(\S+)\/(\d+)$/) {
2579 # Convert CIDR to netmask format
2580 $_[$i] = $1."/".&prefix_to_mask($2);
2582 if ($_[$i] =~ /^(\S+)\/(\S+)$/) {
2583 # Compare with IPv4 network/mask
2584 @mo = split(/\./, $1); @ms = split(/\./, $2);
2585 for($j=0; $j<4; $j++) {
2586 if ((int($io[$j]) & int($ms[$j])) != int($mo[$j])) {
2591 elsif ($_[$i] =~ /^\*(\S+)$/) {
2592 # Compare with hostname regexp
2593 $mismatch = 1 if ($hn !~ /$1$/);
2595 elsif ($_[$i] eq 'LOCAL' && &check_ipaddress($_[1])) {
2596 # Compare with local IPv4 network
2597 local @lo = split(/\./, $_[1]);
2599 $mismatch = 1 if ($lo[0] != $io[0]);
2601 elsif ($lo[0] < 192) {
2602 $mismatch = 1 if ($lo[0] != $io[0] ||
2606 $mismatch = 1 if ($lo[0] != $io[0] ||
2611 elsif ($_[$i] eq 'LOCAL' && &check_ip6address($_[1])) {
2612 # Compare with local IPv6 network, which is always first 4 words
2613 local @lo = split(/:/, $_[1]);
2614 for(my $i=0; $i<4; $i++) {
2615 $mismatch = 1 if ($lo[$i] ne $io[$i]);
2618 elsif ($_[$i] =~ /^[0-9\.]+$/) {
2619 # Compare with IPv4 address or network
2620 @mo = split(/\./, $_[$i]);
2621 while(@mo && !$mo[$#mo]) { pop(@mo); }
2622 for($j=0; $j<@mo; $j++) {
2623 if ($mo[$j] != $io[$j]) {
2628 elsif ($_[$i] =~ /^[a-f0-9:]+$/) {
2629 # Compare with IPv6 address or network
2630 @mo = split(/:/, $_[$i]);
2631 while(@mo && !$mo[$#mo]) { pop(@mo); }
2632 for($j=0; $j<@mo; $j++) {
2633 if ($mo[$j] ne $io[$j]) {
2638 elsif ($_[$i] !~ /^[0-9\.]+$/) {
2639 # Compare with hostname
2640 $mismatch = 1 if ($_[0] ne &to_ipaddress($_[$i]));
2642 return 1 if (!$mismatch);
2647 # users_match(&uinfo, user, ...)
2648 # Returns 1 if a user is in a list of users and groups
2651 local $uinfo = shift(@_);
2653 local @ginfo = getgrgid($uinfo->[3]);
2655 if ($u =~ /^\@(\S+)$/) {
2656 return 1 if (&is_group_member($uinfo, $1));
2658 elsif ($u =~ /^(\d*)-(\d*)$/ && ($1 || $2)) {
2659 return (!$1 || $uinfo[2] >= $1) &&
2660 (!$2 || $uinfo[2] <= $2);
2663 return 1 if ($u eq $uinfo->[0]);
2669 # restart_miniserv()
2670 # Called when a SIGHUP is received to restart the web server. This is done
2671 # by exec()ing perl with the same command line as was originally used
2672 sub restart_miniserv
2674 print STDERR "restarting miniserv\n";
2675 &log_error("Restarting");
2677 &close_all_sockets();
2679 dbmclose(%sessiondb);
2680 kill('KILL', $logclearer) if ($logclearer);
2681 kill('KILL', $extauth) if ($extauth);
2682 exec($perl_path, $miniserv_path, @miniserv_argv);
2683 die "Failed to restart miniserv with $perl_path $miniserv_path";
2696 # to_ipaddress(address, ...)
2701 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2702 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/ || $i =~ /^[a-f0-9:]+$/) {
2703 # A pattern or IP, not a hostname, so don't change
2708 push(@rv, join('.', unpack("CCCC", inet_aton($i))));
2711 return wantarray ? @rv : $rv[0];
2714 # to_ip6address(address, ...)
2719 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2720 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/ || $i =~ /^[a-f0-9:]+$/) {
2721 # A pattern, not a hostname, so don't change
2725 # Lookup IPv6 address
2726 local ($inaddr, $addr);
2727 (undef, undef, undef, $inaddr) =
2728 getaddrinfo($i, undef, Socket6::AF_INET6(), SOCK_STREAM);
2733 (undef, $addr) = unpack_sockaddr_in6($inaddr);
2734 push(@rv, inet_ntop(Socket6::AF_INET6(), $addr));
2738 return wantarray ? @rv : $rv[0];
2741 # to_hostname(ipv4|ipv6-address)
2742 # Reverse-resolves an IPv4 or 6 address to a hostname
2746 if (&check_ip6address($_[0])) {
2747 return gethostbyaddr(inet_pton(Socket6::AF_INET6(), $addr),
2748 Socket6::AF_INET6());
2751 return gethostbyaddr(inet_aton($addr), AF_INET);
2755 # read_line(no-wait, no-limit)
2756 # Reads one line from SOCK or SSL
2759 local ($nowait, $nolimit) = @_;
2760 local($idx, $more, $rv);
2761 while(($idx = index($main::read_buffer, "\n")) < 0) {
2762 if (length($main::read_buffer) > 10000 && !$nolimit) {
2763 &http_error(414, "Request too long",
2764 "Received excessive line <pre>$main::read_buffer</pre>");
2767 # need to read more..
2768 &wait_for_data_error() if (!$nowait);
2770 $more = Net::SSLeay::read($ssl_con);
2773 local $ok = sysread(SOCK, $more, 1024);
2774 $more = undef if ($ok <= 0);
2778 $rv = $main::read_buffer;
2779 undef($main::read_buffer);
2782 $main::read_buffer .= $more;
2784 $rv = substr($main::read_buffer, 0, $idx+1);
2785 $main::read_buffer = substr($main::read_buffer, $idx+1);
2790 # Reads up to some amount of data from SOCK or the SSL connection
2794 if (length($main::read_buffer)) {
2795 if (length($main::read_buffer) > $_[0]) {
2796 # Return the first part of the buffer
2797 $rv = substr($main::read_buffer, 0, $_[0]);
2798 $main::read_buffer = substr($main::read_buffer, $_[0]);
2802 # Return the whole buffer
2803 $rv = $main::read_buffer;
2804 undef($main::read_buffer);
2809 # Call SSL read function
2810 return Net::SSLeay::read($ssl_con, $_[0]);
2813 # Just do a normal read
2815 sysread(SOCK, $buf, $_[0]) || return undef;
2821 # Read a line from a file handle, using sysread to get a byte at a time
2828 $got = sysread($fh, $buf, 1);
2829 last if ($got <= 0);
2831 last if ($buf eq "\n");
2836 # wait_for_data(secs)
2837 # Waits at most the given amount of time for some data on SOCK, returning
2838 # 0 if not found, 1 if some arrived.
2842 vec($rmask, fileno(SOCK), 1) = 1;
2843 local $got = select($rmask, undef, undef, $_[0]);
2844 return $got == 0 ? 0 : 1;
2847 # wait_for_data_error()
2848 # Waits 60 seconds for data on SOCK, and fails if none arrives
2849 sub wait_for_data_error
2851 local $got = &wait_for_data(60);
2853 &http_error(400, "Timeout",
2854 "Waited more than 60 seconds for request data");
2858 # write_data(data, ...)
2859 # Writes a string to SOCK or the SSL connection
2862 local $str = join("", @_);
2864 Net::SSLeay::write($ssl_con, $str);
2867 syswrite(SOCK, $str, length($str));
2869 # Intentionally introduce a small delay to avoid problems where IE reports
2870 # the page as empty / DNS failed when it get a large response too quickly!
2871 select(undef, undef, undef, .01) if ($write_data_count%10 == 0);
2872 $write_data_count += length($str);
2875 # reset_byte_count()
2876 sub reset_byte_count { $write_data_count = 0; }
2879 sub byte_count { return $write_data_count; }
2881 # log_request(hostname, user, request, code, bytes)
2884 if ($config{'log'}) {
2885 local ($user, $ident, $headers);
2886 if ($config{'logident'}) {
2887 # add support for rfc1413 identity checking here
2889 else { $ident = "-"; }
2890 $user = $_[1] ? $_[1] : "-";
2891 local $dstr = &make_datestr();
2892 if (fileno(MINISERVLOG)) {
2893 seek(MINISERVLOG, 0, 2);
2896 open(MINISERVLOG, ">>$config{'logfile'}");
2897 chmod(0600, $config{'logfile'});
2899 if (defined($config{'logheaders'})) {
2900 foreach $h (split(/\s+/, $config{'logheaders'})) {
2901 $headers .= " $h=\"$header{$h}\"";
2904 elsif ($config{'logclf'}) {
2905 $headers = " \"$header{'referer'}\" \"$header{'user-agent'}\"";
2910 print MINISERVLOG "$_[0] $ident $user [$dstr] \"$_[2]\" ",
2911 "$_[3] $_[4]$headers\n";
2919 local @tm = localtime(time());
2920 return sprintf "%2.2d/%s/%4.4d:%2.2d:%2.2d:%2.2d %s",
2921 $tm[3], $month[$tm[4]], $tm[5]+1900,
2922 $tm[2], $tm[1], $tm[0], $timezone;
2925 # log_error(message)
2929 print STDERR "[",&make_datestr(),"] ",
2930 $acpthost ? ( "[",$acpthost,"] " ) : ( ),
2931 $page ? ( $page," : " ) : ( ),
2935 # read_errors(handle)
2936 # Read and return all input from some filehandle
2939 local($fh, $_, $rv);
2941 while(<$fh>) { $rv .= $_; }
2945 sub write_keep_alive
2948 if ($config{'nokeepalive'}) {
2949 # Keep alives have been disabled in config
2952 elsif (@childpids > $config{'maxconns'}*.8) {
2953 # Disable because nearing process limit
2957 # Keep alive specified by caller
2961 # Keep alive determined by browser
2962 $mode = $header{'connection'} =~ /keep-alive/i;
2964 &write_data("Connection: ".($mode ? "Keep-Alive" : "close")."\r\n");
2970 kill('TERM', @childpids) if (@childpids);
2971 kill('KILL', $logclearer) if ($logclearer);
2972 kill('KILL', $extauth) if ($extauth);
2978 local @tm = gmtime($_[0]);
2979 return sprintf "%s, %d %s %d %2.2d:%2.2d:%2.2d GMT",
2980 $weekday[$tm[6]], $tm[3], $month[$tm[4]], $tm[5]+1900,
2981 $tm[2], $tm[1], $tm[0];
2986 my $i; bless \$i, shift;
2992 my($buf,$len,$offset) = @_;
2993 &write_to_sock(substr($buf, $offset, $len));
2994 $miniserv::page_capture_out .= substr($buf, $offset, $len)
2995 if ($miniserv::page_capture);
3002 my $buf = join(defined($,) ? $, : "", @_);
3003 $buf .= $\ if defined($\);
3004 &write_to_sock($buf);
3005 $miniserv::page_capture_out .= $buf
3006 if ($miniserv::page_capture);
3013 my $buf = sprintf $fmt, @_;
3014 &write_to_sock($buf);
3015 $miniserv::page_capture_out .= $buf
3016 if ($miniserv::page_capture);
3019 # Send back already read data while we have it, then read from SOCK
3023 my $bufref = \$_[0];
3026 if ($postpos < length($postinput)) {
3027 # Reading from already fetched array
3028 my $left = length($postinput) - $postpos;
3029 my $canread = $len > $left ? $left : $len;
3030 substr($$bufref, $offset, $canread) =
3031 substr($postinput, $postpos, $canread);
3032 $postpos += $canread;
3036 # Read from network socket
3037 local $data = &read_data($len);
3038 if ($data eq '' && $len) {
3040 print STDERR "finished reading - shutting down socket\n";
3043 substr($$bufref, $offset, length($data)) = $data;
3044 return length($data);
3050 #print STDERR "open() called - should never happen!\n";
3053 # Read a line of input
3057 if ($postpos < length($postinput) &&
3058 ($idx = index($postinput, "\n", $postpos)) >= 0) {
3059 # A line exists in the memory buffer .. use it
3060 my $line = substr($postinput, $postpos, $idx-$postpos+1);
3065 # Need to read from the socket
3067 if ($postpos < length($postinput)) {
3068 # Start with in-memory data
3069 $line = substr($postinput, $postpos);
3070 $postpos = length($postinput);
3072 my $nl = &read_line(0, 1);
3075 print STDERR "finished reading - shutting down socket\n";
3078 $line .= $nl if (defined($nl));
3083 # Read one character of input
3088 my $got = READ($r, \$buf, 1, 0);
3089 return $got > 0 ? $buf : undef;
3094 return fileno(SOCK);
3101 # write_to_sock(data, ...)
3106 if ($doneheaders || $miniserv::nph_script) {
3111 while(!$doneheaders && $headers =~ s/^([^\r\n]*)(\r)?\n//) {
3112 if ($1 =~ /^(\S+):\s+(.*)$/) {
3113 $cgiheader{lc($1)} = $2;
3114 push(@cgiheader, [ $1, $2 ]);
3116 elsif ($1 !~ /\S/) {
3120 &http_error(500, "Bad Header");
3124 if ($cgiheader{"location"}) {
3126 "HTTP/1.0 302 Moved Temporarily\r\n");
3127 &write_data("Date: $datestr\r\n");
3128 &write_data("Server: $config{server}\r\n");
3129 &write_keep_alive(0);
3131 elsif ($cgiheader{"content-type"} eq "") {
3132 &http_error(500, "Missing Content-Type Header");
3135 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
3136 &write_data("Date: $datestr\r\n");
3137 &write_data("Server: $config{server}\r\n");
3138 &write_keep_alive(0);
3140 foreach $h (@cgiheader) {
3141 &write_data("$h->[0]: $h->[1]\r\n");
3143 &write_data("\r\n");
3144 &reset_byte_count();
3145 &write_data($headers);
3153 local $cert = Net::SSLeay::X509_STORE_CTX_get_current_cert($_[1]);
3155 local $errnum = Net::SSLeay::X509_STORE_CTX_get_error($_[1]);
3156 $verified_client = 1 if (!$errnum);
3163 if ($doing_cgi_eval && $$ == $main_process_id) {
3164 # A CGI program called exit! This is a horrible hack to
3165 # finish up before really exiting
3168 close($PASSINw); close($PASSOUTw);
3169 &log_request($acpthost, $authuser, $reqline,
3170 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
3175 # Convert a string to a form ok for putting in a URL
3177 local($tmp, $tmp2, $c);
3180 while(($c = chop($tmp)) ne "") {
3181 if ($c !~ /[A-z0-9]/) {
3182 $c = sprintf("%%%2.2X", ord($c));
3189 # validate_user(username, password, host)
3190 # Checks if some username and password are valid. Returns the modified username,
3191 # the expired / temp pass flag, and the non-existence flag
3194 local ($user, $pass, $host) = @_;
3195 return ( ) if (!$user);
3196 print DEBUG "validate_user: user=$user pass=$pass host=$host\n";
3197 local ($canuser, $canmode, $notexist, $webminuser, $sudo) =
3198 &can_user_login($user, undef, $host);
3199 print DEBUG "validate_user: canuser=$canuser canmode=$canmode notexist=$notexist webminuser=$webminuser sudo=$sudo\n";
3201 # User doesn't even exist, so go no further
3202 return ( undef, 0, 1 );
3204 elsif ($canmode == 0) {
3205 # User does exist but cannot login
3206 return ( $canuser, 0, 0 );
3208 elsif ($canmode == 1) {
3209 # Attempt Webmin authentication
3210 my $uinfo = &get_user_details($webminuser);
3212 &password_crypt($pass, $uinfo->{'pass'}) eq $uinfo->{'pass'}) {
3213 # Password is valid .. but check for expiry
3214 local $lc = $uinfo->{'lastchanges'};
3215 print DEBUG "validate_user: Password is valid lc=$lc pass_maxdays=$config{'pass_maxdays'}\n";
3216 if ($config{'pass_maxdays'} && $lc && !$uinfo->{'nochange'}) {
3217 local $daysold = (time() - $lc)/(24*60*60);
3218 print DEBUG "maxdays=$config{'pass_maxdays'} daysold=$daysold temppass=$uinfo->{'temppass'}\n";
3219 if ($config{'pass_lockdays'} &&
3220 $daysold > $config{'pass_lockdays'}) {
3221 # So old that the account is locked
3222 return ( undef, 0, 0 );
3224 elsif ($daysold > $config{'pass_maxdays'}) {
3225 # Password has expired
3226 return ( $user, 1, 0 );
3229 if ($uinfo->{'temppass'}) {
3230 # Temporary password - force change now
3231 return ( $user, 2, 0 );
3233 return ( $user, 0, 0 );
3236 print DEBUG "validate_user: User $webminuser not found\n";
3237 return ( undef, 0, 0 );
3240 print DEBUG "validate_user: User $webminuser password mismatch $pass != $uinfo->{'pass'}\n";
3241 return ( undef, 0, 0 );
3244 elsif ($canmode == 2 || $canmode == 3) {
3245 # Attempt PAM or passwd file authentication
3246 local $val = &validate_unix_user($canuser, $pass);
3247 print DEBUG "validate_user: unix val=$val\n";
3248 if ($val && $sudo) {
3249 # Need to check if this Unix user can sudo
3250 if (!&check_sudo_permissions($canuser, $pass)) {
3251 print DEBUG "validate_user: sudo failed\n";
3255 print DEBUG "validate_user: sudo passed\n";
3258 return $val == 2 ? ( $canuser, 1, 0 ) :
3259 $val == 1 ? ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3261 elsif ($canmode == 4) {
3262 # Attempt external authentication
3263 return &validate_external_user($canuser, $pass) ?
3264 ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3272 # validate_unix_user(user, password)
3273 # Returns 1 if a username and password are valid under unix, 0 if not,
3274 # or 2 if the account has expired.
3275 # Checks PAM if available, and falls back to reading the system password
3277 sub validate_unix_user
3281 $pam_username = $_[0];
3282 $pam_password = $_[1];
3283 eval "use Authen::PAM;";
3284 local $pamh = new Authen::PAM($config{'pam'}, $pam_username,
3287 local $pam_ret = $pamh->pam_authenticate();
3288 if ($pam_ret == PAM_SUCCESS()) {
3289 # Logged in OK .. make sure password hasn't expired
3290 local $acct_ret = $pamh->pam_acct_mgmt();
3291 if ($acct_ret == PAM_SUCCESS()) {
3292 $pamh->pam_open_session();
3295 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3296 $acct_ret == PAM_ACCT_EXPIRED()) {
3300 print STDERR "Unknown pam_acct_mgmt return value : $acct_ret\n";
3307 elsif ($config{'pam_only'}) {
3308 # Pam is not available, but configuration forces it's use!
3311 elsif ($config{'passwd_file'}) {
3312 # Check in a password file
3314 open(FILE, $config{'passwd_file'});
3315 if ($config{'passwd_file'} eq '/etc/security/passwd') {
3316 # Assume in AIX format
3319 if (/^\s*(\S+):/ && $1 eq $_[0]) {
3321 if (/^\s*password\s*=\s*(\S+)\s*$/) {
3322 $rv = $1 eq &password_crypt($_[1], $1) ?
3330 # Read the system password or shadow file
3332 local @l = split(/:/, $_, -1);
3333 local $u = $l[$config{'passwd_uindex'}];
3334 local $p = $l[$config{'passwd_pindex'}];
3336 $rv = $p eq &password_crypt($_[1], $p) ? 1 : 0;
3337 if ($config{'passwd_cindex'} ne '' && $rv) {
3338 # Password may have expired!
3339 local $c = $l[$config{'passwd_cindex'}];
3340 local $m = $l[$config{'passwd_mindex'}];
3341 local $day = time()/(24*60*60);
3342 if ($c =~ /^\d+/ && $m =~ /^\d+/ &&
3348 if ($p eq "" && $config{'passwd_blank'}) {
3349 # Force password change
3357 return $rv if ($rv);
3360 # Fallback option - check password returned by getpw*
3361 local @uinfo = getpwnam($_[0]);
3362 if ($uinfo[1] ne '' && &password_crypt($_[1], $uinfo[1]) eq $uinfo[1]) {
3366 return 0; # Totally failed
3369 # validate_external_user(user, pass)
3370 # Validate a user by passing the username and password to an external
3371 # squid-style authentication program
3372 sub validate_external_user
3374 return 0 if (!$config{'extauth'});
3376 local $str = "$_[0] $_[1]\n";
3377 syswrite(EXTAUTH, $str, length($str));
3378 local $resp = <EXTAUTH>;
3380 return $resp =~ /^OK/i ? 1 : 0;
3383 # can_user_login(username, no-append, host)
3384 # Checks if a user can login or not.
3385 # First return value is the username.
3386 # Second is 0 if cannot login, 1 if using Webmin pass, 2 if PAM, 3 if password
3387 # file, 4 if external.
3388 # Third is 1 if the user does not exist at all, 0 if he does.
3389 # Fourth is the Webmin username whose permissions apply, based on unixauth.
3390 # Fifth is a flag indicating if a sudo check is needed.
3393 local $uinfo = &get_user_details($_[0]);
3395 # See if this user exists in Unix and can be validated by the same
3396 # method as the unixauth webmin user
3397 local $realuser = $unixauth{$_[0]};
3401 eval { @uinfo = getpwnam($_[0]); }; # may fail on windows
3402 if (!$realuser && @uinfo) {
3403 # No unixauth entry for the username .. try his groups
3404 foreach my $ua (keys %unixauth) {
3405 if ($ua =~ /^\@(.*)$/) {
3406 if (&is_group_member(\@uinfo, $1)) {
3407 $realuser = $unixauth{$ua};
3413 if (!$realuser && @uinfo) {
3414 # Fall back to unix auth for all Unix users
3415 $realuser = $unixauth{"*"};
3417 if (!$realuser && $use_sudo && @uinfo) {
3418 # Allow login effectively as root, if sudo permits it
3422 if (!$realuser && !@uinfo && $config{'pamany'}) {
3423 # If the user completely doesn't exist, we can still allow
3424 # him to authenticate via PAM
3425 $realuser = $config{'pamany'};
3429 # For Usermin, always fall back to unix auth for any user,
3430 # so that later checks with domain added / removed are done.
3431 $realuser = $unixauth{"*"};
3433 return (undef, 0, 1, undef) if (!$realuser);
3434 local $uinfo = &get_user_details($realuser);
3435 return (undef, 0, 1, undef) if (!$uinfo);
3436 local $up = $uinfo->{'pass'};
3438 # Work out possible domain names from the hostname
3439 local @doms = ( $_[2] );
3440 if ($_[2] =~ /^([^\.]+)\.(\S+)$/) {
3444 if ($config{'user_mapping'} && !%user_mapping) {
3445 # Read the user mapping file
3447 open(MAPPING, $config{'user_mapping'});
3451 if (/^(\S+)\s+(\S+)/) {
3452 if ($config{'user_mapping_reverse'}) {
3453 $user_mapping{$1} = $2;
3456 $user_mapping{$2} = $1;
3463 # Check the user mapping file to see if there is an entry for the
3464 # user login in which specifies a new effective user
3466 foreach my $d (@doms) {
3467 $um ||= $user_mapping{"$_[0]\@$d"};
3469 $um ||= $user_mapping{$_[0]};
3470 if (defined($um) && ($_[1]&4) == 0) {
3471 # A mapping exists - use it!
3472 return &can_user_login($um, $_[1]+4, $_[2]);
3475 # Check if a user with the entered login and the domains appended
3476 # or prepended exists, and if so take it to be the effective user
3477 if (!@uinfo && $config{'domainuser'}) {
3478 # Try again with name.domain and name.firstpart
3479 local @firsts = map { /^([^\.]+)/; $1 } @doms;
3480 if (($_[1]&1) == 0) {
3482 foreach $a (@firsts, @doms) {
3483 foreach $p ("$_[0].${a}", "$_[0]-${a}",
3484 "${a}.$_[0]", "${a}-$_[0]",
3485 "$_[0]_${a}", "${a}_$_[0]") {
3486 local @vu = &can_user_login(
3487 $p, $_[1]+1, $_[2]);
3488 return @vu if ($vu[1]);
3494 # Check if the user entered a domain at the end of his username when
3495 # he really shouldn't have, and if so try without it
3496 if (!@uinfo && $config{'domainstrip'} &&
3497 $_[0] =~ /^(\S+)\@(\S+)$/ && ($_[1]&2) == 0) {
3498 local ($stripped, $dom) = ($1, $2);
3499 local @vu = &can_user_login($stripped, $_[1] + 2, $_[2]);
3500 return @vu if ($vu[1]);
3501 local @vu = &can_user_login($stripped, $_[1] + 2, $dom);
3502 return @vu if ($vu[1]);
3505 return ( undef, 0, 1, undef ) if (!@uinfo && !$pamany);
3508 if (defined(@allowusers)) {
3509 # Only allow people on the allow list
3510 return ( undef, 0, 0, undef )
3511 if (!&users_match(\@uinfo, @allowusers));
3513 elsif (defined(@denyusers)) {
3514 # Disallow people on the deny list
3515 return ( undef, 0, 0, undef )
3516 if (&users_match(\@uinfo, @denyusers));
3518 if ($config{'shells_deny'}) {
3520 open(SHELLS, $config{'shells_deny'});
3524 $found++ if ($_ eq $uinfo[8]);
3527 return ( undef, 0, 0, undef ) if (!$found);
3532 # PAM or passwd file authentication
3533 print DEBUG "can_user_login: Validate with PAM\n";
3534 return ( $_[0], $use_pam ? 2 : 3, 0, $realuser, $sudo );
3536 elsif ($up eq 'e') {
3537 # External authentication
3538 print DEBUG "can_user_login: Validate externally\n";
3539 return ( $_[0], 4, 0, $realuser, $sudo );
3542 # Fixed Webmin password
3543 print DEBUG "can_user_login: Validate by Webmin\n";
3544 return ( $_[0], 1, 0, $realuser, $sudo );
3547 elsif ($uinfo->{'pass'} eq 'x') {
3548 # Webmin user authenticated via PAM or password file
3549 return ( $_[0], $use_pam ? 2 : 3, 0, $_[0] );
3551 elsif ($uinfo->{'pass'} eq 'e') {
3552 # Webmin user authenticated externally
3553 return ( $_[0], 4, 0, $_[0] );
3556 # Normal Webmin user
3557 return ( $_[0], 1, 0, $_[0] );
3561 # the PAM conversation function for interactive logins
3564 $pam_conv_func_called++;
3571 $ans = $pam_username if ($code == PAM_PROMPT_ECHO_ON() );
3572 $ans = $pam_password if ($code == PAM_PROMPT_ECHO_OFF() );
3574 push @res, PAM_SUCCESS();
3577 push @res, PAM_SUCCESS();
3586 # get_socket_ip(handle, ipv6-flag)
3587 # Returns the local IP address of some connection, as both a string and in
3591 local ($fh, $ipv6) = @_;
3592 local $sn = getsockname($fh);
3593 return undef if (!$sn);
3594 return &get_address_ip($sn, $ipv6);
3597 # get_address_ip(address, ipv6-flag)
3598 # Given a sockaddr object in binary format, return the binary address, text
3599 # address and port number
3602 local ($sn, $ipv6) = @_;
3604 local ($p, $b) = unpack_sockaddr_in6($sn);
3605 return ($b, inet_ntop(Socket6::AF_INET6(), $b), $p);
3608 local ($p, $b) = unpack_sockaddr_in($sn);
3609 return ($b, inet_ntoa($b), $p);
3613 # get_socket_name(handle, ipv6-flag)
3614 # Returns the local hostname or IP address of some connection
3617 local ($fh, $ipv6) = @_;
3618 return $config{'host'} if ($config{'host'});
3619 local ($mybin, $myaddr) = &get_socket_ip($fh, $ipv6);
3620 if (!$get_socket_name_cache{$myaddr}) {
3622 if (!$config{'no_resolv_myname'}) {
3623 $myname = gethostbyaddr($mybin,
3624 $ipv6 ? Socket6::AF_INET6() : AF_INET);
3626 $myname ||= $myaddr;
3627 $get_socket_name_cache{$myaddr} = $myname;
3629 return $get_socket_name_cache{$myaddr};
3632 # run_login_script(username, sid, remoteip, localip)
3633 sub run_login_script
3635 if ($config{'login_script'}) {
3636 system($config{'login_script'}.
3637 " ".join(" ", map { quotemeta($_) || '""' } @_).
3638 " >/dev/null 2>&1 </dev/null");
3642 # run_logout_script(username, sid, remoteip, localip)
3643 sub run_logout_script
3645 if ($config{'logout_script'}) {
3646 system($config{'logout_script'}.
3647 " ".join(" ", map { quotemeta($_) || '""' } @_).
3648 " >/dev/null 2>&1 </dev/null");
3652 # close_all_sockets()
3653 # Closes all the main listening sockets
3654 sub close_all_sockets
3657 foreach $s (@socketfhs) {
3663 # Close all pipes for talking to sub-processes
3667 foreach $p (@passin) { close($p); }
3668 foreach $p (@passout) { close($p); }
3669 foreach $p (values %conversations) {
3670 if ($p->{'PAMOUTr'}) {
3671 close($p->{'PAMOUTr'});
3672 close($p->{'PAMINw'});
3677 # check_user_ip(user)
3678 # Returns 1 if some user is allowed to login from the accepting IP, 0 if not
3681 local ($username) = @_;
3682 local $uinfo = &get_user_details($username);
3683 return 1 if (!$uinfo);
3684 if ($uinfo->{'deny'} &&
3685 &ip_match($acptip, $localip, @{$uinfo->{'deny'}}) ||
3686 $uinfo->{'allow'} &&
3687 !&ip_match($acptip, $localip, @{$uinfo->{'allow'}})) {
3693 # check_user_time(user)
3694 # Returns 1 if some user is allowed to login at the current date and time
3697 local ($username) = @_;
3698 local $uinfo = &get_user_details($username);
3699 return 1 if (!$uinfo || !$uinfo->{'allowdays'} && !$uinfo->{'allowhours'});
3700 local @tm = localtime(time());
3701 if ($uinfo->{'allowdays'}) {
3702 # Make sure day is allowed
3703 return 0 if (&indexof($tm[6], @{$uinfo->{'allowdays'}}) < 0);
3705 if ($uinfo->{'allowhours'}) {
3706 # Make sure time is allowed
3707 local $m = $tm[2]*60+$tm[1];
3708 return 0 if ($m < $uinfo->{'allowhours'}->[0] ||
3709 $m > $uinfo->{'allowhours'}->[1]);
3714 # generate_random_id(password, [force-urandom])
3715 # Returns a random session ID number
3716 sub generate_random_id
3718 local ($pass, $force_urandom) = @_;
3720 if (!$bad_urandom) {
3721 # First try /dev/urandom, unless we have marked it as bad
3722 $SIG{ALRM} = "miniserv::urandom_timeout";
3724 if (open(RANDOM, "/dev/urandom")) {
3726 if (read(RANDOM, $tmpsid, 16) == 16) {
3727 $sid = lc(unpack('h*',$tmpsid));
3733 if (!$sid && !$force_urandom) {
3736 foreach $c (split(//, &unix_crypt($pass, substr($$, -2)))) {
3737 $sid += ord($c) * $mul;
3744 # handle_login(username, ok, expired, not-exists, password, [no-test-cookie])
3745 # Called from handle_session to either mark a user as logged in, or not
3748 local ($vu, $ok, $expired, $nonexist, $pass, $notest) = @_;
3749 $authuser = $vu if ($ok);
3751 # check if the test cookie is set
3752 if ($header{'cookie'} !~ /testing=1/ && $vu &&
3753 !$config{'no_testing_cookie'} && !$notest) {
3754 &http_error(500, "No cookies",
3755 "Your browser does not support cookies, ".
3756 "which are required for this web server to ".
3757 "work in session authentication mode");
3760 # check with main process for delay
3761 if ($config{'passdelay'} && $vu) {
3762 print DEBUG "handle_login: requesting delay vu=$vu acptip=$acptip ok=$ok\n";
3763 print $PASSINw "delay $vu $acptip $ok\n";
3764 <$PASSOUTr> =~ /(\d+) (\d+)/;
3767 print DEBUG "handle_login: delay=$1 blocked=$2\n";
3770 if ($ok && (!$expired ||
3771 $config{'passwd_mode'} == 1)) {
3772 # Logged in OK! Tell the main process about
3774 local $sid = &generate_random_id($pass);
3775 print DEBUG "handle_login: sid=$sid\n";
3776 print $PASSINw "new $sid $authuser $acptip\n";
3778 # Run the post-login script, if any
3779 &run_login_script($authuser, $sid,
3782 # Check for a redirect URL for the user
3783 local $rurl = &login_redirect($authuser, $pass, $host);
3784 print DEBUG "handle_login: redirect URL rurl=$rurl\n";
3786 # Got one .. go to it
3787 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3788 &write_data("Date: $datestr\r\n");
3789 &write_data("Server: $config{'server'}\r\n");
3790 &write_data("Location: $rurl\r\n");
3791 &write_keep_alive(0);
3792 &write_data("\r\n");
3793 &log_request($acpthost, $authuser, $reqline, 302, 0);
3796 # Set cookie and redirect to originally requested page
3797 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3798 &write_data("Date: $datestr\r\n");
3799 &write_data("Server: $config{'server'}\r\n");
3800 local $ssl = $use_ssl || $config{'inetd_ssl'};
3801 $portstr = $port == 80 && !$ssl ? "" :
3802 $port == 443 && $ssl ? "" : ":$port";
3803 $prot = $ssl ? "https" : "http";
3804 local $sec = $ssl ? "; secure" : "";
3805 #$sec .= "; httpOnly";
3806 if ($in{'page'} !~ /^\/[A-Za-z0-9\/\.\-\_]+$/) {
3807 # Make redirect URL safe
3811 &write_data("Set-Cookie: $sidname=$sid; path=/; expires=\"Thu, 31-Dec-2037 00:00:00\"$sec\r\n");
3814 &write_data("Set-Cookie: $sidname=$sid; path=/$sec\r\n");
3816 &write_data("Location: $prot://$host$portstr$in{'page'}\r\n");
3817 &write_keep_alive(0);
3818 &write_data("\r\n");
3819 &log_request($acpthost, $authuser, $reqline, 302, 0);
3820 syslog("info", "%s", "Successful login as $authuser from $acpthost") if ($use_syslog);
3821 &write_login_utmp($authuser, $acpthost);
3825 elsif ($ok && $expired &&
3826 ($config{'passwd_mode'} == 2 || $expired == 2)) {
3827 # Login was ok, but password has expired or was temporary. Need
3828 # to force display of password change form.
3831 $querystring = "&user=".&urlize($vu).
3833 "&expired=".$expired;
3836 $page = $config{'password_form'};
3838 $miniserv_internal = 2;
3839 syslog("crit", "%s",
3840 "Expired login as $vu ".
3841 "from $acpthost") if ($use_syslog);
3844 # Login failed, or password has expired. The login form will be
3845 # displayed again by later code
3847 $request_uri = $in{'page'};
3848 $already_session_id = undef;
3850 $authuser = $baseauthuser = undef;
3851 syslog("crit", "%s",
3852 ($nonexist ? "Non-existent" :
3853 $expired ? "Expired" : "Invalid").
3854 " login as $vu from $acpthost")
3860 # write_login_utmp(user, host)
3861 # Record the login by some user in utmp
3862 sub write_login_utmp
3865 # Write utmp record for login
3866 %utmp = ( 'ut_host' => $_[1],
3867 'ut_time' => time(),
3869 'ut_type' => 7, # user process
3870 'ut_pid' => $main_process_id,
3871 'ut_line' => $config{'pam'},
3873 if (defined(&User::Utmp::putut)) {
3874 User::Utmp::putut(\%utmp);
3877 User::Utmp::pututline(\%utmp);
3882 # write_logout_utmp(user, host)
3883 # Record the logout by some user in utmp
3884 sub write_logout_utmp
3887 # Write utmp record for logout
3888 %utmp = ( 'ut_host' => $_[1],
3889 'ut_time' => time(),
3891 'ut_type' => 8, # dead process
3892 'ut_pid' => $main_process_id,
3893 'ut_line' => $config{'pam'},
3895 if (defined(&User::Utmp::putut)) {
3896 User::Utmp::putut(\%utmp);
3899 User::Utmp::pututline(\%utmp);
3904 # pam_conversation_process(username, write-pipe, read-pipe)
3905 # This function is called inside a sub-process to communicate with PAM. It sends
3906 # questions down one pipe, and reads responses from another
3907 sub pam_conversation_process
3909 local ($user, $writer, $reader) = @_;
3910 $miniserv::pam_conversation_process_writer = $writer;
3911 $miniserv::pam_conversation_process_reader = $reader;
3912 eval "use Authen::PAM;";
3913 local $convh = new Authen::PAM(
3914 $config{'pam'}, $user, \&miniserv::pam_conversation_process_func);
3915 local $pam_ret = $convh->pam_authenticate();
3916 if ($pam_ret == PAM_SUCCESS()) {
3917 local $acct_ret = $convh->pam_acct_mgmt();
3918 if ($acct_ret == PAM_SUCCESS()) {
3919 $convh->pam_open_session();
3920 print $writer "x2 $user 1 0 0\n";
3922 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3923 $acct_ret == PAM_ACCT_EXPIRED()) {
3924 print $writer "x2 $user 1 1 0\n";
3927 print $writer "x0 Unknown PAM account status $acct_ret\n";
3931 print $writer "x2 $user 0 0 0\n";
3936 # pam_conversation_process_func(type, message, [type, message, ...])
3937 # A pipe that talks to both PAM and the master process
3938 sub pam_conversation_process_func
3941 select($miniserv::pam_conversation_process_writer); $| = 1; select(STDOUT);
3943 local ($type, $msg) = (shift, shift);
3945 local $ok = (print $miniserv::pam_conversation_process_writer "$type $msg\n");
3946 print $miniserv::pam_conversation_process_writer "\n";
3947 local $answer = <$miniserv::pam_conversation_process_reader>;
3948 $answer =~ s/\r|\n//g;
3949 push(@rv, PAM_SUCCESS(), $answer);
3951 push(@rv, PAM_SUCCESS());
3956 # Returns 4 new pipe file handles
3959 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3961 local %taken = ( (map { $_, 1 } @passin),
3962 (map { $_->{'PASSINr'} } values %conversations) );
3963 for($p=0; $taken{"PASSINr$p"}; $p++) { }
3964 $PASSINr = "PASSINr$p";
3965 $PASSINw = "PASSINw$p";
3966 $PASSOUTr = "PASSOUTr$p";
3967 $PASSOUTw = "PASSOUTw$p";
3968 pipe($PASSINr, $PASSINw);
3969 pipe($PASSOUTr, $PASSOUTw);
3970 select($PASSINw); $| = 1;
3971 select($PASSINr); $| = 1;
3972 select($PASSOUTw); $| = 1;
3973 select($PASSOUTw); $| = 1;
3975 return ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3978 # recv_pam_question(&conv, fd)
3979 # Reads one PAM question from the sub-process, and sends it to the HTTP handler.
3980 # Returns 0 if the conversation is over, 1 if not.
3981 sub recv_pam_question
3983 local ($conf, $fh) = @_;
3984 local $pr = $conf->{'PAMOUTr'};
3985 select($pr); $| = 1; select(STDOUT);
3986 local $line = <$pr>;
3987 $line =~ s/\r|\n//g;
3990 $line =~ s/\r|\n//g;
3992 $conf->{'last'} = time();
3995 print $fh "0 PAM conversation error\n";
3999 local ($type, $msg) = split(/\s+/, $line, 2);
4000 if ($type =~ /^x(\d+)/) {
4001 # Pass this status code through
4002 print $fh "$1 $msg\n";
4003 return $1 == 2 || $1 == 0 ? 0 : 1;
4005 elsif ($type == PAM_PROMPT_ECHO_ON()) {
4007 print $fh "1 $msg\n";
4010 elsif ($type == PAM_PROMPT_ECHO_OFF()) {
4012 print $fh "3 $msg\n";
4015 elsif ($type == PAM_ERROR_MSG() || $type == PAM_TEXT_INFO()) {
4016 # A message that does not require a response
4017 print $fh "4 $msg\n";
4022 print $fh "0 Unknown PAM message type $type\n";
4028 # send_pam_answer(&conv, answer)
4029 # Sends a response from the user to the PAM sub-process
4032 local ($conf, $answer) = @_;
4033 local $pw = $conf->{'PAMINw'};
4034 $conf->{'last'} = time();
4035 print $pw "$answer\n";
4038 # end_pam_conversation(&conv)
4039 # Clean up PAM conversation pipes and processes
4040 sub end_pam_conversation
4043 kill('KILL', $conv->{'pid'}) if ($conv->{'pid'});
4044 if ($conv->{'PAMINr'}) {
4045 close($conv->{'PAMINr'});
4046 close($conv->{'PAMOUTr'});
4047 close($conv->{'PAMINw'});
4048 close($conv->{'PAMOUTw'});
4050 delete($conversations{$conv->{'cid'}});
4053 # get_ipkeys(&miniserv)
4054 # Returns a list of IP address to key file mappings from a miniserv.conf entry
4058 foreach $k (keys %{$_[0]}) {
4059 if ($k =~ /^ipkey_(\S+)/) {
4060 local $ipkey = { 'ips' => [ split(/,/, $1) ],
4061 'key' => $_[0]->{$k},
4062 'index' => scalar(@rv) };
4063 $ipkey->{'cert'} = $_[0]->{'ipcert_'.$1};
4070 # create_ssl_context(keyfile, [certfile])
4071 sub create_ssl_context
4073 local ($keyfile, $certfile) = @_;
4075 eval { $ssl_ctx = Net::SSLeay::new_x_ctx() };
4076 $ssl_ctx ||= Net::SSLeay::CTX_new();
4077 $ssl_ctx || die "Failed to create SSL context : $!";
4078 if ($client_certs) {
4079 Net::SSLeay::CTX_load_verify_locations(
4080 $ssl_ctx, $config{'ca'}, "");
4081 Net::SSLeay::CTX_set_verify(
4082 $ssl_ctx, &Net::SSLeay::VERIFY_PEER, \&verify_client);
4084 if ($config{'extracas'}) {
4086 foreach $p (split(/\s+/, $config{'extracas'})) {
4087 Net::SSLeay::CTX_load_verify_locations(
4092 Net::SSLeay::CTX_use_RSAPrivateKey_file(
4094 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL key $keyfile";
4095 Net::SSLeay::CTX_use_certificate_file(
4096 $ssl_ctx, $certfile || $keyfile,
4097 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL cert $certfile";
4102 # ssl_connection_for_ip(socket, ipv6-flag)
4103 # Returns a new SSL connection object for some socket, or undef if failed
4104 sub ssl_connection_for_ip
4106 local ($sock, $ipv6) = @_;
4107 local $sn = getsockname($sock);
4109 print STDERR "Failed to get address for socket $sock\n";
4112 local (undef, $myip, undef) = &get_address_ip($sn, $ipv6);
4113 local $ssl_ctx = $ssl_contexts{$myip} || $ssl_contexts{"*"};
4114 local $ssl_con = Net::SSLeay::new($ssl_ctx);
4115 if ($config{'ssl_cipher_list'}) {
4116 # Force use of ciphers
4117 eval "Net::SSLeay::set_cipher_list(
4118 \$ssl_con, \$config{'ssl_cipher_list'})";
4120 print STDERR "SSL cipher $config{'ssl_cipher_list'} failed : ",
4126 Net::SSLeay::set_fd($ssl_con, fileno($sock));
4127 if (!Net::SSLeay::accept($ssl_con)) {
4128 print STDERR "Failed to initialize SSL connection\n";
4134 # login_redirect(username, password, host)
4135 # Calls the login redirect script (if configured), which may output a URL to
4136 # re-direct a user to after logging in.
4139 return undef if (!$config{'login_redirect'});
4140 local $quser = quotemeta($_[0]);
4141 local $qpass = quotemeta($_[1]);
4142 local $qhost = quotemeta($_[2]);
4143 local $url = `$config{'login_redirect'} $quser $qpass $qhost`;
4148 # reload_config_file()
4149 # Re-read %config, and call post-config actions
4150 sub reload_config_file
4152 &log_error("Reloading configuration");
4153 %config = &read_config_file($config_file);
4154 &update_vital_config();
4157 &build_config_mappings();
4158 &read_webmin_crons();
4159 if ($config{'session'}) {
4160 dbmclose(%sessiondb);
4161 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
4165 # read_config_file(file)
4166 # Reads the given config file, and returns a hash of values
4167 sub read_config_file
4170 open(CONF, $_[0]) || die "Failed to open config file $_[0] : $!";
4173 if (/^#/ || !/\S/) { next; }
4175 $name = $1; $val = $2;
4176 $name =~ s/^\s+//g; $name =~ s/\s+$//g;
4177 $val =~ s/^\s+//g; $val =~ s/\s+$//g;
4184 # update_vital_config()
4185 # Updates %config with defaults, and dies if something vital is missing
4186 sub update_vital_config
4188 my %vital = ("port", 80,
4190 "server", "MiniServ/0.01",
4191 "index_docs", "index.html index.htm index.cgi index.php",
4192 "addtype_html", "text/html",
4193 "addtype_txt", "text/plain",
4194 "addtype_gif", "image/gif",
4195 "addtype_jpg", "image/jpeg",
4196 "addtype_jpeg", "image/jpeg",
4197 "realm", "MiniServ",
4198 "session_login", "/session_login.cgi",
4199 "pam_login", "/pam_login.cgi",
4200 "password_form", "/password_form.cgi",
4201 "password_change", "/password_change.cgi",
4205 "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\$",
4207 "expires", 7*24*60*60,
4208 "pam_test_user", "root",
4210 foreach my $v (keys %vital) {
4212 if ($vital{$v} eq "") {
4213 die "Missing config option $v";
4215 $config{$v} = $vital{$v};
4218 if (!$config{'sessiondb'}) {
4219 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4220 $config{'sessiondb'} = "$1/sessiondb";
4222 if (!$config{'errorlog'}) {
4223 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
4224 $config{'errorlog'} = "$1/miniserv.error";
4226 if (!$config{'tempbase'}) {
4227 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4228 $config{'tempbase'} = "$1/cgitemp";
4230 if (!$config{'blockedfile'}) {
4231 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4232 $config{'blockedfile'} = "$1/blocked";
4234 if (!$config{'webmincron_dir'}) {
4235 $config_file =~ /^(.*)\/[^\/]+$/;
4236 $config{'webmincron_dir'} = "$1/webmincron/crons";
4238 if (!$config{'webmincron_last'}) {
4239 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
4240 $config{'webmincron_last'} = "$1/miniserv.lastcrons";
4242 if (!$config{'webmincron_wrapper'}) {
4243 $config{'webmincron_wrapper'} = $config{'root'}.
4244 "/webmincron/webmincron.pl";
4249 # Fills the %users and %certs hashes from the users file in %config
4258 undef(%lastchanges);
4261 if ($config{'userfile'}) {
4262 open(USERS, $config{'userfile'});
4265 local @user = split(/:/, $_, -1);
4266 $users{$user[0]} = $user[1];
4267 $certs{$user[0]} = $user[3] if ($user[3]);
4268 if ($user[4] =~ /^allow\s+(.*)/) {
4269 $allow{$user[0]} = $config{'alwaysresolve'} ?
4270 [ split(/\s+/, $1) ] :
4271 [ &to_ipaddress(split(/\s+/, $1)) ];
4273 elsif ($user[4] =~ /^deny\s+(.*)/) {
4274 $deny{$user[0]} = $config{'alwaysresolve'} ?
4275 [ split(/\s+/, $1) ] :
4276 [ &to_ipaddress(split(/\s+/, $1)) ];
4278 if ($user[5] =~ /days\s+(\S+)/) {
4279 $allowdays{$user[0]} = [ split(/,/, $1) ];
4281 if ($user[5] =~ /hours\s+(\d+)\.(\d+)-(\d+).(\d+)/) {
4282 $allowhours{$user[0]} = [ $1*60+$2, $3*60+$4 ];
4284 $lastchanges{$user[0]} = $user[6];
4285 $nochange{$user[0]} = $user[9];
4286 $temppass{$user[0]} = $user[10];
4291 # Test user DB, if configured
4292 if ($config{'userdb'}) {
4293 my $dbh = &connect_userdb($config{'userdb'});
4295 print STDERR "Failed to open users database : $dbh\n"
4298 &disconnect_userdb($config{'userdb'}, $dbh);
4303 # get_user_details(username)
4304 # Returns a hash ref of user details, either from config files or the user DB
4305 sub get_user_details
4307 my ($username) = @_;
4308 if (exists($users{$username})) {
4310 return { 'name' => $username,
4311 'pass' => $users{$username},
4312 'certs' => $certs{$username},
4313 'allow' => $allow{$username},
4314 'deny' => $deny{$username},
4315 'allowdays' => $allowdays{$username},
4316 'allowhours' => $allowhours{$username},
4317 'lastchanges' => $lastchanges{$username},
4318 'nochange' => $nochange{$username},
4319 'temppass' => $temppass{$username},
4320 'preroot' => $config{'preroot_'.$username},
4323 if ($config{'userdb'}) {
4324 # Try querying user database
4325 if (exists($get_user_details_cache{$username})) {
4327 return $get_user_details_cache{$username};
4329 print DEBUG "get_user_details: Connecting to user database\n";
4330 my ($dbh, $proto, $prefix, $args) = &connect_userdb($config{'userdb'});
4334 print DEBUG "get_user_details: Failed : $dbh\n";
4335 print STDERR "Failed to connect to user database : $dbh\n";
4337 elsif ($proto eq "mysql" || $proto eq "postgresql") {
4338 # Fetch user ID and password with SQL
4339 print DEBUG "get_user_details: Looking for $username in SQL\n";
4340 my $cmd = $dbh->prepare(
4341 "select id,pass from webmin_user where name = ?");
4342 if (!$cmd || !$cmd->execute($username)) {
4343 print STDERR "Failed to lookup user : ",
4347 my ($id, $pass) = $cmd->fetchrow();
4350 &disconnect_userdb($config{'userdb'}, $dbh);
4351 $get_user_details_cache{$username} = undef;
4352 print DEBUG "get_user_details: User not found\n";
4355 print DEBUG "get_user_details: id=$id pass=$pass\n";
4357 # Fetch attributes and add to user object
4358 print DEBUG "get_user_details: finding user attributes\n";
4359 my $cmd = $dbh->prepare(
4360 "select attr,value from webmin_user_attr where id = ?");
4361 if (!$cmd || !$cmd->execute($id)) {
4362 print STDERR "Failed to lookup user attrs : ",
4366 $user = { 'name' => $username,
4369 'proto' => $proto };
4370 while(my ($attr, $value) = $cmd->fetchrow()) {
4371 $attrs{$attr} = $value;
4375 elsif ($proto eq "ldap") {
4376 # Fetch user DN with LDAP
4377 print DEBUG "get_user_details: Looking for $username in LDAP\n";
4378 my $rv = $dbh->search(
4380 filter => '(&(cn='.$username.')(objectClass='.
4381 $args->{'userclass'}.'))',
4383 if (!$rv || $rv->code) {
4384 print STDERR "Failed to lookup user : ",
4385 ($rv ? $rv->error : "Unknown error"),"\n";
4388 my ($u) = $rv->all_entries();
4390 &disconnect_userdb($config{'userdb'}, $dbh);
4391 $get_user_details_cache{$username} = undef;
4392 print DEBUG "get_user_details: User not found\n";
4396 # Extract attributes
4397 my $pass = $u->get_value('webminPass');
4398 $user = { 'name' => $username,
4401 'proto' => $proto };
4402 foreach my $la ($u->get_value('webminAttr')) {
4403 my ($attr, $value) = split(/=/, $la, 2);
4404 $attrs{$attr} = $value;
4408 # Convert DB attributes into user object fields
4410 print DEBUG "get_user_details: got ",scalar(keys %attrs),
4412 $user->{'certs'} = $attrs{'cert'};
4413 if ($attrs{'allow'}) {
4414 $user->{'allow'} = $config{'alwaysresolve'} ?
4415 [ split(/\s+/, $attrs{'allow'}) ] :
4416 [ &to_ipaddress(split(/\s+/,$attrs{'allow'})) ];
4418 if ($attrs{'deny'}) {
4419 $user->{'deny'} = $config{'alwaysresolve'} ?
4420 [ split(/\s+/, $attrs{'deny'}) ] :
4421 [ &to_ipaddress(split(/\s+/,$attrs{'deny'})) ];
4423 if ($attrs{'days'}) {
4424 $user->{'allowdays'} = [ split(/,/, $attrs{'days'}) ];
4426 if ($attrs{'hoursfrom'} && $attrs{'hoursto'}) {
4427 my ($hf, $mf) = split(/\./, $attrs{'hoursfrom'});
4428 my ($ht, $mt) = split(/\./, $attrs{'hoursto'});
4429 $user->{'allowhours'} = [ $hf*60+$ht, $ht*60+$mt ];
4431 $user->{'lastchanges'} = $attrs{'lastchange'};
4432 $user->{'nochange'} = $attrs{'nochange'};
4433 $user->{'temppass'} = $attrs{'temppass'};
4434 $user->{'preroot'} = $attrs{'theme'};
4436 &disconnect_userdb($config{'userdb'}, $dbh);
4437 $get_user_details_cache{$user->{'name'}} = $user;
4443 # find_user_by_cert(cert)
4444 # Returns a username looked up by certificate
4445 sub find_user_by_cert
4447 my ($peername) = @_;
4448 my $peername2 = $peername;
4449 $peername2 =~ s/Email=/emailAddress=/ || $peername2 =~ s/emailAddress=/Email=/;
4451 # First check users in local files
4452 foreach my $username (keys %certs) {
4453 if ($certs{$username} eq $peername ||
4454 $certs{$username} eq $peername2) {
4460 if ($config{'userdb'}) {
4461 my ($dbh, $proto) = &connect_userdb($config{'userdb'});
4465 elsif ($proto eq "mysql" || $proto eq "postgresql") {
4467 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 = ?");
4468 return undef if (!$cmd);
4469 foreach my $p ($peername, $peername2) {
4471 if ($cmd->execute($p)) {
4472 ($username) = $cmd->fetchrow();
4475 return $username if ($username);
4478 elsif ($proto eq "ldap") {
4480 my $rv = $dbh->search(
4482 filter => '(objectClass='.
4483 $args->{'userclass'}.')',
4485 attrs => [ 'cn', 'webminAttr' ]);
4486 if ($rv && !$rv->code) {
4487 foreach my $u ($rv->all_entries) {
4488 my @attrs = $u->get_value('webminAttr');
4489 foreach my $la (@attrs) {
4490 my ($attr, $value) = split(/=/, $la, 2);
4491 if ($attr eq "cert" &&
4492 ($value eq $peername ||
4493 $value eq $peername2)) {
4494 return $u->get_value('cn');
4504 # connect_userdb(string)
4505 # Returns a handle for talking to a user database - may be a DBI or LDAP handle.
4506 # On failure returns an error message string. In an array context, returns the
4507 # protocol type too.
4511 my ($proto, $user, $pass, $host, $prefix, $args) = &split_userdb_string($str);
4512 if ($proto eq "mysql") {
4513 # Connect to MySQL with DBI
4514 my $drh = eval "use DBI; DBI->install_driver('mysql');";
4515 $drh || return $text{'sql_emysqldriver'};
4516 my ($host, $port) = split(/:/, $host);
4517 my $cstr = "database=$prefix;host=$host";
4518 $cstr .= ";port=$port" if ($port);
4519 print DEBUG "connect_userdb: Connecting to MySQL $cstr as $user\n";
4520 my $dbh = $drh->connect($cstr, $user, $pass, { });
4521 $dbh || return &text('sql_emysqlconnect', $drh->errstr);
4522 print DEBUG "connect_userdb: Connected OK\n";
4523 return wantarray ? ($dbh, $proto, $prefix, $args) : $dbh;
4525 elsif ($proto eq "postgresql") {
4526 # Connect to PostgreSQL with DBI
4527 my $drh = eval "use DBI; DBI->install_driver('Pg');";
4528 $drh || return $text{'sql_epostgresqldriver'};
4529 my ($host, $port) = split(/:/, $host);
4530 my $cstr = "dbname=$prefix;host=$host";
4531 $cstr .= ";port=$port" if ($port);
4532 print DEBUG "connect_userdb: Connecting to PostgreSQL $cstr as $user\n";
4533 my $dbh = $drh->connect($cstr, $user, $pass);
4534 $dbh || return &text('sql_epostgresqlconnect', $drh->errstr);
4535 print DEBUG "connect_userdb: Connected OK\n";
4536 return wantarray ? ($dbh, $proto, $prefix, $args) : $dbh;
4538 elsif ($proto eq "ldap") {
4539 # Connect with perl LDAP module
4540 eval "use Net::LDAP";
4541 $@ && return $text{'sql_eldapdriver'};
4542 my ($host, $port) = split(/:/, $host);
4543 my $scheme = $args->{'scheme'} || 'ldap';
4545 $port = $scheme eq 'ldaps' ? 636 : 389;
4547 my $ldap = Net::LDAP->new($host,
4549 'scheme' => $scheme);
4550 $ldap || return &text('sql_eldapconnect', $host);
4552 if ($args->{'tls'}) {
4553 # Switch to TLS mode
4554 eval { $mesg = $ldap->start_tls(); };
4555 if ($@ || !$mesg || $mesg->code) {
4556 return &text('sql_eldaptls',
4557 $@ ? $@ : $mesg ? $mesg->error : "Unknown error");
4560 # Login to the server
4562 $mesg = $ldap->bind(dn => $user, password => $pass);
4565 $mesg = $ldap->bind(dn => $user, anonymous => 1);
4567 if (!$mesg || $mesg->code) {
4568 return &text('sql_eldaplogin', $user,
4569 $mesg ? $mesg->error : "Unknown error");
4571 return wantarray ? ($ldap, $proto, $prefix, $args) : $ldap;
4574 return "Unknown protocol $proto";
4578 # split_userdb_string(string)
4579 # Converts a string like mysql://user:pass@host/db into separate parts
4580 sub split_userdb_string
4583 if ($str =~ /^([a-z]+):\/\/([^:]*):([^\@]*)\@([a-z0-9\.\-\_]+)\/([^\?]+)(\?(.*))?$/) {
4584 my ($proto, $user, $pass, $host, $prefix, $argstr) =
4585 ($1, $2, $3, $4, $5, $7);
4586 my %args = map { split(/=/, $_, 2) } split(/\&/, $argstr);
4587 return ($proto, $user, $pass, $host, $prefix, \%args);
4592 # disconnect_userdb(string, &handle)
4593 # Closes a handle opened by connect_userdb
4594 sub disconnect_userdb
4597 if ($str =~ /^(mysql|postgresql):/) {
4601 elsif ($str =~ /^ldap:/) {
4608 # Fills %mime with entries from file in %config and extra settings in %config
4612 if ($config{"mimetypes"} ne "") {
4613 open(MIME, $config{"mimetypes"});
4616 if (/^(\S+)\s+(.*)$/) {
4618 my @exts = split(/\s+/, $2);
4619 foreach my $ext (@exts) {
4620 $mime{$ext} = $type;
4626 foreach my $k (keys %config) {
4627 if ($k !~ /^addtype_(.*)$/) { next; }
4628 $mime{$1} = $config{$k};
4632 # build_config_mappings()
4633 # Build the anonymous access list, IP access list, unauthenticated URLs list,
4634 # redirect mapping and allow and deny lists from %config
4635 sub build_config_mappings
4637 # build anonymous access list
4639 foreach my $a (split(/\s+/, $config{'anonymous'})) {
4640 if ($a =~ /^([^=]+)=(\S+)$/) {
4641 $anonymous{$1} = $2;
4645 # build IP access list
4647 foreach my $a (split(/\s+/, $config{'ipaccess'})) {
4648 if ($a =~ /^([^=]+)=(\S+)$/) {
4653 # build unauthenticated URLs list
4654 @unauth = split(/\s+/, $config{'unauth'});
4656 # build redirect mapping
4658 foreach my $r (split(/\s+/, $config{'redirect'})) {
4659 if ($r =~ /^([^=]+)=(\S+)$/) {
4664 # build prefixes to be stripped
4665 undef(@strip_prefix);
4666 foreach my $r (split(/\s+/, $config{'strip_prefix'})) {
4667 push(@strip_prefix, $r);
4670 # Init allow and deny lists
4671 @deny = split(/\s+/, $config{"deny"});
4672 @deny = &to_ipaddress(@deny) if (!$config{'alwaysresolve'});
4673 @allow = split(/\s+/, $config{"allow"});
4674 @allow = &to_ipaddress(@allow) if (!$config{'alwaysresolve'});
4677 if ($config{'allowusers'}) {
4678 @allowusers = split(/\s+/, $config{'allowusers'});
4680 elsif ($config{'denyusers'}) {
4681 @denyusers = split(/\s+/, $config{'denyusers'});
4684 # Build list of unixauth mappings
4686 foreach my $ua (split(/\s+/, $config{'unixauth'})) {
4687 if ($ua =~ /^(\S+)=(\S+)$/) {
4691 $unixauth{"*"} = $ua;
4695 # Build list of non-session-auth pages
4696 undef(%sessiononly);
4697 foreach my $sp (split(/\s+/, $config{'sessiononly'})) {
4698 $sessiononly{$sp} = 1;
4701 # Build list of logout times
4702 undef(@logouttimes);
4703 foreach my $a (split(/\s+/, $config{'logouttimes'})) {
4704 if ($a =~ /^([^=]+)=(\S+)$/) {
4705 push(@logouttimes, [ $1, $2 ]);
4708 push(@logouttimes, [ undef, $config{'logouttime'} ]);
4710 # Build list of DAV pathss
4712 foreach my $d (split(/\s+/, $config{'davpaths'})) {
4713 push(@davpaths, $d);
4715 @davusers = split(/\s+/, $config{'dav_users'});
4717 # Mobile agent substrings and hostname prefixes
4718 @mobile_agents = split(/\t+/, $config{'mobile_agents'});
4719 @mobile_prefixes = split(/\s+/, $config{'mobile_prefixes'});
4723 if ($config{'debug'}) {
4724 open(DEBUG, ">>$config{'debug'}");
4727 open(DEBUG, ">/dev/null");
4730 # Reset cache of sudo checks
4734 # is_group_member(&uinfo, groupname)
4735 # Returns 1 if some user is a primary or secondary member of a group
4738 local ($uinfo, $group) = @_;
4739 local @ginfo = getgrnam($group);
4740 return 0 if (!@ginfo);
4741 return 1 if ($ginfo[2] == $uinfo->[3]); # primary member
4742 foreach my $m (split(/\s+/, $ginfo[3])) {
4743 return 1 if ($m eq $uinfo->[0]);
4748 # prefix_to_mask(prefix)
4749 # Converts a number like 24 to a mask like 255.255.255.0
4752 return $_[0] >= 24 ? "255.255.255.".(256-(2 ** (32-$_[0]))) :
4753 $_[0] >= 16 ? "255.255.".(256-(2 ** (24-$_[0]))).".0" :
4754 $_[0] >= 8 ? "255.".(256-(2 ** (16-$_[0]))).".0.0" :
4755 (256-(2 ** (8-$_[0]))).".0.0.0";
4758 # get_logout_time(user, session-id)
4759 # Given a username, returns the idle time before he will be logged out
4762 local ($user, $sid) = @_;
4763 if (!defined($logout_time_cache{$user,$sid})) {
4765 foreach my $l (@logouttimes) {
4766 if ($l->[0] =~ /^\@(.*)$/) {
4767 # Check group membership
4768 local @uinfo = getpwnam($user);
4769 if (@uinfo && &is_group_member(\@uinfo, $1)) {
4773 elsif ($l->[0] =~ /^\//) {
4774 # Check file contents
4775 open(FILE, $l->[0]);
4792 if ($l->[0] eq $user) {
4796 last if (defined($time));
4798 $logout_time_cache{$user,$sid} = $time;
4800 return $logout_time_cache{$user,$sid};
4803 # password_crypt(password, salt)
4804 # If the salt looks like MD5 and we have a library for it, perform MD5 hashing
4805 # of a password. Otherwise, do Unix crypt.
4808 local ($pass, $salt) = @_;
4809 if ($salt =~ /^\$1\$/ && $use_md5) {
4810 return &encrypt_md5($pass, $salt);
4813 return &unix_crypt($pass, $salt);
4817 # unix_crypt(password, salt)
4818 # Performs standard Unix hashing for a password
4821 local ($pass, $salt) = @_;
4822 if ($use_perl_crypt) {
4823 return Crypt::UnixCrypt::crypt($pass, $salt);
4826 return crypt($pass, $salt);
4830 # handle_dav_request(davpath)
4831 # Pass a request on to the Net::DAV::Server module
4832 sub handle_dav_request
4835 eval "use Filesys::Virtual::Plain";
4836 eval "use Net::DAV::Server";
4837 eval "use HTTP::Request";
4838 eval "use HTTP::Headers";
4840 if ($Net::DAV::Server::VERSION eq '1.28' && $config{'dav_nolock'}) {
4841 delete $Net::DAV::Server::implemented{lock};
4842 delete $Net::DAV::Server::implemented{unlock};
4845 # Read in request data
4846 if (!$posted_data) {
4847 local $clen = $header{"content-length"};
4848 while(length($posted_data) < $clen) {
4849 $buf = &read_data($clen - length($posted_data));
4850 if (!length($buf)) {
4851 &http_error(500, "Failed to read POST request");
4853 $posted_data .= $buf;
4857 # For subsequent logging
4858 open(MINISERVLOG, ">>$config{'logfile'}");
4862 local @u = getpwnam($authuser);
4863 if ($config{'dav_remoteuser'} && !$< && $validated) {
4866 $( = $u[3]; $) = "$u[3] $u[3]";
4867 ($>, $<) = ($u[2], $u[2]);
4869 if ($config{'dav_root'} eq '*') {
4874 &http_error(500, "Unix user $authuser does not exist");
4878 $root ||= $config{'dav_root'};
4881 # Check if this user can use DAV
4883 &users_match(\@u, @davusers) ||
4884 &http_error(500, "You are not allowed to access DAV");
4888 my $filesys = Filesys::Virtual::Plain->new({root_path => $root});
4889 my $webdav = Net::DAV::Server->new();
4890 $webdav->filesys($filesys);
4892 # Make up a request object, and feed to DAV
4893 local $ho = HTTP::Headers->new;
4894 foreach my $h (keys %header) {
4895 next if (lc($h) eq "connection");
4896 $ho->header($h => $header{$h});
4899 $request_uri =~ s/^\Q$path\E//;
4900 $request_uri = "/" if ($request_uri eq "");
4902 my $request = HTTP::Request->new($method, $request_uri, $ho,
4904 if ($config{'dav_debug'}) {
4905 print STDERR "DAV request :\n";
4906 print STDERR "---------------------------------------------\n";
4907 print STDERR $request->as_string();
4908 print STDERR "---------------------------------------------\n";
4910 my $response = $webdav->run($request);
4912 # Send back the reply
4913 &write_data("HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n");
4914 local $content = $response->content();
4916 $content =~ s|href>/(.+)<|href>$path/$1<|g;
4917 $content =~ s|href>/<|href>$path<|g;
4919 foreach my $h ($response->header_field_names) {
4920 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4921 &write_data("$h: ",$response->header($h),"\r\n");
4923 &write_data("Content-length: ",length($content),"\r\n");
4924 local $rv = &write_keep_alive(0);
4925 &write_data("\r\n");
4926 &write_data($content);
4928 if ($config{'dav_debug'}) {
4929 print STDERR "DAV reply :\n";
4930 print STDERR "---------------------------------------------\n";
4931 print STDERR "HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n";
4932 foreach my $h ($response->header_field_names) {
4933 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4934 print STDERR "$h: ",$response->header($h),"\r\n";
4936 print STDERR "Content-length: ",length($content),"\r\n";
4937 print STDERR "\r\n";
4938 print STDERR $content;
4939 print STDERR "---------------------------------------------\n";
4943 &log_request($acpthost, $authuser, $reqline, $response->code(),
4944 length($response->content()));
4947 # get_system_hostname()
4948 # Returns the hostname of this system, for reporting to listeners
4949 sub get_system_hostname
4951 # On Windows, try computername environment variable
4952 return $ENV{'computername'} if ($ENV{'computername'});
4953 return $ENV{'COMPUTERNAME'} if ($ENV{'COMPUTERNAME'});
4955 # If a specific command is set, use it first
4956 if ($config{'hostname_command'}) {
4957 local $out = `($config{'hostname_command'}) 2>&1`;
4964 # First try the hostname command
4965 local $out = `hostname 2>&1`;
4966 if (!$? && $out =~ /\S/) {
4971 # Try the Sys::Hostname module
4972 eval "use Sys::Hostname";
4974 local $rv = eval "hostname()";
4980 # Must use net name on Windows
4981 local $out = `net name 2>&1`;
4982 if ($out =~ /\-+\r?\n(\S+)/) {
4989 # indexof(string, array)
4990 # Returns the index of some value in an array, or -1
4993 for($i=1; $i <= $#_; $i++) {
4994 if ($_[$i] eq $_[0]) { return $i - 1; }
5000 # has_command(command)
5001 # Returns the full path if some command is in the path, undef if not
5005 if (!$_[0]) { return undef; }
5006 if (exists($has_command_cache{$_[0]})) {
5007 return $has_command_cache{$_[0]};
5010 if ($_[0] =~ /^\//) {
5011 $rv = -x $_[0] ? $_[0] : undef;
5014 local $sp = $on_windows ? ';' : ':';
5015 foreach $d (split($sp, $ENV{PATH})) {
5016 if (-x "$d/$_[0]") {
5021 foreach my $sfx (".exe", ".com", ".bat") {
5022 if (-r "$d/$_[0]".$sfx) {
5023 $rv = "$d/$_[0]".$sfx;
5030 $has_command_cache{$_[0]} = $rv;
5034 # check_sudo_permissions(user, pass)
5035 # Returns 1 if some user can run any command via sudo
5036 sub check_sudo_permissions
5038 local ($user, $pass) = @_;
5040 # First try the pipes
5042 print DEBUG "check_sudo_permissions: querying cache for $user\n";
5043 print $PASSINw "readsudo $user\n";
5044 local $can = <$PASSOUTr>;
5046 print DEBUG "check_sudo_permissions: cache said $can\n";
5047 if ($can =~ /^\d+$/ && $can != 2) {
5052 local $ptyfh = new IO::Pty;
5053 print DEBUG "check_sudo_permissions: ptyfh=$ptyfh\n";
5055 print STDERR "Failed to create new PTY with IO::Pty\n";
5058 local @uinfo = getpwnam($user);
5060 print STDERR "Unix user $user does not exist for sudo\n";
5064 # Execute sudo in a sub-process, via a pty
5065 local $ttyfh = $ptyfh->slave();
5066 print DEBUG "check_sudo_permissions: ttyfh=$ttyfh\n";
5067 local $tty = $ptyfh->ttyname();
5068 print DEBUG "check_sudo_permissions: tty=$tty\n";
5069 chown($uinfo[2], $uinfo[3], $tty);
5071 print DEBUG "check_sudo_permissions: about to fork..\n";
5072 local $pid = fork();
5073 print DEBUG "check_sudo_permissions: fork=$pid pid=$$\n";
5075 print STDERR "fork for sudo failed : $!\n";
5080 $ptyfh->make_slave_controlling_terminal();
5081 close(STDIN); close(STDOUT); close(STDERR);
5082 untie(*STDIN); untie(*STDOUT); untie(*STDERR);
5083 close($PASSINw); close($PASSOUTr);
5084 $( = $uinfo[3]; $) = "$uinfo[3] $uinfo[3]";
5085 ($>, $<) = ($uinfo[2], $uinfo[2]);
5090 open(STDIN, "<&SUDOr");
5091 open(STDOUT, ">$tty");
5092 open(STDERR, ">&STDOUT");
5095 print "Exec failed : $!\n";
5098 print DEBUG "check_sudo_permissions: pid=$pid\n";
5100 $ptyfh->close_slave();
5102 # Send password, and get back response
5103 local $oldfh = select(SUDOw);
5106 print DEBUG "check_sudo_permissions: about to send pass\n";
5107 local $SIG{'PIPE'} = 'ignore'; # Sometimes sudo doesn't ask for a password
5108 print SUDOw $pass,"\n";
5109 print DEBUG "check_sudo_permissions: sent pass=$pass\n";
5113 print DEBUG "check_sudo_permissions: got $_";
5119 local ($ok) = ($out =~ /\(ALL\)\s+ALL/ ? 1 : 0);
5123 print $PASSINw "writesudo $user $ok\n";
5129 # is_mobile_useragent(agent)
5130 # Returns 1 if some user agent looks like a cellphone or other mobile device,
5132 sub is_mobile_useragent
5134 local ($agent) = @_;
5136 "UP.Link", # Openwave
5137 "Nokia", # All Nokias start with Nokia
5138 "MOT-", # All Motorola phones start with MOT-
5139 "SAMSUNG", # Samsung browsers
5140 "Samsung", # Samsung browsers
5141 "SEC-", # Samsung browsers
5142 "AU-MIC", # Samsung browsers
5143 "AUDIOVOX", # Audiovox
5144 "BlackBerry", # BlackBerry
5145 "hiptop", # Danger hiptop Sidekick
5146 "SonyEricsson", # Sony Ericsson
5147 "Ericsson", # Old Ericsson browsers , mostly WAP
5148 "Mitsu/1.1.A", # Mitsubishi phones
5149 "Panasonic WAP", # Panasonic old WAP phones
5150 "DoCoMo", # DoCoMo phones
5151 "Lynx", # Lynx text-mode linux browser
5152 "Links", # Another text-mode linux browser
5154 local @substrings = (
5155 "UP.Browser", # Openwave
5156 "MobilePhone", # NetFront
5157 "AU-MIC-A700", # Samsung A700 Obigo browsers
5158 "Danger hiptop", # Danger Sidekick hiptop
5159 "Windows CE", # Windows CE Pocket PC
5160 "IEMobile", # Windows mobile browser
5161 "Blazer", # Palm Treo Blazer
5162 "BlackBerry", # BlackBerries can emulate other browsers, but
5163 # they still keep this string in the UserAgent
5164 "SymbianOS", # New Series60 browser has safari in it and
5165 # SymbianOS is the only distinguishing string
5166 "iPhone", # Apple iPhone KHTML browser
5167 "iPod", # iPod touch browser
5168 "MobileSafari", # HTTP client in iPhone
5170 "Opera Mini", # Opera Mini
5171 "HTC_P3700", # HTC mobile device
5173 "webOS/", # Palm WebOS
5174 "Nintendo DS", # DSi / DSi-XL
5176 foreach my $p (@prefixes) {
5177 return 1 if ($agent =~ /^\Q$p\E/);
5179 foreach my $s (@substrings, @mobile_agents) {
5180 return 1 if ($agent =~ /\Q$s\E/);
5185 # write_blocked_file()
5186 # Writes out a text file of blocked hosts and users
5187 sub write_blocked_file
5189 open(BLOCKED, ">$config{'blockedfile'}");
5190 foreach my $d (grep { $hostfail{$_} } @deny) {
5191 print BLOCKED "host $d $hostfail{$d} $blockhosttime{$d}\n";
5193 foreach my $d (grep { $userfail{$_} } @denyusers) {
5194 print BLOCKED "user $d $userfail{$d} $blockusertime{$d}\n";
5197 chmod(0700, $config{'blockedfile'});
5202 open(PIDFILE, ">$config{'pidfile'}");
5203 printf PIDFILE "%d\n", getpid();
5205 $miniserv_main_pid = getpid();
5208 # lock_user_password(user)
5209 # Updates a user's password file entry to lock it, both in memory and on disk.
5210 # Returns 1 if done, -1 if no such user, 0 if already locked
5211 sub lock_user_password
5214 local $uinfo = &get_user_details($user);
5219 if ($uinfo->{'pass'} =~ /^\!/) {
5223 if (!$uinfo->{'proto'}) {
5224 # Write to users file
5225 $users{$user} = "!".$users{$user};
5226 open(USERS, $config{'userfile'});
5227 local @ufile = <USERS>;
5229 foreach my $u (@ufile) {
5230 local @uinfo = split(/:/, $u);
5231 if ($uinfo[0] eq $user) {
5232 $uinfo[1] = $users{$user};
5234 $u = join(":", @uinfo);
5236 open(USERS, ">$config{'userfile'}");
5242 if ($config{'userdb'}) {
5244 my ($dbh, $proto, $prefix, $args) = &connect_userdb($config{'userdb'});
5248 elsif ($proto eq "mysql" || $proto eq "postgresql") {
5249 # Update user attribute
5250 my $cmd = $dbh->prepare(
5251 "update webmin_user set pass = ? where id = ?");
5252 if (!$cmd || !$cmd->execute("!".$uinfo->{'pass'},
5255 print STDERR "Failed to lock password : ",
5259 $cmd->finish() if ($cmd);
5261 elsif ($proto eq "ldap") {
5262 # Update LDAP object
5263 my $rv = $dbh->modify($uinfo->{'id'},
5264 replace => { 'webminPass' => '!'.$uinfo->{'pass'} });
5265 if (!$rv || $rv->code) {
5266 print STDERR "Failed to lock password : ",
5267 ($rv ? $rv->error : "Unknown error"),"\n";
5271 &disconnect_userdb($config{'userdb'}, $dbh);
5275 return -1; # This should never be reached
5278 # hash_session_id(sid)
5279 # Returns an MD5 or Unix-crypted session ID
5283 if (!$hash_session_id_cache{$sid}) {
5286 $hash_session_id_cache{$sid} = &encrypt_md5($sid);
5290 $hash_session_id_cache{$sid} = &unix_crypt($sid, "XX");
5293 return $hash_session_id_cache{$sid};
5296 # encrypt_md5(string, [salt])
5297 # Returns a string encrypted in MD5 format
5300 local ($passwd, $salt) = @_;
5301 local $magic = '$1$';
5302 if ($salt =~ /^\$1\$([^\$]+)/) {
5303 # Extract actual salt from already encrypted password
5308 local $ctx = eval "new $use_md5";
5315 # Add some more stuff from the hash of the password and salt
5316 local $ctx1 = eval "new $use_md5";
5317 $ctx1->add($passwd);
5321 $ctx1->add($passwd);
5322 local $final = $ctx1->digest();
5323 for($pl=length($passwd); $pl>0; $pl-=16) {
5324 $ctx->add($pl > 16 ? $final : substr($final, 0, $pl));
5327 # This piece of code seems rather pointless, but it's in the C code that
5328 # does MD5 in PAM so it has to go in!
5331 for($i=length($passwd); $i; $i >>= 1) {
5336 $ctx->add(substr($passwd, $j, 1));
5339 $final = $ctx->digest();
5342 # This loop exists only to waste time
5343 for($i=0; $i<1000; $i++) {
5344 $ctx1 = eval "new $use_md5";
5345 $ctx1->add($i & 1 ? $passwd : $final);
5346 $ctx1->add($salt) if ($i % 3);
5347 $ctx1->add($passwd) if ($i % 7);
5348 $ctx1->add($i & 1 ? $final : $passwd);
5349 $final = $ctx1->digest();
5353 # Convert the 16-byte final string into a readable form
5355 local @final = map { ord($_) } split(//, $final);
5356 $l = ($final[ 0]<<16) + ($final[ 6]<<8) + $final[12];
5357 $rv .= &to64($l, 4);
5358 $l = ($final[ 1]<<16) + ($final[ 7]<<8) + $final[13];
5359 $rv .= &to64($l, 4);
5360 $l = ($final[ 2]<<16) + ($final[ 8]<<8) + $final[14];
5361 $rv .= &to64($l, 4);
5362 $l = ($final[ 3]<<16) + ($final[ 9]<<8) + $final[15];
5363 $rv .= &to64($l, 4);
5364 $l = ($final[ 4]<<16) + ($final[10]<<8) + $final[ 5];
5365 $rv .= &to64($l, 4);
5367 $rv .= &to64($l, 2);
5369 # Add salt if needed
5371 return $magic.$salt.'$'.$rv;
5380 local ($v, $n) = @_;
5383 $r .= $itoa64[$v & 0x3f];
5389 # read_file(file, &assoc, [&order], [lowercase])
5390 # Fill an associative array with name=value pairs from a file
5393 open(ARFILE, $_[0]) || return 0;
5396 if (!/^#/ && /^([^=]*)=(.*)$/) {
5397 $_[1]->{$_[3] ? lc($1) : $1} = $2;
5398 push(@{$_[2]}, $1) if ($_[2]);
5405 # write_file(file, array)
5406 # Write out the contents of an associative array as name=value lines
5409 local(%old, @order);
5410 &read_file($_[0], \%old, \@order);
5411 open(ARFILE, ">$_[0]");
5412 foreach $k (@order) {
5413 print ARFILE $k,"=",$_[1]->{$k},"\n" if (exists($_[1]->{$k}));
5415 foreach $k (keys %{$_[1]}) {
5416 print ARFILE $k,"=",$_[1]->{$k},"\n" if (!exists($old{$k}));
5421 # execute_ready_webmin_crons()
5422 # Find and run any cron jobs that are due, based on their last run time and
5423 # execution interval
5424 sub execute_ready_webmin_crons
5428 foreach my $cron (@webmincrons) {
5430 if (!$webmincron_last{$cron->{'id'}}) {
5431 # If not ever run before, don't run right away
5432 $webmincron_last{$cron->{'id'}} = $now;
5435 elsif ($cron->{'interval'} &&
5436 $now - $webmincron_last{$cron->{'id'}} > $cron->{'interval'}) {
5437 # Older than interval .. time to run
5440 elsif ($cron->{'mins'}) {
5441 # Check if current time matches spec, and we haven't run in the
5443 my @tm = localtime($now);
5444 if (&matches_cron($cron->{'mins'}, $tm[1]) &&
5445 &matches_cron($cron->{'hours'}, $tm[2]) &&
5446 &matches_cron($cron->{'days'}, $tm[3]) &&
5447 &matches_cron($cron->{'months'}, $tm[4]+1) &&
5448 &matches_cron($cron->{'weekdays'}, $tm[6]) &&
5449 $now - $webmincron_last{$cron->{'id'}} > 60) {
5455 print DEBUG "Running cron id=$cron->{'id'} ".
5456 "module=$cron->{'module'} func=$cron->{'func'}\n";
5457 $webmincron_last{$cron->{'id'}} = $now;
5461 # Run via a wrapper command, which we run like a CGI
5462 dbmclose(%sessiondb);
5464 # Setup CGI-like environment
5465 $envtz = $ENV{"TZ"};
5466 $envuser = $ENV{"USER"};
5467 $envpath = $ENV{"PATH"};
5468 $envlang = $ENV{"LANG"};
5469 $envroot = $ENV{"SystemRoot"};
5470 $envperllib = $ENV{'PERLLIB'};
5471 foreach my $k (keys %ENV) {
5474 $ENV{"PATH"} = $envpath if ($envpath);
5475 $ENV{"TZ"} = $envtz if ($envtz);
5476 $ENV{"USER"} = $envuser if ($envuser);
5477 $ENV{"OLD_LANG"} = $envlang if ($envlang);
5478 $ENV{"SystemRoot"} = $envroot if ($envroot);
5479 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
5480 $ENV{"HOME"} = $user_homedir;
5481 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
5482 $ENV{"SERVER_ADMIN"} = $config{"email"};
5484 $ENV{"SERVER_ROOT"} = $root0;
5485 $ENV{"SERVER_REALROOT"} = $root0;
5486 $ENV{"SERVER_PORT"} = $config{'port'};
5487 $ENV{"WEBMIN_CRON"} = 1;
5488 $ENV{"DOCUMENT_ROOT"} = $root0;
5489 $ENV{"DOCUMENT_REALROOT"} = $root0;
5490 $ENV{"MINISERV_CONFIG"} = $config_file;
5491 $ENV{"HTTPS"} = "ON" if ($use_ssl);
5492 $ENV{"MINISERV_PID"} = $miniserv_main_pid;
5493 $ENV{"SCRIPT_FILENAME"} = $config{'webmincron_wrapper'};
5494 if ($ENV{"SCRIPT_FILENAME"} =~ /^\Q$root0\E(\/.*)$/) {
5495 $ENV{"SCRIPT_NAME"} = $1;
5497 $config{'webmincron_wrapper'} =~ /^(.*)\//;
5499 foreach $k (keys %config) {
5500 if ($k =~ /^env_(\S+)$/) {
5501 $ENV{$1} = $config{$k};
5505 $SIG{'CHLD'} = 'DEFAULT';
5507 # Have SOCK closed if the perl exec's something
5509 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
5512 # Run the wrapper script by evaling it
5513 $pkg = "webmincron";
5514 $0 = $config{'webmincron_wrapper'};
5516 $main_process_id = $$;
5520 do \$miniserv::config{'webmincron_wrapper'};
5524 print STDERR "Perl cron failure : $@\n";
5529 push(@childpids, $pid);
5533 # Write out file containing last run times
5534 &write_file($config{'webmincron_last'}, \%webmincron_last);
5538 # matches_cron(cron-spec, time)
5539 # Checks if some minute or hour matches some cron spec, which can be * or a list
5543 my ($spec, $tm) = @_;
5548 foreach my $s (split(/,/, $spec)) {
5550 $s =~ /^(\d+)\-(\d+)$/ && $tm >= $1 && $tm <= $2) {
5558 # read_webmin_crons()
5559 # Read all scheduled webmin cron functions and store them in the @webmincrons
5561 sub read_webmin_crons
5564 opendir(CRONS, $config{'webmincron_dir'});
5565 print DEBUG "Reading crons from $config{'webmincron_dir'}\n";
5566 foreach my $f (readdir(CRONS)) {
5567 if ($f =~ /^(\d+)\.cron$/) {
5569 &read_file("$config{'webmincron_dir'}/$f", \%cron);
5572 foreach my $n ('module', 'func') {
5574 print STDERR "Cron $1 missing $n\n";
5578 if (!$cron{'interval'} && !$cron{'mins'} && !$cron{'special'}) {
5579 print STDERR "Cron $1 missing any time spec\n";
5582 if ($cron{'special'} eq 'hourly') {
5583 # Run every hour on the hour
5585 $cron{'hours'} = '*';
5586 $cron{'days'} = '*';
5587 $cron{'months'} = '*';
5588 $cron{'weekdays'} = '*';
5590 elsif ($cron{'special'} eq 'daily') {
5591 # Run every day at midnight
5593 $cron{'hours'} = '0';
5594 $cron{'days'} = '*';
5595 $cron{'months'} = '*';
5596 $cron{'weekdays'} = '*';
5598 elsif ($cron{'special'} eq 'monthly') {
5599 # Run every month on the 1st
5601 $cron{'hours'} = '0';
5602 $cron{'days'} = '1';
5603 $cron{'months'} = '*';
5604 $cron{'weekdays'} = '*';
5606 elsif ($cron{'special'} eq 'weekly') {
5607 # Run every month on the 1st
5609 $cron{'hours'} = '0';
5610 $cron{'days'} = '*';
5611 $cron{'months'} = '*';
5612 $cron{'weekdays'} = '0';
5614 elsif ($cron{'special'} eq 'yearly' ||
5615 $cron{'special'} eq 'annually') {
5616 # Run every year on 1st january
5618 $cron{'hours'} = '0';
5619 $cron{'days'} = '1';
5620 $cron{'months'} = '1';
5621 $cron{'weekdays'} = '*';
5623 elsif ($cron{'special'}) {
5624 print STDERR "Cron $1 invalid special time $cron{'special'}\n";
5627 if ($cron{'special'}) {
5628 delete($cron{'special'});
5631 print DEBUG "adding cron id=$cron{'id'} module=$cron{'module'} func=$cron{'func'}\n";
5632 push(@webmincrons, \%cron);
5638 # Check if some address is valid IPv4, returns 1 if so.
5641 return $_[0] =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/ &&
5642 $1 >= 0 && $1 <= 255 &&
5643 $2 >= 0 && $2 <= 255 &&
5644 $3 >= 0 && $3 <= 255 &&
5645 $4 >= 0 && $4 <= 255;
5648 # Check if some IPv6 address is properly formatted, and returns 1 if so.
5649 sub check_ip6address
5651 my @blocks = split(/:/, $_[0]);
5652 return 0 if (@blocks == 0 || @blocks > 8);
5654 my $where = index($blocks[$ib],"/");
5657 my $b = substr($blocks[$ib],0,$where);
5658 $m = substr($blocks[$ib],$where+1,length($blocks[$ib])-($where+1));
5661 return 0 if ($m <0 || $m >128);
5664 foreach $b (@blocks) {
5665 return 0 if ($b ne "" && $b !~ /^[0-9a-f]{1,4}$/i);
5666 $empty++ if ($b eq "");
5668 return 0 if ($empty > 1 && !($_[0] =~ /^::/ && $empty == 2));
5672 # network_to_address(binary)
5673 # Given a network address in binary IPv4 or v4 format, return the string form
5674 sub network_to_address
5677 if (length($addr) == 4 || !$use_ipv6) {
5678 return inet_ntoa($addr);
5681 return Socket6::inet_ntop(Socket6::AF_INET6(), $addr);
5685 # redirect_stderr_to_log()
5686 # Re-direct STDERR to error log file
5687 sub redirect_stderr_to_log
5689 if ($config{'errorlog'} ne '-') {
5690 open(STDERR, ">>$config{'errorlog'}") ||
5691 die "failed to open $config{'errorlog'} : $!";
5692 if ($config{'logperms'}) {
5693 chmod(oct($config{'logperms'}), $config{'errorlog'});
5696 select(STDERR); $| = 1; select(STDOUT);