2 # A very simple perl web server used by Webmin
4 # Require basic libraries
10 @itoa64 = split(//, "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
12 # Find and read config file
14 die "Usage: miniserv.pl <config file>";
16 if ($ARGV[0] =~ /^([a-z]:)?\//i) {
17 $config_file = $ARGV[0];
21 $config_file = "$pwd/$ARGV[0]";
23 %config = &read_config_file($config_file);
24 if ($config{'perllib'}) {
25 push(@INC, split(/:/, $config{'perllib'}));
26 $ENV{'PERLLIB'} .= ':'.$config{'perllib'};
30 # Check if SSL is enabled and available
32 eval "use Net::SSLeay";
35 # These functions only exist for SSLeay 1.0
36 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
37 eval "Net::SSLeay::load_error_strings()";
38 if ($config{'no_ssl2'}) {
39 eval "Net::SSLeay::CTX_set_options($ctx,&Net::SSLeay::OP_NO_SSLv2)";
41 if (defined(&Net::SSLeay::X509_STORE_CTX_get_current_cert) &&
42 defined(&Net::SSLeay::CTX_load_verify_locations) &&
43 defined(&Net::SSLeay::CTX_set_verify)) {
49 # Check if IPv6 is enabled and available
50 if ($config{'ipv6'}) {
53 push(@startup_msg, "IPv6 support enabled");
57 push(@startup_msg, "IPv6 support cannot be enabled without ".
58 "the Socket6 perl module");
62 # Check if the syslog module is available to log hacking attempts
63 if ($config{'syslog'} && !$config{'inetd'}) {
64 eval "use Sys::Syslog qw(:DEFAULT setlogsock)";
70 # check if the TCP-wrappers module is available
71 if ($config{'libwrap'}) {
72 eval "use Authen::Libwrap qw(hosts_ctl STRING_UNKNOWN)";
78 # Check if the MD5 perl module is available
84 eval "use Digest::MD5";
86 $use_md5 = "Digest::MD5";
90 # Get miniserv's perl path and location
92 open(SOURCE, $miniserv_path);
93 <SOURCE> =~ /^#!(\S+)/;
100 $linked_perl_path = readlink($perl_path);
102 @miniserv_argv = @ARGV;
104 # Check vital config options
105 &update_vital_config();
107 $sidname = $config{'sidname'};
108 die "Session authentication cannot be used in inetd mode"
109 if ($config{'inetd'} && $config{'session'});
111 # check if the PAM module is available to authenticate
112 if ($config{'assume_pam'}) {
113 # Just assume that it will work. This can also be used to work around
114 # a Solaris bug in which using PAM before forking caused it to fail
118 elsif (!$config{'no_pam'}) {
119 eval "use Authen::PAM;";
121 # check if the PAM authentication can be used by opening a
124 if (ref($pamh = new Authen::PAM($config{'pam'},
125 $config{'pam_test_user'},
127 # Now test a login to see if /etc/pam.d/webmin is set
129 $pam_conv_func_called = 0;
130 $pam_username = "test";
131 $pam_password = "test";
132 $pamh->pam_authenticate();
133 if ($pam_conv_func_called) {
135 "PAM authentication enabled");
140 "PAM test failed - maybe ".
141 "/etc/pam.d/$config{'pam'} does not exist");
146 "PAM initialization of Authen::PAM failed");
151 "Perl module Authen::PAM needed for PAM is ".
152 "not installed : $@");
155 if ($config{'pam_only'} && !$use_pam) {
156 print STDERR $startup_msg[0],"\n";
157 print STDERR "PAM use is mandatory, but could not be enabled!\n";
160 elsif ($pam_msg && !$use_pam) {
162 "Continuing without the Authen::PAM perl module");
165 # Check if the User::Utmp perl module is installed
166 if ($config{'utmp'}) {
167 eval "use User::Utmp;";
170 push(@startup_msg, "UTMP logging enabled");
174 "Perl module User::Utmp needed for Utmp logging is ".
175 "not installed : $@");
179 # See if the crypt function fails
180 eval "crypt('foo', 'xx')";
182 eval "use Crypt::UnixCrypt";
186 "Using Crypt::UnixCrypt for password encryption");
190 "crypt() function un-implemented, and Crypt::UnixCrypt ".
191 "not installed - password authentication will fail");
195 # Check if /dev/urandom really generates random IDs, by calling it twice
196 local $rand1 = &generate_random_id("foo", 1);
197 local $rand2 = &generate_random_id("foo", 2);
198 if ($rand1 eq $rand2) {
201 "Random number generator file /dev/urandom is not reliable");
204 # Check if we can call sudo
205 if ($config{'sudo'} && &has_command("sudo")) {
212 "Perl module IO::Pty needed for calling sudo is not ".
217 # init days and months for http_date
218 @weekday = ( "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" );
219 @month = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun",
220 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" );
222 # Change dir to the server root
223 @roots = ( $config{'root'} );
224 for($i=0; defined($config{"extraroot_$i"}); $i++) {
225 push(@roots, $config{"extraroot_$i"});
228 eval { $user_homedir = (getpwuid($<))[7]; };
230 # getpwuid doesn't work on windows
231 $user_homedir = $ENV{"HOME"} || $ENV{"USERPROFILE"} || "/";
238 # Setup SSL if possible and if requested
239 if (!-r $config{'keyfile'} ||
240 $config{'certfile'} && !-r $config{'certfile'}) {
241 # Key file doesn't exist!
244 @ipkeys = &get_ipkeys(\%config);
246 if ($config{'ssl_version'}) {
247 # Force an SSL version
248 $Net::SSLeay::version = $config{'ssl_version'};
249 $Net::SSLeay::ssl_version = $config{'ssl_version'};
251 $client_certs = 0 if (!-r $config{'ca'} || !%certs);
252 $ssl_contexts{"*"} = &create_ssl_context($config{'keyfile'},
253 $config{'certfile'});
254 foreach $ipkey (@ipkeys) {
255 $ctx = &create_ssl_context($ipkey->{'key'}, $ipkey->{'cert'});
256 foreach $ip (@{$ipkey->{'ips'}}) {
257 $ssl_contexts{$ip} = $ctx;
262 # Setup syslog support if possible and if requested
264 open(ERRDUP, ">&STDERR");
265 open(STDERR, ">/dev/null");
266 $log_socket = $config{"logsock"} || "unix";
267 eval 'openlog($config{"pam"}, "cons,pid,ndelay", "authpriv"); setlogsock($log_socket)';
272 local $msg = ucfirst($config{'pam'})." starting";
273 eval { syslog("info", "%s", $msg); };
277 syslog("info", "%s", $msg);
280 # All attempts to use syslog have failed..
285 open(STDERR, ">&ERRDUP");
289 # Read MIME types file and add extra types
293 if ($config{'log'}) {
294 local(@gmt, @lct, $days, $hours, $mins);
295 @gmt = gmtime(time());
296 @lct = localtime(time());
297 $days = $lct[3] - $gmt[3];
298 $hours = ($days < -1 ? 24 : 1 < $days ? -24 : $days * 24) +
300 $mins = $hours * 60 + $lct[1] - $gmt[1];
301 $timezone = ($mins < 0 ? "-" : "+"); $mins = abs($mins);
302 $timezone .= sprintf "%2.2d%2.2d", $mins/60, $mins%60;
305 # Build various maps from the config files
306 &build_config_mappings();
308 # start up external authentication program, if needed
309 if ($config{'extauth'}) {
310 socketpair(EXTAUTH, EXTAUTH2, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
311 if (!($extauth = fork())) {
315 open(STDIN, "<&EXTAUTH2");
316 open(STDOUT, ">&EXTAUTH2");
317 exec($config{'extauth'}) or die "exec failed : $!\n";
320 local $os = select(EXTAUTH);
324 # Pre-load any libraries
325 if (!$config{'inetd'}) {
326 foreach $pl (split(/\s+/, $config{'preload'})) {
327 ($pkg, $lib) = split(/=/, $pl);
328 $pkg =~ s/[^A-Za-z0-9]/_/g;
329 eval "package $pkg; do '$config{'root'}/$lib'";
331 print STDERR "Failed to pre-load $lib in $pkg : $@\n";
334 print STDERR "Pre-loaded $lib in $pkg\n";
337 foreach $pl (split(/\s+/, $config{'premodules'})) {
339 ($dir, $mod) = split(/\//, $pl);
342 ($dir, $mod) = (undef, $pl);
344 push(@INC, "$config{'root'}/$dir");
345 eval "package $mod; use $mod ()";
347 print STDERR "Failed to pre-load $mod : $@\n";
350 print STDERR "Pre-loaded $mod\n";
355 # Open debug log if set
356 if ($config{'debuglog'}) {
357 open(DEBUG, ">>$config{'debuglog'}");
358 chmod(0700, $config{'debuglog'});
359 select(DEBUG); $| = 1; select(STDOUT);
360 print DEBUG "miniserv.pl starting ..\n";
363 # Write out (empty) blocked hosts file
364 &write_blocked_file();
366 # Initially read webmin cron functions and last execution times
367 &read_webmin_crons();
368 %webmincron_last = ( );
369 &read_file($config{'webmincron_last'}, \%webmincron_last);
371 # Re-direct STDERR to a log file
372 if ($config{'errorlog'} ne '-') {
373 open(STDERR, ">>$config{'errorlog'}") || die "failed to open $config{'errorlog'} : $!";
374 if ($config{'logperms'}) {
375 chmod(oct($config{'logperms'}), $config{'errorlog'});
378 select(STDERR); $| = 1; select(STDOUT);
380 if ($config{'inetd'}) {
381 # We are being run from inetd - go direct to handling the request
382 $SIG{'HUP'} = 'IGNORE';
383 $SIG{'TERM'} = 'DEFAULT';
384 $SIG{'PIPE'} = 'DEFAULT';
385 open(SOCK, "+>&STDIN");
387 # Check if it is time for the logfile to be cleared
388 if ($config{'logclear'}) {
389 local $write_logtime = 0;
390 local @st = stat("$config{'logfile'}.time");
392 if ($st[9]+$config{'logtime'}*60*60 < time()){
395 unlink($config{'logfile'});
398 else { $write_logtime = 1; }
399 if ($write_logtime) {
400 open(LOGTIME, ">$config{'logfile'}.time");
401 print LOGTIME time(),"\n";
406 # Initialize SSL for this connection
408 $ssl_con = &ssl_connection_for_ip(SOCK);
412 # Work out the hostname for this web server
413 $host = &get_socket_name(SOCK, 0);
415 $port = $config{'port'};
416 $acptaddr = getpeername(SOCK);
419 # Work out remote and local IPs
420 (undef, $peera, undef) = &get_address_ip($acptaddr, 0);
421 (undef, $locala) = &get_socket_ip(SOCK, 0);
423 print DEBUG "main: Starting handle_request loop pid=$$\n";
424 while(&handle_request($peera, $locala)) { }
425 print DEBUG "main: Done handle_request loop pid=$$\n";
430 # Build list of sockets to listen on
431 if ($config{"bind"} && $config{"bind"} ne "*") {
432 # Listening on a specific IP
433 if (&check_ip6address($config{'bind'})) {
435 $use_ipv6 || die "Cannot bind to $config{'bind'} without IPv6";
436 push(@sockets, [ inet_pton(Socket6::AF_INET6(),$config{'bind'}),
438 Socket6::PF_INET6() ]);
442 push(@sockets, [ inet_aton($config{'bind'}),
448 # Listening on all IPs
450 # Accept IPv6 and v4 connections
451 push(@sockets, [ in6addr_any(), $config{'port'},
452 Socket6::PF_INET6() ]);
456 push(@sockets, [ INADDR_ANY, $config{'port'}, PF_INET ]);
459 foreach $s (split(/\s+/, $config{'sockets'})) {
460 if ($s =~ /^(\d+)$/) {
461 # Just listen on another port on the main IP
462 push(@sockets, [ $sockets[0]->[0], $s, $sockets[0]->[2] ]);
464 elsif ($s =~ /^\*:(\d+)$/) {
465 # Listening on all IPs on some port
467 push(@sockets, [ in6addr_any(), $config{'port'},
468 Socket6::PF_INET6() ]);
471 push(@sockets, [ INADDR_ANY, $config{'port'},
475 elsif ($s =~ /^(\S+):(\d+)$/) {
476 # Listen on a specific port and IP
477 my ($ip, $port) = ($1, $2);
478 if (&check_ip6address($ip)) {
479 $use_ipv6 || die "Cannot bind to $ip without IPv6";
480 push(@sockets, [ inet_pton(Socket6::AF_INET6(),
482 $port, Socket6::PF_INET6() ]);
485 push(@sockets, [ inet_aton($ip), $port,
489 elsif ($s =~ /^([0-9\.]+):\*$/ || $s =~ /^([0-9\.]+)$/) {
490 # Listen on the main port on another IPv4 address
491 push(@sockets, [ inet_aton($1), $sockets[0]->[1],
494 elsif (($s =~ /^([0-9a-f\:]+):\*$/ || $s =~ /^([0-9a-f\:]+)$/) &&
496 # Listen on the main port on another IPv6 address
497 push(@sockets, [ inet_pton(Socket6::AF_INET6(), $1),
499 Socket6::PF_INET6() ]);
503 # Open all the sockets
504 $proto = getprotobyname('tcp');
506 $tried_inaddr_any = 0;
507 for($i=0; $i<@sockets; $i++) {
508 print STDERR "socket=",join(" ", @{$sockets[$i]}),"\n";
510 socket($fh, $sockets[$i]->[2], SOCK_STREAM, $proto) ||
511 die "Failed to open socket family $sockets[$i]->[2] : $!";
512 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
513 $pack = $sockets[$i]->[2] eq PF_INET ?
514 pack_sockaddr_in($sockets[$i]->[1],
516 pack_sockaddr_in6($sockets[$i]->[1],
518 for($j=0; $j<5; $j++) {
519 last if (bind($fh, $pack));
523 # All attempts failed .. give up
524 if ($sockets[$i]->[0] eq INADDR_ANY ||
525 $use_ipv6 && $sockets[$i]->[0] eq in6addr_any()) {
527 "Failed to bind to port $sockets[$i]->[1] : $!");
528 $tried_inaddr_any = 1;
531 $ip = &network_to_address($sockets[$i]->[0]);
533 "Failed to bind to IP $ip port ".
534 "$sockets[$i]->[1] : $!");
538 listen($fh, SOMAXCONN);
539 push(@socketfhs, $fh);
540 $ipv6fhs{$fh} = $sockets[$i]->[2] eq PF_INET ? 0 : 1;
543 foreach $se (@sockerrs) {
544 print STDERR $se,"\n";
547 # If all binds failed, try binding to any address
548 if (!@socketfhs && !$tried_inaddr_any) {
549 print STDERR "Falling back to listening on any address\n";
551 socket($fh, PF_INET, SOCK_STREAM, $proto) ||
552 die "Failed to open socket : $!";
553 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
554 bind($fh, pack_sockaddr_in($sockets[0]->[1], INADDR_ANY)) ||
555 die "Failed to bind to port $sockets[0]->[1] : $!";
556 listen($fh, SOMAXCONN);
557 push(@socketfhs, $fh);
559 elsif (!@socketfhs && $tried_inaddr_any) {
560 die "Could not listen on any ports";
563 if ($config{'listen'}) {
564 # Open the socket that allows other webmin servers to find this one
565 $proto = getprotobyname('udp');
566 if (socket(LISTEN, PF_INET, SOCK_DGRAM, $proto)) {
567 setsockopt(LISTEN, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
568 bind(LISTEN, pack_sockaddr_in($config{'listen'}, INADDR_ANY));
569 listen(LISTEN, SOMAXCONN);
572 $config{'listen'} = 0;
576 # Split from the controlling terminal, unless configured not to
577 if (!$config{'nofork'}) {
578 if (fork()) { exit; }
580 eval { setsid(); }; # may not work on Windows
582 # Close standard file handles
583 open(STDIN, "</dev/null");
584 open(STDOUT, ">/dev/null");
585 &log_error("miniserv.pl started");
586 foreach $msg (@startup_msg) {
590 # write out the PID file
593 # Start the log-clearing process, if needed. This checks every minute
594 # to see if the log has passed its reset time, and if so clears it
595 if ($config{'logclear'}) {
596 if (!($logclearer = fork())) {
597 &close_all_sockets();
600 local $write_logtime = 0;
601 local @st = stat("$config{'logfile'}.time");
603 if ($st[9]+$config{'logtime'}*60*60 < time()){
606 unlink($config{'logfile'});
609 else { $write_logtime = 1; }
610 if ($write_logtime) {
611 open(LOGTIME, ">$config{'logfile'}.time");
612 print LOGTIME time(),"\n";
619 push(@childpids, $logclearer);
622 # Setup the logout time dbm if needed
623 if ($config{'session'}) {
624 eval "use SDBM_File";
625 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
626 eval "\$sessiondb{'1111111111'} = 'foo bar';";
628 dbmclose(%sessiondb);
629 eval "use NDBM_File";
630 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
633 delete($sessiondb{'1111111111'});
638 $SIG{'HUP'} = 'miniserv::trigger_restart';
639 $SIG{'TERM'} = 'miniserv::term_handler';
640 $SIG{'USR1'} = 'miniserv::trigger_reload';
641 $SIG{'PIPE'} = 'IGNORE';
642 local $remove_session_count = 0;
643 $need_pipes = $config{'passdelay'} || $config{'session'};
645 # wait for a new connection, or a message from a child process
647 if (@childpids <= $config{'maxconns'}) {
648 # Only accept new main socket connects when ready
650 foreach $s (@socketfhs) {
651 vec($rmask, fileno($s), 1) = 1;
655 printf STDERR "too many children (%d > %d)\n",
656 scalar(@childpids), $config{'maxconns'};
659 for($i=0; $i<@passin; $i++) {
660 vec($rmask, fileno($passin[$i]), 1) = 1;
663 vec($rmask, fileno(LISTEN), 1) = 1 if ($config{'listen'});
665 # Wait for a connection
666 local $sel = select($rmask, undef, undef, 10);
668 # Check the flag files
669 if ($config{'restartflag'} && -r $config{'restartflag'}) {
670 print STDERR "restart flag file detected\n";
671 unlink($config{'restartflag'});
674 if ($config{'reloadflag'} && -r $config{'reloadflag'}) {
675 unlink($config{'reloadflag'});
680 # Got a HUP signal while in select() .. restart now
684 # Got a USR1 signal while in select() .. re-read config
686 &reload_config_file();
688 local $time_now = time();
690 # Clean up finished processes
692 do { $pid = waitpid(-1, WNOHANG);
693 @childpids = grep { $_ != $pid } @childpids;
694 } while($pid != 0 && $pid != -1);
696 # run the unblocking procedure to check if enough time has passed to
697 # unblock hosts that heve been blocked because of password failures
699 if ($config{'blockhost_failures'}) {
701 while ($i <= $#deny) {
702 if ($blockhosttime{$deny[$i]} &&
703 $config{'blockhost_time'} != 0 &&
704 ($time_now - $blockhosttime{$deny[$i]}) >=
705 $config{'blockhost_time'}) {
706 # the host can be unblocked now
707 $hostfail{$deny[$i]} = 0;
708 splice(@deny, $i, 1);
715 # Do the same for blocked users
716 if ($config{'blockuser_failures'}) {
718 while ($i <= $#deny) {
719 if ($blockusertime{$deny[$i]} &&
720 $config{'blockuser_time'} != 0 &&
721 ($time_now - $blockusertime{$deny[$i]}) >=
722 $config{'blockuser_time'}) {
723 # the user can be unblocked now
724 $userfail{$deny[$i]} = 0;
725 splice(@denyusers, $i, 1);
732 &write_blocked_file();
735 # Check if any webmin cron jobs are ready to run
736 &execute_ready_webmin_crons();
738 if ($config{'session'} && (++$remove_session_count%50) == 0) {
739 # Remove sessions with more than 7 days of inactivity,
741 foreach $s (keys %sessiondb) {
742 local ($user, $ltime, $lip) =
743 split(/\s+/, $sessiondb{$s});
744 if ($time_now - $ltime > 7*24*60*60) {
745 &run_logout_script($s, $user);
746 &write_logout_utmp($user, $lip);
747 delete($sessiondb{$s});
750 "Timeout of session for $user");
756 if ($use_pam && $config{'pam_conv'}) {
757 # Remove PAM sessions with more than 5 minutes of inactivity
759 foreach $c (values %conversations) {
760 if ($time_now - $c->{'time'} > 5*60) {
761 &end_pam_conversation($c);
763 syslog("info", "%s", "Timeout of PAM ".
764 "session for $c->{'user'}");
770 # Don't check any sockets if there is no activity
773 # Check if any of the main sockets have received a new connection
775 foreach $s (@socketfhs) {
776 if (vec($rmask, fileno($s), 1)) {
778 $acptaddr = accept(SOCK, $s);
779 if (!$acptaddr) { next; }
780 binmode(SOCK); # turn off any Perl IO stuff
783 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
785 ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw) =
789 # Work out IP and port of client
790 local ($peerb, $peera, $peerp) =
791 &get_address_ip($acptaddr, $ipv6fhs{$s});
793 # Work out the local IP
794 (undef, $locala) = &get_socket_ip(SOCK, $ipv6fhs{$s});
796 # Check username of connecting user
797 $localauth_user = undef;
798 if ($config{'localauth'} && $peera eq "127.0.0.1") {
799 if (open(TCP, "/proc/net/tcp")) {
800 # Get the info direct from the kernel
801 $peerh = sprintf("%4.4X", $peerp);
804 local @t = split(/[\s:]+/, $_);
805 if ($t[1] eq '0100007F' &&
814 if (!$localauth_user) {
815 # Call lsof for the info
816 local $lsofpid = open(LSOF,
817 "$config{'localauth'} -i ".
818 "TCP\@127.0.0.1:$peerp |");
820 if (/^(\S+)\s+(\d+)\s+(\S+)/ &&
821 $2 != $$ && $2 != $lsofpid){
822 $localauth_user = $3;
829 # Work out the hostname for this web server
830 $host = &get_socket_name(SOCK, $ipv6fhs{$s});
833 "Failed to get local socket name : $!\n";
837 $port = $sockets[$sn]->[1];
839 # fork the subprocess
841 if (!($handpid = fork())) {
842 # setup signal handlers
843 $SIG{'TERM'} = 'DEFAULT';
844 $SIG{'PIPE'} = 'DEFAULT';
845 #$SIG{'CHLD'} = 'IGNORE';
846 $SIG{'HUP'} = 'IGNORE';
847 $SIG{'USR1'} = 'IGNORE';
849 # Initialize SSL for this connection
851 $ssl_con = &ssl_connection_for_ip(SOCK);
855 # Close the file handle for the session DBM
856 dbmclose(%sessiondb);
858 # close useless pipes
861 close($PASSINr); close($PASSOUTw);
863 &close_all_sockets();
866 # XXX IPv6 - refactor to not resolve IP again
868 "main: Starting handle_request loop pid=$$\n";
869 while(&handle_request($peera, $locala)) { }
871 "main: Done handle_request loop pid=$$\n";
874 close($PASSINw); close($PASSOUTw);
877 push(@childpids, $handpid);
879 close($PASSINw); close($PASSOUTr);
880 push(@passin, $PASSINr);
881 push(@passout, $PASSOUTw);
888 if ($config{'listen'} && vec($rmask, fileno(LISTEN), 1)) {
889 # Got UDP packet from another webmin server
891 local $from = recv(LISTEN, $rcvbuf, 1024, 0);
893 local $fromip = inet_ntoa((unpack_sockaddr_in($from))[1]);
894 local $toip = inet_ntoa((unpack_sockaddr_in(
895 getsockname(LISTEN)))[1]);
896 if ((!@deny || !&ip_match($fromip, $toip, @deny)) &&
897 (!@allow || &ip_match($fromip, $toip, @allow))) {
898 local $listenhost = &get_socket_name(LISTEN, 0);
899 send(LISTEN, "$listenhost:$config{'port'}:".
900 ($use_ssl || $config{'inetd_ssl'} ? 1 : 0).":".
901 ($config{'listenhost'} ?
902 &get_system_hostname() : ""),
908 # check for session, password-timeout and PAM messages from subprocesses
909 for($i=0; $i<@passin; $i++) {
910 if (vec($rmask, fileno($passin[$i]), 1)) {
911 # this sub-process is asking about a password
912 local $infd = $passin[$i];
913 local $outfd = $passout[$i];
914 #local $inline = <$infd>;
915 local $inline = &sysread_line($infd);
917 print DEBUG "main: inline $inline";
920 print DEBUG "main: inline EOF\n";
922 if ($inline =~ /^delay\s+(\S+)\s+(\S+)\s+(\d+)/) {
923 # Got a delay request from a subprocess.. for
924 # valid logins, there is no delay (to prevent
925 # denial of service attacks), but for invalid
926 # logins the delay increases with each failed
929 # login OK.. no delay
930 print $outfd "0 0\n";
931 $wasblocked = $hostfail{$2} ||
936 &write_blocked_file();
945 # add the host to the block list,
947 if ($config{'blockhost_failures'} &&
949 $config{'blockhost_failures'}) {
951 $blockhosttime{$2} = $time_now;
954 local $logtext = "Security alert: Host $2 blocked after $config{'blockhost_failures'} failed logins for user $1";
960 # add the user to the user block list,
962 if ($config{'blockuser_failures'} &&
964 $config{'blockuser_failures'}) {
965 push(@denyusers, $1);
966 $blockusertime{$1} = $time_now;
969 local $logtext = "Security alert: User $1 blocked after $config{'blockuser_failures'} failed logins";
975 # Lock out the user's password, if enabled
976 if ($config{'blocklock'} &&
978 $config{'blockuser_failures'}) {
979 my $lk = &lock_user_password($1);
982 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";
989 $dl = $userdlay{$1} -
990 int(($time_now - $userlast{$1})/50);
991 $dl = $dl < 0 ? 0 : $dl+1;
992 print $outfd "$dl $blocked\n";
995 # Write out blocked status file
997 &write_blocked_file();
1000 $userlast{$1} = $time_now;
1002 elsif ($inline =~ /^verify\s+(\S+)\s+(\S+)/) {
1003 # Verifying a session ID
1004 local $session_id = $1;
1005 local $notimeout = $2;
1006 local $skey = $sessiondb{$session_id} ?
1008 &hash_session_id($session_id);
1009 if (!defined($sessiondb{$skey})) {
1010 # Session doesn't exist
1011 print $outfd "0 0\n";
1014 local ($user, $ltime) =
1015 split(/\s+/, $sessiondb{$skey});
1016 local $lot = &get_logout_time($user, $session_id);
1018 $time_now - $ltime > $lot*60 &&
1020 # Session has timed out
1021 print $outfd "1 ",$time_now - $ltime,"\n";
1022 #delete($sessiondb{$skey});
1026 print $outfd "2 $user\n";
1028 $time_now - $ltime >
1030 $sessiondb{$skey} = "$user $time_now";
1035 elsif ($inline =~ /^new\s+(\S+)\s+(\S+)\s+(\S+)/) {
1036 # Creating a new session
1037 local $session_id = $1;
1040 $sessiondb{&hash_session_id($session_id)} =
1041 "$user $time_now $ip";
1043 elsif ($inline =~ /^delete\s+(\S+)/) {
1044 # Logging out a session
1045 local $session_id = $1;
1046 local $skey = $sessiondb{$session_id} ?
1048 &hash_session_id($session_id);
1049 local @sdb = split(/\s+/, $sessiondb{$skey});
1050 print $outfd $sdb[0],"\n";
1051 delete($sessiondb{$skey});
1053 elsif ($inline =~ /^pamstart\s+(\S+)\s+(\S+)\s+(.*)/) {
1054 # Starting a new PAM conversation
1055 local ($cid, $host, $user) = ($1, $2, $3);
1057 # Does this user even need PAM?
1058 local ($realuser, $canlogin) =
1059 &can_user_login($user, undef, $host);
1061 if ($canlogin == 0) {
1062 # Cannot even login!
1063 print $outfd "0 Invalid username\n";
1065 elsif ($canlogin != 2) {
1066 # Not using PAM .. so just ask for
1068 $conv = { 'user' => $realuser,
1073 print $outfd "3 Password\n";
1076 # Start the PAM conversation
1077 # sub-process, and get a question
1078 $conv = { 'user' => $realuser,
1082 local ($PAMINr, $PAMINw, $PAMOUTr,
1083 $PAMOUTw) = &allocate_pipes();
1084 local $pampid = fork();
1086 close($PAMOUTr); close($PAMINw);
1087 &pam_conversation_process(
1091 close($PAMOUTw); close($PAMINr);
1092 $conv->{'pid'} = $pampid;
1093 $conv->{'PAMOUTr'} = $PAMOUTr;
1094 $conv->{'PAMINw'} = $PAMINw;
1095 push(@childpids, $pampid);
1097 # Get the first PAM question
1098 local $pok = &recv_pam_question(
1101 &end_pam_conversation($conv);
1105 $conversations{$cid} = $conv if ($conv);
1107 elsif ($inline =~ /^pamanswer\s+(\S+)\s+(.*)/) {
1108 # A response to a PAM question
1109 local ($cid, $answer) = ($1, $2);
1110 local $conv = $conversations{$cid};
1112 # No such conversation?
1113 print $outfd "0 Bad login session\n";
1115 elsif ($conv->{'pid'}) {
1116 # Send the PAM response and get
1118 &send_pam_answer($conv, $answer);
1119 local $pok = &recv_pam_question($conv, $outfd);
1121 &end_pam_conversation($conv);
1125 # This must be the password .. try it
1126 # and send back the results
1127 local ($vu, $expired, $nonexist) =
1128 &validate_user($conv->{'user'},
1131 local $ok = $vu ? 1 : 0;
1132 print $outfd "2 $conv->{'user'} $ok $expired $notexist\n";
1133 &end_pam_conversation($conv);
1136 elsif ($inline =~ /^writesudo\s+(\S+)\s+(\d+)/) {
1137 # Store the fact that some user can sudo to root
1138 local ($user, $ok) = ($1, $2);
1139 $sudocache{$user} = $ok." ".time();
1141 elsif ($inline =~ /^readsudo\s+(\S+)/) {
1142 # Query the user sudo cache (valid for 1 minute)
1144 local ($ok, $last) =
1145 split(/\s+/, $sudocache{$user});
1146 if ($last < time()-60) {
1151 # Tell client OK or not
1152 print $outfd "$ok\n";
1155 elsif ($inline =~ /\S/) {
1156 # Unknown line from pipe?
1157 print DEBUG "main: Unknown line from pipe $inline\n";
1158 print STDERR "Unknown line from pipe $inline\n";
1162 close($infd); close($outfd);
1163 $passin[$i] = $passout[$i] = undef;
1167 @passin = grep { defined($_) } @passin;
1168 @passout = grep { defined($_) } @passout;
1171 # handle_request(remoteaddress, localaddress)
1172 # Where the real work is done
1175 local ($acptip, $localip) = @_;
1176 print DEBUG "handle_request: from $acptip to $localip\n";
1177 if ($config{'loghost'}) {
1178 $acpthost = gethostbyaddr(inet_aton($acptip), AF_INET);
1179 $acpthost = $acptip if (!$acpthost);
1182 $acpthost = $acptip;
1184 $datestr = &http_date(time());
1186 $ok_message = "Document follows";
1187 $logged_code = undef;
1188 $reqline = $request_uri = $page = undef;
1192 # check address against access list
1193 if (@deny && &ip_match($acptip, $localip, @deny) ||
1194 @allow && !&ip_match($acptip, $localip, @allow)) {
1195 &http_error(403, "Access denied for $acptip");
1200 # Check address with TCP-wrappers
1201 if (!hosts_ctl($config{'pam'}, STRING_UNKNOWN,
1202 $acptip, STRING_UNKNOWN)) {
1203 &http_error(403, "Access denied for $acptip by TCP wrappers");
1207 print DEBUG "handle_request: passed IP checks\n";
1209 # Compute a timeout for the start of headers, based on the number of
1210 # child processes. As this increases, we use a shorter timeout to avoid
1211 # an attacker overloading the system.
1212 local $header_timeout = 60 + ($config{'maxconns'} - @childpids) * 10;
1214 # Wait at most 60 secs for start of headers for initial requests, or
1215 # 10 minutes for kept-alive connections
1217 vec($rmask, fileno(SOCK), 1) = 1;
1218 local $to = $checked_timeout ? 10*60 : $header_timeout;
1219 local $sel = select($rmask, undef, undef, $to);
1221 if ($checked_timeout) {
1222 print DEBUG "handle_request: exiting due to timeout of $to\n";
1226 &http_error(400, "Timeout",
1227 "Waited for that $to seconds for start of headers");
1231 print DEBUG "handle_request: passed timeout check\n";
1233 # Read the HTTP request and headers
1234 local $origreqline = &read_line();
1235 ($reqline = $origreqline) =~ s/\r|\n//g;
1236 $method = $page = $request_uri = undef;
1237 print DEBUG "handle_request reqline=$reqline\n";
1238 if (!$reqline && (!$use_ssl || $checked_timeout > 1)) {
1239 # An empty request .. just close the connection
1240 print DEBUG "handle_request: rejecting empty request\n";
1243 elsif ($reqline !~ /^(\S+)\s+(.*)\s+HTTP\/1\..$/) {
1244 print DEBUG "handle_request: invalid reqline=$reqline\n";
1246 # This could be an http request when it should be https
1248 local $url = $config{'musthost'} ?
1249 "https://$config{'musthost'}:$port/" :
1250 "https://$host:$port/";
1251 if ($config{'ssl_redirect'}) {
1252 # Just re-direct to the correct URL
1253 sleep(1); # Give browser a change to finish
1254 # sending its request
1255 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1256 &write_data("Date: $datestr\r\n");
1257 &write_data("Server: $config{'server'}\r\n");
1258 &write_data("Location: $url\r\n");
1259 &write_keep_alive(0);
1260 &write_data("\r\n");
1264 # Tell user the correct URL
1265 &http_error(200, "Bad Request", "This web server is running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1268 elsif (ord(substr($reqline, 0, 1)) == 128 && !$use_ssl) {
1269 # This could be an https request when it should be http ..
1270 # need to fake a HTTP response
1273 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
1274 eval "Net::SSLeay::load_error_strings()";
1275 $ssl_ctx = Net::SSLeay::CTX_new();
1276 Net::SSLeay::CTX_use_RSAPrivateKey_file(
1277 $ssl_ctx, $config{'keyfile'},
1278 &Net::SSLeay::FILETYPE_PEM);
1279 Net::SSLeay::CTX_use_certificate_file(
1281 $config{'certfile'} || $config{'keyfile'},
1282 &Net::SSLeay::FILETYPE_PEM);
1283 $ssl_con = Net::SSLeay::new($ssl_ctx);
1287 select(SSLw); $| = 1; select(STDOUT);
1288 print SSLw $origreqline;
1290 while(sysread(SOCK, $buf, 1) > 0) {
1297 Net::SSLeay::set_wfd($ssl_con, fileno(SOCK));
1298 Net::SSLeay::set_rfd($ssl_con, fileno(SSLr));
1299 Net::SSLeay::accept($ssl_con) || die "accept() failed";
1301 local $url = $config{'musthost'} ?
1302 "https://$config{'musthost'}:$port/" :
1303 "https://$host:$port/";
1304 if ($config{'ssl_redirect'}) {
1305 # Just re-direct to the correct URL
1306 sleep(1); # Give browser a change to
1307 # finish sending its request
1308 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1309 &write_data("Date: $datestr\r\n");
1310 &write_data("Server: $config{'server'}\r\n");
1311 &write_data("Location: $url\r\n");
1312 &write_keep_alive(0);
1313 &write_data("\r\n");
1317 # Tell user the correct URL
1318 &http_error(200, "Bad Request", "This web server is not running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1322 &http_error(400, "Bad Request");
1326 &http_error(400, "Bad Request");
1330 $request_uri = $page = $2;
1334 ($headline = &read_line()) =~ s/\r|\n//g;
1335 last if ($headline eq "");
1336 print DEBUG "handle_request: got headline $headline\n";
1337 if ($headline =~ /^(\S+):\s*(.*)$/) {
1338 $header{$lastheader = lc($1)} = $2;
1340 elsif ($headline =~ /^\s+(.*)$/) {
1341 $header{$lastheader} .= $headline;
1344 &http_error(400, "Bad Header $headline");
1347 if (defined($header{'host'})) {
1348 if ($header{'host'} =~ /^([^:]+):([0-9]+)$/) {
1349 ($host, $port) = ($1, $2);
1352 $host = $header{'host'};
1354 if ($config{'musthost'} && $host ne $config{'musthost'}) {
1355 # Disallowed hostname used
1356 &http_error(400, "Invalid HTTP hostname");
1360 if ($page =~ /^([^\?]+)\?(.*)$/) {
1361 # There is some query string information
1364 print DEBUG "handle_request: querystring=$querystring\n";
1365 if ($querystring !~ /=/) {
1366 $queryargs = $querystring;
1367 $queryargs =~ s/\+/ /g;
1368 $queryargs =~ s/%(..)/pack("c",hex($1))/ge;
1372 # Parse query-string parameters
1373 local @in = split(/\&/, $querystring);
1375 local ($k, $v) = split(/=/, $i, 2);
1376 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1377 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1382 $posted_data = undef;
1383 if ($method eq 'POST' &&
1384 $header{'content-type'} eq 'application/x-www-form-urlencoded') {
1385 # Read in posted query string information, up the configured maximum
1386 # post request length
1387 $clen = $header{"content-length"};
1388 $clen_read = $clen > $config{'max_post'} ? $config{'max_post'} : $clen;
1389 while(length($posted_data) < $clen_read) {
1390 $buf = &read_data($clen_read - length($posted_data));
1391 if (!length($buf)) {
1392 &http_error(500, "Failed to read POST request");
1394 chomp($posted_data);
1395 $posted_data =~ s/\015$//mg;
1396 $posted_data .= $buf;
1398 print DEBUG "clen_read=$clen_read clen=$clen posted_data=",length($posted_data),"\n";
1399 if ($clen_read != $clen && length($posted_data) > $clen) {
1400 # If the client sent more data than we asked for, chop the
1402 $posted_data = substr($posted_data, 0, $clen);
1404 if (length($posted_data) > $clen) {
1405 # When the client sent too much, delay so that it gets headers
1408 if ($header{'user-agent'} =~ /MSIE/ &&
1409 $header{'user-agent'} !~ /Opera/i) {
1410 # MSIE includes an extra newline in the data
1411 $posted_data =~ s/\r|\n//g;
1413 local @in = split(/\&/, $posted_data);
1415 local ($k, $v) = split(/=/, $i, 2);
1417 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1418 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1421 print DEBUG "handle_request: posted_data=$posted_data\n";
1424 # replace %XX sequences in page
1425 $page =~ s/%(..)/pack("c",hex($1))/ge;
1427 # Check if the browser's user agent indicates a mobile device
1428 $mobile_device = &is_mobile_useragent($header{'user-agent'});
1430 # Check if Host: header is for a mobile URL
1431 foreach my $m (@mobile_prefixes) {
1432 if ($header{'host'} =~ /^\Q$m\E/i) {
1437 # check for the logout flag file, and if existant deny authentication
1438 if ($config{'logout'} && -r $config{'logout'}.$in{'miniserv_logout_id'}) {
1439 print DEBUG "handle_request: logout flag set\n";
1440 $deny_authentication++;
1441 open(LOGOUT, $config{'logout'}.$in{'miniserv_logout_id'});
1442 chop($count = <LOGOUT>);
1446 open(LOGOUT, ">$config{'logout'}$in{'miniserv_logout_id'}");
1447 print LOGOUT "$count\n";
1451 unlink($config{'logout'}.$in{'miniserv_logout_id'});
1455 # check for any redirect for the requested URL
1456 foreach my $pfx (@strip_prefix) {
1457 my $l = length($pfx);
1458 if(length($page) >= $l &&
1459 substr($page,0,$l) eq $pfx) {
1460 $page=substr($page,$l);
1464 $simple = &simplify_path($page, $bogus);
1466 $rpath .= "&".$querystring if (defined($querystring));
1467 $redir = $redirect{$rpath};
1468 if (defined($redir)) {
1469 print DEBUG "handle_request: redir=$redir\n";
1470 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1471 &write_data("Date: $datestr\r\n");
1472 &write_data("Server: $config{'server'}\r\n");
1473 local $ssl = $use_ssl || $config{'inetd_ssl'};
1474 $portstr = $port == 80 && !$ssl ? "" :
1475 $port == 443 && $ssl ? "" : ":$port";
1476 $prot = $ssl ? "https" : "http";
1477 &write_data("Location: $prot://$host$portstr$redir\r\n");
1478 &write_keep_alive(0);
1479 &write_data("\r\n");
1483 # Check for a DAV request
1485 foreach my $d (@davpaths) {
1486 if ($simple eq $d || $simple =~ /^\Q$d\E\//) {
1491 if (!$davpath && ($method eq "SEARCH" || $method eq "PUT")) {
1492 &http_error(400, "Bad Request method $method");
1495 # Check for password if needed
1496 if ($config{'userfile'}) {
1497 print DEBUG "handle_request: Need authentication\n";
1501 # Session authentication is never used for connections by
1502 # another webmin server, or for specified pages, or for DAV, or XMLRPC,
1503 # or mobile browsers if requested.
1504 if ($header{'user-agent'} =~ /webmin/i ||
1505 $header{'user-agent'} =~ /$config{'agents_nosession'}/i ||
1506 $sessiononly{$simple} || $davpath ||
1507 $simple eq "/xmlrpc.cgi" ||
1508 $acptip eq $config{'host_nosession'} ||
1509 $mobile_device && $config{'mobile_nosession'}) {
1510 print DEBUG "handle_request: Forcing HTTP authentication\n";
1511 $config{'session'} = 0;
1514 # Check for SSL authentication
1515 if ($use_ssl && $verified_client) {
1516 $peername = Net::SSLeay::X509_NAME_oneline(
1517 Net::SSLeay::X509_get_subject_name(
1518 Net::SSLeay::get_peer_certificate(
1520 $u = &find_user_by_cert($peername);
1525 if ($use_syslog && !$validated) {
1526 syslog("crit", "%s",
1527 "Unknown SSL certificate $peername");
1531 if (!$validated && !$deny_authentication) {
1532 # check for IP-based authentication
1534 foreach $a (keys %ipaccess) {
1535 if ($acptip eq $a) {
1536 # It does! Auth as the user
1538 $baseauthuser = $authuser =
1544 # Check for normal HTTP authentication
1545 if (!$validated && !$deny_authentication && !$config{'session'} &&
1546 $header{authorization} =~ /^basic\s+(\S+)$/i) {
1547 # authorization given..
1548 ($authuser, $authpass) = split(/:/, &b64decode($1), 2);
1549 print DEBUG "handle_request: doing basic auth check authuser=$authuser authpass=$authpass\n";
1550 local ($vu, $expired, $nonexist) =
1551 &validate_user($authuser, $authpass, $host);
1552 print DEBUG "handle_request: vu=$vu expired=$expired nonexist=$nonexist\n";
1553 if ($vu && (!$expired || $config{'passwd_mode'} == 1)) {
1560 if ($use_syslog && !$validated) {
1561 syslog("crit", "%s",
1562 ($nonexist ? "Non-existent" :
1563 $expired ? "Expired" : "Invalid").
1564 " login as $authuser from $acpthost");
1566 if ($authuser =~ /\r|\n|\s/) {
1567 &http_error(500, "Invalid username",
1568 "Username contains invalid characters");
1570 if ($authpass =~ /\r|\n/) {
1571 &http_error(500, "Invalid password",
1572 "Password contains invalid characters");
1575 if ($config{'passdelay'} && !$config{'inetd'} && $authuser) {
1576 # check with main process for delay
1577 print DEBUG "handle_request: about to ask for password delay\n";
1578 print $PASSINw "delay $authuser $acptip $validated\n";
1579 <$PASSOUTr> =~ /(\d+) (\d+)/;
1581 print DEBUG "handle_request: password delay $1 $2\n";
1586 # Check for a visit to the special session login page
1587 if ($config{'session'} && !$deny_authentication &&
1588 $page eq $config{'session_login'}) {
1589 if ($in{'logout'} && $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1590 # Logout clicked .. remove the session
1592 print $PASSINw "delete $sid\n";
1593 local $louser = <$PASSOUTr>;
1596 $already_session_id = undef;
1597 $authuser = $baseauthuser = undef;
1600 syslog("info", "%s", "Logout by $louser from $acpthost");
1602 &run_logout_script($louser, $sid,
1604 &write_logout_utmp($louser, $actphost);
1609 if ($in{'user'} =~ /\r|\n|\s/) {
1610 &http_error(500, "Invalid username",
1611 "Username contains invalid characters");
1613 if ($in{'pass'} =~ /\r|\n/) {
1614 &http_error(500, "Invalid password",
1615 "Password contains invalid characters");
1618 local ($vu, $expired, $nonexist) =
1619 &validate_user($in{'user'}, $in{'pass'}, $host);
1620 local $hrv = &handle_login(
1621 $vu || $in{'user'}, $vu ? 1 : 0,
1622 $expired, $nonexist, $in{'pass'},
1623 $in{'notestingcookie'});
1624 return $hrv if (defined($hrv));
1628 # Check for a visit to the special PAM login page
1629 if ($config{'session'} && !$deny_authentication &&
1630 $use_pam && $config{'pam_conv'} && $page eq $config{'pam_login'} &&
1632 # A question has been entered .. submit it to the main process
1633 print DEBUG "handle_request: Got call to $page ($in{'cid'})\n";
1634 print DEBUG "handle_request: For PAM, authuser=$authuser\n";
1635 if ($in{'answer'} =~ /\r|\n/ || $in{'cid'} =~ /\r|\n|\s/) {
1636 &http_error(500, "Invalid response",
1637 "Response contains invalid characters");
1641 # Start of a new conversation - answer must be username
1642 $cid = &generate_random_id($in{'answer'});
1643 print $PASSINw "pamstart $cid $host $in{'answer'}\n";
1646 # A response to a previous question
1648 print $PASSINw "pamanswer $cid $in{'answer'}\n";
1651 # Read back the response, and the next question (if any)
1652 local $line = <$PASSOUTr>;
1653 $line =~ s/\r|\n//g;
1654 local ($rv, $question) = split(/\s+/, $line, 2);
1657 local $hrv = &handle_login(
1658 !$in{'cid'} && $in{'answer'} ? $in{'answer'}
1661 return $hrv if (defined($hrv));
1663 elsif ($rv == 1 || $rv == 3) {
1664 # Another question .. force use of PAM CGI
1667 $querystring .= "&cid=$cid&question=".
1669 $querystring .= "&password=1" if ($rv == 3);
1671 $page = $config{'pam_login'};
1672 $miniserv_internal = 1;
1676 # Got back a final ok or failure
1677 local ($user, $ok, $expired, $nonexist) =
1678 split(/\s+/, $question);
1679 local $hrv = &handle_login(
1680 $user, $ok, $expired, $nonexist, undef,
1681 $in{'notestingcookie'});
1682 return $hrv if (defined($hrv));
1685 # A message from PAM .. tell the user
1688 $querystring .= "&cid=$cid&message=".
1691 $page = $config{'pam_login'};
1692 $miniserv_internal = 1;
1697 # Check for a visit to the special password change page
1698 if ($config{'session'} && !$deny_authentication &&
1699 $page eq $config{'password_change'} && !$validated) {
1700 # Just let this slide ..
1702 $miniserv_internal = 3;
1705 # Check for an existing session
1706 if ($config{'session'} && !$validated) {
1707 if ($already_session_id) {
1708 $session_id = $already_session_id;
1709 $authuser = $already_authuser;
1712 elsif (!$deny_authentication &&
1713 $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1714 # Try all session cookies
1715 local $cookie = $header{'cookie'};
1716 while($cookie =~ s/(^|\s)$sidname=([a-f0-9]+)//) {
1719 $in{'webmin_notimeout'} ? 1 : 0;
1720 print $PASSINw "verify $session_id $notimeout\n";
1721 <$PASSOUTr> =~ /(\d+)\s+(\S+)/;
1723 # Valid session continuation
1726 $already_authuser = $authuser;
1735 # Invalid session ID .. don't set
1742 # Check for local authentication
1743 if ($localauth_user && !$header{'x-forwarded-for'} && !$header{'via'}) {
1744 my $luser = &get_user_details($localauth_user);
1746 # Local user exists in webmin users file
1748 $authuser = $localauth_user;
1751 # Check if local user is allowed by unixauth
1752 local @can = &can_user_login($localauth_user,
1756 $authuser = $localauth_user;
1759 $localauth_user = undef;
1765 # Check if this path allows anonymous access
1767 foreach $a (keys %anonymous) {
1768 if (substr($simple, 0, length($a)) eq $a) {
1769 # It does! Auth as the user, if IP access
1770 # control allows him.
1771 if (&check_user_ip($anonymous{$a}) &&
1772 &check_user_time($anonymous{$a})) {
1774 $baseauthuser = $authuser =
1782 # Check if this path allows unauthenticated access
1783 local ($u, $unauth);
1784 foreach $u (@unauth) {
1785 $unauth++ if ($simple =~ /$u/);
1787 if (!$bogus && $unauth) {
1788 # Unauthenticated directory or file request - approve it
1790 $baseauthuser = $authuser = undef;
1795 if ($blocked == 0) {
1796 # No password given.. ask
1797 if ($config{'pam_conv'} && $use_pam) {
1798 # Force CGI for PAM question, starting with
1799 # the username which is always needed
1802 $querystring .= "&initial=1&question=".
1803 &urlize("Username");
1804 $querystring .= "&failed=$failed_user" if ($failed_user);
1805 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1807 $page = $config{'pam_login'};
1808 $miniserv_internal = 1;
1811 elsif ($config{'session'}) {
1812 # Force CGI for session login
1815 $querystring .= "&logout=1&page=/";
1818 # Re-direct to current module only
1819 local $rpage = $request_uri;
1820 if (!$config{'loginkeeppage'}) {
1821 $rpage =~ s/\?.*$//;
1822 $rpage =~ s/[^\/]+$//
1824 $querystring = "page=".&urlize($rpage);
1827 $querystring .= "&failed=$failed_user" if ($failed_user);
1828 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1830 $page = $config{'session_login'};
1831 $miniserv_internal = 1;
1835 # Ask for login with HTTP authentication
1836 &write_data("HTTP/1.0 401 Unauthorized\r\n");
1837 &write_data("Date: $datestr\r\n");
1838 &write_data("Server: $config{'server'}\r\n");
1839 &write_data("WWW-authenticate: Basic ".
1840 "realm=\"$config{'realm'}\"\r\n");
1841 &write_keep_alive(0);
1842 &write_data("Content-type: text/html\r\n");
1843 &write_data("\r\n");
1844 &reset_byte_count();
1845 &write_data("<html>\n");
1846 &write_data("<head><title>Unauthorized</title></head>\n");
1847 &write_data("<body><h1>Unauthorized</h1>\n");
1848 &write_data("A password is required to access this\n");
1849 &write_data("web server. Please try again. <p>\n");
1850 &write_data("</body></html>\n");
1851 &log_request($acpthost, undef, $reqline, 401, &byte_count());
1855 elsif ($blocked == 1) {
1856 # when the host has been blocked, give it an error
1857 &http_error(403, "Access denied for $acptip. The host ".
1858 "has been blocked because of too ".
1859 "many authentication failures.");
1861 elsif ($blocked == 2) {
1862 # when the user has been blocked, give it an error
1863 &http_error(403, "Access denied. The user ".
1864 "has been blocked because of too ".
1865 "many authentication failures.");
1869 # Get the real Webmin username
1870 local @can = &can_user_login($authuser, undef, $host);
1871 $baseauthuser = $can[3] || $authuser;
1873 if ($config{'remoteuser'} && !$< && $validated) {
1874 # Switch to the UID of the remote user (if he exists)
1875 local @u = getpwnam($authuser);
1876 if (@u && $< != $u[2]) {
1877 $( = $u[3]; $) = "$u[3] $u[3]";
1878 ($>, $<) = ($u[2], $u[2]);
1881 &http_error(500, "Unix user $authuser does not exist");
1887 # Check per-user IP access control
1888 if (!&check_user_ip($baseauthuser)) {
1889 &http_error(403, "Access denied for $acptip for $baseauthuser");
1893 # Check per-user allowed times
1894 if (!&check_user_time($baseauthuser)) {
1895 &http_error(403, "Access denied at the current time");
1899 $uinfo = &get_user_details($baseauthuser);
1901 # Validate the path, and convert to canonical form
1903 $simple = &simplify_path($page, $bogus);
1904 print DEBUG "handle_request: page=$page simple=$simple\n";
1906 &http_error(400, "Invalid path");
1909 # Check for a DAV request
1911 return &handle_dav_request($davpath);
1914 # Work out the active theme(s)
1915 local $preroots = $mobile_device && defined($config{'mobile_preroot'}) ?
1916 $config{'mobile_preroot'} :
1917 $authuser && defined($config{'preroot_'.$authuser}) ?
1918 $config{'preroot_'.$authuser} :
1919 $uinfo && defined($uinfo->{'preroot'}) ?
1920 $uinfo->{'preroot'} :
1922 local @preroots = reverse(split(/\s+/, $preroots));
1924 # Canonicalize the directories
1925 foreach my $preroot (@preroots) {
1926 # Always under the current webmin root
1927 $preroot =~ s/^.*\///g;
1928 $preroot = $roots[0].'/'.$preroot;
1931 # Look in the theme root directories first
1932 local ($full, @stfull);
1934 foreach my $preroot (@preroots) {
1937 $full = $preroot.$sofar;
1938 $scriptname = $simple;
1939 foreach $b (split(/\//, $simple)) {
1940 if ($b ne "") { $sofar .= "/$b"; }
1941 $full = $preroot.$sofar;
1942 @stfull = stat($full);
1943 if (!@stfull) { undef($full); last; }
1945 # Check if this is a directory
1947 # It is.. go on parsing
1955 # Check if this is a CGI program
1956 if (&get_type($full) eq "internal/cgi") {
1957 $pathinfo = substr($simple, length($sofar));
1958 $pathinfo .= "/" if ($page =~ /\/$/);
1959 $scriptname = $sofar;
1964 # Don't stop at a directory unless this is the last theme, which
1965 # is the 'real' one that provides the .cgi scripts
1966 if ($is_directory && $preroot ne $preroots[$#preroots]) {
1973 $cgi_pwd = $roots[0];
1975 elsif ($is_directory) {
1976 $cgi_pwd = "$roots[0]$sofar";
1979 "$roots[0]$sofar" =~ /^(.*\/)[^\/]+$/;
1982 $foundroot = $preroot;
1983 if ($is_directory) {
1984 # Check for index files in the directory
1986 foreach $idx (split(/\s+/, $config{"index_docs"})) {
1987 $idxfull = "$full/$idx";
1988 local @stidxfull = stat($idxfull);
1989 if (-r _ && !-d _) {
1991 @stfull = @stidxfull;
1994 if ($scriptname ne "/");
1999 @stfull = stat($full) if (!$foundidx);
2002 last if ($foundroot);
2004 print DEBUG "handle_request: initial full=$full\n";
2006 # Look in the real root directories, stopping when we find a file or directory
2007 if (!$full || $is_directory) {
2008 ROOT: foreach $root (@roots) {
2010 $full = $root.$sofar;
2011 $scriptname = $simple;
2012 foreach $b ($simple eq "/" ? ( "" ) : split(/\//, $simple)) {
2013 if ($b ne "") { $sofar .= "/$b"; }
2014 $full = $root.$sofar;
2015 @stfull = stat($full);
2020 # Check if this is a directory
2022 # It is.. go on parsing
2026 # Check if this is a CGI program
2027 if (&get_type($full) eq "internal/cgi") {
2028 $pathinfo = substr($simple, length($sofar));
2029 $pathinfo .= "/" if ($page =~ /\/$/);
2030 $scriptname = $sofar;
2035 # Run CGI in the same directory as whatever file
2037 $full =~ /^(.*\/)[^\/]+$/; $cgi_pwd = $1;
2046 if (!@stfull) { &http_error(404, "File not found"); }
2048 print DEBUG "handle_request: full=$full\n";
2049 @stfull = stat($full) if (!@stfull);
2051 # check filename against denyfile regexp
2052 local $denyfile = $config{'denyfile'};
2053 if ($denyfile && $full =~ /$denyfile/) {
2054 &http_error(403, "Access denied to $page");
2058 # Reached the end of the path OK.. see what we've got
2060 # See if the URL ends with a / as it should
2061 print DEBUG "handle_request: found a directory\n";
2062 if ($page !~ /\/$/) {
2063 # It doesn't.. redirect
2064 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2065 $ssl = $use_ssl || $config{'inetd_ssl'};
2066 $portstr = $port == 80 && !$ssl ? "" :
2067 $port == 443 && $ssl ? "" : ":$port";
2068 &write_data("Date: $datestr\r\n");
2069 &write_data("Server: $config{server}\r\n");
2070 $prot = $ssl ? "https" : "http";
2071 &write_data("Location: $prot://$host$portstr$page/\r\n");
2072 &write_keep_alive(0);
2073 &write_data("\r\n");
2074 &log_request($acpthost, $authuser, $reqline, 302, 0);
2077 # A directory.. check for index files
2079 foreach $idx (split(/\s+/, $config{"index_docs"})) {
2080 $idxfull = "$full/$idx";
2081 @stidxfull = stat($idxfull);
2082 if (-r _ && !-d _) {
2085 @stfull = @stidxfull;
2086 $scriptname .= "/" if ($scriptname ne "/");
2091 @stfull = stat($full) if (!$foundidx);
2094 # This is definately a directory.. list it
2095 print DEBUG "handle_request: listing directory\n";
2096 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2097 "Date: $datestr\r\n".
2098 "Server: $config{server}\r\n".
2099 "Content-type: text/html\r\n";
2101 &write_keep_alive(0);
2102 &write_data("\r\n");
2103 &reset_byte_count();
2104 &write_data("<h1>Index of $simple</h1>\n");
2105 &write_data("<pre>\n");
2106 &write_data(sprintf "%-35.35s %-20.20s %-10.10s\n",
2107 "Name", "Last Modified", "Size");
2108 &write_data("<hr>\n");
2109 opendir(DIR, $full);
2110 while($df = readdir(DIR)) {
2111 if ($df =~ /^\./) { next; }
2112 $fulldf = $full eq "/" ? $full.$df : $full."/".$df;
2113 (@stbuf = stat($fulldf)) || next;
2114 if (-d _) { $df .= "/"; }
2115 @tm = localtime($stbuf[9]);
2116 $fdate = sprintf "%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d",
2117 $tm[3],$tm[4]+1,$tm[5]+1900,
2118 $tm[0],$tm[1],$tm[2];
2119 $len = length($df); $rest = " "x(35-$len);
2121 "<a href=\"%s\">%-${len}.${len}s</a>$rest %-20.20s %-10.10s\n",
2122 $df, $df, $fdate, $stbuf[7]);
2125 &log_request($acpthost, $authuser, $reqline, $ok_code, &byte_count());
2129 # CGI or normal file
2131 if (&get_type($full) eq "internal/cgi" && $validated != 4) {
2132 # A CGI program to execute
2133 print DEBUG "handle_request: executing CGI\n";
2134 $envtz = $ENV{"TZ"};
2135 $envuser = $ENV{"USER"};
2136 $envpath = $ENV{"PATH"};
2137 $envlang = $ENV{"LANG"};
2138 $envroot = $ENV{"SystemRoot"};
2139 $envperllib = $ENV{'PERLLIB'};
2140 foreach my $k (keys %ENV) {
2143 $ENV{"PATH"} = $envpath if ($envpath);
2144 $ENV{"TZ"} = $envtz if ($envtz);
2145 $ENV{"USER"} = $envuser if ($envuser);
2146 $ENV{"OLD_LANG"} = $envlang if ($envlang);
2147 $ENV{"SystemRoot"} = $envroot if ($envroot);
2148 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
2149 $ENV{"HOME"} = $user_homedir;
2150 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
2151 $ENV{"SERVER_NAME"} = $host;
2152 $ENV{"SERVER_ADMIN"} = $config{"email"};
2153 $ENV{"SERVER_ROOT"} = $roots[0];
2154 $ENV{"SERVER_REALROOT"} = $realroot;
2155 $ENV{"SERVER_PORT"} = $port;
2156 $ENV{"REMOTE_HOST"} = $acpthost;
2157 $ENV{"REMOTE_ADDR"} = $acptip;
2158 $ENV{"REMOTE_USER"} = $authuser;
2159 $ENV{"BASE_REMOTE_USER"} = $authuser ne $baseauthuser ?
2160 $baseauthuser : undef;
2161 $ENV{"REMOTE_PASS"} = $authpass if (defined($authpass) &&
2162 $config{'pass_password'});
2163 if ($uinfo && $uinfo->{'proto'}) {
2164 $ENV{"REMOTE_USER_PROTO"} = $uinfo->{'proto'};
2165 $ENV{"REMOTE_USER_ID"} = $uinfo->{'id'};
2167 print DEBUG "REMOTE_USER = ",$ENV{"REMOTE_USER"},"\n";
2168 print DEBUG "BASE_REMOTE_USER = ",$ENV{"BASE_REMOTE_USER"},"\n";
2169 print DEBUG "proto=$uinfo->{'proto'} id=$uinfo->{'id'}\n" if ($uinfo);
2170 $ENV{"SSL_USER"} = $peername if ($validated == 2);
2171 $ENV{"ANONYMOUS_USER"} = "1" if ($validated == 3 || $validated == 4);
2172 $ENV{"DOCUMENT_ROOT"} = $roots[0];
2173 $ENV{"DOCUMENT_REALROOT"} = $realroot;
2174 $ENV{"GATEWAY_INTERFACE"} = "CGI/1.1";
2175 $ENV{"SERVER_PROTOCOL"} = "HTTP/1.0";
2176 $ENV{"REQUEST_METHOD"} = $method;
2177 $ENV{"SCRIPT_NAME"} = $scriptname;
2178 $ENV{"SCRIPT_FILENAME"} = $full;
2179 $ENV{"REQUEST_URI"} = $request_uri;
2180 $ENV{"PATH_INFO"} = $pathinfo;
2182 $ENV{"PATH_TRANSLATED"} = "$roots[0]$pathinfo";
2183 $ENV{"PATH_REALTRANSLATED"} = "$realroot$pathinfo";
2185 $ENV{"QUERY_STRING"} = $querystring;
2186 $ENV{"MINISERV_CONFIG"} = $config_file;
2187 $ENV{"HTTPS"} = "ON" if ($use_ssl || $config{'inetd_ssl'});
2188 $ENV{"MINISERV_PID"} = $miniserv_main_pid;
2189 $ENV{"SESSION_ID"} = $session_id if ($session_id);
2190 $ENV{"LOCAL_USER"} = $localauth_user if ($localauth_user);
2191 $ENV{"MINISERV_INTERNAL"} = $miniserv_internal if ($miniserv_internal);
2192 if (defined($header{"content-length"})) {
2193 $ENV{"CONTENT_LENGTH"} = $header{"content-length"};
2195 if (defined($header{"content-type"})) {
2196 $ENV{"CONTENT_TYPE"} = $header{"content-type"};
2198 foreach $h (keys %header) {
2199 ($hname = $h) =~ tr/a-z/A-Z/;
2201 $ENV{"HTTP_$hname"} = $header{$h};
2203 $ENV{"PWD"} = $cgi_pwd;
2204 foreach $k (keys %config) {
2205 if ($k =~ /^env_(\S+)$/) {
2206 $ENV{$1} = $config{$k};
2209 delete($ENV{'HTTP_AUTHORIZATION'});
2210 $ENV{'HTTP_COOKIE'} =~ s/;?\s*$sidname=([a-f0-9]+)//;
2211 $ENV{'MOBILE_DEVICE'} = 1 if ($mobile_device);
2213 # Check if the CGI can be handled internally
2215 local $first = <CGI>;
2217 $first =~ s/[#!\r\n]//g;
2218 $nph_script = ($full =~ /\/nph-([^\/]+)$/);
2220 if (!$config{'forkcgis'} &&
2221 ($first eq $perl_path || $first eq $linked_perl_path) &&
2223 $config{'internalcgis'}) {
2224 # setup environment for eval
2226 @ARGV = split(/\s+/, $queryargs);
2229 # Already read the post input
2230 $postinput = $posted_data;
2232 $clen = $header{"content-length"};
2233 $SIG{'CHLD'} = 'DEFAULT';
2235 # Have SOCK closed if the perl exec's something
2237 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
2241 if ($config{'log'}) {
2242 open(MINISERVLOG, ">>$config{'logfile'}");
2243 if ($config{'logperms'}) {
2244 chmod(oct($config{'logperms'}),
2245 $config{'logfile'});
2248 chmod(0600, $config{'logfile'});
2251 $doing_cgi_eval = 1;
2252 $main_process_id = $$;
2254 if ($full =~ /^\Q$foundroot\E\/([^\/]+)\//) {
2255 # Eval in package from Webmin module name
2257 $pkg =~ s/[^A-Za-z0-9]/_/g;
2262 tie(*STDOUT, 'miniserv');
2263 tie(*STDIN, 'miniserv');
2264 do \$miniserv::full;
2267 $doing_cgi_eval = 0;
2270 &http_error(500, "Perl execution failed",
2271 $config{'noshowstderr'} ? undef : $@);
2273 elsif (!$doneheaders && !$nph_script) {
2274 &http_error(500, "Missing Headers");
2281 # fork the process that actually executes the CGI
2282 pipe(CGIINr, CGIINw);
2283 pipe(CGIOUTr, CGIOUTw);
2284 pipe(CGIERRr, CGIERRw);
2285 if (!($cgipid = fork())) {
2286 @execargs = ( $full, split(/\s+/, $queryargs) );
2289 open(STDIN, "<&CGIINr");
2290 open(STDOUT, ">&CGIOUTw");
2291 open(STDERR, ">&CGIERRw");
2292 close(CGIINw); close(CGIOUTr); close(CGIERRr);
2294 die "Failed to exec $full : $!\n";
2297 close(CGIINr); close(CGIOUTw); close(CGIERRw);
2300 # write CGI input to a temp file
2301 $infile = "$config{'tempbase'}.$$";
2302 open(CGIINw, ">$infile");
2303 # NOT binary mode, as CGIs don't read in it!
2308 # already read the posted data
2309 print CGIINw $posted_data;
2311 $clen = $header{"content-length"};
2312 if ($method eq "POST" && $clen_read < $clen) {
2313 $SIG{'PIPE'} = 'IGNORE';
2315 while($got < $clen) {
2316 $buf = &read_data($clen-$got);
2317 if (!length($buf)) {
2318 kill('TERM', $cgipid);
2319 unlink($infile) if ($infile);
2320 &http_error(500, "Failed to read ".
2323 $got += length($buf);
2324 local ($wrote) = (print CGIINw $buf);
2327 # If the CGI terminated early, we still need to read
2328 # from the browser and throw away
2329 while($got < $clen) {
2330 $buf = &read_data($clen-$got);
2331 if (!length($buf)) {
2332 kill('TERM', $cgipid);
2333 unlink($infile) if ($infile);
2334 &http_error(500, "Failed to read ".
2337 $got += length($buf);
2339 $SIG{'PIPE'} = 'DEFAULT';
2345 # Run the CGI program, and feed it input
2347 local $qqueryargs = join(" ", map { "\"$_\"" }
2348 split(/\s+/, $queryargs));
2349 if ($first =~ /(perl|perl.exe)$/i) {
2350 # On Windows, run with Perl
2351 open(CGIOUTr, "$perl_path \"$full\" $qqueryargs <$infile |");
2354 open(CGIOUTr, "\"$full\" $qqueryargs <$infile |");
2360 # read back cgi headers
2361 select(CGIOUTr); $|=1; select(STDOUT);
2365 $line =~ s/\r|\n//g;
2367 if ($got_blank || %cgiheader) { last; }
2371 if ($line !~ /^(\S+):\s+(.*)$/) {
2372 $errs = &read_errors(CGIERRr);
2373 close(CGIOUTr); close(CGIERRr);
2374 unlink($infile) if ($infile);
2375 &http_error(500, "Bad Header", $errs);
2377 $cgiheader{lc($1)} = $2;
2378 push(@cgiheader, [ $1, $2 ]);
2380 if ($cgiheader{"location"}) {
2381 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2382 &write_data("Date: $datestr\r\n");
2383 &write_data("Server: $config{'server'}\r\n");
2384 &write_keep_alive(0);
2385 # ignore the rest of the output. This is a hack,
2386 # but is necessary for IE in some cases :(
2387 close(CGIOUTr); close(CGIERRr);
2389 elsif ($cgiheader{"content-type"} eq "") {
2390 close(CGIOUTr); close(CGIERRr);
2391 unlink($infile) if ($infile);
2392 $errs = &read_errors(CGIERRr);
2393 &http_error(500, "Missing Content-Type Header",
2394 $config{'noshowstderr'} ? undef : $errs);
2397 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2398 &write_data("Date: $datestr\r\n");
2399 &write_data("Server: $config{'server'}\r\n");
2400 &write_keep_alive(0);
2402 foreach $h (@cgiheader) {
2403 &write_data("$h->[0]: $h->[1]\r\n");
2405 &write_data("\r\n");
2407 &reset_byte_count();
2408 while($line = <CGIOUTr>) {
2413 unlink($infile) if ($infile);
2419 print DEBUG "handle_request: outputting file\n";
2420 open(FILE, $full) || &http_error(404, "Failed to open file");
2422 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2423 "Date: $datestr\r\n".
2424 "Server: $config{server}\r\n".
2425 "Content-type: ".&get_type($full)."\r\n".
2426 "Content-length: $stfull[7]\r\n".
2427 "Last-Modified: ".&http_date($stfull[9])."\r\n".
2428 "Expires: ".&http_date(time()+$config{'expires'})."\r\n";
2430 $rv = &write_keep_alive();
2431 &write_data("\r\n");
2432 &reset_byte_count();
2433 while(read(FILE, $buf, 1024) > 0) {
2440 &log_request($acpthost, $authuser, $reqline,
2441 $logged_code ? $logged_code :
2442 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2446 # http_error(code, message, body, [dontexit])
2449 local $eh = $error_handler_recurse ? undef :
2450 $config{"error_handler_$_[0]"} ? $config{"error_handler_$_[0]"} :
2451 $config{'error_handler'} ? $config{'error_handler'} : undef;
2452 print DEBUG "http_error code=$_[0] message=$_[1] body=$_[2]\n";
2454 # Call a CGI program for the error
2456 $querystring = "code=$_[0]&message=".&urlize($_[1]).
2457 "&body=".&urlize($_[2]);
2458 $error_handler_recurse++;
2460 $ok_message = $_[1];
2464 # Use the standard error message display
2465 &write_data("HTTP/1.0 $_[0] $_[1]\r\n");
2466 &write_data("Server: $config{server}\r\n");
2467 &write_data("Date: $datestr\r\n");
2468 &write_data("Content-type: text/html\r\n");
2469 &write_keep_alive(0);
2470 &write_data("\r\n");
2471 &reset_byte_count();
2472 &write_data("<h1>Error - $_[1]</h1>\n");
2474 &write_data("<pre>$_[2]</pre>\n");
2477 &log_request($acpthost, $authuser, $reqline, $_[0], &byte_count())
2479 &log_error($_[1], $_[2] ? " : $_[2]" : "");
2486 if ($_[0] =~ /\.([A-z0-9]+)$/) {
2492 return "text/plain";
2495 # simplify_path(path, bogus)
2496 # Given a path, maybe containing stuff like ".." and "." convert it to a
2497 # clean, absolute form.
2500 local($dir, @bits, @fixedbits, $b);
2502 $dir =~ s/\\/\//g; # fix windows \ in path
2505 $dir =~ s/\0//g; # remove null bytes
2506 @bits = split(/\/+/, $dir);
2509 foreach $b (@bits) {
2513 elsif ($b eq ".." || $b eq "...") {
2515 if (scalar(@fixedbits) == 0) {
2523 push(@fixedbits, $b);
2526 return "/" . join('/', @fixedbits);
2530 # Converts a string from base64 format to normal
2533 local($str) = $_[0];
2535 $str =~ tr|A-Za-z0-9+=/||cd;
2537 $str =~ tr|A-Za-z0-9+/| -_|;
2538 while ($str =~ /(.{1,60})/gs) {
2539 my $len = chr(32 + length($1)*3/4);
2540 $res .= unpack("u", $len . $1 );
2545 # ip_match(remoteip, localip, [match]+)
2546 # Checks an IP address against a list of IPs, networks and networks/masks
2549 local(@io, @mo, @ms, $i, $j, $hn, $needhn);
2550 @io = split(/\./, $_[0]);
2551 for($i=2; $i<@_; $i++) {
2552 $needhn++ if ($_[$i] =~ /^\*(\S+)$/);
2554 if ($needhn && !defined($hn = $ip_match_cache{$_[0]})) {
2555 $hn = gethostbyaddr(inet_aton($_[0]), AF_INET);
2556 $hn = "" if (&to_ipaddress($hn) ne $_[0]);
2557 $ip_match_cache{$_[0]} = $hn;
2559 for($i=2; $i<@_; $i++) {
2560 local $mismatch = 0;
2561 if ($_[$i] =~ /^(\S+)\/(\d+)$/) {
2562 # Convert CIDR to netmask format
2563 $_[$i] = $1."/".&prefix_to_mask($2);
2565 if ($_[$i] =~ /^(\S+)\/(\S+)$/) {
2566 # Compare with network/mask
2567 @mo = split(/\./, $1); @ms = split(/\./, $2);
2568 for($j=0; $j<4; $j++) {
2569 if ((int($io[$j]) & int($ms[$j])) != int($mo[$j])) {
2574 elsif ($_[$i] =~ /^\*(\S+)$/) {
2575 # Compare with hostname regexp
2576 $mismatch = 1 if ($hn !~ /$1$/);
2578 elsif ($_[$i] eq 'LOCAL') {
2579 # Compare with local network
2580 local @lo = split(/\./, $_[1]);
2582 $mismatch = 1 if ($lo[0] != $io[0]);
2584 elsif ($lo[0] < 192) {
2585 $mismatch = 1 if ($lo[0] != $io[0] ||
2589 $mismatch = 1 if ($lo[0] != $io[0] ||
2594 elsif ($_[$i] !~ /^[0-9\.]+$/) {
2595 # Compare with hostname
2596 $mismatch = 1 if ($_[0] ne &to_ipaddress($_[$i]));
2599 # Compare with IP or network
2600 @mo = split(/\./, $_[$i]);
2601 while(@mo && !$mo[$#mo]) { pop(@mo); }
2602 for($j=0; $j<@mo; $j++) {
2603 if ($mo[$j] != $io[$j]) {
2608 return 1 if (!$mismatch);
2613 # users_match(&uinfo, user, ...)
2614 # Returns 1 if a user is in a list of users and groups
2617 local $uinfo = shift(@_);
2619 local @ginfo = getgrgid($uinfo->[3]);
2621 if ($u =~ /^\@(\S+)$/) {
2622 return 1 if (&is_group_member($uinfo, $1));
2624 elsif ($u =~ /^(\d*)-(\d*)$/ && ($1 || $2)) {
2625 return (!$1 || $uinfo[2] >= $1) &&
2626 (!$2 || $uinfo[2] <= $2);
2629 return 1 if ($u eq $uinfo->[0]);
2635 # restart_miniserv()
2636 # Called when a SIGHUP is received to restart the web server. This is done
2637 # by exec()ing perl with the same command line as was originally used
2638 sub restart_miniserv
2640 print STDERR "restarting miniserv\n";
2641 &log_error("Restarting");
2643 &close_all_sockets();
2645 dbmclose(%sessiondb);
2646 kill('KILL', $logclearer) if ($logclearer);
2647 kill('KILL', $extauth) if ($extauth);
2648 exec($perl_path, $miniserv_path, @miniserv_argv);
2649 die "Failed to restart miniserv with $perl_path $miniserv_path";
2666 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2667 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/) { push(@rv, $i); }
2668 else { push(@rv, join('.', unpack("CCCC", inet_aton($i)))); }
2670 return wantarray ? @rv : $rv[0];
2673 # read_line(no-wait, no-limit)
2674 # Reads one line from SOCK or SSL
2677 local ($nowait, $nolimit) = @_;
2678 local($idx, $more, $rv);
2679 while(($idx = index($main::read_buffer, "\n")) < 0) {
2680 if (length($main::read_buffer) > 10000 && !$nolimit) {
2681 &http_error(414, "Request too long",
2682 "Received excessive line <pre>$main::read_buffer</pre>");
2685 # need to read more..
2686 &wait_for_data_error() if (!$nowait);
2688 $more = Net::SSLeay::read($ssl_con);
2691 local $ok = sysread(SOCK, $more, 1024);
2692 $more = undef if ($ok <= 0);
2696 $rv = $main::read_buffer;
2697 undef($main::read_buffer);
2700 $main::read_buffer .= $more;
2702 $rv = substr($main::read_buffer, 0, $idx+1);
2703 $main::read_buffer = substr($main::read_buffer, $idx+1);
2708 # Reads up to some amount of data from SOCK or the SSL connection
2712 if (length($main::read_buffer)) {
2713 if (length($main::read_buffer) > $_[0]) {
2714 # Return the first part of the buffer
2715 $rv = substr($main::read_buffer, 0, $_[0]);
2716 $main::read_buffer = substr($main::read_buffer, $_[0]);
2720 # Return the whole buffer
2721 $rv = $main::read_buffer;
2722 undef($main::read_buffer);
2727 # Call SSL read function
2728 return Net::SSLeay::read($ssl_con, $_[0]);
2731 # Just do a normal read
2733 sysread(SOCK, $buf, $_[0]) || return undef;
2739 # Read a line from a file handle, using sysread to get a byte at a time
2746 $got = sysread($fh, $buf, 1);
2747 last if ($got <= 0);
2749 last if ($buf eq "\n");
2754 # wait_for_data(secs)
2755 # Waits at most the given amount of time for some data on SOCK, returning
2756 # 0 if not found, 1 if some arrived.
2760 vec($rmask, fileno(SOCK), 1) = 1;
2761 local $got = select($rmask, undef, undef, $_[0]);
2762 return $got == 0 ? 0 : 1;
2765 # wait_for_data_error()
2766 # Waits 60 seconds for data on SOCK, and fails if none arrives
2767 sub wait_for_data_error
2769 local $got = &wait_for_data(60);
2771 &http_error(400, "Timeout",
2772 "Waited more than 60 seconds for request data");
2776 # write_data(data, ...)
2777 # Writes a string to SOCK or the SSL connection
2780 local $str = join("", @_);
2782 Net::SSLeay::write($ssl_con, $str);
2785 syswrite(SOCK, $str, length($str));
2787 # Intentionally introduce a small delay to avoid problems where IE reports
2788 # the page as empty / DNS failed when it get a large response too quickly!
2789 select(undef, undef, undef, .01) if ($write_data_count%10 == 0);
2790 $write_data_count += length($str);
2793 # reset_byte_count()
2794 sub reset_byte_count { $write_data_count = 0; }
2797 sub byte_count { return $write_data_count; }
2799 # log_request(hostname, user, request, code, bytes)
2802 if ($config{'log'}) {
2803 local ($user, $ident, $headers);
2804 if ($config{'logident'}) {
2805 # add support for rfc1413 identity checking here
2807 else { $ident = "-"; }
2808 $user = $_[1] ? $_[1] : "-";
2809 local $dstr = &make_datestr();
2810 if (fileno(MINISERVLOG)) {
2811 seek(MINISERVLOG, 0, 2);
2814 open(MINISERVLOG, ">>$config{'logfile'}");
2815 chmod(0600, $config{'logfile'});
2817 if (defined($config{'logheaders'})) {
2818 foreach $h (split(/\s+/, $config{'logheaders'})) {
2819 $headers .= " $h=\"$header{$h}\"";
2822 elsif ($config{'logclf'}) {
2823 $headers = " \"$header{'referer'}\" \"$header{'user-agent'}\"";
2828 print MINISERVLOG "$_[0] $ident $user [$dstr] \"$_[2]\" ",
2829 "$_[3] $_[4]$headers\n";
2837 local @tm = localtime(time());
2838 return sprintf "%2.2d/%s/%4.4d:%2.2d:%2.2d:%2.2d %s",
2839 $tm[3], $month[$tm[4]], $tm[5]+1900,
2840 $tm[2], $tm[1], $tm[0], $timezone;
2843 # log_error(message)
2847 print STDERR "[",&make_datestr(),"] ",
2848 $acpthost ? ( "[",$acpthost,"] " ) : ( ),
2849 $page ? ( $page," : " ) : ( ),
2853 # read_errors(handle)
2854 # Read and return all input from some filehandle
2857 local($fh, $_, $rv);
2859 while(<$fh>) { $rv .= $_; }
2863 sub write_keep_alive
2866 if ($config{'nokeepalive'}) {
2867 # Keep alives have been disabled in config
2870 elsif (@childpids > $config{'maxconns'}*.8) {
2871 # Disable because nearing process limit
2875 # Keep alive specified by caller
2879 # Keep alive determined by browser
2880 $mode = $header{'connection'} =~ /keep-alive/i;
2882 &write_data("Connection: ".($mode ? "Keep-Alive" : "close")."\r\n");
2888 kill('TERM', @childpids) if (@childpids);
2889 kill('KILL', $logclearer) if ($logclearer);
2890 kill('KILL', $extauth) if ($extauth);
2896 local @tm = gmtime($_[0]);
2897 return sprintf "%s, %d %s %d %2.2d:%2.2d:%2.2d GMT",
2898 $weekday[$tm[6]], $tm[3], $month[$tm[4]], $tm[5]+1900,
2899 $tm[2], $tm[1], $tm[0];
2904 my $i; bless \$i, shift;
2910 my($buf,$len,$offset) = @_;
2911 &write_to_sock(substr($buf, $offset, $len));
2918 my $buf = join(defined($,) ? $, : "", @_);
2919 $buf .= $\ if defined($\);
2920 &write_to_sock($buf);
2927 &write_to_sock(sprintf $fmt, @_);
2930 # Send back already read data while we have it, then read from SOCK
2934 my $bufref = \$_[0];
2937 if ($postpos < length($postinput)) {
2938 # Reading from already fetched array
2939 my $left = length($postinput) - $postpos;
2940 my $canread = $len > $left ? $left : $len;
2941 substr($$bufref, $offset, $canread) =
2942 substr($postinput, $postpos, $canread);
2943 $postpos += $canread;
2947 # Read from network socket
2948 local $data = &read_data($len);
2949 if ($data eq '' && $len) {
2951 print STDERR "finished reading - shutting down socket\n";
2954 substr($$bufref, $offset, length($data)) = $data;
2955 return length($data);
2961 #print STDERR "open() called - should never happen!\n";
2964 # Read a line of input
2968 if ($postpos < length($postinput) &&
2969 ($idx = index($postinput, "\n", $postpos)) >= 0) {
2970 # A line exists in the memory buffer .. use it
2971 my $line = substr($postinput, $postpos, $idx-$postpos+1);
2976 # Need to read from the socket
2978 if ($postpos < length($postinput)) {
2979 # Start with in-memory data
2980 $line = substr($postinput, $postpos);
2981 $postpos = length($postinput);
2983 my $nl = &read_line(0, 1);
2986 print STDERR "finished reading - shutting down socket\n";
2989 $line .= $nl if (defined($nl));
2994 # Read one character of input
2999 my $got = READ($r, \$buf, 1, 0);
3000 return $got > 0 ? $buf : undef;
3005 return fileno(SOCK);
3012 # write_to_sock(data, ...)
3017 if ($doneheaders || $miniserv::nph_script) {
3022 while(!$doneheaders && $headers =~ s/^([^\r\n]*)(\r)?\n//) {
3023 if ($1 =~ /^(\S+):\s+(.*)$/) {
3024 $cgiheader{lc($1)} = $2;
3025 push(@cgiheader, [ $1, $2 ]);
3027 elsif ($1 !~ /\S/) {
3031 &http_error(500, "Bad Header");
3035 if ($cgiheader{"location"}) {
3037 "HTTP/1.0 302 Moved Temporarily\r\n");
3038 &write_data("Date: $datestr\r\n");
3039 &write_data("Server: $config{server}\r\n");
3040 &write_keep_alive(0);
3042 elsif ($cgiheader{"content-type"} eq "") {
3043 &http_error(500, "Missing Content-Type Header");
3046 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
3047 &write_data("Date: $datestr\r\n");
3048 &write_data("Server: $config{server}\r\n");
3049 &write_keep_alive(0);
3051 foreach $h (@cgiheader) {
3052 &write_data("$h->[0]: $h->[1]\r\n");
3054 &write_data("\r\n");
3055 &reset_byte_count();
3056 &write_data($headers);
3064 local $cert = Net::SSLeay::X509_STORE_CTX_get_current_cert($_[1]);
3066 local $errnum = Net::SSLeay::X509_STORE_CTX_get_error($_[1]);
3067 $verified_client = 1 if (!$errnum);
3074 if ($doing_cgi_eval && $$ == $main_process_id) {
3075 # A CGI program called exit! This is a horrible hack to
3076 # finish up before really exiting
3079 close($PASSINw); close($PASSOUTw);
3080 &log_request($acpthost, $authuser, $reqline,
3081 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
3086 # Convert a string to a form ok for putting in a URL
3088 local($tmp, $tmp2, $c);
3091 while(($c = chop($tmp)) ne "") {
3092 if ($c !~ /[A-z0-9]/) {
3093 $c = sprintf("%%%2.2X", ord($c));
3100 # validate_user(username, password, host)
3101 # Checks if some username and password are valid. Returns the modified username,
3102 # the expired / temp pass flag, and the non-existence flag
3105 local ($user, $pass, $host) = @_;
3106 return ( ) if (!$user);
3107 print DEBUG "validate_user: user=$user pass=$pass host=$host\n";
3108 local ($canuser, $canmode, $notexist, $webminuser, $sudo) =
3109 &can_user_login($user, undef, $host);
3110 print DEBUG "validate_user: canuser=$canuser canmode=$canmode notexist=$notexist webminuser=$webminuser sudo=$sudo\n";
3112 # User doesn't even exist, so go no further
3113 return ( undef, 0, 1 );
3115 elsif ($canmode == 0) {
3116 # User does exist but cannot login
3117 return ( $canuser, 0, 0 );
3119 elsif ($canmode == 1) {
3120 # Attempt Webmin authentication
3121 my $uinfo = &get_user_details($webminuser);
3123 &password_crypt($pass, $uinfo->{'pass'}) eq $uinfo->{'pass'}) {
3124 # Password is valid .. but check for expiry
3125 local $lc = $uinfo->{'lastchanges'};
3126 print DEBUG "validate_user: Password is valid lc=$lc pass_maxdays=$config{'pass_maxdays'}\n";
3127 if ($config{'pass_maxdays'} && $lc && !$uinfo->{'nochange'}) {
3128 local $daysold = (time() - $lc)/(24*60*60);
3129 print DEBUG "maxdays=$config{'pass_maxdays'} daysold=$daysold temppass=$uinfo->{'temppass'}\n";
3130 if ($config{'pass_lockdays'} &&
3131 $daysold > $config{'pass_lockdays'}) {
3132 # So old that the account is locked
3133 return ( undef, 0, 0 );
3135 elsif ($daysold > $config{'pass_maxdays'}) {
3136 # Password has expired
3137 return ( $user, 1, 0 );
3140 if ($uinfo->{'temppass'}) {
3141 # Temporary password - force change now
3142 return ( $user, 2, 0 );
3144 return ( $user, 0, 0 );
3147 print DEBUG "validate_user: User $webminuser not found\n";
3148 return ( undef, 0, 0 );
3151 print DEBUG "validate_user: User $webminuser password mismatch $pass != $uinfo->{'pass'}\n";
3152 return ( undef, 0, 0 );
3155 elsif ($canmode == 2 || $canmode == 3) {
3156 # Attempt PAM or passwd file authentication
3157 local $val = &validate_unix_user($canuser, $pass);
3158 print DEBUG "validate_user: unix val=$val\n";
3159 if ($val && $sudo) {
3160 # Need to check if this Unix user can sudo
3161 if (!&check_sudo_permissions($canuser, $pass)) {
3162 print DEBUG "validate_user: sudo failed\n";
3166 print DEBUG "validate_user: sudo passed\n";
3169 return $val == 2 ? ( $canuser, 1, 0 ) :
3170 $val == 1 ? ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3172 elsif ($canmode == 4) {
3173 # Attempt external authentication
3174 return &validate_external_user($canuser, $pass) ?
3175 ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3183 # validate_unix_user(user, password)
3184 # Returns 1 if a username and password are valid under unix, 0 if not,
3185 # or 2 if the account has expired.
3186 # Checks PAM if available, and falls back to reading the system password
3188 sub validate_unix_user
3192 $pam_username = $_[0];
3193 $pam_password = $_[1];
3194 eval "use Authen::PAM;";
3195 local $pamh = new Authen::PAM($config{'pam'}, $pam_username,
3198 local $pam_ret = $pamh->pam_authenticate();
3199 if ($pam_ret == PAM_SUCCESS()) {
3200 # Logged in OK .. make sure password hasn't expired
3201 local $acct_ret = $pamh->pam_acct_mgmt();
3202 if ($acct_ret == PAM_SUCCESS()) {
3203 $pamh->pam_open_session();
3206 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3207 $acct_ret == PAM_ACCT_EXPIRED()) {
3211 print STDERR "Unknown pam_acct_mgmt return value : $acct_ret\n";
3218 elsif ($config{'pam_only'}) {
3219 # Pam is not available, but configuration forces it's use!
3222 elsif ($config{'passwd_file'}) {
3223 # Check in a password file
3225 open(FILE, $config{'passwd_file'});
3226 if ($config{'passwd_file'} eq '/etc/security/passwd') {
3227 # Assume in AIX format
3230 if (/^\s*(\S+):/ && $1 eq $_[0]) {
3232 if (/^\s*password\s*=\s*(\S+)\s*$/) {
3233 $rv = $1 eq &password_crypt($_[1], $1) ?
3241 # Read the system password or shadow file
3243 local @l = split(/:/, $_, -1);
3244 local $u = $l[$config{'passwd_uindex'}];
3245 local $p = $l[$config{'passwd_pindex'}];
3247 $rv = $p eq &password_crypt($_[1], $p) ? 1 : 0;
3248 if ($config{'passwd_cindex'} ne '' && $rv) {
3249 # Password may have expired!
3250 local $c = $l[$config{'passwd_cindex'}];
3251 local $m = $l[$config{'passwd_mindex'}];
3252 local $day = time()/(24*60*60);
3253 if ($c =~ /^\d+/ && $m =~ /^\d+/ &&
3259 if ($p eq "" && $config{'passwd_blank'}) {
3260 # Force password change
3268 return $rv if ($rv);
3271 # Fallback option - check password returned by getpw*
3272 local @uinfo = getpwnam($_[0]);
3273 if ($uinfo[1] ne '' && &password_crypt($_[1], $uinfo[1]) eq $uinfo[1]) {
3277 return 0; # Totally failed
3280 # validate_external_user(user, pass)
3281 # Validate a user by passing the username and password to an external
3282 # squid-style authentication program
3283 sub validate_external_user
3285 return 0 if (!$config{'extauth'});
3287 local $str = "$_[0] $_[1]\n";
3288 syswrite(EXTAUTH, $str, length($str));
3289 local $resp = <EXTAUTH>;
3291 return $resp =~ /^OK/i ? 1 : 0;
3294 # can_user_login(username, no-append, host)
3295 # Checks if a user can login or not.
3296 # First return value is the username.
3297 # Second is 0 if cannot login, 1 if using Webmin pass, 2 if PAM, 3 if password
3298 # file, 4 if external.
3299 # Third is 1 if the user does not exist at all, 0 if he does.
3300 # Fourth is the Webmin username whose permissions apply, based on unixauth.
3301 # Fifth is a flag indicating if a sudo check is needed.
3304 local $uinfo = &get_user_details($_[0]);
3306 # See if this user exists in Unix and can be validated by the same
3307 # method as the unixauth webmin user
3308 local $realuser = $unixauth{$_[0]};
3312 eval { @uinfo = getpwnam($_[0]); }; # may fail on windows
3313 if (!$realuser && @uinfo) {
3314 # No unixauth entry for the username .. try his groups
3315 foreach my $ua (keys %unixauth) {
3316 if ($ua =~ /^\@(.*)$/) {
3317 if (&is_group_member(\@uinfo, $1)) {
3318 $realuser = $unixauth{$ua};
3324 if (!$realuser && @uinfo) {
3325 # Fall back to unix auth for all Unix users
3326 $realuser = $unixauth{"*"};
3328 if (!$realuser && $use_sudo && @uinfo) {
3329 # Allow login effectively as root, if sudo permits it
3333 if (!$realuser && !@uinfo && $config{'pamany'}) {
3334 # If the user completely doesn't exist, we can still allow
3335 # him to authenticate via PAM
3336 $realuser = $config{'pamany'};
3340 # For Usermin, always fall back to unix auth for any user,
3341 # so that later checks with domain added / removed are done.
3342 $realuser = $unixauth{"*"};
3344 return (undef, 0, 1, undef) if (!$realuser);
3345 local $uinfo = &get_user_details($realuser);
3346 return (undef, 0, 1, undef) if (!$uinfo);
3347 local $up = $uinfo->{'pass'};
3349 # Work out possible domain names from the hostname
3350 local @doms = ( $_[2] );
3351 if ($_[2] =~ /^([^\.]+)\.(\S+)$/) {
3355 if ($config{'user_mapping'} && !%user_mapping) {
3356 # Read the user mapping file
3358 open(MAPPING, $config{'user_mapping'});
3362 if (/^(\S+)\s+(\S+)/) {
3363 if ($config{'user_mapping_reverse'}) {
3364 $user_mapping{$1} = $2;
3367 $user_mapping{$2} = $1;
3374 # Check the user mapping file to see if there is an entry for the
3375 # user login in which specifies a new effective user
3377 foreach my $d (@doms) {
3378 $um ||= $user_mapping{"$_[0]\@$d"};
3380 $um ||= $user_mapping{$_[0]};
3381 if (defined($um) && ($_[1]&4) == 0) {
3382 # A mapping exists - use it!
3383 return &can_user_login($um, $_[1]+4, $_[2]);
3386 # Check if a user with the entered login and the domains appended
3387 # or prepended exists, and if so take it to be the effective user
3388 if (!@uinfo && $config{'domainuser'}) {
3389 # Try again with name.domain and name.firstpart
3390 local @firsts = map { /^([^\.]+)/; $1 } @doms;
3391 if (($_[1]&1) == 0) {
3393 foreach $a (@firsts, @doms) {
3394 foreach $p ("$_[0].${a}", "$_[0]-${a}",
3395 "${a}.$_[0]", "${a}-$_[0]",
3396 "$_[0]_${a}", "${a}_$_[0]") {
3397 local @vu = &can_user_login(
3398 $p, $_[1]+1, $_[2]);
3399 return @vu if ($vu[1]);
3405 # Check if the user entered a domain at the end of his username when
3406 # he really shouldn't have, and if so try without it
3407 if (!@uinfo && $config{'domainstrip'} &&
3408 $_[0] =~ /^(\S+)\@(\S+)$/ && ($_[1]&2) == 0) {
3409 local ($stripped, $dom) = ($1, $2);
3410 local @vu = &can_user_login($stripped, $_[1] + 2, $_[2]);
3411 return @vu if ($vu[1]);
3412 local @vu = &can_user_login($stripped, $_[1] + 2, $dom);
3413 return @vu if ($vu[1]);
3416 return ( undef, 0, 1, undef ) if (!@uinfo && !$pamany);
3419 if (defined(@allowusers)) {
3420 # Only allow people on the allow list
3421 return ( undef, 0, 0, undef )
3422 if (!&users_match(\@uinfo, @allowusers));
3424 elsif (defined(@denyusers)) {
3425 # Disallow people on the deny list
3426 return ( undef, 0, 0, undef )
3427 if (&users_match(\@uinfo, @denyusers));
3429 if ($config{'shells_deny'}) {
3431 open(SHELLS, $config{'shells_deny'});
3435 $found++ if ($_ eq $uinfo[8]);
3438 return ( undef, 0, 0, undef ) if (!$found);
3443 # PAM or passwd file authentication
3444 print DEBUG "can_user_login: Validate with PAM\n";
3445 return ( $_[0], $use_pam ? 2 : 3, 0, $realuser, $sudo );
3447 elsif ($up eq 'e') {
3448 # External authentication
3449 print DEBUG "can_user_login: Validate externally\n";
3450 return ( $_[0], 4, 0, $realuser, $sudo );
3453 # Fixed Webmin password
3454 print DEBUG "can_user_login: Validate by Webmin\n";
3455 return ( $_[0], 1, 0, $realuser, $sudo );
3458 elsif ($uinfo->{'pass'} eq 'x') {
3459 # Webmin user authenticated via PAM or password file
3460 return ( $_[0], $use_pam ? 2 : 3, 0, $_[0] );
3462 elsif ($uinfo->{'pass'} eq 'e') {
3463 # Webmin user authenticated externally
3464 return ( $_[0], 4, 0, $_[0] );
3467 # Normal Webmin user
3468 return ( $_[0], 1, 0, $_[0] );
3472 # the PAM conversation function for interactive logins
3475 $pam_conv_func_called++;
3482 $ans = $pam_username if ($code == PAM_PROMPT_ECHO_ON() );
3483 $ans = $pam_password if ($code == PAM_PROMPT_ECHO_OFF() );
3485 push @res, PAM_SUCCESS();
3488 push @res, PAM_SUCCESS();
3497 # get_socket_ip(handle, ipv6-flag)
3498 # Returns the local IP address of some connection, as both a string and in
3502 local ($fh, $ipv6) = @_;
3503 local $sn = getsockname($fh);
3504 return undef if (!$sn);
3505 return &get_address_ip($sn, $ipv6);
3508 # get_address_ip(address, ipv6-flag)
3509 # Given a sockaddr object in binary format, return the binary address, text
3510 # address and port number
3513 local ($sn, $ipv6) = @_;
3515 local ($p, $b) = unpack_sockaddr_in6($sn);
3516 return ($b, inet_ntop(Socket6::AF_INET6(), $b), $p);
3519 local ($p, $b) = unpack_sockaddr_in($sn);
3520 return ($b, inet_ntoa($myaddr), $p);
3524 # get_socket_name(handle, ipv6-flag)
3525 # Returns the local hostname or IP address of some connection
3528 local ($fh, $ipv6) = @_;
3529 return $config{'host'} if ($config{'host'});
3530 local ($mybin, $myaddr) = &get_socket_ip($fh, $ipv6);
3531 if (!$get_socket_name_cache{$myaddr}) {
3533 if (!$config{'no_resolv_myname'}) {
3534 $myname = gethostbyaddr($mybin,
3535 $ipv6 ? Socket6::AF_INET6() : AF_INET);
3537 $myname ||= $myaddr;
3538 $get_socket_name_cache{$myaddr} = $myname;
3540 return $get_socket_name_cache{$myaddr};
3543 # run_login_script(username, sid, remoteip, localip)
3544 sub run_login_script
3546 if ($config{'login_script'}) {
3547 system($config{'login_script'}.
3548 " ".join(" ", map { quotemeta($_) || '""' } @_).
3549 " >/dev/null 2>&1 </dev/null");
3553 # run_logout_script(username, sid, remoteip, localip)
3554 sub run_logout_script
3556 if ($config{'logout_script'}) {
3557 system($config{'logout_script'}.
3558 " ".join(" ", map { quotemeta($_) || '""' } @_).
3559 " >/dev/null 2>&1 </dev/null");
3563 # close_all_sockets()
3564 # Closes all the main listening sockets
3565 sub close_all_sockets
3568 foreach $s (@socketfhs) {
3574 # Close all pipes for talking to sub-processes
3578 foreach $p (@passin) { close($p); }
3579 foreach $p (@passout) { close($p); }
3580 foreach $p (values %conversations) {
3581 if ($p->{'PAMOUTr'}) {
3582 close($p->{'PAMOUTr'});
3583 close($p->{'PAMINw'});
3588 # check_user_ip(user)
3589 # Returns 1 if some user is allowed to login from the accepting IP, 0 if not
3592 local ($username) = @_;
3593 local $uinfo = &get_user_details($username);
3594 return 1 if (!$uinfo);
3595 if ($uinfo->{'deny'} &&
3596 &ip_match($acptip, $localip, @{$uinfo->{'deny'}}) ||
3597 $uinfo->{'allow'} &&
3598 !&ip_match($acptip, $localip, @{$uinfo->{'allow'}})) {
3604 # check_user_time(user)
3605 # Returns 1 if some user is allowed to login at the current date and time
3608 local ($username) = @_;
3609 local $uinfo = &get_user_details($username);
3610 return 1 if (!$uinfo || !$uinfo->{'allowdays'} && !$uinfo->{'allowhours'});
3611 local @tm = localtime(time());
3612 if ($uinfo->{'allowdays'}) {
3613 # Make sure day is allowed
3614 return 0 if (&indexof($tm[6], @{$uinfo->{'allowdays'}}) < 0);
3616 if ($uinfo->{'allowhours'}) {
3617 # Make sure time is allowed
3618 local $m = $tm[2]*60+$tm[1];
3619 return 0 if ($m < $uinfo->{'allowhours'}->[0] ||
3620 $m > $uinfo->{'allowhours'}->[1]);
3625 # generate_random_id(password, [force-urandom])
3626 # Returns a random session ID number
3627 sub generate_random_id
3629 local ($pass, $force_urandom) = @_;
3631 if (!$bad_urandom) {
3632 # First try /dev/urandom, unless we have marked it as bad
3633 $SIG{ALRM} = "miniserv::urandom_timeout";
3635 if (open(RANDOM, "/dev/urandom")) {
3637 if (read(RANDOM, $tmpsid, 16) == 16) {
3638 $sid = lc(unpack('h*',$tmpsid));
3644 if (!$sid && !$force_urandom) {
3647 foreach $c (split(//, &unix_crypt($pass, substr($$, -2)))) {
3648 $sid += ord($c) * $mul;
3655 # handle_login(username, ok, expired, not-exists, password, [no-test-cookie])
3656 # Called from handle_session to either mark a user as logged in, or not
3659 local ($vu, $ok, $expired, $nonexist, $pass, $notest) = @_;
3660 $authuser = $vu if ($ok);
3662 # check if the test cookie is set
3663 if ($header{'cookie'} !~ /testing=1/ && $vu &&
3664 !$config{'no_testing_cookie'} && !$notest) {
3665 &http_error(500, "No cookies",
3666 "Your browser does not support cookies, ".
3667 "which are required for this web server to ".
3668 "work in session authentication mode");
3671 # check with main process for delay
3672 if ($config{'passdelay'} && $vu) {
3673 print DEBUG "handle_login: requesting delay vu=$vu acptip=$acptip ok=$ok\n";
3674 print $PASSINw "delay $vu $acptip $ok\n";
3675 <$PASSOUTr> =~ /(\d+) (\d+)/;
3678 print DEBUG "handle_login: delay=$1 blocked=$2\n";
3681 if ($ok && (!$expired ||
3682 $config{'passwd_mode'} == 1)) {
3683 # Logged in OK! Tell the main process about
3685 local $sid = &generate_random_id($pass);
3686 print DEBUG "handle_login: sid=$sid\n";
3687 print $PASSINw "new $sid $authuser $acptip\n";
3689 # Run the post-login script, if any
3690 &run_login_script($authuser, $sid,
3693 # Check for a redirect URL for the user
3694 local $rurl = &login_redirect($authuser, $pass, $host);
3695 print DEBUG "handle_login: redirect URL rurl=$rurl\n";
3697 # Got one .. go to it
3698 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3699 &write_data("Date: $datestr\r\n");
3700 &write_data("Server: $config{'server'}\r\n");
3701 &write_data("Location: $rurl\r\n");
3702 &write_keep_alive(0);
3703 &write_data("\r\n");
3704 &log_request($acpthost, $authuser, $reqline, 302, 0);
3707 # Set cookie and redirect to originally requested page
3708 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3709 &write_data("Date: $datestr\r\n");
3710 &write_data("Server: $config{'server'}\r\n");
3711 local $ssl = $use_ssl || $config{'inetd_ssl'};
3712 $portstr = $port == 80 && !$ssl ? "" :
3713 $port == 443 && $ssl ? "" : ":$port";
3714 $prot = $ssl ? "https" : "http";
3715 local $sec = $ssl ? "; secure" : "";
3716 #$sec .= "; httpOnly";
3717 if ($in{'page'} !~ /^\/[A-Za-z0-9\/\.\-\_]+$/) {
3718 # Make redirect URL safe
3722 &write_data("Set-Cookie: $sidname=$sid; path=/; expires=\"Thu, 31-Dec-2037 00:00:00\"$sec\r\n");
3725 &write_data("Set-Cookie: $sidname=$sid; path=/$sec\r\n");
3727 &write_data("Location: $prot://$host$portstr$in{'page'}\r\n");
3728 &write_keep_alive(0);
3729 &write_data("\r\n");
3730 &log_request($acpthost, $authuser, $reqline, 302, 0);
3731 syslog("info", "%s", "Successful login as $authuser from $acpthost") if ($use_syslog);
3732 &write_login_utmp($authuser, $acpthost);
3736 elsif ($ok && $expired &&
3737 ($config{'passwd_mode'} == 2 || $expired == 2)) {
3738 # Login was ok, but password has expired or was temporary. Need
3739 # to force display of password change form.
3742 $querystring = "&user=".&urlize($vu).
3744 "&expired=".$expired;
3747 $page = $config{'password_form'};
3749 $miniserv_internal = 2;
3750 syslog("crit", "%s",
3751 "Expired login as $vu ".
3752 "from $acpthost") if ($use_syslog);
3755 # Login failed, or password has expired. The login form will be
3756 # displayed again by later code
3758 $request_uri = $in{'page'};
3759 $already_session_id = undef;
3761 $authuser = $baseauthuser = undef;
3762 syslog("crit", "%s",
3763 ($nonexist ? "Non-existent" :
3764 $expired ? "Expired" : "Invalid").
3765 " login as $vu from $acpthost")
3771 # write_login_utmp(user, host)
3772 # Record the login by some user in utmp
3773 sub write_login_utmp
3776 # Write utmp record for login
3777 %utmp = ( 'ut_host' => $_[1],
3778 'ut_time' => time(),
3780 'ut_type' => 7, # user process
3781 'ut_pid' => $main_process_id,
3782 'ut_line' => $config{'pam'},
3784 if (defined(&User::Utmp::putut)) {
3785 User::Utmp::putut(\%utmp);
3788 User::Utmp::pututline(\%utmp);
3793 # write_logout_utmp(user, host)
3794 # Record the logout by some user in utmp
3795 sub write_logout_utmp
3798 # Write utmp record for logout
3799 %utmp = ( 'ut_host' => $_[1],
3800 'ut_time' => time(),
3802 'ut_type' => 8, # dead process
3803 'ut_pid' => $main_process_id,
3804 'ut_line' => $config{'pam'},
3806 if (defined(&User::Utmp::putut)) {
3807 User::Utmp::putut(\%utmp);
3810 User::Utmp::pututline(\%utmp);
3815 # pam_conversation_process(username, write-pipe, read-pipe)
3816 # This function is called inside a sub-process to communicate with PAM. It sends
3817 # questions down one pipe, and reads responses from another
3818 sub pam_conversation_process
3820 local ($user, $writer, $reader) = @_;
3821 $miniserv::pam_conversation_process_writer = $writer;
3822 $miniserv::pam_conversation_process_reader = $reader;
3823 eval "use Authen::PAM;";
3824 local $convh = new Authen::PAM(
3825 $config{'pam'}, $user, \&miniserv::pam_conversation_process_func);
3826 local $pam_ret = $convh->pam_authenticate();
3827 if ($pam_ret == PAM_SUCCESS()) {
3828 local $acct_ret = $convh->pam_acct_mgmt();
3829 if ($acct_ret == PAM_SUCCESS()) {
3830 $convh->pam_open_session();
3831 print $writer "x2 $user 1 0 0\n";
3833 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3834 $acct_ret == PAM_ACCT_EXPIRED()) {
3835 print $writer "x2 $user 1 1 0\n";
3838 print $writer "x0 Unknown PAM account status $acct_ret\n";
3842 print $writer "x2 $user 0 0 0\n";
3847 # pam_conversation_process_func(type, message, [type, message, ...])
3848 # A pipe that talks to both PAM and the master process
3849 sub pam_conversation_process_func
3852 select($miniserv::pam_conversation_process_writer); $| = 1; select(STDOUT);
3854 local ($type, $msg) = (shift, shift);
3856 local $ok = (print $miniserv::pam_conversation_process_writer "$type $msg\n");
3857 print $miniserv::pam_conversation_process_writer "\n";
3858 local $answer = <$miniserv::pam_conversation_process_reader>;
3859 $answer =~ s/\r|\n//g;
3860 push(@rv, PAM_SUCCESS(), $answer);
3862 push(@rv, PAM_SUCCESS());
3867 # Returns 4 new pipe file handles
3870 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3872 local %taken = ( (map { $_, 1 } @passin),
3873 (map { $_->{'PASSINr'} } values %conversations) );
3874 for($p=0; $taken{"PASSINr$p"}; $p++) { }
3875 $PASSINr = "PASSINr$p";
3876 $PASSINw = "PASSINw$p";
3877 $PASSOUTr = "PASSOUTr$p";
3878 $PASSOUTw = "PASSOUTw$p";
3879 pipe($PASSINr, $PASSINw);
3880 pipe($PASSOUTr, $PASSOUTw);
3881 select($PASSINw); $| = 1;
3882 select($PASSINr); $| = 1;
3883 select($PASSOUTw); $| = 1;
3884 select($PASSOUTw); $| = 1;
3886 return ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3889 # recv_pam_question(&conv, fd)
3890 # Reads one PAM question from the sub-process, and sends it to the HTTP handler.
3891 # Returns 0 if the conversation is over, 1 if not.
3892 sub recv_pam_question
3894 local ($conf, $fh) = @_;
3895 local $pr = $conf->{'PAMOUTr'};
3896 select($pr); $| = 1; select(STDOUT);
3897 local $line = <$pr>;
3898 $line =~ s/\r|\n//g;
3901 $line =~ s/\r|\n//g;
3903 $conf->{'last'} = time();
3906 print $fh "0 PAM conversation error\n";
3910 local ($type, $msg) = split(/\s+/, $line, 2);
3911 if ($type =~ /^x(\d+)/) {
3912 # Pass this status code through
3913 print $fh "$1 $msg\n";
3914 return $1 == 2 || $1 == 0 ? 0 : 1;
3916 elsif ($type == PAM_PROMPT_ECHO_ON()) {
3918 print $fh "1 $msg\n";
3921 elsif ($type == PAM_PROMPT_ECHO_OFF()) {
3923 print $fh "3 $msg\n";
3926 elsif ($type == PAM_ERROR_MSG() || $type == PAM_TEXT_INFO()) {
3927 # A message that does not require a response
3928 print $fh "4 $msg\n";
3933 print $fh "0 Unknown PAM message type $type\n";
3939 # send_pam_answer(&conv, answer)
3940 # Sends a response from the user to the PAM sub-process
3943 local ($conf, $answer) = @_;
3944 local $pw = $conf->{'PAMINw'};
3945 $conf->{'last'} = time();
3946 print $pw "$answer\n";
3949 # end_pam_conversation(&conv)
3950 # Clean up PAM conversation pipes and processes
3951 sub end_pam_conversation
3954 kill('KILL', $conv->{'pid'}) if ($conv->{'pid'});
3955 if ($conv->{'PAMINr'}) {
3956 close($conv->{'PAMINr'});
3957 close($conv->{'PAMOUTr'});
3958 close($conv->{'PAMINw'});
3959 close($conv->{'PAMOUTw'});
3961 delete($conversations{$conv->{'cid'}});
3964 # get_ipkeys(&miniserv)
3965 # Returns a list of IP address to key file mappings from a miniserv.conf entry
3969 foreach $k (keys %{$_[0]}) {
3970 if ($k =~ /^ipkey_(\S+)/) {
3971 local $ipkey = { 'ips' => [ split(/,/, $1) ],
3972 'key' => $_[0]->{$k},
3973 'index' => scalar(@rv) };
3974 $ipkey->{'cert'} = $_[0]->{'ipcert_'.$1};
3981 # create_ssl_context(keyfile, [certfile])
3982 sub create_ssl_context
3984 local ($keyfile, $certfile) = @_;
3986 eval { $ssl_ctx = Net::SSLeay::new_x_ctx() };
3987 $ssl_ctx ||= Net::SSLeay::CTX_new();
3988 $ssl_ctx || die "Failed to create SSL context : $!";
3989 if ($client_certs) {
3990 Net::SSLeay::CTX_load_verify_locations(
3991 $ssl_ctx, $config{'ca'}, "");
3992 Net::SSLeay::CTX_set_verify(
3993 $ssl_ctx, &Net::SSLeay::VERIFY_PEER, \&verify_client);
3995 if ($config{'extracas'}) {
3997 foreach $p (split(/\s+/, $config{'extracas'})) {
3998 Net::SSLeay::CTX_load_verify_locations(
4003 Net::SSLeay::CTX_use_RSAPrivateKey_file(
4005 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL key $keyfile";
4006 Net::SSLeay::CTX_use_certificate_file(
4007 $ssl_ctx, $certfile || $keyfile,
4008 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL cert $certfile";
4013 # ssl_connection_for_ip(socket)
4014 # Returns a new SSL connection object for some socket, or undef if failed
4015 sub ssl_connection_for_ip
4018 local $sn = getsockname($sock);
4020 print STDERR "Failed to get address for socket $sock\n";
4023 local $myip = inet_ntoa((unpack_sockaddr_in($sn))[1]);
4024 local $ssl_ctx = $ssl_contexts{$myip} || $ssl_contexts{"*"};
4025 local $ssl_con = Net::SSLeay::new($ssl_ctx);
4026 if ($config{'ssl_cipher_list'}) {
4027 # Force use of ciphers
4028 eval "Net::SSLeay::set_cipher_list(
4029 \$ssl_con, \$config{'ssl_cipher_list'})";
4031 print STDERR "SSL cipher $config{'ssl_cipher_list'} failed : ",
4037 Net::SSLeay::set_fd($ssl_con, fileno($sock));
4038 if (!Net::SSLeay::accept($ssl_con)) {
4039 print STDERR "Failed to initialize SSL connection\n";
4045 # login_redirect(username, password, host)
4046 # Calls the login redirect script (if configured), which may output a URL to
4047 # re-direct a user to after logging in.
4050 return undef if (!$config{'login_redirect'});
4051 local $quser = quotemeta($_[0]);
4052 local $qpass = quotemeta($_[1]);
4053 local $qhost = quotemeta($_[2]);
4054 local $url = `$config{'login_redirect'} $quser $qpass $qhost`;
4059 # reload_config_file()
4060 # Re-read %config, and call post-config actions
4061 sub reload_config_file
4063 &log_error("Reloading configuration");
4064 %config = &read_config_file($config_file);
4065 &update_vital_config();
4068 &build_config_mappings();
4069 &read_webmin_crons();
4070 if ($config{'session'}) {
4071 dbmclose(%sessiondb);
4072 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
4076 # read_config_file(file)
4077 # Reads the given config file, and returns a hash of values
4078 sub read_config_file
4081 open(CONF, $_[0]) || die "Failed to open config file $_[0] : $!";
4084 if (/^#/ || !/\S/) { next; }
4086 $name = $1; $val = $2;
4087 $name =~ s/^\s+//g; $name =~ s/\s+$//g;
4088 $val =~ s/^\s+//g; $val =~ s/\s+$//g;
4095 # update_vital_config()
4096 # Updates %config with defaults, and dies if something vital is missing
4097 sub update_vital_config
4099 my %vital = ("port", 80,
4101 "server", "MiniServ/0.01",
4102 "index_docs", "index.html index.htm index.cgi index.php",
4103 "addtype_html", "text/html",
4104 "addtype_txt", "text/plain",
4105 "addtype_gif", "image/gif",
4106 "addtype_jpg", "image/jpeg",
4107 "addtype_jpeg", "image/jpeg",
4108 "realm", "MiniServ",
4109 "session_login", "/session_login.cgi",
4110 "pam_login", "/pam_login.cgi",
4111 "password_form", "/password_form.cgi",
4112 "password_change", "/password_change.cgi",
4116 "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\$",
4118 "expires", 7*24*60*60,
4119 "pam_test_user", "root",
4121 foreach my $v (keys %vital) {
4123 if ($vital{$v} eq "") {
4124 die "Missing config option $v";
4126 $config{$v} = $vital{$v};
4129 if (!$config{'sessiondb'}) {
4130 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4131 $config{'sessiondb'} = "$1/sessiondb";
4133 if (!$config{'errorlog'}) {
4134 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
4135 $config{'errorlog'} = "$1/miniserv.error";
4137 if (!$config{'tempbase'}) {
4138 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4139 $config{'tempbase'} = "$1/cgitemp";
4141 if (!$config{'blockedfile'}) {
4142 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4143 $config{'blockedfile'} = "$1/blocked";
4145 if (!$config{'webmincron_dir'}) {
4146 $config_file =~ /^(.*)\/[^\/]+$/;
4147 $config{'webmincron_dir'} = "$1/webmincron/crons";
4149 if (!$config{'webmincron_last'}) {
4150 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
4151 $config{'webmincron_last'} = "$1/miniserv.lastcrons";
4153 if (!$config{'webmincron_wrapper'}) {
4154 $config{'webmincron_wrapper'} = $config{'root'}.
4155 "/webmincron/webmincron.pl";
4160 # Fills the %users and %certs hashes from the users file in %config
4169 undef(%lastchanges);
4172 if ($config{'userfile'}) {
4173 open(USERS, $config{'userfile'});
4176 local @user = split(/:/, $_, -1);
4177 $users{$user[0]} = $user[1];
4178 $certs{$user[0]} = $user[3] if ($user[3]);
4179 if ($user[4] =~ /^allow\s+(.*)/) {
4180 $allow{$user[0]} = $config{'alwaysresolve'} ?
4181 [ split(/\s+/, $1) ] :
4182 [ &to_ipaddress(split(/\s+/, $1)) ];
4184 elsif ($user[4] =~ /^deny\s+(.*)/) {
4185 $deny{$user[0]} = $config{'alwaysresolve'} ?
4186 [ split(/\s+/, $1) ] :
4187 [ &to_ipaddress(split(/\s+/, $1)) ];
4189 if ($user[5] =~ /days\s+(\S+)/) {
4190 $allowdays{$user[0]} = [ split(/,/, $1) ];
4192 if ($user[5] =~ /hours\s+(\d+)\.(\d+)-(\d+).(\d+)/) {
4193 $allowhours{$user[0]} = [ $1*60+$2, $3*60+$4 ];
4195 $lastchanges{$user[0]} = $user[6];
4196 $nochange{$user[0]} = $user[9];
4197 $temppass{$user[0]} = $user[10];
4202 # Test user DB, if configured
4203 if ($config{'userdb'}) {
4204 my $dbh = &connect_userdb($config{'userdb'});
4206 print STDERR "Failed to open users database : $dbh\n"
4209 &disconnect_userdb($config{'userdb'}, $dbh);
4214 # get_user_details(username)
4215 # Returns a hash ref of user details, either from config files or the user DB
4216 sub get_user_details
4218 my ($username) = @_;
4219 if (exists($users{$username})) {
4221 return { 'name' => $username,
4222 'pass' => $users{$username},
4223 'certs' => $certs{$username},
4224 'allow' => $allow{$username},
4225 'deny' => $deny{$username},
4226 'allowdays' => $allowdays{$username},
4227 'allowhours' => $allowhours{$username},
4228 'lastchanges' => $lastchanges{$username},
4229 'nochange' => $nochange{$username},
4230 'temppass' => $temppass{$username},
4231 'preroot' => $config{'preroot_'.$username},
4234 if ($config{'userdb'}) {
4235 # Try querying user database
4236 if (exists($get_user_details_cache{$username})) {
4238 return $get_user_details_cache{$username};
4240 print DEBUG "get_user_details: Connecting to user database\n";
4241 my ($dbh, $proto, $prefix, $args) = &connect_userdb($config{'userdb'});
4245 print DEBUG "get_user_details: Failed : $dbh\n";
4246 print STDERR "Failed to connect to user database : $dbh\n";
4248 elsif ($proto eq "mysql" || $proto eq "postgresql") {
4249 # Fetch user ID and password with SQL
4250 print DEBUG "get_user_details: Looking for $username in SQL\n";
4251 my $cmd = $dbh->prepare(
4252 "select id,pass from webmin_user where name = ?");
4253 if (!$cmd || !$cmd->execute($username)) {
4254 print STDERR "Failed to lookup user : ",
4258 my ($id, $pass) = $cmd->fetchrow();
4261 &disconnect_userdb($config{'userdb'}, $dbh);
4262 $get_user_details_cache{$username} = undef;
4263 print DEBUG "get_user_details: User not found\n";
4266 print DEBUG "get_user_details: id=$id pass=$pass\n";
4268 # Fetch attributes and add to user object
4269 print DEBUG "get_user_details: finding user attributes\n";
4270 my $cmd = $dbh->prepare(
4271 "select attr,value from webmin_user_attr where id = ?");
4272 if (!$cmd || !$cmd->execute($id)) {
4273 print STDERR "Failed to lookup user attrs : ",
4277 $user = { 'name' => $username,
4280 'proto' => $proto };
4281 while(my ($attr, $value) = $cmd->fetchrow()) {
4282 $attrs{$attr} = $value;
4286 elsif ($proto eq "ldap") {
4287 # Fetch user DN with LDAP
4288 print DEBUG "get_user_details: Looking for $username in LDAP\n";
4289 my $rv = $dbh->search(
4291 filter => '(&(cn='.$username.')(objectClass='.
4292 $args->{'userclass'}.'))',
4294 if (!$rv || $rv->code) {
4295 print STDERR "Failed to lookup user : ",
4296 ($rv ? $rv->error : "Unknown error"),"\n";
4299 my ($u) = $rv->all_entries();
4301 &disconnect_userdb($config{'userdb'}, $dbh);
4302 $get_user_details_cache{$username} = undef;
4303 print DEBUG "get_user_details: User not found\n";
4307 # Extract attributes
4308 my $pass = $u->get_value('webminPass');
4309 $user = { 'name' => $username,
4312 'proto' => $proto };
4313 foreach my $la ($u->get_value('webminAttr')) {
4314 my ($attr, $value) = split(/=/, $la, 2);
4315 $attrs{$attr} = $value;
4319 # Convert DB attributes into user object fields
4321 print DEBUG "get_user_details: got ",scalar(keys %attrs),
4323 $user->{'certs'} = $attrs{'cert'};
4324 if ($attrs{'allow'}) {
4325 $user->{'allow'} = $config{'alwaysresolve'} ?
4326 [ split(/\s+/, $attrs{'allow'}) ] :
4327 [ &to_ipaddress(split(/\s+/,$attrs{'allow'})) ];
4329 if ($attrs{'deny'}) {
4330 $user->{'deny'} = $config{'alwaysresolve'} ?
4331 [ split(/\s+/, $attrs{'deny'}) ] :
4332 [ &to_ipaddress(split(/\s+/,$attrs{'deny'})) ];
4334 if ($attrs{'days'}) {
4335 $user->{'allowdays'} = [ split(/,/, $attrs{'days'}) ];
4337 if ($attrs{'hoursfrom'} && $attrs{'hoursto'}) {
4338 my ($hf, $mf) = split(/\./, $attrs{'hoursfrom'});
4339 my ($ht, $mt) = split(/\./, $attrs{'hoursto'});
4340 $user->{'allowhours'} = [ $hf*60+$ht, $ht*60+$mt ];
4342 $user->{'lastchanges'} = $attrs{'lastchange'};
4343 $user->{'nochange'} = $attrs{'nochange'};
4344 $user->{'temppass'} = $attrs{'temppass'};
4345 $user->{'preroot'} = $attrs{'theme'};
4347 &disconnect_userdb($config{'userdb'}, $dbh);
4348 $get_user_details_cache{$user->{'name'}} = $user;
4354 # find_user_by_cert(cert)
4355 # Returns a username looked up by certificate
4356 sub find_user_by_cert
4358 my ($peername) = @_;
4359 my $peername2 = $peername;
4360 $peername2 =~ s/Email=/emailAddress=/ || $peername2 =~ s/emailAddress=/Email=/;
4362 # First check users in local files
4363 foreach my $username (keys %certs) {
4364 if ($certs{$username} eq $peername ||
4365 $certs{$username} eq $peername2) {
4371 if ($config{'userdb'}) {
4372 my ($dbh, $proto) = &connect_userdb($config{'userdb'});
4376 elsif ($proto eq "mysql" || $proto eq "postgresql") {
4378 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 = ?");
4379 return undef if (!$cmd);
4380 foreach my $p ($peername, $peername2) {
4382 if ($cmd->execute($p)) {
4383 ($username) = $cmd->fetchrow();
4386 return $username if ($username);
4389 elsif ($proto eq "ldap") {
4391 my $rv = $dbh->search(
4393 filter => '(objectClass='.
4394 $args->{'userclass'}.')',
4396 attrs => [ 'cn', 'webminAttr' ]);
4397 if ($rv && !$rv->code) {
4398 foreach my $u ($rv->all_entries) {
4399 my @attrs = $u->get_value('webminAttr');
4400 foreach my $la (@attrs) {
4401 my ($attr, $value) = split(/=/, $la, 2);
4402 if ($attr eq "cert" &&
4403 ($value eq $peername ||
4404 $value eq $peername2)) {
4405 return $u->get_value('cn');
4415 # connect_userdb(string)
4416 # Returns a handle for talking to a user database - may be a DBI or LDAP handle.
4417 # On failure returns an error message string. In an array context, returns the
4418 # protocol type too.
4422 my ($proto, $user, $pass, $host, $prefix, $args) = &split_userdb_string($str);
4423 if ($proto eq "mysql") {
4424 # Connect to MySQL with DBI
4425 my $drh = eval "use DBI; DBI->install_driver('mysql');";
4426 $drh || return $text{'sql_emysqldriver'};
4427 my ($host, $port) = split(/:/, $host);
4428 my $cstr = "database=$prefix;host=$host";
4429 $cstr .= ";port=$port" if ($port);
4430 print DEBUG "connect_userdb: Connecting to MySQL $cstr as $user\n";
4431 my $dbh = $drh->connect($cstr, $user, $pass, { });
4432 $dbh || return &text('sql_emysqlconnect', $drh->errstr);
4433 print DEBUG "connect_userdb: Connected OK\n";
4434 return wantarray ? ($dbh, $proto, $prefix, $args) : $dbh;
4436 elsif ($proto eq "postgresql") {
4437 # Connect to PostgreSQL with DBI
4438 my $drh = eval "use DBI; DBI->install_driver('Pg');";
4439 $drh || return $text{'sql_epostgresqldriver'};
4440 my ($host, $port) = split(/:/, $host);
4441 my $cstr = "dbname=$prefix;host=$host";
4442 $cstr .= ";port=$port" if ($port);
4443 print DEBUG "connect_userdb: Connecting to PostgreSQL $cstr as $user\n";
4444 my $dbh = $drh->connect($cstr, $user, $pass);
4445 $dbh || return &text('sql_epostgresqlconnect', $drh->errstr);
4446 print DEBUG "connect_userdb: Connected OK\n";
4447 return wantarray ? ($dbh, $proto, $prefix, $args) : $dbh;
4449 elsif ($proto eq "ldap") {
4450 # Connect with perl LDAP module
4451 eval "use Net::LDAP";
4452 $@ && return $text{'sql_eldapdriver'};
4453 my ($host, $port) = split(/:/, $host);
4454 my $scheme = $args->{'scheme'} || 'ldap';
4456 $port = $scheme eq 'ldaps' ? 636 : 389;
4458 my $ldap = Net::LDAP->new($host,
4460 'scheme' => $scheme);
4461 $ldap || return &text('sql_eldapconnect', $host);
4463 if ($args->{'tls'}) {
4464 # Switch to TLS mode
4465 eval { $mesg = $ldap->start_tls(); };
4466 if ($@ || !$mesg || $mesg->code) {
4467 return &text('sql_eldaptls',
4468 $@ ? $@ : $mesg ? $mesg->error : "Unknown error");
4471 # Login to the server
4473 $mesg = $ldap->bind(dn => $user, password => $pass);
4476 $mesg = $ldap->bind(dn => $user, anonymous => 1);
4478 if (!$mesg || $mesg->code) {
4479 return &text('sql_eldaplogin', $user,
4480 $mesg ? $mesg->error : "Unknown error");
4482 return wantarray ? ($ldap, $proto, $prefix, $args) : $ldap;
4485 return "Unknown protocol $proto";
4489 # split_userdb_string(string)
4490 # Converts a string like mysql://user:pass@host/db into separate parts
4491 sub split_userdb_string
4494 if ($str =~ /^([a-z]+):\/\/([^:]*):([^\@]*)\@([a-z0-9\.\-\_]+)\/([^\?]+)(\?(.*))?$/) {
4495 my ($proto, $user, $pass, $host, $prefix, $argstr) =
4496 ($1, $2, $3, $4, $5, $7);
4497 my %args = map { split(/=/, $_, 2) } split(/\&/, $argstr);
4498 return ($proto, $user, $pass, $host, $prefix, \%args);
4503 # disconnect_userdb(string, &handle)
4504 # Closes a handle opened by connect_userdb
4505 sub disconnect_userdb
4508 if ($str =~ /^(mysql|postgresql):/) {
4512 elsif ($str =~ /^ldap:/) {
4519 # Fills %mime with entries from file in %config and extra settings in %config
4523 if ($config{"mimetypes"} ne "") {
4524 open(MIME, $config{"mimetypes"});
4527 if (/^(\S+)\s+(.*)$/) {
4529 my @exts = split(/\s+/, $2);
4530 foreach my $ext (@exts) {
4531 $mime{$ext} = $type;
4537 foreach my $k (keys %config) {
4538 if ($k !~ /^addtype_(.*)$/) { next; }
4539 $mime{$1} = $config{$k};
4543 # build_config_mappings()
4544 # Build the anonymous access list, IP access list, unauthenticated URLs list,
4545 # redirect mapping and allow and deny lists from %config
4546 sub build_config_mappings
4548 # build anonymous access list
4550 foreach my $a (split(/\s+/, $config{'anonymous'})) {
4551 if ($a =~ /^([^=]+)=(\S+)$/) {
4552 $anonymous{$1} = $2;
4556 # build IP access list
4558 foreach my $a (split(/\s+/, $config{'ipaccess'})) {
4559 if ($a =~ /^([^=]+)=(\S+)$/) {
4564 # build unauthenticated URLs list
4565 @unauth = split(/\s+/, $config{'unauth'});
4567 # build redirect mapping
4569 foreach my $r (split(/\s+/, $config{'redirect'})) {
4570 if ($r =~ /^([^=]+)=(\S+)$/) {
4575 # build prefixes to be stripped
4576 undef(@strip_prefix);
4577 foreach my $r (split(/\s+/, $config{'strip_prefix'})) {
4578 push(@strip_prefix, $r);
4581 # Init allow and deny lists
4582 @deny = split(/\s+/, $config{"deny"});
4583 @deny = &to_ipaddress(@deny) if (!$config{'alwaysresolve'});
4584 @allow = split(/\s+/, $config{"allow"});
4585 @allow = &to_ipaddress(@allow) if (!$config{'alwaysresolve'});
4588 if ($config{'allowusers'}) {
4589 @allowusers = split(/\s+/, $config{'allowusers'});
4591 elsif ($config{'denyusers'}) {
4592 @denyusers = split(/\s+/, $config{'denyusers'});
4595 # Build list of unixauth mappings
4597 foreach my $ua (split(/\s+/, $config{'unixauth'})) {
4598 if ($ua =~ /^(\S+)=(\S+)$/) {
4602 $unixauth{"*"} = $ua;
4606 # Build list of non-session-auth pages
4607 undef(%sessiononly);
4608 foreach my $sp (split(/\s+/, $config{'sessiononly'})) {
4609 $sessiononly{$sp} = 1;
4612 # Build list of logout times
4613 undef(@logouttimes);
4614 foreach my $a (split(/\s+/, $config{'logouttimes'})) {
4615 if ($a =~ /^([^=]+)=(\S+)$/) {
4616 push(@logouttimes, [ $1, $2 ]);
4619 push(@logouttimes, [ undef, $config{'logouttime'} ]);
4621 # Build list of DAV pathss
4623 foreach my $d (split(/\s+/, $config{'davpaths'})) {
4624 push(@davpaths, $d);
4626 @davusers = split(/\s+/, $config{'dav_users'});
4628 # Mobile agent substrings and hostname prefixes
4629 @mobile_agents = split(/\t+/, $config{'mobile_agents'});
4630 @mobile_prefixes = split(/\s+/, $config{'mobile_prefixes'});
4634 if ($config{'debug'}) {
4635 open(DEBUG, ">>$config{'debug'}");
4638 open(DEBUG, ">/dev/null");
4641 # Reset cache of sudo checks
4645 # is_group_member(&uinfo, groupname)
4646 # Returns 1 if some user is a primary or secondary member of a group
4649 local ($uinfo, $group) = @_;
4650 local @ginfo = getgrnam($group);
4651 return 0 if (!@ginfo);
4652 return 1 if ($ginfo[2] == $uinfo->[3]); # primary member
4653 foreach my $m (split(/\s+/, $ginfo[3])) {
4654 return 1 if ($m eq $uinfo->[0]);
4659 # prefix_to_mask(prefix)
4660 # Converts a number like 24 to a mask like 255.255.255.0
4663 return $_[0] >= 24 ? "255.255.255.".(256-(2 ** (32-$_[0]))) :
4664 $_[0] >= 16 ? "255.255.".(256-(2 ** (24-$_[0]))).".0" :
4665 $_[0] >= 8 ? "255.".(256-(2 ** (16-$_[0]))).".0.0" :
4666 (256-(2 ** (8-$_[0]))).".0.0.0";
4669 # get_logout_time(user, session-id)
4670 # Given a username, returns the idle time before he will be logged out
4673 local ($user, $sid) = @_;
4674 if (!defined($logout_time_cache{$user,$sid})) {
4676 foreach my $l (@logouttimes) {
4677 if ($l->[0] =~ /^\@(.*)$/) {
4678 # Check group membership
4679 local @uinfo = getpwnam($user);
4680 if (@uinfo && &is_group_member(\@uinfo, $1)) {
4684 elsif ($l->[0] =~ /^\//) {
4685 # Check file contents
4686 open(FILE, $l->[0]);
4703 if ($l->[0] eq $user) {
4707 last if (defined($time));
4709 $logout_time_cache{$user,$sid} = $time;
4711 return $logout_time_cache{$user,$sid};
4714 # password_crypt(password, salt)
4715 # If the salt looks like MD5 and we have a library for it, perform MD5 hashing
4716 # of a password. Otherwise, do Unix crypt.
4719 local ($pass, $salt) = @_;
4720 if ($salt =~ /^\$1\$/ && $use_md5) {
4721 return &encrypt_md5($pass, $salt);
4724 return &unix_crypt($pass, $salt);
4728 # unix_crypt(password, salt)
4729 # Performs standard Unix hashing for a password
4732 local ($pass, $salt) = @_;
4733 if ($use_perl_crypt) {
4734 return Crypt::UnixCrypt::crypt($pass, $salt);
4737 return crypt($pass, $salt);
4741 # handle_dav_request(davpath)
4742 # Pass a request on to the Net::DAV::Server module
4743 sub handle_dav_request
4746 eval "use Filesys::Virtual::Plain";
4747 eval "use Net::DAV::Server";
4748 eval "use HTTP::Request";
4749 eval "use HTTP::Headers";
4751 if ($Net::DAV::Server::VERSION eq '1.28' && $config{'dav_nolock'}) {
4752 delete $Net::DAV::Server::implemented{lock};
4753 delete $Net::DAV::Server::implemented{unlock};
4756 # Read in request data
4757 if (!$posted_data) {
4758 local $clen = $header{"content-length"};
4759 while(length($posted_data) < $clen) {
4760 $buf = &read_data($clen - length($posted_data));
4761 if (!length($buf)) {
4762 &http_error(500, "Failed to read POST request");
4764 $posted_data .= $buf;
4768 # For subsequent logging
4769 open(MINISERVLOG, ">>$config{'logfile'}");
4773 local @u = getpwnam($authuser);
4774 if ($config{'dav_remoteuser'} && !$< && $validated) {
4777 $( = $u[3]; $) = "$u[3] $u[3]";
4778 ($>, $<) = ($u[2], $u[2]);
4780 if ($config{'dav_root'} eq '*') {
4785 &http_error(500, "Unix user $authuser does not exist");
4789 $root ||= $config{'dav_root'};
4792 # Check if this user can use DAV
4794 &users_match(\@u, @davusers) ||
4795 &http_error(500, "You are not allowed to access DAV");
4799 my $filesys = Filesys::Virtual::Plain->new({root_path => $root});
4800 my $webdav = Net::DAV::Server->new();
4801 $webdav->filesys($filesys);
4803 # Make up a request object, and feed to DAV
4804 local $ho = HTTP::Headers->new;
4805 foreach my $h (keys %header) {
4806 next if (lc($h) eq "connection");
4807 $ho->header($h => $header{$h});
4810 $request_uri =~ s/^\Q$path\E//;
4811 $request_uri = "/" if ($request_uri eq "");
4813 my $request = HTTP::Request->new($method, $request_uri, $ho,
4815 if ($config{'dav_debug'}) {
4816 print STDERR "DAV request :\n";
4817 print STDERR "---------------------------------------------\n";
4818 print STDERR $request->as_string();
4819 print STDERR "---------------------------------------------\n";
4821 my $response = $webdav->run($request);
4823 # Send back the reply
4824 &write_data("HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n");
4825 local $content = $response->content();
4827 $content =~ s|href>/(.+)<|href>$path/$1<|g;
4828 $content =~ s|href>/<|href>$path<|g;
4830 foreach my $h ($response->header_field_names) {
4831 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4832 &write_data("$h: ",$response->header($h),"\r\n");
4834 &write_data("Content-length: ",length($content),"\r\n");
4835 local $rv = &write_keep_alive(0);
4836 &write_data("\r\n");
4837 &write_data($content);
4839 if ($config{'dav_debug'}) {
4840 print STDERR "DAV reply :\n";
4841 print STDERR "---------------------------------------------\n";
4842 print STDERR "HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n";
4843 foreach my $h ($response->header_field_names) {
4844 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4845 print STDERR "$h: ",$response->header($h),"\r\n";
4847 print STDERR "Content-length: ",length($content),"\r\n";
4848 print STDERR "\r\n";
4849 print STDERR $content;
4850 print STDERR "---------------------------------------------\n";
4854 &log_request($acpthost, $authuser, $reqline, $response->code(),
4855 length($response->content()));
4858 # get_system_hostname()
4859 # Returns the hostname of this system, for reporting to listeners
4860 sub get_system_hostname
4862 # On Windows, try computername environment variable
4863 return $ENV{'computername'} if ($ENV{'computername'});
4864 return $ENV{'COMPUTERNAME'} if ($ENV{'COMPUTERNAME'});
4866 # If a specific command is set, use it first
4867 if ($config{'hostname_command'}) {
4868 local $out = `($config{'hostname_command'}) 2>&1`;
4875 # First try the hostname command
4876 local $out = `hostname 2>&1`;
4877 if (!$? && $out =~ /\S/) {
4882 # Try the Sys::Hostname module
4883 eval "use Sys::Hostname";
4885 local $rv = eval "hostname()";
4891 # Must use net name on Windows
4892 local $out = `net name 2>&1`;
4893 if ($out =~ /\-+\r?\n(\S+)/) {
4900 # indexof(string, array)
4901 # Returns the index of some value in an array, or -1
4904 for($i=1; $i <= $#_; $i++) {
4905 if ($_[$i] eq $_[0]) { return $i - 1; }
4911 # has_command(command)
4912 # Returns the full path if some command is in the path, undef if not
4916 if (!$_[0]) { return undef; }
4917 if (exists($has_command_cache{$_[0]})) {
4918 return $has_command_cache{$_[0]};
4921 if ($_[0] =~ /^\//) {
4922 $rv = -x $_[0] ? $_[0] : undef;
4925 local $sp = $on_windows ? ';' : ':';
4926 foreach $d (split($sp, $ENV{PATH})) {
4927 if (-x "$d/$_[0]") {
4932 foreach my $sfx (".exe", ".com", ".bat") {
4933 if (-r "$d/$_[0]".$sfx) {
4934 $rv = "$d/$_[0]".$sfx;
4941 $has_command_cache{$_[0]} = $rv;
4945 # check_sudo_permissions(user, pass)
4946 # Returns 1 if some user can run any command via sudo
4947 sub check_sudo_permissions
4949 local ($user, $pass) = @_;
4951 # First try the pipes
4953 print DEBUG "check_sudo_permissions: querying cache for $user\n";
4954 print $PASSINw "readsudo $user\n";
4955 local $can = <$PASSOUTr>;
4957 print DEBUG "check_sudo_permissions: cache said $can\n";
4958 if ($can =~ /^\d+$/ && $can != 2) {
4963 local $ptyfh = new IO::Pty;
4964 print DEBUG "check_sudo_permissions: ptyfh=$ptyfh\n";
4966 print STDERR "Failed to create new PTY with IO::Pty\n";
4969 local @uinfo = getpwnam($user);
4971 print STDERR "Unix user $user does not exist for sudo\n";
4975 # Execute sudo in a sub-process, via a pty
4976 local $ttyfh = $ptyfh->slave();
4977 print DEBUG "check_sudo_permissions: ttyfh=$ttyfh\n";
4978 local $tty = $ptyfh->ttyname();
4979 print DEBUG "check_sudo_permissions: tty=$tty\n";
4980 chown($uinfo[2], $uinfo[3], $tty);
4982 print DEBUG "check_sudo_permissions: about to fork..\n";
4983 local $pid = fork();
4984 print DEBUG "check_sudo_permissions: fork=$pid pid=$$\n";
4986 print STDERR "fork for sudo failed : $!\n";
4991 $ptyfh->make_slave_controlling_terminal();
4992 close(STDIN); close(STDOUT); close(STDERR);
4993 untie(*STDIN); untie(*STDOUT); untie(*STDERR);
4994 close($PASSINw); close($PASSOUTr);
4995 $( = $uinfo[3]; $) = "$uinfo[3] $uinfo[3]";
4996 ($>, $<) = ($uinfo[2], $uinfo[2]);
5001 open(STDIN, "<&SUDOr");
5002 open(STDOUT, ">$tty");
5003 open(STDERR, ">&STDOUT");
5006 print "Exec failed : $!\n";
5009 print DEBUG "check_sudo_permissions: pid=$pid\n";
5011 $ptyfh->close_slave();
5013 # Send password, and get back response
5014 local $oldfh = select(SUDOw);
5017 print DEBUG "check_sudo_permissions: about to send pass\n";
5018 local $SIG{'PIPE'} = 'ignore'; # Sometimes sudo doesn't ask for a password
5019 print SUDOw $pass,"\n";
5020 print DEBUG "check_sudo_permissions: sent pass=$pass\n";
5024 print DEBUG "check_sudo_permissions: got $_";
5030 local ($ok) = ($out =~ /\(ALL\)\s+ALL/ ? 1 : 0);
5034 print $PASSINw "writesudo $user $ok\n";
5040 # is_mobile_useragent(agent)
5041 # Returns 1 if some user agent looks like a cellphone or other mobile device,
5043 sub is_mobile_useragent
5045 local ($agent) = @_;
5047 "UP.Link", # Openwave
5048 "Nokia", # All Nokias start with Nokia
5049 "MOT-", # All Motorola phones start with MOT-
5050 "SAMSUNG", # Samsung browsers
5051 "Samsung", # Samsung browsers
5052 "SEC-", # Samsung browsers
5053 "AU-MIC", # Samsung browsers
5054 "AUDIOVOX", # Audiovox
5055 "BlackBerry", # BlackBerry
5056 "hiptop", # Danger hiptop Sidekick
5057 "SonyEricsson", # Sony Ericsson
5058 "Ericsson", # Old Ericsson browsers , mostly WAP
5059 "Mitsu/1.1.A", # Mitsubishi phones
5060 "Panasonic WAP", # Panasonic old WAP phones
5061 "DoCoMo", # DoCoMo phones
5062 "Lynx", # Lynx text-mode linux browser
5063 "Links", # Another text-mode linux browser
5065 local @substrings = (
5066 "UP.Browser", # Openwave
5067 "MobilePhone", # NetFront
5068 "AU-MIC-A700", # Samsung A700 Obigo browsers
5069 "Danger hiptop", # Danger Sidekick hiptop
5070 "Windows CE", # Windows CE Pocket PC
5071 "IEMobile", # Windows mobile browser
5072 "Blazer", # Palm Treo Blazer
5073 "BlackBerry", # BlackBerries can emulate other browsers, but
5074 # they still keep this string in the UserAgent
5075 "SymbianOS", # New Series60 browser has safari in it and
5076 # SymbianOS is the only distinguishing string
5077 "iPhone", # Apple iPhone KHTML browser
5078 "iPod", # iPod touch browser
5079 "MobileSafari", # HTTP client in iPhone
5081 "Opera Mini", # Opera Mini
5082 "HTC_P3700", # HTC mobile device
5084 "webOS/", # Palm WebOS
5085 "Nintendo DS", # DSi / DSi-XL
5087 foreach my $p (@prefixes) {
5088 return 1 if ($agent =~ /^\Q$p\E/);
5090 foreach my $s (@substrings, @mobile_agents) {
5091 return 1 if ($agent =~ /\Q$s\E/);
5096 # write_blocked_file()
5097 # Writes out a text file of blocked hosts and users
5098 sub write_blocked_file
5100 open(BLOCKED, ">$config{'blockedfile'}");
5101 foreach my $d (grep { $hostfail{$_} } @deny) {
5102 print BLOCKED "host $d $hostfail{$d} $blockhosttime{$d}\n";
5104 foreach my $d (grep { $userfail{$_} } @denyusers) {
5105 print BLOCKED "user $d $userfail{$d} $blockusertime{$d}\n";
5108 chmod(0700, $config{'blockedfile'});
5113 open(PIDFILE, ">$config{'pidfile'}");
5114 printf PIDFILE "%d\n", getpid();
5116 $miniserv_main_pid = getpid();
5119 # lock_user_password(user)
5120 # Updates a user's password file entry to lock it, both in memory and on disk.
5121 # Returns 1 if done, -1 if no such user, 0 if already locked
5122 sub lock_user_password
5125 local $uinfo = &get_user_details($user);
5130 if ($uinfo->{'pass'} =~ /^\!/) {
5134 if (!$uinfo->{'proto'}) {
5135 # Write to users file
5136 $users{$user} = "!".$users{$user};
5137 open(USERS, $config{'userfile'});
5138 local @ufile = <USERS>;
5140 foreach my $u (@ufile) {
5141 local @uinfo = split(/:/, $u);
5142 if ($uinfo[0] eq $user) {
5143 $uinfo[1] = $users{$user};
5145 $u = join(":", @uinfo);
5147 open(USERS, ">$config{'userfile'}");
5153 if ($config{'userdb'}) {
5155 my ($dbh, $proto, $prefix, $args) = &connect_userdb($config{'userdb'});
5159 elsif ($proto eq "mysql" || $proto eq "postgresql") {
5160 # Update user attribute
5161 my $cmd = $dbh->prepare(
5162 "update webmin_user set pass = ? where id = ?");
5163 if (!$cmd || !$cmd->execute("!".$uinfo->{'pass'},
5166 print STDERR "Failed to lock password : ",
5170 $cmd->finish() if ($cmd);
5172 elsif ($proto eq "ldap") {
5173 # Update LDAP object
5174 my $rv = $dbh->modify($uinfo->{'id'},
5175 replace => { 'webminPass' => '!'.$uinfo->{'pass'} });
5176 if (!$rv || $rv->code) {
5177 print STDERR "Failed to lock password : ",
5178 ($rv ? $rv->error : "Unknown error"),"\n";
5182 &disconnect_userdb($config{'userdb'}, $dbh);
5186 return -1; # This should never be reached
5189 # hash_session_id(sid)
5190 # Returns an MD5 or Unix-crypted session ID
5194 if (!$hash_session_id_cache{$sid}) {
5197 $hash_session_id_cache{$sid} = &encrypt_md5($sid);
5201 $hash_session_id_cache{$sid} = &unix_crypt($sid, "XX");
5204 return $hash_session_id_cache{$sid};
5207 # encrypt_md5(string, [salt])
5208 # Returns a string encrypted in MD5 format
5211 local ($passwd, $salt) = @_;
5212 local $magic = '$1$';
5213 if ($salt =~ /^\$1\$([^\$]+)/) {
5214 # Extract actual salt from already encrypted password
5219 local $ctx = eval "new $use_md5";
5226 # Add some more stuff from the hash of the password and salt
5227 local $ctx1 = eval "new $use_md5";
5228 $ctx1->add($passwd);
5232 $ctx1->add($passwd);
5233 local $final = $ctx1->digest();
5234 for($pl=length($passwd); $pl>0; $pl-=16) {
5235 $ctx->add($pl > 16 ? $final : substr($final, 0, $pl));
5238 # This piece of code seems rather pointless, but it's in the C code that
5239 # does MD5 in PAM so it has to go in!
5242 for($i=length($passwd); $i; $i >>= 1) {
5247 $ctx->add(substr($passwd, $j, 1));
5250 $final = $ctx->digest();
5253 # This loop exists only to waste time
5254 for($i=0; $i<1000; $i++) {
5255 $ctx1 = eval "new $use_md5";
5256 $ctx1->add($i & 1 ? $passwd : $final);
5257 $ctx1->add($salt) if ($i % 3);
5258 $ctx1->add($passwd) if ($i % 7);
5259 $ctx1->add($i & 1 ? $final : $passwd);
5260 $final = $ctx1->digest();
5264 # Convert the 16-byte final string into a readable form
5266 local @final = map { ord($_) } split(//, $final);
5267 $l = ($final[ 0]<<16) + ($final[ 6]<<8) + $final[12];
5268 $rv .= &to64($l, 4);
5269 $l = ($final[ 1]<<16) + ($final[ 7]<<8) + $final[13];
5270 $rv .= &to64($l, 4);
5271 $l = ($final[ 2]<<16) + ($final[ 8]<<8) + $final[14];
5272 $rv .= &to64($l, 4);
5273 $l = ($final[ 3]<<16) + ($final[ 9]<<8) + $final[15];
5274 $rv .= &to64($l, 4);
5275 $l = ($final[ 4]<<16) + ($final[10]<<8) + $final[ 5];
5276 $rv .= &to64($l, 4);
5278 $rv .= &to64($l, 2);
5280 # Add salt if needed
5282 return $magic.$salt.'$'.$rv;
5291 local ($v, $n) = @_;
5294 $r .= $itoa64[$v & 0x3f];
5300 # read_file(file, &assoc, [&order], [lowercase])
5301 # Fill an associative array with name=value pairs from a file
5304 open(ARFILE, $_[0]) || return 0;
5307 if (!/^#/ && /^([^=]*)=(.*)$/) {
5308 $_[1]->{$_[3] ? lc($1) : $1} = $2;
5309 push(@{$_[2]}, $1) if ($_[2]);
5316 # write_file(file, array)
5317 # Write out the contents of an associative array as name=value lines
5320 local(%old, @order);
5321 &read_file($_[0], \%old, \@order);
5322 open(ARFILE, ">$_[0]");
5323 foreach $k (@order) {
5324 print ARFILE $k,"=",$_[1]->{$k},"\n" if (exists($_[1]->{$k}));
5326 foreach $k (keys %{$_[1]}) {
5327 print ARFILE $k,"=",$_[1]->{$k},"\n" if (!exists($old{$k}));
5332 # execute_ready_webmin_crons()
5333 # Find and run any cron jobs that are due, based on their last run time and
5334 # execution interval
5335 sub execute_ready_webmin_crons
5339 foreach my $cron (@webmincrons) {
5341 if (!$webmincron_last{$cron->{'id'}}) {
5342 # If not ever run before, don't run right away
5343 $webmincron_last{$cron->{'id'}} = $now;
5346 elsif ($cron->{'interval'} &&
5347 $now - $webmincron_last{$cron->{'id'}} > $cron->{'interval'}) {
5348 # Older than interval .. time to run
5351 elsif ($cron->{'mins'}) {
5352 # Check if current time matches spec, and we haven't run in the
5354 my @tm = localtime($now);
5355 if (&matches_cron($cron->{'mins'}, $tm[1]) &&
5356 &matches_cron($cron->{'hours'}, $tm[2]) &&
5357 &matches_cron($cron->{'days'}, $tm[3]) &&
5358 &matches_cron($cron->{'months'}, $tm[4]+1) &&
5359 &matches_cron($cron->{'weekdays'}, $tm[6]) &&
5360 $now - $webmincron_last{$cron->{'id'}} > 60) {
5366 print DEBUG "Running cron id=$cron->{'id'} ".
5367 "module=$cron->{'module'} func=$cron->{'func'}\n";
5368 $webmincron_last{$cron->{'id'}} = $now;
5372 # Run via a wrapper command, which we run like a CGI
5374 # Setup CGI-like environment
5375 $envtz = $ENV{"TZ"};
5376 $envuser = $ENV{"USER"};
5377 $envpath = $ENV{"PATH"};
5378 $envlang = $ENV{"LANG"};
5379 $envroot = $ENV{"SystemRoot"};
5380 $envperllib = $ENV{'PERLLIB'};
5381 foreach my $k (keys %ENV) {
5384 $ENV{"PATH"} = $envpath if ($envpath);
5385 $ENV{"TZ"} = $envtz if ($envtz);
5386 $ENV{"USER"} = $envuser if ($envuser);
5387 $ENV{"OLD_LANG"} = $envlang if ($envlang);
5388 $ENV{"SystemRoot"} = $envroot if ($envroot);
5389 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
5390 $ENV{"HOME"} = $user_homedir;
5391 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
5392 $ENV{"SERVER_ADMIN"} = $config{"email"};
5394 $ENV{"SERVER_ROOT"} = $root0;
5395 $ENV{"SERVER_REALROOT"} = $root0;
5396 $ENV{"SERVER_PORT"} = $config{'port'};
5397 $ENV{"WEBMIN_CRON"} = 1;
5398 $ENV{"DOCUMENT_ROOT"} = $root0;
5399 $ENV{"DOCUMENT_REALROOT"} = $root0;
5400 $ENV{"MINISERV_CONFIG"} = $config_file;
5401 $ENV{"HTTPS"} = "ON" if ($use_ssl);
5402 $ENV{"MINISERV_PID"} = $miniserv_main_pid;
5403 $ENV{"SCRIPT_FILENAME"} = $config{'webmincron_wrapper'};
5404 if ($ENV{"SCRIPT_FILENAME"} =~ /^\Q$root0\E(\/.*)$/) {
5405 $ENV{"SCRIPT_NAME"} = $1;
5407 $config{'webmincron_wrapper'} =~ /^(.*)\//;
5409 foreach $k (keys %config) {
5410 if ($k =~ /^env_(\S+)$/) {
5411 $ENV{$1} = $config{$k};
5415 $SIG{'CHLD'} = 'DEFAULT';
5417 # Have SOCK closed if the perl exec's something
5419 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
5422 # Run the wrapper script by evaling it
5423 $pkg = "webmincron";
5424 $0 = $config{'webmincron_wrapper'};
5426 $main_process_id = $$;
5430 do \$miniserv::config{'webmincron_wrapper'};
5434 print STDERR "Perl cron failure : $@\n";
5439 push(@childpids, $pid);
5443 # Write out file containing last run times
5444 &write_file($config{'webmincron_last'}, \%webmincron_last);
5448 # matches_cron(cron-spec, time)
5449 # Checks if some minute or hour matches some cron spec, which can be * or a list
5453 my ($spec, $tm) = @_;
5458 foreach my $s (split(/,/, $spec)) {
5460 $s =~ /^(\d+)\-(\d+)$/ && $tm >= $1 && $tm <= $2) {
5468 # read_webmin_crons()
5469 # Read all scheduled webmin cron functions and store them in the @webmincrons
5471 sub read_webmin_crons
5474 opendir(CRONS, $config{'webmincron_dir'});
5475 print DEBUG "Reading crons from $config{'webmincron_dir'}\n";
5476 foreach my $f (readdir(CRONS)) {
5477 if ($f =~ /^(\d+)\.cron$/) {
5479 &read_file("$config{'webmincron_dir'}/$f", \%cron);
5482 foreach my $n ('module', 'func') {
5484 print STDERR "Cron $1 missing $n\n";
5488 if (!$cron{'interval'} && !$cron{'mins'} && !$cron{'special'}) {
5489 print STDERR "Cron $1 missing any time spec\n";
5492 if ($cron{'special'} eq 'hourly') {
5493 # Run every hour on the hour
5495 $cron{'hours'} = '*';
5496 $cron{'days'} = '*';
5497 $cron{'months'} = '*';
5498 $cron{'weekdays'} = '*';
5500 elsif ($cron{'special'} eq 'daily') {
5501 # Run every day at midnight
5503 $cron{'hours'} = '0';
5504 $cron{'days'} = '*';
5505 $cron{'months'} = '*';
5506 $cron{'weekdays'} = '*';
5508 elsif ($cron{'special'} eq 'monthly') {
5509 # Run every month on the 1st
5511 $cron{'hours'} = '0';
5512 $cron{'days'} = '1';
5513 $cron{'months'} = '*';
5514 $cron{'weekdays'} = '*';
5516 elsif ($cron{'special'} eq 'weekly') {
5517 # Run every month on the 1st
5519 $cron{'hours'} = '0';
5520 $cron{'days'} = '*';
5521 $cron{'months'} = '*';
5522 $cron{'weekdays'} = '0';
5524 elsif ($cron{'special'} eq 'yearly' ||
5525 $cron{'special'} eq 'annually') {
5526 # Run every year on 1st january
5528 $cron{'hours'} = '0';
5529 $cron{'days'} = '1';
5530 $cron{'months'} = '1';
5531 $cron{'weekdays'} = '*';
5533 elsif ($cron{'special'}) {
5534 print STDERR "Cron $1 invalid special time $cron{'special'}\n";
5537 if ($cron{'special'}) {
5538 delete($cron{'special'});
5541 print DEBUG "adding cron id=$cron{'id'} module=$cron{'module'} func=$cron{'func'}\n";
5542 push(@webmincrons, \%cron);
5548 # Check if some address is valid IPv4, returns 1 if so.
5551 return $_[0] =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/ &&
5552 $1 >= 0 && $1 <= 255 &&
5553 $2 >= 0 && $2 <= 255 &&
5554 $3 >= 0 && $3 <= 255 &&
5555 $4 >= 0 && $4 <= 255;
5558 # Check if some IPv6 address is properly formatted, and returns 1 if so.
5559 sub check_ip6address
5561 my @blocks = split(/:/, $_[0]);
5562 return 0 if (@blocks == 0 || @blocks > 8);
5564 my $where = index($blocks[$ib],"/");
5567 my $b = substr($blocks[$ib],0,$where);
5568 $m = substr($blocks[$ib],$where+1,length($blocks[$ib])-($where+1));
5571 return 0 if ($m <0 || $m >128);
5574 foreach $b (@blocks) {
5575 return 0 if ($b ne "" && $b !~ /^[0-9a-f]{1,4}$/i);
5576 $empty++ if ($b eq "");
5578 return 0 if ($empty > 1 && !($_[0] =~ /^::/ && $empty == 2));
5582 # network_to_address(binary)
5583 # Given a network address in binary IPv4 or v4 format, return the string form
5584 sub network_to_address
5587 if (length($addr) == 4 || !$use_ipv6) {
5588 return inet_ntoa($addr);
5591 return Socket6::inet_ntop(Socket6::AF_INET6(), $addr);