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 (undef, $peera, undef) = &get_address_ip($acptaddr, $ipv6);
434 (undef, $locala) = &get_socket_ip(SOCK, $ipv6);
436 print DEBUG "main: Starting handle_request loop pid=$$\n";
437 while(&handle_request($peera, $locala, $ipv6)) { }
438 print DEBUG "main: Done handle_request loop pid=$$\n";
443 # Build list of sockets to listen on
444 $config{'bind'} = '' if ($config{'bind'} eq '*');
445 if ($config{'bind'}) {
446 # Listening on a specific IP
447 if (&check_ip6address($config{'bind'})) {
449 $use_ipv6 || die "Cannot bind to $config{'bind'} without IPv6";
450 push(@sockets, [ inet_pton(Socket6::AF_INET6(),$config{'bind'}),
452 Socket6::PF_INET6() ]);
456 push(@sockets, [ inet_aton($config{'bind'}),
462 # Listening on all IPs
463 push(@sockets, [ INADDR_ANY, $config{'port'}, PF_INET() ]);
466 push(@sockets, [ in6addr_any(), $config{'port'},
467 Socket6::PF_INET6() ]);
470 foreach $s (split(/\s+/, $config{'sockets'})) {
471 if ($s =~ /^(\d+)$/) {
472 # Just listen on another port on the main IP
473 push(@sockets, [ $sockets[0]->[0], $s, $sockets[0]->[2] ]);
474 if ($use_ipv6 && !$config{'bind'}) {
475 # Also listen on that port on the main IPv6 address
476 push(@sockets, [ $sockets[1]->[0], $s,
480 elsif ($s =~ /^\*:(\d+)$/) {
481 # Listening on all IPs on some port
482 push(@sockets, [ INADDR_ANY, $1,
485 push(@sockets, [ in6addr_any(), $1,
486 Socket6::PF_INET6() ]);
489 elsif ($s =~ /^(\S+):(\d+)$/) {
490 # Listen on a specific port and IP
491 my ($ip, $port) = ($1, $2);
492 if (&check_ip6address($ip)) {
493 $use_ipv6 || die "Cannot bind to $ip without IPv6";
494 push(@sockets, [ inet_pton(Socket6::AF_INET6(),
496 $port, Socket6::PF_INET6() ]);
499 push(@sockets, [ inet_aton($ip), $port,
503 elsif ($s =~ /^([0-9\.]+):\*$/ || $s =~ /^([0-9\.]+)$/) {
504 # Listen on the main port on another IPv4 address
505 push(@sockets, [ inet_aton($1), $sockets[0]->[1],
508 elsif (($s =~ /^([0-9a-f\:]+):\*$/ || $s =~ /^([0-9a-f\:]+)$/) &&
510 # Listen on the main port on another IPv6 address
511 push(@sockets, [ inet_pton(Socket6::AF_INET6(), $1),
513 Socket6::PF_INET6() ]);
517 # Open all the sockets
518 $proto = getprotobyname('tcp');
520 $tried_inaddr_any = 0;
521 for($i=0; $i<@sockets; $i++) {
523 socket($fh, $sockets[$i]->[2], SOCK_STREAM, $proto) ||
524 die "Failed to open socket family $sockets[$i]->[2] : $!";
525 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
526 if ($sockets[$i]->[2] eq PF_INET()) {
527 $pack = pack_sockaddr_in($sockets[$i]->[1], $sockets[$i]->[0]);
530 $pack = pack_sockaddr_in6($sockets[$i]->[1], $sockets[$i]->[0]);
531 setsockopt($fh, 41, 26, pack("l", 1)); # IPv6 only
533 for($j=0; $j<5; $j++) {
534 last if (bind($fh, $pack));
538 # All attempts failed .. give up
539 if ($sockets[$i]->[0] eq INADDR_ANY ||
540 $use_ipv6 && $sockets[$i]->[0] eq in6addr_any()) {
542 "Failed to bind to port $sockets[$i]->[1] : $!");
543 $tried_inaddr_any = 1;
546 $ip = &network_to_address($sockets[$i]->[0]);
548 "Failed to bind to IP $ip port ".
549 "$sockets[$i]->[1] : $!");
553 listen($fh, SOMAXCONN);
554 push(@socketfhs, $fh);
555 $ipv6fhs{$fh} = $sockets[$i]->[2] eq PF_INET() ? 0 : 1;
558 foreach $se (@sockerrs) {
559 print STDERR $se,"\n";
562 # If all binds failed, try binding to any address
563 if (!@socketfhs && !$tried_inaddr_any) {
564 print STDERR "Falling back to listening on any address\n";
566 socket($fh, PF_INET(), SOCK_STREAM, $proto) ||
567 die "Failed to open socket : $!";
568 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
569 if (!bind($fh, pack_sockaddr_in($sockets[0]->[1], INADDR_ANY))) {
570 print STDERR "Failed to bind to port $sockets[0]->[1] : $!\n";
573 listen($fh, SOMAXCONN);
574 push(@socketfhs, $fh);
576 elsif (!@socketfhs && $tried_inaddr_any) {
577 print STDERR "Could not listen on any ports";
581 if ($config{'listen'}) {
582 # Open the socket that allows other webmin servers to find this one
583 $proto = getprotobyname('udp');
584 if (socket(LISTEN, PF_INET(), SOCK_DGRAM, $proto)) {
585 setsockopt(LISTEN, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
586 bind(LISTEN, pack_sockaddr_in($config{'listen'}, INADDR_ANY));
587 listen(LISTEN, SOMAXCONN);
590 $config{'listen'} = 0;
594 # Split from the controlling terminal, unless configured not to
595 if (!$config{'nofork'}) {
596 if (fork()) { exit; }
598 eval { setsid(); }; # may not work on Windows
600 # Close standard file handles
601 open(STDIN, "</dev/null");
602 open(STDOUT, ">/dev/null");
603 &redirect_stderr_to_log();
604 &log_error("miniserv.pl started");
605 foreach $msg (@startup_msg) {
609 # write out the PID file
612 # Start the log-clearing process, if needed. This checks every minute
613 # to see if the log has passed its reset time, and if so clears it
614 if ($config{'logclear'}) {
615 if (!($logclearer = fork())) {
616 &close_all_sockets();
619 local $write_logtime = 0;
620 local @st = stat("$config{'logfile'}.time");
622 if ($st[9]+$config{'logtime'}*60*60 < time()){
625 unlink($config{'logfile'});
628 else { $write_logtime = 1; }
629 if ($write_logtime) {
630 open(LOGTIME, ">$config{'logfile'}.time");
631 print LOGTIME time(),"\n";
638 push(@childpids, $logclearer);
641 # Setup the logout time dbm if needed
642 if ($config{'session'}) {
643 eval "use SDBM_File";
644 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
645 eval "\$sessiondb{'1111111111'} = 'foo bar';";
647 dbmclose(%sessiondb);
648 eval "use NDBM_File";
649 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
652 delete($sessiondb{'1111111111'});
657 $SIG{'HUP'} = 'miniserv::trigger_restart';
658 $SIG{'TERM'} = 'miniserv::term_handler';
659 $SIG{'USR1'} = 'miniserv::trigger_reload';
660 $SIG{'PIPE'} = 'IGNORE';
661 local $remove_session_count = 0;
662 $need_pipes = $config{'passdelay'} || $config{'session'};
664 # wait for a new connection, or a message from a child process
666 if (@childpids <= $config{'maxconns'}) {
667 # Only accept new main socket connects when ready
669 foreach $s (@socketfhs) {
670 vec($rmask, fileno($s), 1) = 1;
674 printf STDERR "too many children (%d > %d)\n",
675 scalar(@childpids), $config{'maxconns'};
678 for($i=0; $i<@passin; $i++) {
679 vec($rmask, fileno($passin[$i]), 1) = 1;
682 vec($rmask, fileno(LISTEN), 1) = 1 if ($config{'listen'});
684 # Wait for a connection
685 local $sel = select($rmask, undef, undef, 10);
687 # Check the flag files
688 if ($config{'restartflag'} && -r $config{'restartflag'}) {
689 print STDERR "restart flag file detected\n";
690 unlink($config{'restartflag'});
693 if ($config{'reloadflag'} && -r $config{'reloadflag'}) {
694 unlink($config{'reloadflag'});
699 # Got a HUP signal while in select() .. restart now
703 # Got a USR1 signal while in select() .. re-read config
705 &reload_config_file();
707 local $time_now = time();
709 # Clean up finished processes
711 do { $pid = waitpid(-1, WNOHANG);
712 @childpids = grep { $_ != $pid } @childpids;
713 } while($pid != 0 && $pid != -1);
715 # run the unblocking procedure to check if enough time has passed to
716 # unblock hosts that heve been blocked because of password failures
718 if ($config{'blockhost_failures'}) {
720 while ($i <= $#deny) {
721 if ($blockhosttime{$deny[$i]} &&
722 $config{'blockhost_time'} != 0 &&
723 ($time_now - $blockhosttime{$deny[$i]}) >=
724 $config{'blockhost_time'}) {
725 # the host can be unblocked now
726 $hostfail{$deny[$i]} = 0;
727 splice(@deny, $i, 1);
734 # Do the same for blocked users
735 if ($config{'blockuser_failures'}) {
737 while ($i <= $#deny) {
738 if ($blockusertime{$deny[$i]} &&
739 $config{'blockuser_time'} != 0 &&
740 ($time_now - $blockusertime{$deny[$i]}) >=
741 $config{'blockuser_time'}) {
742 # the user can be unblocked now
743 $userfail{$deny[$i]} = 0;
744 splice(@denyusers, $i, 1);
751 &write_blocked_file();
754 # Check if any webmin cron jobs are ready to run
755 &execute_ready_webmin_crons();
757 if ($config{'session'} && (++$remove_session_count%50) == 0) {
758 # Remove sessions with more than 7 days of inactivity,
760 foreach $s (keys %sessiondb) {
761 local ($user, $ltime, $lip) =
762 split(/\s+/, $sessiondb{$s});
763 if ($time_now - $ltime > 7*24*60*60) {
764 &run_logout_script($s, $user);
765 &write_logout_utmp($user, $lip);
766 delete($sessiondb{$s});
769 "Timeout of session for $user");
775 if ($use_pam && $config{'pam_conv'}) {
776 # Remove PAM sessions with more than 5 minutes of inactivity
778 foreach $c (values %conversations) {
779 if ($time_now - $c->{'time'} > 5*60) {
780 &end_pam_conversation($c);
782 syslog("info", "%s", "Timeout of PAM ".
783 "session for $c->{'user'}");
789 # Don't check any sockets if there is no activity
792 # Check if any of the main sockets have received a new connection
794 foreach $s (@socketfhs) {
795 if (vec($rmask, fileno($s), 1)) {
797 $acptaddr = accept(SOCK, $s);
798 if (!$acptaddr) { next; }
799 binmode(SOCK); # turn off any Perl IO stuff
802 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
804 ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw) =
808 # Work out IP and port of client
809 local ($peerb, $peera, $peerp) =
810 &get_address_ip($acptaddr, $ipv6fhs{$s});
812 # Work out the local IP
813 (undef, $locala) = &get_socket_ip(SOCK, $ipv6fhs{$s});
815 # Check username of connecting user
816 $localauth_user = undef;
817 if ($config{'localauth'} && $peera eq "127.0.0.1") {
818 if (open(TCP, "/proc/net/tcp")) {
819 # Get the info direct from the kernel
820 $peerh = sprintf("%4.4X", $peerp);
823 local @t = split(/[\s:]+/, $_);
824 if ($t[1] eq '0100007F' &&
833 if (!$localauth_user) {
834 # Call lsof for the info
835 local $lsofpid = open(LSOF,
836 "$config{'localauth'} -i ".
837 "TCP\@127.0.0.1:$peerp |");
839 if (/^(\S+)\s+(\d+)\s+(\S+)/ &&
840 $2 != $$ && $2 != $lsofpid){
841 $localauth_user = $3;
848 # Work out the hostname for this web server
849 $host = &get_socket_name(SOCK, $ipv6fhs{$s});
852 "Failed to get local socket name : $!\n";
856 $port = $sockets[$sn]->[1];
858 # fork the subprocess
860 if (!($handpid = fork())) {
861 # setup signal handlers
862 $SIG{'TERM'} = 'DEFAULT';
863 $SIG{'PIPE'} = 'DEFAULT';
864 #$SIG{'CHLD'} = 'IGNORE';
865 $SIG{'HUP'} = 'IGNORE';
866 $SIG{'USR1'} = 'IGNORE';
868 # Initialize SSL for this connection
870 $ssl_con = &ssl_connection_for_ip(
875 # Close the file handle for the session DBM
876 dbmclose(%sessiondb);
878 # close useless pipes
881 close($PASSINr); close($PASSOUTw);
883 &close_all_sockets();
887 "main: Starting handle_request loop pid=$$\n";
888 while(&handle_request($peera, $locala,
890 # Loop until keepalive stops
893 "main: Done handle_request loop pid=$$\n";
896 close($PASSINw); close($PASSOUTw);
899 push(@childpids, $handpid);
901 close($PASSINw); close($PASSOUTr);
902 push(@passin, $PASSINr);
903 push(@passout, $PASSOUTw);
910 if ($config{'listen'} && vec($rmask, fileno(LISTEN), 1)) {
911 # Got UDP packet from another webmin server
913 local $from = recv(LISTEN, $rcvbuf, 1024, 0);
915 local $fromip = inet_ntoa((unpack_sockaddr_in($from))[1]);
916 local $toip = inet_ntoa((unpack_sockaddr_in(
917 getsockname(LISTEN)))[1]);
918 if ((!@deny || !&ip_match($fromip, $toip, @deny)) &&
919 (!@allow || &ip_match($fromip, $toip, @allow))) {
920 local $listenhost = &get_socket_name(LISTEN, 0);
921 send(LISTEN, "$listenhost:$config{'port'}:".
922 ($use_ssl || $config{'inetd_ssl'} ? 1 : 0).":".
923 ($config{'listenhost'} ?
924 &get_system_hostname() : ""),
930 # check for session, password-timeout and PAM messages from subprocesses
931 for($i=0; $i<@passin; $i++) {
932 if (vec($rmask, fileno($passin[$i]), 1)) {
933 # this sub-process is asking about a password
934 local $infd = $passin[$i];
935 local $outfd = $passout[$i];
936 #local $inline = <$infd>;
937 local $inline = &sysread_line($infd);
939 print DEBUG "main: inline $inline";
942 print DEBUG "main: inline EOF\n";
944 if ($inline =~ /^delay\s+(\S+)\s+(\S+)\s+(\d+)/) {
945 # Got a delay request from a subprocess.. for
946 # valid logins, there is no delay (to prevent
947 # denial of service attacks), but for invalid
948 # logins the delay increases with each failed
951 # login OK.. no delay
952 print $outfd "0 0\n";
953 $wasblocked = $hostfail{$2} ||
958 &write_blocked_file();
967 # add the host to the block list,
969 if ($config{'blockhost_failures'} &&
971 $config{'blockhost_failures'}) {
973 $blockhosttime{$2} = $time_now;
976 local $logtext = "Security alert: Host $2 blocked after $config{'blockhost_failures'} failed logins for user $1";
982 # add the user to the user block list,
984 if ($config{'blockuser_failures'} &&
986 $config{'blockuser_failures'}) {
987 push(@denyusers, $1);
988 $blockusertime{$1} = $time_now;
991 local $logtext = "Security alert: User $1 blocked after $config{'blockuser_failures'} failed logins";
997 # Lock out the user's password, if enabled
998 if ($config{'blocklock'} &&
1000 $config{'blockuser_failures'}) {
1001 my $lk = &lock_user_password($1);
1004 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";
1005 syslog("crit", "%s",
1011 $dl = $userdlay{$1} -
1012 int(($time_now - $userlast{$1})/50);
1013 $dl = $dl < 0 ? 0 : $dl+1;
1014 print $outfd "$dl $blocked\n";
1015 $userdlay{$1} = $dl;
1017 # Write out blocked status file
1019 &write_blocked_file();
1022 $userlast{$1} = $time_now;
1024 elsif ($inline =~ /^verify\s+(\S+)\s+(\S+)/) {
1025 # Verifying a session ID
1026 local $session_id = $1;
1027 local $notimeout = $2;
1028 local $skey = $sessiondb{$session_id} ?
1030 &hash_session_id($session_id);
1031 if (!defined($sessiondb{$skey})) {
1032 # Session doesn't exist
1033 print $outfd "0 0\n";
1036 local ($user, $ltime) =
1037 split(/\s+/, $sessiondb{$skey});
1038 local $lot = &get_logout_time($user, $session_id);
1040 $time_now - $ltime > $lot*60 &&
1042 # Session has timed out
1043 print $outfd "1 ",$time_now - $ltime,"\n";
1044 #delete($sessiondb{$skey});
1048 print $outfd "2 $user\n";
1050 $time_now - $ltime >
1052 $sessiondb{$skey} = "$user $time_now";
1057 elsif ($inline =~ /^new\s+(\S+)\s+(\S+)\s+(\S+)/) {
1058 # Creating a new session
1059 local $session_id = $1;
1062 $sessiondb{&hash_session_id($session_id)} =
1063 "$user $time_now $ip";
1065 elsif ($inline =~ /^delete\s+(\S+)/) {
1066 # Logging out a session
1067 local $session_id = $1;
1068 local $skey = $sessiondb{$session_id} ?
1070 &hash_session_id($session_id);
1071 local @sdb = split(/\s+/, $sessiondb{$skey});
1072 print $outfd $sdb[0],"\n";
1073 delete($sessiondb{$skey});
1075 elsif ($inline =~ /^pamstart\s+(\S+)\s+(\S+)\s+(.*)/) {
1076 # Starting a new PAM conversation
1077 local ($cid, $host, $user) = ($1, $2, $3);
1079 # Does this user even need PAM?
1080 local ($realuser, $canlogin) =
1081 &can_user_login($user, undef, $host);
1083 if ($canlogin == 0) {
1084 # Cannot even login!
1085 print $outfd "0 Invalid username\n";
1087 elsif ($canlogin != 2) {
1088 # Not using PAM .. so just ask for
1090 $conv = { 'user' => $realuser,
1095 print $outfd "3 Password\n";
1098 # Start the PAM conversation
1099 # sub-process, and get a question
1100 $conv = { 'user' => $realuser,
1104 local ($PAMINr, $PAMINw, $PAMOUTr,
1105 $PAMOUTw) = &allocate_pipes();
1106 local $pampid = fork();
1108 close($PAMOUTr); close($PAMINw);
1109 &pam_conversation_process(
1113 close($PAMOUTw); close($PAMINr);
1114 $conv->{'pid'} = $pampid;
1115 $conv->{'PAMOUTr'} = $PAMOUTr;
1116 $conv->{'PAMINw'} = $PAMINw;
1117 push(@childpids, $pampid);
1119 # Get the first PAM question
1120 local $pok = &recv_pam_question(
1123 &end_pam_conversation($conv);
1127 $conversations{$cid} = $conv if ($conv);
1129 elsif ($inline =~ /^pamanswer\s+(\S+)\s+(.*)/) {
1130 # A response to a PAM question
1131 local ($cid, $answer) = ($1, $2);
1132 local $conv = $conversations{$cid};
1134 # No such conversation?
1135 print $outfd "0 Bad login session\n";
1137 elsif ($conv->{'pid'}) {
1138 # Send the PAM response and get
1140 &send_pam_answer($conv, $answer);
1141 local $pok = &recv_pam_question($conv, $outfd);
1143 &end_pam_conversation($conv);
1147 # This must be the password .. try it
1148 # and send back the results
1149 local ($vu, $expired, $nonexist) =
1150 &validate_user($conv->{'user'},
1153 local $ok = $vu ? 1 : 0;
1154 print $outfd "2 $conv->{'user'} $ok $expired $notexist\n";
1155 &end_pam_conversation($conv);
1158 elsif ($inline =~ /^writesudo\s+(\S+)\s+(\d+)/) {
1159 # Store the fact that some user can sudo to root
1160 local ($user, $ok) = ($1, $2);
1161 $sudocache{$user} = $ok." ".time();
1163 elsif ($inline =~ /^readsudo\s+(\S+)/) {
1164 # Query the user sudo cache (valid for 1 minute)
1166 local ($ok, $last) =
1167 split(/\s+/, $sudocache{$user});
1168 if ($last < time()-60) {
1173 # Tell client OK or not
1174 print $outfd "$ok\n";
1177 elsif ($inline =~ /\S/) {
1178 # Unknown line from pipe?
1179 print DEBUG "main: Unknown line from pipe $inline\n";
1180 print STDERR "Unknown line from pipe $inline\n";
1184 close($infd); close($outfd);
1185 $passin[$i] = $passout[$i] = undef;
1189 @passin = grep { defined($_) } @passin;
1190 @passout = grep { defined($_) } @passout;
1193 # handle_request(remoteaddress, localaddress, ipv6-flag)
1194 # Where the real work is done
1197 local ($acptip, $localip, $ipv6) = @_;
1198 print DEBUG "handle_request: from $acptip to $localip ipv6=$ipv6\n";
1199 if ($config{'loghost'}) {
1200 $acpthost = &to_hostname($acptip);
1201 $acpthost = $acptip if (!$acpthost);
1204 $acpthost = $acptip;
1206 $datestr = &http_date(time());
1208 $ok_message = "Document follows";
1209 $logged_code = undef;
1210 $reqline = $request_uri = $page = undef;
1214 # check address against access list
1215 if (@deny && &ip_match($acptip, $localip, @deny) ||
1216 @allow && !&ip_match($acptip, $localip, @allow)) {
1217 &http_error(403, "Access denied for $acptip");
1222 # Check address with TCP-wrappers
1223 if (!hosts_ctl($config{'pam'}, STRING_UNKNOWN,
1224 $acptip, STRING_UNKNOWN)) {
1225 &http_error(403, "Access denied for $acptip by TCP wrappers");
1229 print DEBUG "handle_request: passed IP checks\n";
1231 # Compute a timeout for the start of headers, based on the number of
1232 # child processes. As this increases, we use a shorter timeout to avoid
1233 # an attacker overloading the system.
1234 local $header_timeout = 60 + ($config{'maxconns'} - @childpids) * 10;
1236 # Wait at most 60 secs for start of headers for initial requests, or
1237 # 10 minutes for kept-alive connections
1239 vec($rmask, fileno(SOCK), 1) = 1;
1240 local $to = $checked_timeout ? 10*60 : $header_timeout;
1241 local $sel = select($rmask, undef, undef, $to);
1243 if ($checked_timeout) {
1244 print DEBUG "handle_request: exiting due to timeout of $to\n";
1248 &http_error(400, "Timeout",
1249 "Waited for that $to seconds for start of headers");
1253 print DEBUG "handle_request: passed timeout check\n";
1255 # Read the HTTP request and headers
1256 local $origreqline = &read_line();
1257 ($reqline = $origreqline) =~ s/\r|\n//g;
1258 $method = $page = $request_uri = undef;
1259 print DEBUG "handle_request reqline=$reqline\n";
1260 if (!$reqline && (!$use_ssl || $checked_timeout > 1)) {
1261 # An empty request .. just close the connection
1262 print DEBUG "handle_request: rejecting empty request\n";
1265 elsif ($reqline !~ /^(\S+)\s+(.*)\s+HTTP\/1\..$/) {
1266 print DEBUG "handle_request: invalid reqline=$reqline\n";
1268 # This could be an http request when it should be https
1270 local $url = $config{'musthost'} ?
1271 "https://$config{'musthost'}:$port/" :
1272 "https://$host:$port/";
1273 if ($config{'ssl_redirect'}) {
1274 # Just re-direct to the correct URL
1275 sleep(1); # Give browser a change to finish
1276 # sending its request
1277 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1278 &write_data("Date: $datestr\r\n");
1279 &write_data("Server: $config{'server'}\r\n");
1280 &write_data("Location: $url\r\n");
1281 &write_keep_alive(0);
1282 &write_data("\r\n");
1286 # Tell user the correct URL
1287 &http_error(200, "Bad Request", "This web server is running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1290 elsif (ord(substr($reqline, 0, 1)) == 128 && !$use_ssl) {
1291 # This could be an https request when it should be http ..
1292 # need to fake a HTTP response
1295 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
1296 eval "Net::SSLeay::load_error_strings()";
1297 $ssl_ctx = Net::SSLeay::CTX_new();
1298 Net::SSLeay::CTX_use_RSAPrivateKey_file(
1299 $ssl_ctx, $config{'keyfile'},
1300 &Net::SSLeay::FILETYPE_PEM);
1301 Net::SSLeay::CTX_use_certificate_file(
1303 $config{'certfile'} || $config{'keyfile'},
1304 &Net::SSLeay::FILETYPE_PEM);
1305 $ssl_con = Net::SSLeay::new($ssl_ctx);
1309 select(SSLw); $| = 1; select(STDOUT);
1310 print SSLw $origreqline;
1312 while(sysread(SOCK, $buf, 1) > 0) {
1319 Net::SSLeay::set_wfd($ssl_con, fileno(SOCK));
1320 Net::SSLeay::set_rfd($ssl_con, fileno(SSLr));
1321 Net::SSLeay::accept($ssl_con) || die "accept() failed";
1323 local $url = $config{'musthost'} ?
1324 "https://$config{'musthost'}:$port/" :
1325 "https://$host:$port/";
1326 if ($config{'ssl_redirect'}) {
1327 # Just re-direct to the correct URL
1328 sleep(1); # Give browser a change to
1329 # finish sending its request
1330 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1331 &write_data("Date: $datestr\r\n");
1332 &write_data("Server: $config{'server'}\r\n");
1333 &write_data("Location: $url\r\n");
1334 &write_keep_alive(0);
1335 &write_data("\r\n");
1339 # Tell user the correct URL
1340 &http_error(200, "Bad Request", "This web server is not running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1344 &http_error(400, "Bad Request");
1348 &http_error(400, "Bad Request");
1352 $request_uri = $page = $2;
1356 ($headline = &read_line()) =~ s/\r|\n//g;
1357 last if ($headline eq "");
1358 print DEBUG "handle_request: got headline $headline\n";
1359 if ($headline =~ /^(\S+):\s*(.*)$/) {
1360 $header{$lastheader = lc($1)} = $2;
1362 elsif ($headline =~ /^\s+(.*)$/) {
1363 $header{$lastheader} .= $headline;
1366 &http_error(400, "Bad Header $headline");
1369 if (defined($header{'host'})) {
1370 if ($header{'host'} =~ /^([^:]+):([0-9]+)$/) {
1371 ($host, $port) = ($1, $2);
1374 $host = $header{'host'};
1376 if ($config{'musthost'} && $host ne $config{'musthost'}) {
1377 # Disallowed hostname used
1378 &http_error(400, "Invalid HTTP hostname");
1382 if ($page =~ /^([^\?]+)\?(.*)$/) {
1383 # There is some query string information
1386 print DEBUG "handle_request: querystring=$querystring\n";
1387 if ($querystring !~ /=/) {
1388 $queryargs = $querystring;
1389 $queryargs =~ s/\+/ /g;
1390 $queryargs =~ s/%(..)/pack("c",hex($1))/ge;
1394 # Parse query-string parameters
1395 local @in = split(/\&/, $querystring);
1397 local ($k, $v) = split(/=/, $i, 2);
1398 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1399 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1404 $posted_data = undef;
1405 if ($method eq 'POST' &&
1406 $header{'content-type'} eq 'application/x-www-form-urlencoded') {
1407 # Read in posted query string information, up the configured maximum
1408 # post request length
1409 $clen = $header{"content-length"};
1410 $clen_read = $clen > $config{'max_post'} ? $config{'max_post'} : $clen;
1411 while(length($posted_data) < $clen_read) {
1412 $buf = &read_data($clen_read - length($posted_data));
1413 if (!length($buf)) {
1414 &http_error(500, "Failed to read POST request");
1416 chomp($posted_data);
1417 $posted_data =~ s/\015$//mg;
1418 $posted_data .= $buf;
1420 print DEBUG "clen_read=$clen_read clen=$clen posted_data=",length($posted_data),"\n";
1421 if ($clen_read != $clen && length($posted_data) > $clen) {
1422 # If the client sent more data than we asked for, chop the
1424 $posted_data = substr($posted_data, 0, $clen);
1426 if (length($posted_data) > $clen) {
1427 # When the client sent too much, delay so that it gets headers
1430 if ($header{'user-agent'} =~ /MSIE/ &&
1431 $header{'user-agent'} !~ /Opera/i) {
1432 # MSIE includes an extra newline in the data
1433 $posted_data =~ s/\r|\n//g;
1435 local @in = split(/\&/, $posted_data);
1437 local ($k, $v) = split(/=/, $i, 2);
1439 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1440 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1443 print DEBUG "handle_request: posted_data=$posted_data\n";
1446 # work out accepted encodings
1447 %acceptenc = map { $_, 1 } split(/,/, $header{'accept-encoding'});
1449 # replace %XX sequences in page
1450 $page =~ s/%(..)/pack("c",hex($1))/ge;
1452 # Check if the browser's user agent indicates a mobile device
1453 $mobile_device = &is_mobile_useragent($header{'user-agent'});
1455 # Check if Host: header is for a mobile URL
1456 foreach my $m (@mobile_prefixes) {
1457 if ($header{'host'} =~ /^\Q$m\E/i) {
1462 # check for the logout flag file, and if existant deny authentication
1463 if ($config{'logout'} && -r $config{'logout'}.$in{'miniserv_logout_id'}) {
1464 print DEBUG "handle_request: logout flag set\n";
1465 $deny_authentication++;
1466 open(LOGOUT, $config{'logout'}.$in{'miniserv_logout_id'});
1467 chop($count = <LOGOUT>);
1471 open(LOGOUT, ">$config{'logout'}$in{'miniserv_logout_id'}");
1472 print LOGOUT "$count\n";
1476 unlink($config{'logout'}.$in{'miniserv_logout_id'});
1480 # check for any redirect for the requested URL
1481 foreach my $pfx (@strip_prefix) {
1482 my $l = length($pfx);
1483 if(length($page) >= $l &&
1484 substr($page,0,$l) eq $pfx) {
1485 $page=substr($page,$l);
1489 $simple = &simplify_path($page, $bogus);
1491 $rpath .= "&".$querystring if (defined($querystring));
1492 $redir = $redirect{$rpath};
1493 if (defined($redir)) {
1494 print DEBUG "handle_request: redir=$redir\n";
1495 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1496 &write_data("Date: $datestr\r\n");
1497 &write_data("Server: $config{'server'}\r\n");
1498 local $ssl = $use_ssl || $config{'inetd_ssl'};
1499 $portstr = $port == 80 && !$ssl ? "" :
1500 $port == 443 && $ssl ? "" : ":$port";
1501 $prot = $ssl ? "https" : "http";
1502 &write_data("Location: $prot://$host$portstr$redir\r\n");
1503 &write_keep_alive(0);
1504 &write_data("\r\n");
1508 # Check for a DAV request
1510 foreach my $d (@davpaths) {
1511 if ($simple eq $d || $simple =~ /^\Q$d\E\//) {
1516 if (!$davpath && ($method eq "SEARCH" || $method eq "PUT")) {
1517 &http_error(400, "Bad Request method $method");
1520 # Check for password if needed
1521 if ($config{'userfile'}) {
1522 print DEBUG "handle_request: Need authentication\n";
1526 # Session authentication is never used for connections by
1527 # another webmin server, or for specified pages, or for DAV, or XMLRPC,
1528 # or mobile browsers if requested.
1529 if ($header{'user-agent'} =~ /webmin/i ||
1530 $header{'user-agent'} =~ /$config{'agents_nosession'}/i ||
1531 $sessiononly{$simple} || $davpath ||
1532 $simple eq "/xmlrpc.cgi" ||
1533 $acptip eq $config{'host_nosession'} ||
1534 $mobile_device && $config{'mobile_nosession'}) {
1535 print DEBUG "handle_request: Forcing HTTP authentication\n";
1536 $config{'session'} = 0;
1539 # Check for SSL authentication
1540 if ($use_ssl && $verified_client) {
1541 $peername = Net::SSLeay::X509_NAME_oneline(
1542 Net::SSLeay::X509_get_subject_name(
1543 Net::SSLeay::get_peer_certificate(
1545 $u = &find_user_by_cert($peername);
1550 if ($use_syslog && !$validated) {
1551 syslog("crit", "%s",
1552 "Unknown SSL certificate $peername");
1556 if (!$validated && !$deny_authentication) {
1557 # check for IP-based authentication
1559 foreach $a (keys %ipaccess) {
1560 if ($acptip eq $a) {
1561 # It does! Auth as the user
1563 $baseauthuser = $authuser =
1569 # Check for normal HTTP authentication
1570 if (!$validated && !$deny_authentication && !$config{'session'} &&
1571 $header{authorization} =~ /^basic\s+(\S+)$/i) {
1572 # authorization given..
1573 ($authuser, $authpass) = split(/:/, &b64decode($1), 2);
1574 print DEBUG "handle_request: doing basic auth check authuser=$authuser authpass=$authpass\n";
1575 local ($vu, $expired, $nonexist) =
1576 &validate_user($authuser, $authpass, $host,
1578 print DEBUG "handle_request: vu=$vu expired=$expired nonexist=$nonexist\n";
1579 if ($vu && (!$expired || $config{'passwd_mode'} == 1)) {
1586 if ($use_syslog && !$validated) {
1587 syslog("crit", "%s",
1588 ($nonexist ? "Non-existent" :
1589 $expired ? "Expired" : "Invalid").
1590 " login as $authuser from $acpthost");
1592 if ($authuser =~ /\r|\n|\s/) {
1593 &http_error(500, "Invalid username",
1594 "Username contains invalid characters");
1596 if ($authpass =~ /\r|\n/) {
1597 &http_error(500, "Invalid password",
1598 "Password contains invalid characters");
1601 if ($config{'passdelay'} && !$config{'inetd'} && $authuser) {
1602 # check with main process for delay
1603 print DEBUG "handle_request: about to ask for password delay\n";
1604 print $PASSINw "delay $authuser $acptip $validated\n";
1605 <$PASSOUTr> =~ /(\d+) (\d+)/;
1607 print DEBUG "handle_request: password delay $1 $2\n";
1612 # Check for a visit to the special session login page
1613 if ($config{'session'} && !$deny_authentication &&
1614 $page eq $config{'session_login'}) {
1615 if ($in{'logout'} && $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1616 # Logout clicked .. remove the session
1618 print $PASSINw "delete $sid\n";
1619 local $louser = <$PASSOUTr>;
1622 $already_session_id = undef;
1623 $authuser = $baseauthuser = undef;
1626 syslog("info", "%s", "Logout by $louser from $acpthost");
1628 &run_logout_script($louser, $sid,
1630 &write_logout_utmp($louser, $actphost);
1635 if ($in{'user'} =~ /\r|\n|\s/) {
1636 &http_error(500, "Invalid username",
1637 "Username contains invalid characters");
1639 if ($in{'pass'} =~ /\r|\n/) {
1640 &http_error(500, "Invalid password",
1641 "Password contains invalid characters");
1644 local ($vu, $expired, $nonexist) =
1645 &validate_user($in{'user'}, $in{'pass'}, $host,
1647 local $hrv = &handle_login(
1648 $vu || $in{'user'}, $vu ? 1 : 0,
1649 $expired, $nonexist, $in{'pass'},
1650 $in{'notestingcookie'});
1651 return $hrv if (defined($hrv));
1655 # Check for a visit to the special PAM login page
1656 if ($config{'session'} && !$deny_authentication &&
1657 $use_pam && $config{'pam_conv'} && $page eq $config{'pam_login'} &&
1659 # A question has been entered .. submit it to the main process
1660 print DEBUG "handle_request: Got call to $page ($in{'cid'})\n";
1661 print DEBUG "handle_request: For PAM, authuser=$authuser\n";
1662 if ($in{'answer'} =~ /\r|\n/ || $in{'cid'} =~ /\r|\n|\s/) {
1663 &http_error(500, "Invalid response",
1664 "Response contains invalid characters");
1668 # Start of a new conversation - answer must be username
1669 $cid = &generate_random_id($in{'answer'});
1670 print $PASSINw "pamstart $cid $host $in{'answer'}\n";
1673 # A response to a previous question
1675 print $PASSINw "pamanswer $cid $in{'answer'}\n";
1678 # Read back the response, and the next question (if any)
1679 local $line = <$PASSOUTr>;
1680 $line =~ s/\r|\n//g;
1681 local ($rv, $question) = split(/\s+/, $line, 2);
1684 local $hrv = &handle_login(
1685 !$in{'cid'} && $in{'answer'} ? $in{'answer'}
1688 return $hrv if (defined($hrv));
1690 elsif ($rv == 1 || $rv == 3) {
1691 # Another question .. force use of PAM CGI
1694 $querystring .= "&cid=$cid&question=".
1696 $querystring .= "&password=1" if ($rv == 3);
1698 $page = $config{'pam_login'};
1699 $miniserv_internal = 1;
1703 # Got back a final ok or failure
1704 local ($user, $ok, $expired, $nonexist) =
1705 split(/\s+/, $question);
1706 local $hrv = &handle_login(
1707 $user, $ok, $expired, $nonexist, undef,
1708 $in{'notestingcookie'});
1709 return $hrv if (defined($hrv));
1712 # A message from PAM .. tell the user
1715 $querystring .= "&cid=$cid&message=".
1718 $page = $config{'pam_login'};
1719 $miniserv_internal = 1;
1724 # Check for a visit to the special password change page
1725 if ($config{'session'} && !$deny_authentication &&
1726 $page eq $config{'password_change'} && !$validated) {
1727 # Just let this slide ..
1729 $miniserv_internal = 3;
1732 # Check for an existing session
1733 if ($config{'session'} && !$validated) {
1734 if ($already_session_id) {
1735 $session_id = $already_session_id;
1736 $authuser = $already_authuser;
1739 elsif (!$deny_authentication &&
1740 $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1741 # Try all session cookies
1742 local $cookie = $header{'cookie'};
1743 while($cookie =~ s/(^|\s)$sidname=([a-f0-9]+)//) {
1746 $in{'webmin_notimeout'} ? 1 : 0;
1747 print $PASSINw "verify $session_id $notimeout\n";
1748 <$PASSOUTr> =~ /(\d+)\s+(\S+)/;
1750 # Valid session continuation
1753 $already_authuser = $authuser;
1762 # Invalid session ID .. don't set
1769 # Check for local authentication
1770 if ($localauth_user && !$header{'x-forwarded-for'} && !$header{'via'}) {
1771 my $luser = &get_user_details($localauth_user);
1773 # Local user exists in webmin users file
1775 $authuser = $localauth_user;
1778 # Check if local user is allowed by unixauth
1779 local @can = &can_user_login($localauth_user,
1783 $authuser = $localauth_user;
1786 $localauth_user = undef;
1792 # Check if this path allows anonymous access
1794 foreach $a (keys %anonymous) {
1795 if (substr($simple, 0, length($a)) eq $a) {
1796 # It does! Auth as the user, if IP access
1797 # control allows him.
1798 if (&check_user_ip($anonymous{$a}) &&
1799 &check_user_time($anonymous{$a})) {
1801 $baseauthuser = $authuser =
1809 # Check if this path allows unauthenticated access
1810 local ($u, $unauth);
1811 foreach $u (@unauth) {
1812 $unauth++ if ($simple =~ /$u/);
1814 if (!$bogus && $unauth) {
1815 # Unauthenticated directory or file request - approve it
1817 $baseauthuser = $authuser = undef;
1822 if ($blocked == 0) {
1823 # No password given.. ask
1824 if ($config{'pam_conv'} && $use_pam) {
1825 # Force CGI for PAM question, starting with
1826 # the username which is always needed
1829 $querystring .= "&initial=1&question=".
1830 &urlize("Username");
1831 $querystring .= "&failed=$failed_user" if ($failed_user);
1832 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1834 $page = $config{'pam_login'};
1835 $miniserv_internal = 1;
1838 elsif ($config{'session'}) {
1839 # Force CGI for session login
1842 $querystring .= "&logout=1&page=/";
1845 # Re-direct to current module only
1846 local $rpage = $request_uri;
1847 if (!$config{'loginkeeppage'}) {
1848 $rpage =~ s/\?.*$//;
1849 $rpage =~ s/[^\/]+$//
1851 $querystring = "page=".&urlize($rpage);
1854 $querystring .= "&failed=$failed_user" if ($failed_user);
1855 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1857 $page = $config{'session_login'};
1858 $miniserv_internal = 1;
1862 # Ask for login with HTTP authentication
1863 &write_data("HTTP/1.0 401 Unauthorized\r\n");
1864 &write_data("Date: $datestr\r\n");
1865 &write_data("Server: $config{'server'}\r\n");
1866 &write_data("WWW-authenticate: Basic ".
1867 "realm=\"$config{'realm'}\"\r\n");
1868 &write_keep_alive(0);
1869 &write_data("Content-type: text/html\r\n");
1870 &write_data("\r\n");
1871 &reset_byte_count();
1872 &write_data("<html>\n");
1873 &write_data("<head><title>Unauthorized</title></head>\n");
1874 &write_data("<body><h1>Unauthorized</h1>\n");
1875 &write_data("A password is required to access this\n");
1876 &write_data("web server. Please try again. <p>\n");
1877 &write_data("</body></html>\n");
1878 &log_request($acpthost, undef, $reqline, 401, &byte_count());
1882 elsif ($blocked == 1) {
1883 # when the host has been blocked, give it an error
1884 &http_error(403, "Access denied for $acptip. The host ".
1885 "has been blocked because of too ".
1886 "many authentication failures.");
1888 elsif ($blocked == 2) {
1889 # when the user has been blocked, give it an error
1890 &http_error(403, "Access denied. The user ".
1891 "has been blocked because of too ".
1892 "many authentication failures.");
1896 # Get the real Webmin username
1897 local @can = &can_user_login($authuser, undef, $host);
1898 $baseauthuser = $can[3] || $authuser;
1900 if ($config{'remoteuser'} && !$< && $validated) {
1901 # Switch to the UID of the remote user (if he exists)
1902 local @u = getpwnam($authuser);
1903 if (@u && $< != $u[2]) {
1904 $( = $u[3]; $) = "$u[3] $u[3]";
1905 ($>, $<) = ($u[2], $u[2]);
1908 &http_error(500, "Unix user $authuser does not exist");
1914 # Check per-user IP access control
1915 if (!&check_user_ip($baseauthuser)) {
1916 &http_error(403, "Access denied for $acptip for $baseauthuser");
1920 # Check per-user allowed times
1921 if (!&check_user_time($baseauthuser)) {
1922 &http_error(403, "Access denied at the current time");
1926 $uinfo = &get_user_details($baseauthuser);
1928 # Validate the path, and convert to canonical form
1930 $simple = &simplify_path($page, $bogus);
1931 print DEBUG "handle_request: page=$page simple=$simple\n";
1933 &http_error(400, "Invalid path");
1936 # Check for a DAV request
1938 return &handle_dav_request($davpath);
1941 # Work out the active theme(s)
1942 local $preroots = $mobile_device && defined($config{'mobile_preroot'}) ?
1943 $config{'mobile_preroot'} :
1944 $authuser && defined($config{'preroot_'.$authuser}) ?
1945 $config{'preroot_'.$authuser} :
1946 $uinfo && defined($uinfo->{'preroot'}) ?
1947 $uinfo->{'preroot'} :
1949 local @preroots = reverse(split(/\s+/, $preroots));
1951 # Canonicalize the directories
1952 foreach my $preroot (@preroots) {
1953 # Always under the current webmin root
1954 $preroot =~ s/^.*\///g;
1955 $preroot = $roots[0].'/'.$preroot;
1958 # Look in the theme root directories first
1959 local ($full, @stfull);
1961 foreach my $preroot (@preroots) {
1964 $full = $preroot.$sofar;
1965 $scriptname = $simple;
1966 foreach $b (split(/\//, $simple)) {
1967 if ($b ne "") { $sofar .= "/$b"; }
1968 $full = $preroot.$sofar;
1969 @stfull = stat($full);
1970 if (!@stfull) { undef($full); last; }
1972 # Check if this is a directory
1974 # It is.. go on parsing
1982 # Check if this is a CGI program
1983 if (&get_type($full) eq "internal/cgi") {
1984 $pathinfo = substr($simple, length($sofar));
1985 $pathinfo .= "/" if ($page =~ /\/$/);
1986 $scriptname = $sofar;
1991 # Don't stop at a directory unless this is the last theme, which
1992 # is the 'real' one that provides the .cgi scripts
1993 if ($is_directory && $preroot ne $preroots[$#preroots]) {
2000 $cgi_pwd = $roots[0];
2002 elsif ($is_directory) {
2003 $cgi_pwd = "$roots[0]$sofar";
2006 "$roots[0]$sofar" =~ /^(.*\/)[^\/]+$/;
2009 $foundroot = $preroot;
2010 if ($is_directory) {
2011 # Check for index files in the directory
2013 foreach $idx (split(/\s+/, $config{"index_docs"})) {
2014 $idxfull = "$full/$idx";
2015 local @stidxfull = stat($idxfull);
2016 if (-r _ && !-d _) {
2018 @stfull = @stidxfull;
2021 if ($scriptname ne "/");
2026 @stfull = stat($full) if (!$foundidx);
2029 last if ($foundroot);
2031 print DEBUG "handle_request: initial full=$full\n";
2033 # Look in the real root directories, stopping when we find a file or directory
2034 if (!$full || $is_directory) {
2035 ROOT: foreach $root (@roots) {
2037 $full = $root.$sofar;
2038 $scriptname = $simple;
2039 foreach $b ($simple eq "/" ? ( "" ) : split(/\//, $simple)) {
2040 if ($b ne "") { $sofar .= "/$b"; }
2041 $full = $root.$sofar;
2042 @stfull = stat($full);
2047 # Check if this is a directory
2049 # It is.. go on parsing
2053 # Check if this is a CGI program
2054 if (&get_type($full) eq "internal/cgi") {
2055 $pathinfo = substr($simple, length($sofar));
2056 $pathinfo .= "/" if ($page =~ /\/$/);
2057 $scriptname = $sofar;
2062 # Run CGI in the same directory as whatever file
2064 $full =~ /^(.*\/)[^\/]+$/; $cgi_pwd = $1;
2073 if (!@stfull) { &http_error(404, "File not found"); }
2075 print DEBUG "handle_request: full=$full\n";
2076 @stfull = stat($full) if (!@stfull);
2078 # check filename against denyfile regexp
2079 local $denyfile = $config{'denyfile'};
2080 if ($denyfile && $full =~ /$denyfile/) {
2081 &http_error(403, "Access denied to $page");
2085 # Reached the end of the path OK.. see what we've got
2087 # See if the URL ends with a / as it should
2088 print DEBUG "handle_request: found a directory\n";
2089 if ($page !~ /\/$/) {
2090 # It doesn't.. redirect
2091 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2092 $ssl = $use_ssl || $config{'inetd_ssl'};
2093 $portstr = $port == 80 && !$ssl ? "" :
2094 $port == 443 && $ssl ? "" : ":$port";
2095 &write_data("Date: $datestr\r\n");
2096 &write_data("Server: $config{server}\r\n");
2097 $prot = $ssl ? "https" : "http";
2098 &write_data("Location: $prot://$host$portstr$page/\r\n");
2099 &write_keep_alive(0);
2100 &write_data("\r\n");
2101 &log_request($acpthost, $authuser, $reqline, 302, 0);
2104 # A directory.. check for index files
2106 foreach $idx (split(/\s+/, $config{"index_docs"})) {
2107 $idxfull = "$full/$idx";
2108 @stidxfull = stat($idxfull);
2109 if (-r _ && !-d _) {
2112 @stfull = @stidxfull;
2113 $scriptname .= "/" if ($scriptname ne "/");
2118 @stfull = stat($full) if (!$foundidx);
2121 # This is definately a directory.. list it
2122 print DEBUG "handle_request: listing directory\n";
2123 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2124 "Date: $datestr\r\n".
2125 "Server: $config{server}\r\n".
2126 "Content-type: text/html\r\n";
2128 &write_keep_alive(0);
2129 &write_data("\r\n");
2130 &reset_byte_count();
2131 &write_data("<h1>Index of $simple</h1>\n");
2132 &write_data("<pre>\n");
2133 &write_data(sprintf "%-35.35s %-20.20s %-10.10s\n",
2134 "Name", "Last Modified", "Size");
2135 &write_data("<hr>\n");
2136 opendir(DIR, $full);
2137 while($df = readdir(DIR)) {
2138 if ($df =~ /^\./) { next; }
2139 $fulldf = $full eq "/" ? $full.$df : $full."/".$df;
2140 (@stbuf = stat($fulldf)) || next;
2141 if (-d _) { $df .= "/"; }
2142 @tm = localtime($stbuf[9]);
2143 $fdate = sprintf "%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d",
2144 $tm[3],$tm[4]+1,$tm[5]+1900,
2145 $tm[0],$tm[1],$tm[2];
2146 $len = length($df); $rest = " "x(35-$len);
2148 "<a href=\"%s\">%-${len}.${len}s</a>$rest %-20.20s %-10.10s\n",
2149 $df, $df, $fdate, $stbuf[7]);
2152 &log_request($acpthost, $authuser, $reqline, $ok_code, &byte_count());
2156 # CGI or normal file
2158 if (&get_type($full) eq "internal/cgi" && $validated != 4) {
2159 # A CGI program to execute
2160 print DEBUG "handle_request: executing CGI\n";
2161 $envtz = $ENV{"TZ"};
2162 $envuser = $ENV{"USER"};
2163 $envpath = $ENV{"PATH"};
2164 $envlang = $ENV{"LANG"};
2165 $envroot = $ENV{"SystemRoot"};
2166 $envperllib = $ENV{'PERLLIB'};
2167 foreach my $k (keys %ENV) {
2170 $ENV{"PATH"} = $envpath if ($envpath);
2171 $ENV{"TZ"} = $envtz if ($envtz);
2172 $ENV{"USER"} = $envuser if ($envuser);
2173 $ENV{"OLD_LANG"} = $envlang if ($envlang);
2174 $ENV{"SystemRoot"} = $envroot if ($envroot);
2175 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
2176 $ENV{"HOME"} = $user_homedir;
2177 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
2178 $ENV{"SERVER_NAME"} = $host;
2179 $ENV{"SERVER_ADMIN"} = $config{"email"};
2180 $ENV{"SERVER_ROOT"} = $roots[0];
2181 $ENV{"SERVER_REALROOT"} = $realroot;
2182 $ENV{"SERVER_PORT"} = $port;
2183 $ENV{"REMOTE_HOST"} = $acpthost;
2184 $ENV{"REMOTE_ADDR"} = $acptip;
2185 $ENV{"REMOTE_ADDR_PROTOCOL"} = $ipv6 ? 6 : 4;
2186 $ENV{"REMOTE_USER"} = $authuser;
2187 $ENV{"BASE_REMOTE_USER"} = $authuser ne $baseauthuser ?
2188 $baseauthuser : undef;
2189 $ENV{"REMOTE_PASS"} = $authpass if (defined($authpass) &&
2190 $config{'pass_password'});
2191 if ($uinfo && $uinfo->{'proto'}) {
2192 $ENV{"REMOTE_USER_PROTO"} = $uinfo->{'proto'};
2193 $ENV{"REMOTE_USER_ID"} = $uinfo->{'id'};
2195 print DEBUG "REMOTE_USER = ",$ENV{"REMOTE_USER"},"\n";
2196 print DEBUG "BASE_REMOTE_USER = ",$ENV{"BASE_REMOTE_USER"},"\n";
2197 print DEBUG "proto=$uinfo->{'proto'} id=$uinfo->{'id'}\n" if ($uinfo);
2198 $ENV{"SSL_USER"} = $peername if ($validated == 2);
2199 $ENV{"ANONYMOUS_USER"} = "1" if ($validated == 3 || $validated == 4);
2200 $ENV{"DOCUMENT_ROOT"} = $roots[0];
2201 $ENV{"DOCUMENT_REALROOT"} = $realroot;
2202 $ENV{"GATEWAY_INTERFACE"} = "CGI/1.1";
2203 $ENV{"SERVER_PROTOCOL"} = "HTTP/1.0";
2204 $ENV{"REQUEST_METHOD"} = $method;
2205 $ENV{"SCRIPT_NAME"} = $scriptname;
2206 $ENV{"SCRIPT_FILENAME"} = $full;
2207 $ENV{"REQUEST_URI"} = $request_uri;
2208 $ENV{"PATH_INFO"} = $pathinfo;
2210 $ENV{"PATH_TRANSLATED"} = "$roots[0]$pathinfo";
2211 $ENV{"PATH_REALTRANSLATED"} = "$realroot$pathinfo";
2213 $ENV{"QUERY_STRING"} = $querystring;
2214 $ENV{"MINISERV_CONFIG"} = $config_file;
2215 $ENV{"HTTPS"} = "ON" if ($use_ssl || $config{'inetd_ssl'});
2216 $ENV{"MINISERV_PID"} = $miniserv_main_pid;
2217 $ENV{"SESSION_ID"} = $session_id if ($session_id);
2218 $ENV{"LOCAL_USER"} = $localauth_user if ($localauth_user);
2219 $ENV{"MINISERV_INTERNAL"} = $miniserv_internal if ($miniserv_internal);
2220 if (defined($header{"content-length"})) {
2221 $ENV{"CONTENT_LENGTH"} = $header{"content-length"};
2223 if (defined($header{"content-type"})) {
2224 $ENV{"CONTENT_TYPE"} = $header{"content-type"};
2226 foreach $h (keys %header) {
2227 ($hname = $h) =~ tr/a-z/A-Z/;
2229 $ENV{"HTTP_$hname"} = $header{$h};
2231 $ENV{"PWD"} = $cgi_pwd;
2232 foreach $k (keys %config) {
2233 if ($k =~ /^env_(\S+)$/) {
2234 $ENV{$1} = $config{$k};
2237 delete($ENV{'HTTP_AUTHORIZATION'});
2238 $ENV{'HTTP_COOKIE'} =~ s/;?\s*$sidname=([a-f0-9]+)//;
2239 $ENV{'MOBILE_DEVICE'} = 1 if ($mobile_device);
2241 # Check if the CGI can be handled internally
2243 local $first = <CGI>;
2245 $first =~ s/[#!\r\n]//g;
2246 $nph_script = ($full =~ /\/nph-([^\/]+)$/);
2248 if (!$config{'forkcgis'} &&
2249 ($first eq $perl_path || $first eq $linked_perl_path) &&
2251 $config{'internalcgis'}) {
2252 # setup environment for eval
2254 @ARGV = split(/\s+/, $queryargs);
2257 # Already read the post input
2258 $postinput = $posted_data;
2260 $clen = $header{"content-length"};
2261 $SIG{'CHLD'} = 'DEFAULT';
2263 # Have SOCK closed if the perl exec's something
2265 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
2269 if ($config{'log'}) {
2270 open(MINISERVLOG, ">>$config{'logfile'}");
2271 if ($config{'logperms'}) {
2272 chmod(oct($config{'logperms'}),
2273 $config{'logfile'});
2276 chmod(0600, $config{'logfile'});
2279 $doing_cgi_eval = 1;
2280 $main_process_id = $$;
2282 if ($full =~ /^\Q$foundroot\E\/([^\/]+)\//) {
2283 # Eval in package from Webmin module name
2285 $pkg =~ s/[^A-Za-z0-9]/_/g;
2290 tie(*STDOUT, 'miniserv');
2291 tie(*STDIN, 'miniserv');
2292 do \$miniserv::full;
2295 $doing_cgi_eval = 0;
2298 &http_error(500, "Perl execution failed",
2299 $config{'noshowstderr'} ? undef : $@);
2301 elsif (!$doneheaders && !$nph_script) {
2302 &http_error(500, "Missing Headers");
2309 # fork the process that actually executes the CGI
2310 pipe(CGIINr, CGIINw);
2311 pipe(CGIOUTr, CGIOUTw);
2312 pipe(CGIERRr, CGIERRw);
2313 if (!($cgipid = fork())) {
2314 @execargs = ( $full, split(/\s+/, $queryargs) );
2317 open(STDIN, "<&CGIINr");
2318 open(STDOUT, ">&CGIOUTw");
2319 open(STDERR, ">&CGIERRw");
2320 close(CGIINw); close(CGIOUTr); close(CGIERRr);
2322 die "Failed to exec $full : $!\n";
2325 close(CGIINr); close(CGIOUTw); close(CGIERRw);
2328 # write CGI input to a temp file
2329 $infile = "$config{'tempbase'}.$$";
2330 open(CGIINw, ">$infile");
2331 # NOT binary mode, as CGIs don't read in it!
2336 # already read the posted data
2337 print CGIINw $posted_data;
2339 $clen = $header{"content-length"};
2340 if ($method eq "POST" && $clen_read < $clen) {
2341 $SIG{'PIPE'} = 'IGNORE';
2343 while($got < $clen) {
2344 $buf = &read_data($clen-$got);
2345 if (!length($buf)) {
2346 kill('TERM', $cgipid);
2347 unlink($infile) if ($infile);
2348 &http_error(500, "Failed to read ".
2351 $got += length($buf);
2352 local ($wrote) = (print CGIINw $buf);
2355 # If the CGI terminated early, we still need to read
2356 # from the browser and throw away
2357 while($got < $clen) {
2358 $buf = &read_data($clen-$got);
2359 if (!length($buf)) {
2360 kill('TERM', $cgipid);
2361 unlink($infile) if ($infile);
2362 &http_error(500, "Failed to read ".
2365 $got += length($buf);
2367 $SIG{'PIPE'} = 'DEFAULT';
2373 # Run the CGI program, and feed it input
2375 local $qqueryargs = join(" ", map { "\"$_\"" }
2376 split(/\s+/, $queryargs));
2377 if ($first =~ /(perl|perl.exe)$/i) {
2378 # On Windows, run with Perl
2379 open(CGIOUTr, "$perl_path \"$full\" $qqueryargs <$infile |");
2382 open(CGIOUTr, "\"$full\" $qqueryargs <$infile |");
2388 # read back cgi headers
2389 select(CGIOUTr); $|=1; select(STDOUT);
2393 $line =~ s/\r|\n//g;
2395 if ($got_blank || %cgiheader) { last; }
2399 if ($line !~ /^(\S+):\s+(.*)$/) {
2400 $errs = &read_errors(CGIERRr);
2401 close(CGIOUTr); close(CGIERRr);
2402 unlink($infile) if ($infile);
2403 &http_error(500, "Bad Header", $errs);
2405 $cgiheader{lc($1)} = $2;
2406 push(@cgiheader, [ $1, $2 ]);
2408 if ($cgiheader{"location"}) {
2409 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2410 &write_data("Date: $datestr\r\n");
2411 &write_data("Server: $config{'server'}\r\n");
2412 &write_keep_alive(0);
2413 # ignore the rest of the output. This is a hack,
2414 # but is necessary for IE in some cases :(
2415 close(CGIOUTr); close(CGIERRr);
2417 elsif ($cgiheader{"content-type"} eq "") {
2418 close(CGIOUTr); close(CGIERRr);
2419 unlink($infile) if ($infile);
2420 $errs = &read_errors(CGIERRr);
2421 &http_error(500, "Missing Content-Type Header",
2422 $config{'noshowstderr'} ? undef : $errs);
2425 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2426 &write_data("Date: $datestr\r\n");
2427 &write_data("Server: $config{'server'}\r\n");
2428 &write_keep_alive(0);
2430 foreach $h (@cgiheader) {
2431 &write_data("$h->[0]: $h->[1]\r\n");
2433 &write_data("\r\n");
2435 &reset_byte_count();
2436 while($line = <CGIOUTr>) {
2441 unlink($infile) if ($infile);
2447 print DEBUG "handle_request: outputting file $full\n";
2448 $gzfile = $full.".gz";
2450 if ($config{'gzip'} ne '0' && -r $gzfile && $acceptenc{'gzip'}) {
2451 # Using gzipped version
2452 @stopen = stat($gzfile);
2453 if ($stopen[9] >= $stfull[9] && open(FILE, $gzfile)) {
2454 print DEBUG "handle_request: using gzipped $gzfile\n";
2459 # Using original file
2461 open(FILE, $full) || &http_error(404, "Failed to open file");
2465 # Build common headers
2466 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2467 "Date: $datestr\r\n".
2468 "Server: $config{server}\r\n".
2469 "Content-type: ".&get_type($full)."\r\n".
2470 "Last-Modified: ".&http_date($stopen[9])."\r\n".
2472 &http_date(time()+&get_expires_time($simple))."\r\n";
2474 if (!$gzipped && $use_gzip && $acceptenc{'gzip'} &&
2475 &should_gzip_file($full)) {
2476 # Load and compress file, then output
2477 print DEBUG "handle_request: outputting gzipped file $full\n";
2478 open(FILE, $full) || &http_error(404, "Failed to open file");
2484 @stopen = stat($file);
2485 $data = Compress::Zlib::memGzip($data);
2486 $resp .= "Content-length: ".length($data)."\r\n".
2487 "Content-Encoding: gzip\r\n";
2489 $rv = &write_keep_alive();
2490 &write_data("\r\n");
2491 &reset_byte_count();
2495 # Stream file output
2496 $resp .= "Content-length: $stopen[7]\r\n";
2497 $resp .= "Content-Encoding: gzip\r\n" if ($gzipped);
2499 $rv = &write_keep_alive();
2500 &write_data("\r\n");
2501 &reset_byte_count();
2502 my $bufsize = $config{'bufsize'} || 1024;
2503 while(read(FILE, $buf, $bufsize) > 0) {
2511 &log_request($acpthost, $authuser, $reqline,
2512 $logged_code ? $logged_code :
2513 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2517 # http_error(code, message, body, [dontexit])
2520 local $eh = $error_handler_recurse ? undef :
2521 $config{"error_handler_$_[0]"} ? $config{"error_handler_$_[0]"} :
2522 $config{'error_handler'} ? $config{'error_handler'} : undef;
2523 print DEBUG "http_error code=$_[0] message=$_[1] body=$_[2]\n";
2525 # Call a CGI program for the error
2527 $querystring = "code=$_[0]&message=".&urlize($_[1]).
2528 "&body=".&urlize($_[2]);
2529 $error_handler_recurse++;
2531 $ok_message = $_[1];
2535 # Use the standard error message display
2536 &write_data("HTTP/1.0 $_[0] $_[1]\r\n");
2537 &write_data("Server: $config{server}\r\n");
2538 &write_data("Date: $datestr\r\n");
2539 &write_data("Content-type: text/html\r\n");
2540 &write_keep_alive(0);
2541 &write_data("\r\n");
2542 &reset_byte_count();
2543 &write_data("<h1>Error - $_[1]</h1>\n");
2545 &write_data("<pre>$_[2]</pre>\n");
2548 &log_request($acpthost, $authuser, $reqline, $_[0], &byte_count())
2550 &log_error($_[1], $_[2] ? " : $_[2]" : "");
2557 if ($_[0] =~ /\.([A-z0-9]+)$/) {
2563 return "text/plain";
2566 # simplify_path(path, bogus)
2567 # Given a path, maybe containing stuff like ".." and "." convert it to a
2568 # clean, absolute form.
2571 local($dir, @bits, @fixedbits, $b);
2573 $dir =~ s/\\/\//g; # fix windows \ in path
2576 $dir =~ s/\0//g; # remove null bytes
2577 @bits = split(/\/+/, $dir);
2580 foreach $b (@bits) {
2584 elsif ($b eq ".." || $b eq "...") {
2586 if (scalar(@fixedbits) == 0) {
2594 push(@fixedbits, $b);
2597 return "/" . join('/', @fixedbits);
2601 # Converts a string from base64 format to normal
2604 local($str) = $_[0];
2606 $str =~ tr|A-Za-z0-9+=/||cd;
2608 $str =~ tr|A-Za-z0-9+/| -_|;
2609 while ($str =~ /(.{1,60})/gs) {
2610 my $len = chr(32 + length($1)*3/4);
2611 $res .= unpack("u", $len . $1 );
2616 # ip_match(remoteip, localip, [match]+)
2617 # Checks an IP address against a list of IPs, networks and networks/masks
2620 local(@io, @mo, @ms, $i, $j, $hn, $needhn);
2621 @io = &check_ip6address($_[0]) ? split(/:/, $_[0])
2622 : split(/\./, $_[0]);
2623 for($i=2; $i<@_; $i++) {
2624 $needhn++ if ($_[$i] =~ /^\*(\S+)$/);
2626 if ($needhn && !defined($hn = $ip_match_cache{$_[0]})) {
2627 # Reverse-lookup hostname if any rules match based on it
2628 $hn = &to_hostname($_[0]);
2629 if (&check_ip6address($_[0])) {
2630 $hn = "" if (&to_ip6address($hn) ne $_[0]);
2633 $hn = "" if (&to_ipaddress($hn) ne $_[0]);
2635 $ip_match_cache{$_[0]} = $hn;
2637 for($i=2; $i<@_; $i++) {
2638 local $mismatch = 0;
2639 if ($_[$i] =~ /^(\S+)\/(\d+)$/) {
2640 # Convert CIDR to netmask format
2641 $_[$i] = $1."/".&prefix_to_mask($2);
2643 if ($_[$i] =~ /^(\S+)\/(\S+)$/) {
2644 # Compare with IPv4 network/mask
2645 @mo = split(/\./, $1); @ms = split(/\./, $2);
2646 for($j=0; $j<4; $j++) {
2647 if ((int($io[$j]) & int($ms[$j])) != int($mo[$j])) {
2652 elsif ($_[$i] =~ /^\*(\S+)$/) {
2653 # Compare with hostname regexp
2654 $mismatch = 1 if ($hn !~ /$1$/);
2656 elsif ($_[$i] eq 'LOCAL' && &check_ipaddress($_[1])) {
2657 # Compare with local IPv4 network
2658 local @lo = split(/\./, $_[1]);
2660 $mismatch = 1 if ($lo[0] != $io[0]);
2662 elsif ($lo[0] < 192) {
2663 $mismatch = 1 if ($lo[0] != $io[0] ||
2667 $mismatch = 1 if ($lo[0] != $io[0] ||
2672 elsif ($_[$i] eq 'LOCAL' && &check_ip6address($_[1])) {
2673 # Compare with local IPv6 network, which is always first 4 words
2674 local @lo = split(/:/, $_[1]);
2675 for(my $i=0; $i<4; $i++) {
2676 $mismatch = 1 if ($lo[$i] ne $io[$i]);
2679 elsif ($_[$i] =~ /^[0-9\.]+$/) {
2680 # Compare with IPv4 address or network
2681 @mo = split(/\./, $_[$i]);
2682 while(@mo && !$mo[$#mo]) { pop(@mo); }
2683 for($j=0; $j<@mo; $j++) {
2684 if ($mo[$j] != $io[$j]) {
2689 elsif ($_[$i] =~ /^[a-f0-9:]+$/) {
2690 # Compare with IPv6 address or network
2691 @mo = split(/:/, $_[$i]);
2692 while(@mo && !$mo[$#mo]) { pop(@mo); }
2693 for($j=0; $j<@mo; $j++) {
2694 if ($mo[$j] ne $io[$j]) {
2699 elsif ($_[$i] !~ /^[0-9\.]+$/) {
2700 # Compare with hostname
2701 $mismatch = 1 if ($_[0] ne &to_ipaddress($_[$i]));
2703 return 1 if (!$mismatch);
2708 # users_match(&uinfo, user, ...)
2709 # Returns 1 if a user is in a list of users and groups
2712 local $uinfo = shift(@_);
2714 local @ginfo = getgrgid($uinfo->[3]);
2716 if ($u =~ /^\@(\S+)$/) {
2717 return 1 if (&is_group_member($uinfo, $1));
2719 elsif ($u =~ /^(\d*)-(\d*)$/ && ($1 || $2)) {
2720 return (!$1 || $uinfo[2] >= $1) &&
2721 (!$2 || $uinfo[2] <= $2);
2724 return 1 if ($u eq $uinfo->[0]);
2730 # restart_miniserv()
2731 # Called when a SIGHUP is received to restart the web server. This is done
2732 # by exec()ing perl with the same command line as was originally used
2733 sub restart_miniserv
2735 print STDERR "restarting miniserv\n";
2736 &log_error("Restarting");
2738 &close_all_sockets();
2740 dbmclose(%sessiondb);
2741 kill('KILL', $logclearer) if ($logclearer);
2742 kill('KILL', $extauth) if ($extauth);
2743 exec($perl_path, $miniserv_path, @miniserv_argv);
2744 die "Failed to restart miniserv with $perl_path $miniserv_path";
2757 # to_ipaddress(address, ...)
2762 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2763 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/ || $i =~ /^[a-f0-9:]+$/) {
2764 # A pattern or IP, not a hostname, so don't change
2769 push(@rv, join('.', unpack("CCCC", inet_aton($i))));
2772 return wantarray ? @rv : $rv[0];
2775 # to_ip6address(address, ...)
2780 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2781 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/ || $i =~ /^[a-f0-9:]+$/) {
2782 # A pattern, not a hostname, so don't change
2786 # Lookup IPv6 address
2787 local ($inaddr, $addr);
2788 (undef, undef, undef, $inaddr) =
2789 getaddrinfo($i, undef, Socket6::AF_INET6(), SOCK_STREAM);
2794 (undef, $addr) = unpack_sockaddr_in6($inaddr);
2795 push(@rv, inet_ntop(Socket6::AF_INET6(), $addr));
2799 return wantarray ? @rv : $rv[0];
2802 # to_hostname(ipv4|ipv6-address)
2803 # Reverse-resolves an IPv4 or 6 address to a hostname
2807 if (&check_ip6address($_[0])) {
2808 return gethostbyaddr(inet_pton(Socket6::AF_INET6(), $addr),
2809 Socket6::AF_INET6());
2812 return gethostbyaddr(inet_aton($addr), AF_INET);
2816 # read_line(no-wait, no-limit)
2817 # Reads one line from SOCK or SSL
2820 local ($nowait, $nolimit) = @_;
2821 local($idx, $more, $rv);
2822 while(($idx = index($main::read_buffer, "\n")) < 0) {
2823 if (length($main::read_buffer) > 10000 && !$nolimit) {
2824 &http_error(414, "Request too long",
2825 "Received excessive line <pre>$main::read_buffer</pre>");
2828 # need to read more..
2829 &wait_for_data_error() if (!$nowait);
2831 $more = Net::SSLeay::read($ssl_con);
2834 my $bufsize = $config{'bufsize'} || 1024;
2835 local $ok = sysread(SOCK, $more, $bufsize);
2836 $more = undef if ($ok <= 0);
2840 $rv = $main::read_buffer;
2841 undef($main::read_buffer);
2844 $main::read_buffer .= $more;
2846 $rv = substr($main::read_buffer, 0, $idx+1);
2847 $main::read_buffer = substr($main::read_buffer, $idx+1);
2852 # Reads up to some amount of data from SOCK or the SSL connection
2856 if (length($main::read_buffer)) {
2857 if (length($main::read_buffer) > $_[0]) {
2858 # Return the first part of the buffer
2859 $rv = substr($main::read_buffer, 0, $_[0]);
2860 $main::read_buffer = substr($main::read_buffer, $_[0]);
2864 # Return the whole buffer
2865 $rv = $main::read_buffer;
2866 undef($main::read_buffer);
2871 # Call SSL read function
2872 return Net::SSLeay::read($ssl_con, $_[0]);
2875 # Just do a normal read
2877 sysread(SOCK, $buf, $_[0]) || return undef;
2883 # Read a line from a file handle, using sysread to get a byte at a time
2890 $got = sysread($fh, $buf, 1);
2891 last if ($got <= 0);
2893 last if ($buf eq "\n");
2898 # wait_for_data(secs)
2899 # Waits at most the given amount of time for some data on SOCK, returning
2900 # 0 if not found, 1 if some arrived.
2904 vec($rmask, fileno(SOCK), 1) = 1;
2905 local $got = select($rmask, undef, undef, $_[0]);
2906 return $got == 0 ? 0 : 1;
2909 # wait_for_data_error()
2910 # Waits 60 seconds for data on SOCK, and fails if none arrives
2911 sub wait_for_data_error
2913 local $got = &wait_for_data(60);
2915 &http_error(400, "Timeout",
2916 "Waited more than 60 seconds for request data");
2920 # write_data(data, ...)
2921 # Writes a string to SOCK or the SSL connection
2924 local $str = join("", @_);
2926 Net::SSLeay::write($ssl_con, $str);
2929 syswrite(SOCK, $str, length($str));
2931 # Intentionally introduce a small delay to avoid problems where IE reports
2932 # the page as empty / DNS failed when it get a large response too quickly!
2933 select(undef, undef, undef, .01) if ($write_data_count%10 == 0);
2934 $write_data_count += length($str);
2937 # reset_byte_count()
2938 sub reset_byte_count { $write_data_count = 0; }
2941 sub byte_count { return $write_data_count; }
2943 # log_request(hostname, user, request, code, bytes)
2946 if ($config{'log'}) {
2947 local ($user, $ident, $headers);
2948 if ($config{'logident'}) {
2949 # add support for rfc1413 identity checking here
2951 else { $ident = "-"; }
2952 $user = $_[1] ? $_[1] : "-";
2953 local $dstr = &make_datestr();
2954 if (fileno(MINISERVLOG)) {
2955 seek(MINISERVLOG, 0, 2);
2958 open(MINISERVLOG, ">>$config{'logfile'}");
2959 chmod(0600, $config{'logfile'});
2961 if (defined($config{'logheaders'})) {
2962 foreach $h (split(/\s+/, $config{'logheaders'})) {
2963 $headers .= " $h=\"$header{$h}\"";
2966 elsif ($config{'logclf'}) {
2967 $headers = " \"$header{'referer'}\" \"$header{'user-agent'}\"";
2972 print MINISERVLOG "$_[0] $ident $user [$dstr] \"$_[2]\" ",
2973 "$_[3] $_[4]$headers\n";
2981 local @tm = localtime(time());
2982 return sprintf "%2.2d/%s/%4.4d:%2.2d:%2.2d:%2.2d %s",
2983 $tm[3], $month[$tm[4]], $tm[5]+1900,
2984 $tm[2], $tm[1], $tm[0], $timezone;
2987 # log_error(message)
2991 print STDERR "[",&make_datestr(),"] ",
2992 $acpthost ? ( "[",$acpthost,"] " ) : ( ),
2993 $page ? ( $page," : " ) : ( ),
2997 # read_errors(handle)
2998 # Read and return all input from some filehandle
3001 local($fh, $_, $rv);
3003 while(<$fh>) { $rv .= $_; }
3007 sub write_keep_alive
3010 if ($config{'nokeepalive'}) {
3011 # Keep alives have been disabled in config
3014 elsif (@childpids > $config{'maxconns'}*.8) {
3015 # Disable because nearing process limit
3019 # Keep alive specified by caller
3023 # Keep alive determined by browser
3024 $mode = $header{'connection'} =~ /keep-alive/i;
3026 &write_data("Connection: ".($mode ? "Keep-Alive" : "close")."\r\n");
3032 kill('TERM', @childpids) if (@childpids);
3033 kill('KILL', $logclearer) if ($logclearer);
3034 kill('KILL', $extauth) if ($extauth);
3040 local @tm = gmtime($_[0]);
3041 return sprintf "%s, %d %s %d %2.2d:%2.2d:%2.2d GMT",
3042 $weekday[$tm[6]], $tm[3], $month[$tm[4]], $tm[5]+1900,
3043 $tm[2], $tm[1], $tm[0];
3048 my $i; bless \$i, shift;
3054 my($buf,$len,$offset) = @_;
3055 &write_to_sock(substr($buf, $offset, $len));
3056 $miniserv::page_capture_out .= substr($buf, $offset, $len)
3057 if ($miniserv::page_capture);
3064 my $buf = join(defined($,) ? $, : "", @_);
3065 $buf .= $\ if defined($\);
3066 &write_to_sock($buf);
3067 $miniserv::page_capture_out .= $buf
3068 if ($miniserv::page_capture);
3075 my $buf = sprintf $fmt, @_;
3076 &write_to_sock($buf);
3077 $miniserv::page_capture_out .= $buf
3078 if ($miniserv::page_capture);
3081 # Send back already read data while we have it, then read from SOCK
3085 my $bufref = \$_[0];
3088 if ($postpos < length($postinput)) {
3089 # Reading from already fetched array
3090 my $left = length($postinput) - $postpos;
3091 my $canread = $len > $left ? $left : $len;
3092 substr($$bufref, $offset, $canread) =
3093 substr($postinput, $postpos, $canread);
3094 $postpos += $canread;
3098 # Read from network socket
3099 local $data = &read_data($len);
3100 if ($data eq '' && $len) {
3102 print STDERR "finished reading - shutting down socket\n";
3105 substr($$bufref, $offset, length($data)) = $data;
3106 return length($data);
3112 #print STDERR "open() called - should never happen!\n";
3115 # Read a line of input
3119 if ($postpos < length($postinput) &&
3120 ($idx = index($postinput, "\n", $postpos)) >= 0) {
3121 # A line exists in the memory buffer .. use it
3122 my $line = substr($postinput, $postpos, $idx-$postpos+1);
3127 # Need to read from the socket
3129 if ($postpos < length($postinput)) {
3130 # Start with in-memory data
3131 $line = substr($postinput, $postpos);
3132 $postpos = length($postinput);
3134 my $nl = &read_line(0, 1);
3137 print STDERR "finished reading - shutting down socket\n";
3140 $line .= $nl if (defined($nl));
3145 # Read one character of input
3150 my $got = READ($r, \$buf, 1, 0);
3151 return $got > 0 ? $buf : undef;
3156 return fileno(SOCK);
3163 # write_to_sock(data, ...)
3168 if ($doneheaders || $miniserv::nph_script) {
3173 while(!$doneheaders && $headers =~ s/^([^\r\n]*)(\r)?\n//) {
3174 if ($1 =~ /^(\S+):\s+(.*)$/) {
3175 $cgiheader{lc($1)} = $2;
3176 push(@cgiheader, [ $1, $2 ]);
3178 elsif ($1 !~ /\S/) {
3182 &http_error(500, "Bad Header");
3186 if ($cgiheader{"location"}) {
3188 "HTTP/1.0 302 Moved Temporarily\r\n");
3189 &write_data("Date: $datestr\r\n");
3190 &write_data("Server: $config{server}\r\n");
3191 &write_keep_alive(0);
3193 elsif ($cgiheader{"content-type"} eq "") {
3194 &http_error(500, "Missing Content-Type Header");
3197 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
3198 &write_data("Date: $datestr\r\n");
3199 &write_data("Server: $config{server}\r\n");
3200 &write_keep_alive(0);
3202 foreach $h (@cgiheader) {
3203 &write_data("$h->[0]: $h->[1]\r\n");
3205 &write_data("\r\n");
3206 &reset_byte_count();
3207 &write_data($headers);
3215 local $cert = Net::SSLeay::X509_STORE_CTX_get_current_cert($_[1]);
3217 local $errnum = Net::SSLeay::X509_STORE_CTX_get_error($_[1]);
3218 $verified_client = 1 if (!$errnum);
3225 if ($doing_cgi_eval && $$ == $main_process_id) {
3226 # A CGI program called exit! This is a horrible hack to
3227 # finish up before really exiting
3230 close($PASSINw); close($PASSOUTw);
3231 &log_request($acpthost, $authuser, $reqline,
3232 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
3237 # Convert a string to a form ok for putting in a URL
3239 local($tmp, $tmp2, $c);
3242 while(($c = chop($tmp)) ne "") {
3243 if ($c !~ /[A-z0-9]/) {
3244 $c = sprintf("%%%2.2X", ord($c));
3251 # validate_user(username, password, host, remote-ip, webmin-port)
3252 # Checks if some username and password are valid. Returns the modified username,
3253 # the expired / temp pass flag, and the non-existence flag
3256 local ($user, $pass, $host, $actpip, $port) = @_;
3257 return ( ) if (!$user);
3258 print DEBUG "validate_user: user=$user pass=$pass host=$host\n";
3259 local ($canuser, $canmode, $notexist, $webminuser, $sudo) =
3260 &can_user_login($user, undef, $host);
3261 print DEBUG "validate_user: canuser=$canuser canmode=$canmode notexist=$notexist webminuser=$webminuser sudo=$sudo\n";
3263 # User doesn't even exist, so go no further
3264 return ( undef, 0, 1 );
3266 elsif ($canmode == 0) {
3267 # User does exist but cannot login
3268 return ( $canuser, 0, 0 );
3270 elsif ($canmode == 1) {
3271 # Attempt Webmin authentication
3272 my $uinfo = &get_user_details($webminuser);
3274 &password_crypt($pass, $uinfo->{'pass'}) eq $uinfo->{'pass'}) {
3275 # Password is valid .. but check for expiry
3276 local $lc = $uinfo->{'lastchanges'};
3277 print DEBUG "validate_user: Password is valid lc=$lc pass_maxdays=$config{'pass_maxdays'}\n";
3278 if ($config{'pass_maxdays'} && $lc && !$uinfo->{'nochange'}) {
3279 local $daysold = (time() - $lc)/(24*60*60);
3280 print DEBUG "maxdays=$config{'pass_maxdays'} daysold=$daysold temppass=$uinfo->{'temppass'}\n";
3281 if ($config{'pass_lockdays'} &&
3282 $daysold > $config{'pass_lockdays'}) {
3283 # So old that the account is locked
3284 return ( undef, 0, 0 );
3286 elsif ($daysold > $config{'pass_maxdays'}) {
3287 # Password has expired
3288 return ( $user, 1, 0 );
3291 if ($uinfo->{'temppass'}) {
3292 # Temporary password - force change now
3293 return ( $user, 2, 0 );
3295 return ( $user, 0, 0 );
3298 print DEBUG "validate_user: User $webminuser not found\n";
3299 return ( undef, 0, 0 );
3302 print DEBUG "validate_user: User $webminuser password mismatch $pass != $uinfo->{'pass'}\n";
3303 return ( undef, 0, 0 );
3306 elsif ($canmode == 2 || $canmode == 3) {
3307 # Attempt PAM or passwd file authentication
3308 local $val = &validate_unix_user($canuser, $pass, $acptip, $port);
3309 print DEBUG "validate_user: unix val=$val\n";
3310 if ($val && $sudo) {
3311 # Need to check if this Unix user can sudo
3312 if (!&check_sudo_permissions($canuser, $pass)) {
3313 print DEBUG "validate_user: sudo failed\n";
3317 print DEBUG "validate_user: sudo passed\n";
3320 return $val == 2 ? ( $canuser, 1, 0 ) :
3321 $val == 1 ? ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3323 elsif ($canmode == 4) {
3324 # Attempt external authentication
3325 return &validate_external_user($canuser, $pass) ?
3326 ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3334 # validate_unix_user(user, password, remote-ip, local-port)
3335 # Returns 1 if a username and password are valid under unix, 0 if not,
3336 # or 2 if the account has expired.
3337 # Checks PAM if available, and falls back to reading the system password
3339 sub validate_unix_user
3343 $pam_username = $_[0];
3344 $pam_password = $_[1];
3345 eval "use Authen::PAM;";
3346 local $pamh = new Authen::PAM($config{'pam'}, $pam_username,
3349 $pamh->pam_set_item("PAM_RHOST", $_[2]) if ($_[2]);
3350 $pamh->pam_set_item("PAM_TTY", $_[3]) if ($_[3]);
3351 local $pam_ret = $pamh->pam_authenticate();
3352 if ($pam_ret == PAM_SUCCESS()) {
3353 # Logged in OK .. make sure password hasn't expired
3354 local $acct_ret = $pamh->pam_acct_mgmt();
3355 if ($acct_ret == PAM_SUCCESS()) {
3356 $pamh->pam_open_session();
3359 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3360 $acct_ret == PAM_ACCT_EXPIRED()) {
3364 print STDERR "Unknown pam_acct_mgmt return value : $acct_ret\n";
3371 elsif ($config{'pam_only'}) {
3372 # Pam is not available, but configuration forces it's use!
3375 elsif ($config{'passwd_file'}) {
3376 # Check in a password file
3378 open(FILE, $config{'passwd_file'});
3379 if ($config{'passwd_file'} eq '/etc/security/passwd') {
3380 # Assume in AIX format
3383 if (/^\s*(\S+):/ && $1 eq $_[0]) {
3385 if (/^\s*password\s*=\s*(\S+)\s*$/) {
3386 $rv = $1 eq &password_crypt($_[1], $1) ?
3394 # Read the system password or shadow file
3396 local @l = split(/:/, $_, -1);
3397 local $u = $l[$config{'passwd_uindex'}];
3398 local $p = $l[$config{'passwd_pindex'}];
3400 $rv = $p eq &password_crypt($_[1], $p) ? 1 : 0;
3401 if ($config{'passwd_cindex'} ne '' && $rv) {
3402 # Password may have expired!
3403 local $c = $l[$config{'passwd_cindex'}];
3404 local $m = $l[$config{'passwd_mindex'}];
3405 local $day = time()/(24*60*60);
3406 if ($c =~ /^\d+/ && $m =~ /^\d+/ &&
3412 if ($p eq "" && $config{'passwd_blank'}) {
3413 # Force password change
3421 return $rv if ($rv);
3424 # Fallback option - check password returned by getpw*
3425 local @uinfo = getpwnam($_[0]);
3426 if ($uinfo[1] ne '' && &password_crypt($_[1], $uinfo[1]) eq $uinfo[1]) {
3430 return 0; # Totally failed
3433 # validate_external_user(user, pass)
3434 # Validate a user by passing the username and password to an external
3435 # squid-style authentication program
3436 sub validate_external_user
3438 return 0 if (!$config{'extauth'});
3440 local $str = "$_[0] $_[1]\n";
3441 syswrite(EXTAUTH, $str, length($str));
3442 local $resp = <EXTAUTH>;
3444 return $resp =~ /^OK/i ? 1 : 0;
3447 # can_user_login(username, no-append, host)
3448 # Checks if a user can login or not.
3449 # First return value is the username.
3450 # Second is 0 if cannot login, 1 if using Webmin pass, 2 if PAM, 3 if password
3451 # file, 4 if external.
3452 # Third is 1 if the user does not exist at all, 0 if he does.
3453 # Fourth is the Webmin username whose permissions apply, based on unixauth.
3454 # Fifth is a flag indicating if a sudo check is needed.
3457 local $uinfo = &get_user_details($_[0]);
3459 # See if this user exists in Unix and can be validated by the same
3460 # method as the unixauth webmin user
3461 local $realuser = $unixauth{$_[0]};
3465 eval { @uinfo = getpwnam($_[0]); }; # may fail on windows
3466 if (!$realuser && @uinfo) {
3467 # No unixauth entry for the username .. try his groups
3468 foreach my $ua (keys %unixauth) {
3469 if ($ua =~ /^\@(.*)$/) {
3470 if (&is_group_member(\@uinfo, $1)) {
3471 $realuser = $unixauth{$ua};
3477 if (!$realuser && @uinfo) {
3478 # Fall back to unix auth for all Unix users
3479 $realuser = $unixauth{"*"};
3481 if (!$realuser && $use_sudo && @uinfo) {
3482 # Allow login effectively as root, if sudo permits it
3486 if (!$realuser && !@uinfo && $config{'pamany'}) {
3487 # If the user completely doesn't exist, we can still allow
3488 # him to authenticate via PAM
3489 $realuser = $config{'pamany'};
3493 # For Usermin, always fall back to unix auth for any user,
3494 # so that later checks with domain added / removed are done.
3495 $realuser = $unixauth{"*"};
3497 return (undef, 0, 1, undef) if (!$realuser);
3498 local $uinfo = &get_user_details($realuser);
3499 return (undef, 0, 1, undef) if (!$uinfo);
3500 local $up = $uinfo->{'pass'};
3502 # Work out possible domain names from the hostname
3503 local @doms = ( $_[2] );
3504 if ($_[2] =~ /^([^\.]+)\.(\S+)$/) {
3508 if ($config{'user_mapping'} && !%user_mapping) {
3509 # Read the user mapping file
3511 open(MAPPING, $config{'user_mapping'});
3515 if (/^(\S+)\s+(\S+)/) {
3516 if ($config{'user_mapping_reverse'}) {
3517 $user_mapping{$1} = $2;
3520 $user_mapping{$2} = $1;
3527 # Check the user mapping file to see if there is an entry for the
3528 # user login in which specifies a new effective user
3530 foreach my $d (@doms) {
3531 $um ||= $user_mapping{"$_[0]\@$d"};
3533 $um ||= $user_mapping{$_[0]};
3534 if (defined($um) && ($_[1]&4) == 0) {
3535 # A mapping exists - use it!
3536 return &can_user_login($um, $_[1]+4, $_[2]);
3539 # Check if a user with the entered login and the domains appended
3540 # or prepended exists, and if so take it to be the effective user
3541 if (!@uinfo && $config{'domainuser'}) {
3542 # Try again with name.domain and name.firstpart
3543 local @firsts = map { /^([^\.]+)/; $1 } @doms;
3544 if (($_[1]&1) == 0) {
3546 foreach $a (@firsts, @doms) {
3547 foreach $p ("$_[0].${a}", "$_[0]-${a}",
3548 "${a}.$_[0]", "${a}-$_[0]",
3549 "$_[0]_${a}", "${a}_$_[0]") {
3550 local @vu = &can_user_login(
3551 $p, $_[1]+1, $_[2]);
3552 return @vu if ($vu[1]);
3558 # Check if the user entered a domain at the end of his username when
3559 # he really shouldn't have, and if so try without it
3560 if (!@uinfo && $config{'domainstrip'} &&
3561 $_[0] =~ /^(\S+)\@(\S+)$/ && ($_[1]&2) == 0) {
3562 local ($stripped, $dom) = ($1, $2);
3563 local @vu = &can_user_login($stripped, $_[1] + 2, $_[2]);
3564 return @vu if ($vu[1]);
3565 local @vu = &can_user_login($stripped, $_[1] + 2, $dom);
3566 return @vu if ($vu[1]);
3569 return ( undef, 0, 1, undef ) if (!@uinfo && !$pamany);
3572 if (scalar(@allowusers)) {
3573 # Only allow people on the allow list
3574 return ( undef, 0, 0, undef )
3575 if (!&users_match(\@uinfo, @allowusers));
3577 elsif (scalar(@denyusers)) {
3578 # Disallow people on the deny list
3579 return ( undef, 0, 0, undef )
3580 if (&users_match(\@uinfo, @denyusers));
3582 if ($config{'shells_deny'}) {
3584 open(SHELLS, $config{'shells_deny'});
3588 $found++ if ($_ eq $uinfo[8]);
3591 return ( undef, 0, 0, undef ) if (!$found);
3596 # PAM or passwd file authentication
3597 print DEBUG "can_user_login: Validate with PAM\n";
3598 return ( $_[0], $use_pam ? 2 : 3, 0, $realuser, $sudo );
3600 elsif ($up eq 'e') {
3601 # External authentication
3602 print DEBUG "can_user_login: Validate externally\n";
3603 return ( $_[0], 4, 0, $realuser, $sudo );
3606 # Fixed Webmin password
3607 print DEBUG "can_user_login: Validate by Webmin\n";
3608 return ( $_[0], 1, 0, $realuser, $sudo );
3611 elsif ($uinfo->{'pass'} eq 'x') {
3612 # Webmin user authenticated via PAM or password file
3613 return ( $_[0], $use_pam ? 2 : 3, 0, $_[0] );
3615 elsif ($uinfo->{'pass'} eq 'e') {
3616 # Webmin user authenticated externally
3617 return ( $_[0], 4, 0, $_[0] );
3620 # Normal Webmin user
3621 return ( $_[0], 1, 0, $_[0] );
3625 # the PAM conversation function for interactive logins
3628 $pam_conv_func_called++;
3635 $ans = $pam_username if ($code == PAM_PROMPT_ECHO_ON() );
3636 $ans = $pam_password if ($code == PAM_PROMPT_ECHO_OFF() );
3638 push @res, PAM_SUCCESS();
3641 push @res, PAM_SUCCESS();
3650 # get_socket_ip(handle, ipv6-flag)
3651 # Returns the local IP address of some connection, as both a string and in
3655 local ($fh, $ipv6) = @_;
3656 local $sn = getsockname($fh);
3657 return undef if (!$sn);
3658 return &get_address_ip($sn, $ipv6);
3661 # get_address_ip(address, ipv6-flag)
3662 # Given a sockaddr object in binary format, return the binary address, text
3663 # address and port number
3666 local ($sn, $ipv6) = @_;
3668 local ($p, $b) = unpack_sockaddr_in6($sn);
3669 return ($b, inet_ntop(Socket6::AF_INET6(), $b), $p);
3672 local ($p, $b) = unpack_sockaddr_in($sn);
3673 return ($b, inet_ntoa($b), $p);
3677 # get_socket_name(handle, ipv6-flag)
3678 # Returns the local hostname or IP address of some connection
3681 local ($fh, $ipv6) = @_;
3682 return $config{'host'} if ($config{'host'});
3683 local ($mybin, $myaddr) = &get_socket_ip($fh, $ipv6);
3684 if (!$get_socket_name_cache{$myaddr}) {
3686 if (!$config{'no_resolv_myname'}) {
3687 $myname = gethostbyaddr($mybin,
3688 $ipv6 ? Socket6::AF_INET6() : AF_INET);
3690 $myname ||= $myaddr;
3691 $get_socket_name_cache{$myaddr} = $myname;
3693 return $get_socket_name_cache{$myaddr};
3696 # run_login_script(username, sid, remoteip, localip)
3697 sub run_login_script
3699 if ($config{'login_script'}) {
3700 system($config{'login_script'}.
3701 " ".join(" ", map { quotemeta($_) || '""' } @_).
3702 " >/dev/null 2>&1 </dev/null");
3706 # run_logout_script(username, sid, remoteip, localip)
3707 sub run_logout_script
3709 if ($config{'logout_script'}) {
3710 system($config{'logout_script'}.
3711 " ".join(" ", map { quotemeta($_) || '""' } @_).
3712 " >/dev/null 2>&1 </dev/null");
3716 # close_all_sockets()
3717 # Closes all the main listening sockets
3718 sub close_all_sockets
3721 foreach $s (@socketfhs) {
3727 # Close all pipes for talking to sub-processes
3731 foreach $p (@passin) { close($p); }
3732 foreach $p (@passout) { close($p); }
3733 foreach $p (values %conversations) {
3734 if ($p->{'PAMOUTr'}) {
3735 close($p->{'PAMOUTr'});
3736 close($p->{'PAMINw'});
3741 # check_user_ip(user)
3742 # Returns 1 if some user is allowed to login from the accepting IP, 0 if not
3745 local ($username) = @_;
3746 local $uinfo = &get_user_details($username);
3747 return 1 if (!$uinfo);
3748 if ($uinfo->{'deny'} &&
3749 &ip_match($acptip, $localip, @{$uinfo->{'deny'}}) ||
3750 $uinfo->{'allow'} &&
3751 !&ip_match($acptip, $localip, @{$uinfo->{'allow'}})) {
3757 # check_user_time(user)
3758 # Returns 1 if some user is allowed to login at the current date and time
3761 local ($username) = @_;
3762 local $uinfo = &get_user_details($username);
3763 return 1 if (!$uinfo || !$uinfo->{'allowdays'} && !$uinfo->{'allowhours'});
3764 local @tm = localtime(time());
3765 if ($uinfo->{'allowdays'}) {
3766 # Make sure day is allowed
3767 return 0 if (&indexof($tm[6], @{$uinfo->{'allowdays'}}) < 0);
3769 if ($uinfo->{'allowhours'}) {
3770 # Make sure time is allowed
3771 local $m = $tm[2]*60+$tm[1];
3772 return 0 if ($m < $uinfo->{'allowhours'}->[0] ||
3773 $m > $uinfo->{'allowhours'}->[1]);
3778 # generate_random_id(password, [force-urandom])
3779 # Returns a random session ID number
3780 sub generate_random_id
3782 local ($pass, $force_urandom) = @_;
3784 if (!$bad_urandom) {
3785 # First try /dev/urandom, unless we have marked it as bad
3786 $SIG{ALRM} = "miniserv::urandom_timeout";
3788 if (open(RANDOM, "/dev/urandom")) {
3790 if (read(RANDOM, $tmpsid, 16) == 16) {
3791 $sid = lc(unpack('h*',$tmpsid));
3797 if (!$sid && !$force_urandom) {
3800 foreach $c (split(//, &unix_crypt($pass, substr($$, -2)))) {
3801 $sid += ord($c) * $mul;
3808 # handle_login(username, ok, expired, not-exists, password, [no-test-cookie])
3809 # Called from handle_session to either mark a user as logged in, or not
3812 local ($vu, $ok, $expired, $nonexist, $pass, $notest) = @_;
3813 $authuser = $vu if ($ok);
3815 # check if the test cookie is set
3816 if ($header{'cookie'} !~ /testing=1/ && $vu &&
3817 !$config{'no_testing_cookie'} && !$notest) {
3818 &http_error(500, "No cookies",
3819 "Your browser does not support cookies, ".
3820 "which are required for this web server to ".
3821 "work in session authentication mode");
3824 # check with main process for delay
3825 if ($config{'passdelay'} && $vu) {
3826 print DEBUG "handle_login: requesting delay vu=$vu acptip=$acptip ok=$ok\n";
3827 print $PASSINw "delay $vu $acptip $ok\n";
3828 <$PASSOUTr> =~ /(\d+) (\d+)/;
3831 print DEBUG "handle_login: delay=$1 blocked=$2\n";
3834 if ($ok && (!$expired ||
3835 $config{'passwd_mode'} == 1)) {
3836 # Logged in OK! Tell the main process about
3838 local $sid = &generate_random_id($pass);
3839 print DEBUG "handle_login: sid=$sid\n";
3840 print $PASSINw "new $sid $authuser $acptip\n";
3842 # Run the post-login script, if any
3843 &run_login_script($authuser, $sid,
3846 # Check for a redirect URL for the user
3847 local $rurl = &login_redirect($authuser, $pass, $host);
3848 print DEBUG "handle_login: redirect URL rurl=$rurl\n";
3850 # Got one .. go to it
3851 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3852 &write_data("Date: $datestr\r\n");
3853 &write_data("Server: $config{'server'}\r\n");
3854 &write_data("Location: $rurl\r\n");
3855 &write_keep_alive(0);
3856 &write_data("\r\n");
3857 &log_request($acpthost, $authuser, $reqline, 302, 0);
3860 # Set cookie and redirect to originally requested page
3861 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3862 &write_data("Date: $datestr\r\n");
3863 &write_data("Server: $config{'server'}\r\n");
3864 local $ssl = $use_ssl || $config{'inetd_ssl'};
3865 $portstr = $port == 80 && !$ssl ? "" :
3866 $port == 443 && $ssl ? "" : ":$port";
3867 $prot = $ssl ? "https" : "http";
3868 local $sec = $ssl ? "; secure" : "";
3869 #$sec .= "; httpOnly";
3870 if ($in{'page'} !~ /^\/[A-Za-z0-9\/\.\-\_]+$/) {
3871 # Make redirect URL safe
3875 &write_data("Set-Cookie: $sidname=$sid; path=/; expires=\"Thu, 31-Dec-2037 00:00:00\"$sec\r\n");
3878 &write_data("Set-Cookie: $sidname=$sid; path=/$sec\r\n");
3880 &write_data("Location: $prot://$host$portstr$in{'page'}\r\n");
3881 &write_keep_alive(0);
3882 &write_data("\r\n");
3883 &log_request($acpthost, $authuser, $reqline, 302, 0);
3884 syslog("info", "%s", "Successful login as $authuser from $acpthost") if ($use_syslog);
3885 &write_login_utmp($authuser, $acpthost);
3889 elsif ($ok && $expired &&
3890 ($config{'passwd_mode'} == 2 || $expired == 2)) {
3891 # Login was ok, but password has expired or was temporary. Need
3892 # to force display of password change form.
3895 $querystring = "&user=".&urlize($vu).
3897 "&expired=".$expired;
3900 $page = $config{'password_form'};
3902 $miniserv_internal = 2;
3903 syslog("crit", "%s",
3904 "Expired login as $vu ".
3905 "from $acpthost") if ($use_syslog);
3908 # Login failed, or password has expired. The login form will be
3909 # displayed again by later code
3911 $request_uri = $in{'page'};
3912 $already_session_id = undef;
3914 $authuser = $baseauthuser = undef;
3915 syslog("crit", "%s",
3916 ($nonexist ? "Non-existent" :
3917 $expired ? "Expired" : "Invalid").
3918 " login as $vu from $acpthost")
3924 # write_login_utmp(user, host)
3925 # Record the login by some user in utmp
3926 sub write_login_utmp
3929 # Write utmp record for login
3930 %utmp = ( 'ut_host' => $_[1],
3931 'ut_time' => time(),
3933 'ut_type' => 7, # user process
3934 'ut_pid' => $main_process_id,
3935 'ut_line' => $config{'pam'},
3937 if (defined(&User::Utmp::putut)) {
3938 User::Utmp::putut(\%utmp);
3941 User::Utmp::pututline(\%utmp);
3946 # write_logout_utmp(user, host)
3947 # Record the logout by some user in utmp
3948 sub write_logout_utmp
3951 # Write utmp record for logout
3952 %utmp = ( 'ut_host' => $_[1],
3953 'ut_time' => time(),
3955 'ut_type' => 8, # dead process
3956 'ut_pid' => $main_process_id,
3957 'ut_line' => $config{'pam'},
3959 if (defined(&User::Utmp::putut)) {
3960 User::Utmp::putut(\%utmp);
3963 User::Utmp::pututline(\%utmp);
3968 # pam_conversation_process(username, write-pipe, read-pipe)
3969 # This function is called inside a sub-process to communicate with PAM. It sends
3970 # questions down one pipe, and reads responses from another
3971 sub pam_conversation_process
3973 local ($user, $writer, $reader) = @_;
3974 $miniserv::pam_conversation_process_writer = $writer;
3975 $miniserv::pam_conversation_process_reader = $reader;
3976 eval "use Authen::PAM;";
3977 local $convh = new Authen::PAM(
3978 $config{'pam'}, $user, \&miniserv::pam_conversation_process_func);
3979 local $pam_ret = $convh->pam_authenticate();
3980 if ($pam_ret == PAM_SUCCESS()) {
3981 local $acct_ret = $convh->pam_acct_mgmt();
3982 if ($acct_ret == PAM_SUCCESS()) {
3983 $convh->pam_open_session();
3984 print $writer "x2 $user 1 0 0\n";
3986 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3987 $acct_ret == PAM_ACCT_EXPIRED()) {
3988 print $writer "x2 $user 1 1 0\n";
3991 print $writer "x0 Unknown PAM account status $acct_ret\n";
3995 print $writer "x2 $user 0 0 0\n";
4000 # pam_conversation_process_func(type, message, [type, message, ...])
4001 # A pipe that talks to both PAM and the master process
4002 sub pam_conversation_process_func
4005 select($miniserv::pam_conversation_process_writer); $| = 1; select(STDOUT);
4007 local ($type, $msg) = (shift, shift);
4009 local $ok = (print $miniserv::pam_conversation_process_writer "$type $msg\n");
4010 print $miniserv::pam_conversation_process_writer "\n";
4011 local $answer = <$miniserv::pam_conversation_process_reader>;
4012 $answer =~ s/\r|\n//g;
4013 push(@rv, PAM_SUCCESS(), $answer);
4015 push(@rv, PAM_SUCCESS());
4020 # Returns 4 new pipe file handles
4023 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
4025 local %taken = ( (map { $_, 1 } @passin),
4026 (map { $_->{'PASSINr'} } values %conversations) );
4027 for($p=0; $taken{"PASSINr$p"}; $p++) { }
4028 $PASSINr = "PASSINr$p";
4029 $PASSINw = "PASSINw$p";
4030 $PASSOUTr = "PASSOUTr$p";
4031 $PASSOUTw = "PASSOUTw$p";
4032 pipe($PASSINr, $PASSINw);
4033 pipe($PASSOUTr, $PASSOUTw);
4034 select($PASSINw); $| = 1;
4035 select($PASSINr); $| = 1;
4036 select($PASSOUTw); $| = 1;
4037 select($PASSOUTw); $| = 1;
4039 return ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
4042 # recv_pam_question(&conv, fd)
4043 # Reads one PAM question from the sub-process, and sends it to the HTTP handler.
4044 # Returns 0 if the conversation is over, 1 if not.
4045 sub recv_pam_question
4047 local ($conf, $fh) = @_;
4048 local $pr = $conf->{'PAMOUTr'};
4049 select($pr); $| = 1; select(STDOUT);
4050 local $line = <$pr>;
4051 $line =~ s/\r|\n//g;
4054 $line =~ s/\r|\n//g;
4056 $conf->{'last'} = time();
4059 print $fh "0 PAM conversation error\n";
4063 local ($type, $msg) = split(/\s+/, $line, 2);
4064 if ($type =~ /^x(\d+)/) {
4065 # Pass this status code through
4066 print $fh "$1 $msg\n";
4067 return $1 == 2 || $1 == 0 ? 0 : 1;
4069 elsif ($type == PAM_PROMPT_ECHO_ON()) {
4071 print $fh "1 $msg\n";
4074 elsif ($type == PAM_PROMPT_ECHO_OFF()) {
4076 print $fh "3 $msg\n";
4079 elsif ($type == PAM_ERROR_MSG() || $type == PAM_TEXT_INFO()) {
4080 # A message that does not require a response
4081 print $fh "4 $msg\n";
4086 print $fh "0 Unknown PAM message type $type\n";
4092 # send_pam_answer(&conv, answer)
4093 # Sends a response from the user to the PAM sub-process
4096 local ($conf, $answer) = @_;
4097 local $pw = $conf->{'PAMINw'};
4098 $conf->{'last'} = time();
4099 print $pw "$answer\n";
4102 # end_pam_conversation(&conv)
4103 # Clean up PAM conversation pipes and processes
4104 sub end_pam_conversation
4107 kill('KILL', $conv->{'pid'}) if ($conv->{'pid'});
4108 if ($conv->{'PAMINr'}) {
4109 close($conv->{'PAMINr'});
4110 close($conv->{'PAMOUTr'});
4111 close($conv->{'PAMINw'});
4112 close($conv->{'PAMOUTw'});
4114 delete($conversations{$conv->{'cid'}});
4117 # get_ipkeys(&miniserv)
4118 # Returns a list of IP address to key file mappings from a miniserv.conf entry
4122 foreach $k (keys %{$_[0]}) {
4123 if ($k =~ /^ipkey_(\S+)/) {
4124 local $ipkey = { 'ips' => [ split(/,/, $1) ],
4125 'key' => $_[0]->{$k},
4126 'index' => scalar(@rv) };
4127 $ipkey->{'cert'} = $_[0]->{'ipcert_'.$1};
4134 # create_ssl_context(keyfile, [certfile])
4135 sub create_ssl_context
4137 local ($keyfile, $certfile) = @_;
4139 eval { $ssl_ctx = Net::SSLeay::new_x_ctx() };
4140 $ssl_ctx ||= Net::SSLeay::CTX_new();
4141 $ssl_ctx || die "Failed to create SSL context : $!";
4142 if ($client_certs) {
4143 Net::SSLeay::CTX_load_verify_locations(
4144 $ssl_ctx, $config{'ca'}, "");
4145 Net::SSLeay::CTX_set_verify(
4146 $ssl_ctx, &Net::SSLeay::VERIFY_PEER, \&verify_client);
4148 if ($config{'extracas'}) {
4150 foreach $p (split(/\s+/, $config{'extracas'})) {
4151 Net::SSLeay::CTX_load_verify_locations(
4156 Net::SSLeay::CTX_use_RSAPrivateKey_file(
4158 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL key $keyfile";
4159 Net::SSLeay::CTX_use_certificate_file(
4160 $ssl_ctx, $certfile || $keyfile,
4161 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL cert $certfile";
4166 # ssl_connection_for_ip(socket, ipv6-flag)
4167 # Returns a new SSL connection object for some socket, or undef if failed
4168 sub ssl_connection_for_ip
4170 local ($sock, $ipv6) = @_;
4171 local $sn = getsockname($sock);
4173 print STDERR "Failed to get address for socket $sock\n";
4176 local (undef, $myip, undef) = &get_address_ip($sn, $ipv6);
4177 local $ssl_ctx = $ssl_contexts{$myip} || $ssl_contexts{"*"};
4178 local $ssl_con = Net::SSLeay::new($ssl_ctx);
4179 if ($config{'ssl_cipher_list'}) {
4180 # Force use of ciphers
4181 eval "Net::SSLeay::set_cipher_list(
4182 \$ssl_con, \$config{'ssl_cipher_list'})";
4184 print STDERR "SSL cipher $config{'ssl_cipher_list'} failed : ",
4190 Net::SSLeay::set_fd($ssl_con, fileno($sock));
4191 if (!Net::SSLeay::accept($ssl_con)) {
4192 print STDERR "Failed to initialize SSL connection\n";
4198 # login_redirect(username, password, host)
4199 # Calls the login redirect script (if configured), which may output a URL to
4200 # re-direct a user to after logging in.
4203 return undef if (!$config{'login_redirect'});
4204 local $quser = quotemeta($_[0]);
4205 local $qpass = quotemeta($_[1]);
4206 local $qhost = quotemeta($_[2]);
4207 local $url = `$config{'login_redirect'} $quser $qpass $qhost`;
4212 # reload_config_file()
4213 # Re-read %config, and call post-config actions
4214 sub reload_config_file
4216 &log_error("Reloading configuration");
4217 %config = &read_config_file($config_file);
4218 &update_vital_config();
4221 &build_config_mappings();
4222 &read_webmin_crons();
4224 if ($config{'session'}) {
4225 dbmclose(%sessiondb);
4226 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
4230 # read_config_file(file)
4231 # Reads the given config file, and returns a hash of values
4232 sub read_config_file
4235 open(CONF, $_[0]) || die "Failed to open config file $_[0] : $!";
4238 if (/^#/ || !/\S/) { next; }
4240 $name = $1; $val = $2;
4241 $name =~ s/^\s+//g; $name =~ s/\s+$//g;
4242 $val =~ s/^\s+//g; $val =~ s/\s+$//g;
4249 # update_vital_config()
4250 # Updates %config with defaults, and dies if something vital is missing
4251 sub update_vital_config
4253 my %vital = ("port", 80,
4255 "server", "MiniServ/0.01",
4256 "index_docs", "index.html index.htm index.cgi index.php",
4257 "addtype_html", "text/html",
4258 "addtype_txt", "text/plain",
4259 "addtype_gif", "image/gif",
4260 "addtype_jpg", "image/jpeg",
4261 "addtype_jpeg", "image/jpeg",
4262 "realm", "MiniServ",
4263 "session_login", "/session_login.cgi",
4264 "pam_login", "/pam_login.cgi",
4265 "password_form", "/password_form.cgi",
4266 "password_change", "/password_change.cgi",
4270 "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\$",
4272 "expires", 7*24*60*60,
4273 "pam_test_user", "root",
4274 "precache", "lang/en */lang/en",
4276 foreach my $v (keys %vital) {
4278 if ($vital{$v} eq "") {
4279 die "Missing config option $v";
4281 $config{$v} = $vital{$v};
4284 if (!$config{'sessiondb'}) {
4285 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4286 $config{'sessiondb'} = "$1/sessiondb";
4288 if (!$config{'errorlog'}) {
4289 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
4290 $config{'errorlog'} = "$1/miniserv.error";
4292 if (!$config{'tempbase'}) {
4293 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4294 $config{'tempbase'} = "$1/cgitemp";
4296 if (!$config{'blockedfile'}) {
4297 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4298 $config{'blockedfile'} = "$1/blocked";
4300 if (!$config{'webmincron_dir'}) {
4301 $config_file =~ /^(.*)\/[^\/]+$/;
4302 $config{'webmincron_dir'} = "$1/webmincron/crons";
4304 if (!$config{'webmincron_last'}) {
4305 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
4306 $config{'webmincron_last'} = "$1/miniserv.lastcrons";
4308 if (!$config{'webmincron_wrapper'}) {
4309 $config{'webmincron_wrapper'} = $config{'root'}.
4310 "/webmincron/webmincron.pl";
4315 # Fills the %users and %certs hashes from the users file in %config
4324 undef(%lastchanges);
4327 if ($config{'userfile'}) {
4328 open(USERS, $config{'userfile'});
4331 local @user = split(/:/, $_, -1);
4332 $users{$user[0]} = $user[1];
4333 $certs{$user[0]} = $user[3] if ($user[3]);
4334 if ($user[4] =~ /^allow\s+(.*)/) {
4335 $allow{$user[0]} = $config{'alwaysresolve'} ?
4336 [ split(/\s+/, $1) ] :
4337 [ &to_ipaddress(split(/\s+/, $1)) ];
4339 elsif ($user[4] =~ /^deny\s+(.*)/) {
4340 $deny{$user[0]} = $config{'alwaysresolve'} ?
4341 [ split(/\s+/, $1) ] :
4342 [ &to_ipaddress(split(/\s+/, $1)) ];
4344 if ($user[5] =~ /days\s+(\S+)/) {
4345 $allowdays{$user[0]} = [ split(/,/, $1) ];
4347 if ($user[5] =~ /hours\s+(\d+)\.(\d+)-(\d+).(\d+)/) {
4348 $allowhours{$user[0]} = [ $1*60+$2, $3*60+$4 ];
4350 $lastchanges{$user[0]} = $user[6];
4351 $nochange{$user[0]} = $user[9];
4352 $temppass{$user[0]} = $user[10];
4357 # Test user DB, if configured
4358 if ($config{'userdb'}) {
4359 my $dbh = &connect_userdb($config{'userdb'});
4361 print STDERR "Failed to open users database : $dbh\n"
4364 &disconnect_userdb($config{'userdb'}, $dbh);
4369 # get_user_details(username)
4370 # Returns a hash ref of user details, either from config files or the user DB
4371 sub get_user_details
4373 my ($username) = @_;
4374 if (exists($users{$username})) {
4376 return { 'name' => $username,
4377 'pass' => $users{$username},
4378 'certs' => $certs{$username},
4379 'allow' => $allow{$username},
4380 'deny' => $deny{$username},
4381 'allowdays' => $allowdays{$username},
4382 'allowhours' => $allowhours{$username},
4383 'lastchanges' => $lastchanges{$username},
4384 'nochange' => $nochange{$username},
4385 'temppass' => $temppass{$username},
4386 'preroot' => $config{'preroot_'.$username},
4389 if ($config{'userdb'}) {
4390 # Try querying user database
4391 if (exists($get_user_details_cache{$username})) {
4393 return $get_user_details_cache{$username};
4395 print DEBUG "get_user_details: Connecting to user database\n";
4396 my ($dbh, $proto, $prefix, $args) = &connect_userdb($config{'userdb'});
4400 print DEBUG "get_user_details: Failed : $dbh\n";
4401 print STDERR "Failed to connect to user database : $dbh\n";
4403 elsif ($proto eq "mysql" || $proto eq "postgresql") {
4404 # Fetch user ID and password with SQL
4405 print DEBUG "get_user_details: Looking for $username in SQL\n";
4406 my $cmd = $dbh->prepare(
4407 "select id,pass from webmin_user where name = ?");
4408 if (!$cmd || !$cmd->execute($username)) {
4409 print STDERR "Failed to lookup user : ",
4413 my ($id, $pass) = $cmd->fetchrow();
4416 &disconnect_userdb($config{'userdb'}, $dbh);
4417 $get_user_details_cache{$username} = undef;
4418 print DEBUG "get_user_details: User not found\n";
4421 print DEBUG "get_user_details: id=$id pass=$pass\n";
4423 # Fetch attributes and add to user object
4424 print DEBUG "get_user_details: finding user attributes\n";
4425 my $cmd = $dbh->prepare(
4426 "select attr,value from webmin_user_attr where id = ?");
4427 if (!$cmd || !$cmd->execute($id)) {
4428 print STDERR "Failed to lookup user attrs : ",
4432 $user = { 'name' => $username,
4435 'proto' => $proto };
4436 while(my ($attr, $value) = $cmd->fetchrow()) {
4437 $attrs{$attr} = $value;
4441 elsif ($proto eq "ldap") {
4442 # Fetch user DN with LDAP
4443 print DEBUG "get_user_details: Looking for $username in LDAP\n";
4444 my $rv = $dbh->search(
4446 filter => '(&(cn='.$username.')(objectClass='.
4447 $args->{'userclass'}.'))',
4449 if (!$rv || $rv->code) {
4450 print STDERR "Failed to lookup user : ",
4451 ($rv ? $rv->error : "Unknown error"),"\n";
4454 my ($u) = $rv->all_entries();
4456 &disconnect_userdb($config{'userdb'}, $dbh);
4457 $get_user_details_cache{$username} = undef;
4458 print DEBUG "get_user_details: User not found\n";
4462 # Extract attributes
4463 my $pass = $u->get_value('webminPass');
4464 $user = { 'name' => $username,
4467 'proto' => $proto };
4468 foreach my $la ($u->get_value('webminAttr')) {
4469 my ($attr, $value) = split(/=/, $la, 2);
4470 $attrs{$attr} = $value;
4474 # Convert DB attributes into user object fields
4476 print DEBUG "get_user_details: got ",scalar(keys %attrs),
4478 $user->{'certs'} = $attrs{'cert'};
4479 if ($attrs{'allow'}) {
4480 $user->{'allow'} = $config{'alwaysresolve'} ?
4481 [ split(/\s+/, $attrs{'allow'}) ] :
4482 [ &to_ipaddress(split(/\s+/,$attrs{'allow'})) ];
4484 if ($attrs{'deny'}) {
4485 $user->{'deny'} = $config{'alwaysresolve'} ?
4486 [ split(/\s+/, $attrs{'deny'}) ] :
4487 [ &to_ipaddress(split(/\s+/,$attrs{'deny'})) ];
4489 if ($attrs{'days'}) {
4490 $user->{'allowdays'} = [ split(/,/, $attrs{'days'}) ];
4492 if ($attrs{'hoursfrom'} && $attrs{'hoursto'}) {
4493 my ($hf, $mf) = split(/\./, $attrs{'hoursfrom'});
4494 my ($ht, $mt) = split(/\./, $attrs{'hoursto'});
4495 $user->{'allowhours'} = [ $hf*60+$ht, $ht*60+$mt ];
4497 $user->{'lastchanges'} = $attrs{'lastchange'};
4498 $user->{'nochange'} = $attrs{'nochange'};
4499 $user->{'temppass'} = $attrs{'temppass'};
4500 $user->{'preroot'} = $attrs{'theme'};
4502 &disconnect_userdb($config{'userdb'}, $dbh);
4503 $get_user_details_cache{$user->{'name'}} = $user;
4509 # find_user_by_cert(cert)
4510 # Returns a username looked up by certificate
4511 sub find_user_by_cert
4513 my ($peername) = @_;
4514 my $peername2 = $peername;
4515 $peername2 =~ s/Email=/emailAddress=/ || $peername2 =~ s/emailAddress=/Email=/;
4517 # First check users in local files
4518 foreach my $username (keys %certs) {
4519 if ($certs{$username} eq $peername ||
4520 $certs{$username} eq $peername2) {
4526 if ($config{'userdb'}) {
4527 my ($dbh, $proto) = &connect_userdb($config{'userdb'});
4531 elsif ($proto eq "mysql" || $proto eq "postgresql") {
4533 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 = ?");
4534 return undef if (!$cmd);
4535 foreach my $p ($peername, $peername2) {
4537 if ($cmd->execute($p)) {
4538 ($username) = $cmd->fetchrow();
4541 return $username if ($username);
4544 elsif ($proto eq "ldap") {
4546 my $rv = $dbh->search(
4548 filter => '(objectClass='.
4549 $args->{'userclass'}.')',
4551 attrs => [ 'cn', 'webminAttr' ]);
4552 if ($rv && !$rv->code) {
4553 foreach my $u ($rv->all_entries) {
4554 my @attrs = $u->get_value('webminAttr');
4555 foreach my $la (@attrs) {
4556 my ($attr, $value) = split(/=/, $la, 2);
4557 if ($attr eq "cert" &&
4558 ($value eq $peername ||
4559 $value eq $peername2)) {
4560 return $u->get_value('cn');
4570 # connect_userdb(string)
4571 # Returns a handle for talking to a user database - may be a DBI or LDAP handle.
4572 # On failure returns an error message string. In an array context, returns the
4573 # protocol type too.
4577 my ($proto, $user, $pass, $host, $prefix, $args) = &split_userdb_string($str);
4578 if ($proto eq "mysql") {
4579 # Connect to MySQL with DBI
4580 my $drh = eval "use DBI; DBI->install_driver('mysql');";
4581 $drh || return $text{'sql_emysqldriver'};
4582 my ($host, $port) = split(/:/, $host);
4583 my $cstr = "database=$prefix;host=$host";
4584 $cstr .= ";port=$port" if ($port);
4585 print DEBUG "connect_userdb: Connecting to MySQL $cstr as $user\n";
4586 my $dbh = $drh->connect($cstr, $user, $pass, { });
4587 $dbh || return &text('sql_emysqlconnect', $drh->errstr);
4588 print DEBUG "connect_userdb: Connected OK\n";
4589 return wantarray ? ($dbh, $proto, $prefix, $args) : $dbh;
4591 elsif ($proto eq "postgresql") {
4592 # Connect to PostgreSQL with DBI
4593 my $drh = eval "use DBI; DBI->install_driver('Pg');";
4594 $drh || return $text{'sql_epostgresqldriver'};
4595 my ($host, $port) = split(/:/, $host);
4596 my $cstr = "dbname=$prefix;host=$host";
4597 $cstr .= ";port=$port" if ($port);
4598 print DEBUG "connect_userdb: Connecting to PostgreSQL $cstr as $user\n";
4599 my $dbh = $drh->connect($cstr, $user, $pass);
4600 $dbh || return &text('sql_epostgresqlconnect', $drh->errstr);
4601 print DEBUG "connect_userdb: Connected OK\n";
4602 return wantarray ? ($dbh, $proto, $prefix, $args) : $dbh;
4604 elsif ($proto eq "ldap") {
4605 # Connect with perl LDAP module
4606 eval "use Net::LDAP";
4607 $@ && return $text{'sql_eldapdriver'};
4608 my ($host, $port) = split(/:/, $host);
4609 my $scheme = $args->{'scheme'} || 'ldap';
4611 $port = $scheme eq 'ldaps' ? 636 : 389;
4613 my $ldap = Net::LDAP->new($host,
4615 'scheme' => $scheme);
4616 $ldap || return &text('sql_eldapconnect', $host);
4618 if ($args->{'tls'}) {
4619 # Switch to TLS mode
4620 eval { $mesg = $ldap->start_tls(); };
4621 if ($@ || !$mesg || $mesg->code) {
4622 return &text('sql_eldaptls',
4623 $@ ? $@ : $mesg ? $mesg->error : "Unknown error");
4626 # Login to the server
4628 $mesg = $ldap->bind(dn => $user, password => $pass);
4631 $mesg = $ldap->bind(dn => $user, anonymous => 1);
4633 if (!$mesg || $mesg->code) {
4634 return &text('sql_eldaplogin', $user,
4635 $mesg ? $mesg->error : "Unknown error");
4637 return wantarray ? ($ldap, $proto, $prefix, $args) : $ldap;
4640 return "Unknown protocol $proto";
4644 # split_userdb_string(string)
4645 # Converts a string like mysql://user:pass@host/db into separate parts
4646 sub split_userdb_string
4649 if ($str =~ /^([a-z]+):\/\/([^:]*):([^\@]*)\@([a-z0-9\.\-\_]+)\/([^\?]+)(\?(.*))?$/) {
4650 my ($proto, $user, $pass, $host, $prefix, $argstr) =
4651 ($1, $2, $3, $4, $5, $7);
4652 my %args = map { split(/=/, $_, 2) } split(/\&/, $argstr);
4653 return ($proto, $user, $pass, $host, $prefix, \%args);
4658 # disconnect_userdb(string, &handle)
4659 # Closes a handle opened by connect_userdb
4660 sub disconnect_userdb
4663 if ($str =~ /^(mysql|postgresql):/) {
4667 elsif ($str =~ /^ldap:/) {
4674 # Fills %mime with entries from file in %config and extra settings in %config
4678 if ($config{"mimetypes"} ne "") {
4679 open(MIME, $config{"mimetypes"});
4682 if (/^(\S+)\s+(.*)$/) {
4684 my @exts = split(/\s+/, $2);
4685 foreach my $ext (@exts) {
4686 $mime{$ext} = $type;
4692 foreach my $k (keys %config) {
4693 if ($k !~ /^addtype_(.*)$/) { next; }
4694 $mime{$1} = $config{$k};
4698 # build_config_mappings()
4699 # Build the anonymous access list, IP access list, unauthenticated URLs list,
4700 # redirect mapping and allow and deny lists from %config
4701 sub build_config_mappings
4703 # build anonymous access list
4705 foreach my $a (split(/\s+/, $config{'anonymous'})) {
4706 if ($a =~ /^([^=]+)=(\S+)$/) {
4707 $anonymous{$1} = $2;
4711 # build IP access list
4713 foreach my $a (split(/\s+/, $config{'ipaccess'})) {
4714 if ($a =~ /^([^=]+)=(\S+)$/) {
4719 # build unauthenticated URLs list
4720 @unauth = split(/\s+/, $config{'unauth'});
4722 # build redirect mapping
4724 foreach my $r (split(/\s+/, $config{'redirect'})) {
4725 if ($r =~ /^([^=]+)=(\S+)$/) {
4730 # build prefixes to be stripped
4731 undef(@strip_prefix);
4732 foreach my $r (split(/\s+/, $config{'strip_prefix'})) {
4733 push(@strip_prefix, $r);
4736 # Init allow and deny lists
4737 @deny = split(/\s+/, $config{"deny"});
4738 @deny = &to_ipaddress(@deny) if (!$config{'alwaysresolve'});
4739 @allow = split(/\s+/, $config{"allow"});
4740 @allow = &to_ipaddress(@allow) if (!$config{'alwaysresolve'});
4743 if ($config{'allowusers'}) {
4744 @allowusers = split(/\s+/, $config{'allowusers'});
4746 elsif ($config{'denyusers'}) {
4747 @denyusers = split(/\s+/, $config{'denyusers'});
4750 # Build list of unixauth mappings
4752 foreach my $ua (split(/\s+/, $config{'unixauth'})) {
4753 if ($ua =~ /^(\S+)=(\S+)$/) {
4757 $unixauth{"*"} = $ua;
4761 # Build list of non-session-auth pages
4762 undef(%sessiononly);
4763 foreach my $sp (split(/\s+/, $config{'sessiononly'})) {
4764 $sessiononly{$sp} = 1;
4767 # Build list of logout times
4768 undef(@logouttimes);
4769 foreach my $a (split(/\s+/, $config{'logouttimes'})) {
4770 if ($a =~ /^([^=]+)=(\S+)$/) {
4771 push(@logouttimes, [ $1, $2 ]);
4774 push(@logouttimes, [ undef, $config{'logouttime'} ]);
4776 # Build list of DAV pathss
4778 foreach my $d (split(/\s+/, $config{'davpaths'})) {
4779 push(@davpaths, $d);
4781 @davusers = split(/\s+/, $config{'dav_users'});
4783 # Mobile agent substrings and hostname prefixes
4784 @mobile_agents = split(/\t+/, $config{'mobile_agents'});
4785 @mobile_prefixes = split(/\s+/, $config{'mobile_prefixes'});
4788 @expires_paths = ( );
4789 foreach my $pe (split(/\t+/, $config{'expires_paths'})) {
4790 my ($p, $e) = split(/=/, $pe);
4791 if ($p && $e ne '') {
4792 push(@expires_paths, [ $p, $e ]);
4798 if ($config{'debug'}) {
4799 open(DEBUG, ">>$config{'debug'}");
4802 open(DEBUG, ">/dev/null");
4805 # Reset cache of sudo checks
4809 # is_group_member(&uinfo, groupname)
4810 # Returns 1 if some user is a primary or secondary member of a group
4813 local ($uinfo, $group) = @_;
4814 local @ginfo = getgrnam($group);
4815 return 0 if (!@ginfo);
4816 return 1 if ($ginfo[2] == $uinfo->[3]); # primary member
4817 foreach my $m (split(/\s+/, $ginfo[3])) {
4818 return 1 if ($m eq $uinfo->[0]);
4823 # prefix_to_mask(prefix)
4824 # Converts a number like 24 to a mask like 255.255.255.0
4827 return $_[0] >= 24 ? "255.255.255.".(256-(2 ** (32-$_[0]))) :
4828 $_[0] >= 16 ? "255.255.".(256-(2 ** (24-$_[0]))).".0" :
4829 $_[0] >= 8 ? "255.".(256-(2 ** (16-$_[0]))).".0.0" :
4830 (256-(2 ** (8-$_[0]))).".0.0.0";
4833 # get_logout_time(user, session-id)
4834 # Given a username, returns the idle time before he will be logged out
4837 local ($user, $sid) = @_;
4838 if (!defined($logout_time_cache{$user,$sid})) {
4840 foreach my $l (@logouttimes) {
4841 if ($l->[0] =~ /^\@(.*)$/) {
4842 # Check group membership
4843 local @uinfo = getpwnam($user);
4844 if (@uinfo && &is_group_member(\@uinfo, $1)) {
4848 elsif ($l->[0] =~ /^\//) {
4849 # Check file contents
4850 open(FILE, $l->[0]);
4867 if ($l->[0] eq $user) {
4871 last if (defined($time));
4873 $logout_time_cache{$user,$sid} = $time;
4875 return $logout_time_cache{$user,$sid};
4878 # password_crypt(password, salt)
4879 # If the salt looks like MD5 and we have a library for it, perform MD5 hashing
4880 # of a password. Otherwise, do Unix crypt.
4883 local ($pass, $salt) = @_;
4884 if ($salt =~ /^\$1\$/ && $use_md5) {
4885 return &encrypt_md5($pass, $salt);
4888 return &unix_crypt($pass, $salt);
4892 # unix_crypt(password, salt)
4893 # Performs standard Unix hashing for a password
4896 local ($pass, $salt) = @_;
4897 if ($use_perl_crypt) {
4898 return Crypt::UnixCrypt::crypt($pass, $salt);
4901 return crypt($pass, $salt);
4905 # handle_dav_request(davpath)
4906 # Pass a request on to the Net::DAV::Server module
4907 sub handle_dav_request
4910 eval "use Filesys::Virtual::Plain";
4911 eval "use Net::DAV::Server";
4912 eval "use HTTP::Request";
4913 eval "use HTTP::Headers";
4915 if ($Net::DAV::Server::VERSION eq '1.28' && $config{'dav_nolock'}) {
4916 delete $Net::DAV::Server::implemented{lock};
4917 delete $Net::DAV::Server::implemented{unlock};
4920 # Read in request data
4921 if (!$posted_data) {
4922 local $clen = $header{"content-length"};
4923 while(length($posted_data) < $clen) {
4924 $buf = &read_data($clen - length($posted_data));
4925 if (!length($buf)) {
4926 &http_error(500, "Failed to read POST request");
4928 $posted_data .= $buf;
4932 # For subsequent logging
4933 open(MINISERVLOG, ">>$config{'logfile'}");
4937 local @u = getpwnam($authuser);
4938 if ($config{'dav_remoteuser'} && !$< && $validated) {
4941 $( = $u[3]; $) = "$u[3] $u[3]";
4942 ($>, $<) = ($u[2], $u[2]);
4944 if ($config{'dav_root'} eq '*') {
4949 &http_error(500, "Unix user $authuser does not exist");
4953 $root ||= $config{'dav_root'};
4956 # Check if this user can use DAV
4958 &users_match(\@u, @davusers) ||
4959 &http_error(500, "You are not allowed to access DAV");
4963 my $filesys = Filesys::Virtual::Plain->new({root_path => $root});
4964 my $webdav = Net::DAV::Server->new();
4965 $webdav->filesys($filesys);
4967 # Make up a request object, and feed to DAV
4968 local $ho = HTTP::Headers->new;
4969 foreach my $h (keys %header) {
4970 next if (lc($h) eq "connection");
4971 $ho->header($h => $header{$h});
4974 $request_uri =~ s/^\Q$path\E//;
4975 $request_uri = "/" if ($request_uri eq "");
4977 my $request = HTTP::Request->new($method, $request_uri, $ho,
4979 if ($config{'dav_debug'}) {
4980 print STDERR "DAV request :\n";
4981 print STDERR "---------------------------------------------\n";
4982 print STDERR $request->as_string();
4983 print STDERR "---------------------------------------------\n";
4985 my $response = $webdav->run($request);
4987 # Send back the reply
4988 &write_data("HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n");
4989 local $content = $response->content();
4991 $content =~ s|href>/(.+)<|href>$path/$1<|g;
4992 $content =~ s|href>/<|href>$path<|g;
4994 foreach my $h ($response->header_field_names) {
4995 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4996 &write_data("$h: ",$response->header($h),"\r\n");
4998 &write_data("Content-length: ",length($content),"\r\n");
4999 local $rv = &write_keep_alive(0);
5000 &write_data("\r\n");
5001 &write_data($content);
5003 if ($config{'dav_debug'}) {
5004 print STDERR "DAV reply :\n";
5005 print STDERR "---------------------------------------------\n";
5006 print STDERR "HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n";
5007 foreach my $h ($response->header_field_names) {
5008 next if (lc($h) eq "connection" || lc($h) eq "content-length");
5009 print STDERR "$h: ",$response->header($h),"\r\n";
5011 print STDERR "Content-length: ",length($content),"\r\n";
5012 print STDERR "\r\n";
5013 print STDERR $content;
5014 print STDERR "---------------------------------------------\n";
5018 &log_request($acpthost, $authuser, $reqline, $response->code(),
5019 length($response->content()));
5022 # get_system_hostname()
5023 # Returns the hostname of this system, for reporting to listeners
5024 sub get_system_hostname
5026 # On Windows, try computername environment variable
5027 return $ENV{'computername'} if ($ENV{'computername'});
5028 return $ENV{'COMPUTERNAME'} if ($ENV{'COMPUTERNAME'});
5030 # If a specific command is set, use it first
5031 if ($config{'hostname_command'}) {
5032 local $out = `($config{'hostname_command'}) 2>&1`;
5039 # First try the hostname command
5040 local $out = `hostname 2>&1`;
5041 if (!$? && $out =~ /\S/) {
5046 # Try the Sys::Hostname module
5047 eval "use Sys::Hostname";
5049 local $rv = eval "hostname()";
5055 # Must use net name on Windows
5056 local $out = `net name 2>&1`;
5057 if ($out =~ /\-+\r?\n(\S+)/) {
5064 # indexof(string, array)
5065 # Returns the index of some value in an array, or -1
5068 for($i=1; $i <= $#_; $i++) {
5069 if ($_[$i] eq $_[0]) { return $i - 1; }
5075 # has_command(command)
5076 # Returns the full path if some command is in the path, undef if not
5080 if (!$_[0]) { return undef; }
5081 if (exists($has_command_cache{$_[0]})) {
5082 return $has_command_cache{$_[0]};
5085 if ($_[0] =~ /^\//) {
5086 $rv = -x $_[0] ? $_[0] : undef;
5089 local $sp = $on_windows ? ';' : ':';
5090 foreach $d (split($sp, $ENV{PATH})) {
5091 if (-x "$d/$_[0]") {
5096 foreach my $sfx (".exe", ".com", ".bat") {
5097 if (-r "$d/$_[0]".$sfx) {
5098 $rv = "$d/$_[0]".$sfx;
5105 $has_command_cache{$_[0]} = $rv;
5109 # check_sudo_permissions(user, pass)
5110 # Returns 1 if some user can run any command via sudo
5111 sub check_sudo_permissions
5113 local ($user, $pass) = @_;
5115 # First try the pipes
5117 print DEBUG "check_sudo_permissions: querying cache for $user\n";
5118 print $PASSINw "readsudo $user\n";
5119 local $can = <$PASSOUTr>;
5121 print DEBUG "check_sudo_permissions: cache said $can\n";
5122 if ($can =~ /^\d+$/ && $can != 2) {
5127 local $ptyfh = new IO::Pty;
5128 print DEBUG "check_sudo_permissions: ptyfh=$ptyfh\n";
5130 print STDERR "Failed to create new PTY with IO::Pty\n";
5133 local @uinfo = getpwnam($user);
5135 print STDERR "Unix user $user does not exist for sudo\n";
5139 # Execute sudo in a sub-process, via a pty
5140 local $ttyfh = $ptyfh->slave();
5141 print DEBUG "check_sudo_permissions: ttyfh=$ttyfh\n";
5142 local $tty = $ptyfh->ttyname();
5143 print DEBUG "check_sudo_permissions: tty=$tty\n";
5144 chown($uinfo[2], $uinfo[3], $tty);
5146 print DEBUG "check_sudo_permissions: about to fork..\n";
5147 local $pid = fork();
5148 print DEBUG "check_sudo_permissions: fork=$pid pid=$$\n";
5150 print STDERR "fork for sudo failed : $!\n";
5155 $ptyfh->make_slave_controlling_terminal();
5156 close(STDIN); close(STDOUT); close(STDERR);
5157 untie(*STDIN); untie(*STDOUT); untie(*STDERR);
5158 close($PASSINw); close($PASSOUTr);
5159 $( = $uinfo[3]; $) = "$uinfo[3] $uinfo[3]";
5160 ($>, $<) = ($uinfo[2], $uinfo[2]);
5165 open(STDIN, "<&SUDOr");
5166 open(STDOUT, ">$tty");
5167 open(STDERR, ">&STDOUT");
5170 print "Exec failed : $!\n";
5173 print DEBUG "check_sudo_permissions: pid=$pid\n";
5175 $ptyfh->close_slave();
5177 # Send password, and get back response
5178 local $oldfh = select(SUDOw);
5181 print DEBUG "check_sudo_permissions: about to send pass\n";
5182 local $SIG{'PIPE'} = 'ignore'; # Sometimes sudo doesn't ask for a password
5183 print SUDOw $pass,"\n";
5184 print DEBUG "check_sudo_permissions: sent pass=$pass\n";
5188 print DEBUG "check_sudo_permissions: got $_";
5194 local ($ok) = ($out =~ /\(ALL\)\s+ALL|\(ALL\)\s+NOPASSWD:\s+ALL/ ? 1 : 0);
5198 print $PASSINw "writesudo $user $ok\n";
5204 # is_mobile_useragent(agent)
5205 # Returns 1 if some user agent looks like a cellphone or other mobile device,
5207 sub is_mobile_useragent
5209 local ($agent) = @_;
5211 "UP.Link", # Openwave
5212 "Nokia", # All Nokias start with Nokia
5213 "MOT-", # All Motorola phones start with MOT-
5214 "SAMSUNG", # Samsung browsers
5215 "Samsung", # Samsung browsers
5216 "SEC-", # Samsung browsers
5217 "AU-MIC", # Samsung browsers
5218 "AUDIOVOX", # Audiovox
5219 "BlackBerry", # BlackBerry
5220 "hiptop", # Danger hiptop Sidekick
5221 "SonyEricsson", # Sony Ericsson
5222 "Ericsson", # Old Ericsson browsers , mostly WAP
5223 "Mitsu/1.1.A", # Mitsubishi phones
5224 "Panasonic WAP", # Panasonic old WAP phones
5225 "DoCoMo", # DoCoMo phones
5226 "Lynx", # Lynx text-mode linux browser
5227 "Links", # Another text-mode linux browser
5229 local @substrings = (
5230 "UP.Browser", # Openwave
5231 "MobilePhone", # NetFront
5232 "AU-MIC-A700", # Samsung A700 Obigo browsers
5233 "Danger hiptop", # Danger Sidekick hiptop
5234 "Windows CE", # Windows CE Pocket PC
5235 "IEMobile", # Windows mobile browser
5236 "Blazer", # Palm Treo Blazer
5237 "BlackBerry", # BlackBerries can emulate other browsers, but
5238 # they still keep this string in the UserAgent
5239 "SymbianOS", # New Series60 browser has safari in it and
5240 # SymbianOS is the only distinguishing string
5241 "iPhone", # Apple iPhone KHTML browser
5242 "iPod", # iPod touch browser
5243 "MobileSafari", # HTTP client in iPhone
5245 "Opera Mini", # Opera Mini
5246 "HTC_P3700", # HTC mobile device
5248 "webOS/", # Palm WebOS
5249 "Nintendo DS", # DSi / DSi-XL
5251 foreach my $p (@prefixes) {
5252 return 1 if ($agent =~ /^\Q$p\E/);
5254 foreach my $s (@substrings, @mobile_agents) {
5255 return 1 if ($agent =~ /\Q$s\E/);
5260 # write_blocked_file()
5261 # Writes out a text file of blocked hosts and users
5262 sub write_blocked_file
5264 open(BLOCKED, ">$config{'blockedfile'}");
5265 foreach my $d (grep { $hostfail{$_} } @deny) {
5266 print BLOCKED "host $d $hostfail{$d} $blockhosttime{$d}\n";
5268 foreach my $d (grep { $userfail{$_} } @denyusers) {
5269 print BLOCKED "user $d $userfail{$d} $blockusertime{$d}\n";
5272 chmod(0700, $config{'blockedfile'});
5277 open(PIDFILE, ">$config{'pidfile'}");
5278 printf PIDFILE "%d\n", getpid();
5280 $miniserv_main_pid = getpid();
5283 # lock_user_password(user)
5284 # Updates a user's password file entry to lock it, both in memory and on disk.
5285 # Returns 1 if done, -1 if no such user, 0 if already locked
5286 sub lock_user_password
5289 local $uinfo = &get_user_details($user);
5294 if ($uinfo->{'pass'} =~ /^\!/) {
5298 if (!$uinfo->{'proto'}) {
5299 # Write to users file
5300 $users{$user} = "!".$users{$user};
5301 open(USERS, $config{'userfile'});
5302 local @ufile = <USERS>;
5304 foreach my $u (@ufile) {
5305 local @uinfo = split(/:/, $u);
5306 if ($uinfo[0] eq $user) {
5307 $uinfo[1] = $users{$user};
5309 $u = join(":", @uinfo);
5311 open(USERS, ">$config{'userfile'}");
5317 if ($config{'userdb'}) {
5319 my ($dbh, $proto, $prefix, $args) = &connect_userdb($config{'userdb'});
5323 elsif ($proto eq "mysql" || $proto eq "postgresql") {
5324 # Update user attribute
5325 my $cmd = $dbh->prepare(
5326 "update webmin_user set pass = ? where id = ?");
5327 if (!$cmd || !$cmd->execute("!".$uinfo->{'pass'},
5330 print STDERR "Failed to lock password : ",
5334 $cmd->finish() if ($cmd);
5336 elsif ($proto eq "ldap") {
5337 # Update LDAP object
5338 my $rv = $dbh->modify($uinfo->{'id'},
5339 replace => { 'webminPass' => '!'.$uinfo->{'pass'} });
5340 if (!$rv || $rv->code) {
5341 print STDERR "Failed to lock password : ",
5342 ($rv ? $rv->error : "Unknown error"),"\n";
5346 &disconnect_userdb($config{'userdb'}, $dbh);
5350 return -1; # This should never be reached
5353 # hash_session_id(sid)
5354 # Returns an MD5 or Unix-crypted session ID
5358 if (!$hash_session_id_cache{$sid}) {
5361 $hash_session_id_cache{$sid} = &encrypt_md5($sid);
5365 $hash_session_id_cache{$sid} = &unix_crypt($sid, "XX");
5368 return $hash_session_id_cache{$sid};
5371 # encrypt_md5(string, [salt])
5372 # Returns a string encrypted in MD5 format
5375 local ($passwd, $salt) = @_;
5376 local $magic = '$1$';
5377 if ($salt =~ /^\$1\$([^\$]+)/) {
5378 # Extract actual salt from already encrypted password
5383 local $ctx = eval "new $use_md5";
5390 # Add some more stuff from the hash of the password and salt
5391 local $ctx1 = eval "new $use_md5";
5392 $ctx1->add($passwd);
5396 $ctx1->add($passwd);
5397 local $final = $ctx1->digest();
5398 for($pl=length($passwd); $pl>0; $pl-=16) {
5399 $ctx->add($pl > 16 ? $final : substr($final, 0, $pl));
5402 # This piece of code seems rather pointless, but it's in the C code that
5403 # does MD5 in PAM so it has to go in!
5406 for($i=length($passwd); $i; $i >>= 1) {
5411 $ctx->add(substr($passwd, $j, 1));
5414 $final = $ctx->digest();
5417 # This loop exists only to waste time
5418 for($i=0; $i<1000; $i++) {
5419 $ctx1 = eval "new $use_md5";
5420 $ctx1->add($i & 1 ? $passwd : $final);
5421 $ctx1->add($salt) if ($i % 3);
5422 $ctx1->add($passwd) if ($i % 7);
5423 $ctx1->add($i & 1 ? $final : $passwd);
5424 $final = $ctx1->digest();
5428 # Convert the 16-byte final string into a readable form
5430 local @final = map { ord($_) } split(//, $final);
5431 $l = ($final[ 0]<<16) + ($final[ 6]<<8) + $final[12];
5432 $rv .= &to64($l, 4);
5433 $l = ($final[ 1]<<16) + ($final[ 7]<<8) + $final[13];
5434 $rv .= &to64($l, 4);
5435 $l = ($final[ 2]<<16) + ($final[ 8]<<8) + $final[14];
5436 $rv .= &to64($l, 4);
5437 $l = ($final[ 3]<<16) + ($final[ 9]<<8) + $final[15];
5438 $rv .= &to64($l, 4);
5439 $l = ($final[ 4]<<16) + ($final[10]<<8) + $final[ 5];
5440 $rv .= &to64($l, 4);
5442 $rv .= &to64($l, 2);
5444 # Add salt if needed
5446 return $magic.$salt.'$'.$rv;
5455 local ($v, $n) = @_;
5458 $r .= $itoa64[$v & 0x3f];
5464 # read_file(file, &assoc, [&order], [lowercase])
5465 # Fill an associative array with name=value pairs from a file
5468 open(ARFILE, $_[0]) || return 0;
5471 if (!/^#/ && /^([^=]*)=(.*)$/) {
5472 $_[1]->{$_[3] ? lc($1) : $1} = $2;
5473 push(@{$_[2]}, $1) if ($_[2]);
5480 # write_file(file, array)
5481 # Write out the contents of an associative array as name=value lines
5484 local(%old, @order);
5485 &read_file($_[0], \%old, \@order);
5486 open(ARFILE, ">$_[0]");
5487 foreach $k (@order) {
5488 print ARFILE $k,"=",$_[1]->{$k},"\n" if (exists($_[1]->{$k}));
5490 foreach $k (keys %{$_[1]}) {
5491 print ARFILE $k,"=",$_[1]->{$k},"\n" if (!exists($old{$k}));
5496 # execute_ready_webmin_crons()
5497 # Find and run any cron jobs that are due, based on their last run time and
5498 # execution interval
5499 sub execute_ready_webmin_crons
5503 foreach my $cron (@webmincrons) {
5505 if (!$webmincron_last{$cron->{'id'}}) {
5506 # If not ever run before, don't run right away
5507 $webmincron_last{$cron->{'id'}} = $now;
5510 elsif ($cron->{'interval'} &&
5511 $now - $webmincron_last{$cron->{'id'}} > $cron->{'interval'}) {
5512 # Older than interval .. time to run
5515 elsif ($cron->{'mins'}) {
5516 # Check if current time matches spec, and we haven't run in the
5518 my @tm = localtime($now);
5519 if (&matches_cron($cron->{'mins'}, $tm[1]) &&
5520 &matches_cron($cron->{'hours'}, $tm[2]) &&
5521 &matches_cron($cron->{'days'}, $tm[3]) &&
5522 &matches_cron($cron->{'months'}, $tm[4]+1) &&
5523 &matches_cron($cron->{'weekdays'}, $tm[6]) &&
5524 $now - $webmincron_last{$cron->{'id'}} > 60) {
5530 print DEBUG "Running cron id=$cron->{'id'} ".
5531 "module=$cron->{'module'} func=$cron->{'func'}\n";
5532 $webmincron_last{$cron->{'id'}} = $now;
5536 # Run via a wrapper command, which we run like a CGI
5537 dbmclose(%sessiondb);
5539 # Setup CGI-like environment
5540 $envtz = $ENV{"TZ"};
5541 $envuser = $ENV{"USER"};
5542 $envpath = $ENV{"PATH"};
5543 $envlang = $ENV{"LANG"};
5544 $envroot = $ENV{"SystemRoot"};
5545 $envperllib = $ENV{'PERLLIB'};
5546 foreach my $k (keys %ENV) {
5549 $ENV{"PATH"} = $envpath if ($envpath);
5550 $ENV{"TZ"} = $envtz if ($envtz);
5551 $ENV{"USER"} = $envuser if ($envuser);
5552 $ENV{"OLD_LANG"} = $envlang if ($envlang);
5553 $ENV{"SystemRoot"} = $envroot if ($envroot);
5554 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
5555 $ENV{"HOME"} = $user_homedir;
5556 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
5557 $ENV{"SERVER_ADMIN"} = $config{"email"};
5559 $ENV{"SERVER_ROOT"} = $root0;
5560 $ENV{"SERVER_REALROOT"} = $root0;
5561 $ENV{"SERVER_PORT"} = $config{'port'};
5562 $ENV{"WEBMIN_CRON"} = 1;
5563 $ENV{"DOCUMENT_ROOT"} = $root0;
5564 $ENV{"DOCUMENT_REALROOT"} = $root0;
5565 $ENV{"MINISERV_CONFIG"} = $config_file;
5566 $ENV{"HTTPS"} = "ON" if ($use_ssl);
5567 $ENV{"MINISERV_PID"} = $miniserv_main_pid;
5568 $ENV{"SCRIPT_FILENAME"} = $config{'webmincron_wrapper'};
5569 if ($ENV{"SCRIPT_FILENAME"} =~ /^\Q$root0\E(\/.*)$/) {
5570 $ENV{"SCRIPT_NAME"} = $1;
5572 $config{'webmincron_wrapper'} =~ /^(.*)\//;
5574 foreach $k (keys %config) {
5575 if ($k =~ /^env_(\S+)$/) {
5576 $ENV{$1} = $config{$k};
5580 $SIG{'CHLD'} = 'DEFAULT';
5582 # Have SOCK closed if the perl exec's something
5584 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
5587 # Run the wrapper script by evaling it
5588 $pkg = "webmincron";
5589 $0 = $config{'webmincron_wrapper'};
5591 $main_process_id = $$;
5595 do \$miniserv::config{'webmincron_wrapper'};
5599 print STDERR "Perl cron failure : $@\n";
5604 push(@childpids, $pid);
5608 # Write out file containing last run times
5609 &write_file($config{'webmincron_last'}, \%webmincron_last);
5613 # matches_cron(cron-spec, time)
5614 # Checks if some minute or hour matches some cron spec, which can be * or a list
5618 my ($spec, $tm) = @_;
5623 foreach my $s (split(/,/, $spec)) {
5625 $s =~ /^(\d+)\-(\d+)$/ && $tm >= $1 && $tm <= $2) {
5633 # read_webmin_crons()
5634 # Read all scheduled webmin cron functions and store them in the @webmincrons
5636 sub read_webmin_crons
5639 opendir(CRONS, $config{'webmincron_dir'});
5640 print DEBUG "Reading crons from $config{'webmincron_dir'}\n";
5641 foreach my $f (readdir(CRONS)) {
5642 if ($f =~ /^(\d+)\.cron$/) {
5644 &read_file("$config{'webmincron_dir'}/$f", \%cron);
5647 foreach my $n ('module', 'func') {
5649 print STDERR "Cron $1 missing $n\n";
5653 if (!$cron{'interval'} && !$cron{'mins'} && !$cron{'special'}) {
5654 print STDERR "Cron $1 missing any time spec\n";
5657 if ($cron{'special'} eq 'hourly') {
5658 # Run every hour on the hour
5660 $cron{'hours'} = '*';
5661 $cron{'days'} = '*';
5662 $cron{'months'} = '*';
5663 $cron{'weekdays'} = '*';
5665 elsif ($cron{'special'} eq 'daily') {
5666 # Run every day at midnight
5668 $cron{'hours'} = '0';
5669 $cron{'days'} = '*';
5670 $cron{'months'} = '*';
5671 $cron{'weekdays'} = '*';
5673 elsif ($cron{'special'} eq 'monthly') {
5674 # Run every month on the 1st
5676 $cron{'hours'} = '0';
5677 $cron{'days'} = '1';
5678 $cron{'months'} = '*';
5679 $cron{'weekdays'} = '*';
5681 elsif ($cron{'special'} eq 'weekly') {
5682 # Run every month on the 1st
5684 $cron{'hours'} = '0';
5685 $cron{'days'} = '*';
5686 $cron{'months'} = '*';
5687 $cron{'weekdays'} = '0';
5689 elsif ($cron{'special'} eq 'yearly' ||
5690 $cron{'special'} eq 'annually') {
5691 # Run every year on 1st january
5693 $cron{'hours'} = '0';
5694 $cron{'days'} = '1';
5695 $cron{'months'} = '1';
5696 $cron{'weekdays'} = '*';
5698 elsif ($cron{'special'}) {
5699 print STDERR "Cron $1 invalid special time $cron{'special'}\n";
5702 if ($cron{'special'}) {
5703 delete($cron{'special'});
5706 print DEBUG "adding cron id=$cron{'id'} module=$cron{'module'} func=$cron{'func'}\n";
5707 push(@webmincrons, \%cron);
5714 # Read into the Webmin cache all files marked for pre-caching
5717 undef(%main::read_file_cache);
5718 foreach my $g (split(/\s+/, $config{'precache'})) {
5719 next if ($g eq "none");
5720 foreach my $f (glob("$config{'root'}/$g")) {
5723 $main::read_file_cache{$f} = { };
5724 &read_file($f, $main::read_file_cache{$f});
5725 $main::read_file_cache_time{$f} = $st[9];
5730 # Check if some address is valid IPv4, returns 1 if so.
5733 return $_[0] =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/ &&
5734 $1 >= 0 && $1 <= 255 &&
5735 $2 >= 0 && $2 <= 255 &&
5736 $3 >= 0 && $3 <= 255 &&
5737 $4 >= 0 && $4 <= 255;
5740 # Check if some IPv6 address is properly formatted, and returns 1 if so.
5741 sub check_ip6address
5743 my @blocks = split(/:/, $_[0]);
5744 return 0 if (@blocks == 0 || @blocks > 8);
5746 my $where = index($blocks[$ib],"/");
5749 my $b = substr($blocks[$ib],0,$where);
5750 $m = substr($blocks[$ib],$where+1,length($blocks[$ib])-($where+1));
5753 return 0 if ($m <0 || $m >128);
5756 foreach $b (@blocks) {
5757 return 0 if ($b ne "" && $b !~ /^[0-9a-f]{1,4}$/i);
5758 $empty++ if ($b eq "");
5760 return 0 if ($empty > 1 && !($_[0] =~ /^::/ && $empty == 2));
5764 # network_to_address(binary)
5765 # Given a network address in binary IPv4 or v4 format, return the string form
5766 sub network_to_address
5769 if (length($addr) == 4 || !$use_ipv6) {
5770 return inet_ntoa($addr);
5773 return Socket6::inet_ntop(Socket6::AF_INET6(), $addr);
5777 # redirect_stderr_to_log()
5778 # Re-direct STDERR to error log file
5779 sub redirect_stderr_to_log
5781 if ($config{'errorlog'} ne '-') {
5782 open(STDERR, ">>$config{'errorlog'}") ||
5783 die "failed to open $config{'errorlog'} : $!";
5784 if ($config{'logperms'}) {
5785 chmod(oct($config{'logperms'}), $config{'errorlog'});
5788 select(STDERR); $| = 1; select(STDOUT);
5791 # should_gzip_file(filename)
5792 # Returns 1 if some path should be gzipped
5793 sub should_gzip_file
5796 return $path !~ /\.(gif|png|jpg|jpeg|tif|tiff)$/i;
5799 # get_expires_time(path)
5800 # Given a URL path, return the client-side expiry time in seconds
5801 sub get_expires_time
5804 foreach my $pe (@expires_paths) {
5805 if ($path =~ /$pe->[0]/i) {
5809 return $config{'expires'};