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, 0);
412 # Work out the hostname for this web server
413 $host = &get_socket_name(SOCK, 0);
415 $port = $config{'port'};
416 $acptaddr = getpeername(SOCK);
419 # Work out remote and local IPs
420 (undef, $peera, undef) = &get_address_ip($acptaddr, 0);
421 (undef, $locala) = &get_socket_ip(SOCK, 0);
423 print DEBUG "main: Starting handle_request loop pid=$$\n";
424 while(&handle_request($peera, $locala, 0)) { }
425 print DEBUG "main: Done handle_request loop pid=$$\n";
430 # Build list of sockets to listen on
431 $config{'bind'} = '' if ($config{'bind'} eq '*');
432 if ($config{'bind'}) {
433 # Listening on a specific IP
434 if (&check_ip6address($config{'bind'})) {
436 $use_ipv6 || die "Cannot bind to $config{'bind'} without IPv6";
437 push(@sockets, [ inet_pton(Socket6::AF_INET6(),$config{'bind'}),
439 Socket6::PF_INET6() ]);
443 push(@sockets, [ inet_aton($config{'bind'}),
449 # Listening on all IPs
450 push(@sockets, [ INADDR_ANY, $config{'port'}, PF_INET() ]);
453 push(@sockets, [ in6addr_any(), $config{'port'},
454 Socket6::PF_INET6() ]);
457 foreach $s (split(/\s+/, $config{'sockets'})) {
458 if ($s =~ /^(\d+)$/) {
459 # Just listen on another port on the main IP
460 push(@sockets, [ $sockets[0]->[0], $s, $sockets[0]->[2] ]);
461 if ($use_ipv6 && !$config{'bind'}) {
462 # Also listen on that port on the main IPv6 address
463 push(@sockets, [ $sockets[1]->[0], $s,
467 elsif ($s =~ /^\*:(\d+)$/) {
468 # Listening on all IPs on some port
469 push(@sockets, [ INADDR_ANY, $config{'port'},
472 push(@sockets, [ in6addr_any(), $config{'port'},
473 Socket6::PF_INET6() ]);
476 elsif ($s =~ /^(\S+):(\d+)$/) {
477 # Listen on a specific port and IP
478 my ($ip, $port) = ($1, $2);
479 if (&check_ip6address($ip)) {
480 $use_ipv6 || die "Cannot bind to $ip without IPv6";
481 push(@sockets, [ inet_pton(Socket6::AF_INET6(),
483 $port, Socket6::PF_INET6() ]);
486 push(@sockets, [ inet_aton($ip), $port,
490 elsif ($s =~ /^([0-9\.]+):\*$/ || $s =~ /^([0-9\.]+)$/) {
491 # Listen on the main port on another IPv4 address
492 push(@sockets, [ inet_aton($1), $sockets[0]->[1],
495 elsif (($s =~ /^([0-9a-f\:]+):\*$/ || $s =~ /^([0-9a-f\:]+)$/) &&
497 # Listen on the main port on another IPv6 address
498 push(@sockets, [ inet_pton(Socket6::AF_INET6(), $1),
500 Socket6::PF_INET6() ]);
504 # Open all the sockets
505 $proto = getprotobyname('tcp');
507 $tried_inaddr_any = 0;
508 for($i=0; $i<@sockets; $i++) {
510 socket($fh, $sockets[$i]->[2], SOCK_STREAM, $proto) ||
511 die "Failed to open socket family $sockets[$i]->[2] : $!";
512 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
513 if ($sockets[$i]->[2] eq PF_INET()) {
514 $pack = pack_sockaddr_in($sockets[$i]->[1], $sockets[$i]->[0]);
517 $pack = pack_sockaddr_in6($sockets[$i]->[1], $sockets[$i]->[0]);
518 setsockopt($fh, 41, 26, pack("l", 1)); # IPv6 only
520 for($j=0; $j<5; $j++) {
521 last if (bind($fh, $pack));
525 # All attempts failed .. give up
526 if ($sockets[$i]->[0] eq INADDR_ANY ||
527 $use_ipv6 && $sockets[$i]->[0] eq in6addr_any()) {
529 "Failed to bind to port $sockets[$i]->[1] : $!");
530 $tried_inaddr_any = 1;
533 $ip = &network_to_address($sockets[$i]->[0]);
535 "Failed to bind to IP $ip port ".
536 "$sockets[$i]->[1] : $!");
540 listen($fh, SOMAXCONN);
541 push(@socketfhs, $fh);
542 $ipv6fhs{$fh} = $sockets[$i]->[2] eq PF_INET() ? 0 : 1;
545 foreach $se (@sockerrs) {
546 print STDERR $se,"\n";
549 # If all binds failed, try binding to any address
550 if (!@socketfhs && !$tried_inaddr_any) {
551 print STDERR "Falling back to listening on any address\n";
553 socket($fh, PF_INET(), SOCK_STREAM, $proto) ||
554 die "Failed to open socket : $!";
555 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
556 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(
858 # Close the file handle for the session DBM
859 dbmclose(%sessiondb);
861 # close useless pipes
864 close($PASSINr); close($PASSOUTw);
866 &close_all_sockets();
870 "main: Starting handle_request loop pid=$$\n";
871 while(&handle_request($peera, $locala,
873 # Loop until keepalive stops
876 "main: Done handle_request loop pid=$$\n";
879 close($PASSINw); close($PASSOUTw);
882 push(@childpids, $handpid);
884 close($PASSINw); close($PASSOUTr);
885 push(@passin, $PASSINr);
886 push(@passout, $PASSOUTw);
893 if ($config{'listen'} && vec($rmask, fileno(LISTEN), 1)) {
894 # Got UDP packet from another webmin server
896 local $from = recv(LISTEN, $rcvbuf, 1024, 0);
898 local $fromip = inet_ntoa((unpack_sockaddr_in($from))[1]);
899 local $toip = inet_ntoa((unpack_sockaddr_in(
900 getsockname(LISTEN)))[1]);
901 if ((!@deny || !&ip_match($fromip, $toip, @deny)) &&
902 (!@allow || &ip_match($fromip, $toip, @allow))) {
903 local $listenhost = &get_socket_name(LISTEN, 0);
904 send(LISTEN, "$listenhost:$config{'port'}:".
905 ($use_ssl || $config{'inetd_ssl'} ? 1 : 0).":".
906 ($config{'listenhost'} ?
907 &get_system_hostname() : ""),
913 # check for session, password-timeout and PAM messages from subprocesses
914 for($i=0; $i<@passin; $i++) {
915 if (vec($rmask, fileno($passin[$i]), 1)) {
916 # this sub-process is asking about a password
917 local $infd = $passin[$i];
918 local $outfd = $passout[$i];
919 #local $inline = <$infd>;
920 local $inline = &sysread_line($infd);
922 print DEBUG "main: inline $inline";
925 print DEBUG "main: inline EOF\n";
927 if ($inline =~ /^delay\s+(\S+)\s+(\S+)\s+(\d+)/) {
928 # Got a delay request from a subprocess.. for
929 # valid logins, there is no delay (to prevent
930 # denial of service attacks), but for invalid
931 # logins the delay increases with each failed
934 # login OK.. no delay
935 print $outfd "0 0\n";
936 $wasblocked = $hostfail{$2} ||
941 &write_blocked_file();
950 # add the host to the block list,
952 if ($config{'blockhost_failures'} &&
954 $config{'blockhost_failures'}) {
956 $blockhosttime{$2} = $time_now;
959 local $logtext = "Security alert: Host $2 blocked after $config{'blockhost_failures'} failed logins for user $1";
965 # add the user to the user block list,
967 if ($config{'blockuser_failures'} &&
969 $config{'blockuser_failures'}) {
970 push(@denyusers, $1);
971 $blockusertime{$1} = $time_now;
974 local $logtext = "Security alert: User $1 blocked after $config{'blockuser_failures'} failed logins";
980 # Lock out the user's password, if enabled
981 if ($config{'blocklock'} &&
983 $config{'blockuser_failures'}) {
984 my $lk = &lock_user_password($1);
987 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";
994 $dl = $userdlay{$1} -
995 int(($time_now - $userlast{$1})/50);
996 $dl = $dl < 0 ? 0 : $dl+1;
997 print $outfd "$dl $blocked\n";
1000 # Write out blocked status file
1002 &write_blocked_file();
1005 $userlast{$1} = $time_now;
1007 elsif ($inline =~ /^verify\s+(\S+)\s+(\S+)/) {
1008 # Verifying a session ID
1009 local $session_id = $1;
1010 local $notimeout = $2;
1011 local $skey = $sessiondb{$session_id} ?
1013 &hash_session_id($session_id);
1014 if (!defined($sessiondb{$skey})) {
1015 # Session doesn't exist
1016 print $outfd "0 0\n";
1019 local ($user, $ltime) =
1020 split(/\s+/, $sessiondb{$skey});
1021 local $lot = &get_logout_time($user, $session_id);
1023 $time_now - $ltime > $lot*60 &&
1025 # Session has timed out
1026 print $outfd "1 ",$time_now - $ltime,"\n";
1027 #delete($sessiondb{$skey});
1031 print $outfd "2 $user\n";
1033 $time_now - $ltime >
1035 $sessiondb{$skey} = "$user $time_now";
1040 elsif ($inline =~ /^new\s+(\S+)\s+(\S+)\s+(\S+)/) {
1041 # Creating a new session
1042 local $session_id = $1;
1045 $sessiondb{&hash_session_id($session_id)} =
1046 "$user $time_now $ip";
1048 elsif ($inline =~ /^delete\s+(\S+)/) {
1049 # Logging out a session
1050 local $session_id = $1;
1051 local $skey = $sessiondb{$session_id} ?
1053 &hash_session_id($session_id);
1054 local @sdb = split(/\s+/, $sessiondb{$skey});
1055 print $outfd $sdb[0],"\n";
1056 delete($sessiondb{$skey});
1058 elsif ($inline =~ /^pamstart\s+(\S+)\s+(\S+)\s+(.*)/) {
1059 # Starting a new PAM conversation
1060 local ($cid, $host, $user) = ($1, $2, $3);
1062 # Does this user even need PAM?
1063 local ($realuser, $canlogin) =
1064 &can_user_login($user, undef, $host);
1066 if ($canlogin == 0) {
1067 # Cannot even login!
1068 print $outfd "0 Invalid username\n";
1070 elsif ($canlogin != 2) {
1071 # Not using PAM .. so just ask for
1073 $conv = { 'user' => $realuser,
1078 print $outfd "3 Password\n";
1081 # Start the PAM conversation
1082 # sub-process, and get a question
1083 $conv = { 'user' => $realuser,
1087 local ($PAMINr, $PAMINw, $PAMOUTr,
1088 $PAMOUTw) = &allocate_pipes();
1089 local $pampid = fork();
1091 close($PAMOUTr); close($PAMINw);
1092 &pam_conversation_process(
1096 close($PAMOUTw); close($PAMINr);
1097 $conv->{'pid'} = $pampid;
1098 $conv->{'PAMOUTr'} = $PAMOUTr;
1099 $conv->{'PAMINw'} = $PAMINw;
1100 push(@childpids, $pampid);
1102 # Get the first PAM question
1103 local $pok = &recv_pam_question(
1106 &end_pam_conversation($conv);
1110 $conversations{$cid} = $conv if ($conv);
1112 elsif ($inline =~ /^pamanswer\s+(\S+)\s+(.*)/) {
1113 # A response to a PAM question
1114 local ($cid, $answer) = ($1, $2);
1115 local $conv = $conversations{$cid};
1117 # No such conversation?
1118 print $outfd "0 Bad login session\n";
1120 elsif ($conv->{'pid'}) {
1121 # Send the PAM response and get
1123 &send_pam_answer($conv, $answer);
1124 local $pok = &recv_pam_question($conv, $outfd);
1126 &end_pam_conversation($conv);
1130 # This must be the password .. try it
1131 # and send back the results
1132 local ($vu, $expired, $nonexist) =
1133 &validate_user($conv->{'user'},
1136 local $ok = $vu ? 1 : 0;
1137 print $outfd "2 $conv->{'user'} $ok $expired $notexist\n";
1138 &end_pam_conversation($conv);
1141 elsif ($inline =~ /^writesudo\s+(\S+)\s+(\d+)/) {
1142 # Store the fact that some user can sudo to root
1143 local ($user, $ok) = ($1, $2);
1144 $sudocache{$user} = $ok." ".time();
1146 elsif ($inline =~ /^readsudo\s+(\S+)/) {
1147 # Query the user sudo cache (valid for 1 minute)
1149 local ($ok, $last) =
1150 split(/\s+/, $sudocache{$user});
1151 if ($last < time()-60) {
1156 # Tell client OK or not
1157 print $outfd "$ok\n";
1160 elsif ($inline =~ /\S/) {
1161 # Unknown line from pipe?
1162 print DEBUG "main: Unknown line from pipe $inline\n";
1163 print STDERR "Unknown line from pipe $inline\n";
1167 close($infd); close($outfd);
1168 $passin[$i] = $passout[$i] = undef;
1172 @passin = grep { defined($_) } @passin;
1173 @passout = grep { defined($_) } @passout;
1176 # handle_request(remoteaddress, localaddress, ipv6-flag)
1177 # Where the real work is done
1180 local ($acptip, $localip, $ipv6) = @_;
1181 print DEBUG "handle_request: from $acptip to $localip ipv6=$ipv6\n";
1182 if ($config{'loghost'}) {
1183 $acpthost = &to_hostname($acptip);
1184 $acpthost = $acptip if (!$acpthost);
1187 $acpthost = $acptip;
1189 $datestr = &http_date(time());
1191 $ok_message = "Document follows";
1192 $logged_code = undef;
1193 $reqline = $request_uri = $page = undef;
1197 # check address against access list
1198 if (@deny && &ip_match($acptip, $localip, @deny) ||
1199 @allow && !&ip_match($acptip, $localip, @allow)) {
1200 &http_error(403, "Access denied for $acptip");
1205 # Check address with TCP-wrappers
1206 if (!hosts_ctl($config{'pam'}, STRING_UNKNOWN,
1207 $acptip, STRING_UNKNOWN)) {
1208 &http_error(403, "Access denied for $acptip by TCP wrappers");
1212 print DEBUG "handle_request: passed IP checks\n";
1214 # Compute a timeout for the start of headers, based on the number of
1215 # child processes. As this increases, we use a shorter timeout to avoid
1216 # an attacker overloading the system.
1217 local $header_timeout = 60 + ($config{'maxconns'} - @childpids) * 10;
1219 # Wait at most 60 secs for start of headers for initial requests, or
1220 # 10 minutes for kept-alive connections
1222 vec($rmask, fileno(SOCK), 1) = 1;
1223 local $to = $checked_timeout ? 10*60 : $header_timeout;
1224 local $sel = select($rmask, undef, undef, $to);
1226 if ($checked_timeout) {
1227 print DEBUG "handle_request: exiting due to timeout of $to\n";
1231 &http_error(400, "Timeout",
1232 "Waited for that $to seconds for start of headers");
1236 print DEBUG "handle_request: passed timeout check\n";
1238 # Read the HTTP request and headers
1239 local $origreqline = &read_line();
1240 ($reqline = $origreqline) =~ s/\r|\n//g;
1241 $method = $page = $request_uri = undef;
1242 print DEBUG "handle_request reqline=$reqline\n";
1243 if (!$reqline && (!$use_ssl || $checked_timeout > 1)) {
1244 # An empty request .. just close the connection
1245 print DEBUG "handle_request: rejecting empty request\n";
1248 elsif ($reqline !~ /^(\S+)\s+(.*)\s+HTTP\/1\..$/) {
1249 print DEBUG "handle_request: invalid reqline=$reqline\n";
1251 # This could be an http request when it should be https
1253 local $url = $config{'musthost'} ?
1254 "https://$config{'musthost'}:$port/" :
1255 "https://$host:$port/";
1256 if ($config{'ssl_redirect'}) {
1257 # Just re-direct to the correct URL
1258 sleep(1); # Give browser a change to finish
1259 # sending its request
1260 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1261 &write_data("Date: $datestr\r\n");
1262 &write_data("Server: $config{'server'}\r\n");
1263 &write_data("Location: $url\r\n");
1264 &write_keep_alive(0);
1265 &write_data("\r\n");
1269 # Tell user the correct URL
1270 &http_error(200, "Bad Request", "This web server is running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1273 elsif (ord(substr($reqline, 0, 1)) == 128 && !$use_ssl) {
1274 # This could be an https request when it should be http ..
1275 # need to fake a HTTP response
1278 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
1279 eval "Net::SSLeay::load_error_strings()";
1280 $ssl_ctx = Net::SSLeay::CTX_new();
1281 Net::SSLeay::CTX_use_RSAPrivateKey_file(
1282 $ssl_ctx, $config{'keyfile'},
1283 &Net::SSLeay::FILETYPE_PEM);
1284 Net::SSLeay::CTX_use_certificate_file(
1286 $config{'certfile'} || $config{'keyfile'},
1287 &Net::SSLeay::FILETYPE_PEM);
1288 $ssl_con = Net::SSLeay::new($ssl_ctx);
1292 select(SSLw); $| = 1; select(STDOUT);
1293 print SSLw $origreqline;
1295 while(sysread(SOCK, $buf, 1) > 0) {
1302 Net::SSLeay::set_wfd($ssl_con, fileno(SOCK));
1303 Net::SSLeay::set_rfd($ssl_con, fileno(SSLr));
1304 Net::SSLeay::accept($ssl_con) || die "accept() failed";
1306 local $url = $config{'musthost'} ?
1307 "https://$config{'musthost'}:$port/" :
1308 "https://$host:$port/";
1309 if ($config{'ssl_redirect'}) {
1310 # Just re-direct to the correct URL
1311 sleep(1); # Give browser a change to
1312 # finish sending its request
1313 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1314 &write_data("Date: $datestr\r\n");
1315 &write_data("Server: $config{'server'}\r\n");
1316 &write_data("Location: $url\r\n");
1317 &write_keep_alive(0);
1318 &write_data("\r\n");
1322 # Tell user the correct URL
1323 &http_error(200, "Bad Request", "This web server is not running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1327 &http_error(400, "Bad Request");
1331 &http_error(400, "Bad Request");
1335 $request_uri = $page = $2;
1339 ($headline = &read_line()) =~ s/\r|\n//g;
1340 last if ($headline eq "");
1341 print DEBUG "handle_request: got headline $headline\n";
1342 if ($headline =~ /^(\S+):\s*(.*)$/) {
1343 $header{$lastheader = lc($1)} = $2;
1345 elsif ($headline =~ /^\s+(.*)$/) {
1346 $header{$lastheader} .= $headline;
1349 &http_error(400, "Bad Header $headline");
1352 if (defined($header{'host'})) {
1353 if ($header{'host'} =~ /^([^:]+):([0-9]+)$/) {
1354 ($host, $port) = ($1, $2);
1357 $host = $header{'host'};
1359 if ($config{'musthost'} && $host ne $config{'musthost'}) {
1360 # Disallowed hostname used
1361 &http_error(400, "Invalid HTTP hostname");
1365 if ($page =~ /^([^\?]+)\?(.*)$/) {
1366 # There is some query string information
1369 print DEBUG "handle_request: querystring=$querystring\n";
1370 if ($querystring !~ /=/) {
1371 $queryargs = $querystring;
1372 $queryargs =~ s/\+/ /g;
1373 $queryargs =~ s/%(..)/pack("c",hex($1))/ge;
1377 # Parse query-string parameters
1378 local @in = split(/\&/, $querystring);
1380 local ($k, $v) = split(/=/, $i, 2);
1381 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1382 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1387 $posted_data = undef;
1388 if ($method eq 'POST' &&
1389 $header{'content-type'} eq 'application/x-www-form-urlencoded') {
1390 # Read in posted query string information, up the configured maximum
1391 # post request length
1392 $clen = $header{"content-length"};
1393 $clen_read = $clen > $config{'max_post'} ? $config{'max_post'} : $clen;
1394 while(length($posted_data) < $clen_read) {
1395 $buf = &read_data($clen_read - length($posted_data));
1396 if (!length($buf)) {
1397 &http_error(500, "Failed to read POST request");
1399 chomp($posted_data);
1400 $posted_data =~ s/\015$//mg;
1401 $posted_data .= $buf;
1403 print DEBUG "clen_read=$clen_read clen=$clen posted_data=",length($posted_data),"\n";
1404 if ($clen_read != $clen && length($posted_data) > $clen) {
1405 # If the client sent more data than we asked for, chop the
1407 $posted_data = substr($posted_data, 0, $clen);
1409 if (length($posted_data) > $clen) {
1410 # When the client sent too much, delay so that it gets headers
1413 if ($header{'user-agent'} =~ /MSIE/ &&
1414 $header{'user-agent'} !~ /Opera/i) {
1415 # MSIE includes an extra newline in the data
1416 $posted_data =~ s/\r|\n//g;
1418 local @in = split(/\&/, $posted_data);
1420 local ($k, $v) = split(/=/, $i, 2);
1422 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1423 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1426 print DEBUG "handle_request: posted_data=$posted_data\n";
1429 # replace %XX sequences in page
1430 $page =~ s/%(..)/pack("c",hex($1))/ge;
1432 # Check if the browser's user agent indicates a mobile device
1433 $mobile_device = &is_mobile_useragent($header{'user-agent'});
1435 # Check if Host: header is for a mobile URL
1436 foreach my $m (@mobile_prefixes) {
1437 if ($header{'host'} =~ /^\Q$m\E/i) {
1442 # check for the logout flag file, and if existant deny authentication
1443 if ($config{'logout'} && -r $config{'logout'}.$in{'miniserv_logout_id'}) {
1444 print DEBUG "handle_request: logout flag set\n";
1445 $deny_authentication++;
1446 open(LOGOUT, $config{'logout'}.$in{'miniserv_logout_id'});
1447 chop($count = <LOGOUT>);
1451 open(LOGOUT, ">$config{'logout'}$in{'miniserv_logout_id'}");
1452 print LOGOUT "$count\n";
1456 unlink($config{'logout'}.$in{'miniserv_logout_id'});
1460 # check for any redirect for the requested URL
1461 foreach my $pfx (@strip_prefix) {
1462 my $l = length($pfx);
1463 if(length($page) >= $l &&
1464 substr($page,0,$l) eq $pfx) {
1465 $page=substr($page,$l);
1469 $simple = &simplify_path($page, $bogus);
1471 $rpath .= "&".$querystring if (defined($querystring));
1472 $redir = $redirect{$rpath};
1473 if (defined($redir)) {
1474 print DEBUG "handle_request: redir=$redir\n";
1475 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1476 &write_data("Date: $datestr\r\n");
1477 &write_data("Server: $config{'server'}\r\n");
1478 local $ssl = $use_ssl || $config{'inetd_ssl'};
1479 $portstr = $port == 80 && !$ssl ? "" :
1480 $port == 443 && $ssl ? "" : ":$port";
1481 $prot = $ssl ? "https" : "http";
1482 &write_data("Location: $prot://$host$portstr$redir\r\n");
1483 &write_keep_alive(0);
1484 &write_data("\r\n");
1488 # Check for a DAV request
1490 foreach my $d (@davpaths) {
1491 if ($simple eq $d || $simple =~ /^\Q$d\E\//) {
1496 if (!$davpath && ($method eq "SEARCH" || $method eq "PUT")) {
1497 &http_error(400, "Bad Request method $method");
1500 # Check for password if needed
1501 if ($config{'userfile'}) {
1502 print DEBUG "handle_request: Need authentication\n";
1506 # Session authentication is never used for connections by
1507 # another webmin server, or for specified pages, or for DAV, or XMLRPC,
1508 # or mobile browsers if requested.
1509 if ($header{'user-agent'} =~ /webmin/i ||
1510 $header{'user-agent'} =~ /$config{'agents_nosession'}/i ||
1511 $sessiononly{$simple} || $davpath ||
1512 $simple eq "/xmlrpc.cgi" ||
1513 $acptip eq $config{'host_nosession'} ||
1514 $mobile_device && $config{'mobile_nosession'}) {
1515 print DEBUG "handle_request: Forcing HTTP authentication\n";
1516 $config{'session'} = 0;
1519 # Check for SSL authentication
1520 if ($use_ssl && $verified_client) {
1521 $peername = Net::SSLeay::X509_NAME_oneline(
1522 Net::SSLeay::X509_get_subject_name(
1523 Net::SSLeay::get_peer_certificate(
1525 $u = &find_user_by_cert($peername);
1530 if ($use_syslog && !$validated) {
1531 syslog("crit", "%s",
1532 "Unknown SSL certificate $peername");
1536 if (!$validated && !$deny_authentication) {
1537 # check for IP-based authentication
1539 foreach $a (keys %ipaccess) {
1540 if ($acptip eq $a) {
1541 # It does! Auth as the user
1543 $baseauthuser = $authuser =
1549 # Check for normal HTTP authentication
1550 if (!$validated && !$deny_authentication && !$config{'session'} &&
1551 $header{authorization} =~ /^basic\s+(\S+)$/i) {
1552 # authorization given..
1553 ($authuser, $authpass) = split(/:/, &b64decode($1), 2);
1554 print DEBUG "handle_request: doing basic auth check authuser=$authuser authpass=$authpass\n";
1555 local ($vu, $expired, $nonexist) =
1556 &validate_user($authuser, $authpass, $host);
1557 print DEBUG "handle_request: vu=$vu expired=$expired nonexist=$nonexist\n";
1558 if ($vu && (!$expired || $config{'passwd_mode'} == 1)) {
1565 if ($use_syslog && !$validated) {
1566 syslog("crit", "%s",
1567 ($nonexist ? "Non-existent" :
1568 $expired ? "Expired" : "Invalid").
1569 " login as $authuser from $acpthost");
1571 if ($authuser =~ /\r|\n|\s/) {
1572 &http_error(500, "Invalid username",
1573 "Username contains invalid characters");
1575 if ($authpass =~ /\r|\n/) {
1576 &http_error(500, "Invalid password",
1577 "Password contains invalid characters");
1580 if ($config{'passdelay'} && !$config{'inetd'} && $authuser) {
1581 # check with main process for delay
1582 print DEBUG "handle_request: about to ask for password delay\n";
1583 print $PASSINw "delay $authuser $acptip $validated\n";
1584 <$PASSOUTr> =~ /(\d+) (\d+)/;
1586 print DEBUG "handle_request: password delay $1 $2\n";
1591 # Check for a visit to the special session login page
1592 if ($config{'session'} && !$deny_authentication &&
1593 $page eq $config{'session_login'}) {
1594 if ($in{'logout'} && $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1595 # Logout clicked .. remove the session
1597 print $PASSINw "delete $sid\n";
1598 local $louser = <$PASSOUTr>;
1601 $already_session_id = undef;
1602 $authuser = $baseauthuser = undef;
1605 syslog("info", "%s", "Logout by $louser from $acpthost");
1607 &run_logout_script($louser, $sid,
1609 &write_logout_utmp($louser, $actphost);
1614 if ($in{'user'} =~ /\r|\n|\s/) {
1615 &http_error(500, "Invalid username",
1616 "Username contains invalid characters");
1618 if ($in{'pass'} =~ /\r|\n/) {
1619 &http_error(500, "Invalid password",
1620 "Password contains invalid characters");
1623 local ($vu, $expired, $nonexist) =
1624 &validate_user($in{'user'}, $in{'pass'}, $host);
1625 local $hrv = &handle_login(
1626 $vu || $in{'user'}, $vu ? 1 : 0,
1627 $expired, $nonexist, $in{'pass'},
1628 $in{'notestingcookie'});
1629 return $hrv if (defined($hrv));
1633 # Check for a visit to the special PAM login page
1634 if ($config{'session'} && !$deny_authentication &&
1635 $use_pam && $config{'pam_conv'} && $page eq $config{'pam_login'} &&
1637 # A question has been entered .. submit it to the main process
1638 print DEBUG "handle_request: Got call to $page ($in{'cid'})\n";
1639 print DEBUG "handle_request: For PAM, authuser=$authuser\n";
1640 if ($in{'answer'} =~ /\r|\n/ || $in{'cid'} =~ /\r|\n|\s/) {
1641 &http_error(500, "Invalid response",
1642 "Response contains invalid characters");
1646 # Start of a new conversation - answer must be username
1647 $cid = &generate_random_id($in{'answer'});
1648 print $PASSINw "pamstart $cid $host $in{'answer'}\n";
1651 # A response to a previous question
1653 print $PASSINw "pamanswer $cid $in{'answer'}\n";
1656 # Read back the response, and the next question (if any)
1657 local $line = <$PASSOUTr>;
1658 $line =~ s/\r|\n//g;
1659 local ($rv, $question) = split(/\s+/, $line, 2);
1662 local $hrv = &handle_login(
1663 !$in{'cid'} && $in{'answer'} ? $in{'answer'}
1666 return $hrv if (defined($hrv));
1668 elsif ($rv == 1 || $rv == 3) {
1669 # Another question .. force use of PAM CGI
1672 $querystring .= "&cid=$cid&question=".
1674 $querystring .= "&password=1" if ($rv == 3);
1676 $page = $config{'pam_login'};
1677 $miniserv_internal = 1;
1681 # Got back a final ok or failure
1682 local ($user, $ok, $expired, $nonexist) =
1683 split(/\s+/, $question);
1684 local $hrv = &handle_login(
1685 $user, $ok, $expired, $nonexist, undef,
1686 $in{'notestingcookie'});
1687 return $hrv if (defined($hrv));
1690 # A message from PAM .. tell the user
1693 $querystring .= "&cid=$cid&message=".
1696 $page = $config{'pam_login'};
1697 $miniserv_internal = 1;
1702 # Check for a visit to the special password change page
1703 if ($config{'session'} && !$deny_authentication &&
1704 $page eq $config{'password_change'} && !$validated) {
1705 # Just let this slide ..
1707 $miniserv_internal = 3;
1710 # Check for an existing session
1711 if ($config{'session'} && !$validated) {
1712 if ($already_session_id) {
1713 $session_id = $already_session_id;
1714 $authuser = $already_authuser;
1717 elsif (!$deny_authentication &&
1718 $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1719 # Try all session cookies
1720 local $cookie = $header{'cookie'};
1721 while($cookie =~ s/(^|\s)$sidname=([a-f0-9]+)//) {
1724 $in{'webmin_notimeout'} ? 1 : 0;
1725 print $PASSINw "verify $session_id $notimeout\n";
1726 <$PASSOUTr> =~ /(\d+)\s+(\S+)/;
1728 # Valid session continuation
1731 $already_authuser = $authuser;
1740 # Invalid session ID .. don't set
1747 # Check for local authentication
1748 if ($localauth_user && !$header{'x-forwarded-for'} && !$header{'via'}) {
1749 my $luser = &get_user_details($localauth_user);
1751 # Local user exists in webmin users file
1753 $authuser = $localauth_user;
1756 # Check if local user is allowed by unixauth
1757 local @can = &can_user_login($localauth_user,
1761 $authuser = $localauth_user;
1764 $localauth_user = undef;
1770 # Check if this path allows anonymous access
1772 foreach $a (keys %anonymous) {
1773 if (substr($simple, 0, length($a)) eq $a) {
1774 # It does! Auth as the user, if IP access
1775 # control allows him.
1776 if (&check_user_ip($anonymous{$a}) &&
1777 &check_user_time($anonymous{$a})) {
1779 $baseauthuser = $authuser =
1787 # Check if this path allows unauthenticated access
1788 local ($u, $unauth);
1789 foreach $u (@unauth) {
1790 $unauth++ if ($simple =~ /$u/);
1792 if (!$bogus && $unauth) {
1793 # Unauthenticated directory or file request - approve it
1795 $baseauthuser = $authuser = undef;
1800 if ($blocked == 0) {
1801 # No password given.. ask
1802 if ($config{'pam_conv'} && $use_pam) {
1803 # Force CGI for PAM question, starting with
1804 # the username which is always needed
1807 $querystring .= "&initial=1&question=".
1808 &urlize("Username");
1809 $querystring .= "&failed=$failed_user" if ($failed_user);
1810 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1812 $page = $config{'pam_login'};
1813 $miniserv_internal = 1;
1816 elsif ($config{'session'}) {
1817 # Force CGI for session login
1820 $querystring .= "&logout=1&page=/";
1823 # Re-direct to current module only
1824 local $rpage = $request_uri;
1825 if (!$config{'loginkeeppage'}) {
1826 $rpage =~ s/\?.*$//;
1827 $rpage =~ s/[^\/]+$//
1829 $querystring = "page=".&urlize($rpage);
1832 $querystring .= "&failed=$failed_user" if ($failed_user);
1833 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1835 $page = $config{'session_login'};
1836 $miniserv_internal = 1;
1840 # Ask for login with HTTP authentication
1841 &write_data("HTTP/1.0 401 Unauthorized\r\n");
1842 &write_data("Date: $datestr\r\n");
1843 &write_data("Server: $config{'server'}\r\n");
1844 &write_data("WWW-authenticate: Basic ".
1845 "realm=\"$config{'realm'}\"\r\n");
1846 &write_keep_alive(0);
1847 &write_data("Content-type: text/html\r\n");
1848 &write_data("\r\n");
1849 &reset_byte_count();
1850 &write_data("<html>\n");
1851 &write_data("<head><title>Unauthorized</title></head>\n");
1852 &write_data("<body><h1>Unauthorized</h1>\n");
1853 &write_data("A password is required to access this\n");
1854 &write_data("web server. Please try again. <p>\n");
1855 &write_data("</body></html>\n");
1856 &log_request($acpthost, undef, $reqline, 401, &byte_count());
1860 elsif ($blocked == 1) {
1861 # when the host has been blocked, give it an error
1862 &http_error(403, "Access denied for $acptip. The host ".
1863 "has been blocked because of too ".
1864 "many authentication failures.");
1866 elsif ($blocked == 2) {
1867 # when the user has been blocked, give it an error
1868 &http_error(403, "Access denied. The user ".
1869 "has been blocked because of too ".
1870 "many authentication failures.");
1874 # Get the real Webmin username
1875 local @can = &can_user_login($authuser, undef, $host);
1876 $baseauthuser = $can[3] || $authuser;
1878 if ($config{'remoteuser'} && !$< && $validated) {
1879 # Switch to the UID of the remote user (if he exists)
1880 local @u = getpwnam($authuser);
1881 if (@u && $< != $u[2]) {
1882 $( = $u[3]; $) = "$u[3] $u[3]";
1883 ($>, $<) = ($u[2], $u[2]);
1886 &http_error(500, "Unix user $authuser does not exist");
1892 # Check per-user IP access control
1893 if (!&check_user_ip($baseauthuser)) {
1894 &http_error(403, "Access denied for $acptip for $baseauthuser");
1898 # Check per-user allowed times
1899 if (!&check_user_time($baseauthuser)) {
1900 &http_error(403, "Access denied at the current time");
1904 $uinfo = &get_user_details($baseauthuser);
1906 # Validate the path, and convert to canonical form
1908 $simple = &simplify_path($page, $bogus);
1909 print DEBUG "handle_request: page=$page simple=$simple\n";
1911 &http_error(400, "Invalid path");
1914 # Check for a DAV request
1916 return &handle_dav_request($davpath);
1919 # Work out the active theme(s)
1920 local $preroots = $mobile_device && defined($config{'mobile_preroot'}) ?
1921 $config{'mobile_preroot'} :
1922 $authuser && defined($config{'preroot_'.$authuser}) ?
1923 $config{'preroot_'.$authuser} :
1924 $uinfo && defined($uinfo->{'preroot'}) ?
1925 $uinfo->{'preroot'} :
1927 local @preroots = reverse(split(/\s+/, $preroots));
1929 # Canonicalize the directories
1930 foreach my $preroot (@preroots) {
1931 # Always under the current webmin root
1932 $preroot =~ s/^.*\///g;
1933 $preroot = $roots[0].'/'.$preroot;
1936 # Look in the theme root directories first
1937 local ($full, @stfull);
1939 foreach my $preroot (@preroots) {
1942 $full = $preroot.$sofar;
1943 $scriptname = $simple;
1944 foreach $b (split(/\//, $simple)) {
1945 if ($b ne "") { $sofar .= "/$b"; }
1946 $full = $preroot.$sofar;
1947 @stfull = stat($full);
1948 if (!@stfull) { undef($full); last; }
1950 # Check if this is a directory
1952 # It is.. go on parsing
1960 # Check if this is a CGI program
1961 if (&get_type($full) eq "internal/cgi") {
1962 $pathinfo = substr($simple, length($sofar));
1963 $pathinfo .= "/" if ($page =~ /\/$/);
1964 $scriptname = $sofar;
1969 # Don't stop at a directory unless this is the last theme, which
1970 # is the 'real' one that provides the .cgi scripts
1971 if ($is_directory && $preroot ne $preroots[$#preroots]) {
1978 $cgi_pwd = $roots[0];
1980 elsif ($is_directory) {
1981 $cgi_pwd = "$roots[0]$sofar";
1984 "$roots[0]$sofar" =~ /^(.*\/)[^\/]+$/;
1987 $foundroot = $preroot;
1988 if ($is_directory) {
1989 # Check for index files in the directory
1991 foreach $idx (split(/\s+/, $config{"index_docs"})) {
1992 $idxfull = "$full/$idx";
1993 local @stidxfull = stat($idxfull);
1994 if (-r _ && !-d _) {
1996 @stfull = @stidxfull;
1999 if ($scriptname ne "/");
2004 @stfull = stat($full) if (!$foundidx);
2007 last if ($foundroot);
2009 print DEBUG "handle_request: initial full=$full\n";
2011 # Look in the real root directories, stopping when we find a file or directory
2012 if (!$full || $is_directory) {
2013 ROOT: foreach $root (@roots) {
2015 $full = $root.$sofar;
2016 $scriptname = $simple;
2017 foreach $b ($simple eq "/" ? ( "" ) : split(/\//, $simple)) {
2018 if ($b ne "") { $sofar .= "/$b"; }
2019 $full = $root.$sofar;
2020 @stfull = stat($full);
2025 # Check if this is a directory
2027 # It is.. go on parsing
2031 # Check if this is a CGI program
2032 if (&get_type($full) eq "internal/cgi") {
2033 $pathinfo = substr($simple, length($sofar));
2034 $pathinfo .= "/" if ($page =~ /\/$/);
2035 $scriptname = $sofar;
2040 # Run CGI in the same directory as whatever file
2042 $full =~ /^(.*\/)[^\/]+$/; $cgi_pwd = $1;
2051 if (!@stfull) { &http_error(404, "File not found"); }
2053 print DEBUG "handle_request: full=$full\n";
2054 @stfull = stat($full) if (!@stfull);
2056 # check filename against denyfile regexp
2057 local $denyfile = $config{'denyfile'};
2058 if ($denyfile && $full =~ /$denyfile/) {
2059 &http_error(403, "Access denied to $page");
2063 # Reached the end of the path OK.. see what we've got
2065 # See if the URL ends with a / as it should
2066 print DEBUG "handle_request: found a directory\n";
2067 if ($page !~ /\/$/) {
2068 # It doesn't.. redirect
2069 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2070 $ssl = $use_ssl || $config{'inetd_ssl'};
2071 $portstr = $port == 80 && !$ssl ? "" :
2072 $port == 443 && $ssl ? "" : ":$port";
2073 &write_data("Date: $datestr\r\n");
2074 &write_data("Server: $config{server}\r\n");
2075 $prot = $ssl ? "https" : "http";
2076 &write_data("Location: $prot://$host$portstr$page/\r\n");
2077 &write_keep_alive(0);
2078 &write_data("\r\n");
2079 &log_request($acpthost, $authuser, $reqline, 302, 0);
2082 # A directory.. check for index files
2084 foreach $idx (split(/\s+/, $config{"index_docs"})) {
2085 $idxfull = "$full/$idx";
2086 @stidxfull = stat($idxfull);
2087 if (-r _ && !-d _) {
2090 @stfull = @stidxfull;
2091 $scriptname .= "/" if ($scriptname ne "/");
2096 @stfull = stat($full) if (!$foundidx);
2099 # This is definately a directory.. list it
2100 print DEBUG "handle_request: listing directory\n";
2101 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2102 "Date: $datestr\r\n".
2103 "Server: $config{server}\r\n".
2104 "Content-type: text/html\r\n";
2106 &write_keep_alive(0);
2107 &write_data("\r\n");
2108 &reset_byte_count();
2109 &write_data("<h1>Index of $simple</h1>\n");
2110 &write_data("<pre>\n");
2111 &write_data(sprintf "%-35.35s %-20.20s %-10.10s\n",
2112 "Name", "Last Modified", "Size");
2113 &write_data("<hr>\n");
2114 opendir(DIR, $full);
2115 while($df = readdir(DIR)) {
2116 if ($df =~ /^\./) { next; }
2117 $fulldf = $full eq "/" ? $full.$df : $full."/".$df;
2118 (@stbuf = stat($fulldf)) || next;
2119 if (-d _) { $df .= "/"; }
2120 @tm = localtime($stbuf[9]);
2121 $fdate = sprintf "%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d",
2122 $tm[3],$tm[4]+1,$tm[5]+1900,
2123 $tm[0],$tm[1],$tm[2];
2124 $len = length($df); $rest = " "x(35-$len);
2126 "<a href=\"%s\">%-${len}.${len}s</a>$rest %-20.20s %-10.10s\n",
2127 $df, $df, $fdate, $stbuf[7]);
2130 &log_request($acpthost, $authuser, $reqline, $ok_code, &byte_count());
2134 # CGI or normal file
2136 if (&get_type($full) eq "internal/cgi" && $validated != 4) {
2137 # A CGI program to execute
2138 print DEBUG "handle_request: executing CGI\n";
2139 $envtz = $ENV{"TZ"};
2140 $envuser = $ENV{"USER"};
2141 $envpath = $ENV{"PATH"};
2142 $envlang = $ENV{"LANG"};
2143 $envroot = $ENV{"SystemRoot"};
2144 $envperllib = $ENV{'PERLLIB'};
2145 foreach my $k (keys %ENV) {
2148 $ENV{"PATH"} = $envpath if ($envpath);
2149 $ENV{"TZ"} = $envtz if ($envtz);
2150 $ENV{"USER"} = $envuser if ($envuser);
2151 $ENV{"OLD_LANG"} = $envlang if ($envlang);
2152 $ENV{"SystemRoot"} = $envroot if ($envroot);
2153 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
2154 $ENV{"HOME"} = $user_homedir;
2155 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
2156 $ENV{"SERVER_NAME"} = $host;
2157 $ENV{"SERVER_ADMIN"} = $config{"email"};
2158 $ENV{"SERVER_ROOT"} = $roots[0];
2159 $ENV{"SERVER_REALROOT"} = $realroot;
2160 $ENV{"SERVER_PORT"} = $port;
2161 $ENV{"REMOTE_HOST"} = $acpthost;
2162 $ENV{"REMOTE_ADDR"} = $acptip;
2163 $ENV{"REMOTE_ADDR_PROTOCOL"} = $ipv6 ? 6 : 4;
2164 $ENV{"REMOTE_USER"} = $authuser;
2165 $ENV{"BASE_REMOTE_USER"} = $authuser ne $baseauthuser ?
2166 $baseauthuser : undef;
2167 $ENV{"REMOTE_PASS"} = $authpass if (defined($authpass) &&
2168 $config{'pass_password'});
2169 if ($uinfo && $uinfo->{'proto'}) {
2170 $ENV{"REMOTE_USER_PROTO"} = $uinfo->{'proto'};
2171 $ENV{"REMOTE_USER_ID"} = $uinfo->{'id'};
2173 print DEBUG "REMOTE_USER = ",$ENV{"REMOTE_USER"},"\n";
2174 print DEBUG "BASE_REMOTE_USER = ",$ENV{"BASE_REMOTE_USER"},"\n";
2175 print DEBUG "proto=$uinfo->{'proto'} id=$uinfo->{'id'}\n" if ($uinfo);
2176 $ENV{"SSL_USER"} = $peername if ($validated == 2);
2177 $ENV{"ANONYMOUS_USER"} = "1" if ($validated == 3 || $validated == 4);
2178 $ENV{"DOCUMENT_ROOT"} = $roots[0];
2179 $ENV{"DOCUMENT_REALROOT"} = $realroot;
2180 $ENV{"GATEWAY_INTERFACE"} = "CGI/1.1";
2181 $ENV{"SERVER_PROTOCOL"} = "HTTP/1.0";
2182 $ENV{"REQUEST_METHOD"} = $method;
2183 $ENV{"SCRIPT_NAME"} = $scriptname;
2184 $ENV{"SCRIPT_FILENAME"} = $full;
2185 $ENV{"REQUEST_URI"} = $request_uri;
2186 $ENV{"PATH_INFO"} = $pathinfo;
2188 $ENV{"PATH_TRANSLATED"} = "$roots[0]$pathinfo";
2189 $ENV{"PATH_REALTRANSLATED"} = "$realroot$pathinfo";
2191 $ENV{"QUERY_STRING"} = $querystring;
2192 $ENV{"MINISERV_CONFIG"} = $config_file;
2193 $ENV{"HTTPS"} = "ON" if ($use_ssl || $config{'inetd_ssl'});
2194 $ENV{"MINISERV_PID"} = $miniserv_main_pid;
2195 $ENV{"SESSION_ID"} = $session_id if ($session_id);
2196 $ENV{"LOCAL_USER"} = $localauth_user if ($localauth_user);
2197 $ENV{"MINISERV_INTERNAL"} = $miniserv_internal if ($miniserv_internal);
2198 if (defined($header{"content-length"})) {
2199 $ENV{"CONTENT_LENGTH"} = $header{"content-length"};
2201 if (defined($header{"content-type"})) {
2202 $ENV{"CONTENT_TYPE"} = $header{"content-type"};
2204 foreach $h (keys %header) {
2205 ($hname = $h) =~ tr/a-z/A-Z/;
2207 $ENV{"HTTP_$hname"} = $header{$h};
2209 $ENV{"PWD"} = $cgi_pwd;
2210 foreach $k (keys %config) {
2211 if ($k =~ /^env_(\S+)$/) {
2212 $ENV{$1} = $config{$k};
2215 delete($ENV{'HTTP_AUTHORIZATION'});
2216 $ENV{'HTTP_COOKIE'} =~ s/;?\s*$sidname=([a-f0-9]+)//;
2217 $ENV{'MOBILE_DEVICE'} = 1 if ($mobile_device);
2219 # Check if the CGI can be handled internally
2221 local $first = <CGI>;
2223 $first =~ s/[#!\r\n]//g;
2224 $nph_script = ($full =~ /\/nph-([^\/]+)$/);
2226 if (!$config{'forkcgis'} &&
2227 ($first eq $perl_path || $first eq $linked_perl_path) &&
2229 $config{'internalcgis'}) {
2230 # setup environment for eval
2232 @ARGV = split(/\s+/, $queryargs);
2235 # Already read the post input
2236 $postinput = $posted_data;
2238 $clen = $header{"content-length"};
2239 $SIG{'CHLD'} = 'DEFAULT';
2241 # Have SOCK closed if the perl exec's something
2243 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
2247 if ($config{'log'}) {
2248 open(MINISERVLOG, ">>$config{'logfile'}");
2249 if ($config{'logperms'}) {
2250 chmod(oct($config{'logperms'}),
2251 $config{'logfile'});
2254 chmod(0600, $config{'logfile'});
2257 $doing_cgi_eval = 1;
2258 $main_process_id = $$;
2260 if ($full =~ /^\Q$foundroot\E\/([^\/]+)\//) {
2261 # Eval in package from Webmin module name
2263 $pkg =~ s/[^A-Za-z0-9]/_/g;
2268 tie(*STDOUT, 'miniserv');
2269 tie(*STDIN, 'miniserv');
2270 do \$miniserv::full;
2273 $doing_cgi_eval = 0;
2276 &http_error(500, "Perl execution failed",
2277 $config{'noshowstderr'} ? undef : $@);
2279 elsif (!$doneheaders && !$nph_script) {
2280 &http_error(500, "Missing Headers");
2287 # fork the process that actually executes the CGI
2288 pipe(CGIINr, CGIINw);
2289 pipe(CGIOUTr, CGIOUTw);
2290 pipe(CGIERRr, CGIERRw);
2291 if (!($cgipid = fork())) {
2292 @execargs = ( $full, split(/\s+/, $queryargs) );
2295 open(STDIN, "<&CGIINr");
2296 open(STDOUT, ">&CGIOUTw");
2297 open(STDERR, ">&CGIERRw");
2298 close(CGIINw); close(CGIOUTr); close(CGIERRr);
2300 die "Failed to exec $full : $!\n";
2303 close(CGIINr); close(CGIOUTw); close(CGIERRw);
2306 # write CGI input to a temp file
2307 $infile = "$config{'tempbase'}.$$";
2308 open(CGIINw, ">$infile");
2309 # NOT binary mode, as CGIs don't read in it!
2314 # already read the posted data
2315 print CGIINw $posted_data;
2317 $clen = $header{"content-length"};
2318 if ($method eq "POST" && $clen_read < $clen) {
2319 $SIG{'PIPE'} = 'IGNORE';
2321 while($got < $clen) {
2322 $buf = &read_data($clen-$got);
2323 if (!length($buf)) {
2324 kill('TERM', $cgipid);
2325 unlink($infile) if ($infile);
2326 &http_error(500, "Failed to read ".
2329 $got += length($buf);
2330 local ($wrote) = (print CGIINw $buf);
2333 # If the CGI terminated early, we still need to read
2334 # from the browser and throw away
2335 while($got < $clen) {
2336 $buf = &read_data($clen-$got);
2337 if (!length($buf)) {
2338 kill('TERM', $cgipid);
2339 unlink($infile) if ($infile);
2340 &http_error(500, "Failed to read ".
2343 $got += length($buf);
2345 $SIG{'PIPE'} = 'DEFAULT';
2351 # Run the CGI program, and feed it input
2353 local $qqueryargs = join(" ", map { "\"$_\"" }
2354 split(/\s+/, $queryargs));
2355 if ($first =~ /(perl|perl.exe)$/i) {
2356 # On Windows, run with Perl
2357 open(CGIOUTr, "$perl_path \"$full\" $qqueryargs <$infile |");
2360 open(CGIOUTr, "\"$full\" $qqueryargs <$infile |");
2366 # read back cgi headers
2367 select(CGIOUTr); $|=1; select(STDOUT);
2371 $line =~ s/\r|\n//g;
2373 if ($got_blank || %cgiheader) { last; }
2377 if ($line !~ /^(\S+):\s+(.*)$/) {
2378 $errs = &read_errors(CGIERRr);
2379 close(CGIOUTr); close(CGIERRr);
2380 unlink($infile) if ($infile);
2381 &http_error(500, "Bad Header", $errs);
2383 $cgiheader{lc($1)} = $2;
2384 push(@cgiheader, [ $1, $2 ]);
2386 if ($cgiheader{"location"}) {
2387 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2388 &write_data("Date: $datestr\r\n");
2389 &write_data("Server: $config{'server'}\r\n");
2390 &write_keep_alive(0);
2391 # ignore the rest of the output. This is a hack,
2392 # but is necessary for IE in some cases :(
2393 close(CGIOUTr); close(CGIERRr);
2395 elsif ($cgiheader{"content-type"} eq "") {
2396 close(CGIOUTr); close(CGIERRr);
2397 unlink($infile) if ($infile);
2398 $errs = &read_errors(CGIERRr);
2399 &http_error(500, "Missing Content-Type Header",
2400 $config{'noshowstderr'} ? undef : $errs);
2403 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2404 &write_data("Date: $datestr\r\n");
2405 &write_data("Server: $config{'server'}\r\n");
2406 &write_keep_alive(0);
2408 foreach $h (@cgiheader) {
2409 &write_data("$h->[0]: $h->[1]\r\n");
2411 &write_data("\r\n");
2413 &reset_byte_count();
2414 while($line = <CGIOUTr>) {
2419 unlink($infile) if ($infile);
2425 print DEBUG "handle_request: outputting file\n";
2426 open(FILE, $full) || &http_error(404, "Failed to open file");
2428 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2429 "Date: $datestr\r\n".
2430 "Server: $config{server}\r\n".
2431 "Content-type: ".&get_type($full)."\r\n".
2432 "Content-length: $stfull[7]\r\n".
2433 "Last-Modified: ".&http_date($stfull[9])."\r\n".
2434 "Expires: ".&http_date(time()+$config{'expires'})."\r\n";
2436 $rv = &write_keep_alive();
2437 &write_data("\r\n");
2438 &reset_byte_count();
2439 while(read(FILE, $buf, 1024) > 0) {
2446 &log_request($acpthost, $authuser, $reqline,
2447 $logged_code ? $logged_code :
2448 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2452 # http_error(code, message, body, [dontexit])
2455 local $eh = $error_handler_recurse ? undef :
2456 $config{"error_handler_$_[0]"} ? $config{"error_handler_$_[0]"} :
2457 $config{'error_handler'} ? $config{'error_handler'} : undef;
2458 print DEBUG "http_error code=$_[0] message=$_[1] body=$_[2]\n";
2460 # Call a CGI program for the error
2462 $querystring = "code=$_[0]&message=".&urlize($_[1]).
2463 "&body=".&urlize($_[2]);
2464 $error_handler_recurse++;
2466 $ok_message = $_[1];
2470 # Use the standard error message display
2471 &write_data("HTTP/1.0 $_[0] $_[1]\r\n");
2472 &write_data("Server: $config{server}\r\n");
2473 &write_data("Date: $datestr\r\n");
2474 &write_data("Content-type: text/html\r\n");
2475 &write_keep_alive(0);
2476 &write_data("\r\n");
2477 &reset_byte_count();
2478 &write_data("<h1>Error - $_[1]</h1>\n");
2480 &write_data("<pre>$_[2]</pre>\n");
2483 &log_request($acpthost, $authuser, $reqline, $_[0], &byte_count())
2485 &log_error($_[1], $_[2] ? " : $_[2]" : "");
2492 if ($_[0] =~ /\.([A-z0-9]+)$/) {
2498 return "text/plain";
2501 # simplify_path(path, bogus)
2502 # Given a path, maybe containing stuff like ".." and "." convert it to a
2503 # clean, absolute form.
2506 local($dir, @bits, @fixedbits, $b);
2508 $dir =~ s/\\/\//g; # fix windows \ in path
2511 $dir =~ s/\0//g; # remove null bytes
2512 @bits = split(/\/+/, $dir);
2515 foreach $b (@bits) {
2519 elsif ($b eq ".." || $b eq "...") {
2521 if (scalar(@fixedbits) == 0) {
2529 push(@fixedbits, $b);
2532 return "/" . join('/', @fixedbits);
2536 # Converts a string from base64 format to normal
2539 local($str) = $_[0];
2541 $str =~ tr|A-Za-z0-9+=/||cd;
2543 $str =~ tr|A-Za-z0-9+/| -_|;
2544 while ($str =~ /(.{1,60})/gs) {
2545 my $len = chr(32 + length($1)*3/4);
2546 $res .= unpack("u", $len . $1 );
2551 # ip_match(remoteip, localip, [match]+)
2552 # Checks an IP address against a list of IPs, networks and networks/masks
2555 local(@io, @mo, @ms, $i, $j, $hn, $needhn);
2556 @io = &check_ip6address($_[0]) ? split(/:/, $_[0])
2557 : split(/\./, $_[0]);
2558 for($i=2; $i<@_; $i++) {
2559 $needhn++ if ($_[$i] =~ /^\*(\S+)$/);
2561 if ($needhn && !defined($hn = $ip_match_cache{$_[0]})) {
2562 # Reverse-lookup hostname if any rules match based on it
2563 $hn = &to_hostname($_[0]);
2564 if (&check_ip6address($_[0])) {
2565 $hn = "" if (&to_ip6address($hn) ne $_[0]);
2568 $hn = "" if (&to_ipaddress($hn) ne $_[0]);
2570 $ip_match_cache{$_[0]} = $hn;
2572 for($i=2; $i<@_; $i++) {
2573 local $mismatch = 0;
2574 if ($_[$i] =~ /^(\S+)\/(\d+)$/) {
2575 # Convert CIDR to netmask format
2576 $_[$i] = $1."/".&prefix_to_mask($2);
2578 if ($_[$i] =~ /^(\S+)\/(\S+)$/) {
2579 # Compare with IPv4 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' && &check_ipaddress($_[1])) {
2592 # Compare with local IPv4 network
2593 local @lo = split(/\./, $_[1]);
2595 $mismatch = 1 if ($lo[0] != $io[0]);
2597 elsif ($lo[0] < 192) {
2598 $mismatch = 1 if ($lo[0] != $io[0] ||
2602 $mismatch = 1 if ($lo[0] != $io[0] ||
2607 elsif ($_[$i] eq 'LOCAL' && &check_ip6address($_[1])) {
2608 # Compare with local IPv6 network, which is always first 4 words
2609 local @lo = split(/:/, $_[1]);
2610 for(my $i=0; $i<4; $i++) {
2611 $mismatch = 1 if ($lo[$i] ne $io[$i]);
2614 elsif ($_[$i] =~ /^[0-9\.]+$/) {
2615 # Compare with IPv4 address or network
2616 @mo = split(/\./, $_[$i]);
2617 while(@mo && !$mo[$#mo]) { pop(@mo); }
2618 for($j=0; $j<@mo; $j++) {
2619 if ($mo[$j] != $io[$j]) {
2624 elsif ($_[$i] =~ /^[a-f0-9:]+$/) {
2625 # Compare with IPv6 address or network
2626 @mo = split(/:/, $_[$i]);
2627 while(@mo && !$mo[$#mo]) { pop(@mo); }
2628 for($j=0; $j<@mo; $j++) {
2629 if ($mo[$j] ne $io[$j]) {
2634 elsif ($_[$i] !~ /^[0-9\.]+$/) {
2635 # Compare with hostname
2636 $mismatch = 1 if ($_[0] ne &to_ipaddress($_[$i]));
2638 return 1 if (!$mismatch);
2643 # users_match(&uinfo, user, ...)
2644 # Returns 1 if a user is in a list of users and groups
2647 local $uinfo = shift(@_);
2649 local @ginfo = getgrgid($uinfo->[3]);
2651 if ($u =~ /^\@(\S+)$/) {
2652 return 1 if (&is_group_member($uinfo, $1));
2654 elsif ($u =~ /^(\d*)-(\d*)$/ && ($1 || $2)) {
2655 return (!$1 || $uinfo[2] >= $1) &&
2656 (!$2 || $uinfo[2] <= $2);
2659 return 1 if ($u eq $uinfo->[0]);
2665 # restart_miniserv()
2666 # Called when a SIGHUP is received to restart the web server. This is done
2667 # by exec()ing perl with the same command line as was originally used
2668 sub restart_miniserv
2670 print STDERR "restarting miniserv\n";
2671 &log_error("Restarting");
2673 &close_all_sockets();
2675 dbmclose(%sessiondb);
2676 kill('KILL', $logclearer) if ($logclearer);
2677 kill('KILL', $extauth) if ($extauth);
2678 exec($perl_path, $miniserv_path, @miniserv_argv);
2679 die "Failed to restart miniserv with $perl_path $miniserv_path";
2692 # to_ipaddress(address, ...)
2697 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2698 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/ || $i =~ /^[a-f0-9:]+$/) {
2699 # A pattern or IP, not a hostname, so don't change
2704 push(@rv, join('.', unpack("CCCC", inet_aton($i))));
2707 return wantarray ? @rv : $rv[0];
2710 # to_ip6address(address, ...)
2715 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2716 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/ || $i =~ /^[a-f0-9:]+$/) {
2717 # A pattern, not a hostname, so don't change
2721 # Lookup IPv6 address
2722 local ($inaddr, $addr);
2723 (undef, undef, undef, $inaddr) =
2724 getaddrinfo($i, undef, Socket6::AF_INET6(), SOCK_STREAM);
2729 (undef, $addr) = unpack_sockaddr_in6($inaddr);
2730 push(@rv, inet_ntop(Socket6::AF_INET6(), $addr));
2734 return wantarray ? @rv : $rv[0];
2737 # to_hostname(ipv4|ipv6-address)
2738 # Reverse-resolves an IPv4 or 6 address to a hostname
2742 if (&check_ip6address($_[0])) {
2743 return gethostbyaddr(inet_pton(Socket6::AF_INET6(), $addr),
2744 Socket6::AF_INET6());
2747 return gethostbyaddr(inet_aton($addr), AF_INET);
2751 # read_line(no-wait, no-limit)
2752 # Reads one line from SOCK or SSL
2755 local ($nowait, $nolimit) = @_;
2756 local($idx, $more, $rv);
2757 while(($idx = index($main::read_buffer, "\n")) < 0) {
2758 if (length($main::read_buffer) > 10000 && !$nolimit) {
2759 &http_error(414, "Request too long",
2760 "Received excessive line <pre>$main::read_buffer</pre>");
2763 # need to read more..
2764 &wait_for_data_error() if (!$nowait);
2766 $more = Net::SSLeay::read($ssl_con);
2769 local $ok = sysread(SOCK, $more, 1024);
2770 $more = undef if ($ok <= 0);
2774 $rv = $main::read_buffer;
2775 undef($main::read_buffer);
2778 $main::read_buffer .= $more;
2780 $rv = substr($main::read_buffer, 0, $idx+1);
2781 $main::read_buffer = substr($main::read_buffer, $idx+1);
2786 # Reads up to some amount of data from SOCK or the SSL connection
2790 if (length($main::read_buffer)) {
2791 if (length($main::read_buffer) > $_[0]) {
2792 # Return the first part of the buffer
2793 $rv = substr($main::read_buffer, 0, $_[0]);
2794 $main::read_buffer = substr($main::read_buffer, $_[0]);
2798 # Return the whole buffer
2799 $rv = $main::read_buffer;
2800 undef($main::read_buffer);
2805 # Call SSL read function
2806 return Net::SSLeay::read($ssl_con, $_[0]);
2809 # Just do a normal read
2811 sysread(SOCK, $buf, $_[0]) || return undef;
2817 # Read a line from a file handle, using sysread to get a byte at a time
2824 $got = sysread($fh, $buf, 1);
2825 last if ($got <= 0);
2827 last if ($buf eq "\n");
2832 # wait_for_data(secs)
2833 # Waits at most the given amount of time for some data on SOCK, returning
2834 # 0 if not found, 1 if some arrived.
2838 vec($rmask, fileno(SOCK), 1) = 1;
2839 local $got = select($rmask, undef, undef, $_[0]);
2840 return $got == 0 ? 0 : 1;
2843 # wait_for_data_error()
2844 # Waits 60 seconds for data on SOCK, and fails if none arrives
2845 sub wait_for_data_error
2847 local $got = &wait_for_data(60);
2849 &http_error(400, "Timeout",
2850 "Waited more than 60 seconds for request data");
2854 # write_data(data, ...)
2855 # Writes a string to SOCK or the SSL connection
2858 local $str = join("", @_);
2860 Net::SSLeay::write($ssl_con, $str);
2863 syswrite(SOCK, $str, length($str));
2865 # Intentionally introduce a small delay to avoid problems where IE reports
2866 # the page as empty / DNS failed when it get a large response too quickly!
2867 select(undef, undef, undef, .01) if ($write_data_count%10 == 0);
2868 $write_data_count += length($str);
2871 # reset_byte_count()
2872 sub reset_byte_count { $write_data_count = 0; }
2875 sub byte_count { return $write_data_count; }
2877 # log_request(hostname, user, request, code, bytes)
2880 if ($config{'log'}) {
2881 local ($user, $ident, $headers);
2882 if ($config{'logident'}) {
2883 # add support for rfc1413 identity checking here
2885 else { $ident = "-"; }
2886 $user = $_[1] ? $_[1] : "-";
2887 local $dstr = &make_datestr();
2888 if (fileno(MINISERVLOG)) {
2889 seek(MINISERVLOG, 0, 2);
2892 open(MINISERVLOG, ">>$config{'logfile'}");
2893 chmod(0600, $config{'logfile'});
2895 if (defined($config{'logheaders'})) {
2896 foreach $h (split(/\s+/, $config{'logheaders'})) {
2897 $headers .= " $h=\"$header{$h}\"";
2900 elsif ($config{'logclf'}) {
2901 $headers = " \"$header{'referer'}\" \"$header{'user-agent'}\"";
2906 print MINISERVLOG "$_[0] $ident $user [$dstr] \"$_[2]\" ",
2907 "$_[3] $_[4]$headers\n";
2915 local @tm = localtime(time());
2916 return sprintf "%2.2d/%s/%4.4d:%2.2d:%2.2d:%2.2d %s",
2917 $tm[3], $month[$tm[4]], $tm[5]+1900,
2918 $tm[2], $tm[1], $tm[0], $timezone;
2921 # log_error(message)
2925 print STDERR "[",&make_datestr(),"] ",
2926 $acpthost ? ( "[",$acpthost,"] " ) : ( ),
2927 $page ? ( $page," : " ) : ( ),
2931 # read_errors(handle)
2932 # Read and return all input from some filehandle
2935 local($fh, $_, $rv);
2937 while(<$fh>) { $rv .= $_; }
2941 sub write_keep_alive
2944 if ($config{'nokeepalive'}) {
2945 # Keep alives have been disabled in config
2948 elsif (@childpids > $config{'maxconns'}*.8) {
2949 # Disable because nearing process limit
2953 # Keep alive specified by caller
2957 # Keep alive determined by browser
2958 $mode = $header{'connection'} =~ /keep-alive/i;
2960 &write_data("Connection: ".($mode ? "Keep-Alive" : "close")."\r\n");
2966 kill('TERM', @childpids) if (@childpids);
2967 kill('KILL', $logclearer) if ($logclearer);
2968 kill('KILL', $extauth) if ($extauth);
2974 local @tm = gmtime($_[0]);
2975 return sprintf "%s, %d %s %d %2.2d:%2.2d:%2.2d GMT",
2976 $weekday[$tm[6]], $tm[3], $month[$tm[4]], $tm[5]+1900,
2977 $tm[2], $tm[1], $tm[0];
2982 my $i; bless \$i, shift;
2988 my($buf,$len,$offset) = @_;
2989 &write_to_sock(substr($buf, $offset, $len));
2990 $miniserv::page_capture_out .= substr($buf, $offset, $len)
2991 if ($miniserv::page_capture);
2998 my $buf = join(defined($,) ? $, : "", @_);
2999 $buf .= $\ if defined($\);
3000 &write_to_sock($buf);
3001 $miniserv::page_capture_out .= $buf
3002 if ($miniserv::page_capture);
3009 my $buf = sprintf $fmt, @_;
3010 &write_to_sock($buf);
3011 $miniserv::page_capture_out .= $buf
3012 if ($miniserv::page_capture);
3015 # Send back already read data while we have it, then read from SOCK
3019 my $bufref = \$_[0];
3022 if ($postpos < length($postinput)) {
3023 # Reading from already fetched array
3024 my $left = length($postinput) - $postpos;
3025 my $canread = $len > $left ? $left : $len;
3026 substr($$bufref, $offset, $canread) =
3027 substr($postinput, $postpos, $canread);
3028 $postpos += $canread;
3032 # Read from network socket
3033 local $data = &read_data($len);
3034 if ($data eq '' && $len) {
3036 print STDERR "finished reading - shutting down socket\n";
3039 substr($$bufref, $offset, length($data)) = $data;
3040 return length($data);
3046 #print STDERR "open() called - should never happen!\n";
3049 # Read a line of input
3053 if ($postpos < length($postinput) &&
3054 ($idx = index($postinput, "\n", $postpos)) >= 0) {
3055 # A line exists in the memory buffer .. use it
3056 my $line = substr($postinput, $postpos, $idx-$postpos+1);
3061 # Need to read from the socket
3063 if ($postpos < length($postinput)) {
3064 # Start with in-memory data
3065 $line = substr($postinput, $postpos);
3066 $postpos = length($postinput);
3068 my $nl = &read_line(0, 1);
3071 print STDERR "finished reading - shutting down socket\n";
3074 $line .= $nl if (defined($nl));
3079 # Read one character of input
3084 my $got = READ($r, \$buf, 1, 0);
3085 return $got > 0 ? $buf : undef;
3090 return fileno(SOCK);
3097 # write_to_sock(data, ...)
3102 if ($doneheaders || $miniserv::nph_script) {
3107 while(!$doneheaders && $headers =~ s/^([^\r\n]*)(\r)?\n//) {
3108 if ($1 =~ /^(\S+):\s+(.*)$/) {
3109 $cgiheader{lc($1)} = $2;
3110 push(@cgiheader, [ $1, $2 ]);
3112 elsif ($1 !~ /\S/) {
3116 &http_error(500, "Bad Header");
3120 if ($cgiheader{"location"}) {
3122 "HTTP/1.0 302 Moved Temporarily\r\n");
3123 &write_data("Date: $datestr\r\n");
3124 &write_data("Server: $config{server}\r\n");
3125 &write_keep_alive(0);
3127 elsif ($cgiheader{"content-type"} eq "") {
3128 &http_error(500, "Missing Content-Type Header");
3131 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
3132 &write_data("Date: $datestr\r\n");
3133 &write_data("Server: $config{server}\r\n");
3134 &write_keep_alive(0);
3136 foreach $h (@cgiheader) {
3137 &write_data("$h->[0]: $h->[1]\r\n");
3139 &write_data("\r\n");
3140 &reset_byte_count();
3141 &write_data($headers);
3149 local $cert = Net::SSLeay::X509_STORE_CTX_get_current_cert($_[1]);
3151 local $errnum = Net::SSLeay::X509_STORE_CTX_get_error($_[1]);
3152 $verified_client = 1 if (!$errnum);
3159 if ($doing_cgi_eval && $$ == $main_process_id) {
3160 # A CGI program called exit! This is a horrible hack to
3161 # finish up before really exiting
3164 close($PASSINw); close($PASSOUTw);
3165 &log_request($acpthost, $authuser, $reqline,
3166 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
3171 # Convert a string to a form ok for putting in a URL
3173 local($tmp, $tmp2, $c);
3176 while(($c = chop($tmp)) ne "") {
3177 if ($c !~ /[A-z0-9]/) {
3178 $c = sprintf("%%%2.2X", ord($c));
3185 # validate_user(username, password, host)
3186 # Checks if some username and password are valid. Returns the modified username,
3187 # the expired / temp pass flag, and the non-existence flag
3190 local ($user, $pass, $host) = @_;
3191 return ( ) if (!$user);
3192 print DEBUG "validate_user: user=$user pass=$pass host=$host\n";
3193 local ($canuser, $canmode, $notexist, $webminuser, $sudo) =
3194 &can_user_login($user, undef, $host);
3195 print DEBUG "validate_user: canuser=$canuser canmode=$canmode notexist=$notexist webminuser=$webminuser sudo=$sudo\n";
3197 # User doesn't even exist, so go no further
3198 return ( undef, 0, 1 );
3200 elsif ($canmode == 0) {
3201 # User does exist but cannot login
3202 return ( $canuser, 0, 0 );
3204 elsif ($canmode == 1) {
3205 # Attempt Webmin authentication
3206 my $uinfo = &get_user_details($webminuser);
3208 &password_crypt($pass, $uinfo->{'pass'}) eq $uinfo->{'pass'}) {
3209 # Password is valid .. but check for expiry
3210 local $lc = $uinfo->{'lastchanges'};
3211 print DEBUG "validate_user: Password is valid lc=$lc pass_maxdays=$config{'pass_maxdays'}\n";
3212 if ($config{'pass_maxdays'} && $lc && !$uinfo->{'nochange'}) {
3213 local $daysold = (time() - $lc)/(24*60*60);
3214 print DEBUG "maxdays=$config{'pass_maxdays'} daysold=$daysold temppass=$uinfo->{'temppass'}\n";
3215 if ($config{'pass_lockdays'} &&
3216 $daysold > $config{'pass_lockdays'}) {
3217 # So old that the account is locked
3218 return ( undef, 0, 0 );
3220 elsif ($daysold > $config{'pass_maxdays'}) {
3221 # Password has expired
3222 return ( $user, 1, 0 );
3225 if ($uinfo->{'temppass'}) {
3226 # Temporary password - force change now
3227 return ( $user, 2, 0 );
3229 return ( $user, 0, 0 );
3232 print DEBUG "validate_user: User $webminuser not found\n";
3233 return ( undef, 0, 0 );
3236 print DEBUG "validate_user: User $webminuser password mismatch $pass != $uinfo->{'pass'}\n";
3237 return ( undef, 0, 0 );
3240 elsif ($canmode == 2 || $canmode == 3) {
3241 # Attempt PAM or passwd file authentication
3242 local $val = &validate_unix_user($canuser, $pass);
3243 print DEBUG "validate_user: unix val=$val\n";
3244 if ($val && $sudo) {
3245 # Need to check if this Unix user can sudo
3246 if (!&check_sudo_permissions($canuser, $pass)) {
3247 print DEBUG "validate_user: sudo failed\n";
3251 print DEBUG "validate_user: sudo passed\n";
3254 return $val == 2 ? ( $canuser, 1, 0 ) :
3255 $val == 1 ? ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3257 elsif ($canmode == 4) {
3258 # Attempt external authentication
3259 return &validate_external_user($canuser, $pass) ?
3260 ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3268 # validate_unix_user(user, password)
3269 # Returns 1 if a username and password are valid under unix, 0 if not,
3270 # or 2 if the account has expired.
3271 # Checks PAM if available, and falls back to reading the system password
3273 sub validate_unix_user
3277 $pam_username = $_[0];
3278 $pam_password = $_[1];
3279 eval "use Authen::PAM;";
3280 local $pamh = new Authen::PAM($config{'pam'}, $pam_username,
3283 local $pam_ret = $pamh->pam_authenticate();
3284 if ($pam_ret == PAM_SUCCESS()) {
3285 # Logged in OK .. make sure password hasn't expired
3286 local $acct_ret = $pamh->pam_acct_mgmt();
3287 if ($acct_ret == PAM_SUCCESS()) {
3288 $pamh->pam_open_session();
3291 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3292 $acct_ret == PAM_ACCT_EXPIRED()) {
3296 print STDERR "Unknown pam_acct_mgmt return value : $acct_ret\n";
3303 elsif ($config{'pam_only'}) {
3304 # Pam is not available, but configuration forces it's use!
3307 elsif ($config{'passwd_file'}) {
3308 # Check in a password file
3310 open(FILE, $config{'passwd_file'});
3311 if ($config{'passwd_file'} eq '/etc/security/passwd') {
3312 # Assume in AIX format
3315 if (/^\s*(\S+):/ && $1 eq $_[0]) {
3317 if (/^\s*password\s*=\s*(\S+)\s*$/) {
3318 $rv = $1 eq &password_crypt($_[1], $1) ?
3326 # Read the system password or shadow file
3328 local @l = split(/:/, $_, -1);
3329 local $u = $l[$config{'passwd_uindex'}];
3330 local $p = $l[$config{'passwd_pindex'}];
3332 $rv = $p eq &password_crypt($_[1], $p) ? 1 : 0;
3333 if ($config{'passwd_cindex'} ne '' && $rv) {
3334 # Password may have expired!
3335 local $c = $l[$config{'passwd_cindex'}];
3336 local $m = $l[$config{'passwd_mindex'}];
3337 local $day = time()/(24*60*60);
3338 if ($c =~ /^\d+/ && $m =~ /^\d+/ &&
3344 if ($p eq "" && $config{'passwd_blank'}) {
3345 # Force password change
3353 return $rv if ($rv);
3356 # Fallback option - check password returned by getpw*
3357 local @uinfo = getpwnam($_[0]);
3358 if ($uinfo[1] ne '' && &password_crypt($_[1], $uinfo[1]) eq $uinfo[1]) {
3362 return 0; # Totally failed
3365 # validate_external_user(user, pass)
3366 # Validate a user by passing the username and password to an external
3367 # squid-style authentication program
3368 sub validate_external_user
3370 return 0 if (!$config{'extauth'});
3372 local $str = "$_[0] $_[1]\n";
3373 syswrite(EXTAUTH, $str, length($str));
3374 local $resp = <EXTAUTH>;
3376 return $resp =~ /^OK/i ? 1 : 0;
3379 # can_user_login(username, no-append, host)
3380 # Checks if a user can login or not.
3381 # First return value is the username.
3382 # Second is 0 if cannot login, 1 if using Webmin pass, 2 if PAM, 3 if password
3383 # file, 4 if external.
3384 # Third is 1 if the user does not exist at all, 0 if he does.
3385 # Fourth is the Webmin username whose permissions apply, based on unixauth.
3386 # Fifth is a flag indicating if a sudo check is needed.
3389 local $uinfo = &get_user_details($_[0]);
3391 # See if this user exists in Unix and can be validated by the same
3392 # method as the unixauth webmin user
3393 local $realuser = $unixauth{$_[0]};
3397 eval { @uinfo = getpwnam($_[0]); }; # may fail on windows
3398 if (!$realuser && @uinfo) {
3399 # No unixauth entry for the username .. try his groups
3400 foreach my $ua (keys %unixauth) {
3401 if ($ua =~ /^\@(.*)$/) {
3402 if (&is_group_member(\@uinfo, $1)) {
3403 $realuser = $unixauth{$ua};
3409 if (!$realuser && @uinfo) {
3410 # Fall back to unix auth for all Unix users
3411 $realuser = $unixauth{"*"};
3413 if (!$realuser && $use_sudo && @uinfo) {
3414 # Allow login effectively as root, if sudo permits it
3418 if (!$realuser && !@uinfo && $config{'pamany'}) {
3419 # If the user completely doesn't exist, we can still allow
3420 # him to authenticate via PAM
3421 $realuser = $config{'pamany'};
3425 # For Usermin, always fall back to unix auth for any user,
3426 # so that later checks with domain added / removed are done.
3427 $realuser = $unixauth{"*"};
3429 return (undef, 0, 1, undef) if (!$realuser);
3430 local $uinfo = &get_user_details($realuser);
3431 return (undef, 0, 1, undef) if (!$uinfo);
3432 local $up = $uinfo->{'pass'};
3434 # Work out possible domain names from the hostname
3435 local @doms = ( $_[2] );
3436 if ($_[2] =~ /^([^\.]+)\.(\S+)$/) {
3440 if ($config{'user_mapping'} && !%user_mapping) {
3441 # Read the user mapping file
3443 open(MAPPING, $config{'user_mapping'});
3447 if (/^(\S+)\s+(\S+)/) {
3448 if ($config{'user_mapping_reverse'}) {
3449 $user_mapping{$1} = $2;
3452 $user_mapping{$2} = $1;
3459 # Check the user mapping file to see if there is an entry for the
3460 # user login in which specifies a new effective user
3462 foreach my $d (@doms) {
3463 $um ||= $user_mapping{"$_[0]\@$d"};
3465 $um ||= $user_mapping{$_[0]};
3466 if (defined($um) && ($_[1]&4) == 0) {
3467 # A mapping exists - use it!
3468 return &can_user_login($um, $_[1]+4, $_[2]);
3471 # Check if a user with the entered login and the domains appended
3472 # or prepended exists, and if so take it to be the effective user
3473 if (!@uinfo && $config{'domainuser'}) {
3474 # Try again with name.domain and name.firstpart
3475 local @firsts = map { /^([^\.]+)/; $1 } @doms;
3476 if (($_[1]&1) == 0) {
3478 foreach $a (@firsts, @doms) {
3479 foreach $p ("$_[0].${a}", "$_[0]-${a}",
3480 "${a}.$_[0]", "${a}-$_[0]",
3481 "$_[0]_${a}", "${a}_$_[0]") {
3482 local @vu = &can_user_login(
3483 $p, $_[1]+1, $_[2]);
3484 return @vu if ($vu[1]);
3490 # Check if the user entered a domain at the end of his username when
3491 # he really shouldn't have, and if so try without it
3492 if (!@uinfo && $config{'domainstrip'} &&
3493 $_[0] =~ /^(\S+)\@(\S+)$/ && ($_[1]&2) == 0) {
3494 local ($stripped, $dom) = ($1, $2);
3495 local @vu = &can_user_login($stripped, $_[1] + 2, $_[2]);
3496 return @vu if ($vu[1]);
3497 local @vu = &can_user_login($stripped, $_[1] + 2, $dom);
3498 return @vu if ($vu[1]);
3501 return ( undef, 0, 1, undef ) if (!@uinfo && !$pamany);
3504 if (defined(@allowusers)) {
3505 # Only allow people on the allow list
3506 return ( undef, 0, 0, undef )
3507 if (!&users_match(\@uinfo, @allowusers));
3509 elsif (defined(@denyusers)) {
3510 # Disallow people on the deny list
3511 return ( undef, 0, 0, undef )
3512 if (&users_match(\@uinfo, @denyusers));
3514 if ($config{'shells_deny'}) {
3516 open(SHELLS, $config{'shells_deny'});
3520 $found++ if ($_ eq $uinfo[8]);
3523 return ( undef, 0, 0, undef ) if (!$found);
3528 # PAM or passwd file authentication
3529 print DEBUG "can_user_login: Validate with PAM\n";
3530 return ( $_[0], $use_pam ? 2 : 3, 0, $realuser, $sudo );
3532 elsif ($up eq 'e') {
3533 # External authentication
3534 print DEBUG "can_user_login: Validate externally\n";
3535 return ( $_[0], 4, 0, $realuser, $sudo );
3538 # Fixed Webmin password
3539 print DEBUG "can_user_login: Validate by Webmin\n";
3540 return ( $_[0], 1, 0, $realuser, $sudo );
3543 elsif ($uinfo->{'pass'} eq 'x') {
3544 # Webmin user authenticated via PAM or password file
3545 return ( $_[0], $use_pam ? 2 : 3, 0, $_[0] );
3547 elsif ($uinfo->{'pass'} eq 'e') {
3548 # Webmin user authenticated externally
3549 return ( $_[0], 4, 0, $_[0] );
3552 # Normal Webmin user
3553 return ( $_[0], 1, 0, $_[0] );
3557 # the PAM conversation function for interactive logins
3560 $pam_conv_func_called++;
3567 $ans = $pam_username if ($code == PAM_PROMPT_ECHO_ON() );
3568 $ans = $pam_password if ($code == PAM_PROMPT_ECHO_OFF() );
3570 push @res, PAM_SUCCESS();
3573 push @res, PAM_SUCCESS();
3582 # get_socket_ip(handle, ipv6-flag)
3583 # Returns the local IP address of some connection, as both a string and in
3587 local ($fh, $ipv6) = @_;
3588 local $sn = getsockname($fh);
3589 return undef if (!$sn);
3590 return &get_address_ip($sn, $ipv6);
3593 # get_address_ip(address, ipv6-flag)
3594 # Given a sockaddr object in binary format, return the binary address, text
3595 # address and port number
3598 local ($sn, $ipv6) = @_;
3600 local ($p, $b) = unpack_sockaddr_in6($sn);
3601 return ($b, inet_ntop(Socket6::AF_INET6(), $b), $p);
3604 local ($p, $b) = unpack_sockaddr_in($sn);
3605 return ($b, inet_ntoa($b), $p);
3609 # get_socket_name(handle, ipv6-flag)
3610 # Returns the local hostname or IP address of some connection
3613 local ($fh, $ipv6) = @_;
3614 return $config{'host'} if ($config{'host'});
3615 local ($mybin, $myaddr) = &get_socket_ip($fh, $ipv6);
3616 if (!$get_socket_name_cache{$myaddr}) {
3618 if (!$config{'no_resolv_myname'}) {
3619 $myname = gethostbyaddr($mybin,
3620 $ipv6 ? Socket6::AF_INET6() : AF_INET);
3622 $myname ||= $myaddr;
3623 $get_socket_name_cache{$myaddr} = $myname;
3625 return $get_socket_name_cache{$myaddr};
3628 # run_login_script(username, sid, remoteip, localip)
3629 sub run_login_script
3631 if ($config{'login_script'}) {
3632 system($config{'login_script'}.
3633 " ".join(" ", map { quotemeta($_) || '""' } @_).
3634 " >/dev/null 2>&1 </dev/null");
3638 # run_logout_script(username, sid, remoteip, localip)
3639 sub run_logout_script
3641 if ($config{'logout_script'}) {
3642 system($config{'logout_script'}.
3643 " ".join(" ", map { quotemeta($_) || '""' } @_).
3644 " >/dev/null 2>&1 </dev/null");
3648 # close_all_sockets()
3649 # Closes all the main listening sockets
3650 sub close_all_sockets
3653 foreach $s (@socketfhs) {
3659 # Close all pipes for talking to sub-processes
3663 foreach $p (@passin) { close($p); }
3664 foreach $p (@passout) { close($p); }
3665 foreach $p (values %conversations) {
3666 if ($p->{'PAMOUTr'}) {
3667 close($p->{'PAMOUTr'});
3668 close($p->{'PAMINw'});
3673 # check_user_ip(user)
3674 # Returns 1 if some user is allowed to login from the accepting IP, 0 if not
3677 local ($username) = @_;
3678 local $uinfo = &get_user_details($username);
3679 return 1 if (!$uinfo);
3680 if ($uinfo->{'deny'} &&
3681 &ip_match($acptip, $localip, @{$uinfo->{'deny'}}) ||
3682 $uinfo->{'allow'} &&
3683 !&ip_match($acptip, $localip, @{$uinfo->{'allow'}})) {
3689 # check_user_time(user)
3690 # Returns 1 if some user is allowed to login at the current date and time
3693 local ($username) = @_;
3694 local $uinfo = &get_user_details($username);
3695 return 1 if (!$uinfo || !$uinfo->{'allowdays'} && !$uinfo->{'allowhours'});
3696 local @tm = localtime(time());
3697 if ($uinfo->{'allowdays'}) {
3698 # Make sure day is allowed
3699 return 0 if (&indexof($tm[6], @{$uinfo->{'allowdays'}}) < 0);
3701 if ($uinfo->{'allowhours'}) {
3702 # Make sure time is allowed
3703 local $m = $tm[2]*60+$tm[1];
3704 return 0 if ($m < $uinfo->{'allowhours'}->[0] ||
3705 $m > $uinfo->{'allowhours'}->[1]);
3710 # generate_random_id(password, [force-urandom])
3711 # Returns a random session ID number
3712 sub generate_random_id
3714 local ($pass, $force_urandom) = @_;
3716 if (!$bad_urandom) {
3717 # First try /dev/urandom, unless we have marked it as bad
3718 $SIG{ALRM} = "miniserv::urandom_timeout";
3720 if (open(RANDOM, "/dev/urandom")) {
3722 if (read(RANDOM, $tmpsid, 16) == 16) {
3723 $sid = lc(unpack('h*',$tmpsid));
3729 if (!$sid && !$force_urandom) {
3732 foreach $c (split(//, &unix_crypt($pass, substr($$, -2)))) {
3733 $sid += ord($c) * $mul;
3740 # handle_login(username, ok, expired, not-exists, password, [no-test-cookie])
3741 # Called from handle_session to either mark a user as logged in, or not
3744 local ($vu, $ok, $expired, $nonexist, $pass, $notest) = @_;
3745 $authuser = $vu if ($ok);
3747 # check if the test cookie is set
3748 if ($header{'cookie'} !~ /testing=1/ && $vu &&
3749 !$config{'no_testing_cookie'} && !$notest) {
3750 &http_error(500, "No cookies",
3751 "Your browser does not support cookies, ".
3752 "which are required for this web server to ".
3753 "work in session authentication mode");
3756 # check with main process for delay
3757 if ($config{'passdelay'} && $vu) {
3758 print DEBUG "handle_login: requesting delay vu=$vu acptip=$acptip ok=$ok\n";
3759 print $PASSINw "delay $vu $acptip $ok\n";
3760 <$PASSOUTr> =~ /(\d+) (\d+)/;
3763 print DEBUG "handle_login: delay=$1 blocked=$2\n";
3766 if ($ok && (!$expired ||
3767 $config{'passwd_mode'} == 1)) {
3768 # Logged in OK! Tell the main process about
3770 local $sid = &generate_random_id($pass);
3771 print DEBUG "handle_login: sid=$sid\n";
3772 print $PASSINw "new $sid $authuser $acptip\n";
3774 # Run the post-login script, if any
3775 &run_login_script($authuser, $sid,
3778 # Check for a redirect URL for the user
3779 local $rurl = &login_redirect($authuser, $pass, $host);
3780 print DEBUG "handle_login: redirect URL rurl=$rurl\n";
3782 # Got one .. go to it
3783 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3784 &write_data("Date: $datestr\r\n");
3785 &write_data("Server: $config{'server'}\r\n");
3786 &write_data("Location: $rurl\r\n");
3787 &write_keep_alive(0);
3788 &write_data("\r\n");
3789 &log_request($acpthost, $authuser, $reqline, 302, 0);
3792 # Set cookie and redirect to originally requested page
3793 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3794 &write_data("Date: $datestr\r\n");
3795 &write_data("Server: $config{'server'}\r\n");
3796 local $ssl = $use_ssl || $config{'inetd_ssl'};
3797 $portstr = $port == 80 && !$ssl ? "" :
3798 $port == 443 && $ssl ? "" : ":$port";
3799 $prot = $ssl ? "https" : "http";
3800 local $sec = $ssl ? "; secure" : "";
3801 #$sec .= "; httpOnly";
3802 if ($in{'page'} !~ /^\/[A-Za-z0-9\/\.\-\_]+$/) {
3803 # Make redirect URL safe
3807 &write_data("Set-Cookie: $sidname=$sid; path=/; expires=\"Thu, 31-Dec-2037 00:00:00\"$sec\r\n");
3810 &write_data("Set-Cookie: $sidname=$sid; path=/$sec\r\n");
3812 &write_data("Location: $prot://$host$portstr$in{'page'}\r\n");
3813 &write_keep_alive(0);
3814 &write_data("\r\n");
3815 &log_request($acpthost, $authuser, $reqline, 302, 0);
3816 syslog("info", "%s", "Successful login as $authuser from $acpthost") if ($use_syslog);
3817 &write_login_utmp($authuser, $acpthost);
3821 elsif ($ok && $expired &&
3822 ($config{'passwd_mode'} == 2 || $expired == 2)) {
3823 # Login was ok, but password has expired or was temporary. Need
3824 # to force display of password change form.
3827 $querystring = "&user=".&urlize($vu).
3829 "&expired=".$expired;
3832 $page = $config{'password_form'};
3834 $miniserv_internal = 2;
3835 syslog("crit", "%s",
3836 "Expired login as $vu ".
3837 "from $acpthost") if ($use_syslog);
3840 # Login failed, or password has expired. The login form will be
3841 # displayed again by later code
3843 $request_uri = $in{'page'};
3844 $already_session_id = undef;
3846 $authuser = $baseauthuser = undef;
3847 syslog("crit", "%s",
3848 ($nonexist ? "Non-existent" :
3849 $expired ? "Expired" : "Invalid").
3850 " login as $vu from $acpthost")
3856 # write_login_utmp(user, host)
3857 # Record the login by some user in utmp
3858 sub write_login_utmp
3861 # Write utmp record for login
3862 %utmp = ( 'ut_host' => $_[1],
3863 'ut_time' => time(),
3865 'ut_type' => 7, # user process
3866 'ut_pid' => $main_process_id,
3867 'ut_line' => $config{'pam'},
3869 if (defined(&User::Utmp::putut)) {
3870 User::Utmp::putut(\%utmp);
3873 User::Utmp::pututline(\%utmp);
3878 # write_logout_utmp(user, host)
3879 # Record the logout by some user in utmp
3880 sub write_logout_utmp
3883 # Write utmp record for logout
3884 %utmp = ( 'ut_host' => $_[1],
3885 'ut_time' => time(),
3887 'ut_type' => 8, # dead process
3888 'ut_pid' => $main_process_id,
3889 'ut_line' => $config{'pam'},
3891 if (defined(&User::Utmp::putut)) {
3892 User::Utmp::putut(\%utmp);
3895 User::Utmp::pututline(\%utmp);
3900 # pam_conversation_process(username, write-pipe, read-pipe)
3901 # This function is called inside a sub-process to communicate with PAM. It sends
3902 # questions down one pipe, and reads responses from another
3903 sub pam_conversation_process
3905 local ($user, $writer, $reader) = @_;
3906 $miniserv::pam_conversation_process_writer = $writer;
3907 $miniserv::pam_conversation_process_reader = $reader;
3908 eval "use Authen::PAM;";
3909 local $convh = new Authen::PAM(
3910 $config{'pam'}, $user, \&miniserv::pam_conversation_process_func);
3911 local $pam_ret = $convh->pam_authenticate();
3912 if ($pam_ret == PAM_SUCCESS()) {
3913 local $acct_ret = $convh->pam_acct_mgmt();
3914 if ($acct_ret == PAM_SUCCESS()) {
3915 $convh->pam_open_session();
3916 print $writer "x2 $user 1 0 0\n";
3918 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3919 $acct_ret == PAM_ACCT_EXPIRED()) {
3920 print $writer "x2 $user 1 1 0\n";
3923 print $writer "x0 Unknown PAM account status $acct_ret\n";
3927 print $writer "x2 $user 0 0 0\n";
3932 # pam_conversation_process_func(type, message, [type, message, ...])
3933 # A pipe that talks to both PAM and the master process
3934 sub pam_conversation_process_func
3937 select($miniserv::pam_conversation_process_writer); $| = 1; select(STDOUT);
3939 local ($type, $msg) = (shift, shift);
3941 local $ok = (print $miniserv::pam_conversation_process_writer "$type $msg\n");
3942 print $miniserv::pam_conversation_process_writer "\n";
3943 local $answer = <$miniserv::pam_conversation_process_reader>;
3944 $answer =~ s/\r|\n//g;
3945 push(@rv, PAM_SUCCESS(), $answer);
3947 push(@rv, PAM_SUCCESS());
3952 # Returns 4 new pipe file handles
3955 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3957 local %taken = ( (map { $_, 1 } @passin),
3958 (map { $_->{'PASSINr'} } values %conversations) );
3959 for($p=0; $taken{"PASSINr$p"}; $p++) { }
3960 $PASSINr = "PASSINr$p";
3961 $PASSINw = "PASSINw$p";
3962 $PASSOUTr = "PASSOUTr$p";
3963 $PASSOUTw = "PASSOUTw$p";
3964 pipe($PASSINr, $PASSINw);
3965 pipe($PASSOUTr, $PASSOUTw);
3966 select($PASSINw); $| = 1;
3967 select($PASSINr); $| = 1;
3968 select($PASSOUTw); $| = 1;
3969 select($PASSOUTw); $| = 1;
3971 return ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3974 # recv_pam_question(&conv, fd)
3975 # Reads one PAM question from the sub-process, and sends it to the HTTP handler.
3976 # Returns 0 if the conversation is over, 1 if not.
3977 sub recv_pam_question
3979 local ($conf, $fh) = @_;
3980 local $pr = $conf->{'PAMOUTr'};
3981 select($pr); $| = 1; select(STDOUT);
3982 local $line = <$pr>;
3983 $line =~ s/\r|\n//g;
3986 $line =~ s/\r|\n//g;
3988 $conf->{'last'} = time();
3991 print $fh "0 PAM conversation error\n";
3995 local ($type, $msg) = split(/\s+/, $line, 2);
3996 if ($type =~ /^x(\d+)/) {
3997 # Pass this status code through
3998 print $fh "$1 $msg\n";
3999 return $1 == 2 || $1 == 0 ? 0 : 1;
4001 elsif ($type == PAM_PROMPT_ECHO_ON()) {
4003 print $fh "1 $msg\n";
4006 elsif ($type == PAM_PROMPT_ECHO_OFF()) {
4008 print $fh "3 $msg\n";
4011 elsif ($type == PAM_ERROR_MSG() || $type == PAM_TEXT_INFO()) {
4012 # A message that does not require a response
4013 print $fh "4 $msg\n";
4018 print $fh "0 Unknown PAM message type $type\n";
4024 # send_pam_answer(&conv, answer)
4025 # Sends a response from the user to the PAM sub-process
4028 local ($conf, $answer) = @_;
4029 local $pw = $conf->{'PAMINw'};
4030 $conf->{'last'} = time();
4031 print $pw "$answer\n";
4034 # end_pam_conversation(&conv)
4035 # Clean up PAM conversation pipes and processes
4036 sub end_pam_conversation
4039 kill('KILL', $conv->{'pid'}) if ($conv->{'pid'});
4040 if ($conv->{'PAMINr'}) {
4041 close($conv->{'PAMINr'});
4042 close($conv->{'PAMOUTr'});
4043 close($conv->{'PAMINw'});
4044 close($conv->{'PAMOUTw'});
4046 delete($conversations{$conv->{'cid'}});
4049 # get_ipkeys(&miniserv)
4050 # Returns a list of IP address to key file mappings from a miniserv.conf entry
4054 foreach $k (keys %{$_[0]}) {
4055 if ($k =~ /^ipkey_(\S+)/) {
4056 local $ipkey = { 'ips' => [ split(/,/, $1) ],
4057 'key' => $_[0]->{$k},
4058 'index' => scalar(@rv) };
4059 $ipkey->{'cert'} = $_[0]->{'ipcert_'.$1};
4066 # create_ssl_context(keyfile, [certfile])
4067 sub create_ssl_context
4069 local ($keyfile, $certfile) = @_;
4071 eval { $ssl_ctx = Net::SSLeay::new_x_ctx() };
4072 $ssl_ctx ||= Net::SSLeay::CTX_new();
4073 $ssl_ctx || die "Failed to create SSL context : $!";
4074 if ($client_certs) {
4075 Net::SSLeay::CTX_load_verify_locations(
4076 $ssl_ctx, $config{'ca'}, "");
4077 Net::SSLeay::CTX_set_verify(
4078 $ssl_ctx, &Net::SSLeay::VERIFY_PEER, \&verify_client);
4080 if ($config{'extracas'}) {
4082 foreach $p (split(/\s+/, $config{'extracas'})) {
4083 Net::SSLeay::CTX_load_verify_locations(
4088 Net::SSLeay::CTX_use_RSAPrivateKey_file(
4090 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL key $keyfile";
4091 Net::SSLeay::CTX_use_certificate_file(
4092 $ssl_ctx, $certfile || $keyfile,
4093 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL cert $certfile";
4098 # ssl_connection_for_ip(socket, ipv6-flag)
4099 # Returns a new SSL connection object for some socket, or undef if failed
4100 sub ssl_connection_for_ip
4102 local ($sock, $ipv6) = @_;
4103 local $sn = getsockname($sock);
4105 print STDERR "Failed to get address for socket $sock\n";
4108 local (undef, $myip, undef) = &get_address_ip($sn, $ipv6);
4109 local $ssl_ctx = $ssl_contexts{$myip} || $ssl_contexts{"*"};
4110 local $ssl_con = Net::SSLeay::new($ssl_ctx);
4111 if ($config{'ssl_cipher_list'}) {
4112 # Force use of ciphers
4113 eval "Net::SSLeay::set_cipher_list(
4114 \$ssl_con, \$config{'ssl_cipher_list'})";
4116 print STDERR "SSL cipher $config{'ssl_cipher_list'} failed : ",
4122 Net::SSLeay::set_fd($ssl_con, fileno($sock));
4123 if (!Net::SSLeay::accept($ssl_con)) {
4124 print STDERR "Failed to initialize SSL connection\n";
4130 # login_redirect(username, password, host)
4131 # Calls the login redirect script (if configured), which may output a URL to
4132 # re-direct a user to after logging in.
4135 return undef if (!$config{'login_redirect'});
4136 local $quser = quotemeta($_[0]);
4137 local $qpass = quotemeta($_[1]);
4138 local $qhost = quotemeta($_[2]);
4139 local $url = `$config{'login_redirect'} $quser $qpass $qhost`;
4144 # reload_config_file()
4145 # Re-read %config, and call post-config actions
4146 sub reload_config_file
4148 &log_error("Reloading configuration");
4149 %config = &read_config_file($config_file);
4150 &update_vital_config();
4153 &build_config_mappings();
4154 &read_webmin_crons();
4155 if ($config{'session'}) {
4156 dbmclose(%sessiondb);
4157 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
4161 # read_config_file(file)
4162 # Reads the given config file, and returns a hash of values
4163 sub read_config_file
4166 open(CONF, $_[0]) || die "Failed to open config file $_[0] : $!";
4169 if (/^#/ || !/\S/) { next; }
4171 $name = $1; $val = $2;
4172 $name =~ s/^\s+//g; $name =~ s/\s+$//g;
4173 $val =~ s/^\s+//g; $val =~ s/\s+$//g;
4180 # update_vital_config()
4181 # Updates %config with defaults, and dies if something vital is missing
4182 sub update_vital_config
4184 my %vital = ("port", 80,
4186 "server", "MiniServ/0.01",
4187 "index_docs", "index.html index.htm index.cgi index.php",
4188 "addtype_html", "text/html",
4189 "addtype_txt", "text/plain",
4190 "addtype_gif", "image/gif",
4191 "addtype_jpg", "image/jpeg",
4192 "addtype_jpeg", "image/jpeg",
4193 "realm", "MiniServ",
4194 "session_login", "/session_login.cgi",
4195 "pam_login", "/pam_login.cgi",
4196 "password_form", "/password_form.cgi",
4197 "password_change", "/password_change.cgi",
4201 "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\$",
4203 "expires", 7*24*60*60,
4204 "pam_test_user", "root",
4206 foreach my $v (keys %vital) {
4208 if ($vital{$v} eq "") {
4209 die "Missing config option $v";
4211 $config{$v} = $vital{$v};
4214 if (!$config{'sessiondb'}) {
4215 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4216 $config{'sessiondb'} = "$1/sessiondb";
4218 if (!$config{'errorlog'}) {
4219 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
4220 $config{'errorlog'} = "$1/miniserv.error";
4222 if (!$config{'tempbase'}) {
4223 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4224 $config{'tempbase'} = "$1/cgitemp";
4226 if (!$config{'blockedfile'}) {
4227 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4228 $config{'blockedfile'} = "$1/blocked";
4230 if (!$config{'webmincron_dir'}) {
4231 $config_file =~ /^(.*)\/[^\/]+$/;
4232 $config{'webmincron_dir'} = "$1/webmincron/crons";
4234 if (!$config{'webmincron_last'}) {
4235 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
4236 $config{'webmincron_last'} = "$1/miniserv.lastcrons";
4238 if (!$config{'webmincron_wrapper'}) {
4239 $config{'webmincron_wrapper'} = $config{'root'}.
4240 "/webmincron/webmincron.pl";
4245 # Fills the %users and %certs hashes from the users file in %config
4254 undef(%lastchanges);
4257 if ($config{'userfile'}) {
4258 open(USERS, $config{'userfile'});
4261 local @user = split(/:/, $_, -1);
4262 $users{$user[0]} = $user[1];
4263 $certs{$user[0]} = $user[3] if ($user[3]);
4264 if ($user[4] =~ /^allow\s+(.*)/) {
4265 $allow{$user[0]} = $config{'alwaysresolve'} ?
4266 [ split(/\s+/, $1) ] :
4267 [ &to_ipaddress(split(/\s+/, $1)) ];
4269 elsif ($user[4] =~ /^deny\s+(.*)/) {
4270 $deny{$user[0]} = $config{'alwaysresolve'} ?
4271 [ split(/\s+/, $1) ] :
4272 [ &to_ipaddress(split(/\s+/, $1)) ];
4274 if ($user[5] =~ /days\s+(\S+)/) {
4275 $allowdays{$user[0]} = [ split(/,/, $1) ];
4277 if ($user[5] =~ /hours\s+(\d+)\.(\d+)-(\d+).(\d+)/) {
4278 $allowhours{$user[0]} = [ $1*60+$2, $3*60+$4 ];
4280 $lastchanges{$user[0]} = $user[6];
4281 $nochange{$user[0]} = $user[9];
4282 $temppass{$user[0]} = $user[10];
4287 # Test user DB, if configured
4288 if ($config{'userdb'}) {
4289 my $dbh = &connect_userdb($config{'userdb'});
4291 print STDERR "Failed to open users database : $dbh\n"
4294 &disconnect_userdb($config{'userdb'}, $dbh);
4299 # get_user_details(username)
4300 # Returns a hash ref of user details, either from config files or the user DB
4301 sub get_user_details
4303 my ($username) = @_;
4304 if (exists($users{$username})) {
4306 return { 'name' => $username,
4307 'pass' => $users{$username},
4308 'certs' => $certs{$username},
4309 'allow' => $allow{$username},
4310 'deny' => $deny{$username},
4311 'allowdays' => $allowdays{$username},
4312 'allowhours' => $allowhours{$username},
4313 'lastchanges' => $lastchanges{$username},
4314 'nochange' => $nochange{$username},
4315 'temppass' => $temppass{$username},
4316 'preroot' => $config{'preroot_'.$username},
4319 if ($config{'userdb'}) {
4320 # Try querying user database
4321 if (exists($get_user_details_cache{$username})) {
4323 return $get_user_details_cache{$username};
4325 print DEBUG "get_user_details: Connecting to user database\n";
4326 my ($dbh, $proto, $prefix, $args) = &connect_userdb($config{'userdb'});
4330 print DEBUG "get_user_details: Failed : $dbh\n";
4331 print STDERR "Failed to connect to user database : $dbh\n";
4333 elsif ($proto eq "mysql" || $proto eq "postgresql") {
4334 # Fetch user ID and password with SQL
4335 print DEBUG "get_user_details: Looking for $username in SQL\n";
4336 my $cmd = $dbh->prepare(
4337 "select id,pass from webmin_user where name = ?");
4338 if (!$cmd || !$cmd->execute($username)) {
4339 print STDERR "Failed to lookup user : ",
4343 my ($id, $pass) = $cmd->fetchrow();
4346 &disconnect_userdb($config{'userdb'}, $dbh);
4347 $get_user_details_cache{$username} = undef;
4348 print DEBUG "get_user_details: User not found\n";
4351 print DEBUG "get_user_details: id=$id pass=$pass\n";
4353 # Fetch attributes and add to user object
4354 print DEBUG "get_user_details: finding user attributes\n";
4355 my $cmd = $dbh->prepare(
4356 "select attr,value from webmin_user_attr where id = ?");
4357 if (!$cmd || !$cmd->execute($id)) {
4358 print STDERR "Failed to lookup user attrs : ",
4362 $user = { 'name' => $username,
4365 'proto' => $proto };
4366 while(my ($attr, $value) = $cmd->fetchrow()) {
4367 $attrs{$attr} = $value;
4371 elsif ($proto eq "ldap") {
4372 # Fetch user DN with LDAP
4373 print DEBUG "get_user_details: Looking for $username in LDAP\n";
4374 my $rv = $dbh->search(
4376 filter => '(&(cn='.$username.')(objectClass='.
4377 $args->{'userclass'}.'))',
4379 if (!$rv || $rv->code) {
4380 print STDERR "Failed to lookup user : ",
4381 ($rv ? $rv->error : "Unknown error"),"\n";
4384 my ($u) = $rv->all_entries();
4386 &disconnect_userdb($config{'userdb'}, $dbh);
4387 $get_user_details_cache{$username} = undef;
4388 print DEBUG "get_user_details: User not found\n";
4392 # Extract attributes
4393 my $pass = $u->get_value('webminPass');
4394 $user = { 'name' => $username,
4397 'proto' => $proto };
4398 foreach my $la ($u->get_value('webminAttr')) {
4399 my ($attr, $value) = split(/=/, $la, 2);
4400 $attrs{$attr} = $value;
4404 # Convert DB attributes into user object fields
4406 print DEBUG "get_user_details: got ",scalar(keys %attrs),
4408 $user->{'certs'} = $attrs{'cert'};
4409 if ($attrs{'allow'}) {
4410 $user->{'allow'} = $config{'alwaysresolve'} ?
4411 [ split(/\s+/, $attrs{'allow'}) ] :
4412 [ &to_ipaddress(split(/\s+/,$attrs{'allow'})) ];
4414 if ($attrs{'deny'}) {
4415 $user->{'deny'} = $config{'alwaysresolve'} ?
4416 [ split(/\s+/, $attrs{'deny'}) ] :
4417 [ &to_ipaddress(split(/\s+/,$attrs{'deny'})) ];
4419 if ($attrs{'days'}) {
4420 $user->{'allowdays'} = [ split(/,/, $attrs{'days'}) ];
4422 if ($attrs{'hoursfrom'} && $attrs{'hoursto'}) {
4423 my ($hf, $mf) = split(/\./, $attrs{'hoursfrom'});
4424 my ($ht, $mt) = split(/\./, $attrs{'hoursto'});
4425 $user->{'allowhours'} = [ $hf*60+$ht, $ht*60+$mt ];
4427 $user->{'lastchanges'} = $attrs{'lastchange'};
4428 $user->{'nochange'} = $attrs{'nochange'};
4429 $user->{'temppass'} = $attrs{'temppass'};
4430 $user->{'preroot'} = $attrs{'theme'};
4432 &disconnect_userdb($config{'userdb'}, $dbh);
4433 $get_user_details_cache{$user->{'name'}} = $user;
4439 # find_user_by_cert(cert)
4440 # Returns a username looked up by certificate
4441 sub find_user_by_cert
4443 my ($peername) = @_;
4444 my $peername2 = $peername;
4445 $peername2 =~ s/Email=/emailAddress=/ || $peername2 =~ s/emailAddress=/Email=/;
4447 # First check users in local files
4448 foreach my $username (keys %certs) {
4449 if ($certs{$username} eq $peername ||
4450 $certs{$username} eq $peername2) {
4456 if ($config{'userdb'}) {
4457 my ($dbh, $proto) = &connect_userdb($config{'userdb'});
4461 elsif ($proto eq "mysql" || $proto eq "postgresql") {
4463 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 = ?");
4464 return undef if (!$cmd);
4465 foreach my $p ($peername, $peername2) {
4467 if ($cmd->execute($p)) {
4468 ($username) = $cmd->fetchrow();
4471 return $username if ($username);
4474 elsif ($proto eq "ldap") {
4476 my $rv = $dbh->search(
4478 filter => '(objectClass='.
4479 $args->{'userclass'}.')',
4481 attrs => [ 'cn', 'webminAttr' ]);
4482 if ($rv && !$rv->code) {
4483 foreach my $u ($rv->all_entries) {
4484 my @attrs = $u->get_value('webminAttr');
4485 foreach my $la (@attrs) {
4486 my ($attr, $value) = split(/=/, $la, 2);
4487 if ($attr eq "cert" &&
4488 ($value eq $peername ||
4489 $value eq $peername2)) {
4490 return $u->get_value('cn');
4500 # connect_userdb(string)
4501 # Returns a handle for talking to a user database - may be a DBI or LDAP handle.
4502 # On failure returns an error message string. In an array context, returns the
4503 # protocol type too.
4507 my ($proto, $user, $pass, $host, $prefix, $args) = &split_userdb_string($str);
4508 if ($proto eq "mysql") {
4509 # Connect to MySQL with DBI
4510 my $drh = eval "use DBI; DBI->install_driver('mysql');";
4511 $drh || return $text{'sql_emysqldriver'};
4512 my ($host, $port) = split(/:/, $host);
4513 my $cstr = "database=$prefix;host=$host";
4514 $cstr .= ";port=$port" if ($port);
4515 print DEBUG "connect_userdb: Connecting to MySQL $cstr as $user\n";
4516 my $dbh = $drh->connect($cstr, $user, $pass, { });
4517 $dbh || return &text('sql_emysqlconnect', $drh->errstr);
4518 print DEBUG "connect_userdb: Connected OK\n";
4519 return wantarray ? ($dbh, $proto, $prefix, $args) : $dbh;
4521 elsif ($proto eq "postgresql") {
4522 # Connect to PostgreSQL with DBI
4523 my $drh = eval "use DBI; DBI->install_driver('Pg');";
4524 $drh || return $text{'sql_epostgresqldriver'};
4525 my ($host, $port) = split(/:/, $host);
4526 my $cstr = "dbname=$prefix;host=$host";
4527 $cstr .= ";port=$port" if ($port);
4528 print DEBUG "connect_userdb: Connecting to PostgreSQL $cstr as $user\n";
4529 my $dbh = $drh->connect($cstr, $user, $pass);
4530 $dbh || return &text('sql_epostgresqlconnect', $drh->errstr);
4531 print DEBUG "connect_userdb: Connected OK\n";
4532 return wantarray ? ($dbh, $proto, $prefix, $args) : $dbh;
4534 elsif ($proto eq "ldap") {
4535 # Connect with perl LDAP module
4536 eval "use Net::LDAP";
4537 $@ && return $text{'sql_eldapdriver'};
4538 my ($host, $port) = split(/:/, $host);
4539 my $scheme = $args->{'scheme'} || 'ldap';
4541 $port = $scheme eq 'ldaps' ? 636 : 389;
4543 my $ldap = Net::LDAP->new($host,
4545 'scheme' => $scheme);
4546 $ldap || return &text('sql_eldapconnect', $host);
4548 if ($args->{'tls'}) {
4549 # Switch to TLS mode
4550 eval { $mesg = $ldap->start_tls(); };
4551 if ($@ || !$mesg || $mesg->code) {
4552 return &text('sql_eldaptls',
4553 $@ ? $@ : $mesg ? $mesg->error : "Unknown error");
4556 # Login to the server
4558 $mesg = $ldap->bind(dn => $user, password => $pass);
4561 $mesg = $ldap->bind(dn => $user, anonymous => 1);
4563 if (!$mesg || $mesg->code) {
4564 return &text('sql_eldaplogin', $user,
4565 $mesg ? $mesg->error : "Unknown error");
4567 return wantarray ? ($ldap, $proto, $prefix, $args) : $ldap;
4570 return "Unknown protocol $proto";
4574 # split_userdb_string(string)
4575 # Converts a string like mysql://user:pass@host/db into separate parts
4576 sub split_userdb_string
4579 if ($str =~ /^([a-z]+):\/\/([^:]*):([^\@]*)\@([a-z0-9\.\-\_]+)\/([^\?]+)(\?(.*))?$/) {
4580 my ($proto, $user, $pass, $host, $prefix, $argstr) =
4581 ($1, $2, $3, $4, $5, $7);
4582 my %args = map { split(/=/, $_, 2) } split(/\&/, $argstr);
4583 return ($proto, $user, $pass, $host, $prefix, \%args);
4588 # disconnect_userdb(string, &handle)
4589 # Closes a handle opened by connect_userdb
4590 sub disconnect_userdb
4593 if ($str =~ /^(mysql|postgresql):/) {
4597 elsif ($str =~ /^ldap:/) {
4604 # Fills %mime with entries from file in %config and extra settings in %config
4608 if ($config{"mimetypes"} ne "") {
4609 open(MIME, $config{"mimetypes"});
4612 if (/^(\S+)\s+(.*)$/) {
4614 my @exts = split(/\s+/, $2);
4615 foreach my $ext (@exts) {
4616 $mime{$ext} = $type;
4622 foreach my $k (keys %config) {
4623 if ($k !~ /^addtype_(.*)$/) { next; }
4624 $mime{$1} = $config{$k};
4628 # build_config_mappings()
4629 # Build the anonymous access list, IP access list, unauthenticated URLs list,
4630 # redirect mapping and allow and deny lists from %config
4631 sub build_config_mappings
4633 # build anonymous access list
4635 foreach my $a (split(/\s+/, $config{'anonymous'})) {
4636 if ($a =~ /^([^=]+)=(\S+)$/) {
4637 $anonymous{$1} = $2;
4641 # build IP access list
4643 foreach my $a (split(/\s+/, $config{'ipaccess'})) {
4644 if ($a =~ /^([^=]+)=(\S+)$/) {
4649 # build unauthenticated URLs list
4650 @unauth = split(/\s+/, $config{'unauth'});
4652 # build redirect mapping
4654 foreach my $r (split(/\s+/, $config{'redirect'})) {
4655 if ($r =~ /^([^=]+)=(\S+)$/) {
4660 # build prefixes to be stripped
4661 undef(@strip_prefix);
4662 foreach my $r (split(/\s+/, $config{'strip_prefix'})) {
4663 push(@strip_prefix, $r);
4666 # Init allow and deny lists
4667 @deny = split(/\s+/, $config{"deny"});
4668 @deny = &to_ipaddress(@deny) if (!$config{'alwaysresolve'});
4669 @allow = split(/\s+/, $config{"allow"});
4670 @allow = &to_ipaddress(@allow) if (!$config{'alwaysresolve'});
4673 if ($config{'allowusers'}) {
4674 @allowusers = split(/\s+/, $config{'allowusers'});
4676 elsif ($config{'denyusers'}) {
4677 @denyusers = split(/\s+/, $config{'denyusers'});
4680 # Build list of unixauth mappings
4682 foreach my $ua (split(/\s+/, $config{'unixauth'})) {
4683 if ($ua =~ /^(\S+)=(\S+)$/) {
4687 $unixauth{"*"} = $ua;
4691 # Build list of non-session-auth pages
4692 undef(%sessiononly);
4693 foreach my $sp (split(/\s+/, $config{'sessiononly'})) {
4694 $sessiononly{$sp} = 1;
4697 # Build list of logout times
4698 undef(@logouttimes);
4699 foreach my $a (split(/\s+/, $config{'logouttimes'})) {
4700 if ($a =~ /^([^=]+)=(\S+)$/) {
4701 push(@logouttimes, [ $1, $2 ]);
4704 push(@logouttimes, [ undef, $config{'logouttime'} ]);
4706 # Build list of DAV pathss
4708 foreach my $d (split(/\s+/, $config{'davpaths'})) {
4709 push(@davpaths, $d);
4711 @davusers = split(/\s+/, $config{'dav_users'});
4713 # Mobile agent substrings and hostname prefixes
4714 @mobile_agents = split(/\t+/, $config{'mobile_agents'});
4715 @mobile_prefixes = split(/\s+/, $config{'mobile_prefixes'});
4719 if ($config{'debug'}) {
4720 open(DEBUG, ">>$config{'debug'}");
4723 open(DEBUG, ">/dev/null");
4726 # Reset cache of sudo checks
4730 # is_group_member(&uinfo, groupname)
4731 # Returns 1 if some user is a primary or secondary member of a group
4734 local ($uinfo, $group) = @_;
4735 local @ginfo = getgrnam($group);
4736 return 0 if (!@ginfo);
4737 return 1 if ($ginfo[2] == $uinfo->[3]); # primary member
4738 foreach my $m (split(/\s+/, $ginfo[3])) {
4739 return 1 if ($m eq $uinfo->[0]);
4744 # prefix_to_mask(prefix)
4745 # Converts a number like 24 to a mask like 255.255.255.0
4748 return $_[0] >= 24 ? "255.255.255.".(256-(2 ** (32-$_[0]))) :
4749 $_[0] >= 16 ? "255.255.".(256-(2 ** (24-$_[0]))).".0" :
4750 $_[0] >= 8 ? "255.".(256-(2 ** (16-$_[0]))).".0.0" :
4751 (256-(2 ** (8-$_[0]))).".0.0.0";
4754 # get_logout_time(user, session-id)
4755 # Given a username, returns the idle time before he will be logged out
4758 local ($user, $sid) = @_;
4759 if (!defined($logout_time_cache{$user,$sid})) {
4761 foreach my $l (@logouttimes) {
4762 if ($l->[0] =~ /^\@(.*)$/) {
4763 # Check group membership
4764 local @uinfo = getpwnam($user);
4765 if (@uinfo && &is_group_member(\@uinfo, $1)) {
4769 elsif ($l->[0] =~ /^\//) {
4770 # Check file contents
4771 open(FILE, $l->[0]);
4788 if ($l->[0] eq $user) {
4792 last if (defined($time));
4794 $logout_time_cache{$user,$sid} = $time;
4796 return $logout_time_cache{$user,$sid};
4799 # password_crypt(password, salt)
4800 # If the salt looks like MD5 and we have a library for it, perform MD5 hashing
4801 # of a password. Otherwise, do Unix crypt.
4804 local ($pass, $salt) = @_;
4805 if ($salt =~ /^\$1\$/ && $use_md5) {
4806 return &encrypt_md5($pass, $salt);
4809 return &unix_crypt($pass, $salt);
4813 # unix_crypt(password, salt)
4814 # Performs standard Unix hashing for a password
4817 local ($pass, $salt) = @_;
4818 if ($use_perl_crypt) {
4819 return Crypt::UnixCrypt::crypt($pass, $salt);
4822 return crypt($pass, $salt);
4826 # handle_dav_request(davpath)
4827 # Pass a request on to the Net::DAV::Server module
4828 sub handle_dav_request
4831 eval "use Filesys::Virtual::Plain";
4832 eval "use Net::DAV::Server";
4833 eval "use HTTP::Request";
4834 eval "use HTTP::Headers";
4836 if ($Net::DAV::Server::VERSION eq '1.28' && $config{'dav_nolock'}) {
4837 delete $Net::DAV::Server::implemented{lock};
4838 delete $Net::DAV::Server::implemented{unlock};
4841 # Read in request data
4842 if (!$posted_data) {
4843 local $clen = $header{"content-length"};
4844 while(length($posted_data) < $clen) {
4845 $buf = &read_data($clen - length($posted_data));
4846 if (!length($buf)) {
4847 &http_error(500, "Failed to read POST request");
4849 $posted_data .= $buf;
4853 # For subsequent logging
4854 open(MINISERVLOG, ">>$config{'logfile'}");
4858 local @u = getpwnam($authuser);
4859 if ($config{'dav_remoteuser'} && !$< && $validated) {
4862 $( = $u[3]; $) = "$u[3] $u[3]";
4863 ($>, $<) = ($u[2], $u[2]);
4865 if ($config{'dav_root'} eq '*') {
4870 &http_error(500, "Unix user $authuser does not exist");
4874 $root ||= $config{'dav_root'};
4877 # Check if this user can use DAV
4879 &users_match(\@u, @davusers) ||
4880 &http_error(500, "You are not allowed to access DAV");
4884 my $filesys = Filesys::Virtual::Plain->new({root_path => $root});
4885 my $webdav = Net::DAV::Server->new();
4886 $webdav->filesys($filesys);
4888 # Make up a request object, and feed to DAV
4889 local $ho = HTTP::Headers->new;
4890 foreach my $h (keys %header) {
4891 next if (lc($h) eq "connection");
4892 $ho->header($h => $header{$h});
4895 $request_uri =~ s/^\Q$path\E//;
4896 $request_uri = "/" if ($request_uri eq "");
4898 my $request = HTTP::Request->new($method, $request_uri, $ho,
4900 if ($config{'dav_debug'}) {
4901 print STDERR "DAV request :\n";
4902 print STDERR "---------------------------------------------\n";
4903 print STDERR $request->as_string();
4904 print STDERR "---------------------------------------------\n";
4906 my $response = $webdav->run($request);
4908 # Send back the reply
4909 &write_data("HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n");
4910 local $content = $response->content();
4912 $content =~ s|href>/(.+)<|href>$path/$1<|g;
4913 $content =~ s|href>/<|href>$path<|g;
4915 foreach my $h ($response->header_field_names) {
4916 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4917 &write_data("$h: ",$response->header($h),"\r\n");
4919 &write_data("Content-length: ",length($content),"\r\n");
4920 local $rv = &write_keep_alive(0);
4921 &write_data("\r\n");
4922 &write_data($content);
4924 if ($config{'dav_debug'}) {
4925 print STDERR "DAV reply :\n";
4926 print STDERR "---------------------------------------------\n";
4927 print STDERR "HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n";
4928 foreach my $h ($response->header_field_names) {
4929 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4930 print STDERR "$h: ",$response->header($h),"\r\n";
4932 print STDERR "Content-length: ",length($content),"\r\n";
4933 print STDERR "\r\n";
4934 print STDERR $content;
4935 print STDERR "---------------------------------------------\n";
4939 &log_request($acpthost, $authuser, $reqline, $response->code(),
4940 length($response->content()));
4943 # get_system_hostname()
4944 # Returns the hostname of this system, for reporting to listeners
4945 sub get_system_hostname
4947 # On Windows, try computername environment variable
4948 return $ENV{'computername'} if ($ENV{'computername'});
4949 return $ENV{'COMPUTERNAME'} if ($ENV{'COMPUTERNAME'});
4951 # If a specific command is set, use it first
4952 if ($config{'hostname_command'}) {
4953 local $out = `($config{'hostname_command'}) 2>&1`;
4960 # First try the hostname command
4961 local $out = `hostname 2>&1`;
4962 if (!$? && $out =~ /\S/) {
4967 # Try the Sys::Hostname module
4968 eval "use Sys::Hostname";
4970 local $rv = eval "hostname()";
4976 # Must use net name on Windows
4977 local $out = `net name 2>&1`;
4978 if ($out =~ /\-+\r?\n(\S+)/) {
4985 # indexof(string, array)
4986 # Returns the index of some value in an array, or -1
4989 for($i=1; $i <= $#_; $i++) {
4990 if ($_[$i] eq $_[0]) { return $i - 1; }
4996 # has_command(command)
4997 # Returns the full path if some command is in the path, undef if not
5001 if (!$_[0]) { return undef; }
5002 if (exists($has_command_cache{$_[0]})) {
5003 return $has_command_cache{$_[0]};
5006 if ($_[0] =~ /^\//) {
5007 $rv = -x $_[0] ? $_[0] : undef;
5010 local $sp = $on_windows ? ';' : ':';
5011 foreach $d (split($sp, $ENV{PATH})) {
5012 if (-x "$d/$_[0]") {
5017 foreach my $sfx (".exe", ".com", ".bat") {
5018 if (-r "$d/$_[0]".$sfx) {
5019 $rv = "$d/$_[0]".$sfx;
5026 $has_command_cache{$_[0]} = $rv;
5030 # check_sudo_permissions(user, pass)
5031 # Returns 1 if some user can run any command via sudo
5032 sub check_sudo_permissions
5034 local ($user, $pass) = @_;
5036 # First try the pipes
5038 print DEBUG "check_sudo_permissions: querying cache for $user\n";
5039 print $PASSINw "readsudo $user\n";
5040 local $can = <$PASSOUTr>;
5042 print DEBUG "check_sudo_permissions: cache said $can\n";
5043 if ($can =~ /^\d+$/ && $can != 2) {
5048 local $ptyfh = new IO::Pty;
5049 print DEBUG "check_sudo_permissions: ptyfh=$ptyfh\n";
5051 print STDERR "Failed to create new PTY with IO::Pty\n";
5054 local @uinfo = getpwnam($user);
5056 print STDERR "Unix user $user does not exist for sudo\n";
5060 # Execute sudo in a sub-process, via a pty
5061 local $ttyfh = $ptyfh->slave();
5062 print DEBUG "check_sudo_permissions: ttyfh=$ttyfh\n";
5063 local $tty = $ptyfh->ttyname();
5064 print DEBUG "check_sudo_permissions: tty=$tty\n";
5065 chown($uinfo[2], $uinfo[3], $tty);
5067 print DEBUG "check_sudo_permissions: about to fork..\n";
5068 local $pid = fork();
5069 print DEBUG "check_sudo_permissions: fork=$pid pid=$$\n";
5071 print STDERR "fork for sudo failed : $!\n";
5076 $ptyfh->make_slave_controlling_terminal();
5077 close(STDIN); close(STDOUT); close(STDERR);
5078 untie(*STDIN); untie(*STDOUT); untie(*STDERR);
5079 close($PASSINw); close($PASSOUTr);
5080 $( = $uinfo[3]; $) = "$uinfo[3] $uinfo[3]";
5081 ($>, $<) = ($uinfo[2], $uinfo[2]);
5086 open(STDIN, "<&SUDOr");
5087 open(STDOUT, ">$tty");
5088 open(STDERR, ">&STDOUT");
5091 print "Exec failed : $!\n";
5094 print DEBUG "check_sudo_permissions: pid=$pid\n";
5096 $ptyfh->close_slave();
5098 # Send password, and get back response
5099 local $oldfh = select(SUDOw);
5102 print DEBUG "check_sudo_permissions: about to send pass\n";
5103 local $SIG{'PIPE'} = 'ignore'; # Sometimes sudo doesn't ask for a password
5104 print SUDOw $pass,"\n";
5105 print DEBUG "check_sudo_permissions: sent pass=$pass\n";
5109 print DEBUG "check_sudo_permissions: got $_";
5115 local ($ok) = ($out =~ /\(ALL\)\s+ALL/ ? 1 : 0);
5119 print $PASSINw "writesudo $user $ok\n";
5125 # is_mobile_useragent(agent)
5126 # Returns 1 if some user agent looks like a cellphone or other mobile device,
5128 sub is_mobile_useragent
5130 local ($agent) = @_;
5132 "UP.Link", # Openwave
5133 "Nokia", # All Nokias start with Nokia
5134 "MOT-", # All Motorola phones start with MOT-
5135 "SAMSUNG", # Samsung browsers
5136 "Samsung", # Samsung browsers
5137 "SEC-", # Samsung browsers
5138 "AU-MIC", # Samsung browsers
5139 "AUDIOVOX", # Audiovox
5140 "BlackBerry", # BlackBerry
5141 "hiptop", # Danger hiptop Sidekick
5142 "SonyEricsson", # Sony Ericsson
5143 "Ericsson", # Old Ericsson browsers , mostly WAP
5144 "Mitsu/1.1.A", # Mitsubishi phones
5145 "Panasonic WAP", # Panasonic old WAP phones
5146 "DoCoMo", # DoCoMo phones
5147 "Lynx", # Lynx text-mode linux browser
5148 "Links", # Another text-mode linux browser
5150 local @substrings = (
5151 "UP.Browser", # Openwave
5152 "MobilePhone", # NetFront
5153 "AU-MIC-A700", # Samsung A700 Obigo browsers
5154 "Danger hiptop", # Danger Sidekick hiptop
5155 "Windows CE", # Windows CE Pocket PC
5156 "IEMobile", # Windows mobile browser
5157 "Blazer", # Palm Treo Blazer
5158 "BlackBerry", # BlackBerries can emulate other browsers, but
5159 # they still keep this string in the UserAgent
5160 "SymbianOS", # New Series60 browser has safari in it and
5161 # SymbianOS is the only distinguishing string
5162 "iPhone", # Apple iPhone KHTML browser
5163 "iPod", # iPod touch browser
5164 "MobileSafari", # HTTP client in iPhone
5166 "Opera Mini", # Opera Mini
5167 "HTC_P3700", # HTC mobile device
5169 "webOS/", # Palm WebOS
5170 "Nintendo DS", # DSi / DSi-XL
5172 foreach my $p (@prefixes) {
5173 return 1 if ($agent =~ /^\Q$p\E/);
5175 foreach my $s (@substrings, @mobile_agents) {
5176 return 1 if ($agent =~ /\Q$s\E/);
5181 # write_blocked_file()
5182 # Writes out a text file of blocked hosts and users
5183 sub write_blocked_file
5185 open(BLOCKED, ">$config{'blockedfile'}");
5186 foreach my $d (grep { $hostfail{$_} } @deny) {
5187 print BLOCKED "host $d $hostfail{$d} $blockhosttime{$d}\n";
5189 foreach my $d (grep { $userfail{$_} } @denyusers) {
5190 print BLOCKED "user $d $userfail{$d} $blockusertime{$d}\n";
5193 chmod(0700, $config{'blockedfile'});
5198 open(PIDFILE, ">$config{'pidfile'}");
5199 printf PIDFILE "%d\n", getpid();
5201 $miniserv_main_pid = getpid();
5204 # lock_user_password(user)
5205 # Updates a user's password file entry to lock it, both in memory and on disk.
5206 # Returns 1 if done, -1 if no such user, 0 if already locked
5207 sub lock_user_password
5210 local $uinfo = &get_user_details($user);
5215 if ($uinfo->{'pass'} =~ /^\!/) {
5219 if (!$uinfo->{'proto'}) {
5220 # Write to users file
5221 $users{$user} = "!".$users{$user};
5222 open(USERS, $config{'userfile'});
5223 local @ufile = <USERS>;
5225 foreach my $u (@ufile) {
5226 local @uinfo = split(/:/, $u);
5227 if ($uinfo[0] eq $user) {
5228 $uinfo[1] = $users{$user};
5230 $u = join(":", @uinfo);
5232 open(USERS, ">$config{'userfile'}");
5238 if ($config{'userdb'}) {
5240 my ($dbh, $proto, $prefix, $args) = &connect_userdb($config{'userdb'});
5244 elsif ($proto eq "mysql" || $proto eq "postgresql") {
5245 # Update user attribute
5246 my $cmd = $dbh->prepare(
5247 "update webmin_user set pass = ? where id = ?");
5248 if (!$cmd || !$cmd->execute("!".$uinfo->{'pass'},
5251 print STDERR "Failed to lock password : ",
5255 $cmd->finish() if ($cmd);
5257 elsif ($proto eq "ldap") {
5258 # Update LDAP object
5259 my $rv = $dbh->modify($uinfo->{'id'},
5260 replace => { 'webminPass' => '!'.$uinfo->{'pass'} });
5261 if (!$rv || $rv->code) {
5262 print STDERR "Failed to lock password : ",
5263 ($rv ? $rv->error : "Unknown error"),"\n";
5267 &disconnect_userdb($config{'userdb'}, $dbh);
5271 return -1; # This should never be reached
5274 # hash_session_id(sid)
5275 # Returns an MD5 or Unix-crypted session ID
5279 if (!$hash_session_id_cache{$sid}) {
5282 $hash_session_id_cache{$sid} = &encrypt_md5($sid);
5286 $hash_session_id_cache{$sid} = &unix_crypt($sid, "XX");
5289 return $hash_session_id_cache{$sid};
5292 # encrypt_md5(string, [salt])
5293 # Returns a string encrypted in MD5 format
5296 local ($passwd, $salt) = @_;
5297 local $magic = '$1$';
5298 if ($salt =~ /^\$1\$([^\$]+)/) {
5299 # Extract actual salt from already encrypted password
5304 local $ctx = eval "new $use_md5";
5311 # Add some more stuff from the hash of the password and salt
5312 local $ctx1 = eval "new $use_md5";
5313 $ctx1->add($passwd);
5317 $ctx1->add($passwd);
5318 local $final = $ctx1->digest();
5319 for($pl=length($passwd); $pl>0; $pl-=16) {
5320 $ctx->add($pl > 16 ? $final : substr($final, 0, $pl));
5323 # This piece of code seems rather pointless, but it's in the C code that
5324 # does MD5 in PAM so it has to go in!
5327 for($i=length($passwd); $i; $i >>= 1) {
5332 $ctx->add(substr($passwd, $j, 1));
5335 $final = $ctx->digest();
5338 # This loop exists only to waste time
5339 for($i=0; $i<1000; $i++) {
5340 $ctx1 = eval "new $use_md5";
5341 $ctx1->add($i & 1 ? $passwd : $final);
5342 $ctx1->add($salt) if ($i % 3);
5343 $ctx1->add($passwd) if ($i % 7);
5344 $ctx1->add($i & 1 ? $final : $passwd);
5345 $final = $ctx1->digest();
5349 # Convert the 16-byte final string into a readable form
5351 local @final = map { ord($_) } split(//, $final);
5352 $l = ($final[ 0]<<16) + ($final[ 6]<<8) + $final[12];
5353 $rv .= &to64($l, 4);
5354 $l = ($final[ 1]<<16) + ($final[ 7]<<8) + $final[13];
5355 $rv .= &to64($l, 4);
5356 $l = ($final[ 2]<<16) + ($final[ 8]<<8) + $final[14];
5357 $rv .= &to64($l, 4);
5358 $l = ($final[ 3]<<16) + ($final[ 9]<<8) + $final[15];
5359 $rv .= &to64($l, 4);
5360 $l = ($final[ 4]<<16) + ($final[10]<<8) + $final[ 5];
5361 $rv .= &to64($l, 4);
5363 $rv .= &to64($l, 2);
5365 # Add salt if needed
5367 return $magic.$salt.'$'.$rv;
5376 local ($v, $n) = @_;
5379 $r .= $itoa64[$v & 0x3f];
5385 # read_file(file, &assoc, [&order], [lowercase])
5386 # Fill an associative array with name=value pairs from a file
5389 open(ARFILE, $_[0]) || return 0;
5392 if (!/^#/ && /^([^=]*)=(.*)$/) {
5393 $_[1]->{$_[3] ? lc($1) : $1} = $2;
5394 push(@{$_[2]}, $1) if ($_[2]);
5401 # write_file(file, array)
5402 # Write out the contents of an associative array as name=value lines
5405 local(%old, @order);
5406 &read_file($_[0], \%old, \@order);
5407 open(ARFILE, ">$_[0]");
5408 foreach $k (@order) {
5409 print ARFILE $k,"=",$_[1]->{$k},"\n" if (exists($_[1]->{$k}));
5411 foreach $k (keys %{$_[1]}) {
5412 print ARFILE $k,"=",$_[1]->{$k},"\n" if (!exists($old{$k}));
5417 # execute_ready_webmin_crons()
5418 # Find and run any cron jobs that are due, based on their last run time and
5419 # execution interval
5420 sub execute_ready_webmin_crons
5424 foreach my $cron (@webmincrons) {
5426 if (!$webmincron_last{$cron->{'id'}}) {
5427 # If not ever run before, don't run right away
5428 $webmincron_last{$cron->{'id'}} = $now;
5431 elsif ($cron->{'interval'} &&
5432 $now - $webmincron_last{$cron->{'id'}} > $cron->{'interval'}) {
5433 # Older than interval .. time to run
5436 elsif ($cron->{'mins'}) {
5437 # Check if current time matches spec, and we haven't run in the
5439 my @tm = localtime($now);
5440 if (&matches_cron($cron->{'mins'}, $tm[1]) &&
5441 &matches_cron($cron->{'hours'}, $tm[2]) &&
5442 &matches_cron($cron->{'days'}, $tm[3]) &&
5443 &matches_cron($cron->{'months'}, $tm[4]+1) &&
5444 &matches_cron($cron->{'weekdays'}, $tm[6]) &&
5445 $now - $webmincron_last{$cron->{'id'}} > 60) {
5451 print DEBUG "Running cron id=$cron->{'id'} ".
5452 "module=$cron->{'module'} func=$cron->{'func'}\n";
5453 $webmincron_last{$cron->{'id'}} = $now;
5457 # Run via a wrapper command, which we run like a CGI
5458 dbmclose(%sessiondb);
5460 # Setup CGI-like environment
5461 $envtz = $ENV{"TZ"};
5462 $envuser = $ENV{"USER"};
5463 $envpath = $ENV{"PATH"};
5464 $envlang = $ENV{"LANG"};
5465 $envroot = $ENV{"SystemRoot"};
5466 $envperllib = $ENV{'PERLLIB'};
5467 foreach my $k (keys %ENV) {
5470 $ENV{"PATH"} = $envpath if ($envpath);
5471 $ENV{"TZ"} = $envtz if ($envtz);
5472 $ENV{"USER"} = $envuser if ($envuser);
5473 $ENV{"OLD_LANG"} = $envlang if ($envlang);
5474 $ENV{"SystemRoot"} = $envroot if ($envroot);
5475 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
5476 $ENV{"HOME"} = $user_homedir;
5477 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
5478 $ENV{"SERVER_ADMIN"} = $config{"email"};
5480 $ENV{"SERVER_ROOT"} = $root0;
5481 $ENV{"SERVER_REALROOT"} = $root0;
5482 $ENV{"SERVER_PORT"} = $config{'port'};
5483 $ENV{"WEBMIN_CRON"} = 1;
5484 $ENV{"DOCUMENT_ROOT"} = $root0;
5485 $ENV{"DOCUMENT_REALROOT"} = $root0;
5486 $ENV{"MINISERV_CONFIG"} = $config_file;
5487 $ENV{"HTTPS"} = "ON" if ($use_ssl);
5488 $ENV{"MINISERV_PID"} = $miniserv_main_pid;
5489 $ENV{"SCRIPT_FILENAME"} = $config{'webmincron_wrapper'};
5490 if ($ENV{"SCRIPT_FILENAME"} =~ /^\Q$root0\E(\/.*)$/) {
5491 $ENV{"SCRIPT_NAME"} = $1;
5493 $config{'webmincron_wrapper'} =~ /^(.*)\//;
5495 foreach $k (keys %config) {
5496 if ($k =~ /^env_(\S+)$/) {
5497 $ENV{$1} = $config{$k};
5501 $SIG{'CHLD'} = 'DEFAULT';
5503 # Have SOCK closed if the perl exec's something
5505 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
5508 # Run the wrapper script by evaling it
5509 $pkg = "webmincron";
5510 $0 = $config{'webmincron_wrapper'};
5512 $main_process_id = $$;
5516 do \$miniserv::config{'webmincron_wrapper'};
5520 print STDERR "Perl cron failure : $@\n";
5525 push(@childpids, $pid);
5529 # Write out file containing last run times
5530 &write_file($config{'webmincron_last'}, \%webmincron_last);
5534 # matches_cron(cron-spec, time)
5535 # Checks if some minute or hour matches some cron spec, which can be * or a list
5539 my ($spec, $tm) = @_;
5544 foreach my $s (split(/,/, $spec)) {
5546 $s =~ /^(\d+)\-(\d+)$/ && $tm >= $1 && $tm <= $2) {
5554 # read_webmin_crons()
5555 # Read all scheduled webmin cron functions and store them in the @webmincrons
5557 sub read_webmin_crons
5560 opendir(CRONS, $config{'webmincron_dir'});
5561 print DEBUG "Reading crons from $config{'webmincron_dir'}\n";
5562 foreach my $f (readdir(CRONS)) {
5563 if ($f =~ /^(\d+)\.cron$/) {
5565 &read_file("$config{'webmincron_dir'}/$f", \%cron);
5568 foreach my $n ('module', 'func') {
5570 print STDERR "Cron $1 missing $n\n";
5574 if (!$cron{'interval'} && !$cron{'mins'} && !$cron{'special'}) {
5575 print STDERR "Cron $1 missing any time spec\n";
5578 if ($cron{'special'} eq 'hourly') {
5579 # Run every hour on the hour
5581 $cron{'hours'} = '*';
5582 $cron{'days'} = '*';
5583 $cron{'months'} = '*';
5584 $cron{'weekdays'} = '*';
5586 elsif ($cron{'special'} eq 'daily') {
5587 # Run every day at midnight
5589 $cron{'hours'} = '0';
5590 $cron{'days'} = '*';
5591 $cron{'months'} = '*';
5592 $cron{'weekdays'} = '*';
5594 elsif ($cron{'special'} eq 'monthly') {
5595 # Run every month on the 1st
5597 $cron{'hours'} = '0';
5598 $cron{'days'} = '1';
5599 $cron{'months'} = '*';
5600 $cron{'weekdays'} = '*';
5602 elsif ($cron{'special'} eq 'weekly') {
5603 # Run every month on the 1st
5605 $cron{'hours'} = '0';
5606 $cron{'days'} = '*';
5607 $cron{'months'} = '*';
5608 $cron{'weekdays'} = '0';
5610 elsif ($cron{'special'} eq 'yearly' ||
5611 $cron{'special'} eq 'annually') {
5612 # Run every year on 1st january
5614 $cron{'hours'} = '0';
5615 $cron{'days'} = '1';
5616 $cron{'months'} = '1';
5617 $cron{'weekdays'} = '*';
5619 elsif ($cron{'special'}) {
5620 print STDERR "Cron $1 invalid special time $cron{'special'}\n";
5623 if ($cron{'special'}) {
5624 delete($cron{'special'});
5627 print DEBUG "adding cron id=$cron{'id'} module=$cron{'module'} func=$cron{'func'}\n";
5628 push(@webmincrons, \%cron);
5634 # Check if some address is valid IPv4, returns 1 if so.
5637 return $_[0] =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/ &&
5638 $1 >= 0 && $1 <= 255 &&
5639 $2 >= 0 && $2 <= 255 &&
5640 $3 >= 0 && $3 <= 255 &&
5641 $4 >= 0 && $4 <= 255;
5644 # Check if some IPv6 address is properly formatted, and returns 1 if so.
5645 sub check_ip6address
5647 my @blocks = split(/:/, $_[0]);
5648 return 0 if (@blocks == 0 || @blocks > 8);
5650 my $where = index($blocks[$ib],"/");
5653 my $b = substr($blocks[$ib],0,$where);
5654 $m = substr($blocks[$ib],$where+1,length($blocks[$ib])-($where+1));
5657 return 0 if ($m <0 || $m >128);
5660 foreach $b (@blocks) {
5661 return 0 if ($b ne "" && $b !~ /^[0-9a-f]{1,4}$/i);
5662 $empty++ if ($b eq "");
5664 return 0 if ($empty > 1 && !($_[0] =~ /^::/ && $empty == 2));
5668 # network_to_address(binary)
5669 # Given a network address in binary IPv4 or v4 format, return the string form
5670 sub network_to_address
5673 if (length($addr) == 4 || !$use_ipv6) {
5674 return inet_ntoa($addr);
5677 return Socket6::inet_ntop(Socket6::AF_INET6(), $addr);