2 # A very simple perl web server used by Webmin
4 # Require basic libraries
10 @itoa64 = split(//, "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
12 # Find and read config file
14 die "Usage: miniserv.pl <config file>";
16 if ($ARGV[0] =~ /^([a-z]:)?\//i) {
17 $config_file = $ARGV[0];
21 $config_file = "$pwd/$ARGV[0]";
23 %config = &read_config_file($config_file);
24 if ($config{'perllib'}) {
25 push(@INC, split(/:/, $config{'perllib'}));
26 $ENV{'PERLLIB'} .= ':'.$config{'perllib'};
30 # Check if SSL is enabled and available
32 eval "use Net::SSLeay";
35 # These functions only exist for SSLeay 1.0
36 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
37 eval "Net::SSLeay::load_error_strings()";
38 if ($config{'no_ssl2'}) {
39 eval "Net::SSLeay::CTX_set_options($ctx,&Net::SSLeay::OP_NO_SSLv2)";
41 if (defined(&Net::SSLeay::X509_STORE_CTX_get_current_cert) &&
42 defined(&Net::SSLeay::CTX_load_verify_locations) &&
43 defined(&Net::SSLeay::CTX_set_verify)) {
49 # Check if IPv6 is enabled and available
50 if ($config{'ipv6'}) {
53 push(@startup_msg, "IPv6 support enabled");
57 push(@startup_msg, "IPv6 support cannot be enabled without ".
58 "the Socket6 perl module");
62 # Check if the syslog module is available to log hacking attempts
63 if ($config{'syslog'} && !$config{'inetd'}) {
64 eval "use Sys::Syslog qw(:DEFAULT setlogsock)";
70 # check if the TCP-wrappers module is available
71 if ($config{'libwrap'}) {
72 eval "use Authen::Libwrap qw(hosts_ctl STRING_UNKNOWN)";
78 # Check if the MD5 perl module is available
84 eval "use Digest::MD5";
86 $use_md5 = "Digest::MD5";
90 # Get miniserv's perl path and location
92 open(SOURCE, $miniserv_path);
93 <SOURCE> =~ /^#!(\S+)/;
100 $linked_perl_path = readlink($perl_path);
102 @miniserv_argv = @ARGV;
104 # Check vital config options
105 &update_vital_config();
107 $sidname = $config{'sidname'};
108 die "Session authentication cannot be used in inetd mode"
109 if ($config{'inetd'} && $config{'session'});
111 # check if the PAM module is available to authenticate
112 if ($config{'assume_pam'}) {
113 # Just assume that it will work. This can also be used to work around
114 # a Solaris bug in which using PAM before forking caused it to fail
118 elsif (!$config{'no_pam'}) {
119 eval "use Authen::PAM;";
121 # check if the PAM authentication can be used by opening a
124 if (ref($pamh = new Authen::PAM($config{'pam'},
125 $config{'pam_test_user'},
127 # Now test a login to see if /etc/pam.d/webmin is set
129 $pam_conv_func_called = 0;
130 $pam_username = "test";
131 $pam_password = "test";
132 $pamh->pam_authenticate();
133 if ($pam_conv_func_called) {
135 "PAM authentication enabled");
140 "PAM test failed - maybe ".
141 "/etc/pam.d/$config{'pam'} does not exist");
146 "PAM initialization of Authen::PAM failed");
151 "Perl module Authen::PAM needed for PAM is ".
152 "not installed : $@");
155 if ($config{'pam_only'} && !$use_pam) {
156 print STDERR $startup_msg[0],"\n";
157 print STDERR "PAM use is mandatory, but could not be enabled!\n";
160 elsif ($pam_msg && !$use_pam) {
162 "Continuing without the Authen::PAM perl module");
165 # Check if the User::Utmp perl module is installed
166 if ($config{'utmp'}) {
167 eval "use User::Utmp;";
170 push(@startup_msg, "UTMP logging enabled");
174 "Perl module User::Utmp needed for Utmp logging is ".
175 "not installed : $@");
179 # See if the crypt function fails
180 eval "crypt('foo', 'xx')";
182 eval "use Crypt::UnixCrypt";
186 "Using Crypt::UnixCrypt for password encryption");
190 "crypt() function un-implemented, and Crypt::UnixCrypt ".
191 "not installed - password authentication will fail");
195 # Check if /dev/urandom really generates random IDs, by calling it twice
196 local $rand1 = &generate_random_id("foo", 1);
197 local $rand2 = &generate_random_id("foo", 2);
198 if ($rand1 eq $rand2) {
201 "Random number generator file /dev/urandom is not reliable");
204 # Check if we can call sudo
205 if ($config{'sudo'} && &has_command("sudo")) {
212 "Perl module IO::Pty needed for calling sudo is not ".
217 # init days and months for http_date
218 @weekday = ( "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" );
219 @month = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun",
220 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" );
222 # Change dir to the server root
223 @roots = ( $config{'root'} );
224 for($i=0; defined($config{"extraroot_$i"}); $i++) {
225 push(@roots, $config{"extraroot_$i"});
228 eval { $user_homedir = (getpwuid($<))[7]; };
230 # getpwuid doesn't work on windows
231 $user_homedir = $ENV{"HOME"} || $ENV{"USERPROFILE"} || "/";
238 # Setup SSL if possible and if requested
239 if (!-r $config{'keyfile'} ||
240 $config{'certfile'} && !-r $config{'certfile'}) {
241 # Key file doesn't exist!
244 @ipkeys = &get_ipkeys(\%config);
246 if ($config{'ssl_version'}) {
247 # Force an SSL version
248 $Net::SSLeay::version = $config{'ssl_version'};
249 $Net::SSLeay::ssl_version = $config{'ssl_version'};
251 $client_certs = 0 if (!-r $config{'ca'} || !%certs);
252 $ssl_contexts{"*"} = &create_ssl_context($config{'keyfile'},
253 $config{'certfile'});
254 foreach $ipkey (@ipkeys) {
255 $ctx = &create_ssl_context($ipkey->{'key'}, $ipkey->{'cert'});
256 foreach $ip (@{$ipkey->{'ips'}}) {
257 $ssl_contexts{$ip} = $ctx;
262 # Setup syslog support if possible and if requested
264 open(ERRDUP, ">&STDERR");
265 open(STDERR, ">/dev/null");
266 $log_socket = $config{"logsock"} || "unix";
267 eval 'openlog($config{"pam"}, "cons,pid,ndelay", "authpriv"); setlogsock($log_socket)';
272 local $msg = ucfirst($config{'pam'})." starting";
273 eval { syslog("info", "%s", $msg); };
277 syslog("info", "%s", $msg);
280 # All attempts to use syslog have failed..
285 open(STDERR, ">&ERRDUP");
289 # Read MIME types file and add extra types
293 if ($config{'log'}) {
294 local(@gmt, @lct, $days, $hours, $mins);
295 @gmt = gmtime(time());
296 @lct = localtime(time());
297 $days = $lct[3] - $gmt[3];
298 $hours = ($days < -1 ? 24 : 1 < $days ? -24 : $days * 24) +
300 $mins = $hours * 60 + $lct[1] - $gmt[1];
301 $timezone = ($mins < 0 ? "-" : "+"); $mins = abs($mins);
302 $timezone .= sprintf "%2.2d%2.2d", $mins/60, $mins%60;
305 # Build various maps from the config files
306 &build_config_mappings();
308 # start up external authentication program, if needed
309 if ($config{'extauth'}) {
310 socketpair(EXTAUTH, EXTAUTH2, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
311 if (!($extauth = fork())) {
315 open(STDIN, "<&EXTAUTH2");
316 open(STDOUT, ">&EXTAUTH2");
317 exec($config{'extauth'}) or die "exec failed : $!\n";
320 local $os = select(EXTAUTH);
324 # Pre-load any libraries
325 if (!$config{'inetd'}) {
326 foreach $pl (split(/\s+/, $config{'preload'})) {
327 ($pkg, $lib) = split(/=/, $pl);
328 $pkg =~ s/[^A-Za-z0-9]/_/g;
329 eval "package $pkg; do '$config{'root'}/$lib'";
331 print STDERR "Failed to pre-load $lib in $pkg : $@\n";
334 print STDERR "Pre-loaded $lib in $pkg\n";
337 foreach $pl (split(/\s+/, $config{'premodules'})) {
339 ($dir, $mod) = split(/\//, $pl);
342 ($dir, $mod) = (undef, $pl);
344 push(@INC, "$config{'root'}/$dir");
345 eval "package $mod; use $mod ()";
347 print STDERR "Failed to pre-load $mod : $@\n";
350 print STDERR "Pre-loaded $mod\n";
355 # Open debug log if set
356 if ($config{'debuglog'}) {
357 open(DEBUG, ">>$config{'debuglog'}");
358 chmod(0700, $config{'debuglog'});
359 select(DEBUG); $| = 1; select(STDOUT);
360 print DEBUG "miniserv.pl starting ..\n";
363 # Write out (empty) blocked hosts file
364 &write_blocked_file();
366 # Initially read webmin cron functions and last execution times
367 &read_webmin_crons();
368 %webmincron_last = ( );
369 &read_file($config{'webmincron_last'}, \%webmincron_last);
371 # Re-direct STDERR to a log file
372 if ($config{'errorlog'} ne '-') {
373 open(STDERR, ">>$config{'errorlog'}") || die "failed to open $config{'errorlog'} : $!";
374 if ($config{'logperms'}) {
375 chmod(oct($config{'logperms'}), $config{'errorlog'});
378 select(STDERR); $| = 1; select(STDOUT);
380 if ($config{'inetd'}) {
381 # We are being run from inetd - go direct to handling the request
382 $SIG{'HUP'} = 'IGNORE';
383 $SIG{'TERM'} = 'DEFAULT';
384 $SIG{'PIPE'} = 'DEFAULT';
385 open(SOCK, "+>&STDIN");
387 # Check if it is time for the logfile to be cleared
388 if ($config{'logclear'}) {
389 local $write_logtime = 0;
390 local @st = stat("$config{'logfile'}.time");
392 if ($st[9]+$config{'logtime'}*60*60 < time()){
395 unlink($config{'logfile'});
398 else { $write_logtime = 1; }
399 if ($write_logtime) {
400 open(LOGTIME, ">$config{'logfile'}.time");
401 print LOGTIME time(),"\n";
406 # Initialize SSL for this connection
408 $ssl_con = &ssl_connection_for_ip(SOCK);
412 # Work out the hostname for this web server
413 $host = &get_socket_name(SOCK, 0);
415 $port = $config{'port'};
416 $acptaddr = getpeername(SOCK);
419 print DEBUG "main: Starting handle_request loop pid=$$\n";
420 while(&handle_request($acptaddr, getsockname(SOCK))) { }
421 print DEBUG "main: Done handle_request loop pid=$$\n";
426 # Build list of sockets to listen on
427 if ($config{"bind"} && $config{"bind"} ne "*") {
428 # Listening on a specific IP
429 if (&check_ip6address($config{'bind'})) {
431 $use_ipv6 || die "Cannot bind to $config{'bind'} without IPv6";
432 push(@sockets, [ inet_pton(Socket6::AF_INET6(),$config{'bind'}),
434 Socket6::PF_INET6() ]);
438 push(@sockets, [ inet_aton($config{'bind'}),
444 # Listening on all IPs
446 # Accept IPv6 and v4 connections
447 push(@sockets, [ in6addr_any(), $config{'port'},
448 Socket6::PF_INET6() ]);
452 push(@sockets, [ INADDR_ANY, $config{'port'}, PF_INET ]);
455 foreach $s (split(/\s+/, $config{'sockets'})) {
456 if ($s =~ /^(\d+)$/) {
457 # Just listen on another port on the main IP
458 push(@sockets, [ $sockets[0]->[0], $s, $sockets[0]->[2] ]);
460 elsif ($s =~ /^\*:(\d+)$/) {
461 # Listening on all IPs on some port
463 push(@sockets, [ in6addr_any(), $config{'port'},
464 Socket6::PF_INET6() ]);
467 push(@sockets, [ INADDR_ANY, $config{'port'},
471 elsif ($s =~ /^(\S+):(\d+)$/) {
472 # Listen on a specific port and IP
473 my ($ip, $port) = ($1, $2);
474 if (&check_ip6address($ip)) {
475 $use_ipv6 || die "Cannot bind to $ip without IPv6";
476 push(@sockets, [ inet_pton(Socket6::AF_INET6(),
478 $port, Socket6::PF_INET6() ]);
481 push(@sockets, [ inet_aton($ip), $port,
485 elsif ($s =~ /^([0-9\.]+):\*$/ || $s =~ /^([0-9\.]+)$/) {
486 # Listen on the main port on another IPv4 address
487 push(@sockets, [ inet_aton($1), $sockets[0]->[1],
490 elsif (($s =~ /^([0-9a-f\:]+):\*$/ || $s =~ /^([0-9a-f\:]+)$/) &&
492 # Listen on the main port on another IPv6 address
493 push(@sockets, [ inet_pton(Socket6::AF_INET6(), $1),
495 Socket6::PF_INET6() ]);
499 # Open all the sockets
500 $proto = getprotobyname('tcp');
502 $tried_inaddr_any = 0;
503 for($i=0; $i<@sockets; $i++) {
504 print STDERR "socket=",join(" ", @{$sockets[$i]}),"\n";
506 socket($fh, $sockets[$i]->[2], SOCK_STREAM, $proto) ||
507 die "Failed to open socket family $sockets[$i]->[2] : $!";
508 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
509 $pack = $sockets[$i]->[2] eq PF_INET ?
510 pack_sockaddr_in($sockets[$i]->[1],
512 pack_sockaddr_in6($sockets[$i]->[1],
514 for($j=0; $j<5; $j++) {
515 last if (bind($fh, $pack));
519 # All attempts failed .. give up
520 if ($sockets[$i]->[0] eq INADDR_ANY ||
521 $use_ipv6 && $sockets[$i]->[0] eq in6addr_any()) {
523 "Failed to bind to port $sockets[$i]->[1] : $!");
524 $tried_inaddr_any = 1;
527 $ip = &network_to_address($sockets[$i]->[0]);
529 "Failed to bind to IP $ip port ".
530 "$sockets[$i]->[1] : $!");
534 listen($fh, SOMAXCONN);
535 push(@socketfhs, $fh);
536 $ipv6fhs{$fh} = $sockets[$i]->[2] eq PF_INET ? 0 : 1;
539 foreach $se (@sockerrs) {
540 print STDERR $se,"\n";
543 # If all binds failed, try binding to any address
544 if (!@socketfhs && !$tried_inaddr_any) {
545 print STDERR "Falling back to listening on any address\n";
547 socket($fh, PF_INET, SOCK_STREAM, $proto) ||
548 die "Failed to open socket : $!";
549 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
550 bind($fh, pack_sockaddr_in($sockets[0]->[1], INADDR_ANY)) ||
551 die "Failed to bind to port $sockets[0]->[1] : $!";
552 listen($fh, SOMAXCONN);
553 push(@socketfhs, $fh);
555 elsif (!@socketfhs && $tried_inaddr_any) {
556 die "Could not listen on any ports";
559 if ($config{'listen'}) {
560 # Open the socket that allows other webmin servers to find this one
561 $proto = getprotobyname('udp');
562 if (socket(LISTEN, PF_INET, SOCK_DGRAM, $proto)) {
563 setsockopt(LISTEN, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
564 bind(LISTEN, pack_sockaddr_in($config{'listen'}, INADDR_ANY));
565 listen(LISTEN, SOMAXCONN);
568 $config{'listen'} = 0;
572 # Split from the controlling terminal, unless configured not to
573 if (!$config{'nofork'}) {
574 if (fork()) { exit; }
576 eval { setsid(); }; # may not work on Windows
578 # Close standard file handles
579 open(STDIN, "</dev/null");
580 open(STDOUT, ">/dev/null");
581 &log_error("miniserv.pl started");
582 foreach $msg (@startup_msg) {
586 # write out the PID file
589 # Start the log-clearing process, if needed. This checks every minute
590 # to see if the log has passed its reset time, and if so clears it
591 if ($config{'logclear'}) {
592 if (!($logclearer = fork())) {
593 &close_all_sockets();
596 local $write_logtime = 0;
597 local @st = stat("$config{'logfile'}.time");
599 if ($st[9]+$config{'logtime'}*60*60 < time()){
602 unlink($config{'logfile'});
605 else { $write_logtime = 1; }
606 if ($write_logtime) {
607 open(LOGTIME, ">$config{'logfile'}.time");
608 print LOGTIME time(),"\n";
615 push(@childpids, $logclearer);
618 # Setup the logout time dbm if needed
619 if ($config{'session'}) {
620 eval "use SDBM_File";
621 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
622 eval "\$sessiondb{'1111111111'} = 'foo bar';";
624 dbmclose(%sessiondb);
625 eval "use NDBM_File";
626 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
629 delete($sessiondb{'1111111111'});
634 $SIG{'HUP'} = 'miniserv::trigger_restart';
635 $SIG{'TERM'} = 'miniserv::term_handler';
636 $SIG{'USR1'} = 'miniserv::trigger_reload';
637 $SIG{'PIPE'} = 'IGNORE';
638 local $remove_session_count = 0;
639 $need_pipes = $config{'passdelay'} || $config{'session'};
641 # wait for a new connection, or a message from a child process
643 if (@childpids <= $config{'maxconns'}) {
644 # Only accept new main socket connects when ready
646 foreach $s (@socketfhs) {
647 vec($rmask, fileno($s), 1) = 1;
651 printf STDERR "too many children (%d > %d)\n",
652 scalar(@childpids), $config{'maxconns'};
655 for($i=0; $i<@passin; $i++) {
656 vec($rmask, fileno($passin[$i]), 1) = 1;
659 vec($rmask, fileno(LISTEN), 1) = 1 if ($config{'listen'});
661 # Wait for a connection
662 local $sel = select($rmask, undef, undef, 10);
664 # Check the flag files
665 if ($config{'restartflag'} && -r $config{'restartflag'}) {
666 print STDERR "restart flag file detected\n";
667 unlink($config{'restartflag'});
670 if ($config{'reloadflag'} && -r $config{'reloadflag'}) {
671 unlink($config{'reloadflag'});
676 # Got a HUP signal while in select() .. restart now
680 # Got a USR1 signal while in select() .. re-read config
682 &reload_config_file();
684 local $time_now = time();
686 # Clean up finished processes
688 do { $pid = waitpid(-1, WNOHANG);
689 @childpids = grep { $_ != $pid } @childpids;
690 } while($pid != 0 && $pid != -1);
692 # run the unblocking procedure to check if enough time has passed to
693 # unblock hosts that heve been blocked because of password failures
695 if ($config{'blockhost_failures'}) {
697 while ($i <= $#deny) {
698 if ($blockhosttime{$deny[$i]} &&
699 $config{'blockhost_time'} != 0 &&
700 ($time_now - $blockhosttime{$deny[$i]}) >=
701 $config{'blockhost_time'}) {
702 # the host can be unblocked now
703 $hostfail{$deny[$i]} = 0;
704 splice(@deny, $i, 1);
711 # Do the same for blocked users
712 if ($config{'blockuser_failures'}) {
714 while ($i <= $#deny) {
715 if ($blockusertime{$deny[$i]} &&
716 $config{'blockuser_time'} != 0 &&
717 ($time_now - $blockusertime{$deny[$i]}) >=
718 $config{'blockuser_time'}) {
719 # the user can be unblocked now
720 $userfail{$deny[$i]} = 0;
721 splice(@denyusers, $i, 1);
728 &write_blocked_file();
731 # Check if any webmin cron jobs are ready to run
732 &execute_ready_webmin_crons();
734 if ($config{'session'} && (++$remove_session_count%50) == 0) {
735 # Remove sessions with more than 7 days of inactivity,
737 foreach $s (keys %sessiondb) {
738 local ($user, $ltime, $lip) =
739 split(/\s+/, $sessiondb{$s});
740 if ($time_now - $ltime > 7*24*60*60) {
741 &run_logout_script($s, $user);
742 &write_logout_utmp($user, $lip);
743 delete($sessiondb{$s});
746 "Timeout of session for $user");
752 if ($use_pam && $config{'pam_conv'}) {
753 # Remove PAM sessions with more than 5 minutes of inactivity
755 foreach $c (values %conversations) {
756 if ($time_now - $c->{'time'} > 5*60) {
757 &end_pam_conversation($c);
759 syslog("info", "%s", "Timeout of PAM ".
760 "session for $c->{'user'}");
766 # Don't check any sockets if there is no activity
769 # Check if any of the main sockets have received a new connection
771 foreach $s (@socketfhs) {
772 if (vec($rmask, fileno($s), 1)) {
774 $acptaddr = accept(SOCK, $s);
775 if (!$acptaddr) { next; }
776 binmode(SOCK); # turn off any Perl IO stuff
779 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
781 ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw) =
785 # Check username of connecting user
786 local ($peerp, $peerb, $peera);
788 # Extract IPv6 address
790 unpack_sockaddr_in6($acptaddr);
791 $peera = inet_ntop(Socket6::AF_INET6(), $peerb);
794 # Extract IPv4 address
796 unpack_sockaddr_in($acptaddr);
797 $peera = inet_ntoa($peerb);
799 $localauth_user = undef;
800 if ($config{'localauth'} && $peera eq "127.0.0.1") {
801 if (open(TCP, "/proc/net/tcp")) {
802 # Get the info direct from the kernel
803 $peerh = sprintf("%4.4X", $peerp);
806 local @t = split(/[\s:]+/, $_);
807 if ($t[1] eq '0100007F' &&
816 if (!$localauth_user) {
817 # Call lsof for the info
818 local $lsofpid = open(LSOF,
819 "$config{'localauth'} -i ".
820 "TCP\@127.0.0.1:$peerp |");
822 if (/^(\S+)\s+(\d+)\s+(\S+)/ &&
823 $2 != $$ && $2 != $lsofpid){
824 $localauth_user = $3;
831 # Work out the hostname for this web server
832 $host = &get_socket_name(SOCK, $ipv6fhs{$s});
835 "Failed to get local socket name : $!\n";
839 $port = $sockets[$sn]->[1];
841 # fork the subprocess
843 if (!($handpid = fork())) {
844 # setup signal handlers
845 $SIG{'TERM'} = 'DEFAULT';
846 $SIG{'PIPE'} = 'DEFAULT';
847 #$SIG{'CHLD'} = 'IGNORE';
848 $SIG{'HUP'} = 'IGNORE';
849 $SIG{'USR1'} = 'IGNORE';
851 # Initialize SSL for this connection
853 $ssl_con = &ssl_connection_for_ip(SOCK);
857 # Close the file handle for the session DBM
858 dbmclose(%sessiondb);
860 # close useless pipes
863 close($PASSINr); close($PASSOUTw);
865 &close_all_sockets();
868 # XXX IPv6 - refactor to not resolve IP again
870 "main: Starting handle_request loop pid=$$\n";
871 while(&handle_request($acptaddr,
872 getsockname(SOCK))) { }
874 "main: Done handle_request loop pid=$$\n";
877 close($PASSINw); close($PASSOUTw);
880 push(@childpids, $handpid);
882 close($PASSINw); close($PASSOUTr);
883 push(@passin, $PASSINr);
884 push(@passout, $PASSOUTw);
891 if ($config{'listen'} && vec($rmask, fileno(LISTEN), 1)) {
892 # Got UDP packet from another webmin server
894 local $from = recv(LISTEN, $rcvbuf, 1024, 0);
896 local $fromip = inet_ntoa((unpack_sockaddr_in($from))[1]);
897 local $toip = inet_ntoa((unpack_sockaddr_in(
898 getsockname(LISTEN)))[1]);
899 if ((!@deny || !&ip_match($fromip, $toip, @deny)) &&
900 (!@allow || &ip_match($fromip, $toip, @allow))) {
901 local $listenhost = &get_socket_name(LISTEN, 0);
902 send(LISTEN, "$listenhost:$config{'port'}:".
903 ($use_ssl || $config{'inetd_ssl'} ? 1 : 0).":".
904 ($config{'listenhost'} ?
905 &get_system_hostname() : ""),
911 # check for session, password-timeout and PAM messages from subprocesses
912 for($i=0; $i<@passin; $i++) {
913 if (vec($rmask, fileno($passin[$i]), 1)) {
914 # this sub-process is asking about a password
915 local $infd = $passin[$i];
916 local $outfd = $passout[$i];
917 #local $inline = <$infd>;
918 local $inline = &sysread_line($infd);
920 print DEBUG "main: inline $inline";
923 print DEBUG "main: inline EOF\n";
925 if ($inline =~ /^delay\s+(\S+)\s+(\S+)\s+(\d+)/) {
926 # Got a delay request from a subprocess.. for
927 # valid logins, there is no delay (to prevent
928 # denial of service attacks), but for invalid
929 # logins the delay increases with each failed
932 # login OK.. no delay
933 print $outfd "0 0\n";
934 $wasblocked = $hostfail{$2} ||
939 &write_blocked_file();
948 # add the host to the block list,
950 if ($config{'blockhost_failures'} &&
952 $config{'blockhost_failures'}) {
954 $blockhosttime{$2} = $time_now;
957 local $logtext = "Security alert: Host $2 blocked after $config{'blockhost_failures'} failed logins for user $1";
963 # add the user to the user block list,
965 if ($config{'blockuser_failures'} &&
967 $config{'blockuser_failures'}) {
968 push(@denyusers, $1);
969 $blockusertime{$1} = $time_now;
972 local $logtext = "Security alert: User $1 blocked after $config{'blockuser_failures'} failed logins";
978 # Lock out the user's password, if enabled
979 if ($config{'blocklock'} &&
981 $config{'blockuser_failures'}) {
982 my $lk = &lock_user_password($1);
985 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";
992 $dl = $userdlay{$1} -
993 int(($time_now - $userlast{$1})/50);
994 $dl = $dl < 0 ? 0 : $dl+1;
995 print $outfd "$dl $blocked\n";
998 # Write out blocked status file
1000 &write_blocked_file();
1003 $userlast{$1} = $time_now;
1005 elsif ($inline =~ /^verify\s+(\S+)\s+(\S+)/) {
1006 # Verifying a session ID
1007 local $session_id = $1;
1008 local $notimeout = $2;
1009 local $skey = $sessiondb{$session_id} ?
1011 &hash_session_id($session_id);
1012 if (!defined($sessiondb{$skey})) {
1013 # Session doesn't exist
1014 print $outfd "0 0\n";
1017 local ($user, $ltime) =
1018 split(/\s+/, $sessiondb{$skey});
1019 local $lot = &get_logout_time($user, $session_id);
1021 $time_now - $ltime > $lot*60 &&
1023 # Session has timed out
1024 print $outfd "1 ",$time_now - $ltime,"\n";
1025 #delete($sessiondb{$skey});
1029 print $outfd "2 $user\n";
1031 $time_now - $ltime >
1033 $sessiondb{$skey} = "$user $time_now";
1038 elsif ($inline =~ /^new\s+(\S+)\s+(\S+)\s+(\S+)/) {
1039 # Creating a new session
1040 local $session_id = $1;
1043 $sessiondb{&hash_session_id($session_id)} =
1044 "$user $time_now $ip";
1046 elsif ($inline =~ /^delete\s+(\S+)/) {
1047 # Logging out a session
1048 local $session_id = $1;
1049 local $skey = $sessiondb{$session_id} ?
1051 &hash_session_id($session_id);
1052 local @sdb = split(/\s+/, $sessiondb{$skey});
1053 print $outfd $sdb[0],"\n";
1054 delete($sessiondb{$skey});
1056 elsif ($inline =~ /^pamstart\s+(\S+)\s+(\S+)\s+(.*)/) {
1057 # Starting a new PAM conversation
1058 local ($cid, $host, $user) = ($1, $2, $3);
1060 # Does this user even need PAM?
1061 local ($realuser, $canlogin) =
1062 &can_user_login($user, undef, $host);
1064 if ($canlogin == 0) {
1065 # Cannot even login!
1066 print $outfd "0 Invalid username\n";
1068 elsif ($canlogin != 2) {
1069 # Not using PAM .. so just ask for
1071 $conv = { 'user' => $realuser,
1076 print $outfd "3 Password\n";
1079 # Start the PAM conversation
1080 # sub-process, and get a question
1081 $conv = { 'user' => $realuser,
1085 local ($PAMINr, $PAMINw, $PAMOUTr,
1086 $PAMOUTw) = &allocate_pipes();
1087 local $pampid = fork();
1089 close($PAMOUTr); close($PAMINw);
1090 &pam_conversation_process(
1094 close($PAMOUTw); close($PAMINr);
1095 $conv->{'pid'} = $pampid;
1096 $conv->{'PAMOUTr'} = $PAMOUTr;
1097 $conv->{'PAMINw'} = $PAMINw;
1098 push(@childpids, $pampid);
1100 # Get the first PAM question
1101 local $pok = &recv_pam_question(
1104 &end_pam_conversation($conv);
1108 $conversations{$cid} = $conv if ($conv);
1110 elsif ($inline =~ /^pamanswer\s+(\S+)\s+(.*)/) {
1111 # A response to a PAM question
1112 local ($cid, $answer) = ($1, $2);
1113 local $conv = $conversations{$cid};
1115 # No such conversation?
1116 print $outfd "0 Bad login session\n";
1118 elsif ($conv->{'pid'}) {
1119 # Send the PAM response and get
1121 &send_pam_answer($conv, $answer);
1122 local $pok = &recv_pam_question($conv, $outfd);
1124 &end_pam_conversation($conv);
1128 # This must be the password .. try it
1129 # and send back the results
1130 local ($vu, $expired, $nonexist) =
1131 &validate_user($conv->{'user'},
1134 local $ok = $vu ? 1 : 0;
1135 print $outfd "2 $conv->{'user'} $ok $expired $notexist\n";
1136 &end_pam_conversation($conv);
1139 elsif ($inline =~ /^writesudo\s+(\S+)\s+(\d+)/) {
1140 # Store the fact that some user can sudo to root
1141 local ($user, $ok) = ($1, $2);
1142 $sudocache{$user} = $ok." ".time();
1144 elsif ($inline =~ /^readsudo\s+(\S+)/) {
1145 # Query the user sudo cache (valid for 1 minute)
1147 local ($ok, $last) =
1148 split(/\s+/, $sudocache{$user});
1149 if ($last < time()-60) {
1154 # Tell client OK or not
1155 print $outfd "$ok\n";
1158 elsif ($inline =~ /\S/) {
1159 # Unknown line from pipe?
1160 print DEBUG "main: Unknown line from pipe $inline\n";
1161 print STDERR "Unknown line from pipe $inline\n";
1165 close($infd); close($outfd);
1166 $passin[$i] = $passout[$i] = undef;
1170 @passin = grep { defined($_) } @passin;
1171 @passout = grep { defined($_) } @passout;
1174 # handle_request(remoteaddress, localaddress)
1175 # Where the real work is done
1178 $acptip = inet_ntoa((unpack_sockaddr_in($_[0]))[1]);
1179 $localip = $_[1] ? inet_ntoa((unpack_sockaddr_in($_[1]))[1]) : undef;
1180 print DEBUG "handle_request: from $acptip to $localip\n";
1181 if ($config{'loghost'}) {
1182 $acpthost = gethostbyaddr(inet_aton($acptip), AF_INET);
1183 $acpthost = $acptip if (!$acpthost);
1186 $acpthost = $acptip;
1188 $datestr = &http_date(time());
1190 $ok_message = "Document follows";
1191 $logged_code = undef;
1192 $reqline = $request_uri = $page = undef;
1196 # check address against access list
1197 if (@deny && &ip_match($acptip, $localip, @deny) ||
1198 @allow && !&ip_match($acptip, $localip, @allow)) {
1199 &http_error(403, "Access denied for $acptip");
1204 # Check address with TCP-wrappers
1205 if (!hosts_ctl($config{'pam'}, STRING_UNKNOWN,
1206 $acptip, STRING_UNKNOWN)) {
1207 &http_error(403, "Access denied for $acptip by TCP wrappers");
1211 print DEBUG "handle_request: passed IP checks\n";
1213 # Compute a timeout for the start of headers, based on the number of
1214 # child processes. As this increases, we use a shorter timeout to avoid
1215 # an attacker overloading the system.
1216 local $header_timeout = 60 + ($config{'maxconns'} - @childpids) * 10;
1218 # Wait at most 60 secs for start of headers for initial requests, or
1219 # 10 minutes for kept-alive connections
1221 vec($rmask, fileno(SOCK), 1) = 1;
1222 local $to = $checked_timeout ? 10*60 : $header_timeout;
1223 local $sel = select($rmask, undef, undef, $to);
1225 if ($checked_timeout) {
1226 print DEBUG "handle_request: exiting due to timeout of $to\n";
1230 &http_error(400, "Timeout",
1231 "Waited for that $to seconds for start of headers");
1235 print DEBUG "handle_request: passed timeout check\n";
1237 # Read the HTTP request and headers
1238 local $origreqline = &read_line();
1239 ($reqline = $origreqline) =~ s/\r|\n//g;
1240 $method = $page = $request_uri = undef;
1241 print DEBUG "handle_request reqline=$reqline\n";
1242 if (!$reqline && (!$use_ssl || $checked_timeout > 1)) {
1243 # An empty request .. just close the connection
1244 print DEBUG "handle_request: rejecting empty request\n";
1247 elsif ($reqline !~ /^(\S+)\s+(.*)\s+HTTP\/1\..$/) {
1248 print DEBUG "handle_request: invalid reqline=$reqline\n";
1250 # This could be an http request when it should be https
1252 local $url = $config{'musthost'} ?
1253 "https://$config{'musthost'}:$port/" :
1254 "https://$host:$port/";
1255 if ($config{'ssl_redirect'}) {
1256 # Just re-direct to the correct URL
1257 sleep(1); # Give browser a change to finish
1258 # sending its request
1259 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1260 &write_data("Date: $datestr\r\n");
1261 &write_data("Server: $config{'server'}\r\n");
1262 &write_data("Location: $url\r\n");
1263 &write_keep_alive(0);
1264 &write_data("\r\n");
1268 # Tell user the correct URL
1269 &http_error(200, "Bad Request", "This web server is running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1272 elsif (ord(substr($reqline, 0, 1)) == 128 && !$use_ssl) {
1273 # This could be an https request when it should be http ..
1274 # need to fake a HTTP response
1277 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
1278 eval "Net::SSLeay::load_error_strings()";
1279 $ssl_ctx = Net::SSLeay::CTX_new();
1280 Net::SSLeay::CTX_use_RSAPrivateKey_file(
1281 $ssl_ctx, $config{'keyfile'},
1282 &Net::SSLeay::FILETYPE_PEM);
1283 Net::SSLeay::CTX_use_certificate_file(
1285 $config{'certfile'} || $config{'keyfile'},
1286 &Net::SSLeay::FILETYPE_PEM);
1287 $ssl_con = Net::SSLeay::new($ssl_ctx);
1291 select(SSLw); $| = 1; select(STDOUT);
1292 print SSLw $origreqline;
1294 while(sysread(SOCK, $buf, 1) > 0) {
1301 Net::SSLeay::set_wfd($ssl_con, fileno(SOCK));
1302 Net::SSLeay::set_rfd($ssl_con, fileno(SSLr));
1303 Net::SSLeay::accept($ssl_con) || die "accept() failed";
1305 local $url = $config{'musthost'} ?
1306 "https://$config{'musthost'}:$port/" :
1307 "https://$host:$port/";
1308 if ($config{'ssl_redirect'}) {
1309 # Just re-direct to the correct URL
1310 sleep(1); # Give browser a change to
1311 # finish sending its request
1312 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1313 &write_data("Date: $datestr\r\n");
1314 &write_data("Server: $config{'server'}\r\n");
1315 &write_data("Location: $url\r\n");
1316 &write_keep_alive(0);
1317 &write_data("\r\n");
1321 # Tell user the correct URL
1322 &http_error(200, "Bad Request", "This web server is not running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1326 &http_error(400, "Bad Request");
1330 &http_error(400, "Bad Request");
1334 $request_uri = $page = $2;
1338 ($headline = &read_line()) =~ s/\r|\n//g;
1339 last if ($headline eq "");
1340 print DEBUG "handle_request: got headline $headline\n";
1341 if ($headline =~ /^(\S+):\s*(.*)$/) {
1342 $header{$lastheader = lc($1)} = $2;
1344 elsif ($headline =~ /^\s+(.*)$/) {
1345 $header{$lastheader} .= $headline;
1348 &http_error(400, "Bad Header $headline");
1351 if (defined($header{'host'})) {
1352 if ($header{'host'} =~ /^([^:]+):([0-9]+)$/) {
1353 ($host, $port) = ($1, $2);
1356 $host = $header{'host'};
1358 if ($config{'musthost'} && $host ne $config{'musthost'}) {
1359 # Disallowed hostname used
1360 &http_error(400, "Invalid HTTP hostname");
1364 if ($page =~ /^([^\?]+)\?(.*)$/) {
1365 # There is some query string information
1368 print DEBUG "handle_request: querystring=$querystring\n";
1369 if ($querystring !~ /=/) {
1370 $queryargs = $querystring;
1371 $queryargs =~ s/\+/ /g;
1372 $queryargs =~ s/%(..)/pack("c",hex($1))/ge;
1376 # Parse query-string parameters
1377 local @in = split(/\&/, $querystring);
1379 local ($k, $v) = split(/=/, $i, 2);
1380 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1381 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1386 $posted_data = undef;
1387 if ($method eq 'POST' &&
1388 $header{'content-type'} eq 'application/x-www-form-urlencoded') {
1389 # Read in posted query string information, up the configured maximum
1390 # post request length
1391 $clen = $header{"content-length"};
1392 $clen_read = $clen > $config{'max_post'} ? $config{'max_post'} : $clen;
1393 while(length($posted_data) < $clen_read) {
1394 $buf = &read_data($clen_read - length($posted_data));
1395 if (!length($buf)) {
1396 &http_error(500, "Failed to read POST request");
1398 chomp($posted_data);
1399 $posted_data =~ s/\015$//mg;
1400 $posted_data .= $buf;
1402 print DEBUG "clen_read=$clen_read clen=$clen posted_data=",length($posted_data),"\n";
1403 if ($clen_read != $clen && length($posted_data) > $clen) {
1404 # If the client sent more data than we asked for, chop the
1406 $posted_data = substr($posted_data, 0, $clen);
1408 if (length($posted_data) > $clen) {
1409 # When the client sent too much, delay so that it gets headers
1412 if ($header{'user-agent'} =~ /MSIE/ &&
1413 $header{'user-agent'} !~ /Opera/i) {
1414 # MSIE includes an extra newline in the data
1415 $posted_data =~ s/\r|\n//g;
1417 local @in = split(/\&/, $posted_data);
1419 local ($k, $v) = split(/=/, $i, 2);
1421 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1422 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1425 print DEBUG "handle_request: posted_data=$posted_data\n";
1428 # replace %XX sequences in page
1429 $page =~ s/%(..)/pack("c",hex($1))/ge;
1431 # Check if the browser's user agent indicates a mobile device
1432 $mobile_device = &is_mobile_useragent($header{'user-agent'});
1434 # Check if Host: header is for a mobile URL
1435 foreach my $m (@mobile_prefixes) {
1436 if ($header{'host'} =~ /^\Q$m\E/i) {
1441 # check for the logout flag file, and if existant deny authentication
1442 if ($config{'logout'} && -r $config{'logout'}.$in{'miniserv_logout_id'}) {
1443 print DEBUG "handle_request: logout flag set\n";
1444 $deny_authentication++;
1445 open(LOGOUT, $config{'logout'}.$in{'miniserv_logout_id'});
1446 chop($count = <LOGOUT>);
1450 open(LOGOUT, ">$config{'logout'}$in{'miniserv_logout_id'}");
1451 print LOGOUT "$count\n";
1455 unlink($config{'logout'}.$in{'miniserv_logout_id'});
1459 # check for any redirect for the requested URL
1460 foreach my $pfx (@strip_prefix) {
1461 my $l = length($pfx);
1462 if(length($page) >= $l &&
1463 substr($page,0,$l) eq $pfx) {
1464 $page=substr($page,$l);
1468 $simple = &simplify_path($page, $bogus);
1470 $rpath .= "&".$querystring if (defined($querystring));
1471 $redir = $redirect{$rpath};
1472 if (defined($redir)) {
1473 print DEBUG "handle_request: redir=$redir\n";
1474 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1475 &write_data("Date: $datestr\r\n");
1476 &write_data("Server: $config{'server'}\r\n");
1477 local $ssl = $use_ssl || $config{'inetd_ssl'};
1478 $portstr = $port == 80 && !$ssl ? "" :
1479 $port == 443 && $ssl ? "" : ":$port";
1480 $prot = $ssl ? "https" : "http";
1481 &write_data("Location: $prot://$host$portstr$redir\r\n");
1482 &write_keep_alive(0);
1483 &write_data("\r\n");
1487 # Check for a DAV request
1489 foreach my $d (@davpaths) {
1490 if ($simple eq $d || $simple =~ /^\Q$d\E\//) {
1495 if (!$davpath && ($method eq "SEARCH" || $method eq "PUT")) {
1496 &http_error(400, "Bad Request method $method");
1499 # Check for password if needed
1500 if ($config{'userfile'}) {
1501 print DEBUG "handle_request: Need authentication\n";
1505 # Session authentication is never used for connections by
1506 # another webmin server, or for specified pages, or for DAV, or XMLRPC,
1507 # or mobile browsers if requested.
1508 if ($header{'user-agent'} =~ /webmin/i ||
1509 $header{'user-agent'} =~ /$config{'agents_nosession'}/i ||
1510 $sessiononly{$simple} || $davpath ||
1511 $simple eq "/xmlrpc.cgi" ||
1512 $acptip eq $config{'host_nosession'} ||
1513 $mobile_device && $config{'mobile_nosession'}) {
1514 print DEBUG "handle_request: Forcing HTTP authentication\n";
1515 $config{'session'} = 0;
1518 # Check for SSL authentication
1519 if ($use_ssl && $verified_client) {
1520 $peername = Net::SSLeay::X509_NAME_oneline(
1521 Net::SSLeay::X509_get_subject_name(
1522 Net::SSLeay::get_peer_certificate(
1524 $u = &find_user_by_cert($peername);
1529 if ($use_syslog && !$validated) {
1530 syslog("crit", "%s",
1531 "Unknown SSL certificate $peername");
1535 if (!$validated && !$deny_authentication) {
1536 # check for IP-based authentication
1538 foreach $a (keys %ipaccess) {
1539 if ($acptip eq $a) {
1540 # It does! Auth as the user
1542 $baseauthuser = $authuser =
1548 # Check for normal HTTP authentication
1549 if (!$validated && !$deny_authentication && !$config{'session'} &&
1550 $header{authorization} =~ /^basic\s+(\S+)$/i) {
1551 # authorization given..
1552 ($authuser, $authpass) = split(/:/, &b64decode($1), 2);
1553 print DEBUG "handle_request: doing basic auth check authuser=$authuser authpass=$authpass\n";
1554 local ($vu, $expired, $nonexist) =
1555 &validate_user($authuser, $authpass, $host);
1556 print DEBUG "handle_request: vu=$vu expired=$expired nonexist=$nonexist\n";
1557 if ($vu && (!$expired || $config{'passwd_mode'} == 1)) {
1564 if ($use_syslog && !$validated) {
1565 syslog("crit", "%s",
1566 ($nonexist ? "Non-existent" :
1567 $expired ? "Expired" : "Invalid").
1568 " login as $authuser from $acpthost");
1570 if ($authuser =~ /\r|\n|\s/) {
1571 &http_error(500, "Invalid username",
1572 "Username contains invalid characters");
1574 if ($authpass =~ /\r|\n/) {
1575 &http_error(500, "Invalid password",
1576 "Password contains invalid characters");
1579 if ($config{'passdelay'} && !$config{'inetd'} && $authuser) {
1580 # check with main process for delay
1581 print DEBUG "handle_request: about to ask for password delay\n";
1582 print $PASSINw "delay $authuser $acptip $validated\n";
1583 <$PASSOUTr> =~ /(\d+) (\d+)/;
1585 print DEBUG "handle_request: password delay $1 $2\n";
1590 # Check for a visit to the special session login page
1591 if ($config{'session'} && !$deny_authentication &&
1592 $page eq $config{'session_login'}) {
1593 if ($in{'logout'} && $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1594 # Logout clicked .. remove the session
1596 print $PASSINw "delete $sid\n";
1597 local $louser = <$PASSOUTr>;
1600 $already_session_id = undef;
1601 $authuser = $baseauthuser = undef;
1604 syslog("info", "%s", "Logout by $louser from $acpthost");
1606 &run_logout_script($louser, $sid,
1608 &write_logout_utmp($louser, $actphost);
1613 if ($in{'user'} =~ /\r|\n|\s/) {
1614 &http_error(500, "Invalid username",
1615 "Username contains invalid characters");
1617 if ($in{'pass'} =~ /\r|\n/) {
1618 &http_error(500, "Invalid password",
1619 "Password contains invalid characters");
1622 local ($vu, $expired, $nonexist) =
1623 &validate_user($in{'user'}, $in{'pass'}, $host);
1624 local $hrv = &handle_login(
1625 $vu || $in{'user'}, $vu ? 1 : 0,
1626 $expired, $nonexist, $in{'pass'},
1627 $in{'notestingcookie'});
1628 return $hrv if (defined($hrv));
1632 # Check for a visit to the special PAM login page
1633 if ($config{'session'} && !$deny_authentication &&
1634 $use_pam && $config{'pam_conv'} && $page eq $config{'pam_login'} &&
1636 # A question has been entered .. submit it to the main process
1637 print DEBUG "handle_request: Got call to $page ($in{'cid'})\n";
1638 print DEBUG "handle_request: For PAM, authuser=$authuser\n";
1639 if ($in{'answer'} =~ /\r|\n/ || $in{'cid'} =~ /\r|\n|\s/) {
1640 &http_error(500, "Invalid response",
1641 "Response contains invalid characters");
1645 # Start of a new conversation - answer must be username
1646 $cid = &generate_random_id($in{'answer'});
1647 print $PASSINw "pamstart $cid $host $in{'answer'}\n";
1650 # A response to a previous question
1652 print $PASSINw "pamanswer $cid $in{'answer'}\n";
1655 # Read back the response, and the next question (if any)
1656 local $line = <$PASSOUTr>;
1657 $line =~ s/\r|\n//g;
1658 local ($rv, $question) = split(/\s+/, $line, 2);
1661 local $hrv = &handle_login(
1662 !$in{'cid'} && $in{'answer'} ? $in{'answer'}
1665 return $hrv if (defined($hrv));
1667 elsif ($rv == 1 || $rv == 3) {
1668 # Another question .. force use of PAM CGI
1671 $querystring .= "&cid=$cid&question=".
1673 $querystring .= "&password=1" if ($rv == 3);
1675 $page = $config{'pam_login'};
1676 $miniserv_internal = 1;
1680 # Got back a final ok or failure
1681 local ($user, $ok, $expired, $nonexist) =
1682 split(/\s+/, $question);
1683 local $hrv = &handle_login(
1684 $user, $ok, $expired, $nonexist, undef,
1685 $in{'notestingcookie'});
1686 return $hrv if (defined($hrv));
1689 # A message from PAM .. tell the user
1692 $querystring .= "&cid=$cid&message=".
1695 $page = $config{'pam_login'};
1696 $miniserv_internal = 1;
1701 # Check for a visit to the special password change page
1702 if ($config{'session'} && !$deny_authentication &&
1703 $page eq $config{'password_change'} && !$validated) {
1704 # Just let this slide ..
1706 $miniserv_internal = 3;
1709 # Check for an existing session
1710 if ($config{'session'} && !$validated) {
1711 if ($already_session_id) {
1712 $session_id = $already_session_id;
1713 $authuser = $already_authuser;
1716 elsif (!$deny_authentication &&
1717 $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1718 # Try all session cookies
1719 local $cookie = $header{'cookie'};
1720 while($cookie =~ s/(^|\s)$sidname=([a-f0-9]+)//) {
1723 $in{'webmin_notimeout'} ? 1 : 0;
1724 print $PASSINw "verify $session_id $notimeout\n";
1725 <$PASSOUTr> =~ /(\d+)\s+(\S+)/;
1727 # Valid session continuation
1730 $already_authuser = $authuser;
1739 # Invalid session ID .. don't set
1746 # Check for local authentication
1747 if ($localauth_user && !$header{'x-forwarded-for'} && !$header{'via'}) {
1748 my $luser = &get_user_details($localauth_user);
1750 # Local user exists in webmin users file
1752 $authuser = $localauth_user;
1755 # Check if local user is allowed by unixauth
1756 local @can = &can_user_login($localauth_user,
1760 $authuser = $localauth_user;
1763 $localauth_user = undef;
1769 # Check if this path allows anonymous access
1771 foreach $a (keys %anonymous) {
1772 if (substr($simple, 0, length($a)) eq $a) {
1773 # It does! Auth as the user, if IP access
1774 # control allows him.
1775 if (&check_user_ip($anonymous{$a}) &&
1776 &check_user_time($anonymous{$a})) {
1778 $baseauthuser = $authuser =
1786 # Check if this path allows unauthenticated access
1787 local ($u, $unauth);
1788 foreach $u (@unauth) {
1789 $unauth++ if ($simple =~ /$u/);
1791 if (!$bogus && $unauth) {
1792 # Unauthenticated directory or file request - approve it
1794 $baseauthuser = $authuser = undef;
1799 if ($blocked == 0) {
1800 # No password given.. ask
1801 if ($config{'pam_conv'} && $use_pam) {
1802 # Force CGI for PAM question, starting with
1803 # the username which is always needed
1806 $querystring .= "&initial=1&question=".
1807 &urlize("Username");
1808 $querystring .= "&failed=$failed_user" if ($failed_user);
1809 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1811 $page = $config{'pam_login'};
1812 $miniserv_internal = 1;
1815 elsif ($config{'session'}) {
1816 # Force CGI for session login
1819 $querystring .= "&logout=1&page=/";
1822 # Re-direct to current module only
1823 local $rpage = $request_uri;
1824 if (!$config{'loginkeeppage'}) {
1825 $rpage =~ s/\?.*$//;
1826 $rpage =~ s/[^\/]+$//
1828 $querystring = "page=".&urlize($rpage);
1831 $querystring .= "&failed=$failed_user" if ($failed_user);
1832 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1834 $page = $config{'session_login'};
1835 $miniserv_internal = 1;
1839 # Ask for login with HTTP authentication
1840 &write_data("HTTP/1.0 401 Unauthorized\r\n");
1841 &write_data("Date: $datestr\r\n");
1842 &write_data("Server: $config{'server'}\r\n");
1843 &write_data("WWW-authenticate: Basic ".
1844 "realm=\"$config{'realm'}\"\r\n");
1845 &write_keep_alive(0);
1846 &write_data("Content-type: text/html\r\n");
1847 &write_data("\r\n");
1848 &reset_byte_count();
1849 &write_data("<html>\n");
1850 &write_data("<head><title>Unauthorized</title></head>\n");
1851 &write_data("<body><h1>Unauthorized</h1>\n");
1852 &write_data("A password is required to access this\n");
1853 &write_data("web server. Please try again. <p>\n");
1854 &write_data("</body></html>\n");
1855 &log_request($acpthost, undef, $reqline, 401, &byte_count());
1859 elsif ($blocked == 1) {
1860 # when the host has been blocked, give it an error
1861 &http_error(403, "Access denied for $acptip. The host ".
1862 "has been blocked because of too ".
1863 "many authentication failures.");
1865 elsif ($blocked == 2) {
1866 # when the user has been blocked, give it an error
1867 &http_error(403, "Access denied. The user ".
1868 "has been blocked because of too ".
1869 "many authentication failures.");
1873 # Get the real Webmin username
1874 local @can = &can_user_login($authuser, undef, $host);
1875 $baseauthuser = $can[3] || $authuser;
1877 if ($config{'remoteuser'} && !$< && $validated) {
1878 # Switch to the UID of the remote user (if he exists)
1879 local @u = getpwnam($authuser);
1880 if (@u && $< != $u[2]) {
1881 $( = $u[3]; $) = "$u[3] $u[3]";
1882 ($>, $<) = ($u[2], $u[2]);
1885 &http_error(500, "Unix user $authuser does not exist");
1891 # Check per-user IP access control
1892 if (!&check_user_ip($baseauthuser)) {
1893 &http_error(403, "Access denied for $acptip for $baseauthuser");
1897 # Check per-user allowed times
1898 if (!&check_user_time($baseauthuser)) {
1899 &http_error(403, "Access denied at the current time");
1903 $uinfo = &get_user_details($baseauthuser);
1905 # Validate the path, and convert to canonical form
1907 $simple = &simplify_path($page, $bogus);
1908 print DEBUG "handle_request: page=$page simple=$simple\n";
1910 &http_error(400, "Invalid path");
1913 # Check for a DAV request
1915 return &handle_dav_request($davpath);
1918 # Work out the active theme(s)
1919 local $preroots = $mobile_device && defined($config{'mobile_preroot'}) ?
1920 $config{'mobile_preroot'} :
1921 $authuser && defined($config{'preroot_'.$authuser}) ?
1922 $config{'preroot_'.$authuser} :
1923 $uinfo && defined($uinfo->{'preroot'}) ?
1924 $uinfo->{'preroot'} :
1926 local @preroots = reverse(split(/\s+/, $preroots));
1928 # Canonicalize the directories
1929 foreach my $preroot (@preroots) {
1930 # Always under the current webmin root
1931 $preroot =~ s/^.*\///g;
1932 $preroot = $roots[0].'/'.$preroot;
1935 # Look in the theme root directories first
1936 local ($full, @stfull);
1938 foreach my $preroot (@preroots) {
1941 $full = $preroot.$sofar;
1942 $scriptname = $simple;
1943 foreach $b (split(/\//, $simple)) {
1944 if ($b ne "") { $sofar .= "/$b"; }
1945 $full = $preroot.$sofar;
1946 @stfull = stat($full);
1947 if (!@stfull) { undef($full); last; }
1949 # Check if this is a directory
1951 # It is.. go on parsing
1959 # Check if this is a CGI program
1960 if (&get_type($full) eq "internal/cgi") {
1961 $pathinfo = substr($simple, length($sofar));
1962 $pathinfo .= "/" if ($page =~ /\/$/);
1963 $scriptname = $sofar;
1968 # Don't stop at a directory unless this is the last theme, which
1969 # is the 'real' one that provides the .cgi scripts
1970 if ($is_directory && $preroot ne $preroots[$#preroots]) {
1977 $cgi_pwd = $roots[0];
1979 elsif ($is_directory) {
1980 $cgi_pwd = "$roots[0]$sofar";
1983 "$roots[0]$sofar" =~ /^(.*\/)[^\/]+$/;
1986 $foundroot = $preroot;
1987 if ($is_directory) {
1988 # Check for index files in the directory
1990 foreach $idx (split(/\s+/, $config{"index_docs"})) {
1991 $idxfull = "$full/$idx";
1992 local @stidxfull = stat($idxfull);
1993 if (-r _ && !-d _) {
1995 @stfull = @stidxfull;
1998 if ($scriptname ne "/");
2003 @stfull = stat($full) if (!$foundidx);
2006 last if ($foundroot);
2008 print DEBUG "handle_request: initial full=$full\n";
2010 # Look in the real root directories, stopping when we find a file or directory
2011 if (!$full || $is_directory) {
2012 ROOT: foreach $root (@roots) {
2014 $full = $root.$sofar;
2015 $scriptname = $simple;
2016 foreach $b ($simple eq "/" ? ( "" ) : split(/\//, $simple)) {
2017 if ($b ne "") { $sofar .= "/$b"; }
2018 $full = $root.$sofar;
2019 @stfull = stat($full);
2024 # Check if this is a directory
2026 # It is.. go on parsing
2030 # Check if this is a CGI program
2031 if (&get_type($full) eq "internal/cgi") {
2032 $pathinfo = substr($simple, length($sofar));
2033 $pathinfo .= "/" if ($page =~ /\/$/);
2034 $scriptname = $sofar;
2039 # Run CGI in the same directory as whatever file
2041 $full =~ /^(.*\/)[^\/]+$/; $cgi_pwd = $1;
2050 if (!@stfull) { &http_error(404, "File not found"); }
2052 print DEBUG "handle_request: full=$full\n";
2053 @stfull = stat($full) if (!@stfull);
2055 # check filename against denyfile regexp
2056 local $denyfile = $config{'denyfile'};
2057 if ($denyfile && $full =~ /$denyfile/) {
2058 &http_error(403, "Access denied to $page");
2062 # Reached the end of the path OK.. see what we've got
2064 # See if the URL ends with a / as it should
2065 print DEBUG "handle_request: found a directory\n";
2066 if ($page !~ /\/$/) {
2067 # It doesn't.. redirect
2068 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2069 $ssl = $use_ssl || $config{'inetd_ssl'};
2070 $portstr = $port == 80 && !$ssl ? "" :
2071 $port == 443 && $ssl ? "" : ":$port";
2072 &write_data("Date: $datestr\r\n");
2073 &write_data("Server: $config{server}\r\n");
2074 $prot = $ssl ? "https" : "http";
2075 &write_data("Location: $prot://$host$portstr$page/\r\n");
2076 &write_keep_alive(0);
2077 &write_data("\r\n");
2078 &log_request($acpthost, $authuser, $reqline, 302, 0);
2081 # A directory.. check for index files
2083 foreach $idx (split(/\s+/, $config{"index_docs"})) {
2084 $idxfull = "$full/$idx";
2085 @stidxfull = stat($idxfull);
2086 if (-r _ && !-d _) {
2089 @stfull = @stidxfull;
2090 $scriptname .= "/" if ($scriptname ne "/");
2095 @stfull = stat($full) if (!$foundidx);
2098 # This is definately a directory.. list it
2099 print DEBUG "handle_request: listing directory\n";
2100 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2101 "Date: $datestr\r\n".
2102 "Server: $config{server}\r\n".
2103 "Content-type: text/html\r\n";
2105 &write_keep_alive(0);
2106 &write_data("\r\n");
2107 &reset_byte_count();
2108 &write_data("<h1>Index of $simple</h1>\n");
2109 &write_data("<pre>\n");
2110 &write_data(sprintf "%-35.35s %-20.20s %-10.10s\n",
2111 "Name", "Last Modified", "Size");
2112 &write_data("<hr>\n");
2113 opendir(DIR, $full);
2114 while($df = readdir(DIR)) {
2115 if ($df =~ /^\./) { next; }
2116 $fulldf = $full eq "/" ? $full.$df : $full."/".$df;
2117 (@stbuf = stat($fulldf)) || next;
2118 if (-d _) { $df .= "/"; }
2119 @tm = localtime($stbuf[9]);
2120 $fdate = sprintf "%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d",
2121 $tm[3],$tm[4]+1,$tm[5]+1900,
2122 $tm[0],$tm[1],$tm[2];
2123 $len = length($df); $rest = " "x(35-$len);
2125 "<a href=\"%s\">%-${len}.${len}s</a>$rest %-20.20s %-10.10s\n",
2126 $df, $df, $fdate, $stbuf[7]);
2129 &log_request($acpthost, $authuser, $reqline, $ok_code, &byte_count());
2133 # CGI or normal file
2135 if (&get_type($full) eq "internal/cgi" && $validated != 4) {
2136 # A CGI program to execute
2137 print DEBUG "handle_request: executing CGI\n";
2138 $envtz = $ENV{"TZ"};
2139 $envuser = $ENV{"USER"};
2140 $envpath = $ENV{"PATH"};
2141 $envlang = $ENV{"LANG"};
2142 $envroot = $ENV{"SystemRoot"};
2143 $envperllib = $ENV{'PERLLIB'};
2144 foreach my $k (keys %ENV) {
2147 $ENV{"PATH"} = $envpath if ($envpath);
2148 $ENV{"TZ"} = $envtz if ($envtz);
2149 $ENV{"USER"} = $envuser if ($envuser);
2150 $ENV{"OLD_LANG"} = $envlang if ($envlang);
2151 $ENV{"SystemRoot"} = $envroot if ($envroot);
2152 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
2153 $ENV{"HOME"} = $user_homedir;
2154 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
2155 $ENV{"SERVER_NAME"} = $host;
2156 $ENV{"SERVER_ADMIN"} = $config{"email"};
2157 $ENV{"SERVER_ROOT"} = $roots[0];
2158 $ENV{"SERVER_REALROOT"} = $realroot;
2159 $ENV{"SERVER_PORT"} = $port;
2160 $ENV{"REMOTE_HOST"} = $acpthost;
2161 $ENV{"REMOTE_ADDR"} = $acptip;
2162 $ENV{"REMOTE_USER"} = $authuser;
2163 $ENV{"BASE_REMOTE_USER"} = $authuser ne $baseauthuser ?
2164 $baseauthuser : undef;
2165 $ENV{"REMOTE_PASS"} = $authpass if (defined($authpass) &&
2166 $config{'pass_password'});
2167 if ($uinfo && $uinfo->{'proto'}) {
2168 $ENV{"REMOTE_USER_PROTO"} = $uinfo->{'proto'};
2169 $ENV{"REMOTE_USER_ID"} = $uinfo->{'id'};
2171 print DEBUG "REMOTE_USER = ",$ENV{"REMOTE_USER"},"\n";
2172 print DEBUG "BASE_REMOTE_USER = ",$ENV{"BASE_REMOTE_USER"},"\n";
2173 print DEBUG "proto=$uinfo->{'proto'} id=$uinfo->{'id'}\n" if ($uinfo);
2174 $ENV{"SSL_USER"} = $peername if ($validated == 2);
2175 $ENV{"ANONYMOUS_USER"} = "1" if ($validated == 3 || $validated == 4);
2176 $ENV{"DOCUMENT_ROOT"} = $roots[0];
2177 $ENV{"DOCUMENT_REALROOT"} = $realroot;
2178 $ENV{"GATEWAY_INTERFACE"} = "CGI/1.1";
2179 $ENV{"SERVER_PROTOCOL"} = "HTTP/1.0";
2180 $ENV{"REQUEST_METHOD"} = $method;
2181 $ENV{"SCRIPT_NAME"} = $scriptname;
2182 $ENV{"SCRIPT_FILENAME"} = $full;
2183 $ENV{"REQUEST_URI"} = $request_uri;
2184 $ENV{"PATH_INFO"} = $pathinfo;
2186 $ENV{"PATH_TRANSLATED"} = "$roots[0]$pathinfo";
2187 $ENV{"PATH_REALTRANSLATED"} = "$realroot$pathinfo";
2189 $ENV{"QUERY_STRING"} = $querystring;
2190 $ENV{"MINISERV_CONFIG"} = $config_file;
2191 $ENV{"HTTPS"} = "ON" if ($use_ssl || $config{'inetd_ssl'});
2192 $ENV{"MINISERV_PID"} = $miniserv_main_pid;
2193 $ENV{"SESSION_ID"} = $session_id if ($session_id);
2194 $ENV{"LOCAL_USER"} = $localauth_user if ($localauth_user);
2195 $ENV{"MINISERV_INTERNAL"} = $miniserv_internal if ($miniserv_internal);
2196 if (defined($header{"content-length"})) {
2197 $ENV{"CONTENT_LENGTH"} = $header{"content-length"};
2199 if (defined($header{"content-type"})) {
2200 $ENV{"CONTENT_TYPE"} = $header{"content-type"};
2202 foreach $h (keys %header) {
2203 ($hname = $h) =~ tr/a-z/A-Z/;
2205 $ENV{"HTTP_$hname"} = $header{$h};
2207 $ENV{"PWD"} = $cgi_pwd;
2208 foreach $k (keys %config) {
2209 if ($k =~ /^env_(\S+)$/) {
2210 $ENV{$1} = $config{$k};
2213 delete($ENV{'HTTP_AUTHORIZATION'});
2214 $ENV{'HTTP_COOKIE'} =~ s/;?\s*$sidname=([a-f0-9]+)//;
2215 $ENV{'MOBILE_DEVICE'} = 1 if ($mobile_device);
2217 # Check if the CGI can be handled internally
2219 local $first = <CGI>;
2221 $first =~ s/[#!\r\n]//g;
2222 $nph_script = ($full =~ /\/nph-([^\/]+)$/);
2224 if (!$config{'forkcgis'} &&
2225 ($first eq $perl_path || $first eq $linked_perl_path) &&
2227 $config{'internalcgis'}) {
2228 # setup environment for eval
2230 @ARGV = split(/\s+/, $queryargs);
2233 # Already read the post input
2234 $postinput = $posted_data;
2236 $clen = $header{"content-length"};
2237 $SIG{'CHLD'} = 'DEFAULT';
2239 # Have SOCK closed if the perl exec's something
2241 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
2245 if ($config{'log'}) {
2246 open(MINISERVLOG, ">>$config{'logfile'}");
2247 if ($config{'logperms'}) {
2248 chmod(oct($config{'logperms'}),
2249 $config{'logfile'});
2252 chmod(0600, $config{'logfile'});
2255 $doing_cgi_eval = 1;
2256 $main_process_id = $$;
2258 if ($full =~ /^\Q$foundroot\E\/([^\/]+)\//) {
2259 # Eval in package from Webmin module name
2261 $pkg =~ s/[^A-Za-z0-9]/_/g;
2266 tie(*STDOUT, 'miniserv');
2267 tie(*STDIN, 'miniserv');
2268 do \$miniserv::full;
2271 $doing_cgi_eval = 0;
2274 &http_error(500, "Perl execution failed",
2275 $config{'noshowstderr'} ? undef : $@);
2277 elsif (!$doneheaders && !$nph_script) {
2278 &http_error(500, "Missing Headers");
2285 # fork the process that actually executes the CGI
2286 pipe(CGIINr, CGIINw);
2287 pipe(CGIOUTr, CGIOUTw);
2288 pipe(CGIERRr, CGIERRw);
2289 if (!($cgipid = fork())) {
2290 @execargs = ( $full, split(/\s+/, $queryargs) );
2293 open(STDIN, "<&CGIINr");
2294 open(STDOUT, ">&CGIOUTw");
2295 open(STDERR, ">&CGIERRw");
2296 close(CGIINw); close(CGIOUTr); close(CGIERRr);
2298 die "Failed to exec $full : $!\n";
2301 close(CGIINr); close(CGIOUTw); close(CGIERRw);
2304 # write CGI input to a temp file
2305 $infile = "$config{'tempbase'}.$$";
2306 open(CGIINw, ">$infile");
2307 # NOT binary mode, as CGIs don't read in it!
2312 # already read the posted data
2313 print CGIINw $posted_data;
2315 $clen = $header{"content-length"};
2316 if ($method eq "POST" && $clen_read < $clen) {
2317 $SIG{'PIPE'} = 'IGNORE';
2319 while($got < $clen) {
2320 $buf = &read_data($clen-$got);
2321 if (!length($buf)) {
2322 kill('TERM', $cgipid);
2323 unlink($infile) if ($infile);
2324 &http_error(500, "Failed to read ".
2327 $got += length($buf);
2328 local ($wrote) = (print CGIINw $buf);
2331 # If the CGI terminated early, we still need to read
2332 # from the browser and throw away
2333 while($got < $clen) {
2334 $buf = &read_data($clen-$got);
2335 if (!length($buf)) {
2336 kill('TERM', $cgipid);
2337 unlink($infile) if ($infile);
2338 &http_error(500, "Failed to read ".
2341 $got += length($buf);
2343 $SIG{'PIPE'} = 'DEFAULT';
2349 # Run the CGI program, and feed it input
2351 local $qqueryargs = join(" ", map { "\"$_\"" }
2352 split(/\s+/, $queryargs));
2353 if ($first =~ /(perl|perl.exe)$/i) {
2354 # On Windows, run with Perl
2355 open(CGIOUTr, "$perl_path \"$full\" $qqueryargs <$infile |");
2358 open(CGIOUTr, "\"$full\" $qqueryargs <$infile |");
2364 # read back cgi headers
2365 select(CGIOUTr); $|=1; select(STDOUT);
2369 $line =~ s/\r|\n//g;
2371 if ($got_blank || %cgiheader) { last; }
2375 if ($line !~ /^(\S+):\s+(.*)$/) {
2376 $errs = &read_errors(CGIERRr);
2377 close(CGIOUTr); close(CGIERRr);
2378 unlink($infile) if ($infile);
2379 &http_error(500, "Bad Header", $errs);
2381 $cgiheader{lc($1)} = $2;
2382 push(@cgiheader, [ $1, $2 ]);
2384 if ($cgiheader{"location"}) {
2385 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2386 &write_data("Date: $datestr\r\n");
2387 &write_data("Server: $config{'server'}\r\n");
2388 &write_keep_alive(0);
2389 # ignore the rest of the output. This is a hack,
2390 # but is necessary for IE in some cases :(
2391 close(CGIOUTr); close(CGIERRr);
2393 elsif ($cgiheader{"content-type"} eq "") {
2394 close(CGIOUTr); close(CGIERRr);
2395 unlink($infile) if ($infile);
2396 $errs = &read_errors(CGIERRr);
2397 &http_error(500, "Missing Content-Type Header",
2398 $config{'noshowstderr'} ? undef : $errs);
2401 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2402 &write_data("Date: $datestr\r\n");
2403 &write_data("Server: $config{'server'}\r\n");
2404 &write_keep_alive(0);
2406 foreach $h (@cgiheader) {
2407 &write_data("$h->[0]: $h->[1]\r\n");
2409 &write_data("\r\n");
2411 &reset_byte_count();
2412 while($line = <CGIOUTr>) {
2417 unlink($infile) if ($infile);
2423 print DEBUG "handle_request: outputting file\n";
2424 open(FILE, $full) || &http_error(404, "Failed to open file");
2426 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2427 "Date: $datestr\r\n".
2428 "Server: $config{server}\r\n".
2429 "Content-type: ".&get_type($full)."\r\n".
2430 "Content-length: $stfull[7]\r\n".
2431 "Last-Modified: ".&http_date($stfull[9])."\r\n".
2432 "Expires: ".&http_date(time()+$config{'expires'})."\r\n";
2434 $rv = &write_keep_alive();
2435 &write_data("\r\n");
2436 &reset_byte_count();
2437 while(read(FILE, $buf, 1024) > 0) {
2444 &log_request($acpthost, $authuser, $reqline,
2445 $logged_code ? $logged_code :
2446 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2450 # http_error(code, message, body, [dontexit])
2453 local $eh = $error_handler_recurse ? undef :
2454 $config{"error_handler_$_[0]"} ? $config{"error_handler_$_[0]"} :
2455 $config{'error_handler'} ? $config{'error_handler'} : undef;
2456 print DEBUG "http_error code=$_[0] message=$_[1] body=$_[2]\n";
2458 # Call a CGI program for the error
2460 $querystring = "code=$_[0]&message=".&urlize($_[1]).
2461 "&body=".&urlize($_[2]);
2462 $error_handler_recurse++;
2464 $ok_message = $_[1];
2468 # Use the standard error message display
2469 &write_data("HTTP/1.0 $_[0] $_[1]\r\n");
2470 &write_data("Server: $config{server}\r\n");
2471 &write_data("Date: $datestr\r\n");
2472 &write_data("Content-type: text/html\r\n");
2473 &write_keep_alive(0);
2474 &write_data("\r\n");
2475 &reset_byte_count();
2476 &write_data("<h1>Error - $_[1]</h1>\n");
2478 &write_data("<pre>$_[2]</pre>\n");
2481 &log_request($acpthost, $authuser, $reqline, $_[0], &byte_count())
2483 &log_error($_[1], $_[2] ? " : $_[2]" : "");
2490 if ($_[0] =~ /\.([A-z0-9]+)$/) {
2496 return "text/plain";
2499 # simplify_path(path, bogus)
2500 # Given a path, maybe containing stuff like ".." and "." convert it to a
2501 # clean, absolute form.
2504 local($dir, @bits, @fixedbits, $b);
2506 $dir =~ s/\\/\//g; # fix windows \ in path
2509 $dir =~ s/\0//g; # remove null bytes
2510 @bits = split(/\/+/, $dir);
2513 foreach $b (@bits) {
2517 elsif ($b eq ".." || $b eq "...") {
2519 if (scalar(@fixedbits) == 0) {
2527 push(@fixedbits, $b);
2530 return "/" . join('/', @fixedbits);
2534 # Converts a string from base64 format to normal
2537 local($str) = $_[0];
2539 $str =~ tr|A-Za-z0-9+=/||cd;
2541 $str =~ tr|A-Za-z0-9+/| -_|;
2542 while ($str =~ /(.{1,60})/gs) {
2543 my $len = chr(32 + length($1)*3/4);
2544 $res .= unpack("u", $len . $1 );
2549 # ip_match(remoteip, localip, [match]+)
2550 # Checks an IP address against a list of IPs, networks and networks/masks
2553 local(@io, @mo, @ms, $i, $j, $hn, $needhn);
2554 @io = split(/\./, $_[0]);
2555 for($i=2; $i<@_; $i++) {
2556 $needhn++ if ($_[$i] =~ /^\*(\S+)$/);
2558 if ($needhn && !defined($hn = $ip_match_cache{$_[0]})) {
2559 $hn = gethostbyaddr(inet_aton($_[0]), AF_INET);
2560 $hn = "" if (&to_ipaddress($hn) ne $_[0]);
2561 $ip_match_cache{$_[0]} = $hn;
2563 for($i=2; $i<@_; $i++) {
2564 local $mismatch = 0;
2565 if ($_[$i] =~ /^(\S+)\/(\d+)$/) {
2566 # Convert CIDR to netmask format
2567 $_[$i] = $1."/".&prefix_to_mask($2);
2569 if ($_[$i] =~ /^(\S+)\/(\S+)$/) {
2570 # Compare with network/mask
2571 @mo = split(/\./, $1); @ms = split(/\./, $2);
2572 for($j=0; $j<4; $j++) {
2573 if ((int($io[$j]) & int($ms[$j])) != int($mo[$j])) {
2578 elsif ($_[$i] =~ /^\*(\S+)$/) {
2579 # Compare with hostname regexp
2580 $mismatch = 1 if ($hn !~ /$1$/);
2582 elsif ($_[$i] eq 'LOCAL') {
2583 # Compare with local network
2584 local @lo = split(/\./, $_[1]);
2586 $mismatch = 1 if ($lo[0] != $io[0]);
2588 elsif ($lo[0] < 192) {
2589 $mismatch = 1 if ($lo[0] != $io[0] ||
2593 $mismatch = 1 if ($lo[0] != $io[0] ||
2598 elsif ($_[$i] !~ /^[0-9\.]+$/) {
2599 # Compare with hostname
2600 $mismatch = 1 if ($_[0] ne &to_ipaddress($_[$i]));
2603 # Compare with IP or network
2604 @mo = split(/\./, $_[$i]);
2605 while(@mo && !$mo[$#mo]) { pop(@mo); }
2606 for($j=0; $j<@mo; $j++) {
2607 if ($mo[$j] != $io[$j]) {
2612 return 1 if (!$mismatch);
2617 # users_match(&uinfo, user, ...)
2618 # Returns 1 if a user is in a list of users and groups
2621 local $uinfo = shift(@_);
2623 local @ginfo = getgrgid($uinfo->[3]);
2625 if ($u =~ /^\@(\S+)$/) {
2626 return 1 if (&is_group_member($uinfo, $1));
2628 elsif ($u =~ /^(\d*)-(\d*)$/ && ($1 || $2)) {
2629 return (!$1 || $uinfo[2] >= $1) &&
2630 (!$2 || $uinfo[2] <= $2);
2633 return 1 if ($u eq $uinfo->[0]);
2639 # restart_miniserv()
2640 # Called when a SIGHUP is received to restart the web server. This is done
2641 # by exec()ing perl with the same command line as was originally used
2642 sub restart_miniserv
2644 print STDERR "restarting miniserv\n";
2645 &log_error("Restarting");
2647 &close_all_sockets();
2649 dbmclose(%sessiondb);
2650 kill('KILL', $logclearer) if ($logclearer);
2651 kill('KILL', $extauth) if ($extauth);
2652 exec($perl_path, $miniserv_path, @miniserv_argv);
2653 die "Failed to restart miniserv with $perl_path $miniserv_path";
2670 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2671 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/) { push(@rv, $i); }
2672 else { push(@rv, join('.', unpack("CCCC", inet_aton($i)))); }
2674 return wantarray ? @rv : $rv[0];
2677 # read_line(no-wait, no-limit)
2678 # Reads one line from SOCK or SSL
2681 local ($nowait, $nolimit) = @_;
2682 local($idx, $more, $rv);
2683 while(($idx = index($main::read_buffer, "\n")) < 0) {
2684 if (length($main::read_buffer) > 10000 && !$nolimit) {
2685 &http_error(414, "Request too long",
2686 "Received excessive line <pre>$main::read_buffer</pre>");
2689 # need to read more..
2690 &wait_for_data_error() if (!$nowait);
2692 $more = Net::SSLeay::read($ssl_con);
2695 local $ok = sysread(SOCK, $more, 1024);
2696 $more = undef if ($ok <= 0);
2700 $rv = $main::read_buffer;
2701 undef($main::read_buffer);
2704 $main::read_buffer .= $more;
2706 $rv = substr($main::read_buffer, 0, $idx+1);
2707 $main::read_buffer = substr($main::read_buffer, $idx+1);
2712 # Reads up to some amount of data from SOCK or the SSL connection
2716 if (length($main::read_buffer)) {
2717 if (length($main::read_buffer) > $_[0]) {
2718 # Return the first part of the buffer
2719 $rv = substr($main::read_buffer, 0, $_[0]);
2720 $main::read_buffer = substr($main::read_buffer, $_[0]);
2724 # Return the whole buffer
2725 $rv = $main::read_buffer;
2726 undef($main::read_buffer);
2731 # Call SSL read function
2732 return Net::SSLeay::read($ssl_con, $_[0]);
2735 # Just do a normal read
2737 sysread(SOCK, $buf, $_[0]) || return undef;
2743 # Read a line from a file handle, using sysread to get a byte at a time
2750 $got = sysread($fh, $buf, 1);
2751 last if ($got <= 0);
2753 last if ($buf eq "\n");
2758 # wait_for_data(secs)
2759 # Waits at most the given amount of time for some data on SOCK, returning
2760 # 0 if not found, 1 if some arrived.
2764 vec($rmask, fileno(SOCK), 1) = 1;
2765 local $got = select($rmask, undef, undef, $_[0]);
2766 return $got == 0 ? 0 : 1;
2769 # wait_for_data_error()
2770 # Waits 60 seconds for data on SOCK, and fails if none arrives
2771 sub wait_for_data_error
2773 local $got = &wait_for_data(60);
2775 &http_error(400, "Timeout",
2776 "Waited more than 60 seconds for request data");
2780 # write_data(data, ...)
2781 # Writes a string to SOCK or the SSL connection
2784 local $str = join("", @_);
2786 Net::SSLeay::write($ssl_con, $str);
2789 syswrite(SOCK, $str, length($str));
2791 # Intentionally introduce a small delay to avoid problems where IE reports
2792 # the page as empty / DNS failed when it get a large response too quickly!
2793 select(undef, undef, undef, .01) if ($write_data_count%10 == 0);
2794 $write_data_count += length($str);
2797 # reset_byte_count()
2798 sub reset_byte_count { $write_data_count = 0; }
2801 sub byte_count { return $write_data_count; }
2803 # log_request(hostname, user, request, code, bytes)
2806 if ($config{'log'}) {
2807 local ($user, $ident, $headers);
2808 if ($config{'logident'}) {
2809 # add support for rfc1413 identity checking here
2811 else { $ident = "-"; }
2812 $user = $_[1] ? $_[1] : "-";
2813 local $dstr = &make_datestr();
2814 if (fileno(MINISERVLOG)) {
2815 seek(MINISERVLOG, 0, 2);
2818 open(MINISERVLOG, ">>$config{'logfile'}");
2819 chmod(0600, $config{'logfile'});
2821 if (defined($config{'logheaders'})) {
2822 foreach $h (split(/\s+/, $config{'logheaders'})) {
2823 $headers .= " $h=\"$header{$h}\"";
2826 elsif ($config{'logclf'}) {
2827 $headers = " \"$header{'referer'}\" \"$header{'user-agent'}\"";
2832 print MINISERVLOG "$_[0] $ident $user [$dstr] \"$_[2]\" ",
2833 "$_[3] $_[4]$headers\n";
2841 local @tm = localtime(time());
2842 return sprintf "%2.2d/%s/%4.4d:%2.2d:%2.2d:%2.2d %s",
2843 $tm[3], $month[$tm[4]], $tm[5]+1900,
2844 $tm[2], $tm[1], $tm[0], $timezone;
2847 # log_error(message)
2851 print STDERR "[",&make_datestr(),"] ",
2852 $acpthost ? ( "[",$acpthost,"] " ) : ( ),
2853 $page ? ( $page," : " ) : ( ),
2857 # read_errors(handle)
2858 # Read and return all input from some filehandle
2861 local($fh, $_, $rv);
2863 while(<$fh>) { $rv .= $_; }
2867 sub write_keep_alive
2870 if ($config{'nokeepalive'}) {
2871 # Keep alives have been disabled in config
2874 elsif (@childpids > $config{'maxconns'}*.8) {
2875 # Disable because nearing process limit
2879 # Keep alive specified by caller
2883 # Keep alive determined by browser
2884 $mode = $header{'connection'} =~ /keep-alive/i;
2886 &write_data("Connection: ".($mode ? "Keep-Alive" : "close")."\r\n");
2892 kill('TERM', @childpids) if (@childpids);
2893 kill('KILL', $logclearer) if ($logclearer);
2894 kill('KILL', $extauth) if ($extauth);
2900 local @tm = gmtime($_[0]);
2901 return sprintf "%s, %d %s %d %2.2d:%2.2d:%2.2d GMT",
2902 $weekday[$tm[6]], $tm[3], $month[$tm[4]], $tm[5]+1900,
2903 $tm[2], $tm[1], $tm[0];
2908 my $i; bless \$i, shift;
2914 my($buf,$len,$offset) = @_;
2915 &write_to_sock(substr($buf, $offset, $len));
2922 my $buf = join(defined($,) ? $, : "", @_);
2923 $buf .= $\ if defined($\);
2924 &write_to_sock($buf);
2931 &write_to_sock(sprintf $fmt, @_);
2934 # Send back already read data while we have it, then read from SOCK
2938 my $bufref = \$_[0];
2941 if ($postpos < length($postinput)) {
2942 # Reading from already fetched array
2943 my $left = length($postinput) - $postpos;
2944 my $canread = $len > $left ? $left : $len;
2945 substr($$bufref, $offset, $canread) =
2946 substr($postinput, $postpos, $canread);
2947 $postpos += $canread;
2951 # Read from network socket
2952 local $data = &read_data($len);
2953 if ($data eq '' && $len) {
2955 print STDERR "finished reading - shutting down socket\n";
2958 substr($$bufref, $offset, length($data)) = $data;
2959 return length($data);
2965 #print STDERR "open() called - should never happen!\n";
2968 # Read a line of input
2972 if ($postpos < length($postinput) &&
2973 ($idx = index($postinput, "\n", $postpos)) >= 0) {
2974 # A line exists in the memory buffer .. use it
2975 my $line = substr($postinput, $postpos, $idx-$postpos+1);
2980 # Need to read from the socket
2982 if ($postpos < length($postinput)) {
2983 # Start with in-memory data
2984 $line = substr($postinput, $postpos);
2985 $postpos = length($postinput);
2987 my $nl = &read_line(0, 1);
2990 print STDERR "finished reading - shutting down socket\n";
2993 $line .= $nl if (defined($nl));
2998 # Read one character of input
3003 my $got = READ($r, \$buf, 1, 0);
3004 return $got > 0 ? $buf : undef;
3009 return fileno(SOCK);
3016 # write_to_sock(data, ...)
3021 if ($doneheaders || $miniserv::nph_script) {
3026 while(!$doneheaders && $headers =~ s/^([^\r\n]*)(\r)?\n//) {
3027 if ($1 =~ /^(\S+):\s+(.*)$/) {
3028 $cgiheader{lc($1)} = $2;
3029 push(@cgiheader, [ $1, $2 ]);
3031 elsif ($1 !~ /\S/) {
3035 &http_error(500, "Bad Header");
3039 if ($cgiheader{"location"}) {
3041 "HTTP/1.0 302 Moved Temporarily\r\n");
3042 &write_data("Date: $datestr\r\n");
3043 &write_data("Server: $config{server}\r\n");
3044 &write_keep_alive(0);
3046 elsif ($cgiheader{"content-type"} eq "") {
3047 &http_error(500, "Missing Content-Type Header");
3050 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
3051 &write_data("Date: $datestr\r\n");
3052 &write_data("Server: $config{server}\r\n");
3053 &write_keep_alive(0);
3055 foreach $h (@cgiheader) {
3056 &write_data("$h->[0]: $h->[1]\r\n");
3058 &write_data("\r\n");
3059 &reset_byte_count();
3060 &write_data($headers);
3068 local $cert = Net::SSLeay::X509_STORE_CTX_get_current_cert($_[1]);
3070 local $errnum = Net::SSLeay::X509_STORE_CTX_get_error($_[1]);
3071 $verified_client = 1 if (!$errnum);
3078 if ($doing_cgi_eval && $$ == $main_process_id) {
3079 # A CGI program called exit! This is a horrible hack to
3080 # finish up before really exiting
3083 close($PASSINw); close($PASSOUTw);
3084 &log_request($acpthost, $authuser, $reqline,
3085 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
3090 # Convert a string to a form ok for putting in a URL
3092 local($tmp, $tmp2, $c);
3095 while(($c = chop($tmp)) ne "") {
3096 if ($c !~ /[A-z0-9]/) {
3097 $c = sprintf("%%%2.2X", ord($c));
3104 # validate_user(username, password, host)
3105 # Checks if some username and password are valid. Returns the modified username,
3106 # the expired / temp pass flag, and the non-existence flag
3109 local ($user, $pass, $host) = @_;
3110 return ( ) if (!$user);
3111 print DEBUG "validate_user: user=$user pass=$pass host=$host\n";
3112 local ($canuser, $canmode, $notexist, $webminuser, $sudo) =
3113 &can_user_login($user, undef, $host);
3114 print DEBUG "validate_user: canuser=$canuser canmode=$canmode notexist=$notexist webminuser=$webminuser sudo=$sudo\n";
3116 # User doesn't even exist, so go no further
3117 return ( undef, 0, 1 );
3119 elsif ($canmode == 0) {
3120 # User does exist but cannot login
3121 return ( $canuser, 0, 0 );
3123 elsif ($canmode == 1) {
3124 # Attempt Webmin authentication
3125 my $uinfo = &get_user_details($webminuser);
3127 &password_crypt($pass, $uinfo->{'pass'}) eq $uinfo->{'pass'}) {
3128 # Password is valid .. but check for expiry
3129 local $lc = $uinfo->{'lastchanges'};
3130 print DEBUG "validate_user: Password is valid lc=$lc pass_maxdays=$config{'pass_maxdays'}\n";
3131 if ($config{'pass_maxdays'} && $lc && !$uinfo->{'nochange'}) {
3132 local $daysold = (time() - $lc)/(24*60*60);
3133 print DEBUG "maxdays=$config{'pass_maxdays'} daysold=$daysold temppass=$uinfo->{'temppass'}\n";
3134 if ($config{'pass_lockdays'} &&
3135 $daysold > $config{'pass_lockdays'}) {
3136 # So old that the account is locked
3137 return ( undef, 0, 0 );
3139 elsif ($daysold > $config{'pass_maxdays'}) {
3140 # Password has expired
3141 return ( $user, 1, 0 );
3144 if ($uinfo->{'temppass'}) {
3145 # Temporary password - force change now
3146 return ( $user, 2, 0 );
3148 return ( $user, 0, 0 );
3151 print DEBUG "validate_user: User $webminuser not found\n";
3152 return ( undef, 0, 0 );
3155 print DEBUG "validate_user: User $webminuser password mismatch $pass != $uinfo->{'pass'}\n";
3156 return ( undef, 0, 0 );
3159 elsif ($canmode == 2 || $canmode == 3) {
3160 # Attempt PAM or passwd file authentication
3161 local $val = &validate_unix_user($canuser, $pass);
3162 print DEBUG "validate_user: unix val=$val\n";
3163 if ($val && $sudo) {
3164 # Need to check if this Unix user can sudo
3165 if (!&check_sudo_permissions($canuser, $pass)) {
3166 print DEBUG "validate_user: sudo failed\n";
3170 print DEBUG "validate_user: sudo passed\n";
3173 return $val == 2 ? ( $canuser, 1, 0 ) :
3174 $val == 1 ? ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3176 elsif ($canmode == 4) {
3177 # Attempt external authentication
3178 return &validate_external_user($canuser, $pass) ?
3179 ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3187 # validate_unix_user(user, password)
3188 # Returns 1 if a username and password are valid under unix, 0 if not,
3189 # or 2 if the account has expired.
3190 # Checks PAM if available, and falls back to reading the system password
3192 sub validate_unix_user
3196 $pam_username = $_[0];
3197 $pam_password = $_[1];
3198 eval "use Authen::PAM;";
3199 local $pamh = new Authen::PAM($config{'pam'}, $pam_username,
3202 local $pam_ret = $pamh->pam_authenticate();
3203 if ($pam_ret == PAM_SUCCESS()) {
3204 # Logged in OK .. make sure password hasn't expired
3205 local $acct_ret = $pamh->pam_acct_mgmt();
3206 if ($acct_ret == PAM_SUCCESS()) {
3207 $pamh->pam_open_session();
3210 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3211 $acct_ret == PAM_ACCT_EXPIRED()) {
3215 print STDERR "Unknown pam_acct_mgmt return value : $acct_ret\n";
3222 elsif ($config{'pam_only'}) {
3223 # Pam is not available, but configuration forces it's use!
3226 elsif ($config{'passwd_file'}) {
3227 # Check in a password file
3229 open(FILE, $config{'passwd_file'});
3230 if ($config{'passwd_file'} eq '/etc/security/passwd') {
3231 # Assume in AIX format
3234 if (/^\s*(\S+):/ && $1 eq $_[0]) {
3236 if (/^\s*password\s*=\s*(\S+)\s*$/) {
3237 $rv = $1 eq &password_crypt($_[1], $1) ?
3245 # Read the system password or shadow file
3247 local @l = split(/:/, $_, -1);
3248 local $u = $l[$config{'passwd_uindex'}];
3249 local $p = $l[$config{'passwd_pindex'}];
3251 $rv = $p eq &password_crypt($_[1], $p) ? 1 : 0;
3252 if ($config{'passwd_cindex'} ne '' && $rv) {
3253 # Password may have expired!
3254 local $c = $l[$config{'passwd_cindex'}];
3255 local $m = $l[$config{'passwd_mindex'}];
3256 local $day = time()/(24*60*60);
3257 if ($c =~ /^\d+/ && $m =~ /^\d+/ &&
3263 if ($p eq "" && $config{'passwd_blank'}) {
3264 # Force password change
3272 return $rv if ($rv);
3275 # Fallback option - check password returned by getpw*
3276 local @uinfo = getpwnam($_[0]);
3277 if ($uinfo[1] ne '' && &password_crypt($_[1], $uinfo[1]) eq $uinfo[1]) {
3281 return 0; # Totally failed
3284 # validate_external_user(user, pass)
3285 # Validate a user by passing the username and password to an external
3286 # squid-style authentication program
3287 sub validate_external_user
3289 return 0 if (!$config{'extauth'});
3291 local $str = "$_[0] $_[1]\n";
3292 syswrite(EXTAUTH, $str, length($str));
3293 local $resp = <EXTAUTH>;
3295 return $resp =~ /^OK/i ? 1 : 0;
3298 # can_user_login(username, no-append, host)
3299 # Checks if a user can login or not.
3300 # First return value is the username.
3301 # Second is 0 if cannot login, 1 if using Webmin pass, 2 if PAM, 3 if password
3302 # file, 4 if external.
3303 # Third is 1 if the user does not exist at all, 0 if he does.
3304 # Fourth is the Webmin username whose permissions apply, based on unixauth.
3305 # Fifth is a flag indicating if a sudo check is needed.
3308 local $uinfo = &get_user_details($_[0]);
3310 # See if this user exists in Unix and can be validated by the same
3311 # method as the unixauth webmin user
3312 local $realuser = $unixauth{$_[0]};
3316 eval { @uinfo = getpwnam($_[0]); }; # may fail on windows
3317 if (!$realuser && @uinfo) {
3318 # No unixauth entry for the username .. try his groups
3319 foreach my $ua (keys %unixauth) {
3320 if ($ua =~ /^\@(.*)$/) {
3321 if (&is_group_member(\@uinfo, $1)) {
3322 $realuser = $unixauth{$ua};
3328 if (!$realuser && @uinfo) {
3329 # Fall back to unix auth for all Unix users
3330 $realuser = $unixauth{"*"};
3332 if (!$realuser && $use_sudo && @uinfo) {
3333 # Allow login effectively as root, if sudo permits it
3337 if (!$realuser && !@uinfo && $config{'pamany'}) {
3338 # If the user completely doesn't exist, we can still allow
3339 # him to authenticate via PAM
3340 $realuser = $config{'pamany'};
3344 # For Usermin, always fall back to unix auth for any user,
3345 # so that later checks with domain added / removed are done.
3346 $realuser = $unixauth{"*"};
3348 return (undef, 0, 1, undef) if (!$realuser);
3349 local $uinfo = &get_user_details($realuser);
3350 return (undef, 0, 1, undef) if (!$uinfo);
3351 local $up = $uinfo->{'pass'};
3353 # Work out possible domain names from the hostname
3354 local @doms = ( $_[2] );
3355 if ($_[2] =~ /^([^\.]+)\.(\S+)$/) {
3359 if ($config{'user_mapping'} && !%user_mapping) {
3360 # Read the user mapping file
3362 open(MAPPING, $config{'user_mapping'});
3366 if (/^(\S+)\s+(\S+)/) {
3367 if ($config{'user_mapping_reverse'}) {
3368 $user_mapping{$1} = $2;
3371 $user_mapping{$2} = $1;
3378 # Check the user mapping file to see if there is an entry for the
3379 # user login in which specifies a new effective user
3381 foreach my $d (@doms) {
3382 $um ||= $user_mapping{"$_[0]\@$d"};
3384 $um ||= $user_mapping{$_[0]};
3385 if (defined($um) && ($_[1]&4) == 0) {
3386 # A mapping exists - use it!
3387 return &can_user_login($um, $_[1]+4, $_[2]);
3390 # Check if a user with the entered login and the domains appended
3391 # or prepended exists, and if so take it to be the effective user
3392 if (!@uinfo && $config{'domainuser'}) {
3393 # Try again with name.domain and name.firstpart
3394 local @firsts = map { /^([^\.]+)/; $1 } @doms;
3395 if (($_[1]&1) == 0) {
3397 foreach $a (@firsts, @doms) {
3398 foreach $p ("$_[0].${a}", "$_[0]-${a}",
3399 "${a}.$_[0]", "${a}-$_[0]",
3400 "$_[0]_${a}", "${a}_$_[0]") {
3401 local @vu = &can_user_login(
3402 $p, $_[1]+1, $_[2]);
3403 return @vu if ($vu[1]);
3409 # Check if the user entered a domain at the end of his username when
3410 # he really shouldn't have, and if so try without it
3411 if (!@uinfo && $config{'domainstrip'} &&
3412 $_[0] =~ /^(\S+)\@(\S+)$/ && ($_[1]&2) == 0) {
3413 local ($stripped, $dom) = ($1, $2);
3414 local @vu = &can_user_login($stripped, $_[1] + 2, $_[2]);
3415 return @vu if ($vu[1]);
3416 local @vu = &can_user_login($stripped, $_[1] + 2, $dom);
3417 return @vu if ($vu[1]);
3420 return ( undef, 0, 1, undef ) if (!@uinfo && !$pamany);
3423 if (defined(@allowusers)) {
3424 # Only allow people on the allow list
3425 return ( undef, 0, 0, undef )
3426 if (!&users_match(\@uinfo, @allowusers));
3428 elsif (defined(@denyusers)) {
3429 # Disallow people on the deny list
3430 return ( undef, 0, 0, undef )
3431 if (&users_match(\@uinfo, @denyusers));
3433 if ($config{'shells_deny'}) {
3435 open(SHELLS, $config{'shells_deny'});
3439 $found++ if ($_ eq $uinfo[8]);
3442 return ( undef, 0, 0, undef ) if (!$found);
3447 # PAM or passwd file authentication
3448 print DEBUG "can_user_login: Validate with PAM\n";
3449 return ( $_[0], $use_pam ? 2 : 3, 0, $realuser, $sudo );
3451 elsif ($up eq 'e') {
3452 # External authentication
3453 print DEBUG "can_user_login: Validate externally\n";
3454 return ( $_[0], 4, 0, $realuser, $sudo );
3457 # Fixed Webmin password
3458 print DEBUG "can_user_login: Validate by Webmin\n";
3459 return ( $_[0], 1, 0, $realuser, $sudo );
3462 elsif ($uinfo->{'pass'} eq 'x') {
3463 # Webmin user authenticated via PAM or password file
3464 return ( $_[0], $use_pam ? 2 : 3, 0, $_[0] );
3466 elsif ($uinfo->{'pass'} eq 'e') {
3467 # Webmin user authenticated externally
3468 return ( $_[0], 4, 0, $_[0] );
3471 # Normal Webmin user
3472 return ( $_[0], 1, 0, $_[0] );
3476 # the PAM conversation function for interactive logins
3479 $pam_conv_func_called++;
3486 $ans = $pam_username if ($code == PAM_PROMPT_ECHO_ON() );
3487 $ans = $pam_password if ($code == PAM_PROMPT_ECHO_OFF() );
3489 push @res, PAM_SUCCESS();
3492 push @res, PAM_SUCCESS();
3501 # get_socket_name(handle, ipv6-flag)
3502 # Returns the local hostname or IP address of some connection
3505 local ($fh, $ipv6) = @_;
3506 return $config{'host'} if ($config{'host'});
3507 local $sn = getsockname($fh);
3508 return undef if (!$sn);
3511 $myaddr = (unpack_sockaddr_in6($sn))[1];
3514 $myaddr = (unpack_sockaddr_in($sn))[1];
3516 if (!$get_socket_name_cache{$myaddr}) {
3518 if (!$config{'no_resolv_myname'}) {
3519 $myname = gethostbyaddr($myaddr,
3520 $ipv6 ? Socket6::AF_INET6() : AF_INET);
3522 if ($myname eq "") {
3524 $myname = inet_ntop(Socket6::AF_INET6(), $myaddr);
3527 $myname = inet_ntoa($myaddr);
3530 $get_socket_name_cache{$myaddr} = $myname;
3532 return $get_socket_name_cache{$myaddr};
3535 # run_login_script(username, sid, remoteip, localip)
3536 sub run_login_script
3538 if ($config{'login_script'}) {
3539 system($config{'login_script'}.
3540 " ".join(" ", map { quotemeta($_) || '""' } @_).
3541 " >/dev/null 2>&1 </dev/null");
3545 # run_logout_script(username, sid, remoteip, localip)
3546 sub run_logout_script
3548 if ($config{'logout_script'}) {
3549 system($config{'logout_script'}.
3550 " ".join(" ", map { quotemeta($_) || '""' } @_).
3551 " >/dev/null 2>&1 </dev/null");
3555 # close_all_sockets()
3556 # Closes all the main listening sockets
3557 sub close_all_sockets
3560 foreach $s (@socketfhs) {
3566 # Close all pipes for talking to sub-processes
3570 foreach $p (@passin) { close($p); }
3571 foreach $p (@passout) { close($p); }
3572 foreach $p (values %conversations) {
3573 if ($p->{'PAMOUTr'}) {
3574 close($p->{'PAMOUTr'});
3575 close($p->{'PAMINw'});
3580 # check_user_ip(user)
3581 # Returns 1 if some user is allowed to login from the accepting IP, 0 if not
3584 local ($username) = @_;
3585 local $uinfo = &get_user_details($username);
3586 return 1 if (!$uinfo);
3587 if ($uinfo->{'deny'} &&
3588 &ip_match($acptip, $localip, @{$uinfo->{'deny'}}) ||
3589 $uinfo->{'allow'} &&
3590 !&ip_match($acptip, $localip, @{$uinfo->{'allow'}})) {
3596 # check_user_time(user)
3597 # Returns 1 if some user is allowed to login at the current date and time
3600 local ($username) = @_;
3601 local $uinfo = &get_user_details($username);
3602 return 1 if (!$uinfo || !$uinfo->{'allowdays'} && !$uinfo->{'allowhours'});
3603 local @tm = localtime(time());
3604 if ($uinfo->{'allowdays'}) {
3605 # Make sure day is allowed
3606 return 0 if (&indexof($tm[6], @{$uinfo->{'allowdays'}}) < 0);
3608 if ($uinfo->{'allowhours'}) {
3609 # Make sure time is allowed
3610 local $m = $tm[2]*60+$tm[1];
3611 return 0 if ($m < $uinfo->{'allowhours'}->[0] ||
3612 $m > $uinfo->{'allowhours'}->[1]);
3617 # generate_random_id(password, [force-urandom])
3618 # Returns a random session ID number
3619 sub generate_random_id
3621 local ($pass, $force_urandom) = @_;
3623 if (!$bad_urandom) {
3624 # First try /dev/urandom, unless we have marked it as bad
3625 $SIG{ALRM} = "miniserv::urandom_timeout";
3627 if (open(RANDOM, "/dev/urandom")) {
3629 if (read(RANDOM, $tmpsid, 16) == 16) {
3630 $sid = lc(unpack('h*',$tmpsid));
3636 if (!$sid && !$force_urandom) {
3639 foreach $c (split(//, &unix_crypt($pass, substr($$, -2)))) {
3640 $sid += ord($c) * $mul;
3647 # handle_login(username, ok, expired, not-exists, password, [no-test-cookie])
3648 # Called from handle_session to either mark a user as logged in, or not
3651 local ($vu, $ok, $expired, $nonexist, $pass, $notest) = @_;
3652 $authuser = $vu if ($ok);
3654 # check if the test cookie is set
3655 if ($header{'cookie'} !~ /testing=1/ && $vu &&
3656 !$config{'no_testing_cookie'} && !$notest) {
3657 &http_error(500, "No cookies",
3658 "Your browser does not support cookies, ".
3659 "which are required for this web server to ".
3660 "work in session authentication mode");
3663 # check with main process for delay
3664 if ($config{'passdelay'} && $vu) {
3665 print DEBUG "handle_login: requesting delay vu=$vu acptip=$acptip ok=$ok\n";
3666 print $PASSINw "delay $vu $acptip $ok\n";
3667 <$PASSOUTr> =~ /(\d+) (\d+)/;
3670 print DEBUG "handle_login: delay=$1 blocked=$2\n";
3673 if ($ok && (!$expired ||
3674 $config{'passwd_mode'} == 1)) {
3675 # Logged in OK! Tell the main process about
3677 local $sid = &generate_random_id($pass);
3678 print DEBUG "handle_login: sid=$sid\n";
3679 print $PASSINw "new $sid $authuser $acptip\n";
3681 # Run the post-login script, if any
3682 &run_login_script($authuser, $sid,
3685 # Check for a redirect URL for the user
3686 local $rurl = &login_redirect($authuser, $pass, $host);
3687 print DEBUG "handle_login: redirect URL rurl=$rurl\n";
3689 # Got one .. go to it
3690 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3691 &write_data("Date: $datestr\r\n");
3692 &write_data("Server: $config{'server'}\r\n");
3693 &write_data("Location: $rurl\r\n");
3694 &write_keep_alive(0);
3695 &write_data("\r\n");
3696 &log_request($acpthost, $authuser, $reqline, 302, 0);
3699 # Set cookie and redirect to originally requested page
3700 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3701 &write_data("Date: $datestr\r\n");
3702 &write_data("Server: $config{'server'}\r\n");
3703 local $ssl = $use_ssl || $config{'inetd_ssl'};
3704 $portstr = $port == 80 && !$ssl ? "" :
3705 $port == 443 && $ssl ? "" : ":$port";
3706 $prot = $ssl ? "https" : "http";
3707 local $sec = $ssl ? "; secure" : "";
3708 #$sec .= "; httpOnly";
3709 if ($in{'page'} !~ /^\/[A-Za-z0-9\/\.\-\_]+$/) {
3710 # Make redirect URL safe
3714 &write_data("Set-Cookie: $sidname=$sid; path=/; expires=\"Thu, 31-Dec-2037 00:00:00\"$sec\r\n");
3717 &write_data("Set-Cookie: $sidname=$sid; path=/$sec\r\n");
3719 &write_data("Location: $prot://$host$portstr$in{'page'}\r\n");
3720 &write_keep_alive(0);
3721 &write_data("\r\n");
3722 &log_request($acpthost, $authuser, $reqline, 302, 0);
3723 syslog("info", "%s", "Successful login as $authuser from $acpthost") if ($use_syslog);
3724 &write_login_utmp($authuser, $acpthost);
3728 elsif ($ok && $expired &&
3729 ($config{'passwd_mode'} == 2 || $expired == 2)) {
3730 # Login was ok, but password has expired or was temporary. Need
3731 # to force display of password change form.
3734 $querystring = "&user=".&urlize($vu).
3736 "&expired=".$expired;
3739 $page = $config{'password_form'};
3741 $miniserv_internal = 2;
3742 syslog("crit", "%s",
3743 "Expired login as $vu ".
3744 "from $acpthost") if ($use_syslog);
3747 # Login failed, or password has expired. The login form will be
3748 # displayed again by later code
3750 $request_uri = $in{'page'};
3751 $already_session_id = undef;
3753 $authuser = $baseauthuser = undef;
3754 syslog("crit", "%s",
3755 ($nonexist ? "Non-existent" :
3756 $expired ? "Expired" : "Invalid").
3757 " login as $vu from $acpthost")
3763 # write_login_utmp(user, host)
3764 # Record the login by some user in utmp
3765 sub write_login_utmp
3768 # Write utmp record for login
3769 %utmp = ( 'ut_host' => $_[1],
3770 'ut_time' => time(),
3772 'ut_type' => 7, # user process
3773 'ut_pid' => $main_process_id,
3774 'ut_line' => $config{'pam'},
3776 if (defined(&User::Utmp::putut)) {
3777 User::Utmp::putut(\%utmp);
3780 User::Utmp::pututline(\%utmp);
3785 # write_logout_utmp(user, host)
3786 # Record the logout by some user in utmp
3787 sub write_logout_utmp
3790 # Write utmp record for logout
3791 %utmp = ( 'ut_host' => $_[1],
3792 'ut_time' => time(),
3794 'ut_type' => 8, # dead process
3795 'ut_pid' => $main_process_id,
3796 'ut_line' => $config{'pam'},
3798 if (defined(&User::Utmp::putut)) {
3799 User::Utmp::putut(\%utmp);
3802 User::Utmp::pututline(\%utmp);
3807 # pam_conversation_process(username, write-pipe, read-pipe)
3808 # This function is called inside a sub-process to communicate with PAM. It sends
3809 # questions down one pipe, and reads responses from another
3810 sub pam_conversation_process
3812 local ($user, $writer, $reader) = @_;
3813 $miniserv::pam_conversation_process_writer = $writer;
3814 $miniserv::pam_conversation_process_reader = $reader;
3815 eval "use Authen::PAM;";
3816 local $convh = new Authen::PAM(
3817 $config{'pam'}, $user, \&miniserv::pam_conversation_process_func);
3818 local $pam_ret = $convh->pam_authenticate();
3819 if ($pam_ret == PAM_SUCCESS()) {
3820 local $acct_ret = $convh->pam_acct_mgmt();
3821 if ($acct_ret == PAM_SUCCESS()) {
3822 $convh->pam_open_session();
3823 print $writer "x2 $user 1 0 0\n";
3825 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3826 $acct_ret == PAM_ACCT_EXPIRED()) {
3827 print $writer "x2 $user 1 1 0\n";
3830 print $writer "x0 Unknown PAM account status $acct_ret\n";
3834 print $writer "x2 $user 0 0 0\n";
3839 # pam_conversation_process_func(type, message, [type, message, ...])
3840 # A pipe that talks to both PAM and the master process
3841 sub pam_conversation_process_func
3844 select($miniserv::pam_conversation_process_writer); $| = 1; select(STDOUT);
3846 local ($type, $msg) = (shift, shift);
3848 local $ok = (print $miniserv::pam_conversation_process_writer "$type $msg\n");
3849 print $miniserv::pam_conversation_process_writer "\n";
3850 local $answer = <$miniserv::pam_conversation_process_reader>;
3851 $answer =~ s/\r|\n//g;
3852 push(@rv, PAM_SUCCESS(), $answer);
3854 push(@rv, PAM_SUCCESS());
3859 # Returns 4 new pipe file handles
3862 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3864 local %taken = ( (map { $_, 1 } @passin),
3865 (map { $_->{'PASSINr'} } values %conversations) );
3866 for($p=0; $taken{"PASSINr$p"}; $p++) { }
3867 $PASSINr = "PASSINr$p";
3868 $PASSINw = "PASSINw$p";
3869 $PASSOUTr = "PASSOUTr$p";
3870 $PASSOUTw = "PASSOUTw$p";
3871 pipe($PASSINr, $PASSINw);
3872 pipe($PASSOUTr, $PASSOUTw);
3873 select($PASSINw); $| = 1;
3874 select($PASSINr); $| = 1;
3875 select($PASSOUTw); $| = 1;
3876 select($PASSOUTw); $| = 1;
3878 return ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3881 # recv_pam_question(&conv, fd)
3882 # Reads one PAM question from the sub-process, and sends it to the HTTP handler.
3883 # Returns 0 if the conversation is over, 1 if not.
3884 sub recv_pam_question
3886 local ($conf, $fh) = @_;
3887 local $pr = $conf->{'PAMOUTr'};
3888 select($pr); $| = 1; select(STDOUT);
3889 local $line = <$pr>;
3890 $line =~ s/\r|\n//g;
3893 $line =~ s/\r|\n//g;
3895 $conf->{'last'} = time();
3898 print $fh "0 PAM conversation error\n";
3902 local ($type, $msg) = split(/\s+/, $line, 2);
3903 if ($type =~ /^x(\d+)/) {
3904 # Pass this status code through
3905 print $fh "$1 $msg\n";
3906 return $1 == 2 || $1 == 0 ? 0 : 1;
3908 elsif ($type == PAM_PROMPT_ECHO_ON()) {
3910 print $fh "1 $msg\n";
3913 elsif ($type == PAM_PROMPT_ECHO_OFF()) {
3915 print $fh "3 $msg\n";
3918 elsif ($type == PAM_ERROR_MSG() || $type == PAM_TEXT_INFO()) {
3919 # A message that does not require a response
3920 print $fh "4 $msg\n";
3925 print $fh "0 Unknown PAM message type $type\n";
3931 # send_pam_answer(&conv, answer)
3932 # Sends a response from the user to the PAM sub-process
3935 local ($conf, $answer) = @_;
3936 local $pw = $conf->{'PAMINw'};
3937 $conf->{'last'} = time();
3938 print $pw "$answer\n";
3941 # end_pam_conversation(&conv)
3942 # Clean up PAM conversation pipes and processes
3943 sub end_pam_conversation
3946 kill('KILL', $conv->{'pid'}) if ($conv->{'pid'});
3947 if ($conv->{'PAMINr'}) {
3948 close($conv->{'PAMINr'});
3949 close($conv->{'PAMOUTr'});
3950 close($conv->{'PAMINw'});
3951 close($conv->{'PAMOUTw'});
3953 delete($conversations{$conv->{'cid'}});
3956 # get_ipkeys(&miniserv)
3957 # Returns a list of IP address to key file mappings from a miniserv.conf entry
3961 foreach $k (keys %{$_[0]}) {
3962 if ($k =~ /^ipkey_(\S+)/) {
3963 local $ipkey = { 'ips' => [ split(/,/, $1) ],
3964 'key' => $_[0]->{$k},
3965 'index' => scalar(@rv) };
3966 $ipkey->{'cert'} = $_[0]->{'ipcert_'.$1};
3973 # create_ssl_context(keyfile, [certfile])
3974 sub create_ssl_context
3976 local ($keyfile, $certfile) = @_;
3978 eval { $ssl_ctx = Net::SSLeay::new_x_ctx() };
3979 $ssl_ctx ||= Net::SSLeay::CTX_new();
3980 $ssl_ctx || die "Failed to create SSL context : $!";
3981 if ($client_certs) {
3982 Net::SSLeay::CTX_load_verify_locations(
3983 $ssl_ctx, $config{'ca'}, "");
3984 Net::SSLeay::CTX_set_verify(
3985 $ssl_ctx, &Net::SSLeay::VERIFY_PEER, \&verify_client);
3987 if ($config{'extracas'}) {
3989 foreach $p (split(/\s+/, $config{'extracas'})) {
3990 Net::SSLeay::CTX_load_verify_locations(
3995 Net::SSLeay::CTX_use_RSAPrivateKey_file(
3997 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL key $keyfile";
3998 Net::SSLeay::CTX_use_certificate_file(
3999 $ssl_ctx, $certfile || $keyfile,
4000 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL cert $certfile";
4005 # ssl_connection_for_ip(socket)
4006 # Returns a new SSL connection object for some socket, or undef if failed
4007 sub ssl_connection_for_ip
4010 local $sn = getsockname($sock);
4012 print STDERR "Failed to get address for socket $sock\n";
4015 local $myip = inet_ntoa((unpack_sockaddr_in($sn))[1]);
4016 local $ssl_ctx = $ssl_contexts{$myip} || $ssl_contexts{"*"};
4017 local $ssl_con = Net::SSLeay::new($ssl_ctx);
4018 if ($config{'ssl_cipher_list'}) {
4019 # Force use of ciphers
4020 eval "Net::SSLeay::set_cipher_list(
4021 \$ssl_con, \$config{'ssl_cipher_list'})";
4023 print STDERR "SSL cipher $config{'ssl_cipher_list'} failed : ",
4029 Net::SSLeay::set_fd($ssl_con, fileno($sock));
4030 if (!Net::SSLeay::accept($ssl_con)) {
4031 print STDERR "Failed to initialize SSL connection\n";
4037 # login_redirect(username, password, host)
4038 # Calls the login redirect script (if configured), which may output a URL to
4039 # re-direct a user to after logging in.
4042 return undef if (!$config{'login_redirect'});
4043 local $quser = quotemeta($_[0]);
4044 local $qpass = quotemeta($_[1]);
4045 local $qhost = quotemeta($_[2]);
4046 local $url = `$config{'login_redirect'} $quser $qpass $qhost`;
4051 # reload_config_file()
4052 # Re-read %config, and call post-config actions
4053 sub reload_config_file
4055 &log_error("Reloading configuration");
4056 %config = &read_config_file($config_file);
4057 &update_vital_config();
4060 &build_config_mappings();
4061 &read_webmin_crons();
4062 if ($config{'session'}) {
4063 dbmclose(%sessiondb);
4064 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
4068 # read_config_file(file)
4069 # Reads the given config file, and returns a hash of values
4070 sub read_config_file
4073 open(CONF, $_[0]) || die "Failed to open config file $_[0] : $!";
4076 if (/^#/ || !/\S/) { next; }
4078 $name = $1; $val = $2;
4079 $name =~ s/^\s+//g; $name =~ s/\s+$//g;
4080 $val =~ s/^\s+//g; $val =~ s/\s+$//g;
4087 # update_vital_config()
4088 # Updates %config with defaults, and dies if something vital is missing
4089 sub update_vital_config
4091 my %vital = ("port", 80,
4093 "server", "MiniServ/0.01",
4094 "index_docs", "index.html index.htm index.cgi index.php",
4095 "addtype_html", "text/html",
4096 "addtype_txt", "text/plain",
4097 "addtype_gif", "image/gif",
4098 "addtype_jpg", "image/jpeg",
4099 "addtype_jpeg", "image/jpeg",
4100 "realm", "MiniServ",
4101 "session_login", "/session_login.cgi",
4102 "pam_login", "/pam_login.cgi",
4103 "password_form", "/password_form.cgi",
4104 "password_change", "/password_change.cgi",
4108 "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\$",
4110 "expires", 7*24*60*60,
4111 "pam_test_user", "root",
4113 foreach my $v (keys %vital) {
4115 if ($vital{$v} eq "") {
4116 die "Missing config option $v";
4118 $config{$v} = $vital{$v};
4121 if (!$config{'sessiondb'}) {
4122 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4123 $config{'sessiondb'} = "$1/sessiondb";
4125 if (!$config{'errorlog'}) {
4126 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
4127 $config{'errorlog'} = "$1/miniserv.error";
4129 if (!$config{'tempbase'}) {
4130 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4131 $config{'tempbase'} = "$1/cgitemp";
4133 if (!$config{'blockedfile'}) {
4134 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4135 $config{'blockedfile'} = "$1/blocked";
4137 if (!$config{'webmincron_dir'}) {
4138 $config_file =~ /^(.*)\/[^\/]+$/;
4139 $config{'webmincron_dir'} = "$1/webmincron/crons";
4141 if (!$config{'webmincron_last'}) {
4142 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
4143 $config{'webmincron_last'} = "$1/miniserv.lastcrons";
4145 if (!$config{'webmincron_wrapper'}) {
4146 $config{'webmincron_wrapper'} = $config{'root'}.
4147 "/webmincron/webmincron.pl";
4152 # Fills the %users and %certs hashes from the users file in %config
4161 undef(%lastchanges);
4164 if ($config{'userfile'}) {
4165 open(USERS, $config{'userfile'});
4168 local @user = split(/:/, $_, -1);
4169 $users{$user[0]} = $user[1];
4170 $certs{$user[0]} = $user[3] if ($user[3]);
4171 if ($user[4] =~ /^allow\s+(.*)/) {
4172 $allow{$user[0]} = $config{'alwaysresolve'} ?
4173 [ split(/\s+/, $1) ] :
4174 [ &to_ipaddress(split(/\s+/, $1)) ];
4176 elsif ($user[4] =~ /^deny\s+(.*)/) {
4177 $deny{$user[0]} = $config{'alwaysresolve'} ?
4178 [ split(/\s+/, $1) ] :
4179 [ &to_ipaddress(split(/\s+/, $1)) ];
4181 if ($user[5] =~ /days\s+(\S+)/) {
4182 $allowdays{$user[0]} = [ split(/,/, $1) ];
4184 if ($user[5] =~ /hours\s+(\d+)\.(\d+)-(\d+).(\d+)/) {
4185 $allowhours{$user[0]} = [ $1*60+$2, $3*60+$4 ];
4187 $lastchanges{$user[0]} = $user[6];
4188 $nochange{$user[0]} = $user[9];
4189 $temppass{$user[0]} = $user[10];
4194 # Test user DB, if configured
4195 if ($config{'userdb'}) {
4196 my $dbh = &connect_userdb($config{'userdb'});
4198 print STDERR "Failed to open users database : $dbh\n"
4201 &disconnect_userdb($config{'userdb'}, $dbh);
4206 # get_user_details(username)
4207 # Returns a hash ref of user details, either from config files or the user DB
4208 sub get_user_details
4210 my ($username) = @_;
4211 if (exists($users{$username})) {
4213 return { 'name' => $username,
4214 'pass' => $users{$username},
4215 'certs' => $certs{$username},
4216 'allow' => $allow{$username},
4217 'deny' => $deny{$username},
4218 'allowdays' => $allowdays{$username},
4219 'allowhours' => $allowhours{$username},
4220 'lastchanges' => $lastchanges{$username},
4221 'nochange' => $nochange{$username},
4222 'temppass' => $temppass{$username},
4223 'preroot' => $config{'preroot_'.$username},
4226 if ($config{'userdb'}) {
4227 # Try querying user database
4228 if (exists($get_user_details_cache{$username})) {
4230 return $get_user_details_cache{$username};
4232 print DEBUG "get_user_details: Connecting to user database\n";
4233 my ($dbh, $proto, $prefix, $args) = &connect_userdb($config{'userdb'});
4237 print DEBUG "get_user_details: Failed : $dbh\n";
4238 print STDERR "Failed to connect to user database : $dbh\n";
4240 elsif ($proto eq "mysql" || $proto eq "postgresql") {
4241 # Fetch user ID and password with SQL
4242 print DEBUG "get_user_details: Looking for $username in SQL\n";
4243 my $cmd = $dbh->prepare(
4244 "select id,pass from webmin_user where name = ?");
4245 if (!$cmd || !$cmd->execute($username)) {
4246 print STDERR "Failed to lookup user : ",
4250 my ($id, $pass) = $cmd->fetchrow();
4253 &disconnect_userdb($config{'userdb'}, $dbh);
4254 $get_user_details_cache{$username} = undef;
4255 print DEBUG "get_user_details: User not found\n";
4258 print DEBUG "get_user_details: id=$id pass=$pass\n";
4260 # Fetch attributes and add to user object
4261 print DEBUG "get_user_details: finding user attributes\n";
4262 my $cmd = $dbh->prepare(
4263 "select attr,value from webmin_user_attr where id = ?");
4264 if (!$cmd || !$cmd->execute($id)) {
4265 print STDERR "Failed to lookup user attrs : ",
4269 $user = { 'name' => $username,
4272 'proto' => $proto };
4273 while(my ($attr, $value) = $cmd->fetchrow()) {
4274 $attrs{$attr} = $value;
4278 elsif ($proto eq "ldap") {
4279 # Fetch user DN with LDAP
4280 print DEBUG "get_user_details: Looking for $username in LDAP\n";
4281 my $rv = $dbh->search(
4283 filter => '(&(cn='.$username.')(objectClass='.
4284 $args->{'userclass'}.'))',
4286 if (!$rv || $rv->code) {
4287 print STDERR "Failed to lookup user : ",
4288 ($rv ? $rv->error : "Unknown error"),"\n";
4291 my ($u) = $rv->all_entries();
4293 &disconnect_userdb($config{'userdb'}, $dbh);
4294 $get_user_details_cache{$username} = undef;
4295 print DEBUG "get_user_details: User not found\n";
4299 # Extract attributes
4300 my $pass = $u->get_value('webminPass');
4301 $user = { 'name' => $username,
4304 'proto' => $proto };
4305 foreach my $la ($u->get_value('webminAttr')) {
4306 my ($attr, $value) = split(/=/, $la, 2);
4307 $attrs{$attr} = $value;
4311 # Convert DB attributes into user object fields
4313 print DEBUG "get_user_details: got ",scalar(keys %attrs),
4315 $user->{'certs'} = $attrs{'cert'};
4316 if ($attrs{'allow'}) {
4317 $user->{'allow'} = $config{'alwaysresolve'} ?
4318 [ split(/\s+/, $attrs{'allow'}) ] :
4319 [ &to_ipaddress(split(/\s+/,$attrs{'allow'})) ];
4321 if ($attrs{'deny'}) {
4322 $user->{'deny'} = $config{'alwaysresolve'} ?
4323 [ split(/\s+/, $attrs{'deny'}) ] :
4324 [ &to_ipaddress(split(/\s+/,$attrs{'deny'})) ];
4326 if ($attrs{'days'}) {
4327 $user->{'allowdays'} = [ split(/,/, $attrs{'days'}) ];
4329 if ($attrs{'hoursfrom'} && $attrs{'hoursto'}) {
4330 my ($hf, $mf) = split(/\./, $attrs{'hoursfrom'});
4331 my ($ht, $mt) = split(/\./, $attrs{'hoursto'});
4332 $user->{'allowhours'} = [ $hf*60+$ht, $ht*60+$mt ];
4334 $user->{'lastchanges'} = $attrs{'lastchange'};
4335 $user->{'nochange'} = $attrs{'nochange'};
4336 $user->{'temppass'} = $attrs{'temppass'};
4337 $user->{'preroot'} = $attrs{'theme'};
4339 &disconnect_userdb($config{'userdb'}, $dbh);
4340 $get_user_details_cache{$user->{'name'}} = $user;
4346 # find_user_by_cert(cert)
4347 # Returns a username looked up by certificate
4348 sub find_user_by_cert
4350 my ($peername) = @_;
4351 my $peername2 = $peername;
4352 $peername2 =~ s/Email=/emailAddress=/ || $peername2 =~ s/emailAddress=/Email=/;
4354 # First check users in local files
4355 foreach my $username (keys %certs) {
4356 if ($certs{$username} eq $peername ||
4357 $certs{$username} eq $peername2) {
4363 if ($config{'userdb'}) {
4364 my ($dbh, $proto) = &connect_userdb($config{'userdb'});
4368 elsif ($proto eq "mysql" || $proto eq "postgresql") {
4370 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 = ?");
4371 return undef if (!$cmd);
4372 foreach my $p ($peername, $peername2) {
4374 if ($cmd->execute($p)) {
4375 ($username) = $cmd->fetchrow();
4378 return $username if ($username);
4381 elsif ($proto eq "ldap") {
4383 my $rv = $dbh->search(
4385 filter => '(objectClass='.
4386 $args->{'userclass'}.')',
4388 attrs => [ 'cn', 'webminAttr' ]);
4389 if ($rv && !$rv->code) {
4390 foreach my $u ($rv->all_entries) {
4391 my @attrs = $u->get_value('webminAttr');
4392 foreach my $la (@attrs) {
4393 my ($attr, $value) = split(/=/, $la, 2);
4394 if ($attr eq "cert" &&
4395 ($value eq $peername ||
4396 $value eq $peername2)) {
4397 return $u->get_value('cn');
4407 # connect_userdb(string)
4408 # Returns a handle for talking to a user database - may be a DBI or LDAP handle.
4409 # On failure returns an error message string. In an array context, returns the
4410 # protocol type too.
4414 my ($proto, $user, $pass, $host, $prefix, $args) = &split_userdb_string($str);
4415 if ($proto eq "mysql") {
4416 # Connect to MySQL with DBI
4417 my $drh = eval "use DBI; DBI->install_driver('mysql');";
4418 $drh || return $text{'sql_emysqldriver'};
4419 my ($host, $port) = split(/:/, $host);
4420 my $cstr = "database=$prefix;host=$host";
4421 $cstr .= ";port=$port" if ($port);
4422 print DEBUG "connect_userdb: Connecting to MySQL $cstr as $user\n";
4423 my $dbh = $drh->connect($cstr, $user, $pass, { });
4424 $dbh || return &text('sql_emysqlconnect', $drh->errstr);
4425 print DEBUG "connect_userdb: Connected OK\n";
4426 return wantarray ? ($dbh, $proto, $prefix, $args) : $dbh;
4428 elsif ($proto eq "postgresql") {
4429 # Connect to PostgreSQL with DBI
4430 my $drh = eval "use DBI; DBI->install_driver('Pg');";
4431 $drh || return $text{'sql_epostgresqldriver'};
4432 my ($host, $port) = split(/:/, $host);
4433 my $cstr = "dbname=$prefix;host=$host";
4434 $cstr .= ";port=$port" if ($port);
4435 print DEBUG "connect_userdb: Connecting to PostgreSQL $cstr as $user\n";
4436 my $dbh = $drh->connect($cstr, $user, $pass);
4437 $dbh || return &text('sql_epostgresqlconnect', $drh->errstr);
4438 print DEBUG "connect_userdb: Connected OK\n";
4439 return wantarray ? ($dbh, $proto, $prefix, $args) : $dbh;
4441 elsif ($proto eq "ldap") {
4442 # Connect with perl LDAP module
4443 eval "use Net::LDAP";
4444 $@ && return $text{'sql_eldapdriver'};
4445 my ($host, $port) = split(/:/, $host);
4446 my $scheme = $args->{'scheme'} || 'ldap';
4448 $port = $scheme eq 'ldaps' ? 636 : 389;
4450 my $ldap = Net::LDAP->new($host,
4452 'scheme' => $scheme);
4453 $ldap || return &text('sql_eldapconnect', $host);
4455 if ($args->{'tls'}) {
4456 # Switch to TLS mode
4457 eval { $mesg = $ldap->start_tls(); };
4458 if ($@ || !$mesg || $mesg->code) {
4459 return &text('sql_eldaptls',
4460 $@ ? $@ : $mesg ? $mesg->error : "Unknown error");
4463 # Login to the server
4465 $mesg = $ldap->bind(dn => $user, password => $pass);
4468 $mesg = $ldap->bind(dn => $user, anonymous => 1);
4470 if (!$mesg || $mesg->code) {
4471 return &text('sql_eldaplogin', $user,
4472 $mesg ? $mesg->error : "Unknown error");
4474 return wantarray ? ($ldap, $proto, $prefix, $args) : $ldap;
4477 return "Unknown protocol $proto";
4481 # split_userdb_string(string)
4482 # Converts a string like mysql://user:pass@host/db into separate parts
4483 sub split_userdb_string
4486 if ($str =~ /^([a-z]+):\/\/([^:]*):([^\@]*)\@([a-z0-9\.\-\_]+)\/([^\?]+)(\?(.*))?$/) {
4487 my ($proto, $user, $pass, $host, $prefix, $argstr) =
4488 ($1, $2, $3, $4, $5, $7);
4489 my %args = map { split(/=/, $_, 2) } split(/\&/, $argstr);
4490 return ($proto, $user, $pass, $host, $prefix, \%args);
4495 # disconnect_userdb(string, &handle)
4496 # Closes a handle opened by connect_userdb
4497 sub disconnect_userdb
4500 if ($str =~ /^(mysql|postgresql):/) {
4504 elsif ($str =~ /^ldap:/) {
4511 # Fills %mime with entries from file in %config and extra settings in %config
4515 if ($config{"mimetypes"} ne "") {
4516 open(MIME, $config{"mimetypes"});
4519 if (/^(\S+)\s+(.*)$/) {
4521 my @exts = split(/\s+/, $2);
4522 foreach my $ext (@exts) {
4523 $mime{$ext} = $type;
4529 foreach my $k (keys %config) {
4530 if ($k !~ /^addtype_(.*)$/) { next; }
4531 $mime{$1} = $config{$k};
4535 # build_config_mappings()
4536 # Build the anonymous access list, IP access list, unauthenticated URLs list,
4537 # redirect mapping and allow and deny lists from %config
4538 sub build_config_mappings
4540 # build anonymous access list
4542 foreach my $a (split(/\s+/, $config{'anonymous'})) {
4543 if ($a =~ /^([^=]+)=(\S+)$/) {
4544 $anonymous{$1} = $2;
4548 # build IP access list
4550 foreach my $a (split(/\s+/, $config{'ipaccess'})) {
4551 if ($a =~ /^([^=]+)=(\S+)$/) {
4556 # build unauthenticated URLs list
4557 @unauth = split(/\s+/, $config{'unauth'});
4559 # build redirect mapping
4561 foreach my $r (split(/\s+/, $config{'redirect'})) {
4562 if ($r =~ /^([^=]+)=(\S+)$/) {
4567 # build prefixes to be stripped
4568 undef(@strip_prefix);
4569 foreach my $r (split(/\s+/, $config{'strip_prefix'})) {
4570 push(@strip_prefix, $r);
4573 # Init allow and deny lists
4574 @deny = split(/\s+/, $config{"deny"});
4575 @deny = &to_ipaddress(@deny) if (!$config{'alwaysresolve'});
4576 @allow = split(/\s+/, $config{"allow"});
4577 @allow = &to_ipaddress(@allow) if (!$config{'alwaysresolve'});
4580 if ($config{'allowusers'}) {
4581 @allowusers = split(/\s+/, $config{'allowusers'});
4583 elsif ($config{'denyusers'}) {
4584 @denyusers = split(/\s+/, $config{'denyusers'});
4587 # Build list of unixauth mappings
4589 foreach my $ua (split(/\s+/, $config{'unixauth'})) {
4590 if ($ua =~ /^(\S+)=(\S+)$/) {
4594 $unixauth{"*"} = $ua;
4598 # Build list of non-session-auth pages
4599 undef(%sessiononly);
4600 foreach my $sp (split(/\s+/, $config{'sessiononly'})) {
4601 $sessiononly{$sp} = 1;
4604 # Build list of logout times
4605 undef(@logouttimes);
4606 foreach my $a (split(/\s+/, $config{'logouttimes'})) {
4607 if ($a =~ /^([^=]+)=(\S+)$/) {
4608 push(@logouttimes, [ $1, $2 ]);
4611 push(@logouttimes, [ undef, $config{'logouttime'} ]);
4613 # Build list of DAV pathss
4615 foreach my $d (split(/\s+/, $config{'davpaths'})) {
4616 push(@davpaths, $d);
4618 @davusers = split(/\s+/, $config{'dav_users'});
4620 # Mobile agent substrings and hostname prefixes
4621 @mobile_agents = split(/\t+/, $config{'mobile_agents'});
4622 @mobile_prefixes = split(/\s+/, $config{'mobile_prefixes'});
4626 if ($config{'debug'}) {
4627 open(DEBUG, ">>$config{'debug'}");
4630 open(DEBUG, ">/dev/null");
4633 # Reset cache of sudo checks
4637 # is_group_member(&uinfo, groupname)
4638 # Returns 1 if some user is a primary or secondary member of a group
4641 local ($uinfo, $group) = @_;
4642 local @ginfo = getgrnam($group);
4643 return 0 if (!@ginfo);
4644 return 1 if ($ginfo[2] == $uinfo->[3]); # primary member
4645 foreach my $m (split(/\s+/, $ginfo[3])) {
4646 return 1 if ($m eq $uinfo->[0]);
4651 # prefix_to_mask(prefix)
4652 # Converts a number like 24 to a mask like 255.255.255.0
4655 return $_[0] >= 24 ? "255.255.255.".(256-(2 ** (32-$_[0]))) :
4656 $_[0] >= 16 ? "255.255.".(256-(2 ** (24-$_[0]))).".0" :
4657 $_[0] >= 8 ? "255.".(256-(2 ** (16-$_[0]))).".0.0" :
4658 (256-(2 ** (8-$_[0]))).".0.0.0";
4661 # get_logout_time(user, session-id)
4662 # Given a username, returns the idle time before he will be logged out
4665 local ($user, $sid) = @_;
4666 if (!defined($logout_time_cache{$user,$sid})) {
4668 foreach my $l (@logouttimes) {
4669 if ($l->[0] =~ /^\@(.*)$/) {
4670 # Check group membership
4671 local @uinfo = getpwnam($user);
4672 if (@uinfo && &is_group_member(\@uinfo, $1)) {
4676 elsif ($l->[0] =~ /^\//) {
4677 # Check file contents
4678 open(FILE, $l->[0]);
4695 if ($l->[0] eq $user) {
4699 last if (defined($time));
4701 $logout_time_cache{$user,$sid} = $time;
4703 return $logout_time_cache{$user,$sid};
4706 # password_crypt(password, salt)
4707 # If the salt looks like MD5 and we have a library for it, perform MD5 hashing
4708 # of a password. Otherwise, do Unix crypt.
4711 local ($pass, $salt) = @_;
4712 if ($salt =~ /^\$1\$/ && $use_md5) {
4713 return &encrypt_md5($pass, $salt);
4716 return &unix_crypt($pass, $salt);
4720 # unix_crypt(password, salt)
4721 # Performs standard Unix hashing for a password
4724 local ($pass, $salt) = @_;
4725 if ($use_perl_crypt) {
4726 return Crypt::UnixCrypt::crypt($pass, $salt);
4729 return crypt($pass, $salt);
4733 # handle_dav_request(davpath)
4734 # Pass a request on to the Net::DAV::Server module
4735 sub handle_dav_request
4738 eval "use Filesys::Virtual::Plain";
4739 eval "use Net::DAV::Server";
4740 eval "use HTTP::Request";
4741 eval "use HTTP::Headers";
4743 if ($Net::DAV::Server::VERSION eq '1.28' && $config{'dav_nolock'}) {
4744 delete $Net::DAV::Server::implemented{lock};
4745 delete $Net::DAV::Server::implemented{unlock};
4748 # Read in request data
4749 if (!$posted_data) {
4750 local $clen = $header{"content-length"};
4751 while(length($posted_data) < $clen) {
4752 $buf = &read_data($clen - length($posted_data));
4753 if (!length($buf)) {
4754 &http_error(500, "Failed to read POST request");
4756 $posted_data .= $buf;
4760 # For subsequent logging
4761 open(MINISERVLOG, ">>$config{'logfile'}");
4765 local @u = getpwnam($authuser);
4766 if ($config{'dav_remoteuser'} && !$< && $validated) {
4769 $( = $u[3]; $) = "$u[3] $u[3]";
4770 ($>, $<) = ($u[2], $u[2]);
4772 if ($config{'dav_root'} eq '*') {
4777 &http_error(500, "Unix user $authuser does not exist");
4781 $root ||= $config{'dav_root'};
4784 # Check if this user can use DAV
4786 &users_match(\@u, @davusers) ||
4787 &http_error(500, "You are not allowed to access DAV");
4791 my $filesys = Filesys::Virtual::Plain->new({root_path => $root});
4792 my $webdav = Net::DAV::Server->new();
4793 $webdav->filesys($filesys);
4795 # Make up a request object, and feed to DAV
4796 local $ho = HTTP::Headers->new;
4797 foreach my $h (keys %header) {
4798 next if (lc($h) eq "connection");
4799 $ho->header($h => $header{$h});
4802 $request_uri =~ s/^\Q$path\E//;
4803 $request_uri = "/" if ($request_uri eq "");
4805 my $request = HTTP::Request->new($method, $request_uri, $ho,
4807 if ($config{'dav_debug'}) {
4808 print STDERR "DAV request :\n";
4809 print STDERR "---------------------------------------------\n";
4810 print STDERR $request->as_string();
4811 print STDERR "---------------------------------------------\n";
4813 my $response = $webdav->run($request);
4815 # Send back the reply
4816 &write_data("HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n");
4817 local $content = $response->content();
4819 $content =~ s|href>/(.+)<|href>$path/$1<|g;
4820 $content =~ s|href>/<|href>$path<|g;
4822 foreach my $h ($response->header_field_names) {
4823 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4824 &write_data("$h: ",$response->header($h),"\r\n");
4826 &write_data("Content-length: ",length($content),"\r\n");
4827 local $rv = &write_keep_alive(0);
4828 &write_data("\r\n");
4829 &write_data($content);
4831 if ($config{'dav_debug'}) {
4832 print STDERR "DAV reply :\n";
4833 print STDERR "---------------------------------------------\n";
4834 print STDERR "HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n";
4835 foreach my $h ($response->header_field_names) {
4836 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4837 print STDERR "$h: ",$response->header($h),"\r\n";
4839 print STDERR "Content-length: ",length($content),"\r\n";
4840 print STDERR "\r\n";
4841 print STDERR $content;
4842 print STDERR "---------------------------------------------\n";
4846 &log_request($acpthost, $authuser, $reqline, $response->code(),
4847 length($response->content()));
4850 # get_system_hostname()
4851 # Returns the hostname of this system, for reporting to listeners
4852 sub get_system_hostname
4854 # On Windows, try computername environment variable
4855 return $ENV{'computername'} if ($ENV{'computername'});
4856 return $ENV{'COMPUTERNAME'} if ($ENV{'COMPUTERNAME'});
4858 # If a specific command is set, use it first
4859 if ($config{'hostname_command'}) {
4860 local $out = `($config{'hostname_command'}) 2>&1`;
4867 # First try the hostname command
4868 local $out = `hostname 2>&1`;
4869 if (!$? && $out =~ /\S/) {
4874 # Try the Sys::Hostname module
4875 eval "use Sys::Hostname";
4877 local $rv = eval "hostname()";
4883 # Must use net name on Windows
4884 local $out = `net name 2>&1`;
4885 if ($out =~ /\-+\r?\n(\S+)/) {
4892 # indexof(string, array)
4893 # Returns the index of some value in an array, or -1
4896 for($i=1; $i <= $#_; $i++) {
4897 if ($_[$i] eq $_[0]) { return $i - 1; }
4903 # has_command(command)
4904 # Returns the full path if some command is in the path, undef if not
4908 if (!$_[0]) { return undef; }
4909 if (exists($has_command_cache{$_[0]})) {
4910 return $has_command_cache{$_[0]};
4913 if ($_[0] =~ /^\//) {
4914 $rv = -x $_[0] ? $_[0] : undef;
4917 local $sp = $on_windows ? ';' : ':';
4918 foreach $d (split($sp, $ENV{PATH})) {
4919 if (-x "$d/$_[0]") {
4924 foreach my $sfx (".exe", ".com", ".bat") {
4925 if (-r "$d/$_[0]".$sfx) {
4926 $rv = "$d/$_[0]".$sfx;
4933 $has_command_cache{$_[0]} = $rv;
4937 # check_sudo_permissions(user, pass)
4938 # Returns 1 if some user can run any command via sudo
4939 sub check_sudo_permissions
4941 local ($user, $pass) = @_;
4943 # First try the pipes
4945 print DEBUG "check_sudo_permissions: querying cache for $user\n";
4946 print $PASSINw "readsudo $user\n";
4947 local $can = <$PASSOUTr>;
4949 print DEBUG "check_sudo_permissions: cache said $can\n";
4950 if ($can =~ /^\d+$/ && $can != 2) {
4955 local $ptyfh = new IO::Pty;
4956 print DEBUG "check_sudo_permissions: ptyfh=$ptyfh\n";
4958 print STDERR "Failed to create new PTY with IO::Pty\n";
4961 local @uinfo = getpwnam($user);
4963 print STDERR "Unix user $user does not exist for sudo\n";
4967 # Execute sudo in a sub-process, via a pty
4968 local $ttyfh = $ptyfh->slave();
4969 print DEBUG "check_sudo_permissions: ttyfh=$ttyfh\n";
4970 local $tty = $ptyfh->ttyname();
4971 print DEBUG "check_sudo_permissions: tty=$tty\n";
4972 chown($uinfo[2], $uinfo[3], $tty);
4974 print DEBUG "check_sudo_permissions: about to fork..\n";
4975 local $pid = fork();
4976 print DEBUG "check_sudo_permissions: fork=$pid pid=$$\n";
4978 print STDERR "fork for sudo failed : $!\n";
4983 $ptyfh->make_slave_controlling_terminal();
4984 close(STDIN); close(STDOUT); close(STDERR);
4985 untie(*STDIN); untie(*STDOUT); untie(*STDERR);
4986 close($PASSINw); close($PASSOUTr);
4987 $( = $uinfo[3]; $) = "$uinfo[3] $uinfo[3]";
4988 ($>, $<) = ($uinfo[2], $uinfo[2]);
4993 open(STDIN, "<&SUDOr");
4994 open(STDOUT, ">$tty");
4995 open(STDERR, ">&STDOUT");
4998 print "Exec failed : $!\n";
5001 print DEBUG "check_sudo_permissions: pid=$pid\n";
5003 $ptyfh->close_slave();
5005 # Send password, and get back response
5006 local $oldfh = select(SUDOw);
5009 print DEBUG "check_sudo_permissions: about to send pass\n";
5010 local $SIG{'PIPE'} = 'ignore'; # Sometimes sudo doesn't ask for a password
5011 print SUDOw $pass,"\n";
5012 print DEBUG "check_sudo_permissions: sent pass=$pass\n";
5016 print DEBUG "check_sudo_permissions: got $_";
5022 local ($ok) = ($out =~ /\(ALL\)\s+ALL/ ? 1 : 0);
5026 print $PASSINw "writesudo $user $ok\n";
5032 # is_mobile_useragent(agent)
5033 # Returns 1 if some user agent looks like a cellphone or other mobile device,
5035 sub is_mobile_useragent
5037 local ($agent) = @_;
5039 "UP.Link", # Openwave
5040 "Nokia", # All Nokias start with Nokia
5041 "MOT-", # All Motorola phones start with MOT-
5042 "SAMSUNG", # Samsung browsers
5043 "Samsung", # Samsung browsers
5044 "SEC-", # Samsung browsers
5045 "AU-MIC", # Samsung browsers
5046 "AUDIOVOX", # Audiovox
5047 "BlackBerry", # BlackBerry
5048 "hiptop", # Danger hiptop Sidekick
5049 "SonyEricsson", # Sony Ericsson
5050 "Ericsson", # Old Ericsson browsers , mostly WAP
5051 "Mitsu/1.1.A", # Mitsubishi phones
5052 "Panasonic WAP", # Panasonic old WAP phones
5053 "DoCoMo", # DoCoMo phones
5054 "Lynx", # Lynx text-mode linux browser
5055 "Links", # Another text-mode linux browser
5057 local @substrings = (
5058 "UP.Browser", # Openwave
5059 "MobilePhone", # NetFront
5060 "AU-MIC-A700", # Samsung A700 Obigo browsers
5061 "Danger hiptop", # Danger Sidekick hiptop
5062 "Windows CE", # Windows CE Pocket PC
5063 "IEMobile", # Windows mobile browser
5064 "Blazer", # Palm Treo Blazer
5065 "BlackBerry", # BlackBerries can emulate other browsers, but
5066 # they still keep this string in the UserAgent
5067 "SymbianOS", # New Series60 browser has safari in it and
5068 # SymbianOS is the only distinguishing string
5069 "iPhone", # Apple iPhone KHTML browser
5070 "iPod", # iPod touch browser
5071 "MobileSafari", # HTTP client in iPhone
5073 "Opera Mini", # Opera Mini
5074 "HTC_P3700", # HTC mobile device
5076 "webOS/", # Palm WebOS
5077 "Nintendo DS", # DSi / DSi-XL
5079 foreach my $p (@prefixes) {
5080 return 1 if ($agent =~ /^\Q$p\E/);
5082 foreach my $s (@substrings, @mobile_agents) {
5083 return 1 if ($agent =~ /\Q$s\E/);
5088 # write_blocked_file()
5089 # Writes out a text file of blocked hosts and users
5090 sub write_blocked_file
5092 open(BLOCKED, ">$config{'blockedfile'}");
5093 foreach my $d (grep { $hostfail{$_} } @deny) {
5094 print BLOCKED "host $d $hostfail{$d} $blockhosttime{$d}\n";
5096 foreach my $d (grep { $userfail{$_} } @denyusers) {
5097 print BLOCKED "user $d $userfail{$d} $blockusertime{$d}\n";
5100 chmod(0700, $config{'blockedfile'});
5105 open(PIDFILE, ">$config{'pidfile'}");
5106 printf PIDFILE "%d\n", getpid();
5108 $miniserv_main_pid = getpid();
5111 # lock_user_password(user)
5112 # Updates a user's password file entry to lock it, both in memory and on disk.
5113 # Returns 1 if done, -1 if no such user, 0 if already locked
5114 sub lock_user_password
5117 local $uinfo = &get_user_details($user);
5122 if ($uinfo->{'pass'} =~ /^\!/) {
5126 if (!$uinfo->{'proto'}) {
5127 # Write to users file
5128 $users{$user} = "!".$users{$user};
5129 open(USERS, $config{'userfile'});
5130 local @ufile = <USERS>;
5132 foreach my $u (@ufile) {
5133 local @uinfo = split(/:/, $u);
5134 if ($uinfo[0] eq $user) {
5135 $uinfo[1] = $users{$user};
5137 $u = join(":", @uinfo);
5139 open(USERS, ">$config{'userfile'}");
5145 if ($config{'userdb'}) {
5147 my ($dbh, $proto, $prefix, $args) = &connect_userdb($config{'userdb'});
5151 elsif ($proto eq "mysql" || $proto eq "postgresql") {
5152 # Update user attribute
5153 my $cmd = $dbh->prepare(
5154 "update webmin_user set pass = ? where id = ?");
5155 if (!$cmd || !$cmd->execute("!".$uinfo->{'pass'},
5158 print STDERR "Failed to lock password : ",
5162 $cmd->finish() if ($cmd);
5164 elsif ($proto eq "ldap") {
5165 # Update LDAP object
5166 my $rv = $dbh->modify($uinfo->{'id'},
5167 replace => { 'webminPass' => '!'.$uinfo->{'pass'} });
5168 if (!$rv || $rv->code) {
5169 print STDERR "Failed to lock password : ",
5170 ($rv ? $rv->error : "Unknown error"),"\n";
5174 &disconnect_userdb($config{'userdb'}, $dbh);
5178 return -1; # This should never be reached
5181 # hash_session_id(sid)
5182 # Returns an MD5 or Unix-crypted session ID
5186 if (!$hash_session_id_cache{$sid}) {
5189 $hash_session_id_cache{$sid} = &encrypt_md5($sid);
5193 $hash_session_id_cache{$sid} = &unix_crypt($sid, "XX");
5196 return $hash_session_id_cache{$sid};
5199 # encrypt_md5(string, [salt])
5200 # Returns a string encrypted in MD5 format
5203 local ($passwd, $salt) = @_;
5204 local $magic = '$1$';
5205 if ($salt =~ /^\$1\$([^\$]+)/) {
5206 # Extract actual salt from already encrypted password
5211 local $ctx = eval "new $use_md5";
5218 # Add some more stuff from the hash of the password and salt
5219 local $ctx1 = eval "new $use_md5";
5220 $ctx1->add($passwd);
5224 $ctx1->add($passwd);
5225 local $final = $ctx1->digest();
5226 for($pl=length($passwd); $pl>0; $pl-=16) {
5227 $ctx->add($pl > 16 ? $final : substr($final, 0, $pl));
5230 # This piece of code seems rather pointless, but it's in the C code that
5231 # does MD5 in PAM so it has to go in!
5234 for($i=length($passwd); $i; $i >>= 1) {
5239 $ctx->add(substr($passwd, $j, 1));
5242 $final = $ctx->digest();
5245 # This loop exists only to waste time
5246 for($i=0; $i<1000; $i++) {
5247 $ctx1 = eval "new $use_md5";
5248 $ctx1->add($i & 1 ? $passwd : $final);
5249 $ctx1->add($salt) if ($i % 3);
5250 $ctx1->add($passwd) if ($i % 7);
5251 $ctx1->add($i & 1 ? $final : $passwd);
5252 $final = $ctx1->digest();
5256 # Convert the 16-byte final string into a readable form
5258 local @final = map { ord($_) } split(//, $final);
5259 $l = ($final[ 0]<<16) + ($final[ 6]<<8) + $final[12];
5260 $rv .= &to64($l, 4);
5261 $l = ($final[ 1]<<16) + ($final[ 7]<<8) + $final[13];
5262 $rv .= &to64($l, 4);
5263 $l = ($final[ 2]<<16) + ($final[ 8]<<8) + $final[14];
5264 $rv .= &to64($l, 4);
5265 $l = ($final[ 3]<<16) + ($final[ 9]<<8) + $final[15];
5266 $rv .= &to64($l, 4);
5267 $l = ($final[ 4]<<16) + ($final[10]<<8) + $final[ 5];
5268 $rv .= &to64($l, 4);
5270 $rv .= &to64($l, 2);
5272 # Add salt if needed
5274 return $magic.$salt.'$'.$rv;
5283 local ($v, $n) = @_;
5286 $r .= $itoa64[$v & 0x3f];
5292 # read_file(file, &assoc, [&order], [lowercase])
5293 # Fill an associative array with name=value pairs from a file
5296 open(ARFILE, $_[0]) || return 0;
5299 if (!/^#/ && /^([^=]*)=(.*)$/) {
5300 $_[1]->{$_[3] ? lc($1) : $1} = $2;
5301 push(@{$_[2]}, $1) if ($_[2]);
5308 # write_file(file, array)
5309 # Write out the contents of an associative array as name=value lines
5312 local(%old, @order);
5313 &read_file($_[0], \%old, \@order);
5314 open(ARFILE, ">$_[0]");
5315 foreach $k (@order) {
5316 print ARFILE $k,"=",$_[1]->{$k},"\n" if (exists($_[1]->{$k}));
5318 foreach $k (keys %{$_[1]}) {
5319 print ARFILE $k,"=",$_[1]->{$k},"\n" if (!exists($old{$k}));
5324 # execute_ready_webmin_crons()
5325 # Find and run any cron jobs that are due, based on their last run time and
5326 # execution interval
5327 sub execute_ready_webmin_crons
5331 foreach my $cron (@webmincrons) {
5333 if (!$webmincron_last{$cron->{'id'}}) {
5334 # If not ever run before, don't run right away
5335 $webmincron_last{$cron->{'id'}} = $now;
5338 elsif ($cron->{'interval'} &&
5339 $now - $webmincron_last{$cron->{'id'}} > $cron->{'interval'}) {
5340 # Older than interval .. time to run
5343 elsif ($cron->{'mins'}) {
5344 # Check if current time matches spec, and we haven't run in the
5346 my @tm = localtime($now);
5347 if (&matches_cron($cron->{'mins'}, $tm[1]) &&
5348 &matches_cron($cron->{'hours'}, $tm[2]) &&
5349 &matches_cron($cron->{'days'}, $tm[3]) &&
5350 &matches_cron($cron->{'months'}, $tm[4]+1) &&
5351 &matches_cron($cron->{'weekdays'}, $tm[6]) &&
5352 $now - $webmincron_last{$cron->{'id'}} > 60) {
5358 print DEBUG "Running cron id=$cron->{'id'} ".
5359 "module=$cron->{'module'} func=$cron->{'func'}\n";
5360 $webmincron_last{$cron->{'id'}} = $now;
5364 # Run via a wrapper command, which we run like a CGI
5366 # Setup CGI-like environment
5367 $envtz = $ENV{"TZ"};
5368 $envuser = $ENV{"USER"};
5369 $envpath = $ENV{"PATH"};
5370 $envlang = $ENV{"LANG"};
5371 $envroot = $ENV{"SystemRoot"};
5372 $envperllib = $ENV{'PERLLIB'};
5373 foreach my $k (keys %ENV) {
5376 $ENV{"PATH"} = $envpath if ($envpath);
5377 $ENV{"TZ"} = $envtz if ($envtz);
5378 $ENV{"USER"} = $envuser if ($envuser);
5379 $ENV{"OLD_LANG"} = $envlang if ($envlang);
5380 $ENV{"SystemRoot"} = $envroot if ($envroot);
5381 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
5382 $ENV{"HOME"} = $user_homedir;
5383 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
5384 $ENV{"SERVER_ADMIN"} = $config{"email"};
5386 $ENV{"SERVER_ROOT"} = $root0;
5387 $ENV{"SERVER_REALROOT"} = $root0;
5388 $ENV{"SERVER_PORT"} = $config{'port'};
5389 $ENV{"WEBMIN_CRON"} = 1;
5390 $ENV{"DOCUMENT_ROOT"} = $root0;
5391 $ENV{"DOCUMENT_REALROOT"} = $root0;
5392 $ENV{"MINISERV_CONFIG"} = $config_file;
5393 $ENV{"HTTPS"} = "ON" if ($use_ssl);
5394 $ENV{"MINISERV_PID"} = $miniserv_main_pid;
5395 $ENV{"SCRIPT_FILENAME"} = $config{'webmincron_wrapper'};
5396 if ($ENV{"SCRIPT_FILENAME"} =~ /^\Q$root0\E(\/.*)$/) {
5397 $ENV{"SCRIPT_NAME"} = $1;
5399 $config{'webmincron_wrapper'} =~ /^(.*)\//;
5401 foreach $k (keys %config) {
5402 if ($k =~ /^env_(\S+)$/) {
5403 $ENV{$1} = $config{$k};
5407 $SIG{'CHLD'} = 'DEFAULT';
5409 # Have SOCK closed if the perl exec's something
5411 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
5414 # Run the wrapper script by evaling it
5415 $pkg = "webmincron";
5416 $0 = $config{'webmincron_wrapper'};
5418 $main_process_id = $$;
5422 do \$miniserv::config{'webmincron_wrapper'};
5426 print STDERR "Perl cron failure : $@\n";
5431 push(@childpids, $pid);
5435 # Write out file containing last run times
5436 &write_file($config{'webmincron_last'}, \%webmincron_last);
5440 # matches_cron(cron-spec, time)
5441 # Checks if some minute or hour matches some cron spec, which can be * or a list
5445 my ($spec, $tm) = @_;
5450 foreach my $s (split(/,/, $spec)) {
5452 $s =~ /^(\d+)\-(\d+)$/ && $tm >= $1 && $tm <= $2) {
5460 # read_webmin_crons()
5461 # Read all scheduled webmin cron functions and store them in the @webmincrons
5463 sub read_webmin_crons
5466 opendir(CRONS, $config{'webmincron_dir'});
5467 print DEBUG "Reading crons from $config{'webmincron_dir'}\n";
5468 foreach my $f (readdir(CRONS)) {
5469 if ($f =~ /^(\d+)\.cron$/) {
5471 &read_file("$config{'webmincron_dir'}/$f", \%cron);
5474 foreach my $n ('module', 'func') {
5476 print STDERR "Cron $1 missing $n\n";
5480 if (!$cron{'interval'} && !$cron{'mins'} && !$cron{'special'}) {
5481 print STDERR "Cron $1 missing any time spec\n";
5484 if ($cron{'special'} eq 'hourly') {
5485 # Run every hour on the hour
5487 $cron{'hours'} = '*';
5488 $cron{'days'} = '*';
5489 $cron{'months'} = '*';
5490 $cron{'weekdays'} = '*';
5492 elsif ($cron{'special'} eq 'daily') {
5493 # Run every day at midnight
5495 $cron{'hours'} = '0';
5496 $cron{'days'} = '*';
5497 $cron{'months'} = '*';
5498 $cron{'weekdays'} = '*';
5500 elsif ($cron{'special'} eq 'monthly') {
5501 # Run every month on the 1st
5503 $cron{'hours'} = '0';
5504 $cron{'days'} = '1';
5505 $cron{'months'} = '*';
5506 $cron{'weekdays'} = '*';
5508 elsif ($cron{'special'} eq 'weekly') {
5509 # Run every month on the 1st
5511 $cron{'hours'} = '0';
5512 $cron{'days'} = '*';
5513 $cron{'months'} = '*';
5514 $cron{'weekdays'} = '0';
5516 elsif ($cron{'special'} eq 'yearly' ||
5517 $cron{'special'} eq 'annually') {
5518 # Run every year on 1st january
5520 $cron{'hours'} = '0';
5521 $cron{'days'} = '1';
5522 $cron{'months'} = '1';
5523 $cron{'weekdays'} = '*';
5525 elsif ($cron{'special'}) {
5526 print STDERR "Cron $1 invalid special time $cron{'special'}\n";
5529 if ($cron{'special'}) {
5530 delete($cron{'special'});
5533 print DEBUG "adding cron id=$cron{'id'} module=$cron{'module'} func=$cron{'func'}\n";
5534 push(@webmincrons, \%cron);
5540 # Check if some address is valid IPv4, returns 1 if so.
5543 return $_[0] =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/ &&
5544 $1 >= 0 && $1 <= 255 &&
5545 $2 >= 0 && $2 <= 255 &&
5546 $3 >= 0 && $3 <= 255 &&
5547 $4 >= 0 && $4 <= 255;
5550 # Check if some IPv6 address is properly formatted, and returns 1 if so.
5551 sub check_ip6address
5553 my @blocks = split(/:/, $_[0]);
5554 return 0 if (@blocks == 0 || @blocks > 8);
5556 my $where = index($blocks[$ib],"/");
5559 my $b = substr($blocks[$ib],0,$where);
5560 $m = substr($blocks[$ib],$where+1,length($blocks[$ib])-($where+1));
5563 return 0 if ($m <0 || $m >128);
5566 foreach $b (@blocks) {
5567 return 0 if ($b ne "" && $b !~ /^[0-9a-f]{1,4}$/i);
5568 $empty++ if ($b eq "");
5570 return 0 if ($empty > 1 && !($_[0] =~ /^::/ && $empty == 2));
5574 # network_to_address(binary)
5575 # Given a network address in binary IPv4 or v4 format, return the string form
5576 sub network_to_address
5579 if (length($addr) == 4 || !$use_ipv6) {
5580 return inet_ntoa($addr);
5583 return Socket6::inet_ntop(Socket6::AF_INET6(), $addr);