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));
2984 $miniserv::page_capture_out .= substr($buf, $offset, $len)
2985 if ($miniserv::page_capture);
2992 my $buf = join(defined($,) ? $, : "", @_);
2993 $buf .= $\ if defined($\);
2994 &write_to_sock($buf);
2995 $miniserv::page_capture_out .= $buf
2996 if ($miniserv::page_capture);
3003 my $buf = sprintf $fmt, @_;
3004 &write_to_sock($buf);
3005 $miniserv::page_capture_out .= $buf
3006 if ($miniserv::page_capture);
3009 # Send back already read data while we have it, then read from SOCK
3013 my $bufref = \$_[0];
3016 if ($postpos < length($postinput)) {
3017 # Reading from already fetched array
3018 my $left = length($postinput) - $postpos;
3019 my $canread = $len > $left ? $left : $len;
3020 substr($$bufref, $offset, $canread) =
3021 substr($postinput, $postpos, $canread);
3022 $postpos += $canread;
3026 # Read from network socket
3027 local $data = &read_data($len);
3028 if ($data eq '' && $len) {
3030 print STDERR "finished reading - shutting down socket\n";
3033 substr($$bufref, $offset, length($data)) = $data;
3034 return length($data);
3040 #print STDERR "open() called - should never happen!\n";
3043 # Read a line of input
3047 if ($postpos < length($postinput) &&
3048 ($idx = index($postinput, "\n", $postpos)) >= 0) {
3049 # A line exists in the memory buffer .. use it
3050 my $line = substr($postinput, $postpos, $idx-$postpos+1);
3055 # Need to read from the socket
3057 if ($postpos < length($postinput)) {
3058 # Start with in-memory data
3059 $line = substr($postinput, $postpos);
3060 $postpos = length($postinput);
3062 my $nl = &read_line(0, 1);
3065 print STDERR "finished reading - shutting down socket\n";
3068 $line .= $nl if (defined($nl));
3073 # Read one character of input
3078 my $got = READ($r, \$buf, 1, 0);
3079 return $got > 0 ? $buf : undef;
3084 return fileno(SOCK);
3091 # write_to_sock(data, ...)
3096 if ($doneheaders || $miniserv::nph_script) {
3101 while(!$doneheaders && $headers =~ s/^([^\r\n]*)(\r)?\n//) {
3102 if ($1 =~ /^(\S+):\s+(.*)$/) {
3103 $cgiheader{lc($1)} = $2;
3104 push(@cgiheader, [ $1, $2 ]);
3106 elsif ($1 !~ /\S/) {
3110 &http_error(500, "Bad Header");
3114 if ($cgiheader{"location"}) {
3116 "HTTP/1.0 302 Moved Temporarily\r\n");
3117 &write_data("Date: $datestr\r\n");
3118 &write_data("Server: $config{server}\r\n");
3119 &write_keep_alive(0);
3121 elsif ($cgiheader{"content-type"} eq "") {
3122 &http_error(500, "Missing Content-Type Header");
3125 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
3126 &write_data("Date: $datestr\r\n");
3127 &write_data("Server: $config{server}\r\n");
3128 &write_keep_alive(0);
3130 foreach $h (@cgiheader) {
3131 &write_data("$h->[0]: $h->[1]\r\n");
3133 &write_data("\r\n");
3134 &reset_byte_count();
3135 &write_data($headers);
3143 local $cert = Net::SSLeay::X509_STORE_CTX_get_current_cert($_[1]);
3145 local $errnum = Net::SSLeay::X509_STORE_CTX_get_error($_[1]);
3146 $verified_client = 1 if (!$errnum);
3153 if ($doing_cgi_eval && $$ == $main_process_id) {
3154 # A CGI program called exit! This is a horrible hack to
3155 # finish up before really exiting
3158 close($PASSINw); close($PASSOUTw);
3159 &log_request($acpthost, $authuser, $reqline,
3160 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
3165 # Convert a string to a form ok for putting in a URL
3167 local($tmp, $tmp2, $c);
3170 while(($c = chop($tmp)) ne "") {
3171 if ($c !~ /[A-z0-9]/) {
3172 $c = sprintf("%%%2.2X", ord($c));
3179 # validate_user(username, password, host)
3180 # Checks if some username and password are valid. Returns the modified username,
3181 # the expired / temp pass flag, and the non-existence flag
3184 local ($user, $pass, $host) = @_;
3185 return ( ) if (!$user);
3186 print DEBUG "validate_user: user=$user pass=$pass host=$host\n";
3187 local ($canuser, $canmode, $notexist, $webminuser, $sudo) =
3188 &can_user_login($user, undef, $host);
3189 print DEBUG "validate_user: canuser=$canuser canmode=$canmode notexist=$notexist webminuser=$webminuser sudo=$sudo\n";
3191 # User doesn't even exist, so go no further
3192 return ( undef, 0, 1 );
3194 elsif ($canmode == 0) {
3195 # User does exist but cannot login
3196 return ( $canuser, 0, 0 );
3198 elsif ($canmode == 1) {
3199 # Attempt Webmin authentication
3200 my $uinfo = &get_user_details($webminuser);
3202 &password_crypt($pass, $uinfo->{'pass'}) eq $uinfo->{'pass'}) {
3203 # Password is valid .. but check for expiry
3204 local $lc = $uinfo->{'lastchanges'};
3205 print DEBUG "validate_user: Password is valid lc=$lc pass_maxdays=$config{'pass_maxdays'}\n";
3206 if ($config{'pass_maxdays'} && $lc && !$uinfo->{'nochange'}) {
3207 local $daysold = (time() - $lc)/(24*60*60);
3208 print DEBUG "maxdays=$config{'pass_maxdays'} daysold=$daysold temppass=$uinfo->{'temppass'}\n";
3209 if ($config{'pass_lockdays'} &&
3210 $daysold > $config{'pass_lockdays'}) {
3211 # So old that the account is locked
3212 return ( undef, 0, 0 );
3214 elsif ($daysold > $config{'pass_maxdays'}) {
3215 # Password has expired
3216 return ( $user, 1, 0 );
3219 if ($uinfo->{'temppass'}) {
3220 # Temporary password - force change now
3221 return ( $user, 2, 0 );
3223 return ( $user, 0, 0 );
3226 print DEBUG "validate_user: User $webminuser not found\n";
3227 return ( undef, 0, 0 );
3230 print DEBUG "validate_user: User $webminuser password mismatch $pass != $uinfo->{'pass'}\n";
3231 return ( undef, 0, 0 );
3234 elsif ($canmode == 2 || $canmode == 3) {
3235 # Attempt PAM or passwd file authentication
3236 local $val = &validate_unix_user($canuser, $pass);
3237 print DEBUG "validate_user: unix val=$val\n";
3238 if ($val && $sudo) {
3239 # Need to check if this Unix user can sudo
3240 if (!&check_sudo_permissions($canuser, $pass)) {
3241 print DEBUG "validate_user: sudo failed\n";
3245 print DEBUG "validate_user: sudo passed\n";
3248 return $val == 2 ? ( $canuser, 1, 0 ) :
3249 $val == 1 ? ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3251 elsif ($canmode == 4) {
3252 # Attempt external authentication
3253 return &validate_external_user($canuser, $pass) ?
3254 ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3262 # validate_unix_user(user, password)
3263 # Returns 1 if a username and password are valid under unix, 0 if not,
3264 # or 2 if the account has expired.
3265 # Checks PAM if available, and falls back to reading the system password
3267 sub validate_unix_user
3271 $pam_username = $_[0];
3272 $pam_password = $_[1];
3273 eval "use Authen::PAM;";
3274 local $pamh = new Authen::PAM($config{'pam'}, $pam_username,
3277 local $pam_ret = $pamh->pam_authenticate();
3278 if ($pam_ret == PAM_SUCCESS()) {
3279 # Logged in OK .. make sure password hasn't expired
3280 local $acct_ret = $pamh->pam_acct_mgmt();
3281 if ($acct_ret == PAM_SUCCESS()) {
3282 $pamh->pam_open_session();
3285 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3286 $acct_ret == PAM_ACCT_EXPIRED()) {
3290 print STDERR "Unknown pam_acct_mgmt return value : $acct_ret\n";
3297 elsif ($config{'pam_only'}) {
3298 # Pam is not available, but configuration forces it's use!
3301 elsif ($config{'passwd_file'}) {
3302 # Check in a password file
3304 open(FILE, $config{'passwd_file'});
3305 if ($config{'passwd_file'} eq '/etc/security/passwd') {
3306 # Assume in AIX format
3309 if (/^\s*(\S+):/ && $1 eq $_[0]) {
3311 if (/^\s*password\s*=\s*(\S+)\s*$/) {
3312 $rv = $1 eq &password_crypt($_[1], $1) ?
3320 # Read the system password or shadow file
3322 local @l = split(/:/, $_, -1);
3323 local $u = $l[$config{'passwd_uindex'}];
3324 local $p = $l[$config{'passwd_pindex'}];
3326 $rv = $p eq &password_crypt($_[1], $p) ? 1 : 0;
3327 if ($config{'passwd_cindex'} ne '' && $rv) {
3328 # Password may have expired!
3329 local $c = $l[$config{'passwd_cindex'}];
3330 local $m = $l[$config{'passwd_mindex'}];
3331 local $day = time()/(24*60*60);
3332 if ($c =~ /^\d+/ && $m =~ /^\d+/ &&
3338 if ($p eq "" && $config{'passwd_blank'}) {
3339 # Force password change
3347 return $rv if ($rv);
3350 # Fallback option - check password returned by getpw*
3351 local @uinfo = getpwnam($_[0]);
3352 if ($uinfo[1] ne '' && &password_crypt($_[1], $uinfo[1]) eq $uinfo[1]) {
3356 return 0; # Totally failed
3359 # validate_external_user(user, pass)
3360 # Validate a user by passing the username and password to an external
3361 # squid-style authentication program
3362 sub validate_external_user
3364 return 0 if (!$config{'extauth'});
3366 local $str = "$_[0] $_[1]\n";
3367 syswrite(EXTAUTH, $str, length($str));
3368 local $resp = <EXTAUTH>;
3370 return $resp =~ /^OK/i ? 1 : 0;
3373 # can_user_login(username, no-append, host)
3374 # Checks if a user can login or not.
3375 # First return value is the username.
3376 # Second is 0 if cannot login, 1 if using Webmin pass, 2 if PAM, 3 if password
3377 # file, 4 if external.
3378 # Third is 1 if the user does not exist at all, 0 if he does.
3379 # Fourth is the Webmin username whose permissions apply, based on unixauth.
3380 # Fifth is a flag indicating if a sudo check is needed.
3383 local $uinfo = &get_user_details($_[0]);
3385 # See if this user exists in Unix and can be validated by the same
3386 # method as the unixauth webmin user
3387 local $realuser = $unixauth{$_[0]};
3391 eval { @uinfo = getpwnam($_[0]); }; # may fail on windows
3392 if (!$realuser && @uinfo) {
3393 # No unixauth entry for the username .. try his groups
3394 foreach my $ua (keys %unixauth) {
3395 if ($ua =~ /^\@(.*)$/) {
3396 if (&is_group_member(\@uinfo, $1)) {
3397 $realuser = $unixauth{$ua};
3403 if (!$realuser && @uinfo) {
3404 # Fall back to unix auth for all Unix users
3405 $realuser = $unixauth{"*"};
3407 if (!$realuser && $use_sudo && @uinfo) {
3408 # Allow login effectively as root, if sudo permits it
3412 if (!$realuser && !@uinfo && $config{'pamany'}) {
3413 # If the user completely doesn't exist, we can still allow
3414 # him to authenticate via PAM
3415 $realuser = $config{'pamany'};
3419 # For Usermin, always fall back to unix auth for any user,
3420 # so that later checks with domain added / removed are done.
3421 $realuser = $unixauth{"*"};
3423 return (undef, 0, 1, undef) if (!$realuser);
3424 local $uinfo = &get_user_details($realuser);
3425 return (undef, 0, 1, undef) if (!$uinfo);
3426 local $up = $uinfo->{'pass'};
3428 # Work out possible domain names from the hostname
3429 local @doms = ( $_[2] );
3430 if ($_[2] =~ /^([^\.]+)\.(\S+)$/) {
3434 if ($config{'user_mapping'} && !%user_mapping) {
3435 # Read the user mapping file
3437 open(MAPPING, $config{'user_mapping'});
3441 if (/^(\S+)\s+(\S+)/) {
3442 if ($config{'user_mapping_reverse'}) {
3443 $user_mapping{$1} = $2;
3446 $user_mapping{$2} = $1;
3453 # Check the user mapping file to see if there is an entry for the
3454 # user login in which specifies a new effective user
3456 foreach my $d (@doms) {
3457 $um ||= $user_mapping{"$_[0]\@$d"};
3459 $um ||= $user_mapping{$_[0]};
3460 if (defined($um) && ($_[1]&4) == 0) {
3461 # A mapping exists - use it!
3462 return &can_user_login($um, $_[1]+4, $_[2]);
3465 # Check if a user with the entered login and the domains appended
3466 # or prepended exists, and if so take it to be the effective user
3467 if (!@uinfo && $config{'domainuser'}) {
3468 # Try again with name.domain and name.firstpart
3469 local @firsts = map { /^([^\.]+)/; $1 } @doms;
3470 if (($_[1]&1) == 0) {
3472 foreach $a (@firsts, @doms) {
3473 foreach $p ("$_[0].${a}", "$_[0]-${a}",
3474 "${a}.$_[0]", "${a}-$_[0]",
3475 "$_[0]_${a}", "${a}_$_[0]") {
3476 local @vu = &can_user_login(
3477 $p, $_[1]+1, $_[2]);
3478 return @vu if ($vu[1]);
3484 # Check if the user entered a domain at the end of his username when
3485 # he really shouldn't have, and if so try without it
3486 if (!@uinfo && $config{'domainstrip'} &&
3487 $_[0] =~ /^(\S+)\@(\S+)$/ && ($_[1]&2) == 0) {
3488 local ($stripped, $dom) = ($1, $2);
3489 local @vu = &can_user_login($stripped, $_[1] + 2, $_[2]);
3490 return @vu if ($vu[1]);
3491 local @vu = &can_user_login($stripped, $_[1] + 2, $dom);
3492 return @vu if ($vu[1]);
3495 return ( undef, 0, 1, undef ) if (!@uinfo && !$pamany);
3498 if (defined(@allowusers)) {
3499 # Only allow people on the allow list
3500 return ( undef, 0, 0, undef )
3501 if (!&users_match(\@uinfo, @allowusers));
3503 elsif (defined(@denyusers)) {
3504 # Disallow people on the deny list
3505 return ( undef, 0, 0, undef )
3506 if (&users_match(\@uinfo, @denyusers));
3508 if ($config{'shells_deny'}) {
3510 open(SHELLS, $config{'shells_deny'});
3514 $found++ if ($_ eq $uinfo[8]);
3517 return ( undef, 0, 0, undef ) if (!$found);
3522 # PAM or passwd file authentication
3523 print DEBUG "can_user_login: Validate with PAM\n";
3524 return ( $_[0], $use_pam ? 2 : 3, 0, $realuser, $sudo );
3526 elsif ($up eq 'e') {
3527 # External authentication
3528 print DEBUG "can_user_login: Validate externally\n";
3529 return ( $_[0], 4, 0, $realuser, $sudo );
3532 # Fixed Webmin password
3533 print DEBUG "can_user_login: Validate by Webmin\n";
3534 return ( $_[0], 1, 0, $realuser, $sudo );
3537 elsif ($uinfo->{'pass'} eq 'x') {
3538 # Webmin user authenticated via PAM or password file
3539 return ( $_[0], $use_pam ? 2 : 3, 0, $_[0] );
3541 elsif ($uinfo->{'pass'} eq 'e') {
3542 # Webmin user authenticated externally
3543 return ( $_[0], 4, 0, $_[0] );
3546 # Normal Webmin user
3547 return ( $_[0], 1, 0, $_[0] );
3551 # the PAM conversation function for interactive logins
3554 $pam_conv_func_called++;
3561 $ans = $pam_username if ($code == PAM_PROMPT_ECHO_ON() );
3562 $ans = $pam_password if ($code == PAM_PROMPT_ECHO_OFF() );
3564 push @res, PAM_SUCCESS();
3567 push @res, PAM_SUCCESS();
3576 # get_socket_ip(handle, ipv6-flag)
3577 # Returns the local IP address of some connection, as both a string and in
3581 local ($fh, $ipv6) = @_;
3582 local $sn = getsockname($fh);
3583 return undef if (!$sn);
3584 return &get_address_ip($sn, $ipv6);
3587 # get_address_ip(address, ipv6-flag)
3588 # Given a sockaddr object in binary format, return the binary address, text
3589 # address and port number
3592 local ($sn, $ipv6) = @_;
3594 local ($p, $b) = unpack_sockaddr_in6($sn);
3595 return ($b, inet_ntop(Socket6::AF_INET6(), $b), $p);
3598 local ($p, $b) = unpack_sockaddr_in($sn);
3599 return ($b, inet_ntoa($b), $p);
3603 # get_socket_name(handle, ipv6-flag)
3604 # Returns the local hostname or IP address of some connection
3607 local ($fh, $ipv6) = @_;
3608 return $config{'host'} if ($config{'host'});
3609 local ($mybin, $myaddr) = &get_socket_ip($fh, $ipv6);
3610 if (!$get_socket_name_cache{$myaddr}) {
3612 if (!$config{'no_resolv_myname'}) {
3613 $myname = gethostbyaddr($mybin,
3614 $ipv6 ? Socket6::AF_INET6() : AF_INET);
3616 $myname ||= $myaddr;
3617 $get_socket_name_cache{$myaddr} = $myname;
3619 return $get_socket_name_cache{$myaddr};
3622 # run_login_script(username, sid, remoteip, localip)
3623 sub run_login_script
3625 if ($config{'login_script'}) {
3626 system($config{'login_script'}.
3627 " ".join(" ", map { quotemeta($_) || '""' } @_).
3628 " >/dev/null 2>&1 </dev/null");
3632 # run_logout_script(username, sid, remoteip, localip)
3633 sub run_logout_script
3635 if ($config{'logout_script'}) {
3636 system($config{'logout_script'}.
3637 " ".join(" ", map { quotemeta($_) || '""' } @_).
3638 " >/dev/null 2>&1 </dev/null");
3642 # close_all_sockets()
3643 # Closes all the main listening sockets
3644 sub close_all_sockets
3647 foreach $s (@socketfhs) {
3653 # Close all pipes for talking to sub-processes
3657 foreach $p (@passin) { close($p); }
3658 foreach $p (@passout) { close($p); }
3659 foreach $p (values %conversations) {
3660 if ($p->{'PAMOUTr'}) {
3661 close($p->{'PAMOUTr'});
3662 close($p->{'PAMINw'});
3667 # check_user_ip(user)
3668 # Returns 1 if some user is allowed to login from the accepting IP, 0 if not
3671 local ($username) = @_;
3672 local $uinfo = &get_user_details($username);
3673 return 1 if (!$uinfo);
3674 if ($uinfo->{'deny'} &&
3675 &ip_match($acptip, $localip, @{$uinfo->{'deny'}}) ||
3676 $uinfo->{'allow'} &&
3677 !&ip_match($acptip, $localip, @{$uinfo->{'allow'}})) {
3683 # check_user_time(user)
3684 # Returns 1 if some user is allowed to login at the current date and time
3687 local ($username) = @_;
3688 local $uinfo = &get_user_details($username);
3689 return 1 if (!$uinfo || !$uinfo->{'allowdays'} && !$uinfo->{'allowhours'});
3690 local @tm = localtime(time());
3691 if ($uinfo->{'allowdays'}) {
3692 # Make sure day is allowed
3693 return 0 if (&indexof($tm[6], @{$uinfo->{'allowdays'}}) < 0);
3695 if ($uinfo->{'allowhours'}) {
3696 # Make sure time is allowed
3697 local $m = $tm[2]*60+$tm[1];
3698 return 0 if ($m < $uinfo->{'allowhours'}->[0] ||
3699 $m > $uinfo->{'allowhours'}->[1]);
3704 # generate_random_id(password, [force-urandom])
3705 # Returns a random session ID number
3706 sub generate_random_id
3708 local ($pass, $force_urandom) = @_;
3710 if (!$bad_urandom) {
3711 # First try /dev/urandom, unless we have marked it as bad
3712 $SIG{ALRM} = "miniserv::urandom_timeout";
3714 if (open(RANDOM, "/dev/urandom")) {
3716 if (read(RANDOM, $tmpsid, 16) == 16) {
3717 $sid = lc(unpack('h*',$tmpsid));
3723 if (!$sid && !$force_urandom) {
3726 foreach $c (split(//, &unix_crypt($pass, substr($$, -2)))) {
3727 $sid += ord($c) * $mul;
3734 # handle_login(username, ok, expired, not-exists, password, [no-test-cookie])
3735 # Called from handle_session to either mark a user as logged in, or not
3738 local ($vu, $ok, $expired, $nonexist, $pass, $notest) = @_;
3739 $authuser = $vu if ($ok);
3741 # check if the test cookie is set
3742 if ($header{'cookie'} !~ /testing=1/ && $vu &&
3743 !$config{'no_testing_cookie'} && !$notest) {
3744 &http_error(500, "No cookies",
3745 "Your browser does not support cookies, ".
3746 "which are required for this web server to ".
3747 "work in session authentication mode");
3750 # check with main process for delay
3751 if ($config{'passdelay'} && $vu) {
3752 print DEBUG "handle_login: requesting delay vu=$vu acptip=$acptip ok=$ok\n";
3753 print $PASSINw "delay $vu $acptip $ok\n";
3754 <$PASSOUTr> =~ /(\d+) (\d+)/;
3757 print DEBUG "handle_login: delay=$1 blocked=$2\n";
3760 if ($ok && (!$expired ||
3761 $config{'passwd_mode'} == 1)) {
3762 # Logged in OK! Tell the main process about
3764 local $sid = &generate_random_id($pass);
3765 print DEBUG "handle_login: sid=$sid\n";
3766 print $PASSINw "new $sid $authuser $acptip\n";
3768 # Run the post-login script, if any
3769 &run_login_script($authuser, $sid,
3772 # Check for a redirect URL for the user
3773 local $rurl = &login_redirect($authuser, $pass, $host);
3774 print DEBUG "handle_login: redirect URL rurl=$rurl\n";
3776 # Got one .. go to it
3777 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3778 &write_data("Date: $datestr\r\n");
3779 &write_data("Server: $config{'server'}\r\n");
3780 &write_data("Location: $rurl\r\n");
3781 &write_keep_alive(0);
3782 &write_data("\r\n");
3783 &log_request($acpthost, $authuser, $reqline, 302, 0);
3786 # Set cookie and redirect to originally requested page
3787 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3788 &write_data("Date: $datestr\r\n");
3789 &write_data("Server: $config{'server'}\r\n");
3790 local $ssl = $use_ssl || $config{'inetd_ssl'};
3791 $portstr = $port == 80 && !$ssl ? "" :
3792 $port == 443 && $ssl ? "" : ":$port";
3793 $prot = $ssl ? "https" : "http";
3794 local $sec = $ssl ? "; secure" : "";
3795 #$sec .= "; httpOnly";
3796 if ($in{'page'} !~ /^\/[A-Za-z0-9\/\.\-\_]+$/) {
3797 # Make redirect URL safe
3801 &write_data("Set-Cookie: $sidname=$sid; path=/; expires=\"Thu, 31-Dec-2037 00:00:00\"$sec\r\n");
3804 &write_data("Set-Cookie: $sidname=$sid; path=/$sec\r\n");
3806 &write_data("Location: $prot://$host$portstr$in{'page'}\r\n");
3807 &write_keep_alive(0);
3808 &write_data("\r\n");
3809 &log_request($acpthost, $authuser, $reqline, 302, 0);
3810 syslog("info", "%s", "Successful login as $authuser from $acpthost") if ($use_syslog);
3811 &write_login_utmp($authuser, $acpthost);
3815 elsif ($ok && $expired &&
3816 ($config{'passwd_mode'} == 2 || $expired == 2)) {
3817 # Login was ok, but password has expired or was temporary. Need
3818 # to force display of password change form.
3821 $querystring = "&user=".&urlize($vu).
3823 "&expired=".$expired;
3826 $page = $config{'password_form'};
3828 $miniserv_internal = 2;
3829 syslog("crit", "%s",
3830 "Expired login as $vu ".
3831 "from $acpthost") if ($use_syslog);
3834 # Login failed, or password has expired. The login form will be
3835 # displayed again by later code
3837 $request_uri = $in{'page'};
3838 $already_session_id = undef;
3840 $authuser = $baseauthuser = undef;
3841 syslog("crit", "%s",
3842 ($nonexist ? "Non-existent" :
3843 $expired ? "Expired" : "Invalid").
3844 " login as $vu from $acpthost")
3850 # write_login_utmp(user, host)
3851 # Record the login by some user in utmp
3852 sub write_login_utmp
3855 # Write utmp record for login
3856 %utmp = ( 'ut_host' => $_[1],
3857 'ut_time' => time(),
3859 'ut_type' => 7, # user process
3860 'ut_pid' => $main_process_id,
3861 'ut_line' => $config{'pam'},
3863 if (defined(&User::Utmp::putut)) {
3864 User::Utmp::putut(\%utmp);
3867 User::Utmp::pututline(\%utmp);
3872 # write_logout_utmp(user, host)
3873 # Record the logout by some user in utmp
3874 sub write_logout_utmp
3877 # Write utmp record for logout
3878 %utmp = ( 'ut_host' => $_[1],
3879 'ut_time' => time(),
3881 'ut_type' => 8, # dead process
3882 'ut_pid' => $main_process_id,
3883 'ut_line' => $config{'pam'},
3885 if (defined(&User::Utmp::putut)) {
3886 User::Utmp::putut(\%utmp);
3889 User::Utmp::pututline(\%utmp);
3894 # pam_conversation_process(username, write-pipe, read-pipe)
3895 # This function is called inside a sub-process to communicate with PAM. It sends
3896 # questions down one pipe, and reads responses from another
3897 sub pam_conversation_process
3899 local ($user, $writer, $reader) = @_;
3900 $miniserv::pam_conversation_process_writer = $writer;
3901 $miniserv::pam_conversation_process_reader = $reader;
3902 eval "use Authen::PAM;";
3903 local $convh = new Authen::PAM(
3904 $config{'pam'}, $user, \&miniserv::pam_conversation_process_func);
3905 local $pam_ret = $convh->pam_authenticate();
3906 if ($pam_ret == PAM_SUCCESS()) {
3907 local $acct_ret = $convh->pam_acct_mgmt();
3908 if ($acct_ret == PAM_SUCCESS()) {
3909 $convh->pam_open_session();
3910 print $writer "x2 $user 1 0 0\n";
3912 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3913 $acct_ret == PAM_ACCT_EXPIRED()) {
3914 print $writer "x2 $user 1 1 0\n";
3917 print $writer "x0 Unknown PAM account status $acct_ret\n";
3921 print $writer "x2 $user 0 0 0\n";
3926 # pam_conversation_process_func(type, message, [type, message, ...])
3927 # A pipe that talks to both PAM and the master process
3928 sub pam_conversation_process_func
3931 select($miniserv::pam_conversation_process_writer); $| = 1; select(STDOUT);
3933 local ($type, $msg) = (shift, shift);
3935 local $ok = (print $miniserv::pam_conversation_process_writer "$type $msg\n");
3936 print $miniserv::pam_conversation_process_writer "\n";
3937 local $answer = <$miniserv::pam_conversation_process_reader>;
3938 $answer =~ s/\r|\n//g;
3939 push(@rv, PAM_SUCCESS(), $answer);
3941 push(@rv, PAM_SUCCESS());
3946 # Returns 4 new pipe file handles
3949 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3951 local %taken = ( (map { $_, 1 } @passin),
3952 (map { $_->{'PASSINr'} } values %conversations) );
3953 for($p=0; $taken{"PASSINr$p"}; $p++) { }
3954 $PASSINr = "PASSINr$p";
3955 $PASSINw = "PASSINw$p";
3956 $PASSOUTr = "PASSOUTr$p";
3957 $PASSOUTw = "PASSOUTw$p";
3958 pipe($PASSINr, $PASSINw);
3959 pipe($PASSOUTr, $PASSOUTw);
3960 select($PASSINw); $| = 1;
3961 select($PASSINr); $| = 1;
3962 select($PASSOUTw); $| = 1;
3963 select($PASSOUTw); $| = 1;
3965 return ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3968 # recv_pam_question(&conv, fd)
3969 # Reads one PAM question from the sub-process, and sends it to the HTTP handler.
3970 # Returns 0 if the conversation is over, 1 if not.
3971 sub recv_pam_question
3973 local ($conf, $fh) = @_;
3974 local $pr = $conf->{'PAMOUTr'};
3975 select($pr); $| = 1; select(STDOUT);
3976 local $line = <$pr>;
3977 $line =~ s/\r|\n//g;
3980 $line =~ s/\r|\n//g;
3982 $conf->{'last'} = time();
3985 print $fh "0 PAM conversation error\n";
3989 local ($type, $msg) = split(/\s+/, $line, 2);
3990 if ($type =~ /^x(\d+)/) {
3991 # Pass this status code through
3992 print $fh "$1 $msg\n";
3993 return $1 == 2 || $1 == 0 ? 0 : 1;
3995 elsif ($type == PAM_PROMPT_ECHO_ON()) {
3997 print $fh "1 $msg\n";
4000 elsif ($type == PAM_PROMPT_ECHO_OFF()) {
4002 print $fh "3 $msg\n";
4005 elsif ($type == PAM_ERROR_MSG() || $type == PAM_TEXT_INFO()) {
4006 # A message that does not require a response
4007 print $fh "4 $msg\n";
4012 print $fh "0 Unknown PAM message type $type\n";
4018 # send_pam_answer(&conv, answer)
4019 # Sends a response from the user to the PAM sub-process
4022 local ($conf, $answer) = @_;
4023 local $pw = $conf->{'PAMINw'};
4024 $conf->{'last'} = time();
4025 print $pw "$answer\n";
4028 # end_pam_conversation(&conv)
4029 # Clean up PAM conversation pipes and processes
4030 sub end_pam_conversation
4033 kill('KILL', $conv->{'pid'}) if ($conv->{'pid'});
4034 if ($conv->{'PAMINr'}) {
4035 close($conv->{'PAMINr'});
4036 close($conv->{'PAMOUTr'});
4037 close($conv->{'PAMINw'});
4038 close($conv->{'PAMOUTw'});
4040 delete($conversations{$conv->{'cid'}});
4043 # get_ipkeys(&miniserv)
4044 # Returns a list of IP address to key file mappings from a miniserv.conf entry
4048 foreach $k (keys %{$_[0]}) {
4049 if ($k =~ /^ipkey_(\S+)/) {
4050 local $ipkey = { 'ips' => [ split(/,/, $1) ],
4051 'key' => $_[0]->{$k},
4052 'index' => scalar(@rv) };
4053 $ipkey->{'cert'} = $_[0]->{'ipcert_'.$1};
4060 # create_ssl_context(keyfile, [certfile])
4061 sub create_ssl_context
4063 local ($keyfile, $certfile) = @_;
4065 eval { $ssl_ctx = Net::SSLeay::new_x_ctx() };
4066 $ssl_ctx ||= Net::SSLeay::CTX_new();
4067 $ssl_ctx || die "Failed to create SSL context : $!";
4068 if ($client_certs) {
4069 Net::SSLeay::CTX_load_verify_locations(
4070 $ssl_ctx, $config{'ca'}, "");
4071 Net::SSLeay::CTX_set_verify(
4072 $ssl_ctx, &Net::SSLeay::VERIFY_PEER, \&verify_client);
4074 if ($config{'extracas'}) {
4076 foreach $p (split(/\s+/, $config{'extracas'})) {
4077 Net::SSLeay::CTX_load_verify_locations(
4082 Net::SSLeay::CTX_use_RSAPrivateKey_file(
4084 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL key $keyfile";
4085 Net::SSLeay::CTX_use_certificate_file(
4086 $ssl_ctx, $certfile || $keyfile,
4087 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL cert $certfile";
4092 # ssl_connection_for_ip(socket)
4093 # Returns a new SSL connection object for some socket, or undef if failed
4094 sub ssl_connection_for_ip
4097 local $sn = getsockname($sock);
4099 print STDERR "Failed to get address for socket $sock\n";
4102 local $myip = inet_ntoa((unpack_sockaddr_in($sn))[1]);
4103 local $ssl_ctx = $ssl_contexts{$myip} || $ssl_contexts{"*"};
4104 local $ssl_con = Net::SSLeay::new($ssl_ctx);
4105 if ($config{'ssl_cipher_list'}) {
4106 # Force use of ciphers
4107 eval "Net::SSLeay::set_cipher_list(
4108 \$ssl_con, \$config{'ssl_cipher_list'})";
4110 print STDERR "SSL cipher $config{'ssl_cipher_list'} failed : ",
4116 Net::SSLeay::set_fd($ssl_con, fileno($sock));
4117 if (!Net::SSLeay::accept($ssl_con)) {
4118 print STDERR "Failed to initialize SSL connection\n";
4124 # login_redirect(username, password, host)
4125 # Calls the login redirect script (if configured), which may output a URL to
4126 # re-direct a user to after logging in.
4129 return undef if (!$config{'login_redirect'});
4130 local $quser = quotemeta($_[0]);
4131 local $qpass = quotemeta($_[1]);
4132 local $qhost = quotemeta($_[2]);
4133 local $url = `$config{'login_redirect'} $quser $qpass $qhost`;
4138 # reload_config_file()
4139 # Re-read %config, and call post-config actions
4140 sub reload_config_file
4142 &log_error("Reloading configuration");
4143 %config = &read_config_file($config_file);
4144 &update_vital_config();
4147 &build_config_mappings();
4148 &read_webmin_crons();
4149 if ($config{'session'}) {
4150 dbmclose(%sessiondb);
4151 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
4155 # read_config_file(file)
4156 # Reads the given config file, and returns a hash of values
4157 sub read_config_file
4160 open(CONF, $_[0]) || die "Failed to open config file $_[0] : $!";
4163 if (/^#/ || !/\S/) { next; }
4165 $name = $1; $val = $2;
4166 $name =~ s/^\s+//g; $name =~ s/\s+$//g;
4167 $val =~ s/^\s+//g; $val =~ s/\s+$//g;
4174 # update_vital_config()
4175 # Updates %config with defaults, and dies if something vital is missing
4176 sub update_vital_config
4178 my %vital = ("port", 80,
4180 "server", "MiniServ/0.01",
4181 "index_docs", "index.html index.htm index.cgi index.php",
4182 "addtype_html", "text/html",
4183 "addtype_txt", "text/plain",
4184 "addtype_gif", "image/gif",
4185 "addtype_jpg", "image/jpeg",
4186 "addtype_jpeg", "image/jpeg",
4187 "realm", "MiniServ",
4188 "session_login", "/session_login.cgi",
4189 "pam_login", "/pam_login.cgi",
4190 "password_form", "/password_form.cgi",
4191 "password_change", "/password_change.cgi",
4195 "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\$",
4197 "expires", 7*24*60*60,
4198 "pam_test_user", "root",
4200 foreach my $v (keys %vital) {
4202 if ($vital{$v} eq "") {
4203 die "Missing config option $v";
4205 $config{$v} = $vital{$v};
4208 if (!$config{'sessiondb'}) {
4209 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4210 $config{'sessiondb'} = "$1/sessiondb";
4212 if (!$config{'errorlog'}) {
4213 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
4214 $config{'errorlog'} = "$1/miniserv.error";
4216 if (!$config{'tempbase'}) {
4217 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4218 $config{'tempbase'} = "$1/cgitemp";
4220 if (!$config{'blockedfile'}) {
4221 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4222 $config{'blockedfile'} = "$1/blocked";
4224 if (!$config{'webmincron_dir'}) {
4225 $config_file =~ /^(.*)\/[^\/]+$/;
4226 $config{'webmincron_dir'} = "$1/webmincron/crons";
4228 if (!$config{'webmincron_last'}) {
4229 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
4230 $config{'webmincron_last'} = "$1/miniserv.lastcrons";
4232 if (!$config{'webmincron_wrapper'}) {
4233 $config{'webmincron_wrapper'} = $config{'root'}.
4234 "/webmincron/webmincron.pl";
4239 # Fills the %users and %certs hashes from the users file in %config
4248 undef(%lastchanges);
4251 if ($config{'userfile'}) {
4252 open(USERS, $config{'userfile'});
4255 local @user = split(/:/, $_, -1);
4256 $users{$user[0]} = $user[1];
4257 $certs{$user[0]} = $user[3] if ($user[3]);
4258 if ($user[4] =~ /^allow\s+(.*)/) {
4259 $allow{$user[0]} = $config{'alwaysresolve'} ?
4260 [ split(/\s+/, $1) ] :
4261 [ &to_ipaddress(split(/\s+/, $1)) ];
4263 elsif ($user[4] =~ /^deny\s+(.*)/) {
4264 $deny{$user[0]} = $config{'alwaysresolve'} ?
4265 [ split(/\s+/, $1) ] :
4266 [ &to_ipaddress(split(/\s+/, $1)) ];
4268 if ($user[5] =~ /days\s+(\S+)/) {
4269 $allowdays{$user[0]} = [ split(/,/, $1) ];
4271 if ($user[5] =~ /hours\s+(\d+)\.(\d+)-(\d+).(\d+)/) {
4272 $allowhours{$user[0]} = [ $1*60+$2, $3*60+$4 ];
4274 $lastchanges{$user[0]} = $user[6];
4275 $nochange{$user[0]} = $user[9];
4276 $temppass{$user[0]} = $user[10];
4281 # Test user DB, if configured
4282 if ($config{'userdb'}) {
4283 my $dbh = &connect_userdb($config{'userdb'});
4285 print STDERR "Failed to open users database : $dbh\n"
4288 &disconnect_userdb($config{'userdb'}, $dbh);
4293 # get_user_details(username)
4294 # Returns a hash ref of user details, either from config files or the user DB
4295 sub get_user_details
4297 my ($username) = @_;
4298 if (exists($users{$username})) {
4300 return { 'name' => $username,
4301 'pass' => $users{$username},
4302 'certs' => $certs{$username},
4303 'allow' => $allow{$username},
4304 'deny' => $deny{$username},
4305 'allowdays' => $allowdays{$username},
4306 'allowhours' => $allowhours{$username},
4307 'lastchanges' => $lastchanges{$username},
4308 'nochange' => $nochange{$username},
4309 'temppass' => $temppass{$username},
4310 'preroot' => $config{'preroot_'.$username},
4313 if ($config{'userdb'}) {
4314 # Try querying user database
4315 if (exists($get_user_details_cache{$username})) {
4317 return $get_user_details_cache{$username};
4319 print DEBUG "get_user_details: Connecting to user database\n";
4320 my ($dbh, $proto, $prefix, $args) = &connect_userdb($config{'userdb'});
4324 print DEBUG "get_user_details: Failed : $dbh\n";
4325 print STDERR "Failed to connect to user database : $dbh\n";
4327 elsif ($proto eq "mysql" || $proto eq "postgresql") {
4328 # Fetch user ID and password with SQL
4329 print DEBUG "get_user_details: Looking for $username in SQL\n";
4330 my $cmd = $dbh->prepare(
4331 "select id,pass from webmin_user where name = ?");
4332 if (!$cmd || !$cmd->execute($username)) {
4333 print STDERR "Failed to lookup user : ",
4337 my ($id, $pass) = $cmd->fetchrow();
4340 &disconnect_userdb($config{'userdb'}, $dbh);
4341 $get_user_details_cache{$username} = undef;
4342 print DEBUG "get_user_details: User not found\n";
4345 print DEBUG "get_user_details: id=$id pass=$pass\n";
4347 # Fetch attributes and add to user object
4348 print DEBUG "get_user_details: finding user attributes\n";
4349 my $cmd = $dbh->prepare(
4350 "select attr,value from webmin_user_attr where id = ?");
4351 if (!$cmd || !$cmd->execute($id)) {
4352 print STDERR "Failed to lookup user attrs : ",
4356 $user = { 'name' => $username,
4359 'proto' => $proto };
4360 while(my ($attr, $value) = $cmd->fetchrow()) {
4361 $attrs{$attr} = $value;
4365 elsif ($proto eq "ldap") {
4366 # Fetch user DN with LDAP
4367 print DEBUG "get_user_details: Looking for $username in LDAP\n";
4368 my $rv = $dbh->search(
4370 filter => '(&(cn='.$username.')(objectClass='.
4371 $args->{'userclass'}.'))',
4373 if (!$rv || $rv->code) {
4374 print STDERR "Failed to lookup user : ",
4375 ($rv ? $rv->error : "Unknown error"),"\n";
4378 my ($u) = $rv->all_entries();
4380 &disconnect_userdb($config{'userdb'}, $dbh);
4381 $get_user_details_cache{$username} = undef;
4382 print DEBUG "get_user_details: User not found\n";
4386 # Extract attributes
4387 my $pass = $u->get_value('webminPass');
4388 $user = { 'name' => $username,
4391 'proto' => $proto };
4392 foreach my $la ($u->get_value('webminAttr')) {
4393 my ($attr, $value) = split(/=/, $la, 2);
4394 $attrs{$attr} = $value;
4398 # Convert DB attributes into user object fields
4400 print DEBUG "get_user_details: got ",scalar(keys %attrs),
4402 $user->{'certs'} = $attrs{'cert'};
4403 if ($attrs{'allow'}) {
4404 $user->{'allow'} = $config{'alwaysresolve'} ?
4405 [ split(/\s+/, $attrs{'allow'}) ] :
4406 [ &to_ipaddress(split(/\s+/,$attrs{'allow'})) ];
4408 if ($attrs{'deny'}) {
4409 $user->{'deny'} = $config{'alwaysresolve'} ?
4410 [ split(/\s+/, $attrs{'deny'}) ] :
4411 [ &to_ipaddress(split(/\s+/,$attrs{'deny'})) ];
4413 if ($attrs{'days'}) {
4414 $user->{'allowdays'} = [ split(/,/, $attrs{'days'}) ];
4416 if ($attrs{'hoursfrom'} && $attrs{'hoursto'}) {
4417 my ($hf, $mf) = split(/\./, $attrs{'hoursfrom'});
4418 my ($ht, $mt) = split(/\./, $attrs{'hoursto'});
4419 $user->{'allowhours'} = [ $hf*60+$ht, $ht*60+$mt ];
4421 $user->{'lastchanges'} = $attrs{'lastchange'};
4422 $user->{'nochange'} = $attrs{'nochange'};
4423 $user->{'temppass'} = $attrs{'temppass'};
4424 $user->{'preroot'} = $attrs{'theme'};
4426 &disconnect_userdb($config{'userdb'}, $dbh);
4427 $get_user_details_cache{$user->{'name'}} = $user;
4433 # find_user_by_cert(cert)
4434 # Returns a username looked up by certificate
4435 sub find_user_by_cert
4437 my ($peername) = @_;
4438 my $peername2 = $peername;
4439 $peername2 =~ s/Email=/emailAddress=/ || $peername2 =~ s/emailAddress=/Email=/;
4441 # First check users in local files
4442 foreach my $username (keys %certs) {
4443 if ($certs{$username} eq $peername ||
4444 $certs{$username} eq $peername2) {
4450 if ($config{'userdb'}) {
4451 my ($dbh, $proto) = &connect_userdb($config{'userdb'});
4455 elsif ($proto eq "mysql" || $proto eq "postgresql") {
4457 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 = ?");
4458 return undef if (!$cmd);
4459 foreach my $p ($peername, $peername2) {
4461 if ($cmd->execute($p)) {
4462 ($username) = $cmd->fetchrow();
4465 return $username if ($username);
4468 elsif ($proto eq "ldap") {
4470 my $rv = $dbh->search(
4472 filter => '(objectClass='.
4473 $args->{'userclass'}.')',
4475 attrs => [ 'cn', 'webminAttr' ]);
4476 if ($rv && !$rv->code) {
4477 foreach my $u ($rv->all_entries) {
4478 my @attrs = $u->get_value('webminAttr');
4479 foreach my $la (@attrs) {
4480 my ($attr, $value) = split(/=/, $la, 2);
4481 if ($attr eq "cert" &&
4482 ($value eq $peername ||
4483 $value eq $peername2)) {
4484 return $u->get_value('cn');
4494 # connect_userdb(string)
4495 # Returns a handle for talking to a user database - may be a DBI or LDAP handle.
4496 # On failure returns an error message string. In an array context, returns the
4497 # protocol type too.
4501 my ($proto, $user, $pass, $host, $prefix, $args) = &split_userdb_string($str);
4502 if ($proto eq "mysql") {
4503 # Connect to MySQL with DBI
4504 my $drh = eval "use DBI; DBI->install_driver('mysql');";
4505 $drh || return $text{'sql_emysqldriver'};
4506 my ($host, $port) = split(/:/, $host);
4507 my $cstr = "database=$prefix;host=$host";
4508 $cstr .= ";port=$port" if ($port);
4509 print DEBUG "connect_userdb: Connecting to MySQL $cstr as $user\n";
4510 my $dbh = $drh->connect($cstr, $user, $pass, { });
4511 $dbh || return &text('sql_emysqlconnect', $drh->errstr);
4512 print DEBUG "connect_userdb: Connected OK\n";
4513 return wantarray ? ($dbh, $proto, $prefix, $args) : $dbh;
4515 elsif ($proto eq "postgresql") {
4516 # Connect to PostgreSQL with DBI
4517 my $drh = eval "use DBI; DBI->install_driver('Pg');";
4518 $drh || return $text{'sql_epostgresqldriver'};
4519 my ($host, $port) = split(/:/, $host);
4520 my $cstr = "dbname=$prefix;host=$host";
4521 $cstr .= ";port=$port" if ($port);
4522 print DEBUG "connect_userdb: Connecting to PostgreSQL $cstr as $user\n";
4523 my $dbh = $drh->connect($cstr, $user, $pass);
4524 $dbh || return &text('sql_epostgresqlconnect', $drh->errstr);
4525 print DEBUG "connect_userdb: Connected OK\n";
4526 return wantarray ? ($dbh, $proto, $prefix, $args) : $dbh;
4528 elsif ($proto eq "ldap") {
4529 # Connect with perl LDAP module
4530 eval "use Net::LDAP";
4531 $@ && return $text{'sql_eldapdriver'};
4532 my ($host, $port) = split(/:/, $host);
4533 my $scheme = $args->{'scheme'} || 'ldap';
4535 $port = $scheme eq 'ldaps' ? 636 : 389;
4537 my $ldap = Net::LDAP->new($host,
4539 'scheme' => $scheme);
4540 $ldap || return &text('sql_eldapconnect', $host);
4542 if ($args->{'tls'}) {
4543 # Switch to TLS mode
4544 eval { $mesg = $ldap->start_tls(); };
4545 if ($@ || !$mesg || $mesg->code) {
4546 return &text('sql_eldaptls',
4547 $@ ? $@ : $mesg ? $mesg->error : "Unknown error");
4550 # Login to the server
4552 $mesg = $ldap->bind(dn => $user, password => $pass);
4555 $mesg = $ldap->bind(dn => $user, anonymous => 1);
4557 if (!$mesg || $mesg->code) {
4558 return &text('sql_eldaplogin', $user,
4559 $mesg ? $mesg->error : "Unknown error");
4561 return wantarray ? ($ldap, $proto, $prefix, $args) : $ldap;
4564 return "Unknown protocol $proto";
4568 # split_userdb_string(string)
4569 # Converts a string like mysql://user:pass@host/db into separate parts
4570 sub split_userdb_string
4573 if ($str =~ /^([a-z]+):\/\/([^:]*):([^\@]*)\@([a-z0-9\.\-\_]+)\/([^\?]+)(\?(.*))?$/) {
4574 my ($proto, $user, $pass, $host, $prefix, $argstr) =
4575 ($1, $2, $3, $4, $5, $7);
4576 my %args = map { split(/=/, $_, 2) } split(/\&/, $argstr);
4577 return ($proto, $user, $pass, $host, $prefix, \%args);
4582 # disconnect_userdb(string, &handle)
4583 # Closes a handle opened by connect_userdb
4584 sub disconnect_userdb
4587 if ($str =~ /^(mysql|postgresql):/) {
4591 elsif ($str =~ /^ldap:/) {
4598 # Fills %mime with entries from file in %config and extra settings in %config
4602 if ($config{"mimetypes"} ne "") {
4603 open(MIME, $config{"mimetypes"});
4606 if (/^(\S+)\s+(.*)$/) {
4608 my @exts = split(/\s+/, $2);
4609 foreach my $ext (@exts) {
4610 $mime{$ext} = $type;
4616 foreach my $k (keys %config) {
4617 if ($k !~ /^addtype_(.*)$/) { next; }
4618 $mime{$1} = $config{$k};
4622 # build_config_mappings()
4623 # Build the anonymous access list, IP access list, unauthenticated URLs list,
4624 # redirect mapping and allow and deny lists from %config
4625 sub build_config_mappings
4627 # build anonymous access list
4629 foreach my $a (split(/\s+/, $config{'anonymous'})) {
4630 if ($a =~ /^([^=]+)=(\S+)$/) {
4631 $anonymous{$1} = $2;
4635 # build IP access list
4637 foreach my $a (split(/\s+/, $config{'ipaccess'})) {
4638 if ($a =~ /^([^=]+)=(\S+)$/) {
4643 # build unauthenticated URLs list
4644 @unauth = split(/\s+/, $config{'unauth'});
4646 # build redirect mapping
4648 foreach my $r (split(/\s+/, $config{'redirect'})) {
4649 if ($r =~ /^([^=]+)=(\S+)$/) {
4654 # build prefixes to be stripped
4655 undef(@strip_prefix);
4656 foreach my $r (split(/\s+/, $config{'strip_prefix'})) {
4657 push(@strip_prefix, $r);
4660 # Init allow and deny lists
4661 @deny = split(/\s+/, $config{"deny"});
4662 @deny = &to_ipaddress(@deny) if (!$config{'alwaysresolve'});
4663 @allow = split(/\s+/, $config{"allow"});
4664 @allow = &to_ipaddress(@allow) if (!$config{'alwaysresolve'});
4667 if ($config{'allowusers'}) {
4668 @allowusers = split(/\s+/, $config{'allowusers'});
4670 elsif ($config{'denyusers'}) {
4671 @denyusers = split(/\s+/, $config{'denyusers'});
4674 # Build list of unixauth mappings
4676 foreach my $ua (split(/\s+/, $config{'unixauth'})) {
4677 if ($ua =~ /^(\S+)=(\S+)$/) {
4681 $unixauth{"*"} = $ua;
4685 # Build list of non-session-auth pages
4686 undef(%sessiononly);
4687 foreach my $sp (split(/\s+/, $config{'sessiononly'})) {
4688 $sessiononly{$sp} = 1;
4691 # Build list of logout times
4692 undef(@logouttimes);
4693 foreach my $a (split(/\s+/, $config{'logouttimes'})) {
4694 if ($a =~ /^([^=]+)=(\S+)$/) {
4695 push(@logouttimes, [ $1, $2 ]);
4698 push(@logouttimes, [ undef, $config{'logouttime'} ]);
4700 # Build list of DAV pathss
4702 foreach my $d (split(/\s+/, $config{'davpaths'})) {
4703 push(@davpaths, $d);
4705 @davusers = split(/\s+/, $config{'dav_users'});
4707 # Mobile agent substrings and hostname prefixes
4708 @mobile_agents = split(/\t+/, $config{'mobile_agents'});
4709 @mobile_prefixes = split(/\s+/, $config{'mobile_prefixes'});
4713 if ($config{'debug'}) {
4714 open(DEBUG, ">>$config{'debug'}");
4717 open(DEBUG, ">/dev/null");
4720 # Reset cache of sudo checks
4724 # is_group_member(&uinfo, groupname)
4725 # Returns 1 if some user is a primary or secondary member of a group
4728 local ($uinfo, $group) = @_;
4729 local @ginfo = getgrnam($group);
4730 return 0 if (!@ginfo);
4731 return 1 if ($ginfo[2] == $uinfo->[3]); # primary member
4732 foreach my $m (split(/\s+/, $ginfo[3])) {
4733 return 1 if ($m eq $uinfo->[0]);
4738 # prefix_to_mask(prefix)
4739 # Converts a number like 24 to a mask like 255.255.255.0
4742 return $_[0] >= 24 ? "255.255.255.".(256-(2 ** (32-$_[0]))) :
4743 $_[0] >= 16 ? "255.255.".(256-(2 ** (24-$_[0]))).".0" :
4744 $_[0] >= 8 ? "255.".(256-(2 ** (16-$_[0]))).".0.0" :
4745 (256-(2 ** (8-$_[0]))).".0.0.0";
4748 # get_logout_time(user, session-id)
4749 # Given a username, returns the idle time before he will be logged out
4752 local ($user, $sid) = @_;
4753 if (!defined($logout_time_cache{$user,$sid})) {
4755 foreach my $l (@logouttimes) {
4756 if ($l->[0] =~ /^\@(.*)$/) {
4757 # Check group membership
4758 local @uinfo = getpwnam($user);
4759 if (@uinfo && &is_group_member(\@uinfo, $1)) {
4763 elsif ($l->[0] =~ /^\//) {
4764 # Check file contents
4765 open(FILE, $l->[0]);
4782 if ($l->[0] eq $user) {
4786 last if (defined($time));
4788 $logout_time_cache{$user,$sid} = $time;
4790 return $logout_time_cache{$user,$sid};
4793 # password_crypt(password, salt)
4794 # If the salt looks like MD5 and we have a library for it, perform MD5 hashing
4795 # of a password. Otherwise, do Unix crypt.
4798 local ($pass, $salt) = @_;
4799 if ($salt =~ /^\$1\$/ && $use_md5) {
4800 return &encrypt_md5($pass, $salt);
4803 return &unix_crypt($pass, $salt);
4807 # unix_crypt(password, salt)
4808 # Performs standard Unix hashing for a password
4811 local ($pass, $salt) = @_;
4812 if ($use_perl_crypt) {
4813 return Crypt::UnixCrypt::crypt($pass, $salt);
4816 return crypt($pass, $salt);
4820 # handle_dav_request(davpath)
4821 # Pass a request on to the Net::DAV::Server module
4822 sub handle_dav_request
4825 eval "use Filesys::Virtual::Plain";
4826 eval "use Net::DAV::Server";
4827 eval "use HTTP::Request";
4828 eval "use HTTP::Headers";
4830 if ($Net::DAV::Server::VERSION eq '1.28' && $config{'dav_nolock'}) {
4831 delete $Net::DAV::Server::implemented{lock};
4832 delete $Net::DAV::Server::implemented{unlock};
4835 # Read in request data
4836 if (!$posted_data) {
4837 local $clen = $header{"content-length"};
4838 while(length($posted_data) < $clen) {
4839 $buf = &read_data($clen - length($posted_data));
4840 if (!length($buf)) {
4841 &http_error(500, "Failed to read POST request");
4843 $posted_data .= $buf;
4847 # For subsequent logging
4848 open(MINISERVLOG, ">>$config{'logfile'}");
4852 local @u = getpwnam($authuser);
4853 if ($config{'dav_remoteuser'} && !$< && $validated) {
4856 $( = $u[3]; $) = "$u[3] $u[3]";
4857 ($>, $<) = ($u[2], $u[2]);
4859 if ($config{'dav_root'} eq '*') {
4864 &http_error(500, "Unix user $authuser does not exist");
4868 $root ||= $config{'dav_root'};
4871 # Check if this user can use DAV
4873 &users_match(\@u, @davusers) ||
4874 &http_error(500, "You are not allowed to access DAV");
4878 my $filesys = Filesys::Virtual::Plain->new({root_path => $root});
4879 my $webdav = Net::DAV::Server->new();
4880 $webdav->filesys($filesys);
4882 # Make up a request object, and feed to DAV
4883 local $ho = HTTP::Headers->new;
4884 foreach my $h (keys %header) {
4885 next if (lc($h) eq "connection");
4886 $ho->header($h => $header{$h});
4889 $request_uri =~ s/^\Q$path\E//;
4890 $request_uri = "/" if ($request_uri eq "");
4892 my $request = HTTP::Request->new($method, $request_uri, $ho,
4894 if ($config{'dav_debug'}) {
4895 print STDERR "DAV request :\n";
4896 print STDERR "---------------------------------------------\n";
4897 print STDERR $request->as_string();
4898 print STDERR "---------------------------------------------\n";
4900 my $response = $webdav->run($request);
4902 # Send back the reply
4903 &write_data("HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n");
4904 local $content = $response->content();
4906 $content =~ s|href>/(.+)<|href>$path/$1<|g;
4907 $content =~ s|href>/<|href>$path<|g;
4909 foreach my $h ($response->header_field_names) {
4910 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4911 &write_data("$h: ",$response->header($h),"\r\n");
4913 &write_data("Content-length: ",length($content),"\r\n");
4914 local $rv = &write_keep_alive(0);
4915 &write_data("\r\n");
4916 &write_data($content);
4918 if ($config{'dav_debug'}) {
4919 print STDERR "DAV reply :\n";
4920 print STDERR "---------------------------------------------\n";
4921 print STDERR "HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n";
4922 foreach my $h ($response->header_field_names) {
4923 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4924 print STDERR "$h: ",$response->header($h),"\r\n";
4926 print STDERR "Content-length: ",length($content),"\r\n";
4927 print STDERR "\r\n";
4928 print STDERR $content;
4929 print STDERR "---------------------------------------------\n";
4933 &log_request($acpthost, $authuser, $reqline, $response->code(),
4934 length($response->content()));
4937 # get_system_hostname()
4938 # Returns the hostname of this system, for reporting to listeners
4939 sub get_system_hostname
4941 # On Windows, try computername environment variable
4942 return $ENV{'computername'} if ($ENV{'computername'});
4943 return $ENV{'COMPUTERNAME'} if ($ENV{'COMPUTERNAME'});
4945 # If a specific command is set, use it first
4946 if ($config{'hostname_command'}) {
4947 local $out = `($config{'hostname_command'}) 2>&1`;
4954 # First try the hostname command
4955 local $out = `hostname 2>&1`;
4956 if (!$? && $out =~ /\S/) {
4961 # Try the Sys::Hostname module
4962 eval "use Sys::Hostname";
4964 local $rv = eval "hostname()";
4970 # Must use net name on Windows
4971 local $out = `net name 2>&1`;
4972 if ($out =~ /\-+\r?\n(\S+)/) {
4979 # indexof(string, array)
4980 # Returns the index of some value in an array, or -1
4983 for($i=1; $i <= $#_; $i++) {
4984 if ($_[$i] eq $_[0]) { return $i - 1; }
4990 # has_command(command)
4991 # Returns the full path if some command is in the path, undef if not
4995 if (!$_[0]) { return undef; }
4996 if (exists($has_command_cache{$_[0]})) {
4997 return $has_command_cache{$_[0]};
5000 if ($_[0] =~ /^\//) {
5001 $rv = -x $_[0] ? $_[0] : undef;
5004 local $sp = $on_windows ? ';' : ':';
5005 foreach $d (split($sp, $ENV{PATH})) {
5006 if (-x "$d/$_[0]") {
5011 foreach my $sfx (".exe", ".com", ".bat") {
5012 if (-r "$d/$_[0]".$sfx) {
5013 $rv = "$d/$_[0]".$sfx;
5020 $has_command_cache{$_[0]} = $rv;
5024 # check_sudo_permissions(user, pass)
5025 # Returns 1 if some user can run any command via sudo
5026 sub check_sudo_permissions
5028 local ($user, $pass) = @_;
5030 # First try the pipes
5032 print DEBUG "check_sudo_permissions: querying cache for $user\n";
5033 print $PASSINw "readsudo $user\n";
5034 local $can = <$PASSOUTr>;
5036 print DEBUG "check_sudo_permissions: cache said $can\n";
5037 if ($can =~ /^\d+$/ && $can != 2) {
5042 local $ptyfh = new IO::Pty;
5043 print DEBUG "check_sudo_permissions: ptyfh=$ptyfh\n";
5045 print STDERR "Failed to create new PTY with IO::Pty\n";
5048 local @uinfo = getpwnam($user);
5050 print STDERR "Unix user $user does not exist for sudo\n";
5054 # Execute sudo in a sub-process, via a pty
5055 local $ttyfh = $ptyfh->slave();
5056 print DEBUG "check_sudo_permissions: ttyfh=$ttyfh\n";
5057 local $tty = $ptyfh->ttyname();
5058 print DEBUG "check_sudo_permissions: tty=$tty\n";
5059 chown($uinfo[2], $uinfo[3], $tty);
5061 print DEBUG "check_sudo_permissions: about to fork..\n";
5062 local $pid = fork();
5063 print DEBUG "check_sudo_permissions: fork=$pid pid=$$\n";
5065 print STDERR "fork for sudo failed : $!\n";
5070 $ptyfh->make_slave_controlling_terminal();
5071 close(STDIN); close(STDOUT); close(STDERR);
5072 untie(*STDIN); untie(*STDOUT); untie(*STDERR);
5073 close($PASSINw); close($PASSOUTr);
5074 $( = $uinfo[3]; $) = "$uinfo[3] $uinfo[3]";
5075 ($>, $<) = ($uinfo[2], $uinfo[2]);
5080 open(STDIN, "<&SUDOr");
5081 open(STDOUT, ">$tty");
5082 open(STDERR, ">&STDOUT");
5085 print "Exec failed : $!\n";
5088 print DEBUG "check_sudo_permissions: pid=$pid\n";
5090 $ptyfh->close_slave();
5092 # Send password, and get back response
5093 local $oldfh = select(SUDOw);
5096 print DEBUG "check_sudo_permissions: about to send pass\n";
5097 local $SIG{'PIPE'} = 'ignore'; # Sometimes sudo doesn't ask for a password
5098 print SUDOw $pass,"\n";
5099 print DEBUG "check_sudo_permissions: sent pass=$pass\n";
5103 print DEBUG "check_sudo_permissions: got $_";
5109 local ($ok) = ($out =~ /\(ALL\)\s+ALL/ ? 1 : 0);
5113 print $PASSINw "writesudo $user $ok\n";
5119 # is_mobile_useragent(agent)
5120 # Returns 1 if some user agent looks like a cellphone or other mobile device,
5122 sub is_mobile_useragent
5124 local ($agent) = @_;
5126 "UP.Link", # Openwave
5127 "Nokia", # All Nokias start with Nokia
5128 "MOT-", # All Motorola phones start with MOT-
5129 "SAMSUNG", # Samsung browsers
5130 "Samsung", # Samsung browsers
5131 "SEC-", # Samsung browsers
5132 "AU-MIC", # Samsung browsers
5133 "AUDIOVOX", # Audiovox
5134 "BlackBerry", # BlackBerry
5135 "hiptop", # Danger hiptop Sidekick
5136 "SonyEricsson", # Sony Ericsson
5137 "Ericsson", # Old Ericsson browsers , mostly WAP
5138 "Mitsu/1.1.A", # Mitsubishi phones
5139 "Panasonic WAP", # Panasonic old WAP phones
5140 "DoCoMo", # DoCoMo phones
5141 "Lynx", # Lynx text-mode linux browser
5142 "Links", # Another text-mode linux browser
5144 local @substrings = (
5145 "UP.Browser", # Openwave
5146 "MobilePhone", # NetFront
5147 "AU-MIC-A700", # Samsung A700 Obigo browsers
5148 "Danger hiptop", # Danger Sidekick hiptop
5149 "Windows CE", # Windows CE Pocket PC
5150 "IEMobile", # Windows mobile browser
5151 "Blazer", # Palm Treo Blazer
5152 "BlackBerry", # BlackBerries can emulate other browsers, but
5153 # they still keep this string in the UserAgent
5154 "SymbianOS", # New Series60 browser has safari in it and
5155 # SymbianOS is the only distinguishing string
5156 "iPhone", # Apple iPhone KHTML browser
5157 "iPod", # iPod touch browser
5158 "MobileSafari", # HTTP client in iPhone
5160 "Opera Mini", # Opera Mini
5161 "HTC_P3700", # HTC mobile device
5163 "webOS/", # Palm WebOS
5164 "Nintendo DS", # DSi / DSi-XL
5166 foreach my $p (@prefixes) {
5167 return 1 if ($agent =~ /^\Q$p\E/);
5169 foreach my $s (@substrings, @mobile_agents) {
5170 return 1 if ($agent =~ /\Q$s\E/);
5175 # write_blocked_file()
5176 # Writes out a text file of blocked hosts and users
5177 sub write_blocked_file
5179 open(BLOCKED, ">$config{'blockedfile'}");
5180 foreach my $d (grep { $hostfail{$_} } @deny) {
5181 print BLOCKED "host $d $hostfail{$d} $blockhosttime{$d}\n";
5183 foreach my $d (grep { $userfail{$_} } @denyusers) {
5184 print BLOCKED "user $d $userfail{$d} $blockusertime{$d}\n";
5187 chmod(0700, $config{'blockedfile'});
5192 open(PIDFILE, ">$config{'pidfile'}");
5193 printf PIDFILE "%d\n", getpid();
5195 $miniserv_main_pid = getpid();
5198 # lock_user_password(user)
5199 # Updates a user's password file entry to lock it, both in memory and on disk.
5200 # Returns 1 if done, -1 if no such user, 0 if already locked
5201 sub lock_user_password
5204 local $uinfo = &get_user_details($user);
5209 if ($uinfo->{'pass'} =~ /^\!/) {
5213 if (!$uinfo->{'proto'}) {
5214 # Write to users file
5215 $users{$user} = "!".$users{$user};
5216 open(USERS, $config{'userfile'});
5217 local @ufile = <USERS>;
5219 foreach my $u (@ufile) {
5220 local @uinfo = split(/:/, $u);
5221 if ($uinfo[0] eq $user) {
5222 $uinfo[1] = $users{$user};
5224 $u = join(":", @uinfo);
5226 open(USERS, ">$config{'userfile'}");
5232 if ($config{'userdb'}) {
5234 my ($dbh, $proto, $prefix, $args) = &connect_userdb($config{'userdb'});
5238 elsif ($proto eq "mysql" || $proto eq "postgresql") {
5239 # Update user attribute
5240 my $cmd = $dbh->prepare(
5241 "update webmin_user set pass = ? where id = ?");
5242 if (!$cmd || !$cmd->execute("!".$uinfo->{'pass'},
5245 print STDERR "Failed to lock password : ",
5249 $cmd->finish() if ($cmd);
5251 elsif ($proto eq "ldap") {
5252 # Update LDAP object
5253 my $rv = $dbh->modify($uinfo->{'id'},
5254 replace => { 'webminPass' => '!'.$uinfo->{'pass'} });
5255 if (!$rv || $rv->code) {
5256 print STDERR "Failed to lock password : ",
5257 ($rv ? $rv->error : "Unknown error"),"\n";
5261 &disconnect_userdb($config{'userdb'}, $dbh);
5265 return -1; # This should never be reached
5268 # hash_session_id(sid)
5269 # Returns an MD5 or Unix-crypted session ID
5273 if (!$hash_session_id_cache{$sid}) {
5276 $hash_session_id_cache{$sid} = &encrypt_md5($sid);
5280 $hash_session_id_cache{$sid} = &unix_crypt($sid, "XX");
5283 return $hash_session_id_cache{$sid};
5286 # encrypt_md5(string, [salt])
5287 # Returns a string encrypted in MD5 format
5290 local ($passwd, $salt) = @_;
5291 local $magic = '$1$';
5292 if ($salt =~ /^\$1\$([^\$]+)/) {
5293 # Extract actual salt from already encrypted password
5298 local $ctx = eval "new $use_md5";
5305 # Add some more stuff from the hash of the password and salt
5306 local $ctx1 = eval "new $use_md5";
5307 $ctx1->add($passwd);
5311 $ctx1->add($passwd);
5312 local $final = $ctx1->digest();
5313 for($pl=length($passwd); $pl>0; $pl-=16) {
5314 $ctx->add($pl > 16 ? $final : substr($final, 0, $pl));
5317 # This piece of code seems rather pointless, but it's in the C code that
5318 # does MD5 in PAM so it has to go in!
5321 for($i=length($passwd); $i; $i >>= 1) {
5326 $ctx->add(substr($passwd, $j, 1));
5329 $final = $ctx->digest();
5332 # This loop exists only to waste time
5333 for($i=0; $i<1000; $i++) {
5334 $ctx1 = eval "new $use_md5";
5335 $ctx1->add($i & 1 ? $passwd : $final);
5336 $ctx1->add($salt) if ($i % 3);
5337 $ctx1->add($passwd) if ($i % 7);
5338 $ctx1->add($i & 1 ? $final : $passwd);
5339 $final = $ctx1->digest();
5343 # Convert the 16-byte final string into a readable form
5345 local @final = map { ord($_) } split(//, $final);
5346 $l = ($final[ 0]<<16) + ($final[ 6]<<8) + $final[12];
5347 $rv .= &to64($l, 4);
5348 $l = ($final[ 1]<<16) + ($final[ 7]<<8) + $final[13];
5349 $rv .= &to64($l, 4);
5350 $l = ($final[ 2]<<16) + ($final[ 8]<<8) + $final[14];
5351 $rv .= &to64($l, 4);
5352 $l = ($final[ 3]<<16) + ($final[ 9]<<8) + $final[15];
5353 $rv .= &to64($l, 4);
5354 $l = ($final[ 4]<<16) + ($final[10]<<8) + $final[ 5];
5355 $rv .= &to64($l, 4);
5357 $rv .= &to64($l, 2);
5359 # Add salt if needed
5361 return $magic.$salt.'$'.$rv;
5370 local ($v, $n) = @_;
5373 $r .= $itoa64[$v & 0x3f];
5379 # read_file(file, &assoc, [&order], [lowercase])
5380 # Fill an associative array with name=value pairs from a file
5383 open(ARFILE, $_[0]) || return 0;
5386 if (!/^#/ && /^([^=]*)=(.*)$/) {
5387 $_[1]->{$_[3] ? lc($1) : $1} = $2;
5388 push(@{$_[2]}, $1) if ($_[2]);
5395 # write_file(file, array)
5396 # Write out the contents of an associative array as name=value lines
5399 local(%old, @order);
5400 &read_file($_[0], \%old, \@order);
5401 open(ARFILE, ">$_[0]");
5402 foreach $k (@order) {
5403 print ARFILE $k,"=",$_[1]->{$k},"\n" if (exists($_[1]->{$k}));
5405 foreach $k (keys %{$_[1]}) {
5406 print ARFILE $k,"=",$_[1]->{$k},"\n" if (!exists($old{$k}));
5411 # execute_ready_webmin_crons()
5412 # Find and run any cron jobs that are due, based on their last run time and
5413 # execution interval
5414 sub execute_ready_webmin_crons
5418 foreach my $cron (@webmincrons) {
5420 if (!$webmincron_last{$cron->{'id'}}) {
5421 # If not ever run before, don't run right away
5422 $webmincron_last{$cron->{'id'}} = $now;
5425 elsif ($cron->{'interval'} &&
5426 $now - $webmincron_last{$cron->{'id'}} > $cron->{'interval'}) {
5427 # Older than interval .. time to run
5430 elsif ($cron->{'mins'}) {
5431 # Check if current time matches spec, and we haven't run in the
5433 my @tm = localtime($now);
5434 if (&matches_cron($cron->{'mins'}, $tm[1]) &&
5435 &matches_cron($cron->{'hours'}, $tm[2]) &&
5436 &matches_cron($cron->{'days'}, $tm[3]) &&
5437 &matches_cron($cron->{'months'}, $tm[4]+1) &&
5438 &matches_cron($cron->{'weekdays'}, $tm[6]) &&
5439 $now - $webmincron_last{$cron->{'id'}} > 60) {
5445 print DEBUG "Running cron id=$cron->{'id'} ".
5446 "module=$cron->{'module'} func=$cron->{'func'}\n";
5447 $webmincron_last{$cron->{'id'}} = $now;
5451 # Run via a wrapper command, which we run like a CGI
5453 # Setup CGI-like environment
5454 $envtz = $ENV{"TZ"};
5455 $envuser = $ENV{"USER"};
5456 $envpath = $ENV{"PATH"};
5457 $envlang = $ENV{"LANG"};
5458 $envroot = $ENV{"SystemRoot"};
5459 $envperllib = $ENV{'PERLLIB'};
5460 foreach my $k (keys %ENV) {
5463 $ENV{"PATH"} = $envpath if ($envpath);
5464 $ENV{"TZ"} = $envtz if ($envtz);
5465 $ENV{"USER"} = $envuser if ($envuser);
5466 $ENV{"OLD_LANG"} = $envlang if ($envlang);
5467 $ENV{"SystemRoot"} = $envroot if ($envroot);
5468 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
5469 $ENV{"HOME"} = $user_homedir;
5470 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
5471 $ENV{"SERVER_ADMIN"} = $config{"email"};
5473 $ENV{"SERVER_ROOT"} = $root0;
5474 $ENV{"SERVER_REALROOT"} = $root0;
5475 $ENV{"SERVER_PORT"} = $config{'port'};
5476 $ENV{"WEBMIN_CRON"} = 1;
5477 $ENV{"DOCUMENT_ROOT"} = $root0;
5478 $ENV{"DOCUMENT_REALROOT"} = $root0;
5479 $ENV{"MINISERV_CONFIG"} = $config_file;
5480 $ENV{"HTTPS"} = "ON" if ($use_ssl);
5481 $ENV{"MINISERV_PID"} = $miniserv_main_pid;
5482 $ENV{"SCRIPT_FILENAME"} = $config{'webmincron_wrapper'};
5483 if ($ENV{"SCRIPT_FILENAME"} =~ /^\Q$root0\E(\/.*)$/) {
5484 $ENV{"SCRIPT_NAME"} = $1;
5486 $config{'webmincron_wrapper'} =~ /^(.*)\//;
5488 foreach $k (keys %config) {
5489 if ($k =~ /^env_(\S+)$/) {
5490 $ENV{$1} = $config{$k};
5494 $SIG{'CHLD'} = 'DEFAULT';
5496 # Have SOCK closed if the perl exec's something
5498 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
5501 # Run the wrapper script by evaling it
5502 $pkg = "webmincron";
5503 $0 = $config{'webmincron_wrapper'};
5505 $main_process_id = $$;
5509 do \$miniserv::config{'webmincron_wrapper'};
5513 print STDERR "Perl cron failure : $@\n";
5518 push(@childpids, $pid);
5522 # Write out file containing last run times
5523 &write_file($config{'webmincron_last'}, \%webmincron_last);
5527 # matches_cron(cron-spec, time)
5528 # Checks if some minute or hour matches some cron spec, which can be * or a list
5532 my ($spec, $tm) = @_;
5537 foreach my $s (split(/,/, $spec)) {
5539 $s =~ /^(\d+)\-(\d+)$/ && $tm >= $1 && $tm <= $2) {
5547 # read_webmin_crons()
5548 # Read all scheduled webmin cron functions and store them in the @webmincrons
5550 sub read_webmin_crons
5553 opendir(CRONS, $config{'webmincron_dir'});
5554 print DEBUG "Reading crons from $config{'webmincron_dir'}\n";
5555 foreach my $f (readdir(CRONS)) {
5556 if ($f =~ /^(\d+)\.cron$/) {
5558 &read_file("$config{'webmincron_dir'}/$f", \%cron);
5561 foreach my $n ('module', 'func') {
5563 print STDERR "Cron $1 missing $n\n";
5567 if (!$cron{'interval'} && !$cron{'mins'} && !$cron{'special'}) {
5568 print STDERR "Cron $1 missing any time spec\n";
5571 if ($cron{'special'} eq 'hourly') {
5572 # Run every hour on the hour
5574 $cron{'hours'} = '*';
5575 $cron{'days'} = '*';
5576 $cron{'months'} = '*';
5577 $cron{'weekdays'} = '*';
5579 elsif ($cron{'special'} eq 'daily') {
5580 # Run every day at midnight
5582 $cron{'hours'} = '0';
5583 $cron{'days'} = '*';
5584 $cron{'months'} = '*';
5585 $cron{'weekdays'} = '*';
5587 elsif ($cron{'special'} eq 'monthly') {
5588 # Run every month on the 1st
5590 $cron{'hours'} = '0';
5591 $cron{'days'} = '1';
5592 $cron{'months'} = '*';
5593 $cron{'weekdays'} = '*';
5595 elsif ($cron{'special'} eq 'weekly') {
5596 # Run every month on the 1st
5598 $cron{'hours'} = '0';
5599 $cron{'days'} = '*';
5600 $cron{'months'} = '*';
5601 $cron{'weekdays'} = '0';
5603 elsif ($cron{'special'} eq 'yearly' ||
5604 $cron{'special'} eq 'annually') {
5605 # Run every year on 1st january
5607 $cron{'hours'} = '0';
5608 $cron{'days'} = '1';
5609 $cron{'months'} = '1';
5610 $cron{'weekdays'} = '*';
5612 elsif ($cron{'special'}) {
5613 print STDERR "Cron $1 invalid special time $cron{'special'}\n";
5616 if ($cron{'special'}) {
5617 delete($cron{'special'});
5620 print DEBUG "adding cron id=$cron{'id'} module=$cron{'module'} func=$cron{'func'}\n";
5621 push(@webmincrons, \%cron);
5627 # Check if some address is valid IPv4, returns 1 if so.
5630 return $_[0] =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/ &&
5631 $1 >= 0 && $1 <= 255 &&
5632 $2 >= 0 && $2 <= 255 &&
5633 $3 >= 0 && $3 <= 255 &&
5634 $4 >= 0 && $4 <= 255;
5637 # Check if some IPv6 address is properly formatted, and returns 1 if so.
5638 sub check_ip6address
5640 my @blocks = split(/:/, $_[0]);
5641 return 0 if (@blocks == 0 || @blocks > 8);
5643 my $where = index($blocks[$ib],"/");
5646 my $b = substr($blocks[$ib],0,$where);
5647 $m = substr($blocks[$ib],$where+1,length($blocks[$ib])-($where+1));
5650 return 0 if ($m <0 || $m >128);
5653 foreach $b (@blocks) {
5654 return 0 if ($b ne "" && $b !~ /^[0-9a-f]{1,4}$/i);
5655 $empty++ if ($b eq "");
5657 return 0 if ($empty > 1 && !($_[0] =~ /^::/ && $empty == 2));
5661 # network_to_address(binary)
5662 # Given a network address in binary IPv4 or v4 format, return the string form
5663 sub network_to_address
5666 if (length($addr) == 4 || !$use_ipv6) {
5667 return inet_ntoa($addr);
5670 return Socket6::inet_ntop(Socket6::AF_INET6(), $addr);