2 # A very simple perl web server used by Webmin
4 # Require basic libraries
10 @itoa64 = split(//, "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
12 # Find and read config file
14 die "Usage: miniserv.pl <config file>";
16 if ($ARGV[0] =~ /^([a-z]:)?\//i) {
17 $config_file = $ARGV[0];
21 $config_file = "$pwd/$ARGV[0]";
23 %config = &read_config_file($config_file);
24 if ($config{'perllib'}) {
25 push(@INC, split(/:/, $config{'perllib'}));
26 $ENV{'PERLLIB'} .= ':'.$config{'perllib'};
30 # Check if SSL is enabled and available
32 eval "use Net::SSLeay";
35 # These functions only exist for SSLeay 1.0
36 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
37 eval "Net::SSLeay::load_error_strings()";
38 if ($config{'no_ssl2'}) {
39 eval "Net::SSLeay::CTX_set_options($ctx,&Net::SSLeay::OP_NO_SSLv2)";
41 if (defined(&Net::SSLeay::X509_STORE_CTX_get_current_cert) &&
42 defined(&Net::SSLeay::CTX_load_verify_locations) &&
43 defined(&Net::SSLeay::CTX_set_verify)) {
49 # Check if IPv6 is enabled and available
50 if ($config{'ipv6'}) {
53 push(@startup_msg, "IPv6 support enabled");
57 push(@startup_msg, "IPv6 support cannot be enabled without ".
58 "the Socket6 perl module");
62 # Check if the syslog module is available to log hacking attempts
63 if ($config{'syslog'} && !$config{'inetd'}) {
64 eval "use Sys::Syslog qw(:DEFAULT setlogsock)";
70 # check if the TCP-wrappers module is available
71 if ($config{'libwrap'}) {
72 eval "use Authen::Libwrap qw(hosts_ctl STRING_UNKNOWN)";
78 # Check if the MD5 perl module is available
84 eval "use Digest::MD5";
86 $use_md5 = "Digest::MD5";
90 # Get miniserv's perl path and location
92 open(SOURCE, $miniserv_path);
93 <SOURCE> =~ /^#!(\S+)/;
100 $linked_perl_path = readlink($perl_path);
102 @miniserv_argv = @ARGV;
104 # Check vital config options
105 &update_vital_config();
107 $sidname = $config{'sidname'};
108 die "Session authentication cannot be used in inetd mode"
109 if ($config{'inetd'} && $config{'session'});
111 # check if the PAM module is available to authenticate
112 if ($config{'assume_pam'}) {
113 # Just assume that it will work. This can also be used to work around
114 # a Solaris bug in which using PAM before forking caused it to fail
118 elsif (!$config{'no_pam'}) {
119 eval "use Authen::PAM;";
121 # check if the PAM authentication can be used by opening a
124 if (ref($pamh = new Authen::PAM($config{'pam'},
125 $config{'pam_test_user'},
127 # Now test a login to see if /etc/pam.d/webmin is set
129 $pam_conv_func_called = 0;
130 $pam_username = "test";
131 $pam_password = "test";
132 $pamh->pam_authenticate();
133 if ($pam_conv_func_called) {
135 "PAM authentication enabled");
140 "PAM test failed - maybe ".
141 "/etc/pam.d/$config{'pam'} does not exist");
146 "PAM initialization of Authen::PAM failed");
151 "Perl module Authen::PAM needed for PAM is ".
152 "not installed : $@");
155 if ($config{'pam_only'} && !$use_pam) {
156 print STDERR $startup_msg[0],"\n";
157 print STDERR "PAM use is mandatory, but could not be enabled!\n";
160 elsif ($pam_msg && !$use_pam) {
162 "Continuing without the Authen::PAM perl module");
165 # Check if the User::Utmp perl module is installed
166 if ($config{'utmp'}) {
167 eval "use User::Utmp;";
170 push(@startup_msg, "UTMP logging enabled");
174 "Perl module User::Utmp needed for Utmp logging is ".
175 "not installed : $@");
179 # See if the crypt function fails
180 eval "crypt('foo', 'xx')";
182 eval "use Crypt::UnixCrypt";
186 "Using Crypt::UnixCrypt for password encryption");
190 "crypt() function un-implemented, and Crypt::UnixCrypt ".
191 "not installed - password authentication will fail");
195 # Check if /dev/urandom really generates random IDs, by calling it twice
196 local $rand1 = &generate_random_id("foo", 1);
197 local $rand2 = &generate_random_id("foo", 2);
198 if ($rand1 eq $rand2) {
201 "Random number generator file /dev/urandom is not reliable");
204 # Check if we can call sudo
205 if ($config{'sudo'} && &has_command("sudo")) {
212 "Perl module IO::Pty needed for calling sudo is not ".
217 # init days and months for http_date
218 @weekday = ( "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" );
219 @month = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun",
220 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" );
222 # Change dir to the server root
223 @roots = ( $config{'root'} );
224 for($i=0; defined($config{"extraroot_$i"}); $i++) {
225 push(@roots, $config{"extraroot_$i"});
228 eval { $user_homedir = (getpwuid($<))[7]; };
230 # getpwuid doesn't work on windows
231 $user_homedir = $ENV{"HOME"} || $ENV{"USERPROFILE"} || "/";
238 # Setup SSL if possible and if requested
239 if (!-r $config{'keyfile'} ||
240 $config{'certfile'} && !-r $config{'certfile'}) {
241 # Key file doesn't exist!
244 @ipkeys = &get_ipkeys(\%config);
246 if ($config{'ssl_version'}) {
247 # Force an SSL version
248 $Net::SSLeay::version = $config{'ssl_version'};
249 $Net::SSLeay::ssl_version = $config{'ssl_version'};
251 $client_certs = 0 if (!-r $config{'ca'} || !%certs);
252 $ssl_contexts{"*"} = &create_ssl_context($config{'keyfile'},
253 $config{'certfile'});
254 foreach $ipkey (@ipkeys) {
255 $ctx = &create_ssl_context($ipkey->{'key'}, $ipkey->{'cert'});
256 foreach $ip (@{$ipkey->{'ips'}}) {
257 $ssl_contexts{$ip} = $ctx;
262 # Setup syslog support if possible and if requested
264 open(ERRDUP, ">&STDERR");
265 open(STDERR, ">/dev/null");
266 $log_socket = $config{"logsock"} || "unix";
267 eval 'openlog($config{"pam"}, "cons,pid,ndelay", "authpriv"); setlogsock($log_socket)';
272 local $msg = ucfirst($config{'pam'})." starting";
273 eval { syslog("info", "%s", $msg); };
277 syslog("info", "%s", $msg);
280 # All attempts to use syslog have failed..
285 open(STDERR, ">&ERRDUP");
289 # Read MIME types file and add extra types
293 if ($config{'log'}) {
294 local(@gmt, @lct, $days, $hours, $mins);
295 @gmt = gmtime(time());
296 @lct = localtime(time());
297 $days = $lct[3] - $gmt[3];
298 $hours = ($days < -1 ? 24 : 1 < $days ? -24 : $days * 24) +
300 $mins = $hours * 60 + $lct[1] - $gmt[1];
301 $timezone = ($mins < 0 ? "-" : "+"); $mins = abs($mins);
302 $timezone .= sprintf "%2.2d%2.2d", $mins/60, $mins%60;
305 # Build various maps from the config files
306 &build_config_mappings();
308 # start up external authentication program, if needed
309 if ($config{'extauth'}) {
310 socketpair(EXTAUTH, EXTAUTH2, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
311 if (!($extauth = fork())) {
315 open(STDIN, "<&EXTAUTH2");
316 open(STDOUT, ">&EXTAUTH2");
317 exec($config{'extauth'}) or die "exec failed : $!\n";
320 local $os = select(EXTAUTH);
324 # Pre-load any libraries
325 if (!$config{'inetd'}) {
326 foreach $pl (split(/\s+/, $config{'preload'})) {
327 ($pkg, $lib) = split(/=/, $pl);
328 $pkg =~ s/[^A-Za-z0-9]/_/g;
329 eval "package $pkg; do '$config{'root'}/$lib'";
331 print STDERR "Failed to pre-load $lib in $pkg : $@\n";
334 print STDERR "Pre-loaded $lib in $pkg\n";
337 foreach $pl (split(/\s+/, $config{'premodules'})) {
339 ($dir, $mod) = split(/\//, $pl);
342 ($dir, $mod) = (undef, $pl);
344 push(@INC, "$config{'root'}/$dir");
345 eval "package $mod; use $mod ()";
347 print STDERR "Failed to pre-load $mod : $@\n";
350 print STDERR "Pre-loaded $mod\n";
355 # Open debug log if set
356 if ($config{'debuglog'}) {
357 open(DEBUG, ">>$config{'debuglog'}");
358 chmod(0700, $config{'debuglog'});
359 select(DEBUG); $| = 1; select(STDOUT);
360 print DEBUG "miniserv.pl starting ..\n";
363 # Write out (empty) blocked hosts file
364 &write_blocked_file();
366 # Initially read webmin cron functions and last execution times
367 &read_webmin_crons();
368 %webmincron_last = ( );
369 &read_file($config{'webmincron_last'}, \%webmincron_last);
371 # Re-direct STDERR to a log file
372 if ($config{'errorlog'} ne '-') {
373 open(STDERR, ">>$config{'errorlog'}") || die "failed to open $config{'errorlog'} : $!";
374 if ($config{'logperms'}) {
375 chmod(oct($config{'logperms'}), $config{'errorlog'});
378 select(STDERR); $| = 1; select(STDOUT);
380 if ($config{'inetd'}) {
381 # We are being run from inetd - go direct to handling the request
382 $SIG{'HUP'} = 'IGNORE';
383 $SIG{'TERM'} = 'DEFAULT';
384 $SIG{'PIPE'} = 'DEFAULT';
385 open(SOCK, "+>&STDIN");
387 # Check if it is time for the logfile to be cleared
388 if ($config{'logclear'}) {
389 local $write_logtime = 0;
390 local @st = stat("$config{'logfile'}.time");
392 if ($st[9]+$config{'logtime'}*60*60 < time()){
395 unlink($config{'logfile'});
398 else { $write_logtime = 1; }
399 if ($write_logtime) {
400 open(LOGTIME, ">$config{'logfile'}.time");
401 print LOGTIME time(),"\n";
406 # Initialize SSL for this connection
408 $ssl_con = &ssl_connection_for_ip(SOCK);
412 # Work out the hostname for this web server
413 $host = &get_socket_name(SOCK, 0);
415 $port = $config{'port'};
416 $acptaddr = getpeername(SOCK);
419 # Work out remote and local IPs
420 (undef, $peera, undef) = &get_address_ip($acptaddr, 0);
421 (undef, $locala) = &get_socket_ip(SOCK, 0);
423 print DEBUG "main: Starting handle_request loop pid=$$\n";
424 while(&handle_request($peera, $locala, 0)) { }
425 print DEBUG "main: Done handle_request loop pid=$$\n";
430 # Build list of sockets to listen on
431 $config{'bind'} = '' if ($config{'bind'} eq '*');
432 if ($config{'bind'}) {
433 # Listening on a specific IP
434 if (&check_ip6address($config{'bind'})) {
436 $use_ipv6 || die "Cannot bind to $config{'bind'} without IPv6";
437 push(@sockets, [ inet_pton(Socket6::AF_INET6(),$config{'bind'}),
439 Socket6::PF_INET6() ]);
443 push(@sockets, [ inet_aton($config{'bind'}),
449 # Listening on all IPs
450 push(@sockets, [ INADDR_ANY, $config{'port'}, PF_INET ]);
453 push(@sockets, [ in6addr_any(), $config{'port'},
454 Socket6::PF_INET6() ]);
457 foreach $s (split(/\s+/, $config{'sockets'})) {
458 if ($s =~ /^(\d+)$/) {
459 # Just listen on another port on the main IP
460 push(@sockets, [ $sockets[0]->[0], $s, $sockets[0]->[2] ]);
461 if ($use_ipv6 && !$config{'bind'}) {
462 # Also listen on that port on the main IPv6 address
463 push(@sockets, [ $sockets[1]->[0], $s,
467 elsif ($s =~ /^\*:(\d+)$/) {
468 # Listening on all IPs on some port
469 push(@sockets, [ INADDR_ANY, $config{'port'},
472 push(@sockets, [ in6addr_any(), $config{'port'},
473 Socket6::PF_INET6() ]);
476 elsif ($s =~ /^(\S+):(\d+)$/) {
477 # Listen on a specific port and IP
478 my ($ip, $port) = ($1, $2);
479 if (&check_ip6address($ip)) {
480 $use_ipv6 || die "Cannot bind to $ip without IPv6";
481 push(@sockets, [ inet_pton(Socket6::AF_INET6(),
483 $port, Socket6::PF_INET6() ]);
486 push(@sockets, [ inet_aton($ip), $port,
490 elsif ($s =~ /^([0-9\.]+):\*$/ || $s =~ /^([0-9\.]+)$/) {
491 # Listen on the main port on another IPv4 address
492 push(@sockets, [ inet_aton($1), $sockets[0]->[1],
495 elsif (($s =~ /^([0-9a-f\:]+):\*$/ || $s =~ /^([0-9a-f\:]+)$/) &&
497 # Listen on the main port on another IPv6 address
498 push(@sockets, [ inet_pton(Socket6::AF_INET6(), $1),
500 Socket6::PF_INET6() ]);
504 # Open all the sockets
505 $proto = getprotobyname('tcp');
507 $tried_inaddr_any = 0;
508 for($i=0; $i<@sockets; $i++) {
510 socket($fh, $sockets[$i]->[2], SOCK_STREAM, $proto) ||
511 die "Failed to open socket family $sockets[$i]->[2] : $!";
512 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
513 if ($sockets[$i]->[2] eq PF_INET) {
514 $pack = pack_sockaddr_in($sockets[$i]->[1], $sockets[$i]->[0]);
517 $pack = pack_sockaddr_in6($sockets[$i]->[1], $sockets[$i]->[0]);
518 setsockopt($fh, 41, 26, pack("l", 1)); # IPv6 only
520 for($j=0; $j<5; $j++) {
521 last if (bind($fh, $pack));
525 # All attempts failed .. give up
526 if ($sockets[$i]->[0] eq INADDR_ANY ||
527 $use_ipv6 && $sockets[$i]->[0] eq in6addr_any()) {
529 "Failed to bind to port $sockets[$i]->[1] : $!");
530 $tried_inaddr_any = 1;
533 $ip = &network_to_address($sockets[$i]->[0]);
535 "Failed to bind to IP $ip port ".
536 "$sockets[$i]->[1] : $!");
540 listen($fh, SOMAXCONN);
541 push(@socketfhs, $fh);
542 $ipv6fhs{$fh} = $sockets[$i]->[2] eq PF_INET ? 0 : 1;
545 foreach $se (@sockerrs) {
546 print STDERR $se,"\n";
549 # If all binds failed, try binding to any address
550 if (!@socketfhs && !$tried_inaddr_any) {
551 print STDERR "Falling back to listening on any address\n";
553 socket($fh, PF_INET, SOCK_STREAM, $proto) ||
554 die "Failed to open socket : $!";
555 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
556 bind($fh, pack_sockaddr_in($sockets[0]->[1], INADDR_ANY)) ||
557 die "Failed to bind to port $sockets[0]->[1] : $!";
558 listen($fh, SOMAXCONN);
559 push(@socketfhs, $fh);
561 elsif (!@socketfhs && $tried_inaddr_any) {
562 die "Could not listen on any ports";
565 if ($config{'listen'}) {
566 # Open the socket that allows other webmin servers to find this one
567 $proto = getprotobyname('udp');
568 if (socket(LISTEN, PF_INET, SOCK_DGRAM, $proto)) {
569 setsockopt(LISTEN, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
570 bind(LISTEN, pack_sockaddr_in($config{'listen'}, INADDR_ANY));
571 listen(LISTEN, SOMAXCONN);
574 $config{'listen'} = 0;
578 # Split from the controlling terminal, unless configured not to
579 if (!$config{'nofork'}) {
580 if (fork()) { exit; }
582 eval { setsid(); }; # may not work on Windows
584 # Close standard file handles
585 open(STDIN, "</dev/null");
586 open(STDOUT, ">/dev/null");
587 &log_error("miniserv.pl started");
588 foreach $msg (@startup_msg) {
592 # write out the PID file
595 # Start the log-clearing process, if needed. This checks every minute
596 # to see if the log has passed its reset time, and if so clears it
597 if ($config{'logclear'}) {
598 if (!($logclearer = fork())) {
599 &close_all_sockets();
602 local $write_logtime = 0;
603 local @st = stat("$config{'logfile'}.time");
605 if ($st[9]+$config{'logtime'}*60*60 < time()){
608 unlink($config{'logfile'});
611 else { $write_logtime = 1; }
612 if ($write_logtime) {
613 open(LOGTIME, ">$config{'logfile'}.time");
614 print LOGTIME time(),"\n";
621 push(@childpids, $logclearer);
624 # Setup the logout time dbm if needed
625 if ($config{'session'}) {
626 eval "use SDBM_File";
627 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
628 eval "\$sessiondb{'1111111111'} = 'foo bar';";
630 dbmclose(%sessiondb);
631 eval "use NDBM_File";
632 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
635 delete($sessiondb{'1111111111'});
640 $SIG{'HUP'} = 'miniserv::trigger_restart';
641 $SIG{'TERM'} = 'miniserv::term_handler';
642 $SIG{'USR1'} = 'miniserv::trigger_reload';
643 $SIG{'PIPE'} = 'IGNORE';
644 local $remove_session_count = 0;
645 $need_pipes = $config{'passdelay'} || $config{'session'};
647 # wait for a new connection, or a message from a child process
649 if (@childpids <= $config{'maxconns'}) {
650 # Only accept new main socket connects when ready
652 foreach $s (@socketfhs) {
653 vec($rmask, fileno($s), 1) = 1;
657 printf STDERR "too many children (%d > %d)\n",
658 scalar(@childpids), $config{'maxconns'};
661 for($i=0; $i<@passin; $i++) {
662 vec($rmask, fileno($passin[$i]), 1) = 1;
665 vec($rmask, fileno(LISTEN), 1) = 1 if ($config{'listen'});
667 # Wait for a connection
668 local $sel = select($rmask, undef, undef, 10);
670 # Check the flag files
671 if ($config{'restartflag'} && -r $config{'restartflag'}) {
672 print STDERR "restart flag file detected\n";
673 unlink($config{'restartflag'});
676 if ($config{'reloadflag'} && -r $config{'reloadflag'}) {
677 unlink($config{'reloadflag'});
682 # Got a HUP signal while in select() .. restart now
686 # Got a USR1 signal while in select() .. re-read config
688 &reload_config_file();
690 local $time_now = time();
692 # Clean up finished processes
694 do { $pid = waitpid(-1, WNOHANG);
695 @childpids = grep { $_ != $pid } @childpids;
696 } while($pid != 0 && $pid != -1);
698 # run the unblocking procedure to check if enough time has passed to
699 # unblock hosts that heve been blocked because of password failures
701 if ($config{'blockhost_failures'}) {
703 while ($i <= $#deny) {
704 if ($blockhosttime{$deny[$i]} &&
705 $config{'blockhost_time'} != 0 &&
706 ($time_now - $blockhosttime{$deny[$i]}) >=
707 $config{'blockhost_time'}) {
708 # the host can be unblocked now
709 $hostfail{$deny[$i]} = 0;
710 splice(@deny, $i, 1);
717 # Do the same for blocked users
718 if ($config{'blockuser_failures'}) {
720 while ($i <= $#deny) {
721 if ($blockusertime{$deny[$i]} &&
722 $config{'blockuser_time'} != 0 &&
723 ($time_now - $blockusertime{$deny[$i]}) >=
724 $config{'blockuser_time'}) {
725 # the user can be unblocked now
726 $userfail{$deny[$i]} = 0;
727 splice(@denyusers, $i, 1);
734 &write_blocked_file();
737 # Check if any webmin cron jobs are ready to run
738 &execute_ready_webmin_crons();
740 if ($config{'session'} && (++$remove_session_count%50) == 0) {
741 # Remove sessions with more than 7 days of inactivity,
743 foreach $s (keys %sessiondb) {
744 local ($user, $ltime, $lip) =
745 split(/\s+/, $sessiondb{$s});
746 if ($time_now - $ltime > 7*24*60*60) {
747 &run_logout_script($s, $user);
748 &write_logout_utmp($user, $lip);
749 delete($sessiondb{$s});
752 "Timeout of session for $user");
758 if ($use_pam && $config{'pam_conv'}) {
759 # Remove PAM sessions with more than 5 minutes of inactivity
761 foreach $c (values %conversations) {
762 if ($time_now - $c->{'time'} > 5*60) {
763 &end_pam_conversation($c);
765 syslog("info", "%s", "Timeout of PAM ".
766 "session for $c->{'user'}");
772 # Don't check any sockets if there is no activity
775 # Check if any of the main sockets have received a new connection
777 foreach $s (@socketfhs) {
778 if (vec($rmask, fileno($s), 1)) {
780 $acptaddr = accept(SOCK, $s);
781 if (!$acptaddr) { next; }
782 binmode(SOCK); # turn off any Perl IO stuff
785 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
787 ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw) =
791 # Work out IP and port of client
792 local ($peerb, $peera, $peerp) =
793 &get_address_ip($acptaddr, $ipv6fhs{$s});
795 # Work out the local IP
796 (undef, $locala) = &get_socket_ip(SOCK, $ipv6fhs{$s});
798 # Check username of connecting user
799 $localauth_user = undef;
800 if ($config{'localauth'} && $peera eq "127.0.0.1") {
801 if (open(TCP, "/proc/net/tcp")) {
802 # Get the info direct from the kernel
803 $peerh = sprintf("%4.4X", $peerp);
806 local @t = split(/[\s:]+/, $_);
807 if ($t[1] eq '0100007F' &&
816 if (!$localauth_user) {
817 # Call lsof for the info
818 local $lsofpid = open(LSOF,
819 "$config{'localauth'} -i ".
820 "TCP\@127.0.0.1:$peerp |");
822 if (/^(\S+)\s+(\d+)\s+(\S+)/ &&
823 $2 != $$ && $2 != $lsofpid){
824 $localauth_user = $3;
831 # Work out the hostname for this web server
832 $host = &get_socket_name(SOCK, $ipv6fhs{$s});
835 "Failed to get local socket name : $!\n";
839 $port = $sockets[$sn]->[1];
841 # fork the subprocess
843 if (!($handpid = fork())) {
844 # setup signal handlers
845 $SIG{'TERM'} = 'DEFAULT';
846 $SIG{'PIPE'} = 'DEFAULT';
847 #$SIG{'CHLD'} = 'IGNORE';
848 $SIG{'HUP'} = 'IGNORE';
849 $SIG{'USR1'} = 'IGNORE';
851 # Initialize SSL for this connection
853 $ssl_con = &ssl_connection_for_ip(SOCK);
857 # Close the file handle for the session DBM
858 dbmclose(%sessiondb);
860 # close useless pipes
863 close($PASSINr); close($PASSOUTw);
865 &close_all_sockets();
869 "main: Starting handle_request loop pid=$$\n";
870 while(&handle_request($peera, $locala,
872 # Loop until keepalive stops
875 "main: Done handle_request loop pid=$$\n";
878 close($PASSINw); close($PASSOUTw);
881 push(@childpids, $handpid);
883 close($PASSINw); close($PASSOUTr);
884 push(@passin, $PASSINr);
885 push(@passout, $PASSOUTw);
892 if ($config{'listen'} && vec($rmask, fileno(LISTEN), 1)) {
893 # Got UDP packet from another webmin server
895 local $from = recv(LISTEN, $rcvbuf, 1024, 0);
897 local $fromip = inet_ntoa((unpack_sockaddr_in($from))[1]);
898 local $toip = inet_ntoa((unpack_sockaddr_in(
899 getsockname(LISTEN)))[1]);
900 if ((!@deny || !&ip_match($fromip, $toip, @deny)) &&
901 (!@allow || &ip_match($fromip, $toip, @allow))) {
902 local $listenhost = &get_socket_name(LISTEN, 0);
903 send(LISTEN, "$listenhost:$config{'port'}:".
904 ($use_ssl || $config{'inetd_ssl'} ? 1 : 0).":".
905 ($config{'listenhost'} ?
906 &get_system_hostname() : ""),
912 # check for session, password-timeout and PAM messages from subprocesses
913 for($i=0; $i<@passin; $i++) {
914 if (vec($rmask, fileno($passin[$i]), 1)) {
915 # this sub-process is asking about a password
916 local $infd = $passin[$i];
917 local $outfd = $passout[$i];
918 #local $inline = <$infd>;
919 local $inline = &sysread_line($infd);
921 print DEBUG "main: inline $inline";
924 print DEBUG "main: inline EOF\n";
926 if ($inline =~ /^delay\s+(\S+)\s+(\S+)\s+(\d+)/) {
927 # Got a delay request from a subprocess.. for
928 # valid logins, there is no delay (to prevent
929 # denial of service attacks), but for invalid
930 # logins the delay increases with each failed
933 # login OK.. no delay
934 print $outfd "0 0\n";
935 $wasblocked = $hostfail{$2} ||
940 &write_blocked_file();
949 # add the host to the block list,
951 if ($config{'blockhost_failures'} &&
953 $config{'blockhost_failures'}) {
955 $blockhosttime{$2} = $time_now;
958 local $logtext = "Security alert: Host $2 blocked after $config{'blockhost_failures'} failed logins for user $1";
964 # add the user to the user block list,
966 if ($config{'blockuser_failures'} &&
968 $config{'blockuser_failures'}) {
969 push(@denyusers, $1);
970 $blockusertime{$1} = $time_now;
973 local $logtext = "Security alert: User $1 blocked after $config{'blockuser_failures'} failed logins";
979 # Lock out the user's password, if enabled
980 if ($config{'blocklock'} &&
982 $config{'blockuser_failures'}) {
983 my $lk = &lock_user_password($1);
986 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";
993 $dl = $userdlay{$1} -
994 int(($time_now - $userlast{$1})/50);
995 $dl = $dl < 0 ? 0 : $dl+1;
996 print $outfd "$dl $blocked\n";
999 # Write out blocked status file
1001 &write_blocked_file();
1004 $userlast{$1} = $time_now;
1006 elsif ($inline =~ /^verify\s+(\S+)\s+(\S+)/) {
1007 # Verifying a session ID
1008 local $session_id = $1;
1009 local $notimeout = $2;
1010 local $skey = $sessiondb{$session_id} ?
1012 &hash_session_id($session_id);
1013 if (!defined($sessiondb{$skey})) {
1014 # Session doesn't exist
1015 print $outfd "0 0\n";
1018 local ($user, $ltime) =
1019 split(/\s+/, $sessiondb{$skey});
1020 local $lot = &get_logout_time($user, $session_id);
1022 $time_now - $ltime > $lot*60 &&
1024 # Session has timed out
1025 print $outfd "1 ",$time_now - $ltime,"\n";
1026 #delete($sessiondb{$skey});
1030 print $outfd "2 $user\n";
1032 $time_now - $ltime >
1034 $sessiondb{$skey} = "$user $time_now";
1039 elsif ($inline =~ /^new\s+(\S+)\s+(\S+)\s+(\S+)/) {
1040 # Creating a new session
1041 local $session_id = $1;
1044 $sessiondb{&hash_session_id($session_id)} =
1045 "$user $time_now $ip";
1047 elsif ($inline =~ /^delete\s+(\S+)/) {
1048 # Logging out a session
1049 local $session_id = $1;
1050 local $skey = $sessiondb{$session_id} ?
1052 &hash_session_id($session_id);
1053 local @sdb = split(/\s+/, $sessiondb{$skey});
1054 print $outfd $sdb[0],"\n";
1055 delete($sessiondb{$skey});
1057 elsif ($inline =~ /^pamstart\s+(\S+)\s+(\S+)\s+(.*)/) {
1058 # Starting a new PAM conversation
1059 local ($cid, $host, $user) = ($1, $2, $3);
1061 # Does this user even need PAM?
1062 local ($realuser, $canlogin) =
1063 &can_user_login($user, undef, $host);
1065 if ($canlogin == 0) {
1066 # Cannot even login!
1067 print $outfd "0 Invalid username\n";
1069 elsif ($canlogin != 2) {
1070 # Not using PAM .. so just ask for
1072 $conv = { 'user' => $realuser,
1077 print $outfd "3 Password\n";
1080 # Start the PAM conversation
1081 # sub-process, and get a question
1082 $conv = { 'user' => $realuser,
1086 local ($PAMINr, $PAMINw, $PAMOUTr,
1087 $PAMOUTw) = &allocate_pipes();
1088 local $pampid = fork();
1090 close($PAMOUTr); close($PAMINw);
1091 &pam_conversation_process(
1095 close($PAMOUTw); close($PAMINr);
1096 $conv->{'pid'} = $pampid;
1097 $conv->{'PAMOUTr'} = $PAMOUTr;
1098 $conv->{'PAMINw'} = $PAMINw;
1099 push(@childpids, $pampid);
1101 # Get the first PAM question
1102 local $pok = &recv_pam_question(
1105 &end_pam_conversation($conv);
1109 $conversations{$cid} = $conv if ($conv);
1111 elsif ($inline =~ /^pamanswer\s+(\S+)\s+(.*)/) {
1112 # A response to a PAM question
1113 local ($cid, $answer) = ($1, $2);
1114 local $conv = $conversations{$cid};
1116 # No such conversation?
1117 print $outfd "0 Bad login session\n";
1119 elsif ($conv->{'pid'}) {
1120 # Send the PAM response and get
1122 &send_pam_answer($conv, $answer);
1123 local $pok = &recv_pam_question($conv, $outfd);
1125 &end_pam_conversation($conv);
1129 # This must be the password .. try it
1130 # and send back the results
1131 local ($vu, $expired, $nonexist) =
1132 &validate_user($conv->{'user'},
1135 local $ok = $vu ? 1 : 0;
1136 print $outfd "2 $conv->{'user'} $ok $expired $notexist\n";
1137 &end_pam_conversation($conv);
1140 elsif ($inline =~ /^writesudo\s+(\S+)\s+(\d+)/) {
1141 # Store the fact that some user can sudo to root
1142 local ($user, $ok) = ($1, $2);
1143 $sudocache{$user} = $ok." ".time();
1145 elsif ($inline =~ /^readsudo\s+(\S+)/) {
1146 # Query the user sudo cache (valid for 1 minute)
1148 local ($ok, $last) =
1149 split(/\s+/, $sudocache{$user});
1150 if ($last < time()-60) {
1155 # Tell client OK or not
1156 print $outfd "$ok\n";
1159 elsif ($inline =~ /\S/) {
1160 # Unknown line from pipe?
1161 print DEBUG "main: Unknown line from pipe $inline\n";
1162 print STDERR "Unknown line from pipe $inline\n";
1166 close($infd); close($outfd);
1167 $passin[$i] = $passout[$i] = undef;
1171 @passin = grep { defined($_) } @passin;
1172 @passout = grep { defined($_) } @passout;
1175 # handle_request(remoteaddress, localaddress, ipv6-flag)
1176 # Where the real work is done
1179 local ($acptip, $localip, $ipv6) = @_;
1180 print DEBUG "handle_request: from $acptip to $localip ipv6=$ipv6\n";
1181 if ($config{'loghost'}) {
1182 $acpthost = &to_hostname($acptip);
1183 $acpthost = $acptip if (!$acpthost);
1186 $acpthost = $acptip;
1188 $datestr = &http_date(time());
1190 $ok_message = "Document follows";
1191 $logged_code = undef;
1192 $reqline = $request_uri = $page = undef;
1196 # check address against access list
1197 if (@deny && &ip_match($acptip, $localip, @deny) ||
1198 @allow && !&ip_match($acptip, $localip, @allow)) {
1199 &http_error(403, "Access denied for $acptip");
1204 # Check address with TCP-wrappers
1205 if (!hosts_ctl($config{'pam'}, STRING_UNKNOWN,
1206 $acptip, STRING_UNKNOWN)) {
1207 &http_error(403, "Access denied for $acptip by TCP wrappers");
1211 print DEBUG "handle_request: passed IP checks\n";
1213 # Compute a timeout for the start of headers, based on the number of
1214 # child processes. As this increases, we use a shorter timeout to avoid
1215 # an attacker overloading the system.
1216 local $header_timeout = 60 + ($config{'maxconns'} - @childpids) * 10;
1218 # Wait at most 60 secs for start of headers for initial requests, or
1219 # 10 minutes for kept-alive connections
1221 vec($rmask, fileno(SOCK), 1) = 1;
1222 local $to = $checked_timeout ? 10*60 : $header_timeout;
1223 local $sel = select($rmask, undef, undef, $to);
1225 if ($checked_timeout) {
1226 print DEBUG "handle_request: exiting due to timeout of $to\n";
1230 &http_error(400, "Timeout",
1231 "Waited for that $to seconds for start of headers");
1235 print DEBUG "handle_request: passed timeout check\n";
1237 # Read the HTTP request and headers
1238 local $origreqline = &read_line();
1239 ($reqline = $origreqline) =~ s/\r|\n//g;
1240 $method = $page = $request_uri = undef;
1241 print DEBUG "handle_request reqline=$reqline\n";
1242 if (!$reqline && (!$use_ssl || $checked_timeout > 1)) {
1243 # An empty request .. just close the connection
1244 print DEBUG "handle_request: rejecting empty request\n";
1247 elsif ($reqline !~ /^(\S+)\s+(.*)\s+HTTP\/1\..$/) {
1248 print DEBUG "handle_request: invalid reqline=$reqline\n";
1250 # This could be an http request when it should be https
1252 local $url = $config{'musthost'} ?
1253 "https://$config{'musthost'}:$port/" :
1254 "https://$host:$port/";
1255 if ($config{'ssl_redirect'}) {
1256 # Just re-direct to the correct URL
1257 sleep(1); # Give browser a change to finish
1258 # sending its request
1259 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1260 &write_data("Date: $datestr\r\n");
1261 &write_data("Server: $config{'server'}\r\n");
1262 &write_data("Location: $url\r\n");
1263 &write_keep_alive(0);
1264 &write_data("\r\n");
1268 # Tell user the correct URL
1269 &http_error(200, "Bad Request", "This web server is running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1272 elsif (ord(substr($reqline, 0, 1)) == 128 && !$use_ssl) {
1273 # This could be an https request when it should be http ..
1274 # need to fake a HTTP response
1277 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
1278 eval "Net::SSLeay::load_error_strings()";
1279 $ssl_ctx = Net::SSLeay::CTX_new();
1280 Net::SSLeay::CTX_use_RSAPrivateKey_file(
1281 $ssl_ctx, $config{'keyfile'},
1282 &Net::SSLeay::FILETYPE_PEM);
1283 Net::SSLeay::CTX_use_certificate_file(
1285 $config{'certfile'} || $config{'keyfile'},
1286 &Net::SSLeay::FILETYPE_PEM);
1287 $ssl_con = Net::SSLeay::new($ssl_ctx);
1291 select(SSLw); $| = 1; select(STDOUT);
1292 print SSLw $origreqline;
1294 while(sysread(SOCK, $buf, 1) > 0) {
1301 Net::SSLeay::set_wfd($ssl_con, fileno(SOCK));
1302 Net::SSLeay::set_rfd($ssl_con, fileno(SSLr));
1303 Net::SSLeay::accept($ssl_con) || die "accept() failed";
1305 local $url = $config{'musthost'} ?
1306 "https://$config{'musthost'}:$port/" :
1307 "https://$host:$port/";
1308 if ($config{'ssl_redirect'}) {
1309 # Just re-direct to the correct URL
1310 sleep(1); # Give browser a change to
1311 # finish sending its request
1312 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1313 &write_data("Date: $datestr\r\n");
1314 &write_data("Server: $config{'server'}\r\n");
1315 &write_data("Location: $url\r\n");
1316 &write_keep_alive(0);
1317 &write_data("\r\n");
1321 # Tell user the correct URL
1322 &http_error(200, "Bad Request", "This web server is not running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1326 &http_error(400, "Bad Request");
1330 &http_error(400, "Bad Request");
1334 $request_uri = $page = $2;
1338 ($headline = &read_line()) =~ s/\r|\n//g;
1339 last if ($headline eq "");
1340 print DEBUG "handle_request: got headline $headline\n";
1341 if ($headline =~ /^(\S+):\s*(.*)$/) {
1342 $header{$lastheader = lc($1)} = $2;
1344 elsif ($headline =~ /^\s+(.*)$/) {
1345 $header{$lastheader} .= $headline;
1348 &http_error(400, "Bad Header $headline");
1351 if (defined($header{'host'})) {
1352 if ($header{'host'} =~ /^([^:]+):([0-9]+)$/) {
1353 ($host, $port) = ($1, $2);
1356 $host = $header{'host'};
1358 if ($config{'musthost'} && $host ne $config{'musthost'}) {
1359 # Disallowed hostname used
1360 &http_error(400, "Invalid HTTP hostname");
1364 if ($page =~ /^([^\?]+)\?(.*)$/) {
1365 # There is some query string information
1368 print DEBUG "handle_request: querystring=$querystring\n";
1369 if ($querystring !~ /=/) {
1370 $queryargs = $querystring;
1371 $queryargs =~ s/\+/ /g;
1372 $queryargs =~ s/%(..)/pack("c",hex($1))/ge;
1376 # Parse query-string parameters
1377 local @in = split(/\&/, $querystring);
1379 local ($k, $v) = split(/=/, $i, 2);
1380 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1381 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1386 $posted_data = undef;
1387 if ($method eq 'POST' &&
1388 $header{'content-type'} eq 'application/x-www-form-urlencoded') {
1389 # Read in posted query string information, up the configured maximum
1390 # post request length
1391 $clen = $header{"content-length"};
1392 $clen_read = $clen > $config{'max_post'} ? $config{'max_post'} : $clen;
1393 while(length($posted_data) < $clen_read) {
1394 $buf = &read_data($clen_read - length($posted_data));
1395 if (!length($buf)) {
1396 &http_error(500, "Failed to read POST request");
1398 chomp($posted_data);
1399 $posted_data =~ s/\015$//mg;
1400 $posted_data .= $buf;
1402 print DEBUG "clen_read=$clen_read clen=$clen posted_data=",length($posted_data),"\n";
1403 if ($clen_read != $clen && length($posted_data) > $clen) {
1404 # If the client sent more data than we asked for, chop the
1406 $posted_data = substr($posted_data, 0, $clen);
1408 if (length($posted_data) > $clen) {
1409 # When the client sent too much, delay so that it gets headers
1412 if ($header{'user-agent'} =~ /MSIE/ &&
1413 $header{'user-agent'} !~ /Opera/i) {
1414 # MSIE includes an extra newline in the data
1415 $posted_data =~ s/\r|\n//g;
1417 local @in = split(/\&/, $posted_data);
1419 local ($k, $v) = split(/=/, $i, 2);
1421 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1422 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1425 print DEBUG "handle_request: posted_data=$posted_data\n";
1428 # replace %XX sequences in page
1429 $page =~ s/%(..)/pack("c",hex($1))/ge;
1431 # Check if the browser's user agent indicates a mobile device
1432 $mobile_device = &is_mobile_useragent($header{'user-agent'});
1434 # Check if Host: header is for a mobile URL
1435 foreach my $m (@mobile_prefixes) {
1436 if ($header{'host'} =~ /^\Q$m\E/i) {
1441 # check for the logout flag file, and if existant deny authentication
1442 if ($config{'logout'} && -r $config{'logout'}.$in{'miniserv_logout_id'}) {
1443 print DEBUG "handle_request: logout flag set\n";
1444 $deny_authentication++;
1445 open(LOGOUT, $config{'logout'}.$in{'miniserv_logout_id'});
1446 chop($count = <LOGOUT>);
1450 open(LOGOUT, ">$config{'logout'}$in{'miniserv_logout_id'}");
1451 print LOGOUT "$count\n";
1455 unlink($config{'logout'}.$in{'miniserv_logout_id'});
1459 # check for any redirect for the requested URL
1460 foreach my $pfx (@strip_prefix) {
1461 my $l = length($pfx);
1462 if(length($page) >= $l &&
1463 substr($page,0,$l) eq $pfx) {
1464 $page=substr($page,$l);
1468 $simple = &simplify_path($page, $bogus);
1470 $rpath .= "&".$querystring if (defined($querystring));
1471 $redir = $redirect{$rpath};
1472 if (defined($redir)) {
1473 print DEBUG "handle_request: redir=$redir\n";
1474 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1475 &write_data("Date: $datestr\r\n");
1476 &write_data("Server: $config{'server'}\r\n");
1477 local $ssl = $use_ssl || $config{'inetd_ssl'};
1478 $portstr = $port == 80 && !$ssl ? "" :
1479 $port == 443 && $ssl ? "" : ":$port";
1480 $prot = $ssl ? "https" : "http";
1481 &write_data("Location: $prot://$host$portstr$redir\r\n");
1482 &write_keep_alive(0);
1483 &write_data("\r\n");
1487 # Check for a DAV request
1489 foreach my $d (@davpaths) {
1490 if ($simple eq $d || $simple =~ /^\Q$d\E\//) {
1495 if (!$davpath && ($method eq "SEARCH" || $method eq "PUT")) {
1496 &http_error(400, "Bad Request method $method");
1499 # Check for password if needed
1500 if ($config{'userfile'}) {
1501 print DEBUG "handle_request: Need authentication\n";
1505 # Session authentication is never used for connections by
1506 # another webmin server, or for specified pages, or for DAV, or XMLRPC,
1507 # or mobile browsers if requested.
1508 if ($header{'user-agent'} =~ /webmin/i ||
1509 $header{'user-agent'} =~ /$config{'agents_nosession'}/i ||
1510 $sessiononly{$simple} || $davpath ||
1511 $simple eq "/xmlrpc.cgi" ||
1512 $acptip eq $config{'host_nosession'} ||
1513 $mobile_device && $config{'mobile_nosession'}) {
1514 print DEBUG "handle_request: Forcing HTTP authentication\n";
1515 $config{'session'} = 0;
1518 # Check for SSL authentication
1519 if ($use_ssl && $verified_client) {
1520 $peername = Net::SSLeay::X509_NAME_oneline(
1521 Net::SSLeay::X509_get_subject_name(
1522 Net::SSLeay::get_peer_certificate(
1524 $u = &find_user_by_cert($peername);
1529 if ($use_syslog && !$validated) {
1530 syslog("crit", "%s",
1531 "Unknown SSL certificate $peername");
1535 if (!$validated && !$deny_authentication) {
1536 # check for IP-based authentication
1538 foreach $a (keys %ipaccess) {
1539 if ($acptip eq $a) {
1540 # It does! Auth as the user
1542 $baseauthuser = $authuser =
1548 # Check for normal HTTP authentication
1549 if (!$validated && !$deny_authentication && !$config{'session'} &&
1550 $header{authorization} =~ /^basic\s+(\S+)$/i) {
1551 # authorization given..
1552 ($authuser, $authpass) = split(/:/, &b64decode($1), 2);
1553 print DEBUG "handle_request: doing basic auth check authuser=$authuser authpass=$authpass\n";
1554 local ($vu, $expired, $nonexist) =
1555 &validate_user($authuser, $authpass, $host);
1556 print DEBUG "handle_request: vu=$vu expired=$expired nonexist=$nonexist\n";
1557 if ($vu && (!$expired || $config{'passwd_mode'} == 1)) {
1564 if ($use_syslog && !$validated) {
1565 syslog("crit", "%s",
1566 ($nonexist ? "Non-existent" :
1567 $expired ? "Expired" : "Invalid").
1568 " login as $authuser from $acpthost");
1570 if ($authuser =~ /\r|\n|\s/) {
1571 &http_error(500, "Invalid username",
1572 "Username contains invalid characters");
1574 if ($authpass =~ /\r|\n/) {
1575 &http_error(500, "Invalid password",
1576 "Password contains invalid characters");
1579 if ($config{'passdelay'} && !$config{'inetd'} && $authuser) {
1580 # check with main process for delay
1581 print DEBUG "handle_request: about to ask for password delay\n";
1582 print $PASSINw "delay $authuser $acptip $validated\n";
1583 <$PASSOUTr> =~ /(\d+) (\d+)/;
1585 print DEBUG "handle_request: password delay $1 $2\n";
1590 # Check for a visit to the special session login page
1591 if ($config{'session'} && !$deny_authentication &&
1592 $page eq $config{'session_login'}) {
1593 if ($in{'logout'} && $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1594 # Logout clicked .. remove the session
1596 print $PASSINw "delete $sid\n";
1597 local $louser = <$PASSOUTr>;
1600 $already_session_id = undef;
1601 $authuser = $baseauthuser = undef;
1604 syslog("info", "%s", "Logout by $louser from $acpthost");
1606 &run_logout_script($louser, $sid,
1608 &write_logout_utmp($louser, $actphost);
1613 if ($in{'user'} =~ /\r|\n|\s/) {
1614 &http_error(500, "Invalid username",
1615 "Username contains invalid characters");
1617 if ($in{'pass'} =~ /\r|\n/) {
1618 &http_error(500, "Invalid password",
1619 "Password contains invalid characters");
1622 local ($vu, $expired, $nonexist) =
1623 &validate_user($in{'user'}, $in{'pass'}, $host);
1624 local $hrv = &handle_login(
1625 $vu || $in{'user'}, $vu ? 1 : 0,
1626 $expired, $nonexist, $in{'pass'},
1627 $in{'notestingcookie'});
1628 return $hrv if (defined($hrv));
1632 # Check for a visit to the special PAM login page
1633 if ($config{'session'} && !$deny_authentication &&
1634 $use_pam && $config{'pam_conv'} && $page eq $config{'pam_login'} &&
1636 # A question has been entered .. submit it to the main process
1637 print DEBUG "handle_request: Got call to $page ($in{'cid'})\n";
1638 print DEBUG "handle_request: For PAM, authuser=$authuser\n";
1639 if ($in{'answer'} =~ /\r|\n/ || $in{'cid'} =~ /\r|\n|\s/) {
1640 &http_error(500, "Invalid response",
1641 "Response contains invalid characters");
1645 # Start of a new conversation - answer must be username
1646 $cid = &generate_random_id($in{'answer'});
1647 print $PASSINw "pamstart $cid $host $in{'answer'}\n";
1650 # A response to a previous question
1652 print $PASSINw "pamanswer $cid $in{'answer'}\n";
1655 # Read back the response, and the next question (if any)
1656 local $line = <$PASSOUTr>;
1657 $line =~ s/\r|\n//g;
1658 local ($rv, $question) = split(/\s+/, $line, 2);
1661 local $hrv = &handle_login(
1662 !$in{'cid'} && $in{'answer'} ? $in{'answer'}
1665 return $hrv if (defined($hrv));
1667 elsif ($rv == 1 || $rv == 3) {
1668 # Another question .. force use of PAM CGI
1671 $querystring .= "&cid=$cid&question=".
1673 $querystring .= "&password=1" if ($rv == 3);
1675 $page = $config{'pam_login'};
1676 $miniserv_internal = 1;
1680 # Got back a final ok or failure
1681 local ($user, $ok, $expired, $nonexist) =
1682 split(/\s+/, $question);
1683 local $hrv = &handle_login(
1684 $user, $ok, $expired, $nonexist, undef,
1685 $in{'notestingcookie'});
1686 return $hrv if (defined($hrv));
1689 # A message from PAM .. tell the user
1692 $querystring .= "&cid=$cid&message=".
1695 $page = $config{'pam_login'};
1696 $miniserv_internal = 1;
1701 # Check for a visit to the special password change page
1702 if ($config{'session'} && !$deny_authentication &&
1703 $page eq $config{'password_change'} && !$validated) {
1704 # Just let this slide ..
1706 $miniserv_internal = 3;
1709 # Check for an existing session
1710 if ($config{'session'} && !$validated) {
1711 if ($already_session_id) {
1712 $session_id = $already_session_id;
1713 $authuser = $already_authuser;
1716 elsif (!$deny_authentication &&
1717 $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1718 # Try all session cookies
1719 local $cookie = $header{'cookie'};
1720 while($cookie =~ s/(^|\s)$sidname=([a-f0-9]+)//) {
1723 $in{'webmin_notimeout'} ? 1 : 0;
1724 print $PASSINw "verify $session_id $notimeout\n";
1725 <$PASSOUTr> =~ /(\d+)\s+(\S+)/;
1727 # Valid session continuation
1730 $already_authuser = $authuser;
1739 # Invalid session ID .. don't set
1746 # Check for local authentication
1747 if ($localauth_user && !$header{'x-forwarded-for'} && !$header{'via'}) {
1748 my $luser = &get_user_details($localauth_user);
1750 # Local user exists in webmin users file
1752 $authuser = $localauth_user;
1755 # Check if local user is allowed by unixauth
1756 local @can = &can_user_login($localauth_user,
1760 $authuser = $localauth_user;
1763 $localauth_user = undef;
1769 # Check if this path allows anonymous access
1771 foreach $a (keys %anonymous) {
1772 if (substr($simple, 0, length($a)) eq $a) {
1773 # It does! Auth as the user, if IP access
1774 # control allows him.
1775 if (&check_user_ip($anonymous{$a}) &&
1776 &check_user_time($anonymous{$a})) {
1778 $baseauthuser = $authuser =
1786 # Check if this path allows unauthenticated access
1787 local ($u, $unauth);
1788 foreach $u (@unauth) {
1789 $unauth++ if ($simple =~ /$u/);
1791 if (!$bogus && $unauth) {
1792 # Unauthenticated directory or file request - approve it
1794 $baseauthuser = $authuser = undef;
1799 if ($blocked == 0) {
1800 # No password given.. ask
1801 if ($config{'pam_conv'} && $use_pam) {
1802 # Force CGI for PAM question, starting with
1803 # the username which is always needed
1806 $querystring .= "&initial=1&question=".
1807 &urlize("Username");
1808 $querystring .= "&failed=$failed_user" if ($failed_user);
1809 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1811 $page = $config{'pam_login'};
1812 $miniserv_internal = 1;
1815 elsif ($config{'session'}) {
1816 # Force CGI for session login
1819 $querystring .= "&logout=1&page=/";
1822 # Re-direct to current module only
1823 local $rpage = $request_uri;
1824 if (!$config{'loginkeeppage'}) {
1825 $rpage =~ s/\?.*$//;
1826 $rpage =~ s/[^\/]+$//
1828 $querystring = "page=".&urlize($rpage);
1831 $querystring .= "&failed=$failed_user" if ($failed_user);
1832 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1834 $page = $config{'session_login'};
1835 $miniserv_internal = 1;
1839 # Ask for login with HTTP authentication
1840 &write_data("HTTP/1.0 401 Unauthorized\r\n");
1841 &write_data("Date: $datestr\r\n");
1842 &write_data("Server: $config{'server'}\r\n");
1843 &write_data("WWW-authenticate: Basic ".
1844 "realm=\"$config{'realm'}\"\r\n");
1845 &write_keep_alive(0);
1846 &write_data("Content-type: text/html\r\n");
1847 &write_data("\r\n");
1848 &reset_byte_count();
1849 &write_data("<html>\n");
1850 &write_data("<head><title>Unauthorized</title></head>\n");
1851 &write_data("<body><h1>Unauthorized</h1>\n");
1852 &write_data("A password is required to access this\n");
1853 &write_data("web server. Please try again. <p>\n");
1854 &write_data("</body></html>\n");
1855 &log_request($acpthost, undef, $reqline, 401, &byte_count());
1859 elsif ($blocked == 1) {
1860 # when the host has been blocked, give it an error
1861 &http_error(403, "Access denied for $acptip. The host ".
1862 "has been blocked because of too ".
1863 "many authentication failures.");
1865 elsif ($blocked == 2) {
1866 # when the user has been blocked, give it an error
1867 &http_error(403, "Access denied. The user ".
1868 "has been blocked because of too ".
1869 "many authentication failures.");
1873 # Get the real Webmin username
1874 local @can = &can_user_login($authuser, undef, $host);
1875 $baseauthuser = $can[3] || $authuser;
1877 if ($config{'remoteuser'} && !$< && $validated) {
1878 # Switch to the UID of the remote user (if he exists)
1879 local @u = getpwnam($authuser);
1880 if (@u && $< != $u[2]) {
1881 $( = $u[3]; $) = "$u[3] $u[3]";
1882 ($>, $<) = ($u[2], $u[2]);
1885 &http_error(500, "Unix user $authuser does not exist");
1891 # Check per-user IP access control
1892 if (!&check_user_ip($baseauthuser)) {
1893 &http_error(403, "Access denied for $acptip for $baseauthuser");
1897 # Check per-user allowed times
1898 if (!&check_user_time($baseauthuser)) {
1899 &http_error(403, "Access denied at the current time");
1903 $uinfo = &get_user_details($baseauthuser);
1905 # Validate the path, and convert to canonical form
1907 $simple = &simplify_path($page, $bogus);
1908 print DEBUG "handle_request: page=$page simple=$simple\n";
1910 &http_error(400, "Invalid path");
1913 # Check for a DAV request
1915 return &handle_dav_request($davpath);
1918 # Work out the active theme(s)
1919 local $preroots = $mobile_device && defined($config{'mobile_preroot'}) ?
1920 $config{'mobile_preroot'} :
1921 $authuser && defined($config{'preroot_'.$authuser}) ?
1922 $config{'preroot_'.$authuser} :
1923 $uinfo && defined($uinfo->{'preroot'}) ?
1924 $uinfo->{'preroot'} :
1926 local @preroots = reverse(split(/\s+/, $preroots));
1928 # Canonicalize the directories
1929 foreach my $preroot (@preroots) {
1930 # Always under the current webmin root
1931 $preroot =~ s/^.*\///g;
1932 $preroot = $roots[0].'/'.$preroot;
1935 # Look in the theme root directories first
1936 local ($full, @stfull);
1938 foreach my $preroot (@preroots) {
1941 $full = $preroot.$sofar;
1942 $scriptname = $simple;
1943 foreach $b (split(/\//, $simple)) {
1944 if ($b ne "") { $sofar .= "/$b"; }
1945 $full = $preroot.$sofar;
1946 @stfull = stat($full);
1947 if (!@stfull) { undef($full); last; }
1949 # Check if this is a directory
1951 # It is.. go on parsing
1959 # Check if this is a CGI program
1960 if (&get_type($full) eq "internal/cgi") {
1961 $pathinfo = substr($simple, length($sofar));
1962 $pathinfo .= "/" if ($page =~ /\/$/);
1963 $scriptname = $sofar;
1968 # Don't stop at a directory unless this is the last theme, which
1969 # is the 'real' one that provides the .cgi scripts
1970 if ($is_directory && $preroot ne $preroots[$#preroots]) {
1977 $cgi_pwd = $roots[0];
1979 elsif ($is_directory) {
1980 $cgi_pwd = "$roots[0]$sofar";
1983 "$roots[0]$sofar" =~ /^(.*\/)[^\/]+$/;
1986 $foundroot = $preroot;
1987 if ($is_directory) {
1988 # Check for index files in the directory
1990 foreach $idx (split(/\s+/, $config{"index_docs"})) {
1991 $idxfull = "$full/$idx";
1992 local @stidxfull = stat($idxfull);
1993 if (-r _ && !-d _) {
1995 @stfull = @stidxfull;
1998 if ($scriptname ne "/");
2003 @stfull = stat($full) if (!$foundidx);
2006 last if ($foundroot);
2008 print DEBUG "handle_request: initial full=$full\n";
2010 # Look in the real root directories, stopping when we find a file or directory
2011 if (!$full || $is_directory) {
2012 ROOT: foreach $root (@roots) {
2014 $full = $root.$sofar;
2015 $scriptname = $simple;
2016 foreach $b ($simple eq "/" ? ( "" ) : split(/\//, $simple)) {
2017 if ($b ne "") { $sofar .= "/$b"; }
2018 $full = $root.$sofar;
2019 @stfull = stat($full);
2024 # Check if this is a directory
2026 # It is.. go on parsing
2030 # Check if this is a CGI program
2031 if (&get_type($full) eq "internal/cgi") {
2032 $pathinfo = substr($simple, length($sofar));
2033 $pathinfo .= "/" if ($page =~ /\/$/);
2034 $scriptname = $sofar;
2039 # Run CGI in the same directory as whatever file
2041 $full =~ /^(.*\/)[^\/]+$/; $cgi_pwd = $1;
2050 if (!@stfull) { &http_error(404, "File not found"); }
2052 print DEBUG "handle_request: full=$full\n";
2053 @stfull = stat($full) if (!@stfull);
2055 # check filename against denyfile regexp
2056 local $denyfile = $config{'denyfile'};
2057 if ($denyfile && $full =~ /$denyfile/) {
2058 &http_error(403, "Access denied to $page");
2062 # Reached the end of the path OK.. see what we've got
2064 # See if the URL ends with a / as it should
2065 print DEBUG "handle_request: found a directory\n";
2066 if ($page !~ /\/$/) {
2067 # It doesn't.. redirect
2068 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2069 $ssl = $use_ssl || $config{'inetd_ssl'};
2070 $portstr = $port == 80 && !$ssl ? "" :
2071 $port == 443 && $ssl ? "" : ":$port";
2072 &write_data("Date: $datestr\r\n");
2073 &write_data("Server: $config{server}\r\n");
2074 $prot = $ssl ? "https" : "http";
2075 &write_data("Location: $prot://$host$portstr$page/\r\n");
2076 &write_keep_alive(0);
2077 &write_data("\r\n");
2078 &log_request($acpthost, $authuser, $reqline, 302, 0);
2081 # A directory.. check for index files
2083 foreach $idx (split(/\s+/, $config{"index_docs"})) {
2084 $idxfull = "$full/$idx";
2085 @stidxfull = stat($idxfull);
2086 if (-r _ && !-d _) {
2089 @stfull = @stidxfull;
2090 $scriptname .= "/" if ($scriptname ne "/");
2095 @stfull = stat($full) if (!$foundidx);
2098 # This is definately a directory.. list it
2099 print DEBUG "handle_request: listing directory\n";
2100 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2101 "Date: $datestr\r\n".
2102 "Server: $config{server}\r\n".
2103 "Content-type: text/html\r\n";
2105 &write_keep_alive(0);
2106 &write_data("\r\n");
2107 &reset_byte_count();
2108 &write_data("<h1>Index of $simple</h1>\n");
2109 &write_data("<pre>\n");
2110 &write_data(sprintf "%-35.35s %-20.20s %-10.10s\n",
2111 "Name", "Last Modified", "Size");
2112 &write_data("<hr>\n");
2113 opendir(DIR, $full);
2114 while($df = readdir(DIR)) {
2115 if ($df =~ /^\./) { next; }
2116 $fulldf = $full eq "/" ? $full.$df : $full."/".$df;
2117 (@stbuf = stat($fulldf)) || next;
2118 if (-d _) { $df .= "/"; }
2119 @tm = localtime($stbuf[9]);
2120 $fdate = sprintf "%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d",
2121 $tm[3],$tm[4]+1,$tm[5]+1900,
2122 $tm[0],$tm[1],$tm[2];
2123 $len = length($df); $rest = " "x(35-$len);
2125 "<a href=\"%s\">%-${len}.${len}s</a>$rest %-20.20s %-10.10s\n",
2126 $df, $df, $fdate, $stbuf[7]);
2129 &log_request($acpthost, $authuser, $reqline, $ok_code, &byte_count());
2133 # CGI or normal file
2135 if (&get_type($full) eq "internal/cgi" && $validated != 4) {
2136 # A CGI program to execute
2137 print DEBUG "handle_request: executing CGI\n";
2138 $envtz = $ENV{"TZ"};
2139 $envuser = $ENV{"USER"};
2140 $envpath = $ENV{"PATH"};
2141 $envlang = $ENV{"LANG"};
2142 $envroot = $ENV{"SystemRoot"};
2143 $envperllib = $ENV{'PERLLIB'};
2144 foreach my $k (keys %ENV) {
2147 $ENV{"PATH"} = $envpath if ($envpath);
2148 $ENV{"TZ"} = $envtz if ($envtz);
2149 $ENV{"USER"} = $envuser if ($envuser);
2150 $ENV{"OLD_LANG"} = $envlang if ($envlang);
2151 $ENV{"SystemRoot"} = $envroot if ($envroot);
2152 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
2153 $ENV{"HOME"} = $user_homedir;
2154 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
2155 $ENV{"SERVER_NAME"} = $host;
2156 $ENV{"SERVER_ADMIN"} = $config{"email"};
2157 $ENV{"SERVER_ROOT"} = $roots[0];
2158 $ENV{"SERVER_REALROOT"} = $realroot;
2159 $ENV{"SERVER_PORT"} = $port;
2160 $ENV{"REMOTE_HOST"} = $acpthost;
2161 $ENV{"REMOTE_ADDR"} = $acptip;
2162 $ENV{"REMOTE_ADDR_PROTOCOL"} = $ipv6 ? 6 : 4;
2163 $ENV{"REMOTE_USER"} = $authuser;
2164 $ENV{"BASE_REMOTE_USER"} = $authuser ne $baseauthuser ?
2165 $baseauthuser : undef;
2166 $ENV{"REMOTE_PASS"} = $authpass if (defined($authpass) &&
2167 $config{'pass_password'});
2168 if ($uinfo && $uinfo->{'proto'}) {
2169 $ENV{"REMOTE_USER_PROTO"} = $uinfo->{'proto'};
2170 $ENV{"REMOTE_USER_ID"} = $uinfo->{'id'};
2172 print DEBUG "REMOTE_USER = ",$ENV{"REMOTE_USER"},"\n";
2173 print DEBUG "BASE_REMOTE_USER = ",$ENV{"BASE_REMOTE_USER"},"\n";
2174 print DEBUG "proto=$uinfo->{'proto'} id=$uinfo->{'id'}\n" if ($uinfo);
2175 $ENV{"SSL_USER"} = $peername if ($validated == 2);
2176 $ENV{"ANONYMOUS_USER"} = "1" if ($validated == 3 || $validated == 4);
2177 $ENV{"DOCUMENT_ROOT"} = $roots[0];
2178 $ENV{"DOCUMENT_REALROOT"} = $realroot;
2179 $ENV{"GATEWAY_INTERFACE"} = "CGI/1.1";
2180 $ENV{"SERVER_PROTOCOL"} = "HTTP/1.0";
2181 $ENV{"REQUEST_METHOD"} = $method;
2182 $ENV{"SCRIPT_NAME"} = $scriptname;
2183 $ENV{"SCRIPT_FILENAME"} = $full;
2184 $ENV{"REQUEST_URI"} = $request_uri;
2185 $ENV{"PATH_INFO"} = $pathinfo;
2187 $ENV{"PATH_TRANSLATED"} = "$roots[0]$pathinfo";
2188 $ENV{"PATH_REALTRANSLATED"} = "$realroot$pathinfo";
2190 $ENV{"QUERY_STRING"} = $querystring;
2191 $ENV{"MINISERV_CONFIG"} = $config_file;
2192 $ENV{"HTTPS"} = "ON" if ($use_ssl || $config{'inetd_ssl'});
2193 $ENV{"MINISERV_PID"} = $miniserv_main_pid;
2194 $ENV{"SESSION_ID"} = $session_id if ($session_id);
2195 $ENV{"LOCAL_USER"} = $localauth_user if ($localauth_user);
2196 $ENV{"MINISERV_INTERNAL"} = $miniserv_internal if ($miniserv_internal);
2197 if (defined($header{"content-length"})) {
2198 $ENV{"CONTENT_LENGTH"} = $header{"content-length"};
2200 if (defined($header{"content-type"})) {
2201 $ENV{"CONTENT_TYPE"} = $header{"content-type"};
2203 foreach $h (keys %header) {
2204 ($hname = $h) =~ tr/a-z/A-Z/;
2206 $ENV{"HTTP_$hname"} = $header{$h};
2208 $ENV{"PWD"} = $cgi_pwd;
2209 foreach $k (keys %config) {
2210 if ($k =~ /^env_(\S+)$/) {
2211 $ENV{$1} = $config{$k};
2214 delete($ENV{'HTTP_AUTHORIZATION'});
2215 $ENV{'HTTP_COOKIE'} =~ s/;?\s*$sidname=([a-f0-9]+)//;
2216 $ENV{'MOBILE_DEVICE'} = 1 if ($mobile_device);
2218 # Check if the CGI can be handled internally
2220 local $first = <CGI>;
2222 $first =~ s/[#!\r\n]//g;
2223 $nph_script = ($full =~ /\/nph-([^\/]+)$/);
2225 if (!$config{'forkcgis'} &&
2226 ($first eq $perl_path || $first eq $linked_perl_path) &&
2228 $config{'internalcgis'}) {
2229 # setup environment for eval
2231 @ARGV = split(/\s+/, $queryargs);
2234 # Already read the post input
2235 $postinput = $posted_data;
2237 $clen = $header{"content-length"};
2238 $SIG{'CHLD'} = 'DEFAULT';
2240 # Have SOCK closed if the perl exec's something
2242 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
2246 if ($config{'log'}) {
2247 open(MINISERVLOG, ">>$config{'logfile'}");
2248 if ($config{'logperms'}) {
2249 chmod(oct($config{'logperms'}),
2250 $config{'logfile'});
2253 chmod(0600, $config{'logfile'});
2256 $doing_cgi_eval = 1;
2257 $main_process_id = $$;
2259 if ($full =~ /^\Q$foundroot\E\/([^\/]+)\//) {
2260 # Eval in package from Webmin module name
2262 $pkg =~ s/[^A-Za-z0-9]/_/g;
2267 tie(*STDOUT, 'miniserv');
2268 tie(*STDIN, 'miniserv');
2269 do \$miniserv::full;
2272 $doing_cgi_eval = 0;
2275 &http_error(500, "Perl execution failed",
2276 $config{'noshowstderr'} ? undef : $@);
2278 elsif (!$doneheaders && !$nph_script) {
2279 &http_error(500, "Missing Headers");
2286 # fork the process that actually executes the CGI
2287 pipe(CGIINr, CGIINw);
2288 pipe(CGIOUTr, CGIOUTw);
2289 pipe(CGIERRr, CGIERRw);
2290 if (!($cgipid = fork())) {
2291 @execargs = ( $full, split(/\s+/, $queryargs) );
2294 open(STDIN, "<&CGIINr");
2295 open(STDOUT, ">&CGIOUTw");
2296 open(STDERR, ">&CGIERRw");
2297 close(CGIINw); close(CGIOUTr); close(CGIERRr);
2299 die "Failed to exec $full : $!\n";
2302 close(CGIINr); close(CGIOUTw); close(CGIERRw);
2305 # write CGI input to a temp file
2306 $infile = "$config{'tempbase'}.$$";
2307 open(CGIINw, ">$infile");
2308 # NOT binary mode, as CGIs don't read in it!
2313 # already read the posted data
2314 print CGIINw $posted_data;
2316 $clen = $header{"content-length"};
2317 if ($method eq "POST" && $clen_read < $clen) {
2318 $SIG{'PIPE'} = 'IGNORE';
2320 while($got < $clen) {
2321 $buf = &read_data($clen-$got);
2322 if (!length($buf)) {
2323 kill('TERM', $cgipid);
2324 unlink($infile) if ($infile);
2325 &http_error(500, "Failed to read ".
2328 $got += length($buf);
2329 local ($wrote) = (print CGIINw $buf);
2332 # If the CGI terminated early, we still need to read
2333 # from the browser and throw away
2334 while($got < $clen) {
2335 $buf = &read_data($clen-$got);
2336 if (!length($buf)) {
2337 kill('TERM', $cgipid);
2338 unlink($infile) if ($infile);
2339 &http_error(500, "Failed to read ".
2342 $got += length($buf);
2344 $SIG{'PIPE'} = 'DEFAULT';
2350 # Run the CGI program, and feed it input
2352 local $qqueryargs = join(" ", map { "\"$_\"" }
2353 split(/\s+/, $queryargs));
2354 if ($first =~ /(perl|perl.exe)$/i) {
2355 # On Windows, run with Perl
2356 open(CGIOUTr, "$perl_path \"$full\" $qqueryargs <$infile |");
2359 open(CGIOUTr, "\"$full\" $qqueryargs <$infile |");
2365 # read back cgi headers
2366 select(CGIOUTr); $|=1; select(STDOUT);
2370 $line =~ s/\r|\n//g;
2372 if ($got_blank || %cgiheader) { last; }
2376 if ($line !~ /^(\S+):\s+(.*)$/) {
2377 $errs = &read_errors(CGIERRr);
2378 close(CGIOUTr); close(CGIERRr);
2379 unlink($infile) if ($infile);
2380 &http_error(500, "Bad Header", $errs);
2382 $cgiheader{lc($1)} = $2;
2383 push(@cgiheader, [ $1, $2 ]);
2385 if ($cgiheader{"location"}) {
2386 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2387 &write_data("Date: $datestr\r\n");
2388 &write_data("Server: $config{'server'}\r\n");
2389 &write_keep_alive(0);
2390 # ignore the rest of the output. This is a hack,
2391 # but is necessary for IE in some cases :(
2392 close(CGIOUTr); close(CGIERRr);
2394 elsif ($cgiheader{"content-type"} eq "") {
2395 close(CGIOUTr); close(CGIERRr);
2396 unlink($infile) if ($infile);
2397 $errs = &read_errors(CGIERRr);
2398 &http_error(500, "Missing Content-Type Header",
2399 $config{'noshowstderr'} ? undef : $errs);
2402 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2403 &write_data("Date: $datestr\r\n");
2404 &write_data("Server: $config{'server'}\r\n");
2405 &write_keep_alive(0);
2407 foreach $h (@cgiheader) {
2408 &write_data("$h->[0]: $h->[1]\r\n");
2410 &write_data("\r\n");
2412 &reset_byte_count();
2413 while($line = <CGIOUTr>) {
2418 unlink($infile) if ($infile);
2424 print DEBUG "handle_request: outputting file\n";
2425 open(FILE, $full) || &http_error(404, "Failed to open file");
2427 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2428 "Date: $datestr\r\n".
2429 "Server: $config{server}\r\n".
2430 "Content-type: ".&get_type($full)."\r\n".
2431 "Content-length: $stfull[7]\r\n".
2432 "Last-Modified: ".&http_date($stfull[9])."\r\n".
2433 "Expires: ".&http_date(time()+$config{'expires'})."\r\n";
2435 $rv = &write_keep_alive();
2436 &write_data("\r\n");
2437 &reset_byte_count();
2438 while(read(FILE, $buf, 1024) > 0) {
2445 &log_request($acpthost, $authuser, $reqline,
2446 $logged_code ? $logged_code :
2447 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2451 # http_error(code, message, body, [dontexit])
2454 local $eh = $error_handler_recurse ? undef :
2455 $config{"error_handler_$_[0]"} ? $config{"error_handler_$_[0]"} :
2456 $config{'error_handler'} ? $config{'error_handler'} : undef;
2457 print DEBUG "http_error code=$_[0] message=$_[1] body=$_[2]\n";
2459 # Call a CGI program for the error
2461 $querystring = "code=$_[0]&message=".&urlize($_[1]).
2462 "&body=".&urlize($_[2]);
2463 $error_handler_recurse++;
2465 $ok_message = $_[1];
2469 # Use the standard error message display
2470 &write_data("HTTP/1.0 $_[0] $_[1]\r\n");
2471 &write_data("Server: $config{server}\r\n");
2472 &write_data("Date: $datestr\r\n");
2473 &write_data("Content-type: text/html\r\n");
2474 &write_keep_alive(0);
2475 &write_data("\r\n");
2476 &reset_byte_count();
2477 &write_data("<h1>Error - $_[1]</h1>\n");
2479 &write_data("<pre>$_[2]</pre>\n");
2482 &log_request($acpthost, $authuser, $reqline, $_[0], &byte_count())
2484 &log_error($_[1], $_[2] ? " : $_[2]" : "");
2491 if ($_[0] =~ /\.([A-z0-9]+)$/) {
2497 return "text/plain";
2500 # simplify_path(path, bogus)
2501 # Given a path, maybe containing stuff like ".." and "." convert it to a
2502 # clean, absolute form.
2505 local($dir, @bits, @fixedbits, $b);
2507 $dir =~ s/\\/\//g; # fix windows \ in path
2510 $dir =~ s/\0//g; # remove null bytes
2511 @bits = split(/\/+/, $dir);
2514 foreach $b (@bits) {
2518 elsif ($b eq ".." || $b eq "...") {
2520 if (scalar(@fixedbits) == 0) {
2528 push(@fixedbits, $b);
2531 return "/" . join('/', @fixedbits);
2535 # Converts a string from base64 format to normal
2538 local($str) = $_[0];
2540 $str =~ tr|A-Za-z0-9+=/||cd;
2542 $str =~ tr|A-Za-z0-9+/| -_|;
2543 while ($str =~ /(.{1,60})/gs) {
2544 my $len = chr(32 + length($1)*3/4);
2545 $res .= unpack("u", $len . $1 );
2550 # ip_match(remoteip, localip, [match]+)
2551 # Checks an IP address against a list of IPs, networks and networks/masks
2554 local(@io, @mo, @ms, $i, $j, $hn, $needhn);
2555 @io = &check_ip6address($_[0]) ? split(/:/, $_[0])
2556 : split(/\./, $_[0]);
2557 for($i=2; $i<@_; $i++) {
2558 $needhn++ if ($_[$i] =~ /^\*(\S+)$/);
2560 if ($needhn && !defined($hn = $ip_match_cache{$_[0]})) {
2561 # Reverse-lookup hostname if any rules match based on it
2562 $hn = &to_hostname($_[0]);
2563 if (&check_ip6address($_[0])) {
2564 $hn = "" if (&to_ip6address($hn) ne $_[0]);
2567 $hn = "" if (&to_ipaddress($hn) ne $_[0]);
2569 $ip_match_cache{$_[0]} = $hn;
2571 for($i=2; $i<@_; $i++) {
2572 local $mismatch = 0;
2573 if ($_[$i] =~ /^(\S+)\/(\d+)$/) {
2574 # Convert CIDR to netmask format
2575 $_[$i] = $1."/".&prefix_to_mask($2);
2577 if ($_[$i] =~ /^(\S+)\/(\S+)$/) {
2578 # Compare with network/mask
2580 @mo = split(/\./, $1); @ms = split(/\./, $2);
2581 for($j=0; $j<4; $j++) {
2582 if ((int($io[$j]) & int($ms[$j])) != int($mo[$j])) {
2587 elsif ($_[$i] =~ /^\*(\S+)$/) {
2588 # Compare with hostname regexp
2589 $mismatch = 1 if ($hn !~ /$1$/);
2591 elsif ($_[$i] eq 'LOCAL') {
2592 # Compare with local network
2594 local @lo = split(/\./, $_[1]);
2596 $mismatch = 1 if ($lo[0] != $io[0]);
2598 elsif ($lo[0] < 192) {
2599 $mismatch = 1 if ($lo[0] != $io[0] ||
2603 $mismatch = 1 if ($lo[0] != $io[0] ||
2608 elsif ($_[$i] =~ /^[0-9\.]+$/) {
2609 # Compare with IPv4 address or network
2610 @mo = split(/\./, $_[$i]);
2611 while(@mo && !$mo[$#mo]) { pop(@mo); }
2612 for($j=0; $j<@mo; $j++) {
2613 if ($mo[$j] != $io[$j]) {
2618 elsif ($_[$i] =~ /^[a-f0-9:]+$/) {
2619 # Compare with IPv6 address or network
2620 @mo = split(/:/, $_[$i]);
2621 while(@mo && !$mo[$#mo]) { pop(@mo); }
2622 for($j=0; $j<@mo; $j++) {
2623 if ($mo[$j] != $io[$j]) {
2628 elsif ($_[$i] !~ /^[0-9\.]+$/) {
2629 # Compare with hostname
2630 $mismatch = 1 if ($_[0] ne &to_ipaddress($_[$i]));
2632 return 1 if (!$mismatch);
2637 # users_match(&uinfo, user, ...)
2638 # Returns 1 if a user is in a list of users and groups
2641 local $uinfo = shift(@_);
2643 local @ginfo = getgrgid($uinfo->[3]);
2645 if ($u =~ /^\@(\S+)$/) {
2646 return 1 if (&is_group_member($uinfo, $1));
2648 elsif ($u =~ /^(\d*)-(\d*)$/ && ($1 || $2)) {
2649 return (!$1 || $uinfo[2] >= $1) &&
2650 (!$2 || $uinfo[2] <= $2);
2653 return 1 if ($u eq $uinfo->[0]);
2659 # restart_miniserv()
2660 # Called when a SIGHUP is received to restart the web server. This is done
2661 # by exec()ing perl with the same command line as was originally used
2662 sub restart_miniserv
2664 print STDERR "restarting miniserv\n";
2665 &log_error("Restarting");
2667 &close_all_sockets();
2669 dbmclose(%sessiondb);
2670 kill('KILL', $logclearer) if ($logclearer);
2671 kill('KILL', $extauth) if ($extauth);
2672 exec($perl_path, $miniserv_path, @miniserv_argv);
2673 die "Failed to restart miniserv with $perl_path $miniserv_path";
2686 # to_ipaddress(address, ...)
2691 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2692 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/ || $i =~ /^[a-f0-9:]+$/) {
2693 # A pattern or IP, not a hostname, so don't change
2698 push(@rv, join('.', unpack("CCCC", inet_aton($i))));
2701 return wantarray ? @rv : $rv[0];
2704 # to_ip6address(address, ...)
2709 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2710 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/ || $i =~ /^[a-f0-9:]+$/) {
2711 # A pattern, not a hostname, so don't change
2715 # Lookup IPv6 address
2716 local ($inaddr, $addr);
2717 (undef, undef, undef, $inaddr) =
2718 getaddrinfo($i, undef, Socket6::AF_INET6(), SOCK_STREAM);
2723 (undef, $addr) = unpack_sockaddr_in6($inaddr);
2724 push(@rv, inet_ntop(Socket6::AF_INET6(), $addr));
2728 return wantarray ? @rv : $rv[0];
2731 # to_hostname(ipv4|ipv6-address)
2732 # Reverse-resolves an IPv4 or 6 address to a hostname
2736 if (&check_ip6address($_[0])) {
2737 return gethostbyaddr(inet_pton(Socket6::AF_INET6(), $addr),
2738 Socket6::AF_INET6());
2741 return gethostbyaddr(inet_aton($addr), AF_INET);
2745 # read_line(no-wait, no-limit)
2746 # Reads one line from SOCK or SSL
2749 local ($nowait, $nolimit) = @_;
2750 local($idx, $more, $rv);
2751 while(($idx = index($main::read_buffer, "\n")) < 0) {
2752 if (length($main::read_buffer) > 10000 && !$nolimit) {
2753 &http_error(414, "Request too long",
2754 "Received excessive line <pre>$main::read_buffer</pre>");
2757 # need to read more..
2758 &wait_for_data_error() if (!$nowait);
2760 $more = Net::SSLeay::read($ssl_con);
2763 local $ok = sysread(SOCK, $more, 1024);
2764 $more = undef if ($ok <= 0);
2768 $rv = $main::read_buffer;
2769 undef($main::read_buffer);
2772 $main::read_buffer .= $more;
2774 $rv = substr($main::read_buffer, 0, $idx+1);
2775 $main::read_buffer = substr($main::read_buffer, $idx+1);
2780 # Reads up to some amount of data from SOCK or the SSL connection
2784 if (length($main::read_buffer)) {
2785 if (length($main::read_buffer) > $_[0]) {
2786 # Return the first part of the buffer
2787 $rv = substr($main::read_buffer, 0, $_[0]);
2788 $main::read_buffer = substr($main::read_buffer, $_[0]);
2792 # Return the whole buffer
2793 $rv = $main::read_buffer;
2794 undef($main::read_buffer);
2799 # Call SSL read function
2800 return Net::SSLeay::read($ssl_con, $_[0]);
2803 # Just do a normal read
2805 sysread(SOCK, $buf, $_[0]) || return undef;
2811 # Read a line from a file handle, using sysread to get a byte at a time
2818 $got = sysread($fh, $buf, 1);
2819 last if ($got <= 0);
2821 last if ($buf eq "\n");
2826 # wait_for_data(secs)
2827 # Waits at most the given amount of time for some data on SOCK, returning
2828 # 0 if not found, 1 if some arrived.
2832 vec($rmask, fileno(SOCK), 1) = 1;
2833 local $got = select($rmask, undef, undef, $_[0]);
2834 return $got == 0 ? 0 : 1;
2837 # wait_for_data_error()
2838 # Waits 60 seconds for data on SOCK, and fails if none arrives
2839 sub wait_for_data_error
2841 local $got = &wait_for_data(60);
2843 &http_error(400, "Timeout",
2844 "Waited more than 60 seconds for request data");
2848 # write_data(data, ...)
2849 # Writes a string to SOCK or the SSL connection
2852 local $str = join("", @_);
2854 Net::SSLeay::write($ssl_con, $str);
2857 syswrite(SOCK, $str, length($str));
2859 # Intentionally introduce a small delay to avoid problems where IE reports
2860 # the page as empty / DNS failed when it get a large response too quickly!
2861 select(undef, undef, undef, .01) if ($write_data_count%10 == 0);
2862 $write_data_count += length($str);
2865 # reset_byte_count()
2866 sub reset_byte_count { $write_data_count = 0; }
2869 sub byte_count { return $write_data_count; }
2871 # log_request(hostname, user, request, code, bytes)
2874 if ($config{'log'}) {
2875 local ($user, $ident, $headers);
2876 if ($config{'logident'}) {
2877 # add support for rfc1413 identity checking here
2879 else { $ident = "-"; }
2880 $user = $_[1] ? $_[1] : "-";
2881 local $dstr = &make_datestr();
2882 if (fileno(MINISERVLOG)) {
2883 seek(MINISERVLOG, 0, 2);
2886 open(MINISERVLOG, ">>$config{'logfile'}");
2887 chmod(0600, $config{'logfile'});
2889 if (defined($config{'logheaders'})) {
2890 foreach $h (split(/\s+/, $config{'logheaders'})) {
2891 $headers .= " $h=\"$header{$h}\"";
2894 elsif ($config{'logclf'}) {
2895 $headers = " \"$header{'referer'}\" \"$header{'user-agent'}\"";
2900 print MINISERVLOG "$_[0] $ident $user [$dstr] \"$_[2]\" ",
2901 "$_[3] $_[4]$headers\n";
2909 local @tm = localtime(time());
2910 return sprintf "%2.2d/%s/%4.4d:%2.2d:%2.2d:%2.2d %s",
2911 $tm[3], $month[$tm[4]], $tm[5]+1900,
2912 $tm[2], $tm[1], $tm[0], $timezone;
2915 # log_error(message)
2919 print STDERR "[",&make_datestr(),"] ",
2920 $acpthost ? ( "[",$acpthost,"] " ) : ( ),
2921 $page ? ( $page," : " ) : ( ),
2925 # read_errors(handle)
2926 # Read and return all input from some filehandle
2929 local($fh, $_, $rv);
2931 while(<$fh>) { $rv .= $_; }
2935 sub write_keep_alive
2938 if ($config{'nokeepalive'}) {
2939 # Keep alives have been disabled in config
2942 elsif (@childpids > $config{'maxconns'}*.8) {
2943 # Disable because nearing process limit
2947 # Keep alive specified by caller
2951 # Keep alive determined by browser
2952 $mode = $header{'connection'} =~ /keep-alive/i;
2954 &write_data("Connection: ".($mode ? "Keep-Alive" : "close")."\r\n");
2960 kill('TERM', @childpids) if (@childpids);
2961 kill('KILL', $logclearer) if ($logclearer);
2962 kill('KILL', $extauth) if ($extauth);
2968 local @tm = gmtime($_[0]);
2969 return sprintf "%s, %d %s %d %2.2d:%2.2d:%2.2d GMT",
2970 $weekday[$tm[6]], $tm[3], $month[$tm[4]], $tm[5]+1900,
2971 $tm[2], $tm[1], $tm[0];
2976 my $i; bless \$i, shift;
2982 my($buf,$len,$offset) = @_;
2983 &write_to_sock(substr($buf, $offset, $len));
2990 my $buf = join(defined($,) ? $, : "", @_);
2991 $buf .= $\ if defined($\);
2992 &write_to_sock($buf);
2999 &write_to_sock(sprintf $fmt, @_);
3002 # Send back already read data while we have it, then read from SOCK
3006 my $bufref = \$_[0];
3009 if ($postpos < length($postinput)) {
3010 # Reading from already fetched array
3011 my $left = length($postinput) - $postpos;
3012 my $canread = $len > $left ? $left : $len;
3013 substr($$bufref, $offset, $canread) =
3014 substr($postinput, $postpos, $canread);
3015 $postpos += $canread;
3019 # Read from network socket
3020 local $data = &read_data($len);
3021 if ($data eq '' && $len) {
3023 print STDERR "finished reading - shutting down socket\n";
3026 substr($$bufref, $offset, length($data)) = $data;
3027 return length($data);
3033 #print STDERR "open() called - should never happen!\n";
3036 # Read a line of input
3040 if ($postpos < length($postinput) &&
3041 ($idx = index($postinput, "\n", $postpos)) >= 0) {
3042 # A line exists in the memory buffer .. use it
3043 my $line = substr($postinput, $postpos, $idx-$postpos+1);
3048 # Need to read from the socket
3050 if ($postpos < length($postinput)) {
3051 # Start with in-memory data
3052 $line = substr($postinput, $postpos);
3053 $postpos = length($postinput);
3055 my $nl = &read_line(0, 1);
3058 print STDERR "finished reading - shutting down socket\n";
3061 $line .= $nl if (defined($nl));
3066 # Read one character of input
3071 my $got = READ($r, \$buf, 1, 0);
3072 return $got > 0 ? $buf : undef;
3077 return fileno(SOCK);
3084 # write_to_sock(data, ...)
3089 if ($doneheaders || $miniserv::nph_script) {
3094 while(!$doneheaders && $headers =~ s/^([^\r\n]*)(\r)?\n//) {
3095 if ($1 =~ /^(\S+):\s+(.*)$/) {
3096 $cgiheader{lc($1)} = $2;
3097 push(@cgiheader, [ $1, $2 ]);
3099 elsif ($1 !~ /\S/) {
3103 &http_error(500, "Bad Header");
3107 if ($cgiheader{"location"}) {
3109 "HTTP/1.0 302 Moved Temporarily\r\n");
3110 &write_data("Date: $datestr\r\n");
3111 &write_data("Server: $config{server}\r\n");
3112 &write_keep_alive(0);
3114 elsif ($cgiheader{"content-type"} eq "") {
3115 &http_error(500, "Missing Content-Type Header");
3118 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
3119 &write_data("Date: $datestr\r\n");
3120 &write_data("Server: $config{server}\r\n");
3121 &write_keep_alive(0);
3123 foreach $h (@cgiheader) {
3124 &write_data("$h->[0]: $h->[1]\r\n");
3126 &write_data("\r\n");
3127 &reset_byte_count();
3128 &write_data($headers);
3136 local $cert = Net::SSLeay::X509_STORE_CTX_get_current_cert($_[1]);
3138 local $errnum = Net::SSLeay::X509_STORE_CTX_get_error($_[1]);
3139 $verified_client = 1 if (!$errnum);
3146 if ($doing_cgi_eval && $$ == $main_process_id) {
3147 # A CGI program called exit! This is a horrible hack to
3148 # finish up before really exiting
3151 close($PASSINw); close($PASSOUTw);
3152 &log_request($acpthost, $authuser, $reqline,
3153 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
3158 # Convert a string to a form ok for putting in a URL
3160 local($tmp, $tmp2, $c);
3163 while(($c = chop($tmp)) ne "") {
3164 if ($c !~ /[A-z0-9]/) {
3165 $c = sprintf("%%%2.2X", ord($c));
3172 # validate_user(username, password, host)
3173 # Checks if some username and password are valid. Returns the modified username,
3174 # the expired / temp pass flag, and the non-existence flag
3177 local ($user, $pass, $host) = @_;
3178 return ( ) if (!$user);
3179 print DEBUG "validate_user: user=$user pass=$pass host=$host\n";
3180 local ($canuser, $canmode, $notexist, $webminuser, $sudo) =
3181 &can_user_login($user, undef, $host);
3182 print DEBUG "validate_user: canuser=$canuser canmode=$canmode notexist=$notexist webminuser=$webminuser sudo=$sudo\n";
3184 # User doesn't even exist, so go no further
3185 return ( undef, 0, 1 );
3187 elsif ($canmode == 0) {
3188 # User does exist but cannot login
3189 return ( $canuser, 0, 0 );
3191 elsif ($canmode == 1) {
3192 # Attempt Webmin authentication
3193 my $uinfo = &get_user_details($webminuser);
3195 &password_crypt($pass, $uinfo->{'pass'}) eq $uinfo->{'pass'}) {
3196 # Password is valid .. but check for expiry
3197 local $lc = $uinfo->{'lastchanges'};
3198 print DEBUG "validate_user: Password is valid lc=$lc pass_maxdays=$config{'pass_maxdays'}\n";
3199 if ($config{'pass_maxdays'} && $lc && !$uinfo->{'nochange'}) {
3200 local $daysold = (time() - $lc)/(24*60*60);
3201 print DEBUG "maxdays=$config{'pass_maxdays'} daysold=$daysold temppass=$uinfo->{'temppass'}\n";
3202 if ($config{'pass_lockdays'} &&
3203 $daysold > $config{'pass_lockdays'}) {
3204 # So old that the account is locked
3205 return ( undef, 0, 0 );
3207 elsif ($daysold > $config{'pass_maxdays'}) {
3208 # Password has expired
3209 return ( $user, 1, 0 );
3212 if ($uinfo->{'temppass'}) {
3213 # Temporary password - force change now
3214 return ( $user, 2, 0 );
3216 return ( $user, 0, 0 );
3219 print DEBUG "validate_user: User $webminuser not found\n";
3220 return ( undef, 0, 0 );
3223 print DEBUG "validate_user: User $webminuser password mismatch $pass != $uinfo->{'pass'}\n";
3224 return ( undef, 0, 0 );
3227 elsif ($canmode == 2 || $canmode == 3) {
3228 # Attempt PAM or passwd file authentication
3229 local $val = &validate_unix_user($canuser, $pass);
3230 print DEBUG "validate_user: unix val=$val\n";
3231 if ($val && $sudo) {
3232 # Need to check if this Unix user can sudo
3233 if (!&check_sudo_permissions($canuser, $pass)) {
3234 print DEBUG "validate_user: sudo failed\n";
3238 print DEBUG "validate_user: sudo passed\n";
3241 return $val == 2 ? ( $canuser, 1, 0 ) :
3242 $val == 1 ? ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3244 elsif ($canmode == 4) {
3245 # Attempt external authentication
3246 return &validate_external_user($canuser, $pass) ?
3247 ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3255 # validate_unix_user(user, password)
3256 # Returns 1 if a username and password are valid under unix, 0 if not,
3257 # or 2 if the account has expired.
3258 # Checks PAM if available, and falls back to reading the system password
3260 sub validate_unix_user
3264 $pam_username = $_[0];
3265 $pam_password = $_[1];
3266 eval "use Authen::PAM;";
3267 local $pamh = new Authen::PAM($config{'pam'}, $pam_username,
3270 local $pam_ret = $pamh->pam_authenticate();
3271 if ($pam_ret == PAM_SUCCESS()) {
3272 # Logged in OK .. make sure password hasn't expired
3273 local $acct_ret = $pamh->pam_acct_mgmt();
3274 if ($acct_ret == PAM_SUCCESS()) {
3275 $pamh->pam_open_session();
3278 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3279 $acct_ret == PAM_ACCT_EXPIRED()) {
3283 print STDERR "Unknown pam_acct_mgmt return value : $acct_ret\n";
3290 elsif ($config{'pam_only'}) {
3291 # Pam is not available, but configuration forces it's use!
3294 elsif ($config{'passwd_file'}) {
3295 # Check in a password file
3297 open(FILE, $config{'passwd_file'});
3298 if ($config{'passwd_file'} eq '/etc/security/passwd') {
3299 # Assume in AIX format
3302 if (/^\s*(\S+):/ && $1 eq $_[0]) {
3304 if (/^\s*password\s*=\s*(\S+)\s*$/) {
3305 $rv = $1 eq &password_crypt($_[1], $1) ?
3313 # Read the system password or shadow file
3315 local @l = split(/:/, $_, -1);
3316 local $u = $l[$config{'passwd_uindex'}];
3317 local $p = $l[$config{'passwd_pindex'}];
3319 $rv = $p eq &password_crypt($_[1], $p) ? 1 : 0;
3320 if ($config{'passwd_cindex'} ne '' && $rv) {
3321 # Password may have expired!
3322 local $c = $l[$config{'passwd_cindex'}];
3323 local $m = $l[$config{'passwd_mindex'}];
3324 local $day = time()/(24*60*60);
3325 if ($c =~ /^\d+/ && $m =~ /^\d+/ &&
3331 if ($p eq "" && $config{'passwd_blank'}) {
3332 # Force password change
3340 return $rv if ($rv);
3343 # Fallback option - check password returned by getpw*
3344 local @uinfo = getpwnam($_[0]);
3345 if ($uinfo[1] ne '' && &password_crypt($_[1], $uinfo[1]) eq $uinfo[1]) {
3349 return 0; # Totally failed
3352 # validate_external_user(user, pass)
3353 # Validate a user by passing the username and password to an external
3354 # squid-style authentication program
3355 sub validate_external_user
3357 return 0 if (!$config{'extauth'});
3359 local $str = "$_[0] $_[1]\n";
3360 syswrite(EXTAUTH, $str, length($str));
3361 local $resp = <EXTAUTH>;
3363 return $resp =~ /^OK/i ? 1 : 0;
3366 # can_user_login(username, no-append, host)
3367 # Checks if a user can login or not.
3368 # First return value is the username.
3369 # Second is 0 if cannot login, 1 if using Webmin pass, 2 if PAM, 3 if password
3370 # file, 4 if external.
3371 # Third is 1 if the user does not exist at all, 0 if he does.
3372 # Fourth is the Webmin username whose permissions apply, based on unixauth.
3373 # Fifth is a flag indicating if a sudo check is needed.
3376 local $uinfo = &get_user_details($_[0]);
3378 # See if this user exists in Unix and can be validated by the same
3379 # method as the unixauth webmin user
3380 local $realuser = $unixauth{$_[0]};
3384 eval { @uinfo = getpwnam($_[0]); }; # may fail on windows
3385 if (!$realuser && @uinfo) {
3386 # No unixauth entry for the username .. try his groups
3387 foreach my $ua (keys %unixauth) {
3388 if ($ua =~ /^\@(.*)$/) {
3389 if (&is_group_member(\@uinfo, $1)) {
3390 $realuser = $unixauth{$ua};
3396 if (!$realuser && @uinfo) {
3397 # Fall back to unix auth for all Unix users
3398 $realuser = $unixauth{"*"};
3400 if (!$realuser && $use_sudo && @uinfo) {
3401 # Allow login effectively as root, if sudo permits it
3405 if (!$realuser && !@uinfo && $config{'pamany'}) {
3406 # If the user completely doesn't exist, we can still allow
3407 # him to authenticate via PAM
3408 $realuser = $config{'pamany'};
3412 # For Usermin, always fall back to unix auth for any user,
3413 # so that later checks with domain added / removed are done.
3414 $realuser = $unixauth{"*"};
3416 return (undef, 0, 1, undef) if (!$realuser);
3417 local $uinfo = &get_user_details($realuser);
3418 return (undef, 0, 1, undef) if (!$uinfo);
3419 local $up = $uinfo->{'pass'};
3421 # Work out possible domain names from the hostname
3422 local @doms = ( $_[2] );
3423 if ($_[2] =~ /^([^\.]+)\.(\S+)$/) {
3427 if ($config{'user_mapping'} && !%user_mapping) {
3428 # Read the user mapping file
3430 open(MAPPING, $config{'user_mapping'});
3434 if (/^(\S+)\s+(\S+)/) {
3435 if ($config{'user_mapping_reverse'}) {
3436 $user_mapping{$1} = $2;
3439 $user_mapping{$2} = $1;
3446 # Check the user mapping file to see if there is an entry for the
3447 # user login in which specifies a new effective user
3449 foreach my $d (@doms) {
3450 $um ||= $user_mapping{"$_[0]\@$d"};
3452 $um ||= $user_mapping{$_[0]};
3453 if (defined($um) && ($_[1]&4) == 0) {
3454 # A mapping exists - use it!
3455 return &can_user_login($um, $_[1]+4, $_[2]);
3458 # Check if a user with the entered login and the domains appended
3459 # or prepended exists, and if so take it to be the effective user
3460 if (!@uinfo && $config{'domainuser'}) {
3461 # Try again with name.domain and name.firstpart
3462 local @firsts = map { /^([^\.]+)/; $1 } @doms;
3463 if (($_[1]&1) == 0) {
3465 foreach $a (@firsts, @doms) {
3466 foreach $p ("$_[0].${a}", "$_[0]-${a}",
3467 "${a}.$_[0]", "${a}-$_[0]",
3468 "$_[0]_${a}", "${a}_$_[0]") {
3469 local @vu = &can_user_login(
3470 $p, $_[1]+1, $_[2]);
3471 return @vu if ($vu[1]);
3477 # Check if the user entered a domain at the end of his username when
3478 # he really shouldn't have, and if so try without it
3479 if (!@uinfo && $config{'domainstrip'} &&
3480 $_[0] =~ /^(\S+)\@(\S+)$/ && ($_[1]&2) == 0) {
3481 local ($stripped, $dom) = ($1, $2);
3482 local @vu = &can_user_login($stripped, $_[1] + 2, $_[2]);
3483 return @vu if ($vu[1]);
3484 local @vu = &can_user_login($stripped, $_[1] + 2, $dom);
3485 return @vu if ($vu[1]);
3488 return ( undef, 0, 1, undef ) if (!@uinfo && !$pamany);
3491 if (defined(@allowusers)) {
3492 # Only allow people on the allow list
3493 return ( undef, 0, 0, undef )
3494 if (!&users_match(\@uinfo, @allowusers));
3496 elsif (defined(@denyusers)) {
3497 # Disallow people on the deny list
3498 return ( undef, 0, 0, undef )
3499 if (&users_match(\@uinfo, @denyusers));
3501 if ($config{'shells_deny'}) {
3503 open(SHELLS, $config{'shells_deny'});
3507 $found++ if ($_ eq $uinfo[8]);
3510 return ( undef, 0, 0, undef ) if (!$found);
3515 # PAM or passwd file authentication
3516 print DEBUG "can_user_login: Validate with PAM\n";
3517 return ( $_[0], $use_pam ? 2 : 3, 0, $realuser, $sudo );
3519 elsif ($up eq 'e') {
3520 # External authentication
3521 print DEBUG "can_user_login: Validate externally\n";
3522 return ( $_[0], 4, 0, $realuser, $sudo );
3525 # Fixed Webmin password
3526 print DEBUG "can_user_login: Validate by Webmin\n";
3527 return ( $_[0], 1, 0, $realuser, $sudo );
3530 elsif ($uinfo->{'pass'} eq 'x') {
3531 # Webmin user authenticated via PAM or password file
3532 return ( $_[0], $use_pam ? 2 : 3, 0, $_[0] );
3534 elsif ($uinfo->{'pass'} eq 'e') {
3535 # Webmin user authenticated externally
3536 return ( $_[0], 4, 0, $_[0] );
3539 # Normal Webmin user
3540 return ( $_[0], 1, 0, $_[0] );
3544 # the PAM conversation function for interactive logins
3547 $pam_conv_func_called++;
3554 $ans = $pam_username if ($code == PAM_PROMPT_ECHO_ON() );
3555 $ans = $pam_password if ($code == PAM_PROMPT_ECHO_OFF() );
3557 push @res, PAM_SUCCESS();
3560 push @res, PAM_SUCCESS();
3569 # get_socket_ip(handle, ipv6-flag)
3570 # Returns the local IP address of some connection, as both a string and in
3574 local ($fh, $ipv6) = @_;
3575 local $sn = getsockname($fh);
3576 return undef if (!$sn);
3577 return &get_address_ip($sn, $ipv6);
3580 # get_address_ip(address, ipv6-flag)
3581 # Given a sockaddr object in binary format, return the binary address, text
3582 # address and port number
3585 local ($sn, $ipv6) = @_;
3587 local ($p, $b) = unpack_sockaddr_in6($sn);
3588 return ($b, inet_ntop(Socket6::AF_INET6(), $b), $p);
3591 local ($p, $b) = unpack_sockaddr_in($sn);
3592 return ($b, inet_ntoa($b), $p);
3596 # get_socket_name(handle, ipv6-flag)
3597 # Returns the local hostname or IP address of some connection
3600 local ($fh, $ipv6) = @_;
3601 return $config{'host'} if ($config{'host'});
3602 local ($mybin, $myaddr) = &get_socket_ip($fh, $ipv6);
3603 if (!$get_socket_name_cache{$myaddr}) {
3605 if (!$config{'no_resolv_myname'}) {
3606 $myname = gethostbyaddr($mybin,
3607 $ipv6 ? Socket6::AF_INET6() : AF_INET);
3609 $myname ||= $myaddr;
3610 $get_socket_name_cache{$myaddr} = $myname;
3612 return $get_socket_name_cache{$myaddr};
3615 # run_login_script(username, sid, remoteip, localip)
3616 sub run_login_script
3618 if ($config{'login_script'}) {
3619 system($config{'login_script'}.
3620 " ".join(" ", map { quotemeta($_) || '""' } @_).
3621 " >/dev/null 2>&1 </dev/null");
3625 # run_logout_script(username, sid, remoteip, localip)
3626 sub run_logout_script
3628 if ($config{'logout_script'}) {
3629 system($config{'logout_script'}.
3630 " ".join(" ", map { quotemeta($_) || '""' } @_).
3631 " >/dev/null 2>&1 </dev/null");
3635 # close_all_sockets()
3636 # Closes all the main listening sockets
3637 sub close_all_sockets
3640 foreach $s (@socketfhs) {
3646 # Close all pipes for talking to sub-processes
3650 foreach $p (@passin) { close($p); }
3651 foreach $p (@passout) { close($p); }
3652 foreach $p (values %conversations) {
3653 if ($p->{'PAMOUTr'}) {
3654 close($p->{'PAMOUTr'});
3655 close($p->{'PAMINw'});
3660 # check_user_ip(user)
3661 # Returns 1 if some user is allowed to login from the accepting IP, 0 if not
3664 local ($username) = @_;
3665 local $uinfo = &get_user_details($username);
3666 return 1 if (!$uinfo);
3667 if ($uinfo->{'deny'} &&
3668 &ip_match($acptip, $localip, @{$uinfo->{'deny'}}) ||
3669 $uinfo->{'allow'} &&
3670 !&ip_match($acptip, $localip, @{$uinfo->{'allow'}})) {
3676 # check_user_time(user)
3677 # Returns 1 if some user is allowed to login at the current date and time
3680 local ($username) = @_;
3681 local $uinfo = &get_user_details($username);
3682 return 1 if (!$uinfo || !$uinfo->{'allowdays'} && !$uinfo->{'allowhours'});
3683 local @tm = localtime(time());
3684 if ($uinfo->{'allowdays'}) {
3685 # Make sure day is allowed
3686 return 0 if (&indexof($tm[6], @{$uinfo->{'allowdays'}}) < 0);
3688 if ($uinfo->{'allowhours'}) {
3689 # Make sure time is allowed
3690 local $m = $tm[2]*60+$tm[1];
3691 return 0 if ($m < $uinfo->{'allowhours'}->[0] ||
3692 $m > $uinfo->{'allowhours'}->[1]);
3697 # generate_random_id(password, [force-urandom])
3698 # Returns a random session ID number
3699 sub generate_random_id
3701 local ($pass, $force_urandom) = @_;
3703 if (!$bad_urandom) {
3704 # First try /dev/urandom, unless we have marked it as bad
3705 $SIG{ALRM} = "miniserv::urandom_timeout";
3707 if (open(RANDOM, "/dev/urandom")) {
3709 if (read(RANDOM, $tmpsid, 16) == 16) {
3710 $sid = lc(unpack('h*',$tmpsid));
3716 if (!$sid && !$force_urandom) {
3719 foreach $c (split(//, &unix_crypt($pass, substr($$, -2)))) {
3720 $sid += ord($c) * $mul;
3727 # handle_login(username, ok, expired, not-exists, password, [no-test-cookie])
3728 # Called from handle_session to either mark a user as logged in, or not
3731 local ($vu, $ok, $expired, $nonexist, $pass, $notest) = @_;
3732 $authuser = $vu if ($ok);
3734 # check if the test cookie is set
3735 if ($header{'cookie'} !~ /testing=1/ && $vu &&
3736 !$config{'no_testing_cookie'} && !$notest) {
3737 &http_error(500, "No cookies",
3738 "Your browser does not support cookies, ".
3739 "which are required for this web server to ".
3740 "work in session authentication mode");
3743 # check with main process for delay
3744 if ($config{'passdelay'} && $vu) {
3745 print DEBUG "handle_login: requesting delay vu=$vu acptip=$acptip ok=$ok\n";
3746 print $PASSINw "delay $vu $acptip $ok\n";
3747 <$PASSOUTr> =~ /(\d+) (\d+)/;
3750 print DEBUG "handle_login: delay=$1 blocked=$2\n";
3753 if ($ok && (!$expired ||
3754 $config{'passwd_mode'} == 1)) {
3755 # Logged in OK! Tell the main process about
3757 local $sid = &generate_random_id($pass);
3758 print DEBUG "handle_login: sid=$sid\n";
3759 print $PASSINw "new $sid $authuser $acptip\n";
3761 # Run the post-login script, if any
3762 &run_login_script($authuser, $sid,
3765 # Check for a redirect URL for the user
3766 local $rurl = &login_redirect($authuser, $pass, $host);
3767 print DEBUG "handle_login: redirect URL rurl=$rurl\n";
3769 # Got one .. go to it
3770 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3771 &write_data("Date: $datestr\r\n");
3772 &write_data("Server: $config{'server'}\r\n");
3773 &write_data("Location: $rurl\r\n");
3774 &write_keep_alive(0);
3775 &write_data("\r\n");
3776 &log_request($acpthost, $authuser, $reqline, 302, 0);
3779 # Set cookie and redirect to originally requested page
3780 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3781 &write_data("Date: $datestr\r\n");
3782 &write_data("Server: $config{'server'}\r\n");
3783 local $ssl = $use_ssl || $config{'inetd_ssl'};
3784 $portstr = $port == 80 && !$ssl ? "" :
3785 $port == 443 && $ssl ? "" : ":$port";
3786 $prot = $ssl ? "https" : "http";
3787 local $sec = $ssl ? "; secure" : "";
3788 #$sec .= "; httpOnly";
3789 if ($in{'page'} !~ /^\/[A-Za-z0-9\/\.\-\_]+$/) {
3790 # Make redirect URL safe
3794 &write_data("Set-Cookie: $sidname=$sid; path=/; expires=\"Thu, 31-Dec-2037 00:00:00\"$sec\r\n");
3797 &write_data("Set-Cookie: $sidname=$sid; path=/$sec\r\n");
3799 &write_data("Location: $prot://$host$portstr$in{'page'}\r\n");
3800 &write_keep_alive(0);
3801 &write_data("\r\n");
3802 &log_request($acpthost, $authuser, $reqline, 302, 0);
3803 syslog("info", "%s", "Successful login as $authuser from $acpthost") if ($use_syslog);
3804 &write_login_utmp($authuser, $acpthost);
3808 elsif ($ok && $expired &&
3809 ($config{'passwd_mode'} == 2 || $expired == 2)) {
3810 # Login was ok, but password has expired or was temporary. Need
3811 # to force display of password change form.
3814 $querystring = "&user=".&urlize($vu).
3816 "&expired=".$expired;
3819 $page = $config{'password_form'};
3821 $miniserv_internal = 2;
3822 syslog("crit", "%s",
3823 "Expired login as $vu ".
3824 "from $acpthost") if ($use_syslog);
3827 # Login failed, or password has expired. The login form will be
3828 # displayed again by later code
3830 $request_uri = $in{'page'};
3831 $already_session_id = undef;
3833 $authuser = $baseauthuser = undef;
3834 syslog("crit", "%s",
3835 ($nonexist ? "Non-existent" :
3836 $expired ? "Expired" : "Invalid").
3837 " login as $vu from $acpthost")
3843 # write_login_utmp(user, host)
3844 # Record the login by some user in utmp
3845 sub write_login_utmp
3848 # Write utmp record for login
3849 %utmp = ( 'ut_host' => $_[1],
3850 'ut_time' => time(),
3852 'ut_type' => 7, # user process
3853 'ut_pid' => $main_process_id,
3854 'ut_line' => $config{'pam'},
3856 if (defined(&User::Utmp::putut)) {
3857 User::Utmp::putut(\%utmp);
3860 User::Utmp::pututline(\%utmp);
3865 # write_logout_utmp(user, host)
3866 # Record the logout by some user in utmp
3867 sub write_logout_utmp
3870 # Write utmp record for logout
3871 %utmp = ( 'ut_host' => $_[1],
3872 'ut_time' => time(),
3874 'ut_type' => 8, # dead process
3875 'ut_pid' => $main_process_id,
3876 'ut_line' => $config{'pam'},
3878 if (defined(&User::Utmp::putut)) {
3879 User::Utmp::putut(\%utmp);
3882 User::Utmp::pututline(\%utmp);
3887 # pam_conversation_process(username, write-pipe, read-pipe)
3888 # This function is called inside a sub-process to communicate with PAM. It sends
3889 # questions down one pipe, and reads responses from another
3890 sub pam_conversation_process
3892 local ($user, $writer, $reader) = @_;
3893 $miniserv::pam_conversation_process_writer = $writer;
3894 $miniserv::pam_conversation_process_reader = $reader;
3895 eval "use Authen::PAM;";
3896 local $convh = new Authen::PAM(
3897 $config{'pam'}, $user, \&miniserv::pam_conversation_process_func);
3898 local $pam_ret = $convh->pam_authenticate();
3899 if ($pam_ret == PAM_SUCCESS()) {
3900 local $acct_ret = $convh->pam_acct_mgmt();
3901 if ($acct_ret == PAM_SUCCESS()) {
3902 $convh->pam_open_session();
3903 print $writer "x2 $user 1 0 0\n";
3905 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3906 $acct_ret == PAM_ACCT_EXPIRED()) {
3907 print $writer "x2 $user 1 1 0\n";
3910 print $writer "x0 Unknown PAM account status $acct_ret\n";
3914 print $writer "x2 $user 0 0 0\n";
3919 # pam_conversation_process_func(type, message, [type, message, ...])
3920 # A pipe that talks to both PAM and the master process
3921 sub pam_conversation_process_func
3924 select($miniserv::pam_conversation_process_writer); $| = 1; select(STDOUT);
3926 local ($type, $msg) = (shift, shift);
3928 local $ok = (print $miniserv::pam_conversation_process_writer "$type $msg\n");
3929 print $miniserv::pam_conversation_process_writer "\n";
3930 local $answer = <$miniserv::pam_conversation_process_reader>;
3931 $answer =~ s/\r|\n//g;
3932 push(@rv, PAM_SUCCESS(), $answer);
3934 push(@rv, PAM_SUCCESS());
3939 # Returns 4 new pipe file handles
3942 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3944 local %taken = ( (map { $_, 1 } @passin),
3945 (map { $_->{'PASSINr'} } values %conversations) );
3946 for($p=0; $taken{"PASSINr$p"}; $p++) { }
3947 $PASSINr = "PASSINr$p";
3948 $PASSINw = "PASSINw$p";
3949 $PASSOUTr = "PASSOUTr$p";
3950 $PASSOUTw = "PASSOUTw$p";
3951 pipe($PASSINr, $PASSINw);
3952 pipe($PASSOUTr, $PASSOUTw);
3953 select($PASSINw); $| = 1;
3954 select($PASSINr); $| = 1;
3955 select($PASSOUTw); $| = 1;
3956 select($PASSOUTw); $| = 1;
3958 return ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3961 # recv_pam_question(&conv, fd)
3962 # Reads one PAM question from the sub-process, and sends it to the HTTP handler.
3963 # Returns 0 if the conversation is over, 1 if not.
3964 sub recv_pam_question
3966 local ($conf, $fh) = @_;
3967 local $pr = $conf->{'PAMOUTr'};
3968 select($pr); $| = 1; select(STDOUT);
3969 local $line = <$pr>;
3970 $line =~ s/\r|\n//g;
3973 $line =~ s/\r|\n//g;
3975 $conf->{'last'} = time();
3978 print $fh "0 PAM conversation error\n";
3982 local ($type, $msg) = split(/\s+/, $line, 2);
3983 if ($type =~ /^x(\d+)/) {
3984 # Pass this status code through
3985 print $fh "$1 $msg\n";
3986 return $1 == 2 || $1 == 0 ? 0 : 1;
3988 elsif ($type == PAM_PROMPT_ECHO_ON()) {
3990 print $fh "1 $msg\n";
3993 elsif ($type == PAM_PROMPT_ECHO_OFF()) {
3995 print $fh "3 $msg\n";
3998 elsif ($type == PAM_ERROR_MSG() || $type == PAM_TEXT_INFO()) {
3999 # A message that does not require a response
4000 print $fh "4 $msg\n";
4005 print $fh "0 Unknown PAM message type $type\n";
4011 # send_pam_answer(&conv, answer)
4012 # Sends a response from the user to the PAM sub-process
4015 local ($conf, $answer) = @_;
4016 local $pw = $conf->{'PAMINw'};
4017 $conf->{'last'} = time();
4018 print $pw "$answer\n";
4021 # end_pam_conversation(&conv)
4022 # Clean up PAM conversation pipes and processes
4023 sub end_pam_conversation
4026 kill('KILL', $conv->{'pid'}) if ($conv->{'pid'});
4027 if ($conv->{'PAMINr'}) {
4028 close($conv->{'PAMINr'});
4029 close($conv->{'PAMOUTr'});
4030 close($conv->{'PAMINw'});
4031 close($conv->{'PAMOUTw'});
4033 delete($conversations{$conv->{'cid'}});
4036 # get_ipkeys(&miniserv)
4037 # Returns a list of IP address to key file mappings from a miniserv.conf entry
4041 foreach $k (keys %{$_[0]}) {
4042 if ($k =~ /^ipkey_(\S+)/) {
4043 local $ipkey = { 'ips' => [ split(/,/, $1) ],
4044 'key' => $_[0]->{$k},
4045 'index' => scalar(@rv) };
4046 $ipkey->{'cert'} = $_[0]->{'ipcert_'.$1};
4053 # create_ssl_context(keyfile, [certfile])
4054 sub create_ssl_context
4056 local ($keyfile, $certfile) = @_;
4058 eval { $ssl_ctx = Net::SSLeay::new_x_ctx() };
4059 $ssl_ctx ||= Net::SSLeay::CTX_new();
4060 $ssl_ctx || die "Failed to create SSL context : $!";
4061 if ($client_certs) {
4062 Net::SSLeay::CTX_load_verify_locations(
4063 $ssl_ctx, $config{'ca'}, "");
4064 Net::SSLeay::CTX_set_verify(
4065 $ssl_ctx, &Net::SSLeay::VERIFY_PEER, \&verify_client);
4067 if ($config{'extracas'}) {
4069 foreach $p (split(/\s+/, $config{'extracas'})) {
4070 Net::SSLeay::CTX_load_verify_locations(
4075 Net::SSLeay::CTX_use_RSAPrivateKey_file(
4077 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL key $keyfile";
4078 Net::SSLeay::CTX_use_certificate_file(
4079 $ssl_ctx, $certfile || $keyfile,
4080 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL cert $certfile";
4085 # ssl_connection_for_ip(socket)
4086 # Returns a new SSL connection object for some socket, or undef if failed
4087 sub ssl_connection_for_ip
4090 local $sn = getsockname($sock);
4092 print STDERR "Failed to get address for socket $sock\n";
4095 local $myip = inet_ntoa((unpack_sockaddr_in($sn))[1]);
4096 local $ssl_ctx = $ssl_contexts{$myip} || $ssl_contexts{"*"};
4097 local $ssl_con = Net::SSLeay::new($ssl_ctx);
4098 if ($config{'ssl_cipher_list'}) {
4099 # Force use of ciphers
4100 eval "Net::SSLeay::set_cipher_list(
4101 \$ssl_con, \$config{'ssl_cipher_list'})";
4103 print STDERR "SSL cipher $config{'ssl_cipher_list'} failed : ",
4109 Net::SSLeay::set_fd($ssl_con, fileno($sock));
4110 if (!Net::SSLeay::accept($ssl_con)) {
4111 print STDERR "Failed to initialize SSL connection\n";
4117 # login_redirect(username, password, host)
4118 # Calls the login redirect script (if configured), which may output a URL to
4119 # re-direct a user to after logging in.
4122 return undef if (!$config{'login_redirect'});
4123 local $quser = quotemeta($_[0]);
4124 local $qpass = quotemeta($_[1]);
4125 local $qhost = quotemeta($_[2]);
4126 local $url = `$config{'login_redirect'} $quser $qpass $qhost`;
4131 # reload_config_file()
4132 # Re-read %config, and call post-config actions
4133 sub reload_config_file
4135 &log_error("Reloading configuration");
4136 %config = &read_config_file($config_file);
4137 &update_vital_config();
4140 &build_config_mappings();
4141 &read_webmin_crons();
4142 if ($config{'session'}) {
4143 dbmclose(%sessiondb);
4144 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
4148 # read_config_file(file)
4149 # Reads the given config file, and returns a hash of values
4150 sub read_config_file
4153 open(CONF, $_[0]) || die "Failed to open config file $_[0] : $!";
4156 if (/^#/ || !/\S/) { next; }
4158 $name = $1; $val = $2;
4159 $name =~ s/^\s+//g; $name =~ s/\s+$//g;
4160 $val =~ s/^\s+//g; $val =~ s/\s+$//g;
4167 # update_vital_config()
4168 # Updates %config with defaults, and dies if something vital is missing
4169 sub update_vital_config
4171 my %vital = ("port", 80,
4173 "server", "MiniServ/0.01",
4174 "index_docs", "index.html index.htm index.cgi index.php",
4175 "addtype_html", "text/html",
4176 "addtype_txt", "text/plain",
4177 "addtype_gif", "image/gif",
4178 "addtype_jpg", "image/jpeg",
4179 "addtype_jpeg", "image/jpeg",
4180 "realm", "MiniServ",
4181 "session_login", "/session_login.cgi",
4182 "pam_login", "/pam_login.cgi",
4183 "password_form", "/password_form.cgi",
4184 "password_change", "/password_change.cgi",
4188 "unauth", "^/unauthenticated/ ^/robots.txt\$ ^[A-Za-z0-9\\-/_]+\\.jar\$ ^[A-Za-z0-9\\-/_]+\\.class\$ ^[A-Za-z0-9\\-/_]+\\.gif\$ ^[A-Za-z0-9\\-/_]+\\.conf\$ ^[A-Za-z0-9\\-/_]+\\.ico\$ ^/robots.txt\$",
4190 "expires", 7*24*60*60,
4191 "pam_test_user", "root",
4193 foreach my $v (keys %vital) {
4195 if ($vital{$v} eq "") {
4196 die "Missing config option $v";
4198 $config{$v} = $vital{$v};
4201 if (!$config{'sessiondb'}) {
4202 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4203 $config{'sessiondb'} = "$1/sessiondb";
4205 if (!$config{'errorlog'}) {
4206 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
4207 $config{'errorlog'} = "$1/miniserv.error";
4209 if (!$config{'tempbase'}) {
4210 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4211 $config{'tempbase'} = "$1/cgitemp";
4213 if (!$config{'blockedfile'}) {
4214 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4215 $config{'blockedfile'} = "$1/blocked";
4217 if (!$config{'webmincron_dir'}) {
4218 $config_file =~ /^(.*)\/[^\/]+$/;
4219 $config{'webmincron_dir'} = "$1/webmincron/crons";
4221 if (!$config{'webmincron_last'}) {
4222 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
4223 $config{'webmincron_last'} = "$1/miniserv.lastcrons";
4225 if (!$config{'webmincron_wrapper'}) {
4226 $config{'webmincron_wrapper'} = $config{'root'}.
4227 "/webmincron/webmincron.pl";
4232 # Fills the %users and %certs hashes from the users file in %config
4241 undef(%lastchanges);
4244 if ($config{'userfile'}) {
4245 open(USERS, $config{'userfile'});
4248 local @user = split(/:/, $_, -1);
4249 $users{$user[0]} = $user[1];
4250 $certs{$user[0]} = $user[3] if ($user[3]);
4251 if ($user[4] =~ /^allow\s+(.*)/) {
4252 $allow{$user[0]} = $config{'alwaysresolve'} ?
4253 [ split(/\s+/, $1) ] :
4254 [ &to_ipaddress(split(/\s+/, $1)) ];
4256 elsif ($user[4] =~ /^deny\s+(.*)/) {
4257 $deny{$user[0]} = $config{'alwaysresolve'} ?
4258 [ split(/\s+/, $1) ] :
4259 [ &to_ipaddress(split(/\s+/, $1)) ];
4261 if ($user[5] =~ /days\s+(\S+)/) {
4262 $allowdays{$user[0]} = [ split(/,/, $1) ];
4264 if ($user[5] =~ /hours\s+(\d+)\.(\d+)-(\d+).(\d+)/) {
4265 $allowhours{$user[0]} = [ $1*60+$2, $3*60+$4 ];
4267 $lastchanges{$user[0]} = $user[6];
4268 $nochange{$user[0]} = $user[9];
4269 $temppass{$user[0]} = $user[10];
4274 # Test user DB, if configured
4275 if ($config{'userdb'}) {
4276 my $dbh = &connect_userdb($config{'userdb'});
4278 print STDERR "Failed to open users database : $dbh\n"
4281 &disconnect_userdb($config{'userdb'}, $dbh);
4286 # get_user_details(username)
4287 # Returns a hash ref of user details, either from config files or the user DB
4288 sub get_user_details
4290 my ($username) = @_;
4291 if (exists($users{$username})) {
4293 return { 'name' => $username,
4294 'pass' => $users{$username},
4295 'certs' => $certs{$username},
4296 'allow' => $allow{$username},
4297 'deny' => $deny{$username},
4298 'allowdays' => $allowdays{$username},
4299 'allowhours' => $allowhours{$username},
4300 'lastchanges' => $lastchanges{$username},
4301 'nochange' => $nochange{$username},
4302 'temppass' => $temppass{$username},
4303 'preroot' => $config{'preroot_'.$username},
4306 if ($config{'userdb'}) {
4307 # Try querying user database
4308 if (exists($get_user_details_cache{$username})) {
4310 return $get_user_details_cache{$username};
4312 print DEBUG "get_user_details: Connecting to user database\n";
4313 my ($dbh, $proto, $prefix, $args) = &connect_userdb($config{'userdb'});
4317 print DEBUG "get_user_details: Failed : $dbh\n";
4318 print STDERR "Failed to connect to user database : $dbh\n";
4320 elsif ($proto eq "mysql" || $proto eq "postgresql") {
4321 # Fetch user ID and password with SQL
4322 print DEBUG "get_user_details: Looking for $username in SQL\n";
4323 my $cmd = $dbh->prepare(
4324 "select id,pass from webmin_user where name = ?");
4325 if (!$cmd || !$cmd->execute($username)) {
4326 print STDERR "Failed to lookup user : ",
4330 my ($id, $pass) = $cmd->fetchrow();
4333 &disconnect_userdb($config{'userdb'}, $dbh);
4334 $get_user_details_cache{$username} = undef;
4335 print DEBUG "get_user_details: User not found\n";
4338 print DEBUG "get_user_details: id=$id pass=$pass\n";
4340 # Fetch attributes and add to user object
4341 print DEBUG "get_user_details: finding user attributes\n";
4342 my $cmd = $dbh->prepare(
4343 "select attr,value from webmin_user_attr where id = ?");
4344 if (!$cmd || !$cmd->execute($id)) {
4345 print STDERR "Failed to lookup user attrs : ",
4349 $user = { 'name' => $username,
4352 'proto' => $proto };
4353 while(my ($attr, $value) = $cmd->fetchrow()) {
4354 $attrs{$attr} = $value;
4358 elsif ($proto eq "ldap") {
4359 # Fetch user DN with LDAP
4360 print DEBUG "get_user_details: Looking for $username in LDAP\n";
4361 my $rv = $dbh->search(
4363 filter => '(&(cn='.$username.')(objectClass='.
4364 $args->{'userclass'}.'))',
4366 if (!$rv || $rv->code) {
4367 print STDERR "Failed to lookup user : ",
4368 ($rv ? $rv->error : "Unknown error"),"\n";
4371 my ($u) = $rv->all_entries();
4373 &disconnect_userdb($config{'userdb'}, $dbh);
4374 $get_user_details_cache{$username} = undef;
4375 print DEBUG "get_user_details: User not found\n";
4379 # Extract attributes
4380 my $pass = $u->get_value('webminPass');
4381 $user = { 'name' => $username,
4384 'proto' => $proto };
4385 foreach my $la ($u->get_value('webminAttr')) {
4386 my ($attr, $value) = split(/=/, $la, 2);
4387 $attrs{$attr} = $value;
4391 # Convert DB attributes into user object fields
4393 print DEBUG "get_user_details: got ",scalar(keys %attrs),
4395 $user->{'certs'} = $attrs{'cert'};
4396 if ($attrs{'allow'}) {
4397 $user->{'allow'} = $config{'alwaysresolve'} ?
4398 [ split(/\s+/, $attrs{'allow'}) ] :
4399 [ &to_ipaddress(split(/\s+/,$attrs{'allow'})) ];
4401 if ($attrs{'deny'}) {
4402 $user->{'deny'} = $config{'alwaysresolve'} ?
4403 [ split(/\s+/, $attrs{'deny'}) ] :
4404 [ &to_ipaddress(split(/\s+/,$attrs{'deny'})) ];
4406 if ($attrs{'days'}) {
4407 $user->{'allowdays'} = [ split(/,/, $attrs{'days'}) ];
4409 if ($attrs{'hoursfrom'} && $attrs{'hoursto'}) {
4410 my ($hf, $mf) = split(/\./, $attrs{'hoursfrom'});
4411 my ($ht, $mt) = split(/\./, $attrs{'hoursto'});
4412 $user->{'allowhours'} = [ $hf*60+$ht, $ht*60+$mt ];
4414 $user->{'lastchanges'} = $attrs{'lastchange'};
4415 $user->{'nochange'} = $attrs{'nochange'};
4416 $user->{'temppass'} = $attrs{'temppass'};
4417 $user->{'preroot'} = $attrs{'theme'};
4419 &disconnect_userdb($config{'userdb'}, $dbh);
4420 $get_user_details_cache{$user->{'name'}} = $user;
4426 # find_user_by_cert(cert)
4427 # Returns a username looked up by certificate
4428 sub find_user_by_cert
4430 my ($peername) = @_;
4431 my $peername2 = $peername;
4432 $peername2 =~ s/Email=/emailAddress=/ || $peername2 =~ s/emailAddress=/Email=/;
4434 # First check users in local files
4435 foreach my $username (keys %certs) {
4436 if ($certs{$username} eq $peername ||
4437 $certs{$username} eq $peername2) {
4443 if ($config{'userdb'}) {
4444 my ($dbh, $proto) = &connect_userdb($config{'userdb'});
4448 elsif ($proto eq "mysql" || $proto eq "postgresql") {
4450 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 = ?");
4451 return undef if (!$cmd);
4452 foreach my $p ($peername, $peername2) {
4454 if ($cmd->execute($p)) {
4455 ($username) = $cmd->fetchrow();
4458 return $username if ($username);
4461 elsif ($proto eq "ldap") {
4463 my $rv = $dbh->search(
4465 filter => '(objectClass='.
4466 $args->{'userclass'}.')',
4468 attrs => [ 'cn', 'webminAttr' ]);
4469 if ($rv && !$rv->code) {
4470 foreach my $u ($rv->all_entries) {
4471 my @attrs = $u->get_value('webminAttr');
4472 foreach my $la (@attrs) {
4473 my ($attr, $value) = split(/=/, $la, 2);
4474 if ($attr eq "cert" &&
4475 ($value eq $peername ||
4476 $value eq $peername2)) {
4477 return $u->get_value('cn');
4487 # connect_userdb(string)
4488 # Returns a handle for talking to a user database - may be a DBI or LDAP handle.
4489 # On failure returns an error message string. In an array context, returns the
4490 # protocol type too.
4494 my ($proto, $user, $pass, $host, $prefix, $args) = &split_userdb_string($str);
4495 if ($proto eq "mysql") {
4496 # Connect to MySQL with DBI
4497 my $drh = eval "use DBI; DBI->install_driver('mysql');";
4498 $drh || return $text{'sql_emysqldriver'};
4499 my ($host, $port) = split(/:/, $host);
4500 my $cstr = "database=$prefix;host=$host";
4501 $cstr .= ";port=$port" if ($port);
4502 print DEBUG "connect_userdb: Connecting to MySQL $cstr as $user\n";
4503 my $dbh = $drh->connect($cstr, $user, $pass, { });
4504 $dbh || return &text('sql_emysqlconnect', $drh->errstr);
4505 print DEBUG "connect_userdb: Connected OK\n";
4506 return wantarray ? ($dbh, $proto, $prefix, $args) : $dbh;
4508 elsif ($proto eq "postgresql") {
4509 # Connect to PostgreSQL with DBI
4510 my $drh = eval "use DBI; DBI->install_driver('Pg');";
4511 $drh || return $text{'sql_epostgresqldriver'};
4512 my ($host, $port) = split(/:/, $host);
4513 my $cstr = "dbname=$prefix;host=$host";
4514 $cstr .= ";port=$port" if ($port);
4515 print DEBUG "connect_userdb: Connecting to PostgreSQL $cstr as $user\n";
4516 my $dbh = $drh->connect($cstr, $user, $pass);
4517 $dbh || return &text('sql_epostgresqlconnect', $drh->errstr);
4518 print DEBUG "connect_userdb: Connected OK\n";
4519 return wantarray ? ($dbh, $proto, $prefix, $args) : $dbh;
4521 elsif ($proto eq "ldap") {
4522 # Connect with perl LDAP module
4523 eval "use Net::LDAP";
4524 $@ && return $text{'sql_eldapdriver'};
4525 my ($host, $port) = split(/:/, $host);
4526 my $scheme = $args->{'scheme'} || 'ldap';
4528 $port = $scheme eq 'ldaps' ? 636 : 389;
4530 my $ldap = Net::LDAP->new($host,
4532 'scheme' => $scheme);
4533 $ldap || return &text('sql_eldapconnect', $host);
4535 if ($args->{'tls'}) {
4536 # Switch to TLS mode
4537 eval { $mesg = $ldap->start_tls(); };
4538 if ($@ || !$mesg || $mesg->code) {
4539 return &text('sql_eldaptls',
4540 $@ ? $@ : $mesg ? $mesg->error : "Unknown error");
4543 # Login to the server
4545 $mesg = $ldap->bind(dn => $user, password => $pass);
4548 $mesg = $ldap->bind(dn => $user, anonymous => 1);
4550 if (!$mesg || $mesg->code) {
4551 return &text('sql_eldaplogin', $user,
4552 $mesg ? $mesg->error : "Unknown error");
4554 return wantarray ? ($ldap, $proto, $prefix, $args) : $ldap;
4557 return "Unknown protocol $proto";
4561 # split_userdb_string(string)
4562 # Converts a string like mysql://user:pass@host/db into separate parts
4563 sub split_userdb_string
4566 if ($str =~ /^([a-z]+):\/\/([^:]*):([^\@]*)\@([a-z0-9\.\-\_]+)\/([^\?]+)(\?(.*))?$/) {
4567 my ($proto, $user, $pass, $host, $prefix, $argstr) =
4568 ($1, $2, $3, $4, $5, $7);
4569 my %args = map { split(/=/, $_, 2) } split(/\&/, $argstr);
4570 return ($proto, $user, $pass, $host, $prefix, \%args);
4575 # disconnect_userdb(string, &handle)
4576 # Closes a handle opened by connect_userdb
4577 sub disconnect_userdb
4580 if ($str =~ /^(mysql|postgresql):/) {
4584 elsif ($str =~ /^ldap:/) {
4591 # Fills %mime with entries from file in %config and extra settings in %config
4595 if ($config{"mimetypes"} ne "") {
4596 open(MIME, $config{"mimetypes"});
4599 if (/^(\S+)\s+(.*)$/) {
4601 my @exts = split(/\s+/, $2);
4602 foreach my $ext (@exts) {
4603 $mime{$ext} = $type;
4609 foreach my $k (keys %config) {
4610 if ($k !~ /^addtype_(.*)$/) { next; }
4611 $mime{$1} = $config{$k};
4615 # build_config_mappings()
4616 # Build the anonymous access list, IP access list, unauthenticated URLs list,
4617 # redirect mapping and allow and deny lists from %config
4618 sub build_config_mappings
4620 # build anonymous access list
4622 foreach my $a (split(/\s+/, $config{'anonymous'})) {
4623 if ($a =~ /^([^=]+)=(\S+)$/) {
4624 $anonymous{$1} = $2;
4628 # build IP access list
4630 foreach my $a (split(/\s+/, $config{'ipaccess'})) {
4631 if ($a =~ /^([^=]+)=(\S+)$/) {
4636 # build unauthenticated URLs list
4637 @unauth = split(/\s+/, $config{'unauth'});
4639 # build redirect mapping
4641 foreach my $r (split(/\s+/, $config{'redirect'})) {
4642 if ($r =~ /^([^=]+)=(\S+)$/) {
4647 # build prefixes to be stripped
4648 undef(@strip_prefix);
4649 foreach my $r (split(/\s+/, $config{'strip_prefix'})) {
4650 push(@strip_prefix, $r);
4653 # Init allow and deny lists
4654 @deny = split(/\s+/, $config{"deny"});
4655 @deny = &to_ipaddress(@deny) if (!$config{'alwaysresolve'});
4656 @allow = split(/\s+/, $config{"allow"});
4657 @allow = &to_ipaddress(@allow) if (!$config{'alwaysresolve'});
4660 if ($config{'allowusers'}) {
4661 @allowusers = split(/\s+/, $config{'allowusers'});
4663 elsif ($config{'denyusers'}) {
4664 @denyusers = split(/\s+/, $config{'denyusers'});
4667 # Build list of unixauth mappings
4669 foreach my $ua (split(/\s+/, $config{'unixauth'})) {
4670 if ($ua =~ /^(\S+)=(\S+)$/) {
4674 $unixauth{"*"} = $ua;
4678 # Build list of non-session-auth pages
4679 undef(%sessiononly);
4680 foreach my $sp (split(/\s+/, $config{'sessiononly'})) {
4681 $sessiononly{$sp} = 1;
4684 # Build list of logout times
4685 undef(@logouttimes);
4686 foreach my $a (split(/\s+/, $config{'logouttimes'})) {
4687 if ($a =~ /^([^=]+)=(\S+)$/) {
4688 push(@logouttimes, [ $1, $2 ]);
4691 push(@logouttimes, [ undef, $config{'logouttime'} ]);
4693 # Build list of DAV pathss
4695 foreach my $d (split(/\s+/, $config{'davpaths'})) {
4696 push(@davpaths, $d);
4698 @davusers = split(/\s+/, $config{'dav_users'});
4700 # Mobile agent substrings and hostname prefixes
4701 @mobile_agents = split(/\t+/, $config{'mobile_agents'});
4702 @mobile_prefixes = split(/\s+/, $config{'mobile_prefixes'});
4706 if ($config{'debug'}) {
4707 open(DEBUG, ">>$config{'debug'}");
4710 open(DEBUG, ">/dev/null");
4713 # Reset cache of sudo checks
4717 # is_group_member(&uinfo, groupname)
4718 # Returns 1 if some user is a primary or secondary member of a group
4721 local ($uinfo, $group) = @_;
4722 local @ginfo = getgrnam($group);
4723 return 0 if (!@ginfo);
4724 return 1 if ($ginfo[2] == $uinfo->[3]); # primary member
4725 foreach my $m (split(/\s+/, $ginfo[3])) {
4726 return 1 if ($m eq $uinfo->[0]);
4731 # prefix_to_mask(prefix)
4732 # Converts a number like 24 to a mask like 255.255.255.0
4735 return $_[0] >= 24 ? "255.255.255.".(256-(2 ** (32-$_[0]))) :
4736 $_[0] >= 16 ? "255.255.".(256-(2 ** (24-$_[0]))).".0" :
4737 $_[0] >= 8 ? "255.".(256-(2 ** (16-$_[0]))).".0.0" :
4738 (256-(2 ** (8-$_[0]))).".0.0.0";
4741 # get_logout_time(user, session-id)
4742 # Given a username, returns the idle time before he will be logged out
4745 local ($user, $sid) = @_;
4746 if (!defined($logout_time_cache{$user,$sid})) {
4748 foreach my $l (@logouttimes) {
4749 if ($l->[0] =~ /^\@(.*)$/) {
4750 # Check group membership
4751 local @uinfo = getpwnam($user);
4752 if (@uinfo && &is_group_member(\@uinfo, $1)) {
4756 elsif ($l->[0] =~ /^\//) {
4757 # Check file contents
4758 open(FILE, $l->[0]);
4775 if ($l->[0] eq $user) {
4779 last if (defined($time));
4781 $logout_time_cache{$user,$sid} = $time;
4783 return $logout_time_cache{$user,$sid};
4786 # password_crypt(password, salt)
4787 # If the salt looks like MD5 and we have a library for it, perform MD5 hashing
4788 # of a password. Otherwise, do Unix crypt.
4791 local ($pass, $salt) = @_;
4792 if ($salt =~ /^\$1\$/ && $use_md5) {
4793 return &encrypt_md5($pass, $salt);
4796 return &unix_crypt($pass, $salt);
4800 # unix_crypt(password, salt)
4801 # Performs standard Unix hashing for a password
4804 local ($pass, $salt) = @_;
4805 if ($use_perl_crypt) {
4806 return Crypt::UnixCrypt::crypt($pass, $salt);
4809 return crypt($pass, $salt);
4813 # handle_dav_request(davpath)
4814 # Pass a request on to the Net::DAV::Server module
4815 sub handle_dav_request
4818 eval "use Filesys::Virtual::Plain";
4819 eval "use Net::DAV::Server";
4820 eval "use HTTP::Request";
4821 eval "use HTTP::Headers";
4823 if ($Net::DAV::Server::VERSION eq '1.28' && $config{'dav_nolock'}) {
4824 delete $Net::DAV::Server::implemented{lock};
4825 delete $Net::DAV::Server::implemented{unlock};
4828 # Read in request data
4829 if (!$posted_data) {
4830 local $clen = $header{"content-length"};
4831 while(length($posted_data) < $clen) {
4832 $buf = &read_data($clen - length($posted_data));
4833 if (!length($buf)) {
4834 &http_error(500, "Failed to read POST request");
4836 $posted_data .= $buf;
4840 # For subsequent logging
4841 open(MINISERVLOG, ">>$config{'logfile'}");
4845 local @u = getpwnam($authuser);
4846 if ($config{'dav_remoteuser'} && !$< && $validated) {
4849 $( = $u[3]; $) = "$u[3] $u[3]";
4850 ($>, $<) = ($u[2], $u[2]);
4852 if ($config{'dav_root'} eq '*') {
4857 &http_error(500, "Unix user $authuser does not exist");
4861 $root ||= $config{'dav_root'};
4864 # Check if this user can use DAV
4866 &users_match(\@u, @davusers) ||
4867 &http_error(500, "You are not allowed to access DAV");
4871 my $filesys = Filesys::Virtual::Plain->new({root_path => $root});
4872 my $webdav = Net::DAV::Server->new();
4873 $webdav->filesys($filesys);
4875 # Make up a request object, and feed to DAV
4876 local $ho = HTTP::Headers->new;
4877 foreach my $h (keys %header) {
4878 next if (lc($h) eq "connection");
4879 $ho->header($h => $header{$h});
4882 $request_uri =~ s/^\Q$path\E//;
4883 $request_uri = "/" if ($request_uri eq "");
4885 my $request = HTTP::Request->new($method, $request_uri, $ho,
4887 if ($config{'dav_debug'}) {
4888 print STDERR "DAV request :\n";
4889 print STDERR "---------------------------------------------\n";
4890 print STDERR $request->as_string();
4891 print STDERR "---------------------------------------------\n";
4893 my $response = $webdav->run($request);
4895 # Send back the reply
4896 &write_data("HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n");
4897 local $content = $response->content();
4899 $content =~ s|href>/(.+)<|href>$path/$1<|g;
4900 $content =~ s|href>/<|href>$path<|g;
4902 foreach my $h ($response->header_field_names) {
4903 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4904 &write_data("$h: ",$response->header($h),"\r\n");
4906 &write_data("Content-length: ",length($content),"\r\n");
4907 local $rv = &write_keep_alive(0);
4908 &write_data("\r\n");
4909 &write_data($content);
4911 if ($config{'dav_debug'}) {
4912 print STDERR "DAV reply :\n";
4913 print STDERR "---------------------------------------------\n";
4914 print STDERR "HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n";
4915 foreach my $h ($response->header_field_names) {
4916 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4917 print STDERR "$h: ",$response->header($h),"\r\n";
4919 print STDERR "Content-length: ",length($content),"\r\n";
4920 print STDERR "\r\n";
4921 print STDERR $content;
4922 print STDERR "---------------------------------------------\n";
4926 &log_request($acpthost, $authuser, $reqline, $response->code(),
4927 length($response->content()));
4930 # get_system_hostname()
4931 # Returns the hostname of this system, for reporting to listeners
4932 sub get_system_hostname
4934 # On Windows, try computername environment variable
4935 return $ENV{'computername'} if ($ENV{'computername'});
4936 return $ENV{'COMPUTERNAME'} if ($ENV{'COMPUTERNAME'});
4938 # If a specific command is set, use it first
4939 if ($config{'hostname_command'}) {
4940 local $out = `($config{'hostname_command'}) 2>&1`;
4947 # First try the hostname command
4948 local $out = `hostname 2>&1`;
4949 if (!$? && $out =~ /\S/) {
4954 # Try the Sys::Hostname module
4955 eval "use Sys::Hostname";
4957 local $rv = eval "hostname()";
4963 # Must use net name on Windows
4964 local $out = `net name 2>&1`;
4965 if ($out =~ /\-+\r?\n(\S+)/) {
4972 # indexof(string, array)
4973 # Returns the index of some value in an array, or -1
4976 for($i=1; $i <= $#_; $i++) {
4977 if ($_[$i] eq $_[0]) { return $i - 1; }
4983 # has_command(command)
4984 # Returns the full path if some command is in the path, undef if not
4988 if (!$_[0]) { return undef; }
4989 if (exists($has_command_cache{$_[0]})) {
4990 return $has_command_cache{$_[0]};
4993 if ($_[0] =~ /^\//) {
4994 $rv = -x $_[0] ? $_[0] : undef;
4997 local $sp = $on_windows ? ';' : ':';
4998 foreach $d (split($sp, $ENV{PATH})) {
4999 if (-x "$d/$_[0]") {
5004 foreach my $sfx (".exe", ".com", ".bat") {
5005 if (-r "$d/$_[0]".$sfx) {
5006 $rv = "$d/$_[0]".$sfx;
5013 $has_command_cache{$_[0]} = $rv;
5017 # check_sudo_permissions(user, pass)
5018 # Returns 1 if some user can run any command via sudo
5019 sub check_sudo_permissions
5021 local ($user, $pass) = @_;
5023 # First try the pipes
5025 print DEBUG "check_sudo_permissions: querying cache for $user\n";
5026 print $PASSINw "readsudo $user\n";
5027 local $can = <$PASSOUTr>;
5029 print DEBUG "check_sudo_permissions: cache said $can\n";
5030 if ($can =~ /^\d+$/ && $can != 2) {
5035 local $ptyfh = new IO::Pty;
5036 print DEBUG "check_sudo_permissions: ptyfh=$ptyfh\n";
5038 print STDERR "Failed to create new PTY with IO::Pty\n";
5041 local @uinfo = getpwnam($user);
5043 print STDERR "Unix user $user does not exist for sudo\n";
5047 # Execute sudo in a sub-process, via a pty
5048 local $ttyfh = $ptyfh->slave();
5049 print DEBUG "check_sudo_permissions: ttyfh=$ttyfh\n";
5050 local $tty = $ptyfh->ttyname();
5051 print DEBUG "check_sudo_permissions: tty=$tty\n";
5052 chown($uinfo[2], $uinfo[3], $tty);
5054 print DEBUG "check_sudo_permissions: about to fork..\n";
5055 local $pid = fork();
5056 print DEBUG "check_sudo_permissions: fork=$pid pid=$$\n";
5058 print STDERR "fork for sudo failed : $!\n";
5063 $ptyfh->make_slave_controlling_terminal();
5064 close(STDIN); close(STDOUT); close(STDERR);
5065 untie(*STDIN); untie(*STDOUT); untie(*STDERR);
5066 close($PASSINw); close($PASSOUTr);
5067 $( = $uinfo[3]; $) = "$uinfo[3] $uinfo[3]";
5068 ($>, $<) = ($uinfo[2], $uinfo[2]);
5073 open(STDIN, "<&SUDOr");
5074 open(STDOUT, ">$tty");
5075 open(STDERR, ">&STDOUT");
5078 print "Exec failed : $!\n";
5081 print DEBUG "check_sudo_permissions: pid=$pid\n";
5083 $ptyfh->close_slave();
5085 # Send password, and get back response
5086 local $oldfh = select(SUDOw);
5089 print DEBUG "check_sudo_permissions: about to send pass\n";
5090 local $SIG{'PIPE'} = 'ignore'; # Sometimes sudo doesn't ask for a password
5091 print SUDOw $pass,"\n";
5092 print DEBUG "check_sudo_permissions: sent pass=$pass\n";
5096 print DEBUG "check_sudo_permissions: got $_";
5102 local ($ok) = ($out =~ /\(ALL\)\s+ALL/ ? 1 : 0);
5106 print $PASSINw "writesudo $user $ok\n";
5112 # is_mobile_useragent(agent)
5113 # Returns 1 if some user agent looks like a cellphone or other mobile device,
5115 sub is_mobile_useragent
5117 local ($agent) = @_;
5119 "UP.Link", # Openwave
5120 "Nokia", # All Nokias start with Nokia
5121 "MOT-", # All Motorola phones start with MOT-
5122 "SAMSUNG", # Samsung browsers
5123 "Samsung", # Samsung browsers
5124 "SEC-", # Samsung browsers
5125 "AU-MIC", # Samsung browsers
5126 "AUDIOVOX", # Audiovox
5127 "BlackBerry", # BlackBerry
5128 "hiptop", # Danger hiptop Sidekick
5129 "SonyEricsson", # Sony Ericsson
5130 "Ericsson", # Old Ericsson browsers , mostly WAP
5131 "Mitsu/1.1.A", # Mitsubishi phones
5132 "Panasonic WAP", # Panasonic old WAP phones
5133 "DoCoMo", # DoCoMo phones
5134 "Lynx", # Lynx text-mode linux browser
5135 "Links", # Another text-mode linux browser
5137 local @substrings = (
5138 "UP.Browser", # Openwave
5139 "MobilePhone", # NetFront
5140 "AU-MIC-A700", # Samsung A700 Obigo browsers
5141 "Danger hiptop", # Danger Sidekick hiptop
5142 "Windows CE", # Windows CE Pocket PC
5143 "IEMobile", # Windows mobile browser
5144 "Blazer", # Palm Treo Blazer
5145 "BlackBerry", # BlackBerries can emulate other browsers, but
5146 # they still keep this string in the UserAgent
5147 "SymbianOS", # New Series60 browser has safari in it and
5148 # SymbianOS is the only distinguishing string
5149 "iPhone", # Apple iPhone KHTML browser
5150 "iPod", # iPod touch browser
5151 "MobileSafari", # HTTP client in iPhone
5153 "Opera Mini", # Opera Mini
5154 "HTC_P3700", # HTC mobile device
5156 "webOS/", # Palm WebOS
5157 "Nintendo DS", # DSi / DSi-XL
5159 foreach my $p (@prefixes) {
5160 return 1 if ($agent =~ /^\Q$p\E/);
5162 foreach my $s (@substrings, @mobile_agents) {
5163 return 1 if ($agent =~ /\Q$s\E/);
5168 # write_blocked_file()
5169 # Writes out a text file of blocked hosts and users
5170 sub write_blocked_file
5172 open(BLOCKED, ">$config{'blockedfile'}");
5173 foreach my $d (grep { $hostfail{$_} } @deny) {
5174 print BLOCKED "host $d $hostfail{$d} $blockhosttime{$d}\n";
5176 foreach my $d (grep { $userfail{$_} } @denyusers) {
5177 print BLOCKED "user $d $userfail{$d} $blockusertime{$d}\n";
5180 chmod(0700, $config{'blockedfile'});
5185 open(PIDFILE, ">$config{'pidfile'}");
5186 printf PIDFILE "%d\n", getpid();
5188 $miniserv_main_pid = getpid();
5191 # lock_user_password(user)
5192 # Updates a user's password file entry to lock it, both in memory and on disk.
5193 # Returns 1 if done, -1 if no such user, 0 if already locked
5194 sub lock_user_password
5197 local $uinfo = &get_user_details($user);
5202 if ($uinfo->{'pass'} =~ /^\!/) {
5206 if (!$uinfo->{'proto'}) {
5207 # Write to users file
5208 $users{$user} = "!".$users{$user};
5209 open(USERS, $config{'userfile'});
5210 local @ufile = <USERS>;
5212 foreach my $u (@ufile) {
5213 local @uinfo = split(/:/, $u);
5214 if ($uinfo[0] eq $user) {
5215 $uinfo[1] = $users{$user};
5217 $u = join(":", @uinfo);
5219 open(USERS, ">$config{'userfile'}");
5225 if ($config{'userdb'}) {
5227 my ($dbh, $proto, $prefix, $args) = &connect_userdb($config{'userdb'});
5231 elsif ($proto eq "mysql" || $proto eq "postgresql") {
5232 # Update user attribute
5233 my $cmd = $dbh->prepare(
5234 "update webmin_user set pass = ? where id = ?");
5235 if (!$cmd || !$cmd->execute("!".$uinfo->{'pass'},
5238 print STDERR "Failed to lock password : ",
5242 $cmd->finish() if ($cmd);
5244 elsif ($proto eq "ldap") {
5245 # Update LDAP object
5246 my $rv = $dbh->modify($uinfo->{'id'},
5247 replace => { 'webminPass' => '!'.$uinfo->{'pass'} });
5248 if (!$rv || $rv->code) {
5249 print STDERR "Failed to lock password : ",
5250 ($rv ? $rv->error : "Unknown error"),"\n";
5254 &disconnect_userdb($config{'userdb'}, $dbh);
5258 return -1; # This should never be reached
5261 # hash_session_id(sid)
5262 # Returns an MD5 or Unix-crypted session ID
5266 if (!$hash_session_id_cache{$sid}) {
5269 $hash_session_id_cache{$sid} = &encrypt_md5($sid);
5273 $hash_session_id_cache{$sid} = &unix_crypt($sid, "XX");
5276 return $hash_session_id_cache{$sid};
5279 # encrypt_md5(string, [salt])
5280 # Returns a string encrypted in MD5 format
5283 local ($passwd, $salt) = @_;
5284 local $magic = '$1$';
5285 if ($salt =~ /^\$1\$([^\$]+)/) {
5286 # Extract actual salt from already encrypted password
5291 local $ctx = eval "new $use_md5";
5298 # Add some more stuff from the hash of the password and salt
5299 local $ctx1 = eval "new $use_md5";
5300 $ctx1->add($passwd);
5304 $ctx1->add($passwd);
5305 local $final = $ctx1->digest();
5306 for($pl=length($passwd); $pl>0; $pl-=16) {
5307 $ctx->add($pl > 16 ? $final : substr($final, 0, $pl));
5310 # This piece of code seems rather pointless, but it's in the C code that
5311 # does MD5 in PAM so it has to go in!
5314 for($i=length($passwd); $i; $i >>= 1) {
5319 $ctx->add(substr($passwd, $j, 1));
5322 $final = $ctx->digest();
5325 # This loop exists only to waste time
5326 for($i=0; $i<1000; $i++) {
5327 $ctx1 = eval "new $use_md5";
5328 $ctx1->add($i & 1 ? $passwd : $final);
5329 $ctx1->add($salt) if ($i % 3);
5330 $ctx1->add($passwd) if ($i % 7);
5331 $ctx1->add($i & 1 ? $final : $passwd);
5332 $final = $ctx1->digest();
5336 # Convert the 16-byte final string into a readable form
5338 local @final = map { ord($_) } split(//, $final);
5339 $l = ($final[ 0]<<16) + ($final[ 6]<<8) + $final[12];
5340 $rv .= &to64($l, 4);
5341 $l = ($final[ 1]<<16) + ($final[ 7]<<8) + $final[13];
5342 $rv .= &to64($l, 4);
5343 $l = ($final[ 2]<<16) + ($final[ 8]<<8) + $final[14];
5344 $rv .= &to64($l, 4);
5345 $l = ($final[ 3]<<16) + ($final[ 9]<<8) + $final[15];
5346 $rv .= &to64($l, 4);
5347 $l = ($final[ 4]<<16) + ($final[10]<<8) + $final[ 5];
5348 $rv .= &to64($l, 4);
5350 $rv .= &to64($l, 2);
5352 # Add salt if needed
5354 return $magic.$salt.'$'.$rv;
5363 local ($v, $n) = @_;
5366 $r .= $itoa64[$v & 0x3f];
5372 # read_file(file, &assoc, [&order], [lowercase])
5373 # Fill an associative array with name=value pairs from a file
5376 open(ARFILE, $_[0]) || return 0;
5379 if (!/^#/ && /^([^=]*)=(.*)$/) {
5380 $_[1]->{$_[3] ? lc($1) : $1} = $2;
5381 push(@{$_[2]}, $1) if ($_[2]);
5388 # write_file(file, array)
5389 # Write out the contents of an associative array as name=value lines
5392 local(%old, @order);
5393 &read_file($_[0], \%old, \@order);
5394 open(ARFILE, ">$_[0]");
5395 foreach $k (@order) {
5396 print ARFILE $k,"=",$_[1]->{$k},"\n" if (exists($_[1]->{$k}));
5398 foreach $k (keys %{$_[1]}) {
5399 print ARFILE $k,"=",$_[1]->{$k},"\n" if (!exists($old{$k}));
5404 # execute_ready_webmin_crons()
5405 # Find and run any cron jobs that are due, based on their last run time and
5406 # execution interval
5407 sub execute_ready_webmin_crons
5411 foreach my $cron (@webmincrons) {
5413 if (!$webmincron_last{$cron->{'id'}}) {
5414 # If not ever run before, don't run right away
5415 $webmincron_last{$cron->{'id'}} = $now;
5418 elsif ($cron->{'interval'} &&
5419 $now - $webmincron_last{$cron->{'id'}} > $cron->{'interval'}) {
5420 # Older than interval .. time to run
5423 elsif ($cron->{'mins'}) {
5424 # Check if current time matches spec, and we haven't run in the
5426 my @tm = localtime($now);
5427 if (&matches_cron($cron->{'mins'}, $tm[1]) &&
5428 &matches_cron($cron->{'hours'}, $tm[2]) &&
5429 &matches_cron($cron->{'days'}, $tm[3]) &&
5430 &matches_cron($cron->{'months'}, $tm[4]+1) &&
5431 &matches_cron($cron->{'weekdays'}, $tm[6]) &&
5432 $now - $webmincron_last{$cron->{'id'}} > 60) {
5438 print DEBUG "Running cron id=$cron->{'id'} ".
5439 "module=$cron->{'module'} func=$cron->{'func'}\n";
5440 $webmincron_last{$cron->{'id'}} = $now;
5444 # Run via a wrapper command, which we run like a CGI
5446 # Setup CGI-like environment
5447 $envtz = $ENV{"TZ"};
5448 $envuser = $ENV{"USER"};
5449 $envpath = $ENV{"PATH"};
5450 $envlang = $ENV{"LANG"};
5451 $envroot = $ENV{"SystemRoot"};
5452 $envperllib = $ENV{'PERLLIB'};
5453 foreach my $k (keys %ENV) {
5456 $ENV{"PATH"} = $envpath if ($envpath);
5457 $ENV{"TZ"} = $envtz if ($envtz);
5458 $ENV{"USER"} = $envuser if ($envuser);
5459 $ENV{"OLD_LANG"} = $envlang if ($envlang);
5460 $ENV{"SystemRoot"} = $envroot if ($envroot);
5461 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
5462 $ENV{"HOME"} = $user_homedir;
5463 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
5464 $ENV{"SERVER_ADMIN"} = $config{"email"};
5466 $ENV{"SERVER_ROOT"} = $root0;
5467 $ENV{"SERVER_REALROOT"} = $root0;
5468 $ENV{"SERVER_PORT"} = $config{'port'};
5469 $ENV{"WEBMIN_CRON"} = 1;
5470 $ENV{"DOCUMENT_ROOT"} = $root0;
5471 $ENV{"DOCUMENT_REALROOT"} = $root0;
5472 $ENV{"MINISERV_CONFIG"} = $config_file;
5473 $ENV{"HTTPS"} = "ON" if ($use_ssl);
5474 $ENV{"MINISERV_PID"} = $miniserv_main_pid;
5475 $ENV{"SCRIPT_FILENAME"} = $config{'webmincron_wrapper'};
5476 if ($ENV{"SCRIPT_FILENAME"} =~ /^\Q$root0\E(\/.*)$/) {
5477 $ENV{"SCRIPT_NAME"} = $1;
5479 $config{'webmincron_wrapper'} =~ /^(.*)\//;
5481 foreach $k (keys %config) {
5482 if ($k =~ /^env_(\S+)$/) {
5483 $ENV{$1} = $config{$k};
5487 $SIG{'CHLD'} = 'DEFAULT';
5489 # Have SOCK closed if the perl exec's something
5491 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
5494 # Run the wrapper script by evaling it
5495 $pkg = "webmincron";
5496 $0 = $config{'webmincron_wrapper'};
5498 $main_process_id = $$;
5502 do \$miniserv::config{'webmincron_wrapper'};
5506 print STDERR "Perl cron failure : $@\n";
5511 push(@childpids, $pid);
5515 # Write out file containing last run times
5516 &write_file($config{'webmincron_last'}, \%webmincron_last);
5520 # matches_cron(cron-spec, time)
5521 # Checks if some minute or hour matches some cron spec, which can be * or a list
5525 my ($spec, $tm) = @_;
5530 foreach my $s (split(/,/, $spec)) {
5532 $s =~ /^(\d+)\-(\d+)$/ && $tm >= $1 && $tm <= $2) {
5540 # read_webmin_crons()
5541 # Read all scheduled webmin cron functions and store them in the @webmincrons
5543 sub read_webmin_crons
5546 opendir(CRONS, $config{'webmincron_dir'});
5547 print DEBUG "Reading crons from $config{'webmincron_dir'}\n";
5548 foreach my $f (readdir(CRONS)) {
5549 if ($f =~ /^(\d+)\.cron$/) {
5551 &read_file("$config{'webmincron_dir'}/$f", \%cron);
5554 foreach my $n ('module', 'func') {
5556 print STDERR "Cron $1 missing $n\n";
5560 if (!$cron{'interval'} && !$cron{'mins'} && !$cron{'special'}) {
5561 print STDERR "Cron $1 missing any time spec\n";
5564 if ($cron{'special'} eq 'hourly') {
5565 # Run every hour on the hour
5567 $cron{'hours'} = '*';
5568 $cron{'days'} = '*';
5569 $cron{'months'} = '*';
5570 $cron{'weekdays'} = '*';
5572 elsif ($cron{'special'} eq 'daily') {
5573 # Run every day at midnight
5575 $cron{'hours'} = '0';
5576 $cron{'days'} = '*';
5577 $cron{'months'} = '*';
5578 $cron{'weekdays'} = '*';
5580 elsif ($cron{'special'} eq 'monthly') {
5581 # Run every month on the 1st
5583 $cron{'hours'} = '0';
5584 $cron{'days'} = '1';
5585 $cron{'months'} = '*';
5586 $cron{'weekdays'} = '*';
5588 elsif ($cron{'special'} eq 'weekly') {
5589 # Run every month on the 1st
5591 $cron{'hours'} = '0';
5592 $cron{'days'} = '*';
5593 $cron{'months'} = '*';
5594 $cron{'weekdays'} = '0';
5596 elsif ($cron{'special'} eq 'yearly' ||
5597 $cron{'special'} eq 'annually') {
5598 # Run every year on 1st january
5600 $cron{'hours'} = '0';
5601 $cron{'days'} = '1';
5602 $cron{'months'} = '1';
5603 $cron{'weekdays'} = '*';
5605 elsif ($cron{'special'}) {
5606 print STDERR "Cron $1 invalid special time $cron{'special'}\n";
5609 if ($cron{'special'}) {
5610 delete($cron{'special'});
5613 print DEBUG "adding cron id=$cron{'id'} module=$cron{'module'} func=$cron{'func'}\n";
5614 push(@webmincrons, \%cron);
5620 # Check if some address is valid IPv4, returns 1 if so.
5623 return $_[0] =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/ &&
5624 $1 >= 0 && $1 <= 255 &&
5625 $2 >= 0 && $2 <= 255 &&
5626 $3 >= 0 && $3 <= 255 &&
5627 $4 >= 0 && $4 <= 255;
5630 # Check if some IPv6 address is properly formatted, and returns 1 if so.
5631 sub check_ip6address
5633 my @blocks = split(/:/, $_[0]);
5634 return 0 if (@blocks == 0 || @blocks > 8);
5636 my $where = index($blocks[$ib],"/");
5639 my $b = substr($blocks[$ib],0,$where);
5640 $m = substr($blocks[$ib],$where+1,length($blocks[$ib])-($where+1));
5643 return 0 if ($m <0 || $m >128);
5646 foreach $b (@blocks) {
5647 return 0 if ($b ne "" && $b !~ /^[0-9a-f]{1,4}$/i);
5648 $empty++ if ($b eq "");
5650 return 0 if ($empty > 1 && !($_[0] =~ /^::/ && $empty == 2));
5654 # network_to_address(binary)
5655 # Given a network address in binary IPv4 or v4 format, return the string form
5656 sub network_to_address
5659 if (length($addr) == 4 || !$use_ipv6) {
5660 return inet_ntoa($addr);
5663 return Socket6::inet_ntop(Socket6::AF_INET6(), $addr);