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 # Load gzip library if enabled
271 if ($config{'gzip'} eq '1') {
272 eval "use Compress::Zlib";
278 # Setup syslog support if possible and if requested
280 open(ERRDUP, ">&STDERR");
281 open(STDERR, ">/dev/null");
282 $log_socket = $config{"logsock"} || "unix";
283 eval 'openlog($config{"pam"}, "cons,pid,ndelay", "authpriv"); setlogsock($log_socket)';
288 local $msg = ucfirst($config{'pam'})." starting";
289 eval { syslog("info", "%s", $msg); };
293 syslog("info", "%s", $msg);
296 # All attempts to use syslog have failed..
301 open(STDERR, ">&ERRDUP");
305 # Read MIME types file and add extra types
309 if ($config{'log'}) {
310 local(@gmt, @lct, $days, $hours, $mins);
311 @gmt = gmtime(time());
312 @lct = localtime(time());
313 $days = $lct[3] - $gmt[3];
314 $hours = ($days < -1 ? 24 : 1 < $days ? -24 : $days * 24) +
316 $mins = $hours * 60 + $lct[1] - $gmt[1];
317 $timezone = ($mins < 0 ? "-" : "+"); $mins = abs($mins);
318 $timezone .= sprintf "%2.2d%2.2d", $mins/60, $mins%60;
321 # Build various maps from the config files
322 &build_config_mappings();
324 # start up external authentication program, if needed
325 if ($config{'extauth'}) {
326 socketpair(EXTAUTH, EXTAUTH2, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
327 if (!($extauth = fork())) {
331 open(STDIN, "<&EXTAUTH2");
332 open(STDOUT, ">&EXTAUTH2");
333 exec($config{'extauth'}) or die "exec failed : $!\n";
336 local $os = select(EXTAUTH);
340 # Pre-load any libraries
341 if (!$config{'inetd'}) {
342 foreach $pl (split(/\s+/, $config{'preload'})) {
343 ($pkg, $lib) = split(/=/, $pl);
344 $pkg =~ s/[^A-Za-z0-9]/_/g;
345 eval "package $pkg; do '$config{'root'}/$lib'";
347 print STDERR "Failed to pre-load $lib in $pkg : $@\n";
350 print STDERR "Pre-loaded $lib in $pkg\n";
353 foreach $pl (split(/\s+/, $config{'premodules'})) {
355 ($dir, $mod) = split(/\//, $pl);
358 ($dir, $mod) = (undef, $pl);
360 push(@INC, "$config{'root'}/$dir");
361 eval "package $mod; use $mod ()";
363 print STDERR "Failed to pre-load $mod : $@\n";
366 print STDERR "Pre-loaded $mod\n";
371 # Open debug log if set
372 if ($config{'debuglog'}) {
373 open(DEBUG, ">>$config{'debuglog'}");
374 chmod(0700, $config{'debuglog'});
375 select(DEBUG); $| = 1; select(STDOUT);
376 print DEBUG "miniserv.pl starting ..\n";
379 # Write out (empty) blocked hosts file
380 &write_blocked_file();
382 # Initially read webmin cron functions and last execution times
383 &read_webmin_crons();
384 %webmincron_last = ( );
385 &read_file($config{'webmincron_last'}, \%webmincron_last);
387 # Pre-cache lang files
390 if ($config{'inetd'}) {
391 # We are being run from inetd - go direct to handling the request
392 &redirect_stderr_to_log();
393 $SIG{'HUP'} = 'IGNORE';
394 $SIG{'TERM'} = 'DEFAULT';
395 $SIG{'PIPE'} = 'DEFAULT';
396 open(SOCK, "+>&STDIN");
398 # Check if it is time for the logfile to be cleared
399 if ($config{'logclear'}) {
400 local $write_logtime = 0;
401 local @st = stat("$config{'logfile'}.time");
403 if ($st[9]+$config{'logtime'}*60*60 < time()){
406 unlink($config{'logfile'});
409 else { $write_logtime = 1; }
410 if ($write_logtime) {
411 open(LOGTIME, ">$config{'logfile'}.time");
412 print LOGTIME time(),"\n";
417 # Initialize SSL for this connection
419 $ssl_con = &ssl_connection_for_ip(SOCK, 0);
423 # Work out the hostname for this web server
424 local $sn = getsockname(SOCK);
425 $ipv6 = length($sn) > 16;
426 $host = &get_socket_name(SOCK, $ipv6);
428 $port = $config{'port'};
429 $acptaddr = getpeername(SOCK);
432 # Work out remote and local IPs
433 $ipv6 = length($acptaddr) > 16;
434 (undef, $locala) = &get_socket_ip(SOCK, $ipv6);
435 (undef, $peera, undef) = &get_address_ip($acptaddr, $ipv6);
437 print DEBUG "main: Starting handle_request loop pid=$$\n";
438 while(&handle_request($peera, $locala, $ipv6)) { }
439 print DEBUG "main: Done handle_request loop pid=$$\n";
444 # Build list of sockets to listen on
445 $config{'bind'} = '' if ($config{'bind'} eq '*');
446 if ($config{'bind'}) {
447 # Listening on a specific IP
448 if (&check_ip6address($config{'bind'})) {
450 $use_ipv6 || die "Cannot bind to $config{'bind'} without IPv6";
451 push(@sockets, [ inet_pton(Socket6::AF_INET6(),$config{'bind'}),
453 Socket6::PF_INET6() ]);
457 push(@sockets, [ inet_aton($config{'bind'}),
463 # Listening on all IPs
464 push(@sockets, [ INADDR_ANY, $config{'port'}, PF_INET() ]);
467 push(@sockets, [ in6addr_any(), $config{'port'},
468 Socket6::PF_INET6() ]);
471 foreach $s (split(/\s+/, $config{'sockets'})) {
472 if ($s =~ /^(\d+)$/) {
473 # Just listen on another port on the main IP
474 push(@sockets, [ $sockets[0]->[0], $s, $sockets[0]->[2] ]);
475 if ($use_ipv6 && !$config{'bind'}) {
476 # Also listen on that port on the main IPv6 address
477 push(@sockets, [ $sockets[1]->[0], $s,
481 elsif ($s =~ /^\*:(\d+)$/) {
482 # Listening on all IPs on some port
483 push(@sockets, [ INADDR_ANY, $1,
486 push(@sockets, [ in6addr_any(), $1,
487 Socket6::PF_INET6() ]);
490 elsif ($s =~ /^(\S+):(\d+)$/) {
491 # Listen on a specific port and IP
492 my ($ip, $port) = ($1, $2);
493 if (&check_ip6address($ip)) {
494 $use_ipv6 || die "Cannot bind to $ip without IPv6";
495 push(@sockets, [ inet_pton(Socket6::AF_INET6(),
497 $port, Socket6::PF_INET6() ]);
500 push(@sockets, [ inet_aton($ip), $port,
504 elsif ($s =~ /^([0-9\.]+):\*$/ || $s =~ /^([0-9\.]+)$/) {
505 # Listen on the main port on another IPv4 address
506 push(@sockets, [ inet_aton($1), $sockets[0]->[1],
509 elsif (($s =~ /^([0-9a-f\:]+):\*$/ || $s =~ /^([0-9a-f\:]+)$/) &&
511 # Listen on the main port on another IPv6 address
512 push(@sockets, [ inet_pton(Socket6::AF_INET6(), $1),
514 Socket6::PF_INET6() ]);
518 # Open all the sockets
519 $proto = getprotobyname('tcp');
521 $tried_inaddr_any = 0;
522 for($i=0; $i<@sockets; $i++) {
524 socket($fh, $sockets[$i]->[2], SOCK_STREAM, $proto) ||
525 die "Failed to open socket family $sockets[$i]->[2] : $!";
526 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
527 if ($sockets[$i]->[2] eq PF_INET()) {
528 $pack = pack_sockaddr_in($sockets[$i]->[1], $sockets[$i]->[0]);
531 $pack = pack_sockaddr_in6($sockets[$i]->[1], $sockets[$i]->[0]);
532 setsockopt($fh, 41, 26, pack("l", 1)); # IPv6 only
534 for($j=0; $j<5; $j++) {
535 last if (bind($fh, $pack));
539 # All attempts failed .. give up
540 if ($sockets[$i]->[0] eq INADDR_ANY ||
541 $use_ipv6 && $sockets[$i]->[0] eq in6addr_any()) {
543 "Failed to bind to port $sockets[$i]->[1] : $!");
544 $tried_inaddr_any = 1;
547 $ip = &network_to_address($sockets[$i]->[0]);
549 "Failed to bind to IP $ip port ".
550 "$sockets[$i]->[1] : $!");
554 listen($fh, SOMAXCONN);
555 push(@socketfhs, $fh);
556 $ipv6fhs{$fh} = $sockets[$i]->[2] eq PF_INET() ? 0 : 1;
559 foreach $se (@sockerrs) {
560 print STDERR $se,"\n";
563 # If all binds failed, try binding to any address
564 if (!@socketfhs && !$tried_inaddr_any) {
565 print STDERR "Falling back to listening on any address\n";
567 socket($fh, PF_INET(), SOCK_STREAM, $proto) ||
568 die "Failed to open socket : $!";
569 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
570 if (!bind($fh, pack_sockaddr_in($sockets[0]->[1], INADDR_ANY))) {
571 print STDERR "Failed to bind to port $sockets[0]->[1] : $!\n";
574 listen($fh, SOMAXCONN);
575 push(@socketfhs, $fh);
577 elsif (!@socketfhs && $tried_inaddr_any) {
578 print STDERR "Could not listen on any ports";
582 if ($config{'listen'}) {
583 # Open the socket that allows other webmin servers to find this one
584 $proto = getprotobyname('udp');
585 if (socket(LISTEN, PF_INET(), SOCK_DGRAM, $proto)) {
586 setsockopt(LISTEN, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
587 bind(LISTEN, pack_sockaddr_in($config{'listen'}, INADDR_ANY));
588 listen(LISTEN, SOMAXCONN);
591 $config{'listen'} = 0;
595 # Split from the controlling terminal, unless configured not to
596 if (!$config{'nofork'}) {
597 if (fork()) { exit; }
599 eval { setsid(); }; # may not work on Windows
601 # Close standard file handles
602 open(STDIN, "</dev/null");
603 open(STDOUT, ">/dev/null");
604 &redirect_stderr_to_log();
605 &log_error("miniserv.pl started");
606 foreach $msg (@startup_msg) {
610 # write out the PID file
613 # Start the log-clearing process, if needed. This checks every minute
614 # to see if the log has passed its reset time, and if so clears it
615 if ($config{'logclear'}) {
616 if (!($logclearer = fork())) {
617 &close_all_sockets();
620 local $write_logtime = 0;
621 local @st = stat("$config{'logfile'}.time");
623 if ($st[9]+$config{'logtime'}*60*60 < time()){
626 unlink($config{'logfile'});
629 else { $write_logtime = 1; }
630 if ($write_logtime) {
631 open(LOGTIME, ">$config{'logfile'}.time");
632 print LOGTIME time(),"\n";
639 push(@childpids, $logclearer);
642 # Setup the logout time dbm if needed
643 if ($config{'session'}) {
644 eval "use SDBM_File";
645 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
646 eval "\$sessiondb{'1111111111'} = 'foo bar';";
648 dbmclose(%sessiondb);
649 eval "use NDBM_File";
650 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
653 delete($sessiondb{'1111111111'});
658 $SIG{'HUP'} = 'miniserv::trigger_restart';
659 $SIG{'TERM'} = 'miniserv::term_handler';
660 $SIG{'USR1'} = 'miniserv::trigger_reload';
661 $SIG{'PIPE'} = 'IGNORE';
662 local $remove_session_count = 0;
663 $need_pipes = $config{'passdelay'} || $config{'session'};
665 # wait for a new connection, or a message from a child process
667 if (@childpids <= $config{'maxconns'}) {
668 # Only accept new main socket connects when ready
670 foreach $s (@socketfhs) {
671 vec($rmask, fileno($s), 1) = 1;
675 printf STDERR "too many children (%d > %d)\n",
676 scalar(@childpids), $config{'maxconns'};
679 for($i=0; $i<@passin; $i++) {
680 vec($rmask, fileno($passin[$i]), 1) = 1;
683 vec($rmask, fileno(LISTEN), 1) = 1 if ($config{'listen'});
685 # Wait for a connection
686 local $sel = select($rmask, undef, undef, 10);
688 # Check the flag files
689 if ($config{'restartflag'} && -r $config{'restartflag'}) {
690 print STDERR "restart flag file detected\n";
691 unlink($config{'restartflag'});
694 if ($config{'reloadflag'} && -r $config{'reloadflag'}) {
695 unlink($config{'reloadflag'});
700 # Got a HUP signal while in select() .. restart now
704 # Got a USR1 signal while in select() .. re-read config
706 &reload_config_file();
708 local $time_now = time();
710 # Clean up finished processes
712 do { $pid = waitpid(-1, WNOHANG);
713 @childpids = grep { $_ != $pid } @childpids;
714 } while($pid != 0 && $pid != -1);
716 # run the unblocking procedure to check if enough time has passed to
717 # unblock hosts that heve been blocked because of password failures
719 if ($config{'blockhost_failures'}) {
721 while ($i <= $#deny) {
722 if ($blockhosttime{$deny[$i]} &&
723 $config{'blockhost_time'} != 0 &&
724 ($time_now - $blockhosttime{$deny[$i]}) >=
725 $config{'blockhost_time'}) {
726 # the host can be unblocked now
727 $hostfail{$deny[$i]} = 0;
728 splice(@deny, $i, 1);
735 # Do the same for blocked users
736 if ($config{'blockuser_failures'}) {
738 while ($i <= $#deny) {
739 if ($blockusertime{$deny[$i]} &&
740 $config{'blockuser_time'} != 0 &&
741 ($time_now - $blockusertime{$deny[$i]}) >=
742 $config{'blockuser_time'}) {
743 # the user can be unblocked now
744 $userfail{$deny[$i]} = 0;
745 splice(@denyusers, $i, 1);
752 &write_blocked_file();
755 # Check if any webmin cron jobs are ready to run
756 &execute_ready_webmin_crons();
758 if ($config{'session'} && (++$remove_session_count%50) == 0) {
759 # Remove sessions with more than 7 days of inactivity,
761 foreach $s (keys %sessiondb) {
762 local ($user, $ltime, $lip) =
763 split(/\s+/, $sessiondb{$s});
764 if ($time_now - $ltime > 7*24*60*60) {
765 &run_logout_script($s, $user);
766 &write_logout_utmp($user, $lip);
767 delete($sessiondb{$s});
770 "Timeout of session for $user");
776 if ($use_pam && $config{'pam_conv'}) {
777 # Remove PAM sessions with more than 5 minutes of inactivity
779 foreach $c (values %conversations) {
780 if ($time_now - $c->{'time'} > 5*60) {
781 &end_pam_conversation($c);
783 syslog("info", "%s", "Timeout of PAM ".
784 "session for $c->{'user'}");
790 # Don't check any sockets if there is no activity
793 # Check if any of the main sockets have received a new connection
795 foreach $s (@socketfhs) {
796 if (vec($rmask, fileno($s), 1)) {
798 $acptaddr = accept(SOCK, $s);
799 if (!$acptaddr) { next; }
800 binmode(SOCK); # turn off any Perl IO stuff
803 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
805 ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw) =
809 # Work out IP and port of client
810 local ($peerb, $peera, $peerp) =
811 &get_address_ip($acptaddr, $ipv6fhs{$s});
813 # Work out the local IP
814 (undef, $locala) = &get_socket_ip(SOCK, $ipv6fhs{$s});
816 # Check username of connecting user
817 $localauth_user = undef;
818 if ($config{'localauth'} && $peera eq "127.0.0.1") {
819 if (open(TCP, "/proc/net/tcp")) {
820 # Get the info direct from the kernel
821 $peerh = sprintf("%4.4X", $peerp);
824 local @t = split(/[\s:]+/, $_);
825 if ($t[1] eq '0100007F' &&
834 if (!$localauth_user) {
835 # Call lsof for the info
836 local $lsofpid = open(LSOF,
837 "$config{'localauth'} -i ".
838 "TCP\@127.0.0.1:$peerp |");
840 if (/^(\S+)\s+(\d+)\s+(\S+)/ &&
841 $2 != $$ && $2 != $lsofpid){
842 $localauth_user = $3;
849 # Work out the hostname for this web server
850 $host = &get_socket_name(SOCK, $ipv6fhs{$s});
853 "Failed to get local socket name : $!\n";
857 $port = $sockets[$sn]->[1];
859 # fork the subprocess
861 if (!($handpid = fork())) {
862 # setup signal handlers
863 $SIG{'TERM'} = 'DEFAULT';
864 $SIG{'PIPE'} = 'DEFAULT';
865 #$SIG{'CHLD'} = 'IGNORE';
866 $SIG{'HUP'} = 'IGNORE';
867 $SIG{'USR1'} = 'IGNORE';
869 # Initialize SSL for this connection
871 $ssl_con = &ssl_connection_for_ip(
876 # Close the file handle for the session DBM
877 dbmclose(%sessiondb);
879 # close useless pipes
882 close($PASSINr); close($PASSOUTw);
884 &close_all_sockets();
888 "main: Starting handle_request loop pid=$$\n";
889 while(&handle_request($peera, $locala,
891 # Loop until keepalive stops
894 "main: Done handle_request loop pid=$$\n";
897 close($PASSINw); close($PASSOUTw);
900 push(@childpids, $handpid);
902 close($PASSINw); close($PASSOUTr);
903 push(@passin, $PASSINr);
904 push(@passout, $PASSOUTw);
911 if ($config{'listen'} && vec($rmask, fileno(LISTEN), 1)) {
912 # Got UDP packet from another webmin server
914 local $from = recv(LISTEN, $rcvbuf, 1024, 0);
916 local $fromip = inet_ntoa((unpack_sockaddr_in($from))[1]);
917 local $toip = inet_ntoa((unpack_sockaddr_in(
918 getsockname(LISTEN)))[1]);
919 if ((!@deny || !&ip_match($fromip, $toip, @deny)) &&
920 (!@allow || &ip_match($fromip, $toip, @allow))) {
921 local $listenhost = &get_socket_name(LISTEN, 0);
922 send(LISTEN, "$listenhost:$config{'port'}:".
923 ($use_ssl || $config{'inetd_ssl'} ? 1 : 0).":".
924 ($config{'listenhost'} ?
925 &get_system_hostname() : ""),
931 # check for session, password-timeout and PAM messages from subprocesses
932 for($i=0; $i<@passin; $i++) {
933 if (vec($rmask, fileno($passin[$i]), 1)) {
934 # this sub-process is asking about a password
935 local $infd = $passin[$i];
936 local $outfd = $passout[$i];
937 #local $inline = <$infd>;
938 local $inline = &sysread_line($infd);
940 print DEBUG "main: inline $inline";
943 print DEBUG "main: inline EOF\n";
945 if ($inline =~ /^delay\s+(\S+)\s+(\S+)\s+(\d+)/) {
946 # Got a delay request from a subprocess.. for
947 # valid logins, there is no delay (to prevent
948 # denial of service attacks), but for invalid
949 # logins the delay increases with each failed
952 # login OK.. no delay
953 print $outfd "0 0\n";
954 $wasblocked = $hostfail{$2} ||
959 &write_blocked_file();
968 # add the host to the block list,
970 if ($config{'blockhost_failures'} &&
972 $config{'blockhost_failures'}) {
974 $blockhosttime{$2} = $time_now;
977 local $logtext = "Security alert: Host $2 blocked after $config{'blockhost_failures'} failed logins for user $1";
983 # add the user to the user block list,
985 if ($config{'blockuser_failures'} &&
987 $config{'blockuser_failures'}) {
988 push(@denyusers, $1);
989 $blockusertime{$1} = $time_now;
992 local $logtext = "Security alert: User $1 blocked after $config{'blockuser_failures'} failed logins";
998 # Lock out the user's password, if enabled
999 if ($config{'blocklock'} &&
1001 $config{'blockuser_failures'}) {
1002 my $lk = &lock_user_password($1);
1005 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";
1006 syslog("crit", "%s",
1012 $dl = $userdlay{$1} -
1013 int(($time_now - $userlast{$1})/50);
1014 $dl = $dl < 0 ? 0 : $dl+1;
1015 print $outfd "$dl $blocked\n";
1016 $userdlay{$1} = $dl;
1018 # Write out blocked status file
1020 &write_blocked_file();
1023 $userlast{$1} = $time_now;
1025 elsif ($inline =~ /^verify\s+(\S+)\s+(\S+)/) {
1026 # Verifying a session ID
1027 local $session_id = $1;
1028 local $notimeout = $2;
1029 local $skey = $sessiondb{$session_id} ?
1031 &hash_session_id($session_id);
1032 if (!defined($sessiondb{$skey})) {
1033 # Session doesn't exist
1034 print $outfd "0 0\n";
1037 local ($user, $ltime) =
1038 split(/\s+/, $sessiondb{$skey});
1039 local $lot = &get_logout_time($user, $session_id);
1041 $time_now - $ltime > $lot*60 &&
1043 # Session has timed out
1044 print $outfd "1 ",$time_now - $ltime,"\n";
1045 #delete($sessiondb{$skey});
1049 print $outfd "2 $user\n";
1051 $time_now - $ltime >
1053 $sessiondb{$skey} = "$user $time_now";
1058 elsif ($inline =~ /^new\s+(\S+)\s+(\S+)\s+(\S+)/) {
1059 # Creating a new session
1060 local $session_id = $1;
1063 $sessiondb{&hash_session_id($session_id)} =
1064 "$user $time_now $ip";
1066 elsif ($inline =~ /^delete\s+(\S+)/) {
1067 # Logging out a session
1068 local $session_id = $1;
1069 local $skey = $sessiondb{$session_id} ?
1071 &hash_session_id($session_id);
1072 local @sdb = split(/\s+/, $sessiondb{$skey});
1073 print $outfd $sdb[0],"\n";
1074 delete($sessiondb{$skey});
1076 elsif ($inline =~ /^pamstart\s+(\S+)\s+(\S+)\s+(.*)/) {
1077 # Starting a new PAM conversation
1078 local ($cid, $host, $user) = ($1, $2, $3);
1080 # Does this user even need PAM?
1081 local ($realuser, $canlogin) =
1082 &can_user_login($user, undef, $host);
1084 if ($canlogin == 0) {
1085 # Cannot even login!
1086 print $outfd "0 Invalid username\n";
1088 elsif ($canlogin != 2) {
1089 # Not using PAM .. so just ask for
1091 $conv = { 'user' => $realuser,
1096 print $outfd "3 Password\n";
1099 # Start the PAM conversation
1100 # sub-process, and get a question
1101 $conv = { 'user' => $realuser,
1105 local ($PAMINr, $PAMINw, $PAMOUTr,
1106 $PAMOUTw) = &allocate_pipes();
1107 local $pampid = fork();
1109 close($PAMOUTr); close($PAMINw);
1110 &pam_conversation_process(
1114 close($PAMOUTw); close($PAMINr);
1115 $conv->{'pid'} = $pampid;
1116 $conv->{'PAMOUTr'} = $PAMOUTr;
1117 $conv->{'PAMINw'} = $PAMINw;
1118 push(@childpids, $pampid);
1120 # Get the first PAM question
1121 local $pok = &recv_pam_question(
1124 &end_pam_conversation($conv);
1128 $conversations{$cid} = $conv if ($conv);
1130 elsif ($inline =~ /^pamanswer\s+(\S+)\s+(.*)/) {
1131 # A response to a PAM question
1132 local ($cid, $answer) = ($1, $2);
1133 local $conv = $conversations{$cid};
1135 # No such conversation?
1136 print $outfd "0 Bad login session\n";
1138 elsif ($conv->{'pid'}) {
1139 # Send the PAM response and get
1141 &send_pam_answer($conv, $answer);
1142 local $pok = &recv_pam_question($conv, $outfd);
1144 &end_pam_conversation($conv);
1148 # This must be the password .. try it
1149 # and send back the results
1150 local ($vu, $expired, $nonexist) =
1151 &validate_user($conv->{'user'},
1154 local $ok = $vu ? 1 : 0;
1155 print $outfd "2 $conv->{'user'} $ok $expired $notexist\n";
1156 &end_pam_conversation($conv);
1159 elsif ($inline =~ /^writesudo\s+(\S+)\s+(\d+)/) {
1160 # Store the fact that some user can sudo to root
1161 local ($user, $ok) = ($1, $2);
1162 $sudocache{$user} = $ok." ".time();
1164 elsif ($inline =~ /^readsudo\s+(\S+)/) {
1165 # Query the user sudo cache (valid for 1 minute)
1167 local ($ok, $last) =
1168 split(/\s+/, $sudocache{$user});
1169 if ($last < time()-60) {
1174 # Tell client OK or not
1175 print $outfd "$ok\n";
1178 elsif ($inline =~ /\S/) {
1179 # Unknown line from pipe?
1180 print DEBUG "main: Unknown line from pipe $inline\n";
1181 print STDERR "Unknown line from pipe $inline\n";
1185 close($infd); close($outfd);
1186 $passin[$i] = $passout[$i] = undef;
1190 @passin = grep { defined($_) } @passin;
1191 @passout = grep { defined($_) } @passout;
1194 # handle_request(remoteaddress, localaddress, ipv6-flag)
1195 # Where the real work is done
1198 local ($acptip, $localip, $ipv6) = @_;
1199 print DEBUG "handle_request: from $acptip to $localip ipv6=$ipv6\n";
1200 if ($config{'loghost'}) {
1201 $acpthost = &to_hostname($acptip);
1202 $acpthost = $acptip if (!$acpthost);
1205 $acpthost = $acptip;
1207 $datestr = &http_date(time());
1209 $ok_message = "Document follows";
1210 $logged_code = undef;
1211 $reqline = $request_uri = $page = undef;
1215 # check address against access list
1216 if (@deny && &ip_match($acptip, $localip, @deny) ||
1217 @allow && !&ip_match($acptip, $localip, @allow)) {
1218 &http_error(403, "Access denied for $acptip");
1223 # Check address with TCP-wrappers
1224 if (!hosts_ctl($config{'pam'}, STRING_UNKNOWN,
1225 $acptip, STRING_UNKNOWN)) {
1226 &http_error(403, "Access denied for $acptip by TCP wrappers");
1230 print DEBUG "handle_request: passed IP checks\n";
1232 # Compute a timeout for the start of headers, based on the number of
1233 # child processes. As this increases, we use a shorter timeout to avoid
1234 # an attacker overloading the system.
1235 local $header_timeout = 60 + ($config{'maxconns'} - @childpids) * 10;
1237 # Wait at most 60 secs for start of headers for initial requests, or
1238 # 10 minutes for kept-alive connections
1240 vec($rmask, fileno(SOCK), 1) = 1;
1241 local $to = $checked_timeout ? 10*60 : $header_timeout;
1242 local $sel = select($rmask, undef, undef, $to);
1244 if ($checked_timeout) {
1245 print DEBUG "handle_request: exiting due to timeout of $to\n";
1249 &http_error(400, "Timeout",
1250 "Waited for that $to seconds for start of headers");
1254 print DEBUG "handle_request: passed timeout check\n";
1256 # Read the HTTP request and headers
1257 local $origreqline = &read_line();
1258 ($reqline = $origreqline) =~ s/\r|\n//g;
1259 $method = $page = $request_uri = undef;
1260 print DEBUG "handle_request reqline=$reqline\n";
1261 if (!$reqline && (!$use_ssl || $checked_timeout > 1)) {
1262 # An empty request .. just close the connection
1263 print DEBUG "handle_request: rejecting empty request\n";
1266 elsif ($reqline !~ /^(\S+)\s+(.*)\s+HTTP\/1\..$/) {
1267 print DEBUG "handle_request: invalid reqline=$reqline\n";
1269 # This could be an http request when it should be https
1271 local $url = $config{'musthost'} ?
1272 "https://$config{'musthost'}:$port/" :
1273 "https://$host:$port/";
1274 if ($config{'ssl_redirect'}) {
1275 # Just re-direct to the correct URL
1276 sleep(1); # Give browser a change to finish
1277 # sending its request
1278 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1279 &write_data("Date: $datestr\r\n");
1280 &write_data("Server: $config{'server'}\r\n");
1281 &write_data("Location: $url\r\n");
1282 &write_keep_alive(0);
1283 &write_data("\r\n");
1287 # Tell user the correct URL
1288 &http_error(200, "Bad Request", "This web server is running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1291 elsif (ord(substr($reqline, 0, 1)) == 128 && !$use_ssl) {
1292 # This could be an https request when it should be http ..
1293 # need to fake a HTTP response
1296 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
1297 eval "Net::SSLeay::load_error_strings()";
1298 $ssl_ctx = Net::SSLeay::CTX_new();
1299 Net::SSLeay::CTX_use_RSAPrivateKey_file(
1300 $ssl_ctx, $config{'keyfile'},
1301 &Net::SSLeay::FILETYPE_PEM);
1302 Net::SSLeay::CTX_use_certificate_file(
1304 $config{'certfile'} || $config{'keyfile'},
1305 &Net::SSLeay::FILETYPE_PEM);
1306 $ssl_con = Net::SSLeay::new($ssl_ctx);
1310 select(SSLw); $| = 1; select(STDOUT);
1311 print SSLw $origreqline;
1313 while(sysread(SOCK, $buf, 1) > 0) {
1320 Net::SSLeay::set_wfd($ssl_con, fileno(SOCK));
1321 Net::SSLeay::set_rfd($ssl_con, fileno(SSLr));
1322 Net::SSLeay::accept($ssl_con) || die "accept() failed";
1324 local $url = $config{'musthost'} ?
1325 "https://$config{'musthost'}:$port/" :
1326 "https://$host:$port/";
1327 if ($config{'ssl_redirect'}) {
1328 # Just re-direct to the correct URL
1329 sleep(1); # Give browser a change to
1330 # finish sending its request
1331 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1332 &write_data("Date: $datestr\r\n");
1333 &write_data("Server: $config{'server'}\r\n");
1334 &write_data("Location: $url\r\n");
1335 &write_keep_alive(0);
1336 &write_data("\r\n");
1340 # Tell user the correct URL
1341 &http_error(200, "Bad Request", "This web server is not running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1345 &http_error(400, "Bad Request");
1349 &http_error(400, "Bad Request");
1353 $request_uri = $page = $2;
1357 ($headline = &read_line()) =~ s/\r|\n//g;
1358 last if ($headline eq "");
1359 print DEBUG "handle_request: got headline $headline\n";
1360 if ($headline =~ /^(\S+):\s*(.*)$/) {
1361 $header{$lastheader = lc($1)} = $2;
1363 elsif ($headline =~ /^\s+(.*)$/) {
1364 $header{$lastheader} .= $headline;
1367 &http_error(400, "Bad Header $headline");
1370 if (defined($header{'host'})) {
1371 if ($header{'host'} =~ /^([^:]+):([0-9]+)$/) {
1372 ($host, $port) = ($1, $2);
1375 $host = $header{'host'};
1377 if ($config{'musthost'} && $host ne $config{'musthost'}) {
1378 # Disallowed hostname used
1379 &http_error(400, "Invalid HTTP hostname");
1383 if ($page =~ /^([^\?]+)\?(.*)$/) {
1384 # There is some query string information
1387 print DEBUG "handle_request: querystring=$querystring\n";
1388 if ($querystring !~ /=/) {
1389 $queryargs = $querystring;
1390 $queryargs =~ s/\+/ /g;
1391 $queryargs =~ s/%(..)/pack("c",hex($1))/ge;
1395 # Parse query-string parameters
1396 local @in = split(/\&/, $querystring);
1398 local ($k, $v) = split(/=/, $i, 2);
1399 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1400 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1405 $posted_data = undef;
1406 if ($method eq 'POST' &&
1407 $header{'content-type'} eq 'application/x-www-form-urlencoded') {
1408 # Read in posted query string information, up the configured maximum
1409 # post request length
1410 $clen = $header{"content-length"};
1411 $clen_read = $clen > $config{'max_post'} ? $config{'max_post'} : $clen;
1412 while(length($posted_data) < $clen_read) {
1413 $buf = &read_data($clen_read - length($posted_data));
1414 if (!length($buf)) {
1415 &http_error(500, "Failed to read POST request");
1417 chomp($posted_data);
1418 $posted_data =~ s/\015$//mg;
1419 $posted_data .= $buf;
1421 print DEBUG "clen_read=$clen_read clen=$clen posted_data=",length($posted_data),"\n";
1422 if ($clen_read != $clen && length($posted_data) > $clen) {
1423 # If the client sent more data than we asked for, chop the
1425 $posted_data = substr($posted_data, 0, $clen);
1427 if (length($posted_data) > $clen) {
1428 # When the client sent too much, delay so that it gets headers
1431 if ($header{'user-agent'} =~ /MSIE/ &&
1432 $header{'user-agent'} !~ /Opera/i) {
1433 # MSIE includes an extra newline in the data
1434 $posted_data =~ s/\r|\n//g;
1436 local @in = split(/\&/, $posted_data);
1438 local ($k, $v) = split(/=/, $i, 2);
1440 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1441 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1444 print DEBUG "handle_request: posted_data=$posted_data\n";
1447 # work out accepted encodings
1448 %acceptenc = map { $_, 1 } split(/,/, $header{'accept-encoding'});
1450 # replace %XX sequences in page
1451 $page =~ s/%(..)/pack("c",hex($1))/ge;
1453 # Check if the browser's user agent indicates a mobile device
1454 $mobile_device = &is_mobile_useragent($header{'user-agent'});
1456 # Check if Host: header is for a mobile URL
1457 foreach my $m (@mobile_prefixes) {
1458 if ($header{'host'} =~ /^\Q$m\E/i) {
1463 # check for the logout flag file, and if existant deny authentication
1464 if ($config{'logout'} && -r $config{'logout'}.$in{'miniserv_logout_id'}) {
1465 print DEBUG "handle_request: logout flag set\n";
1466 $deny_authentication++;
1467 open(LOGOUT, $config{'logout'}.$in{'miniserv_logout_id'});
1468 chop($count = <LOGOUT>);
1472 open(LOGOUT, ">$config{'logout'}$in{'miniserv_logout_id'}");
1473 print LOGOUT "$count\n";
1477 unlink($config{'logout'}.$in{'miniserv_logout_id'});
1481 # check for any redirect for the requested URL
1482 foreach my $pfx (@strip_prefix) {
1483 my $l = length($pfx);
1484 if(length($page) >= $l &&
1485 substr($page,0,$l) eq $pfx) {
1486 $page=substr($page,$l);
1490 $simple = &simplify_path($page, $bogus);
1492 $rpath .= "&".$querystring if (defined($querystring));
1493 $redir = $redirect{$rpath};
1494 if (defined($redir)) {
1495 print DEBUG "handle_request: redir=$redir\n";
1496 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1497 &write_data("Date: $datestr\r\n");
1498 &write_data("Server: $config{'server'}\r\n");
1499 local $ssl = $use_ssl || $config{'inetd_ssl'};
1500 $portstr = $port == 80 && !$ssl ? "" :
1501 $port == 443 && $ssl ? "" : ":$port";
1502 $prot = $ssl ? "https" : "http";
1503 &write_data("Location: $prot://$host$portstr$redir\r\n");
1504 &write_keep_alive(0);
1505 &write_data("\r\n");
1509 # Check for a DAV request
1511 foreach my $d (@davpaths) {
1512 if ($simple eq $d || $simple =~ /^\Q$d\E\//) {
1517 if (!$davpath && ($method eq "SEARCH" || $method eq "PUT")) {
1518 &http_error(400, "Bad Request method $method");
1521 # Check for password if needed
1522 if ($config{'userfile'}) {
1523 print DEBUG "handle_request: Need authentication\n";
1527 # Session authentication is never used for connections by
1528 # another webmin server, or for specified pages, or for DAV, or XMLRPC,
1529 # or mobile browsers if requested.
1530 if ($header{'user-agent'} =~ /webmin/i ||
1531 $header{'user-agent'} =~ /$config{'agents_nosession'}/i ||
1532 $sessiononly{$simple} || $davpath ||
1533 $simple eq "/xmlrpc.cgi" ||
1534 $acptip eq $config{'host_nosession'} ||
1535 $mobile_device && $config{'mobile_nosession'}) {
1536 print DEBUG "handle_request: Forcing HTTP authentication\n";
1537 $config{'session'} = 0;
1540 # Check for SSL authentication
1541 if ($use_ssl && $verified_client) {
1542 $peername = Net::SSLeay::X509_NAME_oneline(
1543 Net::SSLeay::X509_get_subject_name(
1544 Net::SSLeay::get_peer_certificate(
1546 $u = &find_user_by_cert($peername);
1551 if ($use_syslog && !$validated) {
1552 syslog("crit", "%s",
1553 "Unknown SSL certificate $peername");
1557 if (!$validated && !$deny_authentication) {
1558 # check for IP-based authentication
1560 foreach $a (keys %ipaccess) {
1561 if ($acptip eq $a) {
1562 # It does! Auth as the user
1564 $baseauthuser = $authuser =
1570 # Check for normal HTTP authentication
1571 if (!$validated && !$deny_authentication && !$config{'session'} &&
1572 $header{authorization} =~ /^basic\s+(\S+)$/i) {
1573 # authorization given..
1574 ($authuser, $authpass) = split(/:/, &b64decode($1), 2);
1575 print DEBUG "handle_request: doing basic auth check authuser=$authuser authpass=$authpass\n";
1576 local ($vu, $expired, $nonexist) =
1577 &validate_user($authuser, $authpass, $host,
1579 print DEBUG "handle_request: vu=$vu expired=$expired nonexist=$nonexist\n";
1580 if ($vu && (!$expired || $config{'passwd_mode'} == 1)) {
1587 if ($use_syslog && !$validated) {
1588 syslog("crit", "%s",
1589 ($nonexist ? "Non-existent" :
1590 $expired ? "Expired" : "Invalid").
1591 " login as $authuser from $acpthost");
1593 if ($authuser =~ /\r|\n|\s/) {
1594 &http_error(500, "Invalid username",
1595 "Username contains invalid characters");
1597 if ($authpass =~ /\r|\n/) {
1598 &http_error(500, "Invalid password",
1599 "Password contains invalid characters");
1602 if ($config{'passdelay'} && !$config{'inetd'} && $authuser) {
1603 # check with main process for delay
1604 print DEBUG "handle_request: about to ask for password delay\n";
1605 print $PASSINw "delay $authuser $acptip $validated\n";
1606 <$PASSOUTr> =~ /(\d+) (\d+)/;
1608 print DEBUG "handle_request: password delay $1 $2\n";
1613 # Check for a visit to the special session login page
1614 if ($config{'session'} && !$deny_authentication &&
1615 $page eq $config{'session_login'}) {
1616 if ($in{'logout'} && $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1617 # Logout clicked .. remove the session
1619 print $PASSINw "delete $sid\n";
1620 local $louser = <$PASSOUTr>;
1623 $already_session_id = undef;
1624 $authuser = $baseauthuser = undef;
1627 syslog("info", "%s", "Logout by $louser from $acpthost");
1629 &run_logout_script($louser, $sid,
1631 &write_logout_utmp($louser, $actphost);
1636 if ($in{'user'} =~ /\r|\n|\s/) {
1637 &http_error(500, "Invalid username",
1638 "Username contains invalid characters");
1640 if ($in{'pass'} =~ /\r|\n/) {
1641 &http_error(500, "Invalid password",
1642 "Password contains invalid characters");
1645 local ($vu, $expired, $nonexist) =
1646 &validate_user($in{'user'}, $in{'pass'}, $host,
1648 local $hrv = &handle_login(
1649 $vu || $in{'user'}, $vu ? 1 : 0,
1650 $expired, $nonexist, $in{'pass'},
1651 $in{'notestingcookie'});
1652 return $hrv if (defined($hrv));
1656 # Check for a visit to the special PAM login page
1657 if ($config{'session'} && !$deny_authentication &&
1658 $use_pam && $config{'pam_conv'} && $page eq $config{'pam_login'} &&
1660 # A question has been entered .. submit it to the main process
1661 print DEBUG "handle_request: Got call to $page ($in{'cid'})\n";
1662 print DEBUG "handle_request: For PAM, authuser=$authuser\n";
1663 if ($in{'answer'} =~ /\r|\n/ || $in{'cid'} =~ /\r|\n|\s/) {
1664 &http_error(500, "Invalid response",
1665 "Response contains invalid characters");
1669 # Start of a new conversation - answer must be username
1670 $cid = &generate_random_id($in{'answer'});
1671 print $PASSINw "pamstart $cid $host $in{'answer'}\n";
1674 # A response to a previous question
1676 print $PASSINw "pamanswer $cid $in{'answer'}\n";
1679 # Read back the response, and the next question (if any)
1680 local $line = <$PASSOUTr>;
1681 $line =~ s/\r|\n//g;
1682 local ($rv, $question) = split(/\s+/, $line, 2);
1685 local $hrv = &handle_login(
1686 !$in{'cid'} && $in{'answer'} ? $in{'answer'}
1689 return $hrv if (defined($hrv));
1691 elsif ($rv == 1 || $rv == 3) {
1692 # Another question .. force use of PAM CGI
1695 $querystring .= "&cid=$cid&question=".
1697 $querystring .= "&password=1" if ($rv == 3);
1699 $page = $config{'pam_login'};
1700 $miniserv_internal = 1;
1704 # Got back a final ok or failure
1705 local ($user, $ok, $expired, $nonexist) =
1706 split(/\s+/, $question);
1707 local $hrv = &handle_login(
1708 $user, $ok, $expired, $nonexist, undef,
1709 $in{'notestingcookie'});
1710 return $hrv if (defined($hrv));
1713 # A message from PAM .. tell the user
1716 $querystring .= "&cid=$cid&message=".
1719 $page = $config{'pam_login'};
1720 $miniserv_internal = 1;
1725 # Check for a visit to the special password change page
1726 if ($config{'session'} && !$deny_authentication &&
1727 $page eq $config{'password_change'} && !$validated) {
1728 # Just let this slide ..
1730 $miniserv_internal = 3;
1733 # Check for an existing session
1734 if ($config{'session'} && !$validated) {
1735 if ($already_session_id) {
1736 $session_id = $already_session_id;
1737 $authuser = $already_authuser;
1740 elsif (!$deny_authentication &&
1741 $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1742 # Try all session cookies
1743 local $cookie = $header{'cookie'};
1744 while($cookie =~ s/(^|\s)$sidname=([a-f0-9]+)//) {
1747 $in{'webmin_notimeout'} ? 1 : 0;
1748 print $PASSINw "verify $session_id $notimeout\n";
1749 <$PASSOUTr> =~ /(\d+)\s+(\S+)/;
1751 # Valid session continuation
1754 $already_authuser = $authuser;
1763 # Invalid session ID .. don't set
1770 # Check for local authentication
1771 if ($localauth_user && !$header{'x-forwarded-for'} && !$header{'via'}) {
1772 my $luser = &get_user_details($localauth_user);
1774 # Local user exists in webmin users file
1776 $authuser = $localauth_user;
1779 # Check if local user is allowed by unixauth
1780 local @can = &can_user_login($localauth_user,
1784 $authuser = $localauth_user;
1787 $localauth_user = undef;
1793 # Check if this path allows anonymous access
1795 foreach $a (keys %anonymous) {
1796 if (substr($simple, 0, length($a)) eq $a) {
1797 # It does! Auth as the user, if IP access
1798 # control allows him.
1799 if (&check_user_ip($anonymous{$a}) &&
1800 &check_user_time($anonymous{$a})) {
1802 $baseauthuser = $authuser =
1810 # Check if this path allows unauthenticated access
1811 local ($u, $unauth);
1812 foreach $u (@unauth) {
1813 $unauth++ if ($simple =~ /$u/);
1815 if (!$bogus && $unauth) {
1816 # Unauthenticated directory or file request - approve it
1818 $baseauthuser = $authuser = undef;
1823 if ($blocked == 0) {
1824 # No password given.. ask
1825 if ($config{'pam_conv'} && $use_pam) {
1826 # Force CGI for PAM question, starting with
1827 # the username which is always needed
1830 $querystring .= "&initial=1&question=".
1831 &urlize("Username");
1832 $querystring .= "&failed=$failed_user" if ($failed_user);
1833 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1835 $page = $config{'pam_login'};
1836 $miniserv_internal = 1;
1839 elsif ($config{'session'}) {
1840 # Force CGI for session login
1843 $querystring .= "&logout=1&page=/";
1846 # Re-direct to current module only
1847 local $rpage = $request_uri;
1848 if (!$config{'loginkeeppage'}) {
1849 $rpage =~ s/\?.*$//;
1850 $rpage =~ s/[^\/]+$//
1852 $querystring = "page=".&urlize($rpage);
1855 $querystring .= "&failed=$failed_user" if ($failed_user);
1856 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1858 $page = $config{'session_login'};
1859 $miniserv_internal = 1;
1863 # Ask for login with HTTP authentication
1864 &write_data("HTTP/1.0 401 Unauthorized\r\n");
1865 &write_data("Date: $datestr\r\n");
1866 &write_data("Server: $config{'server'}\r\n");
1867 &write_data("WWW-authenticate: Basic ".
1868 "realm=\"$config{'realm'}\"\r\n");
1869 &write_keep_alive(0);
1870 &write_data("Content-type: text/html\r\n");
1871 &write_data("\r\n");
1872 &reset_byte_count();
1873 &write_data("<html>\n");
1874 &write_data("<head><title>Unauthorized</title></head>\n");
1875 &write_data("<body><h1>Unauthorized</h1>\n");
1876 &write_data("A password is required to access this\n");
1877 &write_data("web server. Please try again. <p>\n");
1878 &write_data("</body></html>\n");
1879 &log_request($acpthost, undef, $reqline, 401, &byte_count());
1883 elsif ($blocked == 1) {
1884 # when the host has been blocked, give it an error
1885 &http_error(403, "Access denied for $acptip. The host ".
1886 "has been blocked because of too ".
1887 "many authentication failures.");
1889 elsif ($blocked == 2) {
1890 # when the user has been blocked, give it an error
1891 &http_error(403, "Access denied. The user ".
1892 "has been blocked because of too ".
1893 "many authentication failures.");
1897 # Get the real Webmin username
1898 local @can = &can_user_login($authuser, undef, $host);
1899 $baseauthuser = $can[3] || $authuser;
1901 if ($config{'remoteuser'} && !$< && $validated) {
1902 # Switch to the UID of the remote user (if he exists)
1903 local @u = getpwnam($authuser);
1904 if (@u && $< != $u[2]) {
1905 $( = $u[3]; $) = "$u[3] $u[3]";
1906 ($>, $<) = ($u[2], $u[2]);
1909 &http_error(500, "Unix user $authuser does not exist");
1915 # Check per-user IP access control
1916 if (!&check_user_ip($baseauthuser)) {
1917 &http_error(403, "Access denied for $acptip for $baseauthuser");
1921 # Check per-user allowed times
1922 if (!&check_user_time($baseauthuser)) {
1923 &http_error(403, "Access denied at the current time");
1927 $uinfo = &get_user_details($baseauthuser);
1929 # Validate the path, and convert to canonical form
1931 $simple = &simplify_path($page, $bogus);
1932 print DEBUG "handle_request: page=$page simple=$simple\n";
1934 &http_error(400, "Invalid path");
1937 # Check for a DAV request
1939 return &handle_dav_request($davpath);
1942 # Work out the active theme(s)
1943 local $preroots = $mobile_device && defined($config{'mobile_preroot'}) ?
1944 $config{'mobile_preroot'} :
1945 $authuser && defined($config{'preroot_'.$authuser}) ?
1946 $config{'preroot_'.$authuser} :
1947 $uinfo && defined($uinfo->{'preroot'}) ?
1948 $uinfo->{'preroot'} :
1950 local @preroots = reverse(split(/\s+/, $preroots));
1952 # Canonicalize the directories
1953 foreach my $preroot (@preroots) {
1954 # Always under the current webmin root
1955 $preroot =~ s/^.*\///g;
1956 $preroot = $roots[0].'/'.$preroot;
1959 # Look in the theme root directories first
1960 local ($full, @stfull);
1962 foreach my $preroot (@preroots) {
1965 $full = $preroot.$sofar;
1966 $scriptname = $simple;
1967 foreach $b (split(/\//, $simple)) {
1968 if ($b ne "") { $sofar .= "/$b"; }
1969 $full = $preroot.$sofar;
1970 @stfull = stat($full);
1971 if (!@stfull) { undef($full); last; }
1973 # Check if this is a directory
1975 # It is.. go on parsing
1983 # Check if this is a CGI program
1984 if (&get_type($full) eq "internal/cgi") {
1985 $pathinfo = substr($simple, length($sofar));
1986 $pathinfo .= "/" if ($page =~ /\/$/);
1987 $scriptname = $sofar;
1992 # Don't stop at a directory unless this is the last theme, which
1993 # is the 'real' one that provides the .cgi scripts
1994 if ($is_directory && $preroot ne $preroots[$#preroots]) {
2001 $cgi_pwd = $roots[0];
2003 elsif ($is_directory) {
2004 $cgi_pwd = "$roots[0]$sofar";
2007 "$roots[0]$sofar" =~ /^(.*\/)[^\/]+$/;
2010 $foundroot = $preroot;
2011 if ($is_directory) {
2012 # Check for index files in the directory
2014 foreach $idx (split(/\s+/, $config{"index_docs"})) {
2015 $idxfull = "$full/$idx";
2016 local @stidxfull = stat($idxfull);
2017 if (-r _ && !-d _) {
2019 @stfull = @stidxfull;
2022 if ($scriptname ne "/");
2027 @stfull = stat($full) if (!$foundidx);
2030 last if ($foundroot);
2032 print DEBUG "handle_request: initial full=$full\n";
2034 # Look in the real root directories, stopping when we find a file or directory
2035 if (!$full || $is_directory) {
2036 ROOT: foreach $root (@roots) {
2038 $full = $root.$sofar;
2039 $scriptname = $simple;
2040 foreach $b ($simple eq "/" ? ( "" ) : split(/\//, $simple)) {
2041 if ($b ne "") { $sofar .= "/$b"; }
2042 $full = $root.$sofar;
2043 @stfull = stat($full);
2048 # Check if this is a directory
2050 # It is.. go on parsing
2054 # Check if this is a CGI program
2055 if (&get_type($full) eq "internal/cgi") {
2056 $pathinfo = substr($simple, length($sofar));
2057 $pathinfo .= "/" if ($page =~ /\/$/);
2058 $scriptname = $sofar;
2063 # Run CGI in the same directory as whatever file
2065 $full =~ /^(.*\/)[^\/]+$/; $cgi_pwd = $1;
2074 if (!@stfull) { &http_error(404, "File not found"); }
2076 print DEBUG "handle_request: full=$full\n";
2077 @stfull = stat($full) if (!@stfull);
2079 # check filename against denyfile regexp
2080 local $denyfile = $config{'denyfile'};
2081 if ($denyfile && $full =~ /$denyfile/) {
2082 &http_error(403, "Access denied to $page");
2086 # Reached the end of the path OK.. see what we've got
2088 # See if the URL ends with a / as it should
2089 print DEBUG "handle_request: found a directory\n";
2090 if ($page !~ /\/$/) {
2091 # It doesn't.. redirect
2092 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2093 $ssl = $use_ssl || $config{'inetd_ssl'};
2094 $portstr = $port == 80 && !$ssl ? "" :
2095 $port == 443 && $ssl ? "" : ":$port";
2096 &write_data("Date: $datestr\r\n");
2097 &write_data("Server: $config{server}\r\n");
2098 $prot = $ssl ? "https" : "http";
2099 &write_data("Location: $prot://$host$portstr$page/\r\n");
2100 &write_keep_alive(0);
2101 &write_data("\r\n");
2102 &log_request($acpthost, $authuser, $reqline, 302, 0);
2105 # A directory.. check for index files
2107 foreach $idx (split(/\s+/, $config{"index_docs"})) {
2108 $idxfull = "$full/$idx";
2109 @stidxfull = stat($idxfull);
2110 if (-r _ && !-d _) {
2113 @stfull = @stidxfull;
2114 $scriptname .= "/" if ($scriptname ne "/");
2119 @stfull = stat($full) if (!$foundidx);
2122 # This is definately a directory.. list it
2123 print DEBUG "handle_request: listing directory\n";
2124 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2125 "Date: $datestr\r\n".
2126 "Server: $config{server}\r\n".
2127 "Content-type: text/html\r\n";
2129 &write_keep_alive(0);
2130 &write_data("\r\n");
2131 &reset_byte_count();
2132 &write_data("<h1>Index of $simple</h1>\n");
2133 &write_data("<pre>\n");
2134 &write_data(sprintf "%-35.35s %-20.20s %-10.10s\n",
2135 "Name", "Last Modified", "Size");
2136 &write_data("<hr>\n");
2137 opendir(DIR, $full);
2138 while($df = readdir(DIR)) {
2139 if ($df =~ /^\./) { next; }
2140 $fulldf = $full eq "/" ? $full.$df : $full."/".$df;
2141 (@stbuf = stat($fulldf)) || next;
2142 if (-d _) { $df .= "/"; }
2143 @tm = localtime($stbuf[9]);
2144 $fdate = sprintf "%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d",
2145 $tm[3],$tm[4]+1,$tm[5]+1900,
2146 $tm[0],$tm[1],$tm[2];
2147 $len = length($df); $rest = " "x(35-$len);
2149 "<a href=\"%s\">%-${len}.${len}s</a>$rest %-20.20s %-10.10s\n",
2150 $df, $df, $fdate, $stbuf[7]);
2153 &log_request($acpthost, $authuser, $reqline, $ok_code, &byte_count());
2157 # CGI or normal file
2159 if (&get_type($full) eq "internal/cgi" && $validated != 4) {
2160 # A CGI program to execute
2161 print DEBUG "handle_request: executing CGI\n";
2162 $envtz = $ENV{"TZ"};
2163 $envuser = $ENV{"USER"};
2164 $envpath = $ENV{"PATH"};
2165 $envlang = $ENV{"LANG"};
2166 $envroot = $ENV{"SystemRoot"};
2167 $envperllib = $ENV{'PERLLIB'};
2168 foreach my $k (keys %ENV) {
2171 $ENV{"PATH"} = $envpath if ($envpath);
2172 $ENV{"TZ"} = $envtz if ($envtz);
2173 $ENV{"USER"} = $envuser if ($envuser);
2174 $ENV{"OLD_LANG"} = $envlang if ($envlang);
2175 $ENV{"SystemRoot"} = $envroot if ($envroot);
2176 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
2177 $ENV{"HOME"} = $user_homedir;
2178 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
2179 $ENV{"SERVER_NAME"} = $host;
2180 $ENV{"SERVER_ADMIN"} = $config{"email"};
2181 $ENV{"SERVER_ROOT"} = $roots[0];
2182 $ENV{"SERVER_REALROOT"} = $realroot;
2183 $ENV{"SERVER_PORT"} = $port;
2184 $ENV{"REMOTE_HOST"} = $acpthost;
2185 $ENV{"REMOTE_ADDR"} = $acptip;
2186 $ENV{"REMOTE_ADDR_PROTOCOL"} = $ipv6 ? 6 : 4;
2187 $ENV{"REMOTE_USER"} = $authuser;
2188 $ENV{"BASE_REMOTE_USER"} = $authuser ne $baseauthuser ?
2189 $baseauthuser : undef;
2190 $ENV{"REMOTE_PASS"} = $authpass if (defined($authpass) &&
2191 $config{'pass_password'});
2192 if ($uinfo && $uinfo->{'proto'}) {
2193 $ENV{"REMOTE_USER_PROTO"} = $uinfo->{'proto'};
2194 $ENV{"REMOTE_USER_ID"} = $uinfo->{'id'};
2196 print DEBUG "REMOTE_USER = ",$ENV{"REMOTE_USER"},"\n";
2197 print DEBUG "BASE_REMOTE_USER = ",$ENV{"BASE_REMOTE_USER"},"\n";
2198 print DEBUG "proto=$uinfo->{'proto'} id=$uinfo->{'id'}\n" if ($uinfo);
2199 $ENV{"SSL_USER"} = $peername if ($validated == 2);
2200 $ENV{"ANONYMOUS_USER"} = "1" if ($validated == 3 || $validated == 4);
2201 $ENV{"DOCUMENT_ROOT"} = $roots[0];
2202 $ENV{"DOCUMENT_REALROOT"} = $realroot;
2203 $ENV{"GATEWAY_INTERFACE"} = "CGI/1.1";
2204 $ENV{"SERVER_PROTOCOL"} = "HTTP/1.0";
2205 $ENV{"REQUEST_METHOD"} = $method;
2206 $ENV{"SCRIPT_NAME"} = $scriptname;
2207 $ENV{"SCRIPT_FILENAME"} = $full;
2208 $ENV{"REQUEST_URI"} = $request_uri;
2209 $ENV{"PATH_INFO"} = $pathinfo;
2211 $ENV{"PATH_TRANSLATED"} = "$roots[0]$pathinfo";
2212 $ENV{"PATH_REALTRANSLATED"} = "$realroot$pathinfo";
2214 $ENV{"QUERY_STRING"} = $querystring;
2215 $ENV{"MINISERV_CONFIG"} = $config_file;
2216 $ENV{"HTTPS"} = "ON" if ($use_ssl || $config{'inetd_ssl'});
2217 $ENV{"MINISERV_PID"} = $miniserv_main_pid;
2218 $ENV{"SESSION_ID"} = $session_id if ($session_id);
2219 $ENV{"LOCAL_USER"} = $localauth_user if ($localauth_user);
2220 $ENV{"MINISERV_INTERNAL"} = $miniserv_internal if ($miniserv_internal);
2221 if (defined($header{"content-length"})) {
2222 $ENV{"CONTENT_LENGTH"} = $header{"content-length"};
2224 if (defined($header{"content-type"})) {
2225 $ENV{"CONTENT_TYPE"} = $header{"content-type"};
2227 foreach $h (keys %header) {
2228 ($hname = $h) =~ tr/a-z/A-Z/;
2230 $ENV{"HTTP_$hname"} = $header{$h};
2232 $ENV{"PWD"} = $cgi_pwd;
2233 foreach $k (keys %config) {
2234 if ($k =~ /^env_(\S+)$/) {
2235 $ENV{$1} = $config{$k};
2238 delete($ENV{'HTTP_AUTHORIZATION'});
2239 $ENV{'HTTP_COOKIE'} =~ s/;?\s*$sidname=([a-f0-9]+)//;
2240 $ENV{'MOBILE_DEVICE'} = 1 if ($mobile_device);
2242 # Check if the CGI can be handled internally
2244 local $first = <CGI>;
2246 $first =~ s/[#!\r\n]//g;
2247 $nph_script = ($full =~ /\/nph-([^\/]+)$/);
2249 if (!$config{'forkcgis'} &&
2250 ($first eq $perl_path || $first eq $linked_perl_path) &&
2252 $config{'internalcgis'}) {
2253 # setup environment for eval
2255 @ARGV = split(/\s+/, $queryargs);
2258 # Already read the post input
2259 $postinput = $posted_data;
2261 $clen = $header{"content-length"};
2262 $SIG{'CHLD'} = 'DEFAULT';
2264 # Have SOCK closed if the perl exec's something
2266 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
2270 if ($config{'log'}) {
2271 open(MINISERVLOG, ">>$config{'logfile'}");
2272 if ($config{'logperms'}) {
2273 chmod(oct($config{'logperms'}),
2274 $config{'logfile'});
2277 chmod(0600, $config{'logfile'});
2280 $doing_cgi_eval = 1;
2281 $main_process_id = $$;
2283 if ($full =~ /^\Q$foundroot\E\/([^\/]+)\//) {
2284 # Eval in package from Webmin module name
2286 $pkg =~ s/[^A-Za-z0-9]/_/g;
2291 tie(*STDOUT, 'miniserv');
2292 tie(*STDIN, 'miniserv');
2293 do \$miniserv::full;
2296 $doing_cgi_eval = 0;
2299 &http_error(500, "Perl execution failed",
2300 $config{'noshowstderr'} ? undef : $@);
2302 elsif (!$doneheaders && !$nph_script) {
2303 &http_error(500, "Missing Headers");
2310 # fork the process that actually executes the CGI
2311 pipe(CGIINr, CGIINw);
2312 pipe(CGIOUTr, CGIOUTw);
2313 pipe(CGIERRr, CGIERRw);
2314 if (!($cgipid = fork())) {
2315 @execargs = ( $full, split(/\s+/, $queryargs) );
2318 open(STDIN, "<&CGIINr");
2319 open(STDOUT, ">&CGIOUTw");
2320 open(STDERR, ">&CGIERRw");
2321 close(CGIINw); close(CGIOUTr); close(CGIERRr);
2323 die "Failed to exec $full : $!\n";
2326 close(CGIINr); close(CGIOUTw); close(CGIERRw);
2329 # write CGI input to a temp file
2330 $infile = "$config{'tempbase'}.$$";
2331 open(CGIINw, ">$infile");
2332 # NOT binary mode, as CGIs don't read in it!
2337 # already read the posted data
2338 print CGIINw $posted_data;
2340 $clen = $header{"content-length"};
2341 if ($method eq "POST" && $clen_read < $clen) {
2342 $SIG{'PIPE'} = 'IGNORE';
2344 while($got < $clen) {
2345 $buf = &read_data($clen-$got);
2346 if (!length($buf)) {
2347 kill('TERM', $cgipid);
2348 unlink($infile) if ($infile);
2349 &http_error(500, "Failed to read ".
2352 $got += length($buf);
2353 local ($wrote) = (print CGIINw $buf);
2356 # If the CGI terminated early, we still need to read
2357 # from the browser and throw away
2358 while($got < $clen) {
2359 $buf = &read_data($clen-$got);
2360 if (!length($buf)) {
2361 kill('TERM', $cgipid);
2362 unlink($infile) if ($infile);
2363 &http_error(500, "Failed to read ".
2366 $got += length($buf);
2368 $SIG{'PIPE'} = 'DEFAULT';
2374 # Run the CGI program, and feed it input
2376 local $qqueryargs = join(" ", map { "\"$_\"" }
2377 split(/\s+/, $queryargs));
2378 if ($first =~ /(perl|perl.exe)$/i) {
2379 # On Windows, run with Perl
2380 open(CGIOUTr, "$perl_path \"$full\" $qqueryargs <$infile |");
2383 open(CGIOUTr, "\"$full\" $qqueryargs <$infile |");
2389 # read back cgi headers
2390 select(CGIOUTr); $|=1; select(STDOUT);
2394 $line =~ s/\r|\n//g;
2396 if ($got_blank || %cgiheader) { last; }
2400 if ($line !~ /^(\S+):\s+(.*)$/) {
2401 $errs = &read_errors(CGIERRr);
2402 close(CGIOUTr); close(CGIERRr);
2403 unlink($infile) if ($infile);
2404 &http_error(500, "Bad Header", $errs);
2406 $cgiheader{lc($1)} = $2;
2407 push(@cgiheader, [ $1, $2 ]);
2409 if ($cgiheader{"location"}) {
2410 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2411 &write_data("Date: $datestr\r\n");
2412 &write_data("Server: $config{'server'}\r\n");
2413 &write_keep_alive(0);
2414 # ignore the rest of the output. This is a hack,
2415 # but is necessary for IE in some cases :(
2416 close(CGIOUTr); close(CGIERRr);
2418 elsif ($cgiheader{"content-type"} eq "") {
2419 close(CGIOUTr); close(CGIERRr);
2420 unlink($infile) if ($infile);
2421 $errs = &read_errors(CGIERRr);
2422 &http_error(500, "Missing Content-Type Header",
2423 $config{'noshowstderr'} ? undef : $errs);
2426 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2427 &write_data("Date: $datestr\r\n");
2428 &write_data("Server: $config{'server'}\r\n");
2429 &write_keep_alive(0);
2431 foreach $h (@cgiheader) {
2432 &write_data("$h->[0]: $h->[1]\r\n");
2434 &write_data("\r\n");
2436 &reset_byte_count();
2437 while($line = <CGIOUTr>) {
2442 unlink($infile) if ($infile);
2448 print DEBUG "handle_request: outputting file $full\n";
2449 $gzfile = $full.".gz";
2451 if ($config{'gzip'} ne '0' && -r $gzfile && $acceptenc{'gzip'}) {
2452 # Using gzipped version
2453 @stopen = stat($gzfile);
2454 if ($stopen[9] >= $stfull[9] && open(FILE, $gzfile)) {
2455 print DEBUG "handle_request: using gzipped $gzfile\n";
2460 # Using original file
2462 open(FILE, $full) || &http_error(404, "Failed to open file");
2466 # Build common headers
2467 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2468 "Date: $datestr\r\n".
2469 "Server: $config{server}\r\n".
2470 "Content-type: ".&get_type($full)."\r\n".
2471 "Last-Modified: ".&http_date($stopen[9])."\r\n".
2473 &http_date(time()+&get_expires_time($simple))."\r\n";
2475 if (!$gzipped && $use_gzip && $acceptenc{'gzip'} &&
2476 &should_gzip_file($full)) {
2477 # Load and compress file, then output
2478 print DEBUG "handle_request: outputting gzipped file $full\n";
2479 open(FILE, $full) || &http_error(404, "Failed to open file");
2485 @stopen = stat($file);
2486 $data = Compress::Zlib::memGzip($data);
2487 $resp .= "Content-length: ".length($data)."\r\n".
2488 "Content-Encoding: gzip\r\n";
2490 $rv = &write_keep_alive();
2491 &write_data("\r\n");
2492 &reset_byte_count();
2496 # Stream file output
2497 $resp .= "Content-length: $stopen[7]\r\n";
2498 $resp .= "Content-Encoding: gzip\r\n" if ($gzipped);
2500 $rv = &write_keep_alive();
2501 &write_data("\r\n");
2502 &reset_byte_count();
2503 my $bufsize = $config{'bufsize'} || 1024;
2504 while(read(FILE, $buf, $bufsize) > 0) {
2512 &log_request($acpthost, $authuser, $reqline,
2513 $logged_code ? $logged_code :
2514 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2518 # http_error(code, message, body, [dontexit])
2521 local $eh = $error_handler_recurse ? undef :
2522 $config{"error_handler_$_[0]"} ? $config{"error_handler_$_[0]"} :
2523 $config{'error_handler'} ? $config{'error_handler'} : undef;
2524 print DEBUG "http_error code=$_[0] message=$_[1] body=$_[2]\n";
2526 # Call a CGI program for the error
2528 $querystring = "code=$_[0]&message=".&urlize($_[1]).
2529 "&body=".&urlize($_[2]);
2530 $error_handler_recurse++;
2532 $ok_message = $_[1];
2536 # Use the standard error message display
2537 &write_data("HTTP/1.0 $_[0] $_[1]\r\n");
2538 &write_data("Server: $config{server}\r\n");
2539 &write_data("Date: $datestr\r\n");
2540 &write_data("Content-type: text/html\r\n");
2541 &write_keep_alive(0);
2542 &write_data("\r\n");
2543 &reset_byte_count();
2544 &write_data("<h1>Error - $_[1]</h1>\n");
2546 &write_data("<pre>$_[2]</pre>\n");
2549 &log_request($acpthost, $authuser, $reqline, $_[0], &byte_count())
2551 &log_error($_[1], $_[2] ? " : $_[2]" : "");
2558 if ($_[0] =~ /\.([A-z0-9]+)$/) {
2564 return "text/plain";
2567 # simplify_path(path, bogus)
2568 # Given a path, maybe containing stuff like ".." and "." convert it to a
2569 # clean, absolute form.
2572 local($dir, @bits, @fixedbits, $b);
2574 $dir =~ s/\\/\//g; # fix windows \ in path
2577 $dir =~ s/\0//g; # remove null bytes
2578 @bits = split(/\/+/, $dir);
2581 foreach $b (@bits) {
2585 elsif ($b eq ".." || $b eq "...") {
2587 if (scalar(@fixedbits) == 0) {
2595 push(@fixedbits, $b);
2598 return "/" . join('/', @fixedbits);
2602 # Converts a string from base64 format to normal
2605 local($str) = $_[0];
2607 $str =~ tr|A-Za-z0-9+=/||cd;
2609 $str =~ tr|A-Za-z0-9+/| -_|;
2610 while ($str =~ /(.{1,60})/gs) {
2611 my $len = chr(32 + length($1)*3/4);
2612 $res .= unpack("u", $len . $1 );
2617 # ip_match(remoteip, localip, [match]+)
2618 # Checks an IP address against a list of IPs, networks and networks/masks
2621 local(@io, @mo, @ms, $i, $j, $hn, $needhn);
2622 @io = &check_ip6address($_[0]) ? split(/:/, $_[0])
2623 : split(/\./, $_[0]);
2624 for($i=2; $i<@_; $i++) {
2625 $needhn++ if ($_[$i] =~ /^\*(\S+)$/);
2627 if ($needhn && !defined($hn = $ip_match_cache{$_[0]})) {
2628 # Reverse-lookup hostname if any rules match based on it
2629 $hn = &to_hostname($_[0]);
2630 if (&check_ip6address($_[0])) {
2631 $hn = "" if (&to_ip6address($hn) ne $_[0]);
2634 $hn = "" if (&to_ipaddress($hn) ne $_[0]);
2636 $ip_match_cache{$_[0]} = $hn;
2638 for($i=2; $i<@_; $i++) {
2639 local $mismatch = 0;
2640 if ($_[$i] =~ /^(\S+)\/(\d+)$/) {
2641 # Convert CIDR to netmask format
2642 $_[$i] = $1."/".&prefix_to_mask($2);
2644 if ($_[$i] =~ /^(\S+)\/(\S+)$/) {
2645 # Compare with IPv4 network/mask
2646 @mo = split(/\./, $1); @ms = split(/\./, $2);
2647 for($j=0; $j<4; $j++) {
2648 if ((int($io[$j]) & int($ms[$j])) != int($mo[$j])) {
2653 elsif ($_[$i] =~ /^\*(\S+)$/) {
2654 # Compare with hostname regexp
2655 $mismatch = 1 if ($hn !~ /$1$/);
2657 elsif ($_[$i] eq 'LOCAL' && &check_ipaddress($_[1])) {
2658 # Compare with local IPv4 network
2659 local @lo = split(/\./, $_[1]);
2661 $mismatch = 1 if ($lo[0] != $io[0]);
2663 elsif ($lo[0] < 192) {
2664 $mismatch = 1 if ($lo[0] != $io[0] ||
2668 $mismatch = 1 if ($lo[0] != $io[0] ||
2673 elsif ($_[$i] eq 'LOCAL' && &check_ip6address($_[1])) {
2674 # Compare with local IPv6 network, which is always first 4 words
2675 local @lo = split(/:/, $_[1]);
2676 for(my $i=0; $i<4; $i++) {
2677 $mismatch = 1 if ($lo[$i] ne $io[$i]);
2680 elsif ($_[$i] =~ /^[0-9\.]+$/) {
2681 # Compare with IPv4 address or network
2682 @mo = split(/\./, $_[$i]);
2683 while(@mo && !$mo[$#mo]) { pop(@mo); }
2684 for($j=0; $j<@mo; $j++) {
2685 if ($mo[$j] != $io[$j]) {
2690 elsif ($_[$i] =~ /^[a-f0-9:]+$/) {
2691 # Compare with IPv6 address or network
2692 @mo = split(/:/, $_[$i]);
2693 while(@mo && !$mo[$#mo]) { pop(@mo); }
2694 for($j=0; $j<@mo; $j++) {
2695 if ($mo[$j] ne $io[$j]) {
2700 elsif ($_[$i] !~ /^[0-9\.]+$/) {
2701 # Compare with hostname
2702 $mismatch = 1 if ($_[0] ne &to_ipaddress($_[$i]));
2704 return 1 if (!$mismatch);
2709 # users_match(&uinfo, user, ...)
2710 # Returns 1 if a user is in a list of users and groups
2713 local $uinfo = shift(@_);
2715 local @ginfo = getgrgid($uinfo->[3]);
2717 if ($u =~ /^\@(\S+)$/) {
2718 return 1 if (&is_group_member($uinfo, $1));
2720 elsif ($u =~ /^(\d*)-(\d*)$/ && ($1 || $2)) {
2721 return (!$1 || $uinfo[2] >= $1) &&
2722 (!$2 || $uinfo[2] <= $2);
2725 return 1 if ($u eq $uinfo->[0]);
2731 # restart_miniserv()
2732 # Called when a SIGHUP is received to restart the web server. This is done
2733 # by exec()ing perl with the same command line as was originally used
2734 sub restart_miniserv
2736 print STDERR "restarting miniserv\n";
2737 &log_error("Restarting");
2739 &close_all_sockets();
2741 dbmclose(%sessiondb);
2742 kill('KILL', $logclearer) if ($logclearer);
2743 kill('KILL', $extauth) if ($extauth);
2744 exec($perl_path, $miniserv_path, @miniserv_argv);
2745 die "Failed to restart miniserv with $perl_path $miniserv_path";
2758 # to_ipaddress(address, ...)
2763 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2764 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/ || $i =~ /^[a-f0-9:]+$/) {
2765 # A pattern or IP, not a hostname, so don't change
2770 push(@rv, join('.', unpack("CCCC", inet_aton($i))));
2773 return wantarray ? @rv : $rv[0];
2776 # to_ip6address(address, ...)
2781 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2782 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/ || $i =~ /^[a-f0-9:]+$/) {
2783 # A pattern, not a hostname, so don't change
2787 # Lookup IPv6 address
2788 local ($inaddr, $addr);
2789 (undef, undef, undef, $inaddr) =
2790 getaddrinfo($i, undef, Socket6::AF_INET6(), SOCK_STREAM);
2795 (undef, $addr) = unpack_sockaddr_in6($inaddr);
2796 push(@rv, inet_ntop(Socket6::AF_INET6(), $addr));
2800 return wantarray ? @rv : $rv[0];
2803 # to_hostname(ipv4|ipv6-address)
2804 # Reverse-resolves an IPv4 or 6 address to a hostname
2808 if (&check_ip6address($_[0])) {
2809 return gethostbyaddr(inet_pton(Socket6::AF_INET6(), $addr),
2810 Socket6::AF_INET6());
2813 return gethostbyaddr(inet_aton($addr), AF_INET);
2817 # read_line(no-wait, no-limit)
2818 # Reads one line from SOCK or SSL
2821 local ($nowait, $nolimit) = @_;
2822 local($idx, $more, $rv);
2823 while(($idx = index($main::read_buffer, "\n")) < 0) {
2824 if (length($main::read_buffer) > 10000 && !$nolimit) {
2825 &http_error(414, "Request too long",
2826 "Received excessive line <pre>$main::read_buffer</pre>");
2829 # need to read more..
2830 &wait_for_data_error() if (!$nowait);
2832 $more = Net::SSLeay::read($ssl_con);
2835 my $bufsize = $config{'bufsize'} || 1024;
2836 local $ok = sysread(SOCK, $more, $bufsize);
2837 $more = undef if ($ok <= 0);
2841 $rv = $main::read_buffer;
2842 undef($main::read_buffer);
2845 $main::read_buffer .= $more;
2847 $rv = substr($main::read_buffer, 0, $idx+1);
2848 $main::read_buffer = substr($main::read_buffer, $idx+1);
2853 # Reads up to some amount of data from SOCK or the SSL connection
2857 if (length($main::read_buffer)) {
2858 if (length($main::read_buffer) > $_[0]) {
2859 # Return the first part of the buffer
2860 $rv = substr($main::read_buffer, 0, $_[0]);
2861 $main::read_buffer = substr($main::read_buffer, $_[0]);
2865 # Return the whole buffer
2866 $rv = $main::read_buffer;
2867 undef($main::read_buffer);
2872 # Call SSL read function
2873 return Net::SSLeay::read($ssl_con, $_[0]);
2876 # Just do a normal read
2878 sysread(SOCK, $buf, $_[0]) || return undef;
2884 # Read a line from a file handle, using sysread to get a byte at a time
2891 $got = sysread($fh, $buf, 1);
2892 last if ($got <= 0);
2894 last if ($buf eq "\n");
2899 # wait_for_data(secs)
2900 # Waits at most the given amount of time for some data on SOCK, returning
2901 # 0 if not found, 1 if some arrived.
2905 vec($rmask, fileno(SOCK), 1) = 1;
2906 local $got = select($rmask, undef, undef, $_[0]);
2907 return $got == 0 ? 0 : 1;
2910 # wait_for_data_error()
2911 # Waits 60 seconds for data on SOCK, and fails if none arrives
2912 sub wait_for_data_error
2914 local $got = &wait_for_data(60);
2916 &http_error(400, "Timeout",
2917 "Waited more than 60 seconds for request data");
2921 # write_data(data, ...)
2922 # Writes a string to SOCK or the SSL connection
2925 local $str = join("", @_);
2927 Net::SSLeay::write($ssl_con, $str);
2930 syswrite(SOCK, $str, length($str));
2932 # Intentionally introduce a small delay to avoid problems where IE reports
2933 # the page as empty / DNS failed when it get a large response too quickly!
2934 select(undef, undef, undef, .01) if ($write_data_count%10 == 0);
2935 $write_data_count += length($str);
2938 # reset_byte_count()
2939 sub reset_byte_count { $write_data_count = 0; }
2942 sub byte_count { return $write_data_count; }
2944 # log_request(hostname, user, request, code, bytes)
2947 if ($config{'log'}) {
2948 local ($user, $ident, $headers);
2949 if ($config{'logident'}) {
2950 # add support for rfc1413 identity checking here
2952 else { $ident = "-"; }
2953 $user = $_[1] ? $_[1] : "-";
2954 local $dstr = &make_datestr();
2955 if (fileno(MINISERVLOG)) {
2956 seek(MINISERVLOG, 0, 2);
2959 open(MINISERVLOG, ">>$config{'logfile'}");
2960 chmod(0600, $config{'logfile'});
2962 if (defined($config{'logheaders'})) {
2963 foreach $h (split(/\s+/, $config{'logheaders'})) {
2964 $headers .= " $h=\"$header{$h}\"";
2967 elsif ($config{'logclf'}) {
2968 $headers = " \"$header{'referer'}\" \"$header{'user-agent'}\"";
2973 print MINISERVLOG "$_[0] $ident $user [$dstr] \"$_[2]\" ",
2974 "$_[3] $_[4]$headers\n";
2982 local @tm = localtime(time());
2983 return sprintf "%2.2d/%s/%4.4d:%2.2d:%2.2d:%2.2d %s",
2984 $tm[3], $month[$tm[4]], $tm[5]+1900,
2985 $tm[2], $tm[1], $tm[0], $timezone;
2988 # log_error(message)
2992 print STDERR "[",&make_datestr(),"] ",
2993 $acpthost ? ( "[",$acpthost,"] " ) : ( ),
2994 $page ? ( $page," : " ) : ( ),
2998 # read_errors(handle)
2999 # Read and return all input from some filehandle
3002 local($fh, $_, $rv);
3004 while(<$fh>) { $rv .= $_; }
3008 sub write_keep_alive
3011 if ($config{'nokeepalive'}) {
3012 # Keep alives have been disabled in config
3015 elsif (@childpids > $config{'maxconns'}*.8) {
3016 # Disable because nearing process limit
3020 # Keep alive specified by caller
3024 # Keep alive determined by browser
3025 $mode = $header{'connection'} =~ /keep-alive/i;
3027 &write_data("Connection: ".($mode ? "Keep-Alive" : "close")."\r\n");
3033 kill('TERM', @childpids) if (@childpids);
3034 kill('KILL', $logclearer) if ($logclearer);
3035 kill('KILL', $extauth) if ($extauth);
3041 local @tm = gmtime($_[0]);
3042 return sprintf "%s, %d %s %d %2.2d:%2.2d:%2.2d GMT",
3043 $weekday[$tm[6]], $tm[3], $month[$tm[4]], $tm[5]+1900,
3044 $tm[2], $tm[1], $tm[0];
3049 my $i; bless \$i, shift;
3055 my($buf,$len,$offset) = @_;
3056 &write_to_sock(substr($buf, $offset, $len));
3057 $miniserv::page_capture_out .= substr($buf, $offset, $len)
3058 if ($miniserv::page_capture);
3065 my $buf = join(defined($,) ? $, : "", @_);
3066 $buf .= $\ if defined($\);
3067 &write_to_sock($buf);
3068 $miniserv::page_capture_out .= $buf
3069 if ($miniserv::page_capture);
3076 my $buf = sprintf $fmt, @_;
3077 &write_to_sock($buf);
3078 $miniserv::page_capture_out .= $buf
3079 if ($miniserv::page_capture);
3082 # Send back already read data while we have it, then read from SOCK
3086 my $bufref = \$_[0];
3089 if ($postpos < length($postinput)) {
3090 # Reading from already fetched array
3091 my $left = length($postinput) - $postpos;
3092 my $canread = $len > $left ? $left : $len;
3093 substr($$bufref, $offset, $canread) =
3094 substr($postinput, $postpos, $canread);
3095 $postpos += $canread;
3099 # Read from network socket
3100 local $data = &read_data($len);
3101 if ($data eq '' && $len) {
3103 print STDERR "finished reading - shutting down socket\n";
3106 substr($$bufref, $offset, length($data)) = $data;
3107 return length($data);
3113 #print STDERR "open() called - should never happen!\n";
3116 # Read a line of input
3120 if ($postpos < length($postinput) &&
3121 ($idx = index($postinput, "\n", $postpos)) >= 0) {
3122 # A line exists in the memory buffer .. use it
3123 my $line = substr($postinput, $postpos, $idx-$postpos+1);
3128 # Need to read from the socket
3130 if ($postpos < length($postinput)) {
3131 # Start with in-memory data
3132 $line = substr($postinput, $postpos);
3133 $postpos = length($postinput);
3135 my $nl = &read_line(0, 1);
3138 print STDERR "finished reading - shutting down socket\n";
3141 $line .= $nl if (defined($nl));
3146 # Read one character of input
3151 my $got = READ($r, \$buf, 1, 0);
3152 return $got > 0 ? $buf : undef;
3157 return fileno(SOCK);
3164 # write_to_sock(data, ...)
3169 if ($doneheaders || $miniserv::nph_script) {
3174 while(!$doneheaders && $headers =~ s/^([^\r\n]*)(\r)?\n//) {
3175 if ($1 =~ /^(\S+):\s+(.*)$/) {
3176 $cgiheader{lc($1)} = $2;
3177 push(@cgiheader, [ $1, $2 ]);
3179 elsif ($1 !~ /\S/) {
3183 &http_error(500, "Bad Header");
3187 if ($cgiheader{"location"}) {
3189 "HTTP/1.0 302 Moved Temporarily\r\n");
3190 &write_data("Date: $datestr\r\n");
3191 &write_data("Server: $config{server}\r\n");
3192 &write_keep_alive(0);
3194 elsif ($cgiheader{"content-type"} eq "") {
3195 &http_error(500, "Missing Content-Type Header");
3198 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
3199 &write_data("Date: $datestr\r\n");
3200 &write_data("Server: $config{server}\r\n");
3201 &write_keep_alive(0);
3203 foreach $h (@cgiheader) {
3204 &write_data("$h->[0]: $h->[1]\r\n");
3206 &write_data("\r\n");
3207 &reset_byte_count();
3208 &write_data($headers);
3216 local $cert = Net::SSLeay::X509_STORE_CTX_get_current_cert($_[1]);
3218 local $errnum = Net::SSLeay::X509_STORE_CTX_get_error($_[1]);
3219 $verified_client = 1 if (!$errnum);
3226 if ($doing_cgi_eval && $$ == $main_process_id) {
3227 # A CGI program called exit! This is a horrible hack to
3228 # finish up before really exiting
3231 close($PASSINw); close($PASSOUTw);
3232 &log_request($acpthost, $authuser, $reqline,
3233 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
3238 # Convert a string to a form ok for putting in a URL
3240 local($tmp, $tmp2, $c);
3243 while(($c = chop($tmp)) ne "") {
3244 if ($c !~ /[A-z0-9]/) {
3245 $c = sprintf("%%%2.2X", ord($c));
3252 # validate_user(username, password, host, remote-ip, webmin-port)
3253 # Checks if some username and password are valid. Returns the modified username,
3254 # the expired / temp pass flag, and the non-existence flag
3257 local ($user, $pass, $host, $actpip, $port) = @_;
3258 return ( ) if (!$user);
3259 print DEBUG "validate_user: user=$user pass=$pass host=$host\n";
3260 local ($canuser, $canmode, $notexist, $webminuser, $sudo) =
3261 &can_user_login($user, undef, $host);
3262 print DEBUG "validate_user: canuser=$canuser canmode=$canmode notexist=$notexist webminuser=$webminuser sudo=$sudo\n";
3264 # User doesn't even exist, so go no further
3265 return ( undef, 0, 1 );
3267 elsif ($canmode == 0) {
3268 # User does exist but cannot login
3269 return ( $canuser, 0, 0 );
3271 elsif ($canmode == 1) {
3272 # Attempt Webmin authentication
3273 my $uinfo = &get_user_details($webminuser);
3275 &password_crypt($pass, $uinfo->{'pass'}) eq $uinfo->{'pass'}) {
3276 # Password is valid .. but check for expiry
3277 local $lc = $uinfo->{'lastchanges'};
3278 print DEBUG "validate_user: Password is valid lc=$lc pass_maxdays=$config{'pass_maxdays'}\n";
3279 if ($config{'pass_maxdays'} && $lc && !$uinfo->{'nochange'}) {
3280 local $daysold = (time() - $lc)/(24*60*60);
3281 print DEBUG "maxdays=$config{'pass_maxdays'} daysold=$daysold temppass=$uinfo->{'temppass'}\n";
3282 if ($config{'pass_lockdays'} &&
3283 $daysold > $config{'pass_lockdays'}) {
3284 # So old that the account is locked
3285 return ( undef, 0, 0 );
3287 elsif ($daysold > $config{'pass_maxdays'}) {
3288 # Password has expired
3289 return ( $user, 1, 0 );
3292 if ($uinfo->{'temppass'}) {
3293 # Temporary password - force change now
3294 return ( $user, 2, 0 );
3296 return ( $user, 0, 0 );
3299 print DEBUG "validate_user: User $webminuser not found\n";
3300 return ( undef, 0, 0 );
3303 print DEBUG "validate_user: User $webminuser password mismatch $pass != $uinfo->{'pass'}\n";
3304 return ( undef, 0, 0 );
3307 elsif ($canmode == 2 || $canmode == 3) {
3308 # Attempt PAM or passwd file authentication
3309 local $val = &validate_unix_user($canuser, $pass, $acptip, $port);
3310 print DEBUG "validate_user: unix val=$val\n";
3311 if ($val && $sudo) {
3312 # Need to check if this Unix user can sudo
3313 if (!&check_sudo_permissions($canuser, $pass)) {
3314 print DEBUG "validate_user: sudo failed\n";
3318 print DEBUG "validate_user: sudo passed\n";
3321 return $val == 2 ? ( $canuser, 1, 0 ) :
3322 $val == 1 ? ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3324 elsif ($canmode == 4) {
3325 # Attempt external authentication
3326 return &validate_external_user($canuser, $pass) ?
3327 ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3335 # validate_unix_user(user, password, remote-ip, local-port)
3336 # Returns 1 if a username and password are valid under unix, 0 if not,
3337 # or 2 if the account has expired.
3338 # Checks PAM if available, and falls back to reading the system password
3340 sub validate_unix_user
3344 $pam_username = $_[0];
3345 $pam_password = $_[1];
3346 eval "use Authen::PAM;";
3347 local $pamh = new Authen::PAM($config{'pam'}, $pam_username,
3350 $pamh->pam_set_item("PAM_RHOST", $_[2]) if ($_[2]);
3351 $pamh->pam_set_item("PAM_TTY", $_[3]) if ($_[3]);
3352 local $pam_ret = $pamh->pam_authenticate();
3353 if ($pam_ret == PAM_SUCCESS()) {
3354 # Logged in OK .. make sure password hasn't expired
3355 local $acct_ret = $pamh->pam_acct_mgmt();
3356 if ($acct_ret == PAM_SUCCESS()) {
3357 $pamh->pam_open_session();
3360 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3361 $acct_ret == PAM_ACCT_EXPIRED()) {
3365 print STDERR "Unknown pam_acct_mgmt return value : $acct_ret\n";
3372 elsif ($config{'pam_only'}) {
3373 # Pam is not available, but configuration forces it's use!
3376 elsif ($config{'passwd_file'}) {
3377 # Check in a password file
3379 open(FILE, $config{'passwd_file'});
3380 if ($config{'passwd_file'} eq '/etc/security/passwd') {
3381 # Assume in AIX format
3384 if (/^\s*(\S+):/ && $1 eq $_[0]) {
3386 if (/^\s*password\s*=\s*(\S+)\s*$/) {
3387 $rv = $1 eq &password_crypt($_[1], $1) ?
3395 # Read the system password or shadow file
3397 local @l = split(/:/, $_, -1);
3398 local $u = $l[$config{'passwd_uindex'}];
3399 local $p = $l[$config{'passwd_pindex'}];
3401 $rv = $p eq &password_crypt($_[1], $p) ? 1 : 0;
3402 if ($config{'passwd_cindex'} ne '' && $rv) {
3403 # Password may have expired!
3404 local $c = $l[$config{'passwd_cindex'}];
3405 local $m = $l[$config{'passwd_mindex'}];
3406 local $day = time()/(24*60*60);
3407 if ($c =~ /^\d+/ && $m =~ /^\d+/ &&
3413 if ($p eq "" && $config{'passwd_blank'}) {
3414 # Force password change
3422 return $rv if ($rv);
3425 # Fallback option - check password returned by getpw*
3426 local @uinfo = getpwnam($_[0]);
3427 if ($uinfo[1] ne '' && &password_crypt($_[1], $uinfo[1]) eq $uinfo[1]) {
3431 return 0; # Totally failed
3434 # validate_external_user(user, pass)
3435 # Validate a user by passing the username and password to an external
3436 # squid-style authentication program
3437 sub validate_external_user
3439 return 0 if (!$config{'extauth'});
3441 local $str = "$_[0] $_[1]\n";
3442 syswrite(EXTAUTH, $str, length($str));
3443 local $resp = <EXTAUTH>;
3445 return $resp =~ /^OK/i ? 1 : 0;
3448 # can_user_login(username, no-append, host)
3449 # Checks if a user can login or not.
3450 # First return value is the username.
3451 # Second is 0 if cannot login, 1 if using Webmin pass, 2 if PAM, 3 if password
3452 # file, 4 if external.
3453 # Third is 1 if the user does not exist at all, 0 if he does.
3454 # Fourth is the Webmin username whose permissions apply, based on unixauth.
3455 # Fifth is a flag indicating if a sudo check is needed.
3458 local $uinfo = &get_user_details($_[0]);
3460 # See if this user exists in Unix and can be validated by the same
3461 # method as the unixauth webmin user
3462 local $realuser = $unixauth{$_[0]};
3466 eval { @uinfo = getpwnam($_[0]); }; # may fail on windows
3467 if (!$realuser && @uinfo) {
3468 # No unixauth entry for the username .. try his groups
3469 foreach my $ua (keys %unixauth) {
3470 if ($ua =~ /^\@(.*)$/) {
3471 if (&is_group_member(\@uinfo, $1)) {
3472 $realuser = $unixauth{$ua};
3478 if (!$realuser && @uinfo) {
3479 # Fall back to unix auth for all Unix users
3480 $realuser = $unixauth{"*"};
3482 if (!$realuser && $use_sudo && @uinfo) {
3483 # Allow login effectively as root, if sudo permits it
3487 if (!$realuser && !@uinfo && $config{'pamany'}) {
3488 # If the user completely doesn't exist, we can still allow
3489 # him to authenticate via PAM
3490 $realuser = $config{'pamany'};
3494 # For Usermin, always fall back to unix auth for any user,
3495 # so that later checks with domain added / removed are done.
3496 $realuser = $unixauth{"*"};
3498 return (undef, 0, 1, undef) if (!$realuser);
3499 local $uinfo = &get_user_details($realuser);
3500 return (undef, 0, 1, undef) if (!$uinfo);
3501 local $up = $uinfo->{'pass'};
3503 # Work out possible domain names from the hostname
3504 local @doms = ( $_[2] );
3505 if ($_[2] =~ /^([^\.]+)\.(\S+)$/) {
3509 if ($config{'user_mapping'} && !%user_mapping) {
3510 # Read the user mapping file
3512 open(MAPPING, $config{'user_mapping'});
3516 if (/^(\S+)\s+(\S+)/) {
3517 if ($config{'user_mapping_reverse'}) {
3518 $user_mapping{$1} = $2;
3521 $user_mapping{$2} = $1;
3528 # Check the user mapping file to see if there is an entry for the
3529 # user login in which specifies a new effective user
3531 foreach my $d (@doms) {
3532 $um ||= $user_mapping{"$_[0]\@$d"};
3534 $um ||= $user_mapping{$_[0]};
3535 if (defined($um) && ($_[1]&4) == 0) {
3536 # A mapping exists - use it!
3537 return &can_user_login($um, $_[1]+4, $_[2]);
3540 # Check if a user with the entered login and the domains appended
3541 # or prepended exists, and if so take it to be the effective user
3542 if (!@uinfo && $config{'domainuser'}) {
3543 # Try again with name.domain and name.firstpart
3544 local @firsts = map { /^([^\.]+)/; $1 } @doms;
3545 if (($_[1]&1) == 0) {
3547 foreach $a (@firsts, @doms) {
3548 foreach $p ("$_[0].${a}", "$_[0]-${a}",
3549 "${a}.$_[0]", "${a}-$_[0]",
3550 "$_[0]_${a}", "${a}_$_[0]") {
3551 local @vu = &can_user_login(
3552 $p, $_[1]+1, $_[2]);
3553 return @vu if ($vu[1]);
3559 # Check if the user entered a domain at the end of his username when
3560 # he really shouldn't have, and if so try without it
3561 if (!@uinfo && $config{'domainstrip'} &&
3562 $_[0] =~ /^(\S+)\@(\S+)$/ && ($_[1]&2) == 0) {
3563 local ($stripped, $dom) = ($1, $2);
3564 local @vu = &can_user_login($stripped, $_[1] + 2, $_[2]);
3565 return @vu if ($vu[1]);
3566 local @vu = &can_user_login($stripped, $_[1] + 2, $dom);
3567 return @vu if ($vu[1]);
3570 return ( undef, 0, 1, undef ) if (!@uinfo && !$pamany);
3573 if (scalar(@allowusers)) {
3574 # Only allow people on the allow list
3575 return ( undef, 0, 0, undef )
3576 if (!&users_match(\@uinfo, @allowusers));
3578 elsif (scalar(@denyusers)) {
3579 # Disallow people on the deny list
3580 return ( undef, 0, 0, undef )
3581 if (&users_match(\@uinfo, @denyusers));
3583 if ($config{'shells_deny'}) {
3585 open(SHELLS, $config{'shells_deny'});
3589 $found++ if ($_ eq $uinfo[8]);
3592 return ( undef, 0, 0, undef ) if (!$found);
3597 # PAM or passwd file authentication
3598 print DEBUG "can_user_login: Validate with PAM\n";
3599 return ( $_[0], $use_pam ? 2 : 3, 0, $realuser, $sudo );
3601 elsif ($up eq 'e') {
3602 # External authentication
3603 print DEBUG "can_user_login: Validate externally\n";
3604 return ( $_[0], 4, 0, $realuser, $sudo );
3607 # Fixed Webmin password
3608 print DEBUG "can_user_login: Validate by Webmin\n";
3609 return ( $_[0], 1, 0, $realuser, $sudo );
3612 elsif ($uinfo->{'pass'} eq 'x') {
3613 # Webmin user authenticated via PAM or password file
3614 return ( $_[0], $use_pam ? 2 : 3, 0, $_[0] );
3616 elsif ($uinfo->{'pass'} eq 'e') {
3617 # Webmin user authenticated externally
3618 return ( $_[0], 4, 0, $_[0] );
3621 # Normal Webmin user
3622 return ( $_[0], 1, 0, $_[0] );
3626 # the PAM conversation function for interactive logins
3629 $pam_conv_func_called++;
3636 $ans = $pam_username if ($code == PAM_PROMPT_ECHO_ON() );
3637 $ans = $pam_password if ($code == PAM_PROMPT_ECHO_OFF() );
3639 push @res, PAM_SUCCESS();
3642 push @res, PAM_SUCCESS();
3651 # get_socket_ip(handle, ipv6-flag)
3652 # Returns the local IP address of some connection, as both a string and in
3656 local ($fh, $ipv6) = @_;
3657 local $sn = getsockname($fh);
3658 return undef if (!$sn);
3659 return &get_address_ip($sn, $ipv6);
3662 # get_address_ip(address, ipv6-flag)
3663 # Given a sockaddr object in binary format, return the binary address, text
3664 # address and port number
3667 local ($sn, $ipv6) = @_;
3669 local ($p, $b) = unpack_sockaddr_in6($sn);
3670 return ($b, inet_ntop(Socket6::AF_INET6(), $b), $p);
3673 local ($p, $b) = unpack_sockaddr_in($sn);
3674 return ($b, inet_ntoa($b), $p);
3678 # get_socket_name(handle, ipv6-flag)
3679 # Returns the local hostname or IP address of some connection
3682 local ($fh, $ipv6) = @_;
3683 return $config{'host'} if ($config{'host'});
3684 local ($mybin, $myaddr) = &get_socket_ip($fh, $ipv6);
3685 if (!$get_socket_name_cache{$myaddr}) {
3687 if (!$config{'no_resolv_myname'}) {
3688 $myname = gethostbyaddr($mybin,
3689 $ipv6 ? Socket6::AF_INET6() : AF_INET);
3691 $myname ||= $myaddr;
3692 $get_socket_name_cache{$myaddr} = $myname;
3694 return $get_socket_name_cache{$myaddr};
3697 # run_login_script(username, sid, remoteip, localip)
3698 sub run_login_script
3700 if ($config{'login_script'}) {
3701 system($config{'login_script'}.
3702 " ".join(" ", map { quotemeta($_) || '""' } @_).
3703 " >/dev/null 2>&1 </dev/null");
3707 # run_logout_script(username, sid, remoteip, localip)
3708 sub run_logout_script
3710 if ($config{'logout_script'}) {
3711 system($config{'logout_script'}.
3712 " ".join(" ", map { quotemeta($_) || '""' } @_).
3713 " >/dev/null 2>&1 </dev/null");
3717 # close_all_sockets()
3718 # Closes all the main listening sockets
3719 sub close_all_sockets
3722 foreach $s (@socketfhs) {
3728 # Close all pipes for talking to sub-processes
3732 foreach $p (@passin) { close($p); }
3733 foreach $p (@passout) { close($p); }
3734 foreach $p (values %conversations) {
3735 if ($p->{'PAMOUTr'}) {
3736 close($p->{'PAMOUTr'});
3737 close($p->{'PAMINw'});
3742 # check_user_ip(user)
3743 # Returns 1 if some user is allowed to login from the accepting IP, 0 if not
3746 local ($username) = @_;
3747 local $uinfo = &get_user_details($username);
3748 return 1 if (!$uinfo);
3749 if ($uinfo->{'deny'} &&
3750 &ip_match($acptip, $localip, @{$uinfo->{'deny'}}) ||
3751 $uinfo->{'allow'} &&
3752 !&ip_match($acptip, $localip, @{$uinfo->{'allow'}})) {
3758 # check_user_time(user)
3759 # Returns 1 if some user is allowed to login at the current date and time
3762 local ($username) = @_;
3763 local $uinfo = &get_user_details($username);
3764 return 1 if (!$uinfo || !$uinfo->{'allowdays'} && !$uinfo->{'allowhours'});
3765 local @tm = localtime(time());
3766 if ($uinfo->{'allowdays'}) {
3767 # Make sure day is allowed
3768 return 0 if (&indexof($tm[6], @{$uinfo->{'allowdays'}}) < 0);
3770 if ($uinfo->{'allowhours'}) {
3771 # Make sure time is allowed
3772 local $m = $tm[2]*60+$tm[1];
3773 return 0 if ($m < $uinfo->{'allowhours'}->[0] ||
3774 $m > $uinfo->{'allowhours'}->[1]);
3779 # generate_random_id(password, [force-urandom])
3780 # Returns a random session ID number
3781 sub generate_random_id
3783 local ($pass, $force_urandom) = @_;
3785 if (!$bad_urandom) {
3786 # First try /dev/urandom, unless we have marked it as bad
3787 $SIG{ALRM} = "miniserv::urandom_timeout";
3789 if (open(RANDOM, "/dev/urandom")) {
3791 if (read(RANDOM, $tmpsid, 16) == 16) {
3792 $sid = lc(unpack('h*',$tmpsid));
3798 if (!$sid && !$force_urandom) {
3801 foreach $c (split(//, &unix_crypt($pass, substr($$, -2)))) {
3802 $sid += ord($c) * $mul;
3809 # handle_login(username, ok, expired, not-exists, password, [no-test-cookie])
3810 # Called from handle_session to either mark a user as logged in, or not
3813 local ($vu, $ok, $expired, $nonexist, $pass, $notest) = @_;
3814 $authuser = $vu if ($ok);
3816 # check if the test cookie is set
3817 if ($header{'cookie'} !~ /testing=1/ && $vu &&
3818 !$config{'no_testing_cookie'} && !$notest) {
3819 &http_error(500, "No cookies",
3820 "Your browser does not support cookies, ".
3821 "which are required for this web server to ".
3822 "work in session authentication mode");
3825 # check with main process for delay
3826 if ($config{'passdelay'} && $vu) {
3827 print DEBUG "handle_login: requesting delay vu=$vu acptip=$acptip ok=$ok\n";
3828 print $PASSINw "delay $vu $acptip $ok\n";
3829 <$PASSOUTr> =~ /(\d+) (\d+)/;
3832 print DEBUG "handle_login: delay=$1 blocked=$2\n";
3835 if ($ok && (!$expired ||
3836 $config{'passwd_mode'} == 1)) {
3837 # Logged in OK! Tell the main process about
3839 local $sid = &generate_random_id($pass);
3840 print DEBUG "handle_login: sid=$sid\n";
3841 print $PASSINw "new $sid $authuser $acptip\n";
3843 # Run the post-login script, if any
3844 &run_login_script($authuser, $sid,
3847 # Check for a redirect URL for the user
3848 local $rurl = &login_redirect($authuser, $pass, $host);
3849 print DEBUG "handle_login: redirect URL rurl=$rurl\n";
3851 # Got one .. go to it
3852 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3853 &write_data("Date: $datestr\r\n");
3854 &write_data("Server: $config{'server'}\r\n");
3855 &write_data("Location: $rurl\r\n");
3856 &write_keep_alive(0);
3857 &write_data("\r\n");
3858 &log_request($acpthost, $authuser, $reqline, 302, 0);
3861 # Set cookie and redirect to originally requested page
3862 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3863 &write_data("Date: $datestr\r\n");
3864 &write_data("Server: $config{'server'}\r\n");
3865 local $ssl = $use_ssl || $config{'inetd_ssl'};
3866 $portstr = $port == 80 && !$ssl ? "" :
3867 $port == 443 && $ssl ? "" : ":$port";
3868 $prot = $ssl ? "https" : "http";
3869 local $sec = $ssl ? "; secure" : "";
3870 #$sec .= "; httpOnly";
3871 if ($in{'page'} !~ /^\/[A-Za-z0-9\/\.\-\_]+$/) {
3872 # Make redirect URL safe
3876 &write_data("Set-Cookie: $sidname=$sid; path=/; expires=\"Thu, 31-Dec-2037 00:00:00\"$sec\r\n");
3879 &write_data("Set-Cookie: $sidname=$sid; path=/$sec\r\n");
3881 &write_data("Location: $prot://$host$portstr$in{'page'}\r\n");
3882 &write_keep_alive(0);
3883 &write_data("\r\n");
3884 &log_request($acpthost, $authuser, $reqline, 302, 0);
3885 syslog("info", "%s", "Successful login as $authuser from $acpthost") if ($use_syslog);
3886 &write_login_utmp($authuser, $acpthost);
3890 elsif ($ok && $expired &&
3891 ($config{'passwd_mode'} == 2 || $expired == 2)) {
3892 # Login was ok, but password has expired or was temporary. Need
3893 # to force display of password change form.
3896 $querystring = "&user=".&urlize($vu).
3898 "&expired=".$expired;
3901 $page = $config{'password_form'};
3903 $miniserv_internal = 2;
3904 syslog("crit", "%s",
3905 "Expired login as $vu ".
3906 "from $acpthost") if ($use_syslog);
3909 # Login failed, or password has expired. The login form will be
3910 # displayed again by later code
3912 $request_uri = $in{'page'};
3913 $already_session_id = undef;
3915 $authuser = $baseauthuser = undef;
3916 syslog("crit", "%s",
3917 ($nonexist ? "Non-existent" :
3918 $expired ? "Expired" : "Invalid").
3919 " login as $vu from $acpthost")
3925 # write_login_utmp(user, host)
3926 # Record the login by some user in utmp
3927 sub write_login_utmp
3930 # Write utmp record for login
3931 %utmp = ( 'ut_host' => $_[1],
3932 'ut_time' => time(),
3934 'ut_type' => 7, # user process
3935 'ut_pid' => $main_process_id,
3936 'ut_line' => $config{'pam'},
3938 if (defined(&User::Utmp::putut)) {
3939 User::Utmp::putut(\%utmp);
3942 User::Utmp::pututline(\%utmp);
3947 # write_logout_utmp(user, host)
3948 # Record the logout by some user in utmp
3949 sub write_logout_utmp
3952 # Write utmp record for logout
3953 %utmp = ( 'ut_host' => $_[1],
3954 'ut_time' => time(),
3956 'ut_type' => 8, # dead process
3957 'ut_pid' => $main_process_id,
3958 'ut_line' => $config{'pam'},
3960 if (defined(&User::Utmp::putut)) {
3961 User::Utmp::putut(\%utmp);
3964 User::Utmp::pututline(\%utmp);
3969 # pam_conversation_process(username, write-pipe, read-pipe)
3970 # This function is called inside a sub-process to communicate with PAM. It sends
3971 # questions down one pipe, and reads responses from another
3972 sub pam_conversation_process
3974 local ($user, $writer, $reader) = @_;
3975 $miniserv::pam_conversation_process_writer = $writer;
3976 $miniserv::pam_conversation_process_reader = $reader;
3977 eval "use Authen::PAM;";
3978 local $convh = new Authen::PAM(
3979 $config{'pam'}, $user, \&miniserv::pam_conversation_process_func);
3980 local $pam_ret = $convh->pam_authenticate();
3981 if ($pam_ret == PAM_SUCCESS()) {
3982 local $acct_ret = $convh->pam_acct_mgmt();
3983 if ($acct_ret == PAM_SUCCESS()) {
3984 $convh->pam_open_session();
3985 print $writer "x2 $user 1 0 0\n";
3987 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3988 $acct_ret == PAM_ACCT_EXPIRED()) {
3989 print $writer "x2 $user 1 1 0\n";
3992 print $writer "x0 Unknown PAM account status $acct_ret\n";
3996 print $writer "x2 $user 0 0 0\n";
4001 # pam_conversation_process_func(type, message, [type, message, ...])
4002 # A pipe that talks to both PAM and the master process
4003 sub pam_conversation_process_func
4006 select($miniserv::pam_conversation_process_writer); $| = 1; select(STDOUT);
4008 local ($type, $msg) = (shift, shift);
4010 local $ok = (print $miniserv::pam_conversation_process_writer "$type $msg\n");
4011 print $miniserv::pam_conversation_process_writer "\n";
4012 local $answer = <$miniserv::pam_conversation_process_reader>;
4013 $answer =~ s/\r|\n//g;
4014 push(@rv, PAM_SUCCESS(), $answer);
4016 push(@rv, PAM_SUCCESS());
4021 # Returns 4 new pipe file handles
4024 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
4026 local %taken = ( (map { $_, 1 } @passin),
4027 (map { $_->{'PASSINr'} } values %conversations) );
4028 for($p=0; $taken{"PASSINr$p"}; $p++) { }
4029 $PASSINr = "PASSINr$p";
4030 $PASSINw = "PASSINw$p";
4031 $PASSOUTr = "PASSOUTr$p";
4032 $PASSOUTw = "PASSOUTw$p";
4033 pipe($PASSINr, $PASSINw);
4034 pipe($PASSOUTr, $PASSOUTw);
4035 select($PASSINw); $| = 1;
4036 select($PASSINr); $| = 1;
4037 select($PASSOUTw); $| = 1;
4038 select($PASSOUTw); $| = 1;
4040 return ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
4043 # recv_pam_question(&conv, fd)
4044 # Reads one PAM question from the sub-process, and sends it to the HTTP handler.
4045 # Returns 0 if the conversation is over, 1 if not.
4046 sub recv_pam_question
4048 local ($conf, $fh) = @_;
4049 local $pr = $conf->{'PAMOUTr'};
4050 select($pr); $| = 1; select(STDOUT);
4051 local $line = <$pr>;
4052 $line =~ s/\r|\n//g;
4055 $line =~ s/\r|\n//g;
4057 $conf->{'last'} = time();
4060 print $fh "0 PAM conversation error\n";
4064 local ($type, $msg) = split(/\s+/, $line, 2);
4065 if ($type =~ /^x(\d+)/) {
4066 # Pass this status code through
4067 print $fh "$1 $msg\n";
4068 return $1 == 2 || $1 == 0 ? 0 : 1;
4070 elsif ($type == PAM_PROMPT_ECHO_ON()) {
4072 print $fh "1 $msg\n";
4075 elsif ($type == PAM_PROMPT_ECHO_OFF()) {
4077 print $fh "3 $msg\n";
4080 elsif ($type == PAM_ERROR_MSG() || $type == PAM_TEXT_INFO()) {
4081 # A message that does not require a response
4082 print $fh "4 $msg\n";
4087 print $fh "0 Unknown PAM message type $type\n";
4093 # send_pam_answer(&conv, answer)
4094 # Sends a response from the user to the PAM sub-process
4097 local ($conf, $answer) = @_;
4098 local $pw = $conf->{'PAMINw'};
4099 $conf->{'last'} = time();
4100 print $pw "$answer\n";
4103 # end_pam_conversation(&conv)
4104 # Clean up PAM conversation pipes and processes
4105 sub end_pam_conversation
4108 kill('KILL', $conv->{'pid'}) if ($conv->{'pid'});
4109 if ($conv->{'PAMINr'}) {
4110 close($conv->{'PAMINr'});
4111 close($conv->{'PAMOUTr'});
4112 close($conv->{'PAMINw'});
4113 close($conv->{'PAMOUTw'});
4115 delete($conversations{$conv->{'cid'}});
4118 # get_ipkeys(&miniserv)
4119 # Returns a list of IP address to key file mappings from a miniserv.conf entry
4123 foreach $k (keys %{$_[0]}) {
4124 if ($k =~ /^ipkey_(\S+)/) {
4125 local $ipkey = { 'ips' => [ split(/,/, $1) ],
4126 'key' => $_[0]->{$k},
4127 'index' => scalar(@rv) };
4128 $ipkey->{'cert'} = $_[0]->{'ipcert_'.$1};
4135 # create_ssl_context(keyfile, [certfile])
4136 sub create_ssl_context
4138 local ($keyfile, $certfile) = @_;
4140 eval { $ssl_ctx = Net::SSLeay::new_x_ctx() };
4141 $ssl_ctx ||= Net::SSLeay::CTX_new();
4142 $ssl_ctx || die "Failed to create SSL context : $!";
4143 if ($client_certs) {
4144 Net::SSLeay::CTX_load_verify_locations(
4145 $ssl_ctx, $config{'ca'}, "");
4146 Net::SSLeay::CTX_set_verify(
4147 $ssl_ctx, &Net::SSLeay::VERIFY_PEER, \&verify_client);
4149 if ($config{'extracas'}) {
4151 foreach $p (split(/\s+/, $config{'extracas'})) {
4152 Net::SSLeay::CTX_load_verify_locations(
4157 Net::SSLeay::CTX_use_RSAPrivateKey_file(
4159 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL key $keyfile";
4160 Net::SSLeay::CTX_use_certificate_file(
4161 $ssl_ctx, $certfile || $keyfile,
4162 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL cert $certfile";
4167 # ssl_connection_for_ip(socket, ipv6-flag)
4168 # Returns a new SSL connection object for some socket, or undef if failed
4169 sub ssl_connection_for_ip
4171 local ($sock, $ipv6) = @_;
4172 local $sn = getsockname($sock);
4174 print STDERR "Failed to get address for socket $sock\n";
4177 local (undef, $myip, undef) = &get_address_ip($sn, $ipv6);
4178 local $ssl_ctx = $ssl_contexts{$myip} || $ssl_contexts{"*"};
4179 local $ssl_con = Net::SSLeay::new($ssl_ctx);
4180 if ($config{'ssl_cipher_list'}) {
4181 # Force use of ciphers
4182 eval "Net::SSLeay::set_cipher_list(
4183 \$ssl_con, \$config{'ssl_cipher_list'})";
4185 print STDERR "SSL cipher $config{'ssl_cipher_list'} failed : ",
4191 Net::SSLeay::set_fd($ssl_con, fileno($sock));
4192 if (!Net::SSLeay::accept($ssl_con)) {
4193 print STDERR "Failed to initialize SSL connection\n";
4199 # login_redirect(username, password, host)
4200 # Calls the login redirect script (if configured), which may output a URL to
4201 # re-direct a user to after logging in.
4204 return undef if (!$config{'login_redirect'});
4205 local $quser = quotemeta($_[0]);
4206 local $qpass = quotemeta($_[1]);
4207 local $qhost = quotemeta($_[2]);
4208 local $url = `$config{'login_redirect'} $quser $qpass $qhost`;
4213 # reload_config_file()
4214 # Re-read %config, and call post-config actions
4215 sub reload_config_file
4217 &log_error("Reloading configuration");
4218 %config = &read_config_file($config_file);
4219 &update_vital_config();
4222 &build_config_mappings();
4223 &read_webmin_crons();
4225 if ($config{'session'}) {
4226 dbmclose(%sessiondb);
4227 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
4231 # read_config_file(file)
4232 # Reads the given config file, and returns a hash of values
4233 sub read_config_file
4236 open(CONF, $_[0]) || die "Failed to open config file $_[0] : $!";
4239 if (/^#/ || !/\S/) { next; }
4241 $name = $1; $val = $2;
4242 $name =~ s/^\s+//g; $name =~ s/\s+$//g;
4243 $val =~ s/^\s+//g; $val =~ s/\s+$//g;
4250 # update_vital_config()
4251 # Updates %config with defaults, and dies if something vital is missing
4252 sub update_vital_config
4254 my %vital = ("port", 80,
4256 "server", "MiniServ/0.01",
4257 "index_docs", "index.html index.htm index.cgi index.php",
4258 "addtype_html", "text/html",
4259 "addtype_txt", "text/plain",
4260 "addtype_gif", "image/gif",
4261 "addtype_jpg", "image/jpeg",
4262 "addtype_jpeg", "image/jpeg",
4263 "realm", "MiniServ",
4264 "session_login", "/session_login.cgi",
4265 "pam_login", "/pam_login.cgi",
4266 "password_form", "/password_form.cgi",
4267 "password_change", "/password_change.cgi",
4271 "unauth", "^/unauthenticated/ ^/robots.txt\$ ^[A-Za-z0-9\\-/_]+\\.jar\$ ^[A-Za-z0-9\\-/_]+\\.class\$ ^[A-Za-z0-9\\-/_]+\\.gif\$ ^[A-Za-z0-9\\-/_]+\\.png\$ ^[A-Za-z0-9\\-/_]+\\.conf\$ ^[A-Za-z0-9\\-/_]+\\.ico\$ ^/robots.txt\$",
4273 "expires", 7*24*60*60,
4274 "pam_test_user", "root",
4275 "precache", "lang/en */lang/en",
4277 foreach my $v (keys %vital) {
4279 if ($vital{$v} eq "") {
4280 die "Missing config option $v";
4282 $config{$v} = $vital{$v};
4285 if (!$config{'sessiondb'}) {
4286 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4287 $config{'sessiondb'} = "$1/sessiondb";
4289 if (!$config{'errorlog'}) {
4290 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
4291 $config{'errorlog'} = "$1/miniserv.error";
4293 if (!$config{'tempbase'}) {
4294 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4295 $config{'tempbase'} = "$1/cgitemp";
4297 if (!$config{'blockedfile'}) {
4298 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4299 $config{'blockedfile'} = "$1/blocked";
4301 if (!$config{'webmincron_dir'}) {
4302 $config_file =~ /^(.*)\/[^\/]+$/;
4303 $config{'webmincron_dir'} = "$1/webmincron/crons";
4305 if (!$config{'webmincron_last'}) {
4306 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
4307 $config{'webmincron_last'} = "$1/miniserv.lastcrons";
4309 if (!$config{'webmincron_wrapper'}) {
4310 $config{'webmincron_wrapper'} = $config{'root'}.
4311 "/webmincron/webmincron.pl";
4316 # Fills the %users and %certs hashes from the users file in %config
4325 undef(%lastchanges);
4328 if ($config{'userfile'}) {
4329 open(USERS, $config{'userfile'});
4332 local @user = split(/:/, $_, -1);
4333 $users{$user[0]} = $user[1];
4334 $certs{$user[0]} = $user[3] if ($user[3]);
4335 if ($user[4] =~ /^allow\s+(.*)/) {
4336 $allow{$user[0]} = $config{'alwaysresolve'} ?
4337 [ split(/\s+/, $1) ] :
4338 [ &to_ipaddress(split(/\s+/, $1)) ];
4340 elsif ($user[4] =~ /^deny\s+(.*)/) {
4341 $deny{$user[0]} = $config{'alwaysresolve'} ?
4342 [ split(/\s+/, $1) ] :
4343 [ &to_ipaddress(split(/\s+/, $1)) ];
4345 if ($user[5] =~ /days\s+(\S+)/) {
4346 $allowdays{$user[0]} = [ split(/,/, $1) ];
4348 if ($user[5] =~ /hours\s+(\d+)\.(\d+)-(\d+).(\d+)/) {
4349 $allowhours{$user[0]} = [ $1*60+$2, $3*60+$4 ];
4351 $lastchanges{$user[0]} = $user[6];
4352 $nochange{$user[0]} = $user[9];
4353 $temppass{$user[0]} = $user[10];
4358 # Test user DB, if configured
4359 if ($config{'userdb'}) {
4360 my $dbh = &connect_userdb($config{'userdb'});
4362 print STDERR "Failed to open users database : $dbh\n"
4365 &disconnect_userdb($config{'userdb'}, $dbh);
4370 # get_user_details(username)
4371 # Returns a hash ref of user details, either from config files or the user DB
4372 sub get_user_details
4374 my ($username) = @_;
4375 if (exists($users{$username})) {
4377 return { 'name' => $username,
4378 'pass' => $users{$username},
4379 'certs' => $certs{$username},
4380 'allow' => $allow{$username},
4381 'deny' => $deny{$username},
4382 'allowdays' => $allowdays{$username},
4383 'allowhours' => $allowhours{$username},
4384 'lastchanges' => $lastchanges{$username},
4385 'nochange' => $nochange{$username},
4386 'temppass' => $temppass{$username},
4387 'preroot' => $config{'preroot_'.$username},
4390 if ($config{'userdb'}) {
4391 # Try querying user database
4392 if (exists($get_user_details_cache{$username})) {
4394 return $get_user_details_cache{$username};
4396 print DEBUG "get_user_details: Connecting to user database\n";
4397 my ($dbh, $proto, $prefix, $args) = &connect_userdb($config{'userdb'});
4401 print DEBUG "get_user_details: Failed : $dbh\n";
4402 print STDERR "Failed to connect to user database : $dbh\n";
4404 elsif ($proto eq "mysql" || $proto eq "postgresql") {
4405 # Fetch user ID and password with SQL
4406 print DEBUG "get_user_details: Looking for $username in SQL\n";
4407 my $cmd = $dbh->prepare(
4408 "select id,pass from webmin_user where name = ?");
4409 if (!$cmd || !$cmd->execute($username)) {
4410 print STDERR "Failed to lookup user : ",
4414 my ($id, $pass) = $cmd->fetchrow();
4417 &disconnect_userdb($config{'userdb'}, $dbh);
4418 $get_user_details_cache{$username} = undef;
4419 print DEBUG "get_user_details: User not found\n";
4422 print DEBUG "get_user_details: id=$id pass=$pass\n";
4424 # Fetch attributes and add to user object
4425 print DEBUG "get_user_details: finding user attributes\n";
4426 my $cmd = $dbh->prepare(
4427 "select attr,value from webmin_user_attr where id = ?");
4428 if (!$cmd || !$cmd->execute($id)) {
4429 print STDERR "Failed to lookup user attrs : ",
4433 $user = { 'name' => $username,
4436 'proto' => $proto };
4437 while(my ($attr, $value) = $cmd->fetchrow()) {
4438 $attrs{$attr} = $value;
4442 elsif ($proto eq "ldap") {
4443 # Fetch user DN with LDAP
4444 print DEBUG "get_user_details: Looking for $username in LDAP\n";
4445 my $rv = $dbh->search(
4447 filter => '(&(cn='.$username.')(objectClass='.
4448 $args->{'userclass'}.'))',
4450 if (!$rv || $rv->code) {
4451 print STDERR "Failed to lookup user : ",
4452 ($rv ? $rv->error : "Unknown error"),"\n";
4455 my ($u) = $rv->all_entries();
4457 &disconnect_userdb($config{'userdb'}, $dbh);
4458 $get_user_details_cache{$username} = undef;
4459 print DEBUG "get_user_details: User not found\n";
4463 # Extract attributes
4464 my $pass = $u->get_value('webminPass');
4465 $user = { 'name' => $username,
4468 'proto' => $proto };
4469 foreach my $la ($u->get_value('webminAttr')) {
4470 my ($attr, $value) = split(/=/, $la, 2);
4471 $attrs{$attr} = $value;
4475 # Convert DB attributes into user object fields
4477 print DEBUG "get_user_details: got ",scalar(keys %attrs),
4479 $user->{'certs'} = $attrs{'cert'};
4480 if ($attrs{'allow'}) {
4481 $user->{'allow'} = $config{'alwaysresolve'} ?
4482 [ split(/\s+/, $attrs{'allow'}) ] :
4483 [ &to_ipaddress(split(/\s+/,$attrs{'allow'})) ];
4485 if ($attrs{'deny'}) {
4486 $user->{'deny'} = $config{'alwaysresolve'} ?
4487 [ split(/\s+/, $attrs{'deny'}) ] :
4488 [ &to_ipaddress(split(/\s+/,$attrs{'deny'})) ];
4490 if ($attrs{'days'}) {
4491 $user->{'allowdays'} = [ split(/,/, $attrs{'days'}) ];
4493 if ($attrs{'hoursfrom'} && $attrs{'hoursto'}) {
4494 my ($hf, $mf) = split(/\./, $attrs{'hoursfrom'});
4495 my ($ht, $mt) = split(/\./, $attrs{'hoursto'});
4496 $user->{'allowhours'} = [ $hf*60+$ht, $ht*60+$mt ];
4498 $user->{'lastchanges'} = $attrs{'lastchange'};
4499 $user->{'nochange'} = $attrs{'nochange'};
4500 $user->{'temppass'} = $attrs{'temppass'};
4501 $user->{'preroot'} = $attrs{'theme'};
4503 &disconnect_userdb($config{'userdb'}, $dbh);
4504 $get_user_details_cache{$user->{'name'}} = $user;
4510 # find_user_by_cert(cert)
4511 # Returns a username looked up by certificate
4512 sub find_user_by_cert
4514 my ($peername) = @_;
4515 my $peername2 = $peername;
4516 $peername2 =~ s/Email=/emailAddress=/ || $peername2 =~ s/emailAddress=/Email=/;
4518 # First check users in local files
4519 foreach my $username (keys %certs) {
4520 if ($certs{$username} eq $peername ||
4521 $certs{$username} eq $peername2) {
4527 if ($config{'userdb'}) {
4528 my ($dbh, $proto) = &connect_userdb($config{'userdb'});
4532 elsif ($proto eq "mysql" || $proto eq "postgresql") {
4534 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 = ?");
4535 return undef if (!$cmd);
4536 foreach my $p ($peername, $peername2) {
4538 if ($cmd->execute($p)) {
4539 ($username) = $cmd->fetchrow();
4542 return $username if ($username);
4545 elsif ($proto eq "ldap") {
4547 my $rv = $dbh->search(
4549 filter => '(objectClass='.
4550 $args->{'userclass'}.')',
4552 attrs => [ 'cn', 'webminAttr' ]);
4553 if ($rv && !$rv->code) {
4554 foreach my $u ($rv->all_entries) {
4555 my @attrs = $u->get_value('webminAttr');
4556 foreach my $la (@attrs) {
4557 my ($attr, $value) = split(/=/, $la, 2);
4558 if ($attr eq "cert" &&
4559 ($value eq $peername ||
4560 $value eq $peername2)) {
4561 return $u->get_value('cn');
4571 # connect_userdb(string)
4572 # Returns a handle for talking to a user database - may be a DBI or LDAP handle.
4573 # On failure returns an error message string. In an array context, returns the
4574 # protocol type too.
4578 my ($proto, $user, $pass, $host, $prefix, $args) = &split_userdb_string($str);
4579 if ($proto eq "mysql") {
4580 # Connect to MySQL with DBI
4581 my $drh = eval "use DBI; DBI->install_driver('mysql');";
4582 $drh || return $text{'sql_emysqldriver'};
4583 my ($host, $port) = split(/:/, $host);
4584 my $cstr = "database=$prefix;host=$host";
4585 $cstr .= ";port=$port" if ($port);
4586 print DEBUG "connect_userdb: Connecting to MySQL $cstr as $user\n";
4587 my $dbh = $drh->connect($cstr, $user, $pass, { });
4588 $dbh || return &text('sql_emysqlconnect', $drh->errstr);
4589 print DEBUG "connect_userdb: Connected OK\n";
4590 return wantarray ? ($dbh, $proto, $prefix, $args) : $dbh;
4592 elsif ($proto eq "postgresql") {
4593 # Connect to PostgreSQL with DBI
4594 my $drh = eval "use DBI; DBI->install_driver('Pg');";
4595 $drh || return $text{'sql_epostgresqldriver'};
4596 my ($host, $port) = split(/:/, $host);
4597 my $cstr = "dbname=$prefix;host=$host";
4598 $cstr .= ";port=$port" if ($port);
4599 print DEBUG "connect_userdb: Connecting to PostgreSQL $cstr as $user\n";
4600 my $dbh = $drh->connect($cstr, $user, $pass);
4601 $dbh || return &text('sql_epostgresqlconnect', $drh->errstr);
4602 print DEBUG "connect_userdb: Connected OK\n";
4603 return wantarray ? ($dbh, $proto, $prefix, $args) : $dbh;
4605 elsif ($proto eq "ldap") {
4606 # Connect with perl LDAP module
4607 eval "use Net::LDAP";
4608 $@ && return $text{'sql_eldapdriver'};
4609 my ($host, $port) = split(/:/, $host);
4610 my $scheme = $args->{'scheme'} || 'ldap';
4612 $port = $scheme eq 'ldaps' ? 636 : 389;
4614 my $ldap = Net::LDAP->new($host,
4616 'scheme' => $scheme);
4617 $ldap || return &text('sql_eldapconnect', $host);
4619 if ($args->{'tls'}) {
4620 # Switch to TLS mode
4621 eval { $mesg = $ldap->start_tls(); };
4622 if ($@ || !$mesg || $mesg->code) {
4623 return &text('sql_eldaptls',
4624 $@ ? $@ : $mesg ? $mesg->error : "Unknown error");
4627 # Login to the server
4629 $mesg = $ldap->bind(dn => $user, password => $pass);
4632 $mesg = $ldap->bind(dn => $user, anonymous => 1);
4634 if (!$mesg || $mesg->code) {
4635 return &text('sql_eldaplogin', $user,
4636 $mesg ? $mesg->error : "Unknown error");
4638 return wantarray ? ($ldap, $proto, $prefix, $args) : $ldap;
4641 return "Unknown protocol $proto";
4645 # split_userdb_string(string)
4646 # Converts a string like mysql://user:pass@host/db into separate parts
4647 sub split_userdb_string
4650 if ($str =~ /^([a-z]+):\/\/([^:]*):([^\@]*)\@([a-z0-9\.\-\_]+)\/([^\?]+)(\?(.*))?$/) {
4651 my ($proto, $user, $pass, $host, $prefix, $argstr) =
4652 ($1, $2, $3, $4, $5, $7);
4653 my %args = map { split(/=/, $_, 2) } split(/\&/, $argstr);
4654 return ($proto, $user, $pass, $host, $prefix, \%args);
4659 # disconnect_userdb(string, &handle)
4660 # Closes a handle opened by connect_userdb
4661 sub disconnect_userdb
4664 if ($str =~ /^(mysql|postgresql):/) {
4668 elsif ($str =~ /^ldap:/) {
4675 # Fills %mime with entries from file in %config and extra settings in %config
4679 if ($config{"mimetypes"} ne "") {
4680 open(MIME, $config{"mimetypes"});
4683 if (/^(\S+)\s+(.*)$/) {
4685 my @exts = split(/\s+/, $2);
4686 foreach my $ext (@exts) {
4687 $mime{$ext} = $type;
4693 foreach my $k (keys %config) {
4694 if ($k !~ /^addtype_(.*)$/) { next; }
4695 $mime{$1} = $config{$k};
4699 # build_config_mappings()
4700 # Build the anonymous access list, IP access list, unauthenticated URLs list,
4701 # redirect mapping and allow and deny lists from %config
4702 sub build_config_mappings
4704 # build anonymous access list
4706 foreach my $a (split(/\s+/, $config{'anonymous'})) {
4707 if ($a =~ /^([^=]+)=(\S+)$/) {
4708 $anonymous{$1} = $2;
4712 # build IP access list
4714 foreach my $a (split(/\s+/, $config{'ipaccess'})) {
4715 if ($a =~ /^([^=]+)=(\S+)$/) {
4720 # build unauthenticated URLs list
4721 @unauth = split(/\s+/, $config{'unauth'});
4723 # build redirect mapping
4725 foreach my $r (split(/\s+/, $config{'redirect'})) {
4726 if ($r =~ /^([^=]+)=(\S+)$/) {
4731 # build prefixes to be stripped
4732 undef(@strip_prefix);
4733 foreach my $r (split(/\s+/, $config{'strip_prefix'})) {
4734 push(@strip_prefix, $r);
4737 # Init allow and deny lists
4738 @deny = split(/\s+/, $config{"deny"});
4739 @deny = &to_ipaddress(@deny) if (!$config{'alwaysresolve'});
4740 @allow = split(/\s+/, $config{"allow"});
4741 @allow = &to_ipaddress(@allow) if (!$config{'alwaysresolve'});
4744 if ($config{'allowusers'}) {
4745 @allowusers = split(/\s+/, $config{'allowusers'});
4747 elsif ($config{'denyusers'}) {
4748 @denyusers = split(/\s+/, $config{'denyusers'});
4751 # Build list of unixauth mappings
4753 foreach my $ua (split(/\s+/, $config{'unixauth'})) {
4754 if ($ua =~ /^(\S+)=(\S+)$/) {
4758 $unixauth{"*"} = $ua;
4762 # Build list of non-session-auth pages
4763 undef(%sessiononly);
4764 foreach my $sp (split(/\s+/, $config{'sessiononly'})) {
4765 $sessiononly{$sp} = 1;
4768 # Build list of logout times
4769 undef(@logouttimes);
4770 foreach my $a (split(/\s+/, $config{'logouttimes'})) {
4771 if ($a =~ /^([^=]+)=(\S+)$/) {
4772 push(@logouttimes, [ $1, $2 ]);
4775 push(@logouttimes, [ undef, $config{'logouttime'} ]);
4777 # Build list of DAV pathss
4779 foreach my $d (split(/\s+/, $config{'davpaths'})) {
4780 push(@davpaths, $d);
4782 @davusers = split(/\s+/, $config{'dav_users'});
4784 # Mobile agent substrings and hostname prefixes
4785 @mobile_agents = split(/\t+/, $config{'mobile_agents'});
4786 @mobile_prefixes = split(/\s+/, $config{'mobile_prefixes'});
4789 @expires_paths = ( );
4790 foreach my $pe (split(/\t+/, $config{'expires_paths'})) {
4791 my ($p, $e) = split(/=/, $pe);
4792 if ($p && $e ne '') {
4793 push(@expires_paths, [ $p, $e ]);
4799 if ($config{'debug'}) {
4800 open(DEBUG, ">>$config{'debug'}");
4803 open(DEBUG, ">/dev/null");
4806 # Reset cache of sudo checks
4810 # is_group_member(&uinfo, groupname)
4811 # Returns 1 if some user is a primary or secondary member of a group
4814 local ($uinfo, $group) = @_;
4815 local @ginfo = getgrnam($group);
4816 return 0 if (!@ginfo);
4817 return 1 if ($ginfo[2] == $uinfo->[3]); # primary member
4818 foreach my $m (split(/\s+/, $ginfo[3])) {
4819 return 1 if ($m eq $uinfo->[0]);
4824 # prefix_to_mask(prefix)
4825 # Converts a number like 24 to a mask like 255.255.255.0
4828 return $_[0] >= 24 ? "255.255.255.".(256-(2 ** (32-$_[0]))) :
4829 $_[0] >= 16 ? "255.255.".(256-(2 ** (24-$_[0]))).".0" :
4830 $_[0] >= 8 ? "255.".(256-(2 ** (16-$_[0]))).".0.0" :
4831 (256-(2 ** (8-$_[0]))).".0.0.0";
4834 # get_logout_time(user, session-id)
4835 # Given a username, returns the idle time before he will be logged out
4838 local ($user, $sid) = @_;
4839 if (!defined($logout_time_cache{$user,$sid})) {
4841 foreach my $l (@logouttimes) {
4842 if ($l->[0] =~ /^\@(.*)$/) {
4843 # Check group membership
4844 local @uinfo = getpwnam($user);
4845 if (@uinfo && &is_group_member(\@uinfo, $1)) {
4849 elsif ($l->[0] =~ /^\//) {
4850 # Check file contents
4851 open(FILE, $l->[0]);
4868 if ($l->[0] eq $user) {
4872 last if (defined($time));
4874 $logout_time_cache{$user,$sid} = $time;
4876 return $logout_time_cache{$user,$sid};
4879 # password_crypt(password, salt)
4880 # If the salt looks like MD5 and we have a library for it, perform MD5 hashing
4881 # of a password. Otherwise, do Unix crypt.
4884 local ($pass, $salt) = @_;
4885 if ($salt =~ /^\$1\$/ && $use_md5) {
4886 return &encrypt_md5($pass, $salt);
4889 return &unix_crypt($pass, $salt);
4893 # unix_crypt(password, salt)
4894 # Performs standard Unix hashing for a password
4897 local ($pass, $salt) = @_;
4898 if ($use_perl_crypt) {
4899 return Crypt::UnixCrypt::crypt($pass, $salt);
4902 return crypt($pass, $salt);
4906 # handle_dav_request(davpath)
4907 # Pass a request on to the Net::DAV::Server module
4908 sub handle_dav_request
4911 eval "use Filesys::Virtual::Plain";
4912 eval "use Net::DAV::Server";
4913 eval "use HTTP::Request";
4914 eval "use HTTP::Headers";
4916 if ($Net::DAV::Server::VERSION eq '1.28' && $config{'dav_nolock'}) {
4917 delete $Net::DAV::Server::implemented{lock};
4918 delete $Net::DAV::Server::implemented{unlock};
4921 # Read in request data
4922 if (!$posted_data) {
4923 local $clen = $header{"content-length"};
4924 while(length($posted_data) < $clen) {
4925 $buf = &read_data($clen - length($posted_data));
4926 if (!length($buf)) {
4927 &http_error(500, "Failed to read POST request");
4929 $posted_data .= $buf;
4933 # For subsequent logging
4934 open(MINISERVLOG, ">>$config{'logfile'}");
4938 local @u = getpwnam($authuser);
4939 if ($config{'dav_remoteuser'} && !$< && $validated) {
4942 $( = $u[3]; $) = "$u[3] $u[3]";
4943 ($>, $<) = ($u[2], $u[2]);
4945 if ($config{'dav_root'} eq '*') {
4950 &http_error(500, "Unix user $authuser does not exist");
4954 $root ||= $config{'dav_root'};
4957 # Check if this user can use DAV
4959 &users_match(\@u, @davusers) ||
4960 &http_error(500, "You are not allowed to access DAV");
4964 my $filesys = Filesys::Virtual::Plain->new({root_path => $root});
4965 my $webdav = Net::DAV::Server->new();
4966 $webdav->filesys($filesys);
4968 # Make up a request object, and feed to DAV
4969 local $ho = HTTP::Headers->new;
4970 foreach my $h (keys %header) {
4971 next if (lc($h) eq "connection");
4972 $ho->header($h => $header{$h});
4975 $request_uri =~ s/^\Q$path\E//;
4976 $request_uri = "/" if ($request_uri eq "");
4978 my $request = HTTP::Request->new($method, $request_uri, $ho,
4980 if ($config{'dav_debug'}) {
4981 print STDERR "DAV request :\n";
4982 print STDERR "---------------------------------------------\n";
4983 print STDERR $request->as_string();
4984 print STDERR "---------------------------------------------\n";
4986 my $response = $webdav->run($request);
4988 # Send back the reply
4989 &write_data("HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n");
4990 local $content = $response->content();
4992 $content =~ s|href>/(.+)<|href>$path/$1<|g;
4993 $content =~ s|href>/<|href>$path<|g;
4995 foreach my $h ($response->header_field_names) {
4996 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4997 &write_data("$h: ",$response->header($h),"\r\n");
4999 &write_data("Content-length: ",length($content),"\r\n");
5000 local $rv = &write_keep_alive(0);
5001 &write_data("\r\n");
5002 &write_data($content);
5004 if ($config{'dav_debug'}) {
5005 print STDERR "DAV reply :\n";
5006 print STDERR "---------------------------------------------\n";
5007 print STDERR "HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n";
5008 foreach my $h ($response->header_field_names) {
5009 next if (lc($h) eq "connection" || lc($h) eq "content-length");
5010 print STDERR "$h: ",$response->header($h),"\r\n";
5012 print STDERR "Content-length: ",length($content),"\r\n";
5013 print STDERR "\r\n";
5014 print STDERR $content;
5015 print STDERR "---------------------------------------------\n";
5019 &log_request($acpthost, $authuser, $reqline, $response->code(),
5020 length($response->content()));
5023 # get_system_hostname()
5024 # Returns the hostname of this system, for reporting to listeners
5025 sub get_system_hostname
5027 # On Windows, try computername environment variable
5028 return $ENV{'computername'} if ($ENV{'computername'});
5029 return $ENV{'COMPUTERNAME'} if ($ENV{'COMPUTERNAME'});
5031 # If a specific command is set, use it first
5032 if ($config{'hostname_command'}) {
5033 local $out = `($config{'hostname_command'}) 2>&1`;
5040 # First try the hostname command
5041 local $out = `hostname 2>&1`;
5042 if (!$? && $out =~ /\S/) {
5047 # Try the Sys::Hostname module
5048 eval "use Sys::Hostname";
5050 local $rv = eval "hostname()";
5056 # Must use net name on Windows
5057 local $out = `net name 2>&1`;
5058 if ($out =~ /\-+\r?\n(\S+)/) {
5065 # indexof(string, array)
5066 # Returns the index of some value in an array, or -1
5069 for($i=1; $i <= $#_; $i++) {
5070 if ($_[$i] eq $_[0]) { return $i - 1; }
5076 # has_command(command)
5077 # Returns the full path if some command is in the path, undef if not
5081 if (!$_[0]) { return undef; }
5082 if (exists($has_command_cache{$_[0]})) {
5083 return $has_command_cache{$_[0]};
5086 if ($_[0] =~ /^\//) {
5087 $rv = -x $_[0] ? $_[0] : undef;
5090 local $sp = $on_windows ? ';' : ':';
5091 foreach $d (split($sp, $ENV{PATH})) {
5092 if (-x "$d/$_[0]") {
5097 foreach my $sfx (".exe", ".com", ".bat") {
5098 if (-r "$d/$_[0]".$sfx) {
5099 $rv = "$d/$_[0]".$sfx;
5106 $has_command_cache{$_[0]} = $rv;
5110 # check_sudo_permissions(user, pass)
5111 # Returns 1 if some user can run any command via sudo
5112 sub check_sudo_permissions
5114 local ($user, $pass) = @_;
5116 # First try the pipes
5118 print DEBUG "check_sudo_permissions: querying cache for $user\n";
5119 print $PASSINw "readsudo $user\n";
5120 local $can = <$PASSOUTr>;
5122 print DEBUG "check_sudo_permissions: cache said $can\n";
5123 if ($can =~ /^\d+$/ && $can != 2) {
5128 local $ptyfh = new IO::Pty;
5129 print DEBUG "check_sudo_permissions: ptyfh=$ptyfh\n";
5131 print STDERR "Failed to create new PTY with IO::Pty\n";
5134 local @uinfo = getpwnam($user);
5136 print STDERR "Unix user $user does not exist for sudo\n";
5140 # Execute sudo in a sub-process, via a pty
5141 local $ttyfh = $ptyfh->slave();
5142 print DEBUG "check_sudo_permissions: ttyfh=$ttyfh\n";
5143 local $tty = $ptyfh->ttyname();
5144 print DEBUG "check_sudo_permissions: tty=$tty\n";
5145 chown($uinfo[2], $uinfo[3], $tty);
5147 print DEBUG "check_sudo_permissions: about to fork..\n";
5148 local $pid = fork();
5149 print DEBUG "check_sudo_permissions: fork=$pid pid=$$\n";
5151 print STDERR "fork for sudo failed : $!\n";
5156 $ptyfh->make_slave_controlling_terminal();
5157 close(STDIN); close(STDOUT); close(STDERR);
5158 untie(*STDIN); untie(*STDOUT); untie(*STDERR);
5159 close($PASSINw); close($PASSOUTr);
5160 $( = $uinfo[3]; $) = "$uinfo[3] $uinfo[3]";
5161 ($>, $<) = ($uinfo[2], $uinfo[2]);
5166 open(STDIN, "<&SUDOr");
5167 open(STDOUT, ">$tty");
5168 open(STDERR, ">&STDOUT");
5171 print "Exec failed : $!\n";
5174 print DEBUG "check_sudo_permissions: pid=$pid\n";
5176 $ptyfh->close_slave();
5178 # Send password, and get back response
5179 local $oldfh = select(SUDOw);
5182 print DEBUG "check_sudo_permissions: about to send pass\n";
5183 local $SIG{'PIPE'} = 'ignore'; # Sometimes sudo doesn't ask for a password
5184 print SUDOw $pass,"\n";
5185 print DEBUG "check_sudo_permissions: sent pass=$pass\n";
5189 print DEBUG "check_sudo_permissions: got $_";
5195 local ($ok) = ($out =~ /\(ALL\)\s+ALL|\(ALL\)\s+NOPASSWD:\s+ALL/ ? 1 : 0);
5199 print $PASSINw "writesudo $user $ok\n";
5205 # is_mobile_useragent(agent)
5206 # Returns 1 if some user agent looks like a cellphone or other mobile device,
5208 sub is_mobile_useragent
5210 local ($agent) = @_;
5212 "UP.Link", # Openwave
5213 "Nokia", # All Nokias start with Nokia
5214 "MOT-", # All Motorola phones start with MOT-
5215 "SAMSUNG", # Samsung browsers
5216 "Samsung", # Samsung browsers
5217 "SEC-", # Samsung browsers
5218 "AU-MIC", # Samsung browsers
5219 "AUDIOVOX", # Audiovox
5220 "BlackBerry", # BlackBerry
5221 "hiptop", # Danger hiptop Sidekick
5222 "SonyEricsson", # Sony Ericsson
5223 "Ericsson", # Old Ericsson browsers , mostly WAP
5224 "Mitsu/1.1.A", # Mitsubishi phones
5225 "Panasonic WAP", # Panasonic old WAP phones
5226 "DoCoMo", # DoCoMo phones
5227 "Lynx", # Lynx text-mode linux browser
5228 "Links", # Another text-mode linux browser
5230 local @substrings = (
5231 "UP.Browser", # Openwave
5232 "MobilePhone", # NetFront
5233 "AU-MIC-A700", # Samsung A700 Obigo browsers
5234 "Danger hiptop", # Danger Sidekick hiptop
5235 "Windows CE", # Windows CE Pocket PC
5236 "IEMobile", # Windows mobile browser
5237 "Blazer", # Palm Treo Blazer
5238 "BlackBerry", # BlackBerries can emulate other browsers, but
5239 # they still keep this string in the UserAgent
5240 "SymbianOS", # New Series60 browser has safari in it and
5241 # SymbianOS is the only distinguishing string
5242 "iPhone", # Apple iPhone KHTML browser
5243 "iPod", # iPod touch browser
5244 "MobileSafari", # HTTP client in iPhone
5246 "Opera Mini", # Opera Mini
5247 "HTC_P3700", # HTC mobile device
5249 "webOS/", # Palm WebOS
5250 "Nintendo DS", # DSi / DSi-XL
5252 foreach my $p (@prefixes) {
5253 return 1 if ($agent =~ /^\Q$p\E/);
5255 foreach my $s (@substrings, @mobile_agents) {
5256 return 1 if ($agent =~ /\Q$s\E/);
5261 # write_blocked_file()
5262 # Writes out a text file of blocked hosts and users
5263 sub write_blocked_file
5265 open(BLOCKED, ">$config{'blockedfile'}");
5266 foreach my $d (grep { $hostfail{$_} } @deny) {
5267 print BLOCKED "host $d $hostfail{$d} $blockhosttime{$d}\n";
5269 foreach my $d (grep { $userfail{$_} } @denyusers) {
5270 print BLOCKED "user $d $userfail{$d} $blockusertime{$d}\n";
5273 chmod(0700, $config{'blockedfile'});
5278 open(PIDFILE, ">$config{'pidfile'}");
5279 printf PIDFILE "%d\n", getpid();
5281 $miniserv_main_pid = getpid();
5284 # lock_user_password(user)
5285 # Updates a user's password file entry to lock it, both in memory and on disk.
5286 # Returns 1 if done, -1 if no such user, 0 if already locked
5287 sub lock_user_password
5290 local $uinfo = &get_user_details($user);
5295 if ($uinfo->{'pass'} =~ /^\!/) {
5299 if (!$uinfo->{'proto'}) {
5300 # Write to users file
5301 $users{$user} = "!".$users{$user};
5302 open(USERS, $config{'userfile'});
5303 local @ufile = <USERS>;
5305 foreach my $u (@ufile) {
5306 local @uinfo = split(/:/, $u);
5307 if ($uinfo[0] eq $user) {
5308 $uinfo[1] = $users{$user};
5310 $u = join(":", @uinfo);
5312 open(USERS, ">$config{'userfile'}");
5318 if ($config{'userdb'}) {
5320 my ($dbh, $proto, $prefix, $args) = &connect_userdb($config{'userdb'});
5324 elsif ($proto eq "mysql" || $proto eq "postgresql") {
5325 # Update user attribute
5326 my $cmd = $dbh->prepare(
5327 "update webmin_user set pass = ? where id = ?");
5328 if (!$cmd || !$cmd->execute("!".$uinfo->{'pass'},
5331 print STDERR "Failed to lock password : ",
5335 $cmd->finish() if ($cmd);
5337 elsif ($proto eq "ldap") {
5338 # Update LDAP object
5339 my $rv = $dbh->modify($uinfo->{'id'},
5340 replace => { 'webminPass' => '!'.$uinfo->{'pass'} });
5341 if (!$rv || $rv->code) {
5342 print STDERR "Failed to lock password : ",
5343 ($rv ? $rv->error : "Unknown error"),"\n";
5347 &disconnect_userdb($config{'userdb'}, $dbh);
5351 return -1; # This should never be reached
5354 # hash_session_id(sid)
5355 # Returns an MD5 or Unix-crypted session ID
5359 if (!$hash_session_id_cache{$sid}) {
5362 $hash_session_id_cache{$sid} = &encrypt_md5($sid);
5366 $hash_session_id_cache{$sid} = &unix_crypt($sid, "XX");
5369 return $hash_session_id_cache{$sid};
5372 # encrypt_md5(string, [salt])
5373 # Returns a string encrypted in MD5 format
5376 local ($passwd, $salt) = @_;
5377 local $magic = '$1$';
5378 if ($salt =~ /^\$1\$([^\$]+)/) {
5379 # Extract actual salt from already encrypted password
5384 local $ctx = eval "new $use_md5";
5391 # Add some more stuff from the hash of the password and salt
5392 local $ctx1 = eval "new $use_md5";
5393 $ctx1->add($passwd);
5397 $ctx1->add($passwd);
5398 local $final = $ctx1->digest();
5399 for($pl=length($passwd); $pl>0; $pl-=16) {
5400 $ctx->add($pl > 16 ? $final : substr($final, 0, $pl));
5403 # This piece of code seems rather pointless, but it's in the C code that
5404 # does MD5 in PAM so it has to go in!
5407 for($i=length($passwd); $i; $i >>= 1) {
5412 $ctx->add(substr($passwd, $j, 1));
5415 $final = $ctx->digest();
5418 # This loop exists only to waste time
5419 for($i=0; $i<1000; $i++) {
5420 $ctx1 = eval "new $use_md5";
5421 $ctx1->add($i & 1 ? $passwd : $final);
5422 $ctx1->add($salt) if ($i % 3);
5423 $ctx1->add($passwd) if ($i % 7);
5424 $ctx1->add($i & 1 ? $final : $passwd);
5425 $final = $ctx1->digest();
5429 # Convert the 16-byte final string into a readable form
5431 local @final = map { ord($_) } split(//, $final);
5432 $l = ($final[ 0]<<16) + ($final[ 6]<<8) + $final[12];
5433 $rv .= &to64($l, 4);
5434 $l = ($final[ 1]<<16) + ($final[ 7]<<8) + $final[13];
5435 $rv .= &to64($l, 4);
5436 $l = ($final[ 2]<<16) + ($final[ 8]<<8) + $final[14];
5437 $rv .= &to64($l, 4);
5438 $l = ($final[ 3]<<16) + ($final[ 9]<<8) + $final[15];
5439 $rv .= &to64($l, 4);
5440 $l = ($final[ 4]<<16) + ($final[10]<<8) + $final[ 5];
5441 $rv .= &to64($l, 4);
5443 $rv .= &to64($l, 2);
5445 # Add salt if needed
5447 return $magic.$salt.'$'.$rv;
5456 local ($v, $n) = @_;
5459 $r .= $itoa64[$v & 0x3f];
5465 # read_file(file, &assoc, [&order], [lowercase])
5466 # Fill an associative array with name=value pairs from a file
5469 open(ARFILE, $_[0]) || return 0;
5472 if (!/^#/ && /^([^=]*)=(.*)$/) {
5473 $_[1]->{$_[3] ? lc($1) : $1} = $2;
5474 push(@{$_[2]}, $1) if ($_[2]);
5481 # write_file(file, array)
5482 # Write out the contents of an associative array as name=value lines
5485 local(%old, @order);
5486 &read_file($_[0], \%old, \@order);
5487 open(ARFILE, ">$_[0]");
5488 foreach $k (@order) {
5489 print ARFILE $k,"=",$_[1]->{$k},"\n" if (exists($_[1]->{$k}));
5491 foreach $k (keys %{$_[1]}) {
5492 print ARFILE $k,"=",$_[1]->{$k},"\n" if (!exists($old{$k}));
5497 # execute_ready_webmin_crons()
5498 # Find and run any cron jobs that are due, based on their last run time and
5499 # execution interval
5500 sub execute_ready_webmin_crons
5504 foreach my $cron (@webmincrons) {
5506 if (!$webmincron_last{$cron->{'id'}}) {
5507 # If not ever run before, don't run right away
5508 $webmincron_last{$cron->{'id'}} = $now;
5511 elsif ($cron->{'interval'} &&
5512 $now - $webmincron_last{$cron->{'id'}} > $cron->{'interval'}) {
5513 # Older than interval .. time to run
5516 elsif ($cron->{'mins'}) {
5517 # Check if current time matches spec, and we haven't run in the
5519 my @tm = localtime($now);
5520 if (&matches_cron($cron->{'mins'}, $tm[1]) &&
5521 &matches_cron($cron->{'hours'}, $tm[2]) &&
5522 &matches_cron($cron->{'days'}, $tm[3]) &&
5523 &matches_cron($cron->{'months'}, $tm[4]+1) &&
5524 &matches_cron($cron->{'weekdays'}, $tm[6]) &&
5525 $now - $webmincron_last{$cron->{'id'}} > 60) {
5531 print DEBUG "Running cron id=$cron->{'id'} ".
5532 "module=$cron->{'module'} func=$cron->{'func'}\n";
5533 $webmincron_last{$cron->{'id'}} = $now;
5537 # Run via a wrapper command, which we run like a CGI
5538 dbmclose(%sessiondb);
5540 # Setup CGI-like environment
5541 $envtz = $ENV{"TZ"};
5542 $envuser = $ENV{"USER"};
5543 $envpath = $ENV{"PATH"};
5544 $envlang = $ENV{"LANG"};
5545 $envroot = $ENV{"SystemRoot"};
5546 $envperllib = $ENV{'PERLLIB'};
5547 foreach my $k (keys %ENV) {
5550 $ENV{"PATH"} = $envpath if ($envpath);
5551 $ENV{"TZ"} = $envtz if ($envtz);
5552 $ENV{"USER"} = $envuser if ($envuser);
5553 $ENV{"OLD_LANG"} = $envlang if ($envlang);
5554 $ENV{"SystemRoot"} = $envroot if ($envroot);
5555 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
5556 $ENV{"HOME"} = $user_homedir;
5557 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
5558 $ENV{"SERVER_ADMIN"} = $config{"email"};
5560 $ENV{"SERVER_ROOT"} = $root0;
5561 $ENV{"SERVER_REALROOT"} = $root0;
5562 $ENV{"SERVER_PORT"} = $config{'port'};
5563 $ENV{"WEBMIN_CRON"} = 1;
5564 $ENV{"DOCUMENT_ROOT"} = $root0;
5565 $ENV{"DOCUMENT_REALROOT"} = $root0;
5566 $ENV{"MINISERV_CONFIG"} = $config_file;
5567 $ENV{"HTTPS"} = "ON" if ($use_ssl);
5568 $ENV{"MINISERV_PID"} = $miniserv_main_pid;
5569 $ENV{"SCRIPT_FILENAME"} = $config{'webmincron_wrapper'};
5570 if ($ENV{"SCRIPT_FILENAME"} =~ /^\Q$root0\E(\/.*)$/) {
5571 $ENV{"SCRIPT_NAME"} = $1;
5573 $config{'webmincron_wrapper'} =~ /^(.*)\//;
5575 foreach $k (keys %config) {
5576 if ($k =~ /^env_(\S+)$/) {
5577 $ENV{$1} = $config{$k};
5581 $SIG{'CHLD'} = 'DEFAULT';
5583 # Have SOCK closed if the perl exec's something
5585 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
5588 # Run the wrapper script by evaling it
5589 $pkg = "webmincron";
5590 $0 = $config{'webmincron_wrapper'};
5592 $main_process_id = $$;
5596 do \$miniserv::config{'webmincron_wrapper'};
5600 print STDERR "Perl cron failure : $@\n";
5605 push(@childpids, $pid);
5609 # Write out file containing last run times
5610 &write_file($config{'webmincron_last'}, \%webmincron_last);
5614 # matches_cron(cron-spec, time)
5615 # Checks if some minute or hour matches some cron spec, which can be * or a list
5619 my ($spec, $tm) = @_;
5624 foreach my $s (split(/,/, $spec)) {
5626 $s =~ /^(\d+)\-(\d+)$/ && $tm >= $1 && $tm <= $2) {
5634 # read_webmin_crons()
5635 # Read all scheduled webmin cron functions and store them in the @webmincrons
5637 sub read_webmin_crons
5640 opendir(CRONS, $config{'webmincron_dir'});
5641 print DEBUG "Reading crons from $config{'webmincron_dir'}\n";
5642 foreach my $f (readdir(CRONS)) {
5643 if ($f =~ /^(\d+)\.cron$/) {
5645 &read_file("$config{'webmincron_dir'}/$f", \%cron);
5648 foreach my $n ('module', 'func') {
5650 print STDERR "Cron $1 missing $n\n";
5654 if (!$cron{'interval'} && !$cron{'mins'} && !$cron{'special'}) {
5655 print STDERR "Cron $1 missing any time spec\n";
5658 if ($cron{'special'} eq 'hourly') {
5659 # Run every hour on the hour
5661 $cron{'hours'} = '*';
5662 $cron{'days'} = '*';
5663 $cron{'months'} = '*';
5664 $cron{'weekdays'} = '*';
5666 elsif ($cron{'special'} eq 'daily') {
5667 # Run every day at midnight
5669 $cron{'hours'} = '0';
5670 $cron{'days'} = '*';
5671 $cron{'months'} = '*';
5672 $cron{'weekdays'} = '*';
5674 elsif ($cron{'special'} eq 'monthly') {
5675 # Run every month on the 1st
5677 $cron{'hours'} = '0';
5678 $cron{'days'} = '1';
5679 $cron{'months'} = '*';
5680 $cron{'weekdays'} = '*';
5682 elsif ($cron{'special'} eq 'weekly') {
5683 # Run every month on the 1st
5685 $cron{'hours'} = '0';
5686 $cron{'days'} = '*';
5687 $cron{'months'} = '*';
5688 $cron{'weekdays'} = '0';
5690 elsif ($cron{'special'} eq 'yearly' ||
5691 $cron{'special'} eq 'annually') {
5692 # Run every year on 1st january
5694 $cron{'hours'} = '0';
5695 $cron{'days'} = '1';
5696 $cron{'months'} = '1';
5697 $cron{'weekdays'} = '*';
5699 elsif ($cron{'special'}) {
5700 print STDERR "Cron $1 invalid special time $cron{'special'}\n";
5703 if ($cron{'special'}) {
5704 delete($cron{'special'});
5707 print DEBUG "adding cron id=$cron{'id'} module=$cron{'module'} func=$cron{'func'}\n";
5708 push(@webmincrons, \%cron);
5715 # Read into the Webmin cache all files marked for pre-caching
5718 undef(%main::read_file_cache);
5719 foreach my $g (split(/\s+/, $config{'precache'})) {
5720 next if ($g eq "none");
5721 foreach my $f (glob("$config{'root'}/$g")) {
5724 $main::read_file_cache{$f} = { };
5725 &read_file($f, $main::read_file_cache{$f});
5726 $main::read_file_cache_time{$f} = $st[9];
5731 # Check if some address is valid IPv4, returns 1 if so.
5734 return $_[0] =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/ &&
5735 $1 >= 0 && $1 <= 255 &&
5736 $2 >= 0 && $2 <= 255 &&
5737 $3 >= 0 && $3 <= 255 &&
5738 $4 >= 0 && $4 <= 255;
5741 # Check if some IPv6 address is properly formatted, and returns 1 if so.
5742 sub check_ip6address
5744 my @blocks = split(/:/, $_[0]);
5745 return 0 if (@blocks == 0 || @blocks > 8);
5747 my $where = index($blocks[$ib],"/");
5750 my $b = substr($blocks[$ib],0,$where);
5751 $m = substr($blocks[$ib],$where+1,length($blocks[$ib])-($where+1));
5754 return 0 if ($m <0 || $m >128);
5757 foreach $b (@blocks) {
5758 return 0 if ($b ne "" && $b !~ /^[0-9a-f]{1,4}$/i);
5759 $empty++ if ($b eq "");
5761 return 0 if ($empty > 1 && !($_[0] =~ /^::/ && $empty == 2));
5765 # network_to_address(binary)
5766 # Given a network address in binary IPv4 or v4 format, return the string form
5767 sub network_to_address
5770 if (length($addr) == 4 || !$use_ipv6) {
5771 return inet_ntoa($addr);
5774 return Socket6::inet_ntop(Socket6::AF_INET6(), $addr);
5778 # redirect_stderr_to_log()
5779 # Re-direct STDERR to error log file
5780 sub redirect_stderr_to_log
5782 if ($config{'errorlog'} ne '-') {
5783 open(STDERR, ">>$config{'errorlog'}") ||
5784 die "failed to open $config{'errorlog'} : $!";
5785 if ($config{'logperms'}) {
5786 chmod(oct($config{'logperms'}), $config{'errorlog'});
5789 select(STDERR); $| = 1; select(STDOUT);
5792 # should_gzip_file(filename)
5793 # Returns 1 if some path should be gzipped
5794 sub should_gzip_file
5797 return $path !~ /\.(gif|png|jpg|jpeg|tif|tiff)$/i;
5800 # get_expires_time(path)
5801 # Given a URL path, return the client-side expiry time in seconds
5802 sub get_expires_time
5805 foreach my $pe (@expires_paths) {
5806 if ($path =~ /$pe->[0]/i) {
5810 return $config{'expires'};