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'};
29 # Check is SSL is enabled and available
31 eval "use Net::SSLeay";
34 # These functions only exist for SSLeay 1.0
35 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
36 eval "Net::SSLeay::load_error_strings()";
37 if ($config{'no_ssl2'}) {
38 eval "Net::SSLeay::CTX_set_options($ctx,&Net::SSLeay::OP_NO_SSLv2)";
40 if (defined(&Net::SSLeay::X509_STORE_CTX_get_current_cert) &&
41 defined(&Net::SSLeay::CTX_load_verify_locations) &&
42 defined(&Net::SSLeay::CTX_set_verify)) {
48 # Check if the syslog module is available to log hacking attempts
49 if ($config{'syslog'} && !$config{'inetd'}) {
50 eval "use Sys::Syslog qw(:DEFAULT setlogsock)";
56 # check if the TCP-wrappers module is available
57 if ($config{'libwrap'}) {
58 eval "use Authen::Libwrap qw(hosts_ctl STRING_UNKNOWN)";
64 # Check if the MD5 perl module is available
70 eval "use Digest::MD5";
72 $use_md5 = "Digest::MD5";
76 # Get miniserv's perl path and location
78 open(SOURCE, $miniserv_path);
79 <SOURCE> =~ /^#!(\S+)/;
86 $linked_perl_path = readlink($perl_path);
88 @miniserv_argv = @ARGV;
90 # Check vital config options
91 &update_vital_config();
93 $sidname = $config{'sidname'};
94 die "Session authentication cannot be used in inetd mode"
95 if ($config{'inetd'} && $config{'session'});
97 # check if the PAM module is available to authenticate
98 if ($config{'assume_pam'}) {
99 # Just assume that it will work. This can also be used to work around
100 # a Solaris bug in which using PAM before forking caused it to fail
104 elsif (!$config{'no_pam'}) {
105 eval "use Authen::PAM;";
107 # check if the PAM authentication can be used by opening a
110 if (ref($pamh = new Authen::PAM($config{'pam'},
111 $config{'pam_test_user'},
113 # Now test a login to see if /etc/pam.d/webmin is set
115 $pam_conv_func_called = 0;
116 $pam_username = "test";
117 $pam_password = "test";
118 $pamh->pam_authenticate();
119 if ($pam_conv_func_called) {
120 $pam_msg = "PAM authentication enabled";
124 $pam_msg = "PAM test failed - maybe /etc/pam.d/$config{'pam'} does not exist";
128 $pam_msg = "PAM initialization of Authen::PAM failed";
132 $pam_msg = "Perl module Authen::PAM needed for PAM is not installed : $@";
135 if ($config{'pam_only'} && !$use_pam) {
136 print STDERR $pam_msg;
137 print STDERR "PAM use is mandatory, but could not be enabled!\n";
140 elsif ($pam_msg && !$use_pam) {
141 $pam_msg2 = "Continuing without the Authen::PAM perl module";
144 # Check if the User::Utmp perl module is installed
145 if ($config{'utmp'}) {
146 eval "use User::Utmp;";
149 $utmp_msg = "UTMP logging enabled";
152 $utmp_msg = "Perl module User::Utmp needed for Utmp logging is not installed : $@";
156 # See if the crypt function fails
157 eval "crypt('foo', 'xx')";
159 eval "use Crypt::UnixCrypt";
162 $crypt_msg = "Using Crypt::UnixCrypt for password encryption\n";
165 $crypt_msg = "crypt() function un-implemented, and Crypt::UnixCrypt not installed - password authentication will probably fail\n";
169 # Check if /dev/urandom really generates random IDs, by calling it twice
170 local $rand1 = &generate_random_id("foo", 1);
171 local $rand2 = &generate_random_id("foo", 2);
173 if ($rand1 eq $rand2) {
175 $rand_msg = "Random number generator file /dev/urandom is not reliable";
178 # Check if we can call sudo
179 if ($config{'sudo'} && &has_command("sudo")) {
185 $sudo_msg = "Perl module IO::Pty needed for calling sudo is not installed : $@";
189 # init days and months for http_date
190 @weekday = ( "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" );
191 @month = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun",
192 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" );
194 # Change dir to the server root
195 @roots = ( $config{'root'} );
196 for($i=0; defined($config{"extraroot_$i"}); $i++) {
197 push(@roots, $config{"extraroot_$i"});
200 eval { $user_homedir = (getpwuid($<))[7]; };
202 # getpwuid doesn't work on windows
203 $user_homedir = $ENV{"HOME"} || $ENV{"USERPROFILE"} || "/";
210 # Setup SSL if possible and if requested
211 if (!-r $config{'keyfile'} ||
212 $config{'certfile'} && !-r $config{'certfile'}) {
213 # Key file doesn't exist!
216 @ipkeys = &get_ipkeys(\%config);
218 if ($config{'ssl_version'}) {
219 # Force an SSL version
220 $Net::SSLeay::version = $config{'ssl_version'};
221 $Net::SSLeay::ssl_version = $config{'ssl_version'};
223 $client_certs = 0 if (!-r $config{'ca'} || !%certs);
224 $ssl_contexts{"*"} = &create_ssl_context($config{'keyfile'},
225 $config{'certfile'});
226 foreach $ipkey (@ipkeys) {
227 $ctx = &create_ssl_context($ipkey->{'key'}, $ipkey->{'cert'});
228 foreach $ip (@{$ipkey->{'ips'}}) {
229 $ssl_contexts{$ip} = $ctx;
234 # Setup syslog support if possible and if requested
236 open(ERRDUP, ">&STDERR");
237 open(STDERR, ">/dev/null");
238 $log_socket = $config{"logsock"} || "unix";
239 eval 'openlog($config{"pam"}, "cons,pid,ndelay", "authpriv"); setlogsock($log_socket)';
244 local $msg = ucfirst($config{'pam'})." starting";
245 eval { syslog("info", "%s", $msg); };
249 syslog("info", "%s", $msg);
252 # All attempts to use syslog have failed..
257 open(STDERR, ">&ERRDUP");
261 # Read MIME types file and add extra types
265 if ($config{'log'}) {
266 local(@gmt, @lct, $days, $hours, $mins);
267 @gmt = gmtime(time());
268 @lct = localtime(time());
269 $days = $lct[3] - $gmt[3];
270 $hours = ($days < -1 ? 24 : 1 < $days ? -24 : $days * 24) +
272 $mins = $hours * 60 + $lct[1] - $gmt[1];
273 $timezone = ($mins < 0 ? "-" : "+"); $mins = abs($mins);
274 $timezone .= sprintf "%2.2d%2.2d", $mins/60, $mins%60;
277 # Build various maps from the config files
278 &build_config_mappings();
280 # start up external authentication program, if needed
281 if ($config{'extauth'}) {
282 socketpair(EXTAUTH, EXTAUTH2, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
283 if (!($extauth = fork())) {
287 open(STDIN, "<&EXTAUTH2");
288 open(STDOUT, ">&EXTAUTH2");
289 exec($config{'extauth'}) or die "exec failed : $!\n";
292 local $os = select(EXTAUTH);
296 # Pre-load any libraries
297 if (!$config{'inetd'}) {
298 foreach $pl (split(/\s+/, $config{'preload'})) {
299 ($pkg, $lib) = split(/=/, $pl);
300 $pkg =~ s/[^A-Za-z0-9]/_/g;
301 eval "package $pkg; do '$config{'root'}/$lib'";
303 print STDERR "Failed to pre-load $lib in $pkg : $@\n";
306 print STDERR "Pre-loaded $lib in $pkg\n";
309 foreach $pl (split(/\s+/, $config{'premodules'})) {
311 ($dir, $mod) = split(/\//, $pl);
314 ($dir, $mod) = (undef, $pl);
316 push(@INC, "$config{'root'}/$dir");
317 eval "package $mod; use $mod ()";
319 print STDERR "Failed to pre-load $mod : $@\n";
322 print STDERR "Pre-loaded $mod\n";
327 # Open debug log if set
328 if ($config{'debuglog'}) {
329 open(DEBUG, ">>$config{'debuglog'}");
330 chmod(0700, $config{'debuglog'});
331 select(DEBUG); $| = 1; select(STDOUT);
332 print DEBUG "miniserv.pl starting ..\n";
335 # Write out (empty) blocked hosts file
336 &write_blocked_file();
338 # Initially read webmin cron functions and last execution times
339 &read_webmin_crons();
340 %webmincron_last = ( );
341 &read_file($config{'webmincron_last'}, \%webmincron_last);
343 # Re-direct STDERR to a log file
344 if ($config{'errorlog'} ne '-') {
345 open(STDERR, ">>$config{'errorlog'}") || die "failed to open $config{'errorlog'} : $!";
346 if ($config{'logperms'}) {
347 chmod(oct($config{'logperms'}), $config{'errorlog'});
350 select(STDERR); $| = 1; select(STDOUT);
352 if ($config{'inetd'}) {
353 # We are being run from inetd - go direct to handling the request
354 $SIG{'HUP'} = 'IGNORE';
355 $SIG{'TERM'} = 'DEFAULT';
356 $SIG{'PIPE'} = 'DEFAULT';
357 open(SOCK, "+>&STDIN");
359 # Check if it is time for the logfile to be cleared
360 if ($config{'logclear'}) {
361 local $write_logtime = 0;
362 local @st = stat("$config{'logfile'}.time");
364 if ($st[9]+$config{'logtime'}*60*60 < time()){
367 unlink($config{'logfile'});
370 else { $write_logtime = 1; }
371 if ($write_logtime) {
372 open(LOGTIME, ">$config{'logfile'}.time");
373 print LOGTIME time(),"\n";
378 # Initialize SSL for this connection
380 $ssl_con = &ssl_connection_for_ip(SOCK);
384 # Work out the hostname for this web server
385 $host = &get_socket_name(SOCK);
387 $port = $config{'port'};
388 $acptaddr = getpeername(SOCK);
391 print DEBUG "main: Starting handle_request loop pid=$$\n";
392 while(&handle_request($acptaddr, getsockname(SOCK))) { }
393 print DEBUG "main: Done handle_request loop pid=$$\n";
398 # Build list of sockets to listen on
399 if ($config{"bind"} && $config{"bind"} ne "*") {
400 push(@sockets, [ inet_aton($config{'bind'}), $config{'port'} ]);
403 push(@sockets, [ INADDR_ANY, $config{'port'} ]);
405 foreach $s (split(/\s+/, $config{'sockets'})) {
406 if ($s =~ /^(\d+)$/) {
407 # Just listen on another port on the main IP
408 push(@sockets, [ $sockets[0]->[0], $s ]);
410 elsif ($s =~ /^(\S+):(\d+)$/) {
411 # Listen on a specific port and IP
412 push(@sockets, [ $1 eq "*" ? INADDR_ANY : inet_aton($1), $2 ]);
414 elsif ($s =~ /^([0-9\.]+):\*$/ || $s =~ /^([0-9\.]+)$/) {
415 # Listen on the main port on another IP
416 push(@sockets, [ inet_aton($1), $sockets[0]->[1] ]);
420 # Open all the sockets
421 $proto = getprotobyname('tcp');
423 $tried_inaddr_any = 0;
424 for($i=0; $i<@sockets; $i++) {
426 socket($fh, PF_INET, SOCK_STREAM, $proto) ||
427 die "Failed to open socket : $!";
428 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
429 for($j=0; $j<5; $j++) {
430 last if (bind($fh, pack_sockaddr_in($sockets[$i]->[1],
431 $sockets[$i]->[0])));
435 # All attempts failed .. give up
436 if ($sockets[$i]->[0] eq INADDR_ANY) {
437 push(@sockerrs, "Failed to bind to port $sockets[$i]->[1] : $!");
438 $tried_inaddr_any = 1;
441 $ip = inet_ntoa($sockets[$i]->[0]);
442 push(@sockerrs, "Failed to bind to IP $ip port $sockets[$i]->[1] : $!");
446 listen($fh, SOMAXCONN);
447 push(@socketfhs, $fh);
450 foreach $se (@sockerrs) {
451 print STDERR $se,"\n";
454 # If all binds failed, try binding to any address
455 if (!@socketfhs && !$tried_inaddr_any) {
456 print STDERR "Falling back to listening on any address\n";
458 socket($fh, PF_INET, SOCK_STREAM, $proto) ||
459 die "Failed to open socket : $!";
460 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
461 bind($fh, pack_sockaddr_in($sockets[0]->[1], INADDR_ANY)) ||
462 die "Failed to bind to port $sockets[0]->[1] : $!";
463 listen($fh, SOMAXCONN);
464 push(@socketfhs, $fh);
466 elsif (!@socketfhs && $tried_inaddr_any) {
467 die "Could not listen on any ports";
470 if ($config{'listen'}) {
471 # Open the socket that allows other webmin servers to find this one
472 $proto = getprotobyname('udp');
473 if (socket(LISTEN, PF_INET, SOCK_DGRAM, $proto)) {
474 setsockopt(LISTEN, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
475 bind(LISTEN, pack_sockaddr_in($config{'listen'}, INADDR_ANY));
476 listen(LISTEN, SOMAXCONN);
479 $config{'listen'} = 0;
483 # Split from the controlling terminal, unless configured not to
484 if (!$config{'nofork'}) {
485 if (fork()) { exit; }
487 eval { setsid(); }; # may not work on Windows
489 # Close standard file handles
490 open(STDIN, "</dev/null");
491 open(STDOUT, ">/dev/null");
492 &log_error("miniserv.pl started");
493 &log_error($pam_msg) if ($pam_msg);
494 &log_error($pam_msg2) if ($pam_msg2);
495 &log_error($utmp_msg) if ($utmp_msg);
496 &log_error($crypt_msg) if ($crypt_msg);
497 &log_error($sudo_msg) if ($sudo_msg);
498 &log_error($rand_msg) if ($rand_msg);
500 # write out the PID file
503 # Start the log-clearing process, if needed. This checks every minute
504 # to see if the log has passed its reset time, and if so clears it
505 if ($config{'logclear'}) {
506 if (!($logclearer = fork())) {
507 &close_all_sockets();
510 local $write_logtime = 0;
511 local @st = stat("$config{'logfile'}.time");
513 if ($st[9]+$config{'logtime'}*60*60 < time()){
516 unlink($config{'logfile'});
519 else { $write_logtime = 1; }
520 if ($write_logtime) {
521 open(LOGTIME, ">$config{'logfile'}.time");
522 print LOGTIME time(),"\n";
529 push(@childpids, $logclearer);
532 # Setup the logout time dbm if needed
533 if ($config{'session'}) {
534 eval "use SDBM_File";
535 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
536 eval "\$sessiondb{'1111111111'} = 'foo bar';";
538 dbmclose(%sessiondb);
539 eval "use NDBM_File";
540 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
543 delete($sessiondb{'1111111111'});
548 $SIG{'HUP'} = 'miniserv::trigger_restart';
549 $SIG{'TERM'} = 'miniserv::term_handler';
550 $SIG{'USR1'} = 'miniserv::trigger_reload';
551 $SIG{'PIPE'} = 'IGNORE';
552 local $remove_session_count = 0;
553 $need_pipes = $config{'passdelay'} || $config{'session'};
555 # wait for a new connection, or a message from a child process
557 if (@childpids <= $config{'maxconns'}) {
558 # Only accept new main socket connects when ready
560 foreach $s (@socketfhs) {
561 vec($rmask, fileno($s), 1) = 1;
565 printf STDERR "too many children (%d > %d)\n",
566 scalar(@childpids), $config{'maxconns'};
569 for($i=0; $i<@passin; $i++) {
570 vec($rmask, fileno($passin[$i]), 1) = 1;
573 vec($rmask, fileno(LISTEN), 1) = 1 if ($config{'listen'});
575 # Wait for a connection
576 local $sel = select($rmask, undef, undef, 10);
578 # Check the flag files
579 if ($config{'restartflag'} && -r $config{'restartflag'}) {
580 print STDERR "restart flag file detected\n";
581 unlink($config{'restartflag'});
584 if ($config{'reloadflag'} && -r $config{'reloadflag'}) {
585 unlink($config{'reloadflag'});
590 # Got a HUP signal while in select() .. restart now
594 # Got a USR1 signal while in select() .. re-read config
596 &reload_config_file();
598 local $time_now = time();
600 # Clean up finished processes
602 do { $pid = waitpid(-1, WNOHANG);
603 @childpids = grep { $_ != $pid } @childpids;
604 } while($pid != 0 && $pid != -1);
606 # run the unblocking procedure to check if enough time has passed to
607 # unblock hosts that heve been blocked because of password failures
609 if ($config{'blockhost_failures'}) {
611 while ($i <= $#deny) {
612 if ($blockhosttime{$deny[$i]} &&
613 $config{'blockhost_time'} != 0 &&
614 ($time_now - $blockhosttime{$deny[$i]}) >=
615 $config{'blockhost_time'}) {
616 # the host can be unblocked now
617 $hostfail{$deny[$i]} = 0;
618 splice(@deny, $i, 1);
625 # Do the same for blocked users
626 if ($config{'blockuser_failures'}) {
628 while ($i <= $#deny) {
629 if ($blockusertime{$deny[$i]} &&
630 $config{'blockuser_time'} != 0 &&
631 ($time_now - $blockusertime{$deny[$i]}) >=
632 $config{'blockuser_time'}) {
633 # the user can be unblocked now
634 $userfail{$deny[$i]} = 0;
635 splice(@denyusers, $i, 1);
642 &write_blocked_file();
645 # Check if any webmin cron jobs are ready to run
646 &execute_ready_webmin_crons();
648 if ($config{'session'} && (++$remove_session_count%50) == 0) {
649 # Remove sessions with more than 7 days of inactivity,
651 foreach $s (keys %sessiondb) {
652 local ($user, $ltime, $lip) =
653 split(/\s+/, $sessiondb{$s});
654 if ($time_now - $ltime > 7*24*60*60) {
655 &run_logout_script($s, $user);
656 &write_logout_utmp($user, $lip);
657 delete($sessiondb{$s});
660 "Timeout of session for $user");
666 if ($use_pam && $config{'pam_conv'}) {
667 # Remove PAM sessions with more than 5 minutes of inactivity
669 foreach $c (values %conversations) {
670 if ($time_now - $c->{'time'} > 5*60) {
671 &end_pam_conversation($c);
673 syslog("info", "%s", "Timeout of PAM ".
674 "session for $c->{'user'}");
680 # Don't check any sockets if there is no activity
683 # Check if any of the main sockets have received a new connection
685 foreach $s (@socketfhs) {
686 if (vec($rmask, fileno($s), 1)) {
688 $acptaddr = accept(SOCK, $s);
689 if (!$acptaddr) { next; }
690 binmode(SOCK); # turn off any Perl IO stuff
693 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
695 ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw) =
699 # Check username of connecting user
700 local ($peerp, $peera) = unpack_sockaddr_in($acptaddr);
701 $localauth_user = undef;
702 if ($config{'localauth'} && inet_ntoa($peera) eq "127.0.0.1") {
703 if (open(TCP, "/proc/net/tcp")) {
704 # Get the info direct from the kernel
707 local @t = split(/[\s:]+/, $_);
708 if ($t[1] eq '0100007F' &&
709 $t[2] eq sprintf("%4.4X", $peerp)) {
710 $localauth_user = getpwuid($t[11]);
716 if (!$localauth_user) {
717 # Call lsof for the info
718 local $lsofpid = open(LSOF,
719 "$config{'localauth'} -i TCP\@127.0.0.1:$peerp |");
721 if (/^(\S+)\s+(\d+)\s+(\S+)/ &&
722 $2 != $$ && $2 != $lsofpid) {
723 $localauth_user = $3;
730 # Work out the hostname for this web server
731 $host = &get_socket_name(SOCK);
733 print STDERR "Failed to get local socket name : $!\n";
737 $port = $sockets[$sn]->[1];
739 # fork the subprocess
741 if (!($handpid = fork())) {
742 # setup signal handlers
743 $SIG{'TERM'} = 'DEFAULT';
744 $SIG{'PIPE'} = 'DEFAULT';
745 #$SIG{'CHLD'} = 'IGNORE';
746 $SIG{'HUP'} = 'IGNORE';
747 $SIG{'USR1'} = 'IGNORE';
749 # Initialize SSL for this connection
751 $ssl_con = &ssl_connection_for_ip(SOCK);
755 # Close the file handle for the session DBM
756 dbmclose(%sessiondb);
758 # close useless pipes
761 close($PASSINr); close($PASSOUTw);
763 &close_all_sockets();
767 "main: Starting handle_request loop pid=$$\n";
768 while(&handle_request($acptaddr,
769 getsockname(SOCK))) { }
771 "main: Done handle_request loop pid=$$\n";
774 close($PASSINw); close($PASSOUTw);
777 push(@childpids, $handpid);
779 close($PASSINw); close($PASSOUTr);
780 push(@passin, $PASSINr);
781 push(@passout, $PASSOUTw);
788 if ($config{'listen'} && vec($rmask, fileno(LISTEN), 1)) {
789 # Got UDP packet from another webmin server
791 local $from = recv(LISTEN, $rcvbuf, 1024, 0);
793 local $fromip = inet_ntoa((unpack_sockaddr_in($from))[1]);
794 local $toip = inet_ntoa((unpack_sockaddr_in(
795 getsockname(LISTEN)))[1]);
796 if ((!@deny || !&ip_match($fromip, $toip, @deny)) &&
797 (!@allow || &ip_match($fromip, $toip, @allow))) {
798 local $listenhost = &get_socket_name(LISTEN);
799 send(LISTEN, "$listenhost:$config{'port'}:".
800 ($use_ssl || $config{'inetd_ssl'} ? 1 : 0).":".
801 ($config{'listenhost'} ?
802 &get_system_hostname() : ""),
808 # check for session, password-timeout and PAM messages from subprocesses
809 for($i=0; $i<@passin; $i++) {
810 if (vec($rmask, fileno($passin[$i]), 1)) {
811 # this sub-process is asking about a password
812 local $infd = $passin[$i];
813 local $outfd = $passout[$i];
814 #local $inline = <$infd>;
815 local $inline = &sysread_line($infd);
817 print DEBUG "main: inline $inline";
820 print DEBUG "main: inline EOF\n";
822 if ($inline =~ /^delay\s+(\S+)\s+(\S+)\s+(\d+)/) {
823 # Got a delay request from a subprocess.. for
824 # valid logins, there is no delay (to prevent
825 # denial of service attacks), but for invalid
826 # logins the delay increases with each failed
829 # login OK.. no delay
830 print $outfd "0 0\n";
831 $wasblocked = $hostfail{$2} ||
836 &write_blocked_file();
845 # add the host to the block list,
847 if ($config{'blockhost_failures'} &&
849 $config{'blockhost_failures'}) {
851 $blockhosttime{$2} = $time_now;
854 local $logtext = "Security alert: Host $2 blocked after $config{'blockhost_failures'} failed logins for user $1";
860 # add the user to the user block list,
862 if ($config{'blockuser_failures'} &&
864 $config{'blockuser_failures'}) {
865 push(@denyusers, $1);
866 $blockusertime{$1} = $time_now;
869 local $logtext = "Security alert: User $1 blocked after $config{'blockuser_failures'} failed logins";
875 # Lock out the user's password, if enabled
876 if ($config{'blocklock'} &&
878 $config{'blockuser_failures'}) {
879 my $lk = &lock_user_password($1);
882 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";
889 $dl = $userdlay{$1} -
890 int(($time_now - $userlast{$1})/50);
891 $dl = $dl < 0 ? 0 : $dl+1;
892 print $outfd "$dl $blocked\n";
895 # Write out blocked status file
897 &write_blocked_file();
900 $userlast{$1} = $time_now;
902 elsif ($inline =~ /^verify\s+(\S+)\s+(\S+)/) {
903 # Verifying a session ID
904 local $session_id = $1;
905 local $notimeout = $2;
906 local $skey = $sessiondb{$session_id} ?
908 &hash_session_id($session_id);
909 if (!defined($sessiondb{$skey})) {
910 # Session doesn't exist
911 print $outfd "0 0\n";
914 local ($user, $ltime) =
915 split(/\s+/, $sessiondb{$skey});
916 local $lot = &get_logout_time($user, $session_id);
918 $time_now - $ltime > $lot*60 &&
920 # Session has timed out
921 print $outfd "1 ",$time_now - $ltime,"\n";
922 #delete($sessiondb{$skey});
926 print $outfd "2 $user\n";
930 $sessiondb{$skey} = "$user $time_now";
935 elsif ($inline =~ /^new\s+(\S+)\s+(\S+)\s+(\S+)/) {
936 # Creating a new session
937 local $session_id = $1;
940 $sessiondb{&hash_session_id($session_id)} =
941 "$user $time_now $ip";
943 elsif ($inline =~ /^delete\s+(\S+)/) {
944 # Logging out a session
945 local $session_id = $1;
946 local $skey = $sessiondb{$session_id} ?
948 &hash_session_id($session_id);
949 local @sdb = split(/\s+/, $sessiondb{$skey});
950 print $outfd $sdb[0],"\n";
951 delete($sessiondb{$skey});
953 elsif ($inline =~ /^pamstart\s+(\S+)\s+(\S+)\s+(.*)/) {
954 # Starting a new PAM conversation
955 local ($cid, $host, $user) = ($1, $2, $3);
957 # Does this user even need PAM?
958 local ($realuser, $canlogin) =
959 &can_user_login($user, undef, $host);
961 if ($canlogin == 0) {
963 print $outfd "0 Invalid username\n";
965 elsif ($canlogin != 2) {
966 # Not using PAM .. so just ask for
968 $conv = { 'user' => $realuser,
973 print $outfd "3 Password\n";
976 # Start the PAM conversation
977 # sub-process, and get a question
978 $conv = { 'user' => $realuser,
982 local ($PAMINr, $PAMINw, $PAMOUTr,
983 $PAMOUTw) = &allocate_pipes();
984 local $pampid = fork();
986 close($PAMOUTr); close($PAMINw);
987 &pam_conversation_process(
991 close($PAMOUTw); close($PAMINr);
992 $conv->{'pid'} = $pampid;
993 $conv->{'PAMOUTr'} = $PAMOUTr;
994 $conv->{'PAMINw'} = $PAMINw;
995 push(@childpids, $pampid);
997 # Get the first PAM question
998 local $pok = &recv_pam_question(
1001 &end_pam_conversation($conv);
1005 $conversations{$cid} = $conv if ($conv);
1007 elsif ($inline =~ /^pamanswer\s+(\S+)\s+(.*)/) {
1008 # A response to a PAM question
1009 local ($cid, $answer) = ($1, $2);
1010 local $conv = $conversations{$cid};
1012 # No such conversation?
1013 print $outfd "0 Bad login session\n";
1015 elsif ($conv->{'pid'}) {
1016 # Send the PAM response and get
1018 &send_pam_answer($conv, $answer);
1019 local $pok = &recv_pam_question($conv, $outfd);
1021 &end_pam_conversation($conv);
1025 # This must be the password .. try it
1026 # and send back the results
1027 local ($vu, $expired, $nonexist) =
1028 &validate_user($conv->{'user'},
1031 local $ok = $vu ? 1 : 0;
1032 print $outfd "2 $conv->{'user'} $ok $expired $notexist\n";
1033 &end_pam_conversation($conv);
1036 elsif ($inline =~ /^writesudo\s+(\S+)\s+(\d+)/) {
1037 # Store the fact that some user can sudo to root
1038 local ($user, $ok) = ($1, $2);
1039 $sudocache{$user} = $ok." ".time();
1041 elsif ($inline =~ /^readsudo\s+(\S+)/) {
1042 # Query the user sudo cache (valid for 1 minute)
1044 local ($ok, $last) =
1045 split(/\s+/, $sudocache{$user});
1046 if ($last < time()-60) {
1051 # Tell client OK or not
1052 print $outfd "$ok\n";
1055 elsif ($inline =~ /\S/) {
1056 # Unknown line from pipe?
1057 print DEBUG "main: Unknown line from pipe $inline\n";
1058 print STDERR "Unknown line from pipe $inline\n";
1062 close($infd); close($outfd);
1063 $passin[$i] = $passout[$i] = undef;
1067 @passin = grep { defined($_) } @passin;
1068 @passout = grep { defined($_) } @passout;
1071 # handle_request(remoteaddress, localaddress)
1072 # Where the real work is done
1075 $acptip = inet_ntoa((unpack_sockaddr_in($_[0]))[1]);
1076 $localip = $_[1] ? inet_ntoa((unpack_sockaddr_in($_[1]))[1]) : undef;
1077 print DEBUG "handle_request: from $acptip to $localip\n";
1078 if ($config{'loghost'}) {
1079 $acpthost = gethostbyaddr(inet_aton($acptip), AF_INET);
1080 $acpthost = $acptip if (!$acpthost);
1083 $acpthost = $acptip;
1085 $datestr = &http_date(time());
1087 $ok_message = "Document follows";
1088 $logged_code = undef;
1089 $reqline = $request_uri = $page = undef;
1093 # check address against access list
1094 if (@deny && &ip_match($acptip, $localip, @deny) ||
1095 @allow && !&ip_match($acptip, $localip, @allow)) {
1096 &http_error(403, "Access denied for $acptip");
1101 # Check address with TCP-wrappers
1102 if (!hosts_ctl($config{'pam'}, STRING_UNKNOWN,
1103 $acptip, STRING_UNKNOWN)) {
1104 &http_error(403, "Access denied for $acptip by TCP wrappers");
1108 print DEBUG "handle_request: passed IP checks\n";
1110 # Compute a timeout for the start of headers, based on the number of
1111 # child processes. As this increases, we use a shorter timeout to avoid
1112 # an attacker overloading the system.
1113 local $header_timeout = 60 + ($config{'maxconns'} - @childpids) * 10;
1115 # Wait at most 60 secs for start of headers for initial requests, or
1116 # 10 minutes for kept-alive connections
1118 vec($rmask, fileno(SOCK), 1) = 1;
1119 local $to = $checked_timeout ? 10*60 : $header_timeout;
1120 local $sel = select($rmask, undef, undef, $to);
1122 if ($checked_timeout) {
1123 print DEBUG "handle_request: exiting due to timeout of $to\n";
1127 &http_error(400, "Timeout",
1128 "Waited for that $to seconds for start of headers");
1132 print DEBUG "handle_request: passed timeout check\n";
1134 # Read the HTTP request and headers
1135 local $origreqline = &read_line();
1136 ($reqline = $origreqline) =~ s/\r|\n//g;
1137 $method = $page = $request_uri = undef;
1138 print DEBUG "handle_request reqline=$reqline\n";
1139 if (!$reqline && (!$use_ssl || $checked_timeout > 1)) {
1140 # An empty request .. just close the connection
1141 print DEBUG "handle_request: rejecting empty request\n";
1144 elsif ($reqline !~ /^(\S+)\s+(.*)\s+HTTP\/1\..$/) {
1145 print DEBUG "handle_request: invalid reqline=$reqline\n";
1147 # This could be an http request when it should be https
1149 local $url = $config{'musthost'} ?
1150 "https://$config{'musthost'}:$port/" :
1151 "https://$host:$port/";
1152 if ($config{'ssl_redirect'}) {
1153 # Just re-direct to the correct URL
1154 sleep(1); # Give browser a change to finish
1155 # sending its request
1156 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1157 &write_data("Date: $datestr\r\n");
1158 &write_data("Server: $config{'server'}\r\n");
1159 &write_data("Location: $url\r\n");
1160 &write_keep_alive(0);
1161 &write_data("\r\n");
1165 # Tell user the correct URL
1166 &http_error(200, "Bad Request", "This web server is running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1169 elsif (ord(substr($reqline, 0, 1)) == 128 && !$use_ssl) {
1170 # This could be an https request when it should be http ..
1171 # need to fake a HTTP response
1174 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
1175 eval "Net::SSLeay::load_error_strings()";
1176 $ssl_ctx = Net::SSLeay::CTX_new();
1177 Net::SSLeay::CTX_use_RSAPrivateKey_file(
1178 $ssl_ctx, $config{'keyfile'},
1179 &Net::SSLeay::FILETYPE_PEM);
1180 Net::SSLeay::CTX_use_certificate_file(
1182 $config{'certfile'} || $config{'keyfile'},
1183 &Net::SSLeay::FILETYPE_PEM);
1184 $ssl_con = Net::SSLeay::new($ssl_ctx);
1188 select(SSLw); $| = 1; select(STDOUT);
1189 print SSLw $origreqline;
1191 while(sysread(SOCK, $buf, 1) > 0) {
1198 Net::SSLeay::set_wfd($ssl_con, fileno(SOCK));
1199 Net::SSLeay::set_rfd($ssl_con, fileno(SSLr));
1200 Net::SSLeay::accept($ssl_con) || die "accept() failed";
1202 local $url = $config{'musthost'} ?
1203 "https://$config{'musthost'}:$port/" :
1204 "https://$host:$port/";
1205 if ($config{'ssl_redirect'}) {
1206 # Just re-direct to the correct URL
1207 sleep(1); # Give browser a change to
1208 # finish sending its request
1209 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1210 &write_data("Date: $datestr\r\n");
1211 &write_data("Server: $config{'server'}\r\n");
1212 &write_data("Location: $url\r\n");
1213 &write_keep_alive(0);
1214 &write_data("\r\n");
1218 # Tell user the correct URL
1219 &http_error(200, "Bad Request", "This web server is not running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1223 &http_error(400, "Bad Request");
1227 &http_error(400, "Bad Request");
1231 $request_uri = $page = $2;
1235 ($headline = &read_line()) =~ s/\r|\n//g;
1236 last if ($headline eq "");
1237 print DEBUG "handle_request: got headline $headline\n";
1238 if ($headline =~ /^(\S+):\s*(.*)$/) {
1239 $header{$lastheader = lc($1)} = $2;
1241 elsif ($headline =~ /^\s+(.*)$/) {
1242 $header{$lastheader} .= $headline;
1245 &http_error(400, "Bad Header $headline");
1248 if (defined($header{'host'})) {
1249 if ($header{'host'} =~ /^([^:]+):([0-9]+)$/) {
1250 ($host, $port) = ($1, $2);
1253 $host = $header{'host'};
1255 if ($config{'musthost'} && $host ne $config{'musthost'}) {
1256 # Disallowed hostname used
1257 &http_error(400, "Invalid HTTP hostname");
1261 if ($page =~ /^([^\?]+)\?(.*)$/) {
1262 # There is some query string information
1265 print DEBUG "handle_request: querystring=$querystring\n";
1266 if ($querystring !~ /=/) {
1267 $queryargs = $querystring;
1268 $queryargs =~ s/\+/ /g;
1269 $queryargs =~ s/%(..)/pack("c",hex($1))/ge;
1273 # Parse query-string parameters
1274 local @in = split(/\&/, $querystring);
1276 local ($k, $v) = split(/=/, $i, 2);
1277 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1278 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1283 $posted_data = undef;
1284 if ($method eq 'POST' &&
1285 $header{'content-type'} eq 'application/x-www-form-urlencoded') {
1286 # Read in posted query string information, up the configured maximum
1287 # post request length
1288 $clen = $header{"content-length"};
1289 $clen_read = $clen > $config{'max_post'} ? $config{'max_post'} : $clen;
1290 while(length($posted_data) < $clen_read) {
1291 $buf = &read_data($clen_read - length($posted_data));
1292 if (!length($buf)) {
1293 &http_error(500, "Failed to read POST request");
1295 chomp($posted_data);
1296 $posted_data =~ s/\015$//mg;
1297 $posted_data .= $buf;
1299 print DEBUG "clen_read=$clen_read clen=$clen posted_data=",length($posted_data),"\n";
1300 if ($clen_read != $clen && length($posted_data) > $clen) {
1301 # If the client sent more data than we asked for, chop the
1303 $posted_data = substr($posted_data, 0, $clen);
1305 if (length($posted_data) > $clen) {
1306 # When the client sent too much, delay so that it gets headers
1309 if ($header{'user-agent'} =~ /MSIE/ &&
1310 $header{'user-agent'} !~ /Opera/i) {
1311 # MSIE includes an extra newline in the data
1312 $posted_data =~ s/\r|\n//g;
1314 local @in = split(/\&/, $posted_data);
1316 local ($k, $v) = split(/=/, $i, 2);
1318 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1319 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1322 print DEBUG "handle_request: posted_data=$posted_data\n";
1325 # replace %XX sequences in page
1326 $page =~ s/%(..)/pack("c",hex($1))/ge;
1328 # Check if the browser's user agent indicates a mobile device
1329 $mobile_device = &is_mobile_useragent($header{'user-agent'});
1331 # Check if Host: header is for a mobile URL
1332 foreach my $m (@mobile_prefixes) {
1333 if ($header{'host'} =~ /^\Q$m\E/i) {
1338 # check for the logout flag file, and if existant deny authentication
1339 if ($config{'logout'} && -r $config{'logout'}.$in{'miniserv_logout_id'}) {
1340 print DEBUG "handle_request: logout flag set\n";
1341 $deny_authentication++;
1342 open(LOGOUT, $config{'logout'}.$in{'miniserv_logout_id'});
1343 chop($count = <LOGOUT>);
1347 open(LOGOUT, ">$config{'logout'}$in{'miniserv_logout_id'}");
1348 print LOGOUT "$count\n";
1352 unlink($config{'logout'}.$in{'miniserv_logout_id'});
1356 # check for any redirect for the requested URL
1357 foreach my $pfx (@strip_prefix) {
1358 my $l = length($pfx);
1359 if(length($page) >= $l &&
1360 substr($page,0,$l) eq $pfx) {
1361 $page=substr($page,$l);
1365 $simple = &simplify_path($page, $bogus);
1367 $rpath .= "&".$querystring if (defined($querystring));
1368 $redir = $redirect{$rpath};
1369 if (defined($redir)) {
1370 print DEBUG "handle_request: redir=$redir\n";
1371 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1372 &write_data("Date: $datestr\r\n");
1373 &write_data("Server: $config{'server'}\r\n");
1374 local $ssl = $use_ssl || $config{'inetd_ssl'};
1375 $portstr = $port == 80 && !$ssl ? "" :
1376 $port == 443 && $ssl ? "" : ":$port";
1377 $prot = $ssl ? "https" : "http";
1378 &write_data("Location: $prot://$host$portstr$redir\r\n");
1379 &write_keep_alive(0);
1380 &write_data("\r\n");
1384 # Check for a DAV request
1386 foreach my $d (@davpaths) {
1387 if ($simple eq $d || $simple =~ /^\Q$d\E\//) {
1392 if (!$davpath && ($method eq "SEARCH" || $method eq "PUT")) {
1393 &http_error(400, "Bad Request method $method");
1396 # Check for password if needed
1397 if ($config{'userfile'}) {
1398 print DEBUG "handle_request: Need authentication\n";
1402 # Session authentication is never used for connections by
1403 # another webmin server, or for specified pages, or for DAV, or XMLRPC,
1404 # or mobile browsers if requested.
1405 if ($header{'user-agent'} =~ /webmin/i ||
1406 $header{'user-agent'} =~ /$config{'agents_nosession'}/i ||
1407 $sessiononly{$simple} || $davpath ||
1408 $simple eq "/xmlrpc.cgi" ||
1409 $acptip eq $config{'host_nosession'} ||
1410 $mobile_device && $config{'mobile_nosession'}) {
1411 print DEBUG "handle_request: Forcing HTTP authentication\n";
1412 $config{'session'} = 0;
1415 # Check for SSL authentication
1416 if ($use_ssl && $verified_client) {
1417 $peername = Net::SSLeay::X509_NAME_oneline(
1418 Net::SSLeay::X509_get_subject_name(
1419 Net::SSLeay::get_peer_certificate(
1421 $u = &find_user_by_cert($peername);
1426 if ($use_syslog && !$validated) {
1427 syslog("crit", "%s",
1428 "Unknown SSL certificate $peername");
1432 if (!$validated && !$deny_authentication) {
1433 # check for IP-based authentication
1435 foreach $a (keys %ipaccess) {
1436 if ($acptip eq $a) {
1437 # It does! Auth as the user
1439 $baseauthuser = $authuser =
1445 # Check for normal HTTP authentication
1446 if (!$validated && !$deny_authentication && !$config{'session'} &&
1447 $header{authorization} =~ /^basic\s+(\S+)$/i) {
1448 # authorization given..
1449 ($authuser, $authpass) = split(/:/, &b64decode($1), 2);
1450 print DEBUG "handle_request: doing basic auth check authuser=$authuser authpass=$authpass\n";
1451 local ($vu, $expired, $nonexist) =
1452 &validate_user($authuser, $authpass, $host);
1453 print DEBUG "handle_request: vu=$vu expired=$expired nonexist=$nonexist\n";
1454 if ($vu && (!$expired || $config{'passwd_mode'} == 1)) {
1461 if ($use_syslog && !$validated) {
1462 syslog("crit", "%s",
1463 ($nonexist ? "Non-existent" :
1464 $expired ? "Expired" : "Invalid").
1465 " login as $authuser from $acpthost");
1467 if ($authuser =~ /\r|\n|\s/) {
1468 &http_error(500, "Invalid username",
1469 "Username contains invalid characters");
1471 if ($authpass =~ /\r|\n/) {
1472 &http_error(500, "Invalid password",
1473 "Password contains invalid characters");
1476 if ($config{'passdelay'} && !$config{'inetd'} && $authuser) {
1477 # check with main process for delay
1478 print DEBUG "handle_request: about to ask for password delay\n";
1479 print $PASSINw "delay $authuser $acptip $validated\n";
1480 <$PASSOUTr> =~ /(\d+) (\d+)/;
1482 print DEBUG "handle_request: password delay $1 $2\n";
1487 # Check for a visit to the special session login page
1488 if ($config{'session'} && !$deny_authentication &&
1489 $page eq $config{'session_login'}) {
1490 if ($in{'logout'} && $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1491 # Logout clicked .. remove the session
1493 print $PASSINw "delete $sid\n";
1494 local $louser = <$PASSOUTr>;
1497 $already_session_id = undef;
1498 $authuser = $baseauthuser = undef;
1501 syslog("info", "%s", "Logout by $louser from $acpthost");
1503 &run_logout_script($louser, $sid,
1505 &write_logout_utmp($louser, $actphost);
1510 if ($in{'user'} =~ /\r|\n|\s/) {
1511 &http_error(500, "Invalid username",
1512 "Username contains invalid characters");
1514 if ($in{'pass'} =~ /\r|\n/) {
1515 &http_error(500, "Invalid password",
1516 "Password contains invalid characters");
1519 local ($vu, $expired, $nonexist) =
1520 &validate_user($in{'user'}, $in{'pass'}, $host);
1521 local $hrv = &handle_login(
1522 $vu || $in{'user'}, $vu ? 1 : 0,
1523 $expired, $nonexist, $in{'pass'},
1524 $in{'notestingcookie'});
1525 return $hrv if (defined($hrv));
1529 # Check for a visit to the special PAM login page
1530 if ($config{'session'} && !$deny_authentication &&
1531 $use_pam && $config{'pam_conv'} && $page eq $config{'pam_login'} &&
1533 # A question has been entered .. submit it to the main process
1534 print DEBUG "handle_request: Got call to $page ($in{'cid'})\n";
1535 print DEBUG "handle_request: For PAM, authuser=$authuser\n";
1536 if ($in{'answer'} =~ /\r|\n/ || $in{'cid'} =~ /\r|\n|\s/) {
1537 &http_error(500, "Invalid response",
1538 "Response contains invalid characters");
1542 # Start of a new conversation - answer must be username
1543 $cid = &generate_random_id($in{'answer'});
1544 print $PASSINw "pamstart $cid $host $in{'answer'}\n";
1547 # A response to a previous question
1549 print $PASSINw "pamanswer $cid $in{'answer'}\n";
1552 # Read back the response, and the next question (if any)
1553 local $line = <$PASSOUTr>;
1554 $line =~ s/\r|\n//g;
1555 local ($rv, $question) = split(/\s+/, $line, 2);
1558 local $hrv = &handle_login(
1559 !$in{'cid'} && $in{'answer'} ? $in{'answer'}
1562 return $hrv if (defined($hrv));
1564 elsif ($rv == 1 || $rv == 3) {
1565 # Another question .. force use of PAM CGI
1568 $querystring .= "&cid=$cid&question=".
1570 $querystring .= "&password=1" if ($rv == 3);
1572 $page = $config{'pam_login'};
1573 $miniserv_internal = 1;
1577 # Got back a final ok or failure
1578 local ($user, $ok, $expired, $nonexist) =
1579 split(/\s+/, $question);
1580 local $hrv = &handle_login(
1581 $user, $ok, $expired, $nonexist, undef,
1582 $in{'notestingcookie'});
1583 return $hrv if (defined($hrv));
1586 # A message from PAM .. tell the user
1589 $querystring .= "&cid=$cid&message=".
1592 $page = $config{'pam_login'};
1593 $miniserv_internal = 1;
1598 # Check for a visit to the special password change page
1599 if ($config{'session'} && !$deny_authentication &&
1600 $page eq $config{'password_change'} && !$validated) {
1601 # Just let this slide ..
1603 $miniserv_internal = 3;
1606 # Check for an existing session
1607 if ($config{'session'} && !$validated) {
1608 if ($already_session_id) {
1609 $session_id = $already_session_id;
1610 $authuser = $already_authuser;
1613 elsif (!$deny_authentication &&
1614 $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1615 # Try all session cookies
1616 local $cookie = $header{'cookie'};
1617 while($cookie =~ s/(^|\s)$sidname=([a-f0-9]+)//) {
1620 $in{'webmin_notimeout'} ? 1 : 0;
1621 print $PASSINw "verify $session_id $notimeout\n";
1622 <$PASSOUTr> =~ /(\d+)\s+(\S+)/;
1624 # Valid session continuation
1627 $already_authuser = $authuser;
1636 # Invalid session ID .. don't set
1643 # Check for local authentication
1644 if ($localauth_user && !$header{'x-forwarded-for'} && !$header{'via'}) {
1645 my $luser = &get_user_details($localauth_user);
1647 # Local user exists in webmin users file
1649 $authuser = $localauth_user;
1652 # Check if local user is allowed by unixauth
1653 local @can = &can_user_login($localauth_user,
1657 $authuser = $localauth_user;
1660 $localauth_user = undef;
1666 # Check if this path allows anonymous access
1668 foreach $a (keys %anonymous) {
1669 if (substr($simple, 0, length($a)) eq $a) {
1670 # It does! Auth as the user, if IP access
1671 # control allows him.
1672 if (&check_user_ip($anonymous{$a}) &&
1673 &check_user_time($anonymous{$a})) {
1675 $baseauthuser = $authuser =
1683 # Check if this path allows unauthenticated access
1684 local ($u, $unauth);
1685 foreach $u (@unauth) {
1686 $unauth++ if ($simple =~ /$u/);
1688 if (!$bogus && $unauth) {
1689 # Unauthenticated directory or file request - approve it
1691 $baseauthuser = $authuser = undef;
1696 if ($blocked == 0) {
1697 # No password given.. ask
1698 if ($config{'pam_conv'} && $use_pam) {
1699 # Force CGI for PAM question, starting with
1700 # the username which is always needed
1703 $querystring .= "&initial=1&question=".
1704 &urlize("Username");
1705 $querystring .= "&failed=$failed_user" if ($failed_user);
1706 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1708 $page = $config{'pam_login'};
1709 $miniserv_internal = 1;
1712 elsif ($config{'session'}) {
1713 # Force CGI for session login
1716 $querystring .= "&logout=1&page=/";
1719 # Re-direct to current module only
1720 local $rpage = $request_uri;
1721 if (!$config{'loginkeeppage'}) {
1722 $rpage =~ s/\?.*$//;
1723 $rpage =~ s/[^\/]+$//
1725 $querystring = "page=".&urlize($rpage);
1728 $querystring .= "&failed=$failed_user" if ($failed_user);
1729 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1731 $page = $config{'session_login'};
1732 $miniserv_internal = 1;
1736 # Ask for login with HTTP authentication
1737 &write_data("HTTP/1.0 401 Unauthorized\r\n");
1738 &write_data("Date: $datestr\r\n");
1739 &write_data("Server: $config{'server'}\r\n");
1740 &write_data("WWW-authenticate: Basic ".
1741 "realm=\"$config{'realm'}\"\r\n");
1742 &write_keep_alive(0);
1743 &write_data("Content-type: text/html\r\n");
1744 &write_data("\r\n");
1745 &reset_byte_count();
1746 &write_data("<html>\n");
1747 &write_data("<head><title>Unauthorized</title></head>\n");
1748 &write_data("<body><h1>Unauthorized</h1>\n");
1749 &write_data("A password is required to access this\n");
1750 &write_data("web server. Please try again. <p>\n");
1751 &write_data("</body></html>\n");
1752 &log_request($acpthost, undef, $reqline, 401, &byte_count());
1756 elsif ($blocked == 1) {
1757 # when the host has been blocked, give it an error
1758 &http_error(403, "Access denied for $acptip. The host ".
1759 "has been blocked because of too ".
1760 "many authentication failures.");
1762 elsif ($blocked == 2) {
1763 # when the user has been blocked, give it an error
1764 &http_error(403, "Access denied. The user ".
1765 "has been blocked because of too ".
1766 "many authentication failures.");
1770 # Get the real Webmin username
1771 local @can = &can_user_login($authuser, undef, $host);
1772 $baseauthuser = $can[3] || $authuser;
1774 if ($config{'remoteuser'} && !$< && $validated) {
1775 # Switch to the UID of the remote user (if he exists)
1776 local @u = getpwnam($authuser);
1777 if (@u && $< != $u[2]) {
1778 $( = $u[3]; $) = "$u[3] $u[3]";
1779 ($>, $<) = ($u[2], $u[2]);
1782 &http_error(500, "Unix user $authuser does not exist");
1788 # Check per-user IP access control
1789 if (!&check_user_ip($baseauthuser)) {
1790 &http_error(403, "Access denied for $acptip for $baseauthuser");
1794 # Check per-user allowed times
1795 if (!&check_user_time($baseauthuser)) {
1796 &http_error(403, "Access denied at the current time");
1800 $uinfo = &get_user_details($baseauthuser);
1802 # Validate the path, and convert to canonical form
1804 $simple = &simplify_path($page, $bogus);
1805 print DEBUG "handle_request: page=$page simple=$simple\n";
1807 &http_error(400, "Invalid path");
1810 # Check for a DAV request
1812 return &handle_dav_request($davpath);
1815 # Work out the active theme(s)
1816 local $preroots = $mobile_device && defined($config{'mobile_preroot'}) ?
1817 $config{'mobile_preroot'} :
1818 $authuser && defined($config{'preroot_'.$authuser}) ?
1819 $config{'preroot_'.$authuser} :
1820 $uinfo && defined($uinfo->{'preroot'}) ?
1821 $uinfo->{'preroot'} :
1823 local @preroots = reverse(split(/\s+/, $preroots));
1825 # Canonicalize the directories
1826 foreach my $preroot (@preroots) {
1827 # Always under the current webmin root
1828 $preroot =~ s/^.*\///g;
1829 $preroot = $roots[0].'/'.$preroot;
1832 # Look in the theme root directories first
1833 local ($full, @stfull);
1835 foreach my $preroot (@preroots) {
1838 $full = $preroot.$sofar;
1839 $scriptname = $simple;
1840 foreach $b (split(/\//, $simple)) {
1841 if ($b ne "") { $sofar .= "/$b"; }
1842 $full = $preroot.$sofar;
1843 @stfull = stat($full);
1844 if (!@stfull) { undef($full); last; }
1846 # Check if this is a directory
1848 # It is.. go on parsing
1856 # Check if this is a CGI program
1857 if (&get_type($full) eq "internal/cgi") {
1858 $pathinfo = substr($simple, length($sofar));
1859 $pathinfo .= "/" if ($page =~ /\/$/);
1860 $scriptname = $sofar;
1865 # Don't stop at a directory unless this is the last theme, which
1866 # is the 'real' one that provides the .cgi scripts
1867 if ($is_directory && $preroot ne $preroots[$#preroots]) {
1874 $cgi_pwd = $roots[0];
1876 elsif ($is_directory) {
1877 $cgi_pwd = "$roots[0]$sofar";
1880 "$roots[0]$sofar" =~ /^(.*\/)[^\/]+$/;
1883 $foundroot = $preroot;
1884 if ($is_directory) {
1885 # Check for index files in the directory
1887 foreach $idx (split(/\s+/, $config{"index_docs"})) {
1888 $idxfull = "$full/$idx";
1889 local @stidxfull = stat($idxfull);
1890 if (-r _ && !-d _) {
1892 @stfull = @stidxfull;
1895 if ($scriptname ne "/");
1900 @stfull = stat($full) if (!$foundidx);
1903 last if ($foundroot);
1905 print DEBUG "handle_request: initial full=$full\n";
1907 # Look in the real root directories, stopping when we find a file or directory
1908 if (!$full || $is_directory) {
1909 ROOT: foreach $root (@roots) {
1911 $full = $root.$sofar;
1912 $scriptname = $simple;
1913 foreach $b ($simple eq "/" ? ( "" ) : split(/\//, $simple)) {
1914 if ($b ne "") { $sofar .= "/$b"; }
1915 $full = $root.$sofar;
1916 @stfull = stat($full);
1921 # Check if this is a directory
1923 # It is.. go on parsing
1927 # Check if this is a CGI program
1928 if (&get_type($full) eq "internal/cgi") {
1929 $pathinfo = substr($simple, length($sofar));
1930 $pathinfo .= "/" if ($page =~ /\/$/);
1931 $scriptname = $sofar;
1936 # Run CGI in the same directory as whatever file
1938 $full =~ /^(.*\/)[^\/]+$/; $cgi_pwd = $1;
1947 if (!@stfull) { &http_error(404, "File not found"); }
1949 print DEBUG "handle_request: full=$full\n";
1950 @stfull = stat($full) if (!@stfull);
1952 # check filename against denyfile regexp
1953 local $denyfile = $config{'denyfile'};
1954 if ($denyfile && $full =~ /$denyfile/) {
1955 &http_error(403, "Access denied to $page");
1959 # Reached the end of the path OK.. see what we've got
1961 # See if the URL ends with a / as it should
1962 print DEBUG "handle_request: found a directory\n";
1963 if ($page !~ /\/$/) {
1964 # It doesn't.. redirect
1965 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1966 $ssl = $use_ssl || $config{'inetd_ssl'};
1967 $portstr = $port == 80 && !$ssl ? "" :
1968 $port == 443 && $ssl ? "" : ":$port";
1969 &write_data("Date: $datestr\r\n");
1970 &write_data("Server: $config{server}\r\n");
1971 $prot = $ssl ? "https" : "http";
1972 &write_data("Location: $prot://$host$portstr$page/\r\n");
1973 &write_keep_alive(0);
1974 &write_data("\r\n");
1975 &log_request($acpthost, $authuser, $reqline, 302, 0);
1978 # A directory.. check for index files
1980 foreach $idx (split(/\s+/, $config{"index_docs"})) {
1981 $idxfull = "$full/$idx";
1982 @stidxfull = stat($idxfull);
1983 if (-r _ && !-d _) {
1986 @stfull = @stidxfull;
1987 $scriptname .= "/" if ($scriptname ne "/");
1992 @stfull = stat($full) if (!$foundidx);
1995 # This is definately a directory.. list it
1996 print DEBUG "handle_request: listing directory\n";
1997 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
1998 "Date: $datestr\r\n".
1999 "Server: $config{server}\r\n".
2000 "Content-type: text/html\r\n";
2002 &write_keep_alive(0);
2003 &write_data("\r\n");
2004 &reset_byte_count();
2005 &write_data("<h1>Index of $simple</h1>\n");
2006 &write_data("<pre>\n");
2007 &write_data(sprintf "%-35.35s %-20.20s %-10.10s\n",
2008 "Name", "Last Modified", "Size");
2009 &write_data("<hr>\n");
2010 opendir(DIR, $full);
2011 while($df = readdir(DIR)) {
2012 if ($df =~ /^\./) { next; }
2013 $fulldf = $full eq "/" ? $full.$df : $full."/".$df;
2014 (@stbuf = stat($fulldf)) || next;
2015 if (-d _) { $df .= "/"; }
2016 @tm = localtime($stbuf[9]);
2017 $fdate = sprintf "%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d",
2018 $tm[3],$tm[4]+1,$tm[5]+1900,
2019 $tm[0],$tm[1],$tm[2];
2020 $len = length($df); $rest = " "x(35-$len);
2022 "<a href=\"%s\">%-${len}.${len}s</a>$rest %-20.20s %-10.10s\n",
2023 $df, $df, $fdate, $stbuf[7]);
2026 &log_request($acpthost, $authuser, $reqline, $ok_code, &byte_count());
2030 # CGI or normal file
2032 if (&get_type($full) eq "internal/cgi" && $validated != 4) {
2033 # A CGI program to execute
2034 print DEBUG "handle_request: executing CGI\n";
2035 $envtz = $ENV{"TZ"};
2036 $envuser = $ENV{"USER"};
2037 $envpath = $ENV{"PATH"};
2038 $envlang = $ENV{"LANG"};
2039 $envroot = $ENV{"SystemRoot"};
2040 $envperllib = $ENV{'PERLLIB'};
2041 foreach my $k (keys %ENV) {
2044 $ENV{"PATH"} = $envpath if ($envpath);
2045 $ENV{"TZ"} = $envtz if ($envtz);
2046 $ENV{"USER"} = $envuser if ($envuser);
2047 $ENV{"OLD_LANG"} = $envlang if ($envlang);
2048 $ENV{"SystemRoot"} = $envroot if ($envroot);
2049 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
2050 $ENV{"HOME"} = $user_homedir;
2051 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
2052 $ENV{"SERVER_NAME"} = $host;
2053 $ENV{"SERVER_ADMIN"} = $config{"email"};
2054 $ENV{"SERVER_ROOT"} = $roots[0];
2055 $ENV{"SERVER_REALROOT"} = $realroot;
2056 $ENV{"SERVER_PORT"} = $port;
2057 $ENV{"REMOTE_HOST"} = $acpthost;
2058 $ENV{"REMOTE_ADDR"} = $acptip;
2059 $ENV{"REMOTE_USER"} = $authuser;
2060 $ENV{"BASE_REMOTE_USER"} = $authuser ne $baseauthuser ?
2061 $baseauthuser : undef;
2062 $ENV{"REMOTE_PASS"} = $authpass if (defined($authpass) &&
2063 $config{'pass_password'});
2064 if ($uinfo && $uinfo->{'proto'}) {
2065 $ENV{"REMOTE_USER_PROTO"} = $uinfo->{'proto'};
2066 $ENV{"REMOTE_USER_ID"} = $uinfo->{'id'};
2068 print DEBUG "REMOTE_USER = ",$ENV{"REMOTE_USER"},"\n";
2069 print DEBUG "BASE_REMOTE_USER = ",$ENV{"BASE_REMOTE_USER"},"\n";
2070 print DEBUG "proto=$uinfo->{'proto'} id=$uinfo->{'id'}\n" if ($uinfo);
2071 $ENV{"SSL_USER"} = $peername if ($validated == 2);
2072 $ENV{"ANONYMOUS_USER"} = "1" if ($validated == 3 || $validated == 4);
2073 $ENV{"DOCUMENT_ROOT"} = $roots[0];
2074 $ENV{"DOCUMENT_REALROOT"} = $realroot;
2075 $ENV{"GATEWAY_INTERFACE"} = "CGI/1.1";
2076 $ENV{"SERVER_PROTOCOL"} = "HTTP/1.0";
2077 $ENV{"REQUEST_METHOD"} = $method;
2078 $ENV{"SCRIPT_NAME"} = $scriptname;
2079 $ENV{"SCRIPT_FILENAME"} = $full;
2080 $ENV{"REQUEST_URI"} = $request_uri;
2081 $ENV{"PATH_INFO"} = $pathinfo;
2083 $ENV{"PATH_TRANSLATED"} = "$roots[0]$pathinfo";
2084 $ENV{"PATH_REALTRANSLATED"} = "$realroot$pathinfo";
2086 $ENV{"QUERY_STRING"} = $querystring;
2087 $ENV{"MINISERV_CONFIG"} = $config_file;
2088 $ENV{"HTTPS"} = "ON" if ($use_ssl || $config{'inetd_ssl'});
2089 $ENV{"MINISERV_PID"} = $miniserv_main_pid;
2090 $ENV{"SESSION_ID"} = $session_id if ($session_id);
2091 $ENV{"LOCAL_USER"} = $localauth_user if ($localauth_user);
2092 $ENV{"MINISERV_INTERNAL"} = $miniserv_internal if ($miniserv_internal);
2093 if (defined($header{"content-length"})) {
2094 $ENV{"CONTENT_LENGTH"} = $header{"content-length"};
2096 if (defined($header{"content-type"})) {
2097 $ENV{"CONTENT_TYPE"} = $header{"content-type"};
2099 foreach $h (keys %header) {
2100 ($hname = $h) =~ tr/a-z/A-Z/;
2102 $ENV{"HTTP_$hname"} = $header{$h};
2104 $ENV{"PWD"} = $cgi_pwd;
2105 foreach $k (keys %config) {
2106 if ($k =~ /^env_(\S+)$/) {
2107 $ENV{$1} = $config{$k};
2110 delete($ENV{'HTTP_AUTHORIZATION'});
2111 $ENV{'HTTP_COOKIE'} =~ s/;?\s*$sidname=([a-f0-9]+)//;
2112 $ENV{'MOBILE_DEVICE'} = 1 if ($mobile_device);
2114 # Check if the CGI can be handled internally
2116 local $first = <CGI>;
2118 $first =~ s/[#!\r\n]//g;
2119 $nph_script = ($full =~ /\/nph-([^\/]+)$/);
2121 if (!$config{'forkcgis'} &&
2122 ($first eq $perl_path || $first eq $linked_perl_path) &&
2124 $config{'internalcgis'}) {
2125 # setup environment for eval
2127 @ARGV = split(/\s+/, $queryargs);
2130 # Already read the post input
2131 $postinput = $posted_data;
2133 $clen = $header{"content-length"};
2134 $SIG{'CHLD'} = 'DEFAULT';
2136 # Have SOCK closed if the perl exec's something
2138 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
2142 if ($config{'log'}) {
2143 open(MINISERVLOG, ">>$config{'logfile'}");
2144 if ($config{'logperms'}) {
2145 chmod(oct($config{'logperms'}),
2146 $config{'logfile'});
2149 chmod(0600, $config{'logfile'});
2152 $doing_cgi_eval = 1;
2153 $main_process_id = $$;
2155 if ($full =~ /^\Q$foundroot\E\/([^\/]+)\//) {
2156 # Eval in package from Webmin module name
2158 $pkg =~ s/[^A-Za-z0-9]/_/g;
2163 tie(*STDOUT, 'miniserv');
2164 tie(*STDIN, 'miniserv');
2165 do \$miniserv::full;
2168 $doing_cgi_eval = 0;
2171 &http_error(500, "Perl execution failed",
2172 $config{'noshowstderr'} ? undef : $@);
2174 elsif (!$doneheaders && !$nph_script) {
2175 &http_error(500, "Missing Headers");
2182 # fork the process that actually executes the CGI
2183 pipe(CGIINr, CGIINw);
2184 pipe(CGIOUTr, CGIOUTw);
2185 pipe(CGIERRr, CGIERRw);
2186 if (!($cgipid = fork())) {
2187 @execargs = ( $full, split(/\s+/, $queryargs) );
2190 open(STDIN, "<&CGIINr");
2191 open(STDOUT, ">&CGIOUTw");
2192 open(STDERR, ">&CGIERRw");
2193 close(CGIINw); close(CGIOUTr); close(CGIERRr);
2195 die "Failed to exec $full : $!\n";
2198 close(CGIINr); close(CGIOUTw); close(CGIERRw);
2201 # write CGI input to a temp file
2202 $infile = "$config{'tempbase'}.$$";
2203 open(CGIINw, ">$infile");
2204 # NOT binary mode, as CGIs don't read in it!
2209 # already read the posted data
2210 print CGIINw $posted_data;
2212 $clen = $header{"content-length"};
2213 if ($method eq "POST" && $clen_read < $clen) {
2214 $SIG{'PIPE'} = 'IGNORE';
2216 while($got < $clen) {
2217 $buf = &read_data($clen-$got);
2218 if (!length($buf)) {
2219 kill('TERM', $cgipid);
2220 unlink($infile) if ($infile);
2221 &http_error(500, "Failed to read ".
2224 $got += length($buf);
2225 local ($wrote) = (print CGIINw $buf);
2228 # If the CGI terminated early, we still need to read
2229 # from the browser and throw away
2230 while($got < $clen) {
2231 $buf = &read_data($clen-$got);
2232 if (!length($buf)) {
2233 kill('TERM', $cgipid);
2234 unlink($infile) if ($infile);
2235 &http_error(500, "Failed to read ".
2238 $got += length($buf);
2240 $SIG{'PIPE'} = 'DEFAULT';
2246 # Run the CGI program, and feed it input
2248 local $qqueryargs = join(" ", map { "\"$_\"" }
2249 split(/\s+/, $queryargs));
2250 if ($first =~ /(perl|perl.exe)$/i) {
2251 # On Windows, run with Perl
2252 open(CGIOUTr, "$perl_path \"$full\" $qqueryargs <$infile |");
2255 open(CGIOUTr, "\"$full\" $qqueryargs <$infile |");
2261 # read back cgi headers
2262 select(CGIOUTr); $|=1; select(STDOUT);
2266 $line =~ s/\r|\n//g;
2268 if ($got_blank || %cgiheader) { last; }
2272 if ($line !~ /^(\S+):\s+(.*)$/) {
2273 $errs = &read_errors(CGIERRr);
2274 close(CGIOUTr); close(CGIERRr);
2275 unlink($infile) if ($infile);
2276 &http_error(500, "Bad Header", $errs);
2278 $cgiheader{lc($1)} = $2;
2279 push(@cgiheader, [ $1, $2 ]);
2281 if ($cgiheader{"location"}) {
2282 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2283 &write_data("Date: $datestr\r\n");
2284 &write_data("Server: $config{'server'}\r\n");
2285 &write_keep_alive(0);
2286 # ignore the rest of the output. This is a hack,
2287 # but is necessary for IE in some cases :(
2288 close(CGIOUTr); close(CGIERRr);
2290 elsif ($cgiheader{"content-type"} eq "") {
2291 close(CGIOUTr); close(CGIERRr);
2292 unlink($infile) if ($infile);
2293 $errs = &read_errors(CGIERRr);
2294 &http_error(500, "Missing Content-Type Header",
2295 $config{'noshowstderr'} ? undef : $errs);
2298 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2299 &write_data("Date: $datestr\r\n");
2300 &write_data("Server: $config{'server'}\r\n");
2301 &write_keep_alive(0);
2303 foreach $h (@cgiheader) {
2304 &write_data("$h->[0]: $h->[1]\r\n");
2306 &write_data("\r\n");
2308 &reset_byte_count();
2309 while($line = <CGIOUTr>) {
2314 unlink($infile) if ($infile);
2320 print DEBUG "handle_request: outputting file\n";
2321 open(FILE, $full) || &http_error(404, "Failed to open file");
2323 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2324 "Date: $datestr\r\n".
2325 "Server: $config{server}\r\n".
2326 "Content-type: ".&get_type($full)."\r\n".
2327 "Content-length: $stfull[7]\r\n".
2328 "Last-Modified: ".&http_date($stfull[9])."\r\n".
2329 "Expires: ".&http_date(time()+$config{'expires'})."\r\n";
2331 $rv = &write_keep_alive();
2332 &write_data("\r\n");
2333 &reset_byte_count();
2334 while(read(FILE, $buf, 1024) > 0) {
2341 &log_request($acpthost, $authuser, $reqline,
2342 $logged_code ? $logged_code :
2343 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2347 # http_error(code, message, body, [dontexit])
2350 local $eh = $error_handler_recurse ? undef :
2351 $config{"error_handler_$_[0]"} ? $config{"error_handler_$_[0]"} :
2352 $config{'error_handler'} ? $config{'error_handler'} : undef;
2353 print DEBUG "http_error code=$_[0] message=$_[1] body=$_[2]\n";
2355 # Call a CGI program for the error
2357 $querystring = "code=$_[0]&message=".&urlize($_[1]).
2358 "&body=".&urlize($_[2]);
2359 $error_handler_recurse++;
2361 $ok_message = $_[1];
2365 # Use the standard error message display
2366 &write_data("HTTP/1.0 $_[0] $_[1]\r\n");
2367 &write_data("Server: $config{server}\r\n");
2368 &write_data("Date: $datestr\r\n");
2369 &write_data("Content-type: text/html\r\n");
2370 &write_keep_alive(0);
2371 &write_data("\r\n");
2372 &reset_byte_count();
2373 &write_data("<h1>Error - $_[1]</h1>\n");
2375 &write_data("<pre>$_[2]</pre>\n");
2378 &log_request($acpthost, $authuser, $reqline, $_[0], &byte_count())
2380 &log_error($_[1], $_[2] ? " : $_[2]" : "");
2387 if ($_[0] =~ /\.([A-z0-9]+)$/) {
2393 return "text/plain";
2396 # simplify_path(path, bogus)
2397 # Given a path, maybe containing stuff like ".." and "." convert it to a
2398 # clean, absolute form.
2401 local($dir, @bits, @fixedbits, $b);
2403 $dir =~ s/\\/\//g; # fix windows \ in path
2406 $dir =~ s/\0//g; # remove null bytes
2407 @bits = split(/\/+/, $dir);
2410 foreach $b (@bits) {
2414 elsif ($b eq ".." || $b eq "...") {
2416 if (scalar(@fixedbits) == 0) {
2424 push(@fixedbits, $b);
2427 return "/" . join('/', @fixedbits);
2431 # Converts a string from base64 format to normal
2434 local($str) = $_[0];
2436 $str =~ tr|A-Za-z0-9+=/||cd;
2438 $str =~ tr|A-Za-z0-9+/| -_|;
2439 while ($str =~ /(.{1,60})/gs) {
2440 my $len = chr(32 + length($1)*3/4);
2441 $res .= unpack("u", $len . $1 );
2446 # ip_match(remoteip, localip, [match]+)
2447 # Checks an IP address against a list of IPs, networks and networks/masks
2450 local(@io, @mo, @ms, $i, $j, $hn, $needhn);
2451 @io = split(/\./, $_[0]);
2452 for($i=2; $i<@_; $i++) {
2453 $needhn++ if ($_[$i] =~ /^\*(\S+)$/);
2455 if ($needhn && !defined($hn = $ip_match_cache{$_[0]})) {
2456 $hn = gethostbyaddr(inet_aton($_[0]), AF_INET);
2457 $hn = "" if (&to_ipaddress($hn) ne $_[0]);
2458 $ip_match_cache{$_[0]} = $hn;
2460 for($i=2; $i<@_; $i++) {
2461 local $mismatch = 0;
2462 if ($_[$i] =~ /^(\S+)\/(\d+)$/) {
2463 # Convert CIDR to netmask format
2464 $_[$i] = $1."/".&prefix_to_mask($2);
2466 if ($_[$i] =~ /^(\S+)\/(\S+)$/) {
2467 # Compare with network/mask
2468 @mo = split(/\./, $1); @ms = split(/\./, $2);
2469 for($j=0; $j<4; $j++) {
2470 if ((int($io[$j]) & int($ms[$j])) != int($mo[$j])) {
2475 elsif ($_[$i] =~ /^\*(\S+)$/) {
2476 # Compare with hostname regexp
2477 $mismatch = 1 if ($hn !~ /$1$/);
2479 elsif ($_[$i] eq 'LOCAL') {
2480 # Compare with local network
2481 local @lo = split(/\./, $_[1]);
2483 $mismatch = 1 if ($lo[0] != $io[0]);
2485 elsif ($lo[0] < 192) {
2486 $mismatch = 1 if ($lo[0] != $io[0] ||
2490 $mismatch = 1 if ($lo[0] != $io[0] ||
2495 elsif ($_[$i] !~ /^[0-9\.]+$/) {
2496 # Compare with hostname
2497 $mismatch = 1 if ($_[0] ne &to_ipaddress($_[$i]));
2500 # Compare with IP or network
2501 @mo = split(/\./, $_[$i]);
2502 while(@mo && !$mo[$#mo]) { pop(@mo); }
2503 for($j=0; $j<@mo; $j++) {
2504 if ($mo[$j] != $io[$j]) {
2509 return 1 if (!$mismatch);
2514 # users_match(&uinfo, user, ...)
2515 # Returns 1 if a user is in a list of users and groups
2518 local $uinfo = shift(@_);
2520 local @ginfo = getgrgid($uinfo->[3]);
2522 if ($u =~ /^\@(\S+)$/) {
2523 return 1 if (&is_group_member($uinfo, $1));
2525 elsif ($u =~ /^(\d*)-(\d*)$/ && ($1 || $2)) {
2526 return (!$1 || $uinfo[2] >= $1) &&
2527 (!$2 || $uinfo[2] <= $2);
2530 return 1 if ($u eq $uinfo->[0]);
2536 # restart_miniserv()
2537 # Called when a SIGHUP is received to restart the web server. This is done
2538 # by exec()ing perl with the same command line as was originally used
2539 sub restart_miniserv
2541 print STDERR "restarting miniserv\n";
2542 &log_error("Restarting");
2544 &close_all_sockets();
2546 dbmclose(%sessiondb);
2547 kill('KILL', $logclearer) if ($logclearer);
2548 kill('KILL', $extauth) if ($extauth);
2549 exec($perl_path, $miniserv_path, @miniserv_argv);
2550 die "Failed to restart miniserv with $perl_path $miniserv_path";
2567 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2568 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/) { push(@rv, $i); }
2569 else { push(@rv, join('.', unpack("CCCC", inet_aton($i)))); }
2571 return wantarray ? @rv : $rv[0];
2574 # read_line(no-wait, no-limit)
2575 # Reads one line from SOCK or SSL
2578 local ($nowait, $nolimit) = @_;
2579 local($idx, $more, $rv);
2580 while(($idx = index($main::read_buffer, "\n")) < 0) {
2581 if (length($main::read_buffer) > 10000 && !$nolimit) {
2582 &http_error(414, "Request too long",
2583 "Received excessive line <pre>$main::read_buffer</pre>");
2586 # need to read more..
2587 &wait_for_data_error() if (!$nowait);
2589 $more = Net::SSLeay::read($ssl_con);
2592 local $ok = sysread(SOCK, $more, 1024);
2593 $more = undef if ($ok <= 0);
2597 $rv = $main::read_buffer;
2598 undef($main::read_buffer);
2601 $main::read_buffer .= $more;
2603 $rv = substr($main::read_buffer, 0, $idx+1);
2604 $main::read_buffer = substr($main::read_buffer, $idx+1);
2609 # Reads up to some amount of data from SOCK or the SSL connection
2613 if (length($main::read_buffer)) {
2614 if (length($main::read_buffer) > $_[0]) {
2615 # Return the first part of the buffer
2616 $rv = substr($main::read_buffer, 0, $_[0]);
2617 $main::read_buffer = substr($main::read_buffer, $_[0]);
2621 # Return the whole buffer
2622 $rv = $main::read_buffer;
2623 undef($main::read_buffer);
2628 # Call SSL read function
2629 return Net::SSLeay::read($ssl_con, $_[0]);
2632 # Just do a normal read
2634 sysread(SOCK, $buf, $_[0]) || return undef;
2640 # Read a line from a file handle, using sysread to get a byte at a time
2647 $got = sysread($fh, $buf, 1);
2648 last if ($got <= 0);
2650 last if ($buf eq "\n");
2655 # wait_for_data(secs)
2656 # Waits at most the given amount of time for some data on SOCK, returning
2657 # 0 if not found, 1 if some arrived.
2661 vec($rmask, fileno(SOCK), 1) = 1;
2662 local $got = select($rmask, undef, undef, $_[0]);
2663 return $got == 0 ? 0 : 1;
2666 # wait_for_data_error()
2667 # Waits 60 seconds for data on SOCK, and fails if none arrives
2668 sub wait_for_data_error
2670 local $got = &wait_for_data(60);
2672 &http_error(400, "Timeout",
2673 "Waited more than 60 seconds for request data");
2677 # write_data(data, ...)
2678 # Writes a string to SOCK or the SSL connection
2681 local $str = join("", @_);
2683 Net::SSLeay::write($ssl_con, $str);
2686 syswrite(SOCK, $str, length($str));
2688 # Intentionally introduce a small delay to avoid problems where IE reports
2689 # the page as empty / DNS failed when it get a large response too quickly!
2690 select(undef, undef, undef, .01) if ($write_data_count%10 == 0);
2691 $write_data_count += length($str);
2694 # reset_byte_count()
2695 sub reset_byte_count { $write_data_count = 0; }
2698 sub byte_count { return $write_data_count; }
2700 # log_request(hostname, user, request, code, bytes)
2703 if ($config{'log'}) {
2704 local ($user, $ident, $headers);
2705 if ($config{'logident'}) {
2706 # add support for rfc1413 identity checking here
2708 else { $ident = "-"; }
2709 $user = $_[1] ? $_[1] : "-";
2710 local $dstr = &make_datestr();
2711 if (fileno(MINISERVLOG)) {
2712 seek(MINISERVLOG, 0, 2);
2715 open(MINISERVLOG, ">>$config{'logfile'}");
2716 chmod(0600, $config{'logfile'});
2718 if (defined($config{'logheaders'})) {
2719 foreach $h (split(/\s+/, $config{'logheaders'})) {
2720 $headers .= " $h=\"$header{$h}\"";
2723 elsif ($config{'logclf'}) {
2724 $headers = " \"$header{'referer'}\" \"$header{'user-agent'}\"";
2729 print MINISERVLOG "$_[0] $ident $user [$dstr] \"$_[2]\" ",
2730 "$_[3] $_[4]$headers\n";
2738 local @tm = localtime(time());
2739 return sprintf "%2.2d/%s/%4.4d:%2.2d:%2.2d:%2.2d %s",
2740 $tm[3], $month[$tm[4]], $tm[5]+1900,
2741 $tm[2], $tm[1], $tm[0], $timezone;
2744 # log_error(message)
2748 print STDERR "[",&make_datestr(),"] ",
2749 $acpthost ? ( "[",$acpthost,"] " ) : ( ),
2750 $page ? ( $page," : " ) : ( ),
2754 # read_errors(handle)
2755 # Read and return all input from some filehandle
2758 local($fh, $_, $rv);
2760 while(<$fh>) { $rv .= $_; }
2764 sub write_keep_alive
2767 if ($config{'nokeepalive'}) {
2768 # Keep alives have been disabled in config
2771 elsif (@childpids > $config{'maxconns'}*.8) {
2772 # Disable because nearing process limit
2776 # Keep alive specified by caller
2780 # Keep alive determined by browser
2781 $mode = $header{'connection'} =~ /keep-alive/i;
2783 &write_data("Connection: ".($mode ? "Keep-Alive" : "close")."\r\n");
2789 kill('TERM', @childpids) if (@childpids);
2790 kill('KILL', $logclearer) if ($logclearer);
2791 kill('KILL', $extauth) if ($extauth);
2797 local @tm = gmtime($_[0]);
2798 return sprintf "%s, %d %s %d %2.2d:%2.2d:%2.2d GMT",
2799 $weekday[$tm[6]], $tm[3], $month[$tm[4]], $tm[5]+1900,
2800 $tm[2], $tm[1], $tm[0];
2805 my $i; bless \$i, shift;
2811 my($buf,$len,$offset) = @_;
2812 &write_to_sock(substr($buf, $offset, $len));
2819 my $buf = join(defined($,) ? $, : "", @_);
2820 $buf .= $\ if defined($\);
2821 &write_to_sock($buf);
2828 &write_to_sock(sprintf $fmt, @_);
2831 # Send back already read data while we have it, then read from SOCK
2835 my $bufref = \$_[0];
2838 if ($postpos < length($postinput)) {
2839 # Reading from already fetched array
2840 my $left = length($postinput) - $postpos;
2841 my $canread = $len > $left ? $left : $len;
2842 substr($$bufref, $offset, $canread) =
2843 substr($postinput, $postpos, $canread);
2844 $postpos += $canread;
2848 # Read from network socket
2849 local $data = &read_data($len);
2850 if ($data eq '' && $len) {
2852 print STDERR "finished reading - shutting down socket\n";
2855 substr($$bufref, $offset, length($data)) = $data;
2856 return length($data);
2862 #print STDERR "open() called - should never happen!\n";
2865 # Read a line of input
2869 if ($postpos < length($postinput) &&
2870 ($idx = index($postinput, "\n", $postpos)) >= 0) {
2871 # A line exists in the memory buffer .. use it
2872 my $line = substr($postinput, $postpos, $idx-$postpos+1);
2877 # Need to read from the socket
2879 if ($postpos < length($postinput)) {
2880 # Start with in-memory data
2881 $line = substr($postinput, $postpos);
2882 $postpos = length($postinput);
2884 my $nl = &read_line(0, 1);
2887 print STDERR "finished reading - shutting down socket\n";
2890 $line .= $nl if (defined($nl));
2895 # Read one character of input
2900 my $got = READ($r, \$buf, 1, 0);
2901 return $got > 0 ? $buf : undef;
2906 return fileno(SOCK);
2913 # write_to_sock(data, ...)
2918 if ($doneheaders || $miniserv::nph_script) {
2923 while(!$doneheaders && $headers =~ s/^([^\r\n]*)(\r)?\n//) {
2924 if ($1 =~ /^(\S+):\s+(.*)$/) {
2925 $cgiheader{lc($1)} = $2;
2926 push(@cgiheader, [ $1, $2 ]);
2928 elsif ($1 !~ /\S/) {
2932 &http_error(500, "Bad Header");
2936 if ($cgiheader{"location"}) {
2938 "HTTP/1.0 302 Moved Temporarily\r\n");
2939 &write_data("Date: $datestr\r\n");
2940 &write_data("Server: $config{server}\r\n");
2941 &write_keep_alive(0);
2943 elsif ($cgiheader{"content-type"} eq "") {
2944 &http_error(500, "Missing Content-Type Header");
2947 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2948 &write_data("Date: $datestr\r\n");
2949 &write_data("Server: $config{server}\r\n");
2950 &write_keep_alive(0);
2952 foreach $h (@cgiheader) {
2953 &write_data("$h->[0]: $h->[1]\r\n");
2955 &write_data("\r\n");
2956 &reset_byte_count();
2957 &write_data($headers);
2965 local $cert = Net::SSLeay::X509_STORE_CTX_get_current_cert($_[1]);
2967 local $errnum = Net::SSLeay::X509_STORE_CTX_get_error($_[1]);
2968 $verified_client = 1 if (!$errnum);
2975 if ($doing_cgi_eval && $$ == $main_process_id) {
2976 # A CGI program called exit! This is a horrible hack to
2977 # finish up before really exiting
2980 close($PASSINw); close($PASSOUTw);
2981 &log_request($acpthost, $authuser, $reqline,
2982 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2987 # Convert a string to a form ok for putting in a URL
2989 local($tmp, $tmp2, $c);
2992 while(($c = chop($tmp)) ne "") {
2993 if ($c !~ /[A-z0-9]/) {
2994 $c = sprintf("%%%2.2X", ord($c));
3001 # validate_user(username, password, host)
3002 # Checks if some username and password are valid. Returns the modified username,
3003 # the expired / temp pass flag, and the non-existence flag
3006 local ($user, $pass, $host) = @_;
3007 return ( ) if (!$user);
3008 print DEBUG "validate_user: user=$user pass=$pass host=$host\n";
3009 local ($canuser, $canmode, $notexist, $webminuser, $sudo) =
3010 &can_user_login($user, undef, $host);
3011 print DEBUG "validate_user: canuser=$canuser canmode=$canmode notexist=$notexist webminuser=$webminuser sudo=$sudo\n";
3013 # User doesn't even exist, so go no further
3014 return ( undef, 0, 1 );
3016 elsif ($canmode == 0) {
3017 # User does exist but cannot login
3018 return ( $canuser, 0, 0 );
3020 elsif ($canmode == 1) {
3021 # Attempt Webmin authentication
3022 my $uinfo = &get_user_details($webminuser);
3023 if ($uinfo && &password_crypt($pass, $uinfo->{'pass'})) {
3024 # Password is valid .. but check for expiry
3025 local $lc = $uinfo->{'lastchanges'};
3026 if ($config{'pass_maxdays'} && $lc && !$uinfo->{'nochange'}) {
3027 local $daysold = (time() - $lc)/(24*60*60);
3028 print DEBUG "maxdays=$config{'pass_maxdays'} daysold=$daysold temppass=$uinfo->{'temppass'}\n";
3029 if ($config{'pass_lockdays'} &&
3030 $daysold > $config{'pass_lockdays'}) {
3031 # So old that the account is locked
3032 return ( undef, 0, 0 );
3034 elsif ($daysold > $config{'pass_maxdays'}) {
3035 # Password has expired
3036 return ( $user, 1, 0 );
3039 if ($uinfo->{'temppass'}) {
3040 # Temporary password - force change now
3041 return ( $user, 2, 0 );
3043 return ( $user, 0, 0 );
3046 return ( undef, 0, 0 );
3049 elsif ($canmode == 2 || $canmode == 3) {
3050 # Attempt PAM or passwd file authentication
3051 local $val = &validate_unix_user($canuser, $pass);
3052 print DEBUG "validate_user: unix val=$val\n";
3053 if ($val && $sudo) {
3054 # Need to check if this Unix user can sudo
3055 if (!&check_sudo_permissions($canuser, $pass)) {
3056 print DEBUG "validate_user: sudo failed\n";
3060 print DEBUG "validate_user: sudo passed\n";
3063 return $val == 2 ? ( $canuser, 1, 0 ) :
3064 $val == 1 ? ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3066 elsif ($canmode == 4) {
3067 # Attempt external authentication
3068 return &validate_external_user($canuser, $pass) ?
3069 ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3077 # validate_unix_user(user, password)
3078 # Returns 1 if a username and password are valid under unix, 0 if not,
3079 # or 2 if the account has expired.
3080 # Checks PAM if available, and falls back to reading the system password
3082 sub validate_unix_user
3086 $pam_username = $_[0];
3087 $pam_password = $_[1];
3088 eval "use Authen::PAM;";
3089 local $pamh = new Authen::PAM($config{'pam'}, $pam_username,
3092 local $pam_ret = $pamh->pam_authenticate();
3093 if ($pam_ret == PAM_SUCCESS()) {
3094 # Logged in OK .. make sure password hasn't expired
3095 local $acct_ret = $pamh->pam_acct_mgmt();
3096 if ($acct_ret == PAM_SUCCESS()) {
3097 $pamh->pam_open_session();
3100 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3101 $acct_ret == PAM_ACCT_EXPIRED()) {
3105 print STDERR "Unknown pam_acct_mgmt return value : $acct_ret\n";
3112 elsif ($config{'pam_only'}) {
3113 # Pam is not available, but configuration forces it's use!
3116 elsif ($config{'passwd_file'}) {
3117 # Check in a password file
3119 open(FILE, $config{'passwd_file'});
3120 if ($config{'passwd_file'} eq '/etc/security/passwd') {
3121 # Assume in AIX format
3124 if (/^\s*(\S+):/ && $1 eq $_[0]) {
3126 if (/^\s*password\s*=\s*(\S+)\s*$/) {
3127 $rv = $1 eq &password_crypt($_[1], $1) ?
3135 # Read the system password or shadow file
3137 local @l = split(/:/, $_, -1);
3138 local $u = $l[$config{'passwd_uindex'}];
3139 local $p = $l[$config{'passwd_pindex'}];
3141 $rv = $p eq &password_crypt($_[1], $p) ? 1 : 0;
3142 if ($config{'passwd_cindex'} ne '' && $rv) {
3143 # Password may have expired!
3144 local $c = $l[$config{'passwd_cindex'}];
3145 local $m = $l[$config{'passwd_mindex'}];
3146 local $day = time()/(24*60*60);
3147 if ($c =~ /^\d+/ && $m =~ /^\d+/ &&
3153 if ($p eq "" && $config{'passwd_blank'}) {
3154 # Force password change
3162 return $rv if ($rv);
3165 # Fallback option - check password returned by getpw*
3166 local @uinfo = getpwnam($_[0]);
3167 if ($uinfo[1] ne '' && &password_crypt($_[1], $uinfo[1]) eq $uinfo[1]) {
3171 return 0; # Totally failed
3174 # validate_external_user(user, pass)
3175 # Validate a user by passing the username and password to an external
3176 # squid-style authentication program
3177 sub validate_external_user
3179 return 0 if (!$config{'extauth'});
3181 local $str = "$_[0] $_[1]\n";
3182 syswrite(EXTAUTH, $str, length($str));
3183 local $resp = <EXTAUTH>;
3185 return $resp =~ /^OK/i ? 1 : 0;
3188 # can_user_login(username, no-append, host)
3189 # Checks if a user can login or not.
3190 # First return value is the username.
3191 # Second is 0 if cannot login, 1 if using Webmin pass, 2 if PAM, 3 if password
3192 # file, 4 if external.
3193 # Third is 1 if the user does not exist at all, 0 if he does.
3194 # Fourth is the Webmin username whose permissions apply, based on unixauth.
3195 # Fifth is a flag indicating if a sudo check is needed.
3198 local $uinfo = &get_user_details($_[0]);
3200 # See if this user exists in Unix and can be validated by the same
3201 # method as the unixauth webmin user
3202 local $realuser = $unixauth{$_[0]};
3206 eval { @uinfo = getpwnam($_[0]); }; # may fail on windows
3207 if (!$realuser && @uinfo) {
3208 # No unixauth entry for the username .. try his groups
3209 foreach my $ua (keys %unixauth) {
3210 if ($ua =~ /^\@(.*)$/) {
3211 if (&is_group_member(\@uinfo, $1)) {
3212 $realuser = $unixauth{$ua};
3218 if (!$realuser && @uinfo) {
3219 # Fall back to unix auth for all Unix users
3220 $realuser = $unixauth{"*"};
3222 if (!$realuser && $use_sudo && @uinfo) {
3223 # Allow login effectively as root, if sudo permits it
3227 if (!$realuser && !@uinfo && $config{'pamany'}) {
3228 # If the user completely doesn't exist, we can still allow
3229 # him to authenticate via PAM
3230 $realuser = $config{'pamany'};
3234 # For Usermin, always fall back to unix auth for any user,
3235 # so that later checks with domain added / removed are done.
3236 $realuser = $unixauth{"*"};
3238 return (undef, 0, 1, undef) if (!$realuser);
3239 local $uinfo = &get_user_details($realuser);
3240 return (undef, 0, 1, undef) if (!$uinfo);
3241 local $up = $uinfo{'pass'};
3243 # Work out possible domain names from the hostname
3244 local @doms = ( $_[2] );
3245 if ($_[2] =~ /^([^\.]+)\.(\S+)$/) {
3249 if ($config{'user_mapping'} && !%user_mapping) {
3250 # Read the user mapping file
3252 open(MAPPING, $config{'user_mapping'});
3256 if (/^(\S+)\s+(\S+)/) {
3257 if ($config{'user_mapping_reverse'}) {
3258 $user_mapping{$1} = $2;
3261 $user_mapping{$2} = $1;
3268 # Check the user mapping file to see if there is an entry for the
3269 # user login in which specifies a new effective user
3271 foreach my $d (@doms) {
3272 $um ||= $user_mapping{"$_[0]\@$d"};
3274 $um ||= $user_mapping{$_[0]};
3275 if (defined($um) && ($_[1]&4) == 0) {
3276 # A mapping exists - use it!
3277 return &can_user_login($um, $_[1]+4, $_[2]);
3280 # Check if a user with the entered login and the domains appended
3281 # or prepended exists, and if so take it to be the effective user
3282 if (!@uinfo && $config{'domainuser'}) {
3283 # Try again with name.domain and name.firstpart
3284 local @firsts = map { /^([^\.]+)/; $1 } @doms;
3285 if (($_[1]&1) == 0) {
3287 foreach $a (@firsts, @doms) {
3288 foreach $p ("$_[0].${a}", "$_[0]-${a}",
3289 "${a}.$_[0]", "${a}-$_[0]",
3290 "$_[0]_${a}", "${a}_$_[0]") {
3291 local @vu = &can_user_login(
3292 $p, $_[1]+1, $_[2]);
3293 return @vu if ($vu[1]);
3299 # Check if the user entered a domain at the end of his username when
3300 # he really shouldn't have, and if so try without it
3301 if (!@uinfo && $config{'domainstrip'} &&
3302 $_[0] =~ /^(\S+)\@(\S+)$/ && ($_[1]&2) == 0) {
3303 local ($stripped, $dom) = ($1, $2);
3304 local @vu = &can_user_login($stripped, $_[1] + 2, $_[2]);
3305 return @vu if ($vu[1]);
3306 local @vu = &can_user_login($stripped, $_[1] + 2, $dom);
3307 return @vu if ($vu[1]);
3310 return ( undef, 0, 1, undef ) if (!@uinfo && !$pamany);
3313 if (defined(@allowusers)) {
3314 # Only allow people on the allow list
3315 return ( undef, 0, 0, undef )
3316 if (!&users_match(\@uinfo, @allowusers));
3318 elsif (defined(@denyusers)) {
3319 # Disallow people on the deny list
3320 return ( undef, 0, 0, undef )
3321 if (&users_match(\@uinfo, @denyusers));
3323 if ($config{'shells_deny'}) {
3325 open(SHELLS, $config{'shells_deny'});
3329 $found++ if ($_ eq $uinfo[8]);
3332 return ( undef, 0, 0, undef ) if (!$found);
3337 # PAM or passwd file authentication
3338 return ( $_[0], $use_pam ? 2 : 3, 0, $realuser, $sudo );
3340 elsif ($up eq 'e') {
3341 # External authentication
3342 return ( $_[0], 4, 0, $realuser, $sudo );
3345 # Fixed Webmin password
3346 return ( $_[0], 1, 0, $realuser, $sudo );
3349 elsif ($uinfo->{'pass'} eq 'x') {
3350 # Webmin user authenticated via PAM or password file
3351 return ( $_[0], $use_pam ? 2 : 3, 0, $_[0] );
3353 elsif ($uinfo->{'pass'} eq 'e') {
3354 # Webmin user authenticated externally
3355 return ( $_[0], 4, 0, $_[0] );
3358 # Normal Webmin user
3359 return ( $_[0], 1, 0, $_[0] );
3363 # the PAM conversation function for interactive logins
3366 $pam_conv_func_called++;
3373 $ans = $pam_username if ($code == PAM_PROMPT_ECHO_ON() );
3374 $ans = $pam_password if ($code == PAM_PROMPT_ECHO_OFF() );
3376 push @res, PAM_SUCCESS();
3379 push @res, PAM_SUCCESS();
3388 # get_socket_name(handle)
3389 # Returns the local hostname or IP address of some connection
3392 return $config{'host'} if ($config{'host'});
3393 local $sn = getsockname($_[0]);
3394 return undef if (!$sn);
3395 local $myaddr = (unpack_sockaddr_in($sn))[1];
3396 if (!$get_socket_name_cache{$myaddr}) {
3398 if (!$config{'no_resolv_myname'}) {
3399 $myname = gethostbyaddr($myaddr, AF_INET);
3401 if ($myname eq "") {
3402 $myname = inet_ntoa($myaddr);
3404 $get_socket_name_cache{$myaddr} = $myname;
3406 return $get_socket_name_cache{$myaddr};
3409 # run_login_script(username, sid, remoteip, localip)
3410 sub run_login_script
3412 if ($config{'login_script'}) {
3413 system($config{'login_script'}.
3414 " ".join(" ", map { quotemeta($_) || '""' } @_).
3415 " >/dev/null 2>&1 </dev/null");
3419 # run_logout_script(username, sid, remoteip, localip)
3420 sub run_logout_script
3422 if ($config{'logout_script'}) {
3423 system($config{'logout_script'}.
3424 " ".join(" ", map { quotemeta($_) || '""' } @_).
3425 " >/dev/null 2>&1 </dev/null");
3429 # close_all_sockets()
3430 # Closes all the main listening sockets
3431 sub close_all_sockets
3434 foreach $s (@socketfhs) {
3440 # Close all pipes for talking to sub-processes
3444 foreach $p (@passin) { close($p); }
3445 foreach $p (@passout) { close($p); }
3446 foreach $p (values %conversations) {
3447 if ($p->{'PAMOUTr'}) {
3448 close($p->{'PAMOUTr'});
3449 close($p->{'PAMINw'});
3454 # check_user_ip(user)
3455 # Returns 1 if some user is allowed to login from the accepting IP, 0 if not
3458 local ($username) = @_;
3459 local $uinfo = &get_user_details($username);
3460 return 1 if (!$uinfo);
3461 if ($uinfo->{'deny'} &&
3462 &ip_match($acptip, $localip, @{$uinfo->{'deny'}}) ||
3463 $uinfo->{'allow'} &&
3464 !&ip_match($acptip, $localip, @{$uinfo->{'allow'}})) {
3470 # check_user_time(user)
3471 # Returns 1 if some user is allowed to login at the current date and time
3474 local ($username) = @_;
3475 local $uinfo = &get_user_details($username);
3476 return 1 if (!$uinfo || !$uinfo->{'allowdays'} && !$uinfo->{'allowhours'});
3477 local @tm = localtime(time());
3478 if ($uinfo->{'allowdays'}) {
3479 # Make sure day is allowed
3480 return 0 if (&indexof($tm[6], @{$uinfo->{'allowdays'}}) < 0);
3482 if ($uinfo->{'allowhours'}) {
3483 # Make sure time is allowed
3484 local $m = $tm[2]*60+$tm[1];
3485 return 0 if ($m < $uinfo->{'allowhours'}->[0] ||
3486 $m > $uinfo->{'allowhours'}->[1]);
3491 # generate_random_id(password, [force-urandom])
3492 # Returns a random session ID number
3493 sub generate_random_id
3495 local ($pass, $force_urandom) = @_;
3497 if (!$bad_urandom) {
3498 # First try /dev/urandom, unless we have marked it as bad
3499 $SIG{ALRM} = "miniserv::urandom_timeout";
3501 if (open(RANDOM, "/dev/urandom")) {
3503 if (read(RANDOM, $tmpsid, 16) == 16) {
3504 $sid = lc(unpack('h*',$tmpsid));
3510 if (!$sid && !$force_urandom) {
3513 foreach $c (split(//, &unix_crypt($pass, substr($$, -2)))) {
3514 $sid += ord($c) * $mul;
3521 # handle_login(username, ok, expired, not-exists, password, [no-test-cookie])
3522 # Called from handle_session to either mark a user as logged in, or not
3525 local ($vu, $ok, $expired, $nonexist, $pass, $notest) = @_;
3526 $authuser = $vu if ($ok);
3528 # check if the test cookie is set
3529 if ($header{'cookie'} !~ /testing=1/ && $vu &&
3530 !$config{'no_testing_cookie'} && !$notest) {
3531 &http_error(500, "No cookies",
3532 "Your browser does not support cookies, ".
3533 "which are required for this web server to ".
3534 "work in session authentication mode");
3537 # check with main process for delay
3538 if ($config{'passdelay'} && $vu) {
3539 print $PASSINw "delay $vu $acptip $ok\n";
3540 <$PASSOUTr> =~ /(\d+) (\d+)/;
3545 if ($ok && (!$expired ||
3546 $config{'passwd_mode'} == 1)) {
3547 # Logged in OK! Tell the main process about
3549 local $sid = &generate_random_id($pass);
3550 print $PASSINw "new $sid $authuser $acptip\n";
3552 # Run the post-login script, if any
3553 &run_login_script($authuser, $sid,
3556 # Check for a redirect URL for the user
3557 local $rurl = &login_redirect($authuser, $pass, $host);
3559 # Got one .. go to it
3560 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3561 &write_data("Date: $datestr\r\n");
3562 &write_data("Server: $config{'server'}\r\n");
3563 &write_data("Location: $rurl\r\n");
3564 &write_keep_alive(0);
3565 &write_data("\r\n");
3566 &log_request($acpthost, $authuser, $reqline, 302, 0);
3569 # Set cookie and redirect to originally requested page
3570 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3571 &write_data("Date: $datestr\r\n");
3572 &write_data("Server: $config{'server'}\r\n");
3573 local $ssl = $use_ssl || $config{'inetd_ssl'};
3574 $portstr = $port == 80 && !$ssl ? "" :
3575 $port == 443 && $ssl ? "" : ":$port";
3576 $prot = $ssl ? "https" : "http";
3577 local $sec = $ssl ? "; secure" : "";
3578 #$sec .= "; httpOnly";
3579 if ($in{'page'} !~ /^\/[A-Za-z0-9\/\.\-\_]+$/) {
3580 # Make redirect URL safe
3584 &write_data("Set-Cookie: $sidname=$sid; path=/; expires=\"Thu, 31-Dec-2037 00:00:00\"$sec\r\n");
3587 &write_data("Set-Cookie: $sidname=$sid; path=/$sec\r\n");
3589 &write_data("Location: $prot://$host$portstr$in{'page'}\r\n");
3590 &write_keep_alive(0);
3591 &write_data("\r\n");
3592 &log_request($acpthost, $authuser, $reqline, 302, 0);
3593 syslog("info", "%s", "Successful login as $authuser from $acpthost") if ($use_syslog);
3594 &write_login_utmp($authuser, $acpthost);
3598 elsif ($ok && $expired &&
3599 ($config{'passwd_mode'} == 2 || $expired == 2)) {
3600 # Login was ok, but password has expired or was temporary. Need
3601 # to force display of password change form.
3604 $querystring = "&user=".&urlize($vu).
3606 "&expired=".$expired;
3609 $page = $config{'password_form'};
3611 $miniserv_internal = 2;
3612 syslog("crit", "%s",
3613 "Expired login as $vu ".
3614 "from $acpthost") if ($use_syslog);
3617 # Login failed, or password has expired. The login form will be
3618 # displayed again by later code
3620 $request_uri = $in{'page'};
3621 $already_session_id = undef;
3623 $authuser = $baseauthuser = undef;
3624 syslog("crit", "%s",
3625 ($nonexist ? "Non-existent" :
3626 $expired ? "Expired" : "Invalid").
3627 " login as $vu from $acpthost")
3633 # write_login_utmp(user, host)
3634 # Record the login by some user in utmp
3635 sub write_login_utmp
3638 # Write utmp record for login
3639 %utmp = ( 'ut_host' => $_[1],
3640 'ut_time' => time(),
3642 'ut_type' => 7, # user process
3643 'ut_pid' => $main_process_id,
3644 'ut_line' => $config{'pam'},
3646 if (defined(&User::Utmp::putut)) {
3647 User::Utmp::putut(\%utmp);
3650 User::Utmp::pututline(\%utmp);
3655 # write_logout_utmp(user, host)
3656 # Record the logout by some user in utmp
3657 sub write_logout_utmp
3660 # Write utmp record for logout
3661 %utmp = ( 'ut_host' => $_[1],
3662 'ut_time' => time(),
3664 'ut_type' => 8, # dead process
3665 'ut_pid' => $main_process_id,
3666 'ut_line' => $config{'pam'},
3668 if (defined(&User::Utmp::putut)) {
3669 User::Utmp::putut(\%utmp);
3672 User::Utmp::pututline(\%utmp);
3677 # pam_conversation_process(username, write-pipe, read-pipe)
3678 # This function is called inside a sub-process to communicate with PAM. It sends
3679 # questions down one pipe, and reads responses from another
3680 sub pam_conversation_process
3682 local ($user, $writer, $reader) = @_;
3683 $miniserv::pam_conversation_process_writer = $writer;
3684 $miniserv::pam_conversation_process_reader = $reader;
3685 eval "use Authen::PAM;";
3686 local $convh = new Authen::PAM(
3687 $config{'pam'}, $user, \&miniserv::pam_conversation_process_func);
3688 local $pam_ret = $convh->pam_authenticate();
3689 if ($pam_ret == PAM_SUCCESS()) {
3690 local $acct_ret = $convh->pam_acct_mgmt();
3691 if ($acct_ret == PAM_SUCCESS()) {
3692 $convh->pam_open_session();
3693 print $writer "x2 $user 1 0 0\n";
3695 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3696 $acct_ret == PAM_ACCT_EXPIRED()) {
3697 print $writer "x2 $user 1 1 0\n";
3700 print $writer "x0 Unknown PAM account status $acct_ret\n";
3704 print $writer "x2 $user 0 0 0\n";
3709 # pam_conversation_process_func(type, message, [type, message, ...])
3710 # A pipe that talks to both PAM and the master process
3711 sub pam_conversation_process_func
3714 select($miniserv::pam_conversation_process_writer); $| = 1; select(STDOUT);
3716 local ($type, $msg) = (shift, shift);
3718 local $ok = (print $miniserv::pam_conversation_process_writer "$type $msg\n");
3719 print $miniserv::pam_conversation_process_writer "\n";
3720 local $answer = <$miniserv::pam_conversation_process_reader>;
3721 $answer =~ s/\r|\n//g;
3722 push(@rv, PAM_SUCCESS(), $answer);
3724 push(@rv, PAM_SUCCESS());
3729 # Returns 4 new pipe file handles
3732 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3734 local %taken = ( (map { $_, 1 } @passin),
3735 (map { $_->{'PASSINr'} } values %conversations) );
3736 for($p=0; $taken{"PASSINr$p"}; $p++) { }
3737 $PASSINr = "PASSINr$p";
3738 $PASSINw = "PASSINw$p";
3739 $PASSOUTr = "PASSOUTr$p";
3740 $PASSOUTw = "PASSOUTw$p";
3741 pipe($PASSINr, $PASSINw);
3742 pipe($PASSOUTr, $PASSOUTw);
3743 select($PASSINw); $| = 1;
3744 select($PASSINr); $| = 1;
3745 select($PASSOUTw); $| = 1;
3746 select($PASSOUTw); $| = 1;
3748 return ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3751 # recv_pam_question(&conv, fd)
3752 # Reads one PAM question from the sub-process, and sends it to the HTTP handler.
3753 # Returns 0 if the conversation is over, 1 if not.
3754 sub recv_pam_question
3756 local ($conf, $fh) = @_;
3757 local $pr = $conf->{'PAMOUTr'};
3758 select($pr); $| = 1; select(STDOUT);
3759 local $line = <$pr>;
3760 $line =~ s/\r|\n//g;
3763 $line =~ s/\r|\n//g;
3765 $conf->{'last'} = time();
3768 print $fh "0 PAM conversation error\n";
3772 local ($type, $msg) = split(/\s+/, $line, 2);
3773 if ($type =~ /^x(\d+)/) {
3774 # Pass this status code through
3775 print $fh "$1 $msg\n";
3776 return $1 == 2 || $1 == 0 ? 0 : 1;
3778 elsif ($type == PAM_PROMPT_ECHO_ON()) {
3780 print $fh "1 $msg\n";
3783 elsif ($type == PAM_PROMPT_ECHO_OFF()) {
3785 print $fh "3 $msg\n";
3788 elsif ($type == PAM_ERROR_MSG() || $type == PAM_TEXT_INFO()) {
3789 # A message that does not require a response
3790 print $fh "4 $msg\n";
3795 print $fh "0 Unknown PAM message type $type\n";
3801 # send_pam_answer(&conv, answer)
3802 # Sends a response from the user to the PAM sub-process
3805 local ($conf, $answer) = @_;
3806 local $pw = $conf->{'PAMINw'};
3807 $conf->{'last'} = time();
3808 print $pw "$answer\n";
3811 # end_pam_conversation(&conv)
3812 # Clean up PAM conversation pipes and processes
3813 sub end_pam_conversation
3816 kill('KILL', $conv->{'pid'}) if ($conv->{'pid'});
3817 if ($conv->{'PAMINr'}) {
3818 close($conv->{'PAMINr'});
3819 close($conv->{'PAMOUTr'});
3820 close($conv->{'PAMINw'});
3821 close($conv->{'PAMOUTw'});
3823 delete($conversations{$conv->{'cid'}});
3826 # get_ipkeys(&miniserv)
3827 # Returns a list of IP address to key file mappings from a miniserv.conf entry
3831 foreach $k (keys %{$_[0]}) {
3832 if ($k =~ /^ipkey_(\S+)/) {
3833 local $ipkey = { 'ips' => [ split(/,/, $1) ],
3834 'key' => $_[0]->{$k},
3835 'index' => scalar(@rv) };
3836 $ipkey->{'cert'} = $_[0]->{'ipcert_'.$1};
3843 # create_ssl_context(keyfile, [certfile])
3844 sub create_ssl_context
3846 local ($keyfile, $certfile) = @_;
3848 eval { $ssl_ctx = Net::SSLeay::new_x_ctx() };
3849 $ssl_ctx ||= Net::SSLeay::CTX_new();
3850 $ssl_ctx || die "Failed to create SSL context : $!";
3851 if ($client_certs) {
3852 Net::SSLeay::CTX_load_verify_locations(
3853 $ssl_ctx, $config{'ca'}, "");
3854 Net::SSLeay::CTX_set_verify(
3855 $ssl_ctx, &Net::SSLeay::VERIFY_PEER, \&verify_client);
3857 if ($config{'extracas'}) {
3859 foreach $p (split(/\s+/, $config{'extracas'})) {
3860 Net::SSLeay::CTX_load_verify_locations(
3865 Net::SSLeay::CTX_use_RSAPrivateKey_file(
3867 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL key $keyfile";
3868 Net::SSLeay::CTX_use_certificate_file(
3869 $ssl_ctx, $certfile || $keyfile,
3870 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL cert $certfile";
3875 # ssl_connection_for_ip(socket)
3876 # Returns a new SSL connection object for some socket, or undef if failed
3877 sub ssl_connection_for_ip
3880 local $sn = getsockname($sock);
3882 print STDERR "Failed to get address for socket $sock\n";
3885 local $myip = inet_ntoa((unpack_sockaddr_in($sn))[1]);
3886 local $ssl_ctx = $ssl_contexts{$myip} || $ssl_contexts{"*"};
3887 local $ssl_con = Net::SSLeay::new($ssl_ctx);
3888 if ($config{'ssl_cipher_list'}) {
3889 # Force use of ciphers
3890 eval "Net::SSLeay::set_cipher_list(
3891 \$ssl_con, \$config{'ssl_cipher_list'})";
3893 print STDERR "SSL cipher $config{'ssl_cipher_list'} failed : ",
3899 Net::SSLeay::set_fd($ssl_con, fileno($sock));
3900 if (!Net::SSLeay::accept($ssl_con)) {
3901 print STDERR "Failed to initialize SSL connection\n";
3907 # login_redirect(username, password, host)
3908 # Calls the login redirect script (if configured), which may output a URL to
3909 # re-direct a user to after logging in.
3912 return undef if (!$config{'login_redirect'});
3913 local $quser = quotemeta($_[0]);
3914 local $qpass = quotemeta($_[1]);
3915 local $qhost = quotemeta($_[2]);
3916 local $url = `$config{'login_redirect'} $quser $qpass $qhost`;
3921 # reload_config_file()
3922 # Re-read %config, and call post-config actions
3923 sub reload_config_file
3925 &log_error("Reloading configuration");
3926 %config = &read_config_file($config_file);
3927 &update_vital_config();
3930 &build_config_mappings();
3931 &read_webmin_crons();
3932 if ($config{'session'}) {
3933 dbmclose(%sessiondb);
3934 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
3938 # read_config_file(file)
3939 # Reads the given config file, and returns a hash of values
3940 sub read_config_file
3943 open(CONF, $_[0]) || die "Failed to open config file $_[0] : $!";
3946 if (/^#/ || !/\S/) { next; }
3948 $name = $1; $val = $2;
3949 $name =~ s/^\s+//g; $name =~ s/\s+$//g;
3950 $val =~ s/^\s+//g; $val =~ s/\s+$//g;
3957 # update_vital_config()
3958 # Updates %config with defaults, and dies if something vital is missing
3959 sub update_vital_config
3961 my %vital = ("port", 80,
3963 "server", "MiniServ/0.01",
3964 "index_docs", "index.html index.htm index.cgi index.php",
3965 "addtype_html", "text/html",
3966 "addtype_txt", "text/plain",
3967 "addtype_gif", "image/gif",
3968 "addtype_jpg", "image/jpeg",
3969 "addtype_jpeg", "image/jpeg",
3970 "realm", "MiniServ",
3971 "session_login", "/session_login.cgi",
3972 "pam_login", "/pam_login.cgi",
3973 "password_form", "/password_form.cgi",
3974 "password_change", "/password_change.cgi",
3978 "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\$",
3980 "expires", 7*24*60*60,
3981 "pam_test_user", "root",
3983 foreach my $v (keys %vital) {
3985 if ($vital{$v} eq "") {
3986 die "Missing config option $v";
3988 $config{$v} = $vital{$v};
3991 if (!$config{'sessiondb'}) {
3992 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3993 $config{'sessiondb'} = "$1/sessiondb";
3995 if (!$config{'errorlog'}) {
3996 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
3997 $config{'errorlog'} = "$1/miniserv.error";
3999 if (!$config{'tempbase'}) {
4000 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4001 $config{'tempbase'} = "$1/cgitemp";
4003 if (!$config{'blockedfile'}) {
4004 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4005 $config{'blockedfile'} = "$1/blocked";
4007 if (!$config{'webmincron_dir'}) {
4008 $config_file =~ /^(.*)\/[^\/]+$/;
4009 $config{'webmincron_dir'} = "$1/webmincron/crons";
4011 if (!$config{'webmincron_last'}) {
4012 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
4013 $config{'webmincron_last'} = "$1/miniserv.lastcrons";
4015 if (!$config{'webmincron_wrapper'}) {
4016 $config{'webmincron_wrapper'} = $config{'root'}.
4017 "/webmincron/webmincron.pl";
4022 # Fills the %users and %certs hashes from the users file in %config
4031 undef(%lastchanges);
4034 if ($config{'userfile'}) {
4035 open(USERS, $config{'userfile'});
4038 local @user = split(/:/, $_, -1);
4039 $users{$user[0]} = $user[1];
4040 $certs{$user[0]} = $user[3] if ($user[3]);
4041 if ($user[4] =~ /^allow\s+(.*)/) {
4042 $allow{$user[0]} = $config{'alwaysresolve'} ?
4043 [ split(/\s+/, $1) ] :
4044 [ &to_ipaddress(split(/\s+/, $1)) ];
4046 elsif ($user[4] =~ /^deny\s+(.*)/) {
4047 $deny{$user[0]} = $config{'alwaysresolve'} ?
4048 [ split(/\s+/, $1) ] :
4049 [ &to_ipaddress(split(/\s+/, $1)) ];
4051 if ($user[5] =~ /days\s+(\S+)/) {
4052 $allowdays{$user[0]} = [ split(/,/, $1) ];
4054 if ($user[5] =~ /hours\s+(\d+)\.(\d+)-(\d+).(\d+)/) {
4055 $allowhours{$user[0]} = [ $1*60+$2, $3*60+$4 ];
4057 $lastchanges{$user[0]} = $user[6];
4058 $nochange{$user[0]} = $user[9];
4059 $temppass{$user[0]} = $user[10];
4064 # Test user DB, if configured
4065 if ($config{'userdb'}) {
4066 my $dbh = &connect_userdb($config{'userdb'});
4068 print STDERR "Failed to open users database : $dbh\n"
4071 &disconnect_userdb($config{'userdb'}, $dbh);
4076 # get_user_details(username)
4077 # Returns a hash ref of user details, either from config files or the user DB
4078 sub get_user_details
4080 my ($username) = @_;
4081 if (exists($users{$username})) {
4083 return { 'name' => $username,
4084 'pass' => $users{$username},
4085 'certs' => $certs{$username},
4086 'allow' => $allow{$username},
4087 'deny' => $deny{$username},
4088 'allowdays' => $allowdays{$username},
4089 'allowhours' => $allowhours{$username},
4090 'lastchanges' => $lastchanges{$username},
4091 'nochange' => $nochange{$username},
4092 'temppass' => $temppass{$username},
4093 'preroot' => $config{'preroot_'.$username},
4096 if ($config{'userdb'}) {
4097 # Try querying user database
4098 if (exists($get_user_details_cache{$username})) {
4100 return $get_user_details_cache{$username};
4102 print DEBUG "get_user_details: Connecting to user database\n";
4103 my ($dbh, $proto, $prefix, $args) = &connect_userdb($config{'userdb'});
4107 print DEBUG "get_user_details: Failed : $dbh\n";
4108 print STDERR "Failed to connect to user database : $dbh\n";
4110 elsif ($proto eq "mysql" || $proto eq "postgresql") {
4111 # Fetch user ID and password with SQL
4112 print DEBUG "get_user_details: Looking for $username in SQL\n";
4113 my $cmd = $dbh->prepare(
4114 "select id,pass from webmin_user where name = ?");
4115 if (!$cmd || !$cmd->execute($username)) {
4116 print STDERR "Failed to lookup user : ",
4120 my ($id, $pass) = $cmd->fetchrow();
4123 &disconnect_userdb($config{'userdb'}, $dbh);
4124 $get_user_details_cache{$username} = undef;
4125 print DEBUG "get_user_details: User not found\n";
4128 print DEBUG "get_user_details: id=$id pass=$pass\n";
4130 # Fetch attributes and add to user object
4131 print DEBUG "get_user_details: finding user attributes\n";
4132 my $cmd = $dbh->prepare(
4133 "select attr,value from webmin_user_attr where id = ?");
4134 if (!$cmd || !$cmd->execute($id)) {
4135 print STDERR "Failed to lookup user attrs : ",
4139 $user = { 'name' => $username,
4142 'proto' => $proto };
4143 while(my ($attr, $value) = $cmd->fetchrow()) {
4144 $attrs{$attr} = $value;
4148 elsif ($proto eq "ldap") {
4149 # Fetch user DN with LDAP
4150 print DEBUG "get_user_details: Looking for $username in LDAP\n";
4151 my $rv = $dbh->search(
4153 filter => '(&(cn='.$username.')(objectClass='.
4154 $args->{'userclass'}.'))',
4156 if (!$rv || $rv->code) {
4157 print STDERR "Failed to lookup user : ",
4158 ($rv ? $rv->error : "Unknown error"),"\n";
4161 my ($u) = $rv->all_entries();
4163 &disconnect_userdb($config{'userdb'}, $dbh);
4164 $get_user_details_cache{$username} = undef;
4165 print DEBUG "get_user_details: User not found\n";
4169 # Extract attributes
4170 my $pass = $u->get_value('pass');
4171 $user = { 'name' => $username,
4174 'proto' => $proto };
4175 foreach my $la ($u->get_value('webminAttr')) {
4176 my ($attr, $value) = split(/=/, $la, 2);
4177 $attrs{$attr} = $value;
4181 # Convert DB attributes into user object fields
4183 print DEBUG "get_user_details: got ",scalar(keys %attrs),
4185 $user->{'certs'} = $attrs{'cert'};
4186 if ($attrs{'allow'}) {
4187 $user->{'allow'} = $config{'alwaysresolve'} ?
4188 [ split(/\s+/, $attrs{'allow'}) ] :
4189 [ &to_ipaddress(split(/\s+/,$attrs{'allow'})) ];
4191 if ($attrs{'deny'}) {
4192 $user->{'deny'} = $config{'alwaysresolve'} ?
4193 [ split(/\s+/, $attrs{'deny'}) ] :
4194 [ &to_ipaddress(split(/\s+/,$attrs{'deny'})) ];
4196 if ($attrs{'days'}) {
4197 $user->{'allowdays'} = [ split(/,/, $attrs{'days'}) ];
4199 if ($attrs{'hoursfrom'} && $attrs{'hoursto'}) {
4200 my ($hf, $mf) = split(/\./, $attrs{'hoursfrom'});
4201 my ($ht, $mt) = split(/\./, $attrs{'hoursto'});
4202 $user->{'allowhours'} = [ $hf*60+$ht, $ht*60+$mt ];
4204 $user->{'lastchanges'} = $attrs{'lastchange'};
4205 $user->{'nochange'} = $attrs{'nochange'};
4206 $user->{'temppass'} = $attrs{'temppass'};
4207 $user->{'preroot'} = $attrs{'theme'};
4209 &disconnect_userdb($config{'userdb'}, $dbh);
4210 $get_user_details_cache{$user->{'name'}} = $user;
4216 # find_user_by_cert(cert)
4217 # Returns a username looked up by certificate
4218 sub find_user_by_cert
4220 my ($peername) = @_;
4221 my $peername2 = $peername;
4222 $peername2 =~ s/Email=/emailAddress=/ || $peername2 =~ s/emailAddress=/Email=/;
4224 # First check users in local files
4225 foreach my $username (keys %certs) {
4226 if ($certs{$username} eq $peername ||
4227 $certs{$username} eq $peername2) {
4233 if ($config{'userdb'}) {
4234 my ($dbh, $proto) = &connect_userdb($config{'userdb'});
4238 elsif ($proto eq "mysql" || $proto eq "postgresql") {
4240 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 = ?");
4241 return undef if (!$cmd);
4242 foreach my $p ($peername, $peername2) {
4244 if ($cmd->execute($p)) {
4245 ($username) = $cmd->fetchrow();
4248 return $username if ($username);
4251 elsif ($proto eq "ldap") {
4253 my $rv = $dbh->search(
4255 filter => '(objectClass='.
4256 $args->{'userclass'}.')',
4258 attrs => [ 'cn', 'webminAttr' ]);
4259 if ($rv && !$rv->code) {
4260 foreach my $u ($rv->all_entries) {
4261 my @attrs = $u->get_value('webminAttr');
4262 foreach my $la (@attrs) {
4263 my ($attr, $value) = split(/=/, $la, 2);
4264 if ($attr eq "cert" &&
4265 ($value eq $peername ||
4266 $value eq $peername2)) {
4267 return $u->get_value('cn');
4277 # connect_userdb(string)
4278 # Returns a handle for talking to a user database - may be a DBI or LDAP handle.
4279 # On failure returns an error message string. In an array context, returns the
4280 # protocol type too.
4284 my ($proto, $user, $pass, $host, $prefix, $args) = &split_userdb_string($str);
4285 if ($proto eq "mysql") {
4286 # Connect to MySQL with DBI
4287 my $drh = eval "use DBI; DBI->install_driver('mysql');";
4288 $drh || return $text{'sql_emysqldriver'};
4289 my ($host, $port) = split(/:/, $host);
4290 my $cstr = "database=$prefix;host=$host";
4291 $cstr .= ";port=$port" if ($port);
4292 print DEBUG "connect_userdb: Connecting to MySQL $cstr as $user\n";
4293 my $dbh = $drh->connect($cstr, $user, $pass, { });
4294 $dbh || return &text('sql_emysqlconnect', $drh->errstr);
4295 print DEBUG "connect_userdb: Connected OK\n";
4296 return wantarray ? ($dbh, $proto, $prefix, $args) : $dbh;
4298 elsif ($proto eq "postgresql") {
4299 # Connect to PostgreSQL with DBI
4300 my $drh = eval "use DBI; DBI->install_driver('Pg');";
4301 $drh || return $text{'sql_epostgresqldriver'};
4302 my ($host, $port) = split(/:/, $host);
4303 my $cstr = "dbname=$prefix;host=$host";
4304 $cstr .= ";port=$port" if ($port);
4305 print DEBUG "connect_userdb: Connecting to PostgreSQL $cstr as $user\n";
4306 my $dbh = $drh->connect($cstr, $user, $pass);
4307 $dbh || return &text('sql_epostgresqlconnect', $drh->errstr);
4308 print DEBUG "connect_userdb: Connected OK\n";
4309 return wantarray ? ($dbh, $proto, $prefix, $args) : $dbh;
4311 elsif ($proto eq "ldap") {
4312 # Connect with perl LDAP module
4313 eval "use Net::LDAP";
4314 $@ && return $text{'sql_eldapdriver'};
4315 my ($host, $port) = split(/:/, $host);
4316 my $scheme = $args->{'scheme'} || 'ldap';
4318 $port = $scheme eq 'ldaps' ? 636 : 389;
4320 my $ldap = Net::LDAP->new($host,
4322 'scheme' => $scheme);
4323 $ldap || return &text('sql_eldapconnect', $host);
4325 if ($args->{'tls'}) {
4326 # Switch to TLS mode
4327 eval { $mesg = $ldap->start_tls(); };
4328 if ($@ || !$mesg || $mesg->code) {
4329 return &text('sql_eldaptls',
4330 $@ ? $@ : $mesg ? $mesg->error : "Unknown error");
4333 # Login to the server
4335 $mesg = $ldap->bind(dn => $user, password => $pass);
4338 $mesg = $ldap->bind(dn => $user, anonymous => 1);
4340 if (!$mesg || $mesg->code) {
4341 return &text('sql_eldaplogin', $user,
4342 $mesg ? $mesg->error : "Unknown error");
4344 return wantarray ? ($ldap, $proto, $prefix, $args) : $ldap;
4347 return "Unknown protocol $proto";
4351 # split_userdb_string(string)
4352 # Converts a string like mysql://user:pass@host/db into separate parts
4353 sub split_userdb_string
4356 if ($str =~ /^([a-z]+):\/\/([^:]*):([^\@]*)\@([a-z0-9\.\-\_]+)\/([^\?]+)(\?(.*))?$/) {
4357 my ($proto, $user, $pass, $host, $prefix, $argstr) =
4358 ($1, $2, $3, $4, $5, $7);
4359 my %args = map { split(/=/, $_, 2) } split(/\&/, $argstr);
4360 return ($proto, $user, $pass, $host, $prefix, \%args);
4365 # disconnect_userdb(string, &handle)
4366 # Closes a handle opened by connect_userdb
4367 sub disconnect_userdb
4370 if ($str =~ /^(mysql|postgresql):/) {
4374 elsif ($str =~ /^ldap:/) {
4381 # Fills %mime with entries from file in %config and extra settings in %config
4385 if ($config{"mimetypes"} ne "") {
4386 open(MIME, $config{"mimetypes"});
4389 if (/^(\S+)\s+(.*)$/) {
4391 my @exts = split(/\s+/, $2);
4392 foreach my $ext (@exts) {
4393 $mime{$ext} = $type;
4399 foreach my $k (keys %config) {
4400 if ($k !~ /^addtype_(.*)$/) { next; }
4401 $mime{$1} = $config{$k};
4405 # build_config_mappings()
4406 # Build the anonymous access list, IP access list, unauthenticated URLs list,
4407 # redirect mapping and allow and deny lists from %config
4408 sub build_config_mappings
4410 # build anonymous access list
4412 foreach my $a (split(/\s+/, $config{'anonymous'})) {
4413 if ($a =~ /^([^=]+)=(\S+)$/) {
4414 $anonymous{$1} = $2;
4418 # build IP access list
4420 foreach my $a (split(/\s+/, $config{'ipaccess'})) {
4421 if ($a =~ /^([^=]+)=(\S+)$/) {
4426 # build unauthenticated URLs list
4427 @unauth = split(/\s+/, $config{'unauth'});
4429 # build redirect mapping
4431 foreach my $r (split(/\s+/, $config{'redirect'})) {
4432 if ($r =~ /^([^=]+)=(\S+)$/) {
4437 # build prefixes to be stripped
4438 undef(@strip_prefix);
4439 foreach my $r (split(/\s+/, $config{'strip_prefix'})) {
4440 push(@strip_prefix, $r);
4443 # Init allow and deny lists
4444 @deny = split(/\s+/, $config{"deny"});
4445 @deny = &to_ipaddress(@deny) if (!$config{'alwaysresolve'});
4446 @allow = split(/\s+/, $config{"allow"});
4447 @allow = &to_ipaddress(@allow) if (!$config{'alwaysresolve'});
4450 if ($config{'allowusers'}) {
4451 @allowusers = split(/\s+/, $config{'allowusers'});
4453 elsif ($config{'denyusers'}) {
4454 @denyusers = split(/\s+/, $config{'denyusers'});
4457 # Build list of unixauth mappings
4459 foreach my $ua (split(/\s+/, $config{'unixauth'})) {
4460 if ($ua =~ /^(\S+)=(\S+)$/) {
4464 $unixauth{"*"} = $ua;
4468 # Build list of non-session-auth pages
4469 undef(%sessiononly);
4470 foreach my $sp (split(/\s+/, $config{'sessiononly'})) {
4471 $sessiononly{$sp} = 1;
4474 # Build list of logout times
4475 undef(@logouttimes);
4476 foreach my $a (split(/\s+/, $config{'logouttimes'})) {
4477 if ($a =~ /^([^=]+)=(\S+)$/) {
4478 push(@logouttimes, [ $1, $2 ]);
4481 push(@logouttimes, [ undef, $config{'logouttime'} ]);
4483 # Build list of DAV pathss
4485 foreach my $d (split(/\s+/, $config{'davpaths'})) {
4486 push(@davpaths, $d);
4488 @davusers = split(/\s+/, $config{'dav_users'});
4490 # Mobile agent substrings and hostname prefixes
4491 @mobile_agents = split(/\t+/, $config{'mobile_agents'});
4492 @mobile_prefixes = split(/\s+/, $config{'mobile_prefixes'});
4496 if ($config{'debug'}) {
4497 open(DEBUG, ">>$config{'debug'}");
4500 open(DEBUG, ">/dev/null");
4503 # Reset cache of sudo checks
4507 # is_group_member(&uinfo, groupname)
4508 # Returns 1 if some user is a primary or secondary member of a group
4511 local ($uinfo, $group) = @_;
4512 local @ginfo = getgrnam($group);
4513 return 0 if (!@ginfo);
4514 return 1 if ($ginfo[2] == $uinfo->[3]); # primary member
4515 foreach my $m (split(/\s+/, $ginfo[3])) {
4516 return 1 if ($m eq $uinfo->[0]);
4521 # prefix_to_mask(prefix)
4522 # Converts a number like 24 to a mask like 255.255.255.0
4525 return $_[0] >= 24 ? "255.255.255.".(256-(2 ** (32-$_[0]))) :
4526 $_[0] >= 16 ? "255.255.".(256-(2 ** (24-$_[0]))).".0" :
4527 $_[0] >= 8 ? "255.".(256-(2 ** (16-$_[0]))).".0.0" :
4528 (256-(2 ** (8-$_[0]))).".0.0.0";
4531 # get_logout_time(user, session-id)
4532 # Given a username, returns the idle time before he will be logged out
4535 local ($user, $sid) = @_;
4536 if (!defined($logout_time_cache{$user,$sid})) {
4538 foreach my $l (@logouttimes) {
4539 if ($l->[0] =~ /^\@(.*)$/) {
4540 # Check group membership
4541 local @uinfo = getpwnam($user);
4542 if (@uinfo && &is_group_member(\@uinfo, $1)) {
4546 elsif ($l->[0] =~ /^\//) {
4547 # Check file contents
4548 open(FILE, $l->[0]);
4565 if ($l->[0] eq $user) {
4569 last if (defined($time));
4571 $logout_time_cache{$user,$sid} = $time;
4573 return $logout_time_cache{$user,$sid};
4576 # password_crypt(password, salt)
4577 # If the salt looks like MD5 and we have a library for it, perform MD5 hashing
4578 # of a password. Otherwise, do Unix crypt.
4581 local ($pass, $salt) = @_;
4582 if ($salt =~ /^\$1\$/ && $use_md5) {
4583 return &encrypt_md5($pass, $salt);
4586 return &unix_crypt($pass, $salt);
4590 # unix_crypt(password, salt)
4591 # Performs standard Unix hashing for a password
4594 local ($pass, $salt) = @_;
4595 if ($use_perl_crypt) {
4596 return Crypt::UnixCrypt::crypt($pass, $salt);
4599 return crypt($pass, $salt);
4603 # handle_dav_request(davpath)
4604 # Pass a request on to the Net::DAV::Server module
4605 sub handle_dav_request
4608 eval "use Filesys::Virtual::Plain";
4609 eval "use Net::DAV::Server";
4610 eval "use HTTP::Request";
4611 eval "use HTTP::Headers";
4613 if ($Net::DAV::Server::VERSION eq '1.28' && $config{'dav_nolock'}) {
4614 delete $Net::DAV::Server::implemented{lock};
4615 delete $Net::DAV::Server::implemented{unlock};
4618 # Read in request data
4619 if (!$posted_data) {
4620 local $clen = $header{"content-length"};
4621 while(length($posted_data) < $clen) {
4622 $buf = &read_data($clen - length($posted_data));
4623 if (!length($buf)) {
4624 &http_error(500, "Failed to read POST request");
4626 $posted_data .= $buf;
4630 # For subsequent logging
4631 open(MINISERVLOG, ">>$config{'logfile'}");
4635 local @u = getpwnam($authuser);
4636 if ($config{'dav_remoteuser'} && !$< && $validated) {
4639 $( = $u[3]; $) = "$u[3] $u[3]";
4640 ($>, $<) = ($u[2], $u[2]);
4642 if ($config{'dav_root'} eq '*') {
4647 &http_error(500, "Unix user $authuser does not exist");
4651 $root ||= $config{'dav_root'};
4654 # Check if this user can use DAV
4656 &users_match(\@u, @davusers) ||
4657 &http_error(500, "You are not allowed to access DAV");
4661 my $filesys = Filesys::Virtual::Plain->new({root_path => $root});
4662 my $webdav = Net::DAV::Server->new();
4663 $webdav->filesys($filesys);
4665 # Make up a request object, and feed to DAV
4666 local $ho = HTTP::Headers->new;
4667 foreach my $h (keys %header) {
4668 next if (lc($h) eq "connection");
4669 $ho->header($h => $header{$h});
4672 $request_uri =~ s/^\Q$path\E//;
4673 $request_uri = "/" if ($request_uri eq "");
4675 my $request = HTTP::Request->new($method, $request_uri, $ho,
4677 if ($config{'dav_debug'}) {
4678 print STDERR "DAV request :\n";
4679 print STDERR "---------------------------------------------\n";
4680 print STDERR $request->as_string();
4681 print STDERR "---------------------------------------------\n";
4683 my $response = $webdav->run($request);
4685 # Send back the reply
4686 &write_data("HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n");
4687 local $content = $response->content();
4689 $content =~ s|href>/(.+)<|href>$path/$1<|g;
4690 $content =~ s|href>/<|href>$path<|g;
4692 foreach my $h ($response->header_field_names) {
4693 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4694 &write_data("$h: ",$response->header($h),"\r\n");
4696 &write_data("Content-length: ",length($content),"\r\n");
4697 local $rv = &write_keep_alive(0);
4698 &write_data("\r\n");
4699 &write_data($content);
4701 if ($config{'dav_debug'}) {
4702 print STDERR "DAV reply :\n";
4703 print STDERR "---------------------------------------------\n";
4704 print STDERR "HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n";
4705 foreach my $h ($response->header_field_names) {
4706 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4707 print STDERR "$h: ",$response->header($h),"\r\n";
4709 print STDERR "Content-length: ",length($content),"\r\n";
4710 print STDERR "\r\n";
4711 print STDERR $content;
4712 print STDERR "---------------------------------------------\n";
4716 &log_request($acpthost, $authuser, $reqline, $response->code(),
4717 length($response->content()));
4720 # get_system_hostname()
4721 # Returns the hostname of this system, for reporting to listeners
4722 sub get_system_hostname
4724 # On Windows, try computername environment variable
4725 return $ENV{'computername'} if ($ENV{'computername'});
4726 return $ENV{'COMPUTERNAME'} if ($ENV{'COMPUTERNAME'});
4728 # If a specific command is set, use it first
4729 if ($config{'hostname_command'}) {
4730 local $out = `($config{'hostname_command'}) 2>&1`;
4737 # First try the hostname command
4738 local $out = `hostname 2>&1`;
4739 if (!$? && $out =~ /\S/) {
4744 # Try the Sys::Hostname module
4745 eval "use Sys::Hostname";
4747 local $rv = eval "hostname()";
4753 # Must use net name on Windows
4754 local $out = `net name 2>&1`;
4755 if ($out =~ /\-+\r?\n(\S+)/) {
4762 # indexof(string, array)
4763 # Returns the index of some value in an array, or -1
4766 for($i=1; $i <= $#_; $i++) {
4767 if ($_[$i] eq $_[0]) { return $i - 1; }
4773 # has_command(command)
4774 # Returns the full path if some command is in the path, undef if not
4778 if (!$_[0]) { return undef; }
4779 if (exists($has_command_cache{$_[0]})) {
4780 return $has_command_cache{$_[0]};
4783 if ($_[0] =~ /^\//) {
4784 $rv = -x $_[0] ? $_[0] : undef;
4787 local $sp = $on_windows ? ';' : ':';
4788 foreach $d (split($sp, $ENV{PATH})) {
4789 if (-x "$d/$_[0]") {
4794 foreach my $sfx (".exe", ".com", ".bat") {
4795 if (-r "$d/$_[0]".$sfx) {
4796 $rv = "$d/$_[0]".$sfx;
4803 $has_command_cache{$_[0]} = $rv;
4807 # check_sudo_permissions(user, pass)
4808 # Returns 1 if some user can run any command via sudo
4809 sub check_sudo_permissions
4811 local ($user, $pass) = @_;
4813 # First try the pipes
4815 print DEBUG "check_sudo_permissions: querying cache for $user\n";
4816 print $PASSINw "readsudo $user\n";
4817 local $can = <$PASSOUTr>;
4819 print DEBUG "check_sudo_permissions: cache said $can\n";
4820 if ($can =~ /^\d+$/ && $can != 2) {
4825 local $ptyfh = new IO::Pty;
4826 print DEBUG "check_sudo_permissions: ptyfh=$ptyfh\n";
4828 print STDERR "Failed to create new PTY with IO::Pty\n";
4831 local @uinfo = getpwnam($user);
4833 print STDERR "Unix user $user does not exist for sudo\n";
4837 # Execute sudo in a sub-process, via a pty
4838 local $ttyfh = $ptyfh->slave();
4839 print DEBUG "check_sudo_permissions: ttyfh=$ttyfh\n";
4840 local $tty = $ptyfh->ttyname();
4841 print DEBUG "check_sudo_permissions: tty=$tty\n";
4842 chown($uinfo[2], $uinfo[3], $tty);
4844 print DEBUG "check_sudo_permissions: about to fork..\n";
4845 local $pid = fork();
4846 print DEBUG "check_sudo_permissions: fork=$pid pid=$$\n";
4848 print STDERR "fork for sudo failed : $!\n";
4853 $ptyfh->make_slave_controlling_terminal();
4854 close(STDIN); close(STDOUT); close(STDERR);
4855 untie(*STDIN); untie(*STDOUT); untie(*STDERR);
4856 close($PASSINw); close($PASSOUTr);
4857 $( = $uinfo[3]; $) = "$uinfo[3] $uinfo[3]";
4858 ($>, $<) = ($uinfo[2], $uinfo[2]);
4863 open(STDIN, "<&SUDOr");
4864 open(STDOUT, ">$tty");
4865 open(STDERR, ">&STDOUT");
4868 print "Exec failed : $!\n";
4871 print DEBUG "check_sudo_permissions: pid=$pid\n";
4873 $ptyfh->close_slave();
4875 # Send password, and get back response
4876 local $oldfh = select(SUDOw);
4879 print DEBUG "check_sudo_permissions: about to send pass\n";
4880 local $SIG{'PIPE'} = 'ignore'; # Sometimes sudo doesn't ask for a password
4881 print SUDOw $pass,"\n";
4882 print DEBUG "check_sudo_permissions: sent pass=$pass\n";
4886 print DEBUG "check_sudo_permissions: got $_";
4892 local ($ok) = ($out =~ /\(ALL\)\s+ALL/ ? 1 : 0);
4896 print $PASSINw "writesudo $user $ok\n";
4902 # is_mobile_useragent(agent)
4903 # Returns 1 if some user agent looks like a cellphone or other mobile device,
4905 sub is_mobile_useragent
4907 local ($agent) = @_;
4909 "UP.Link", # Openwave
4910 "Nokia", # All Nokias start with Nokia
4911 "MOT-", # All Motorola phones start with MOT-
4912 "SAMSUNG", # Samsung browsers
4913 "Samsung", # Samsung browsers
4914 "SEC-", # Samsung browsers
4915 "AU-MIC", # Samsung browsers
4916 "AUDIOVOX", # Audiovox
4917 "BlackBerry", # BlackBerry
4918 "hiptop", # Danger hiptop Sidekick
4919 "SonyEricsson", # Sony Ericsson
4920 "Ericsson", # Old Ericsson browsers , mostly WAP
4921 "Mitsu/1.1.A", # Mitsubishi phones
4922 "Panasonic WAP", # Panasonic old WAP phones
4923 "DoCoMo", # DoCoMo phones
4924 "Lynx", # Lynx text-mode linux browser
4925 "Links", # Another text-mode linux browser
4927 local @substrings = (
4928 "UP.Browser", # Openwave
4929 "MobilePhone", # NetFront
4930 "AU-MIC-A700", # Samsung A700 Obigo browsers
4931 "Danger hiptop", # Danger Sidekick hiptop
4932 "Windows CE", # Windows CE Pocket PC
4933 "IEMobile", # Windows mobile browser
4934 "Blazer", # Palm Treo Blazer
4935 "BlackBerry", # BlackBerries can emulate other browsers, but
4936 # they still keep this string in the UserAgent
4937 "SymbianOS", # New Series60 browser has safari in it and
4938 # SymbianOS is the only distinguishing string
4939 "iPhone", # Apple iPhone KHTML browser
4940 "iPod", # iPod touch browser
4941 "MobileSafari", # HTTP client in iPhone
4943 "Opera Mini", # Opera Mini
4944 "HTC_P3700", # HTC mobile device
4946 "webOS/", # Palm WebOS
4947 "Nintendo DS", # DSi / DSi-XL
4949 foreach my $p (@prefixes) {
4950 return 1 if ($agent =~ /^\Q$p\E/);
4952 foreach my $s (@substrings, @mobile_agents) {
4953 return 1 if ($agent =~ /\Q$s\E/);
4958 # write_blocked_file()
4959 # Writes out a text file of blocked hosts and users
4960 sub write_blocked_file
4962 open(BLOCKED, ">$config{'blockedfile'}");
4963 foreach my $d (grep { $hostfail{$_} } @deny) {
4964 print BLOCKED "host $d $hostfail{$d} $blockhosttime{$d}\n";
4966 foreach my $d (grep { $userfail{$_} } @denyusers) {
4967 print BLOCKED "user $d $userfail{$d} $blockusertime{$d}\n";
4970 chmod(0700, $config{'blockedfile'});
4975 open(PIDFILE, ">$config{'pidfile'}");
4976 printf PIDFILE "%d\n", getpid();
4978 $miniserv_main_pid = getpid();
4981 # lock_user_password(user)
4982 # Updates a user's password file entry to lock it, both in memory and on disk.
4983 # Returns 1 if done, -1 if no such user, 0 if already locked
4984 sub lock_user_password
4987 local $uinfo = &get_user_details($user);
4992 if ($uinfo->{'pass'} =~ /^\!/) {
4996 if (!$uinfo->{'proto'}) {
4997 # Write to users file
4998 $users{$user} = "!".$users{$user};
4999 open(USERS, $config{'userfile'});
5000 local @ufile = <USERS>;
5002 foreach my $u (@ufile) {
5003 local @uinfo = split(/:/, $u);
5004 if ($uinfo[0] eq $user) {
5005 $uinfo[1] = $users{$user};
5007 $u = join(":", @uinfo);
5009 open(USERS, ">$config{'userfile'}");
5015 if ($config{'userdb'}) {
5017 my ($dbh, $proto, $prefix, $args) = &connect_userdb($config{'userdb'});
5021 elsif ($proto eq "mysql" || $proto eq "postgresql") {
5022 # Update user attribute
5023 my $cmd = $dbh->prepare(
5024 "update webmin_user set pass = ? where id = ?");
5025 if (!$cmd || !$cmd->execute("!".$uinfo->{'pass'},
5028 print STDERR "Failed to lock password : ",
5032 $cmd->finish() if ($cmd);
5034 elsif ($proto eq "ldap") {
5035 # Update LDAP object
5036 my $rv = $dbh->modify($uinfo->{'id'},
5037 replace => { 'webminPass' => '!'.$uinfo->{'pass'} });
5038 if (!$rv || $rv->code) {
5039 print STDERR "Failed to lock password : ",
5040 ($rv ? $rv->error : "Unknown error"),"\n";
5044 &disconnect_userdb($config{'userdb'}, $dbh);
5048 return -1; # This should never be reached
5051 # hash_session_id(sid)
5052 # Returns an MD5 or Unix-crypted session ID
5056 if (!$hash_session_id_cache{$sid}) {
5059 $hash_session_id_cache{$sid} = &encrypt_md5($sid);
5063 $hash_session_id_cache{$sid} = &unix_crypt($sid, "XX");
5066 return $hash_session_id_cache{$sid};
5069 # encrypt_md5(string, [salt])
5070 # Returns a string encrypted in MD5 format
5073 local ($passwd, $salt) = @_;
5074 local $magic = '$1$';
5075 if ($salt =~ /^\$1\$([^\$]+)/) {
5076 # Extract actual salt from already encrypted password
5081 local $ctx = eval "new $use_md5";
5088 # Add some more stuff from the hash of the password and salt
5089 local $ctx1 = eval "new $use_md5";
5090 $ctx1->add($passwd);
5094 $ctx1->add($passwd);
5095 local $final = $ctx1->digest();
5096 for($pl=length($passwd); $pl>0; $pl-=16) {
5097 $ctx->add($pl > 16 ? $final : substr($final, 0, $pl));
5100 # This piece of code seems rather pointless, but it's in the C code that
5101 # does MD5 in PAM so it has to go in!
5104 for($i=length($passwd); $i; $i >>= 1) {
5109 $ctx->add(substr($passwd, $j, 1));
5112 $final = $ctx->digest();
5115 # This loop exists only to waste time
5116 for($i=0; $i<1000; $i++) {
5117 $ctx1 = eval "new $use_md5";
5118 $ctx1->add($i & 1 ? $passwd : $final);
5119 $ctx1->add($salt) if ($i % 3);
5120 $ctx1->add($passwd) if ($i % 7);
5121 $ctx1->add($i & 1 ? $final : $passwd);
5122 $final = $ctx1->digest();
5126 # Convert the 16-byte final string into a readable form
5128 local @final = map { ord($_) } split(//, $final);
5129 $l = ($final[ 0]<<16) + ($final[ 6]<<8) + $final[12];
5130 $rv .= &to64($l, 4);
5131 $l = ($final[ 1]<<16) + ($final[ 7]<<8) + $final[13];
5132 $rv .= &to64($l, 4);
5133 $l = ($final[ 2]<<16) + ($final[ 8]<<8) + $final[14];
5134 $rv .= &to64($l, 4);
5135 $l = ($final[ 3]<<16) + ($final[ 9]<<8) + $final[15];
5136 $rv .= &to64($l, 4);
5137 $l = ($final[ 4]<<16) + ($final[10]<<8) + $final[ 5];
5138 $rv .= &to64($l, 4);
5140 $rv .= &to64($l, 2);
5142 # Add salt if needed
5144 return $magic.$salt.'$'.$rv;
5153 local ($v, $n) = @_;
5156 $r .= $itoa64[$v & 0x3f];
5162 # read_file(file, &assoc, [&order], [lowercase])
5163 # Fill an associative array with name=value pairs from a file
5166 open(ARFILE, $_[0]) || return 0;
5169 if (!/^#/ && /^([^=]*)=(.*)$/) {
5170 $_[1]->{$_[3] ? lc($1) : $1} = $2;
5171 push(@{$_[2]}, $1) if ($_[2]);
5178 # write_file(file, array)
5179 # Write out the contents of an associative array as name=value lines
5182 local(%old, @order);
5183 &read_file($_[0], \%old, \@order);
5184 open(ARFILE, ">$_[0]");
5185 foreach $k (@order) {
5186 print ARFILE $k,"=",$_[1]->{$k},"\n" if (exists($_[1]->{$k}));
5188 foreach $k (keys %{$_[1]}) {
5189 print ARFILE $k,"=",$_[1]->{$k},"\n" if (!exists($old{$k}));
5194 # execute_ready_webmin_crons()
5195 # Find and run any cron jobs that are due, based on their last run time and
5196 # execution interval
5197 sub execute_ready_webmin_crons
5201 foreach my $cron (@webmincrons) {
5203 if (!$webmincron_last{$cron->{'id'}}) {
5204 # If not ever run before, don't run right away
5205 $webmincron_last{$cron->{'id'}} = $now;
5208 elsif ($cron->{'interval'} &&
5209 $now - $webmincron_last{$cron->{'id'}} > $cron->{'interval'}) {
5210 # Older than interval .. time to run
5213 elsif ($cron->{'mins'}) {
5214 # Check if current time matches spec, and we haven't run in the
5216 my @tm = localtime($now);
5217 if (&matches_cron($cron->{'mins'}, $tm[1]) &&
5218 &matches_cron($cron->{'hours'}, $tm[2]) &&
5219 &matches_cron($cron->{'days'}, $tm[3]) &&
5220 &matches_cron($cron->{'months'}, $tm[4]+1) &&
5221 &matches_cron($cron->{'weekdays'}, $tm[6]) &&
5222 $now - $webmincron_last{$cron->{'id'}} > 60) {
5228 print DEBUG "Running cron id=$cron->{'id'} ".
5229 "module=$cron->{'module'} func=$cron->{'func'}\n";
5230 $webmincron_last{$cron->{'id'}} = $now;
5234 # Run via a wrapper command, which we run like a CGI
5236 # Setup CGI-like environment
5237 $envtz = $ENV{"TZ"};
5238 $envuser = $ENV{"USER"};
5239 $envpath = $ENV{"PATH"};
5240 $envlang = $ENV{"LANG"};
5241 $envroot = $ENV{"SystemRoot"};
5242 $envperllib = $ENV{'PERLLIB'};
5243 foreach my $k (keys %ENV) {
5246 $ENV{"PATH"} = $envpath if ($envpath);
5247 $ENV{"TZ"} = $envtz if ($envtz);
5248 $ENV{"USER"} = $envuser if ($envuser);
5249 $ENV{"OLD_LANG"} = $envlang if ($envlang);
5250 $ENV{"SystemRoot"} = $envroot if ($envroot);
5251 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
5252 $ENV{"HOME"} = $user_homedir;
5253 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
5254 $ENV{"SERVER_ADMIN"} = $config{"email"};
5256 $ENV{"SERVER_ROOT"} = $root0;
5257 $ENV{"SERVER_REALROOT"} = $root0;
5258 $ENV{"SERVER_PORT"} = $config{'port'};
5259 $ENV{"WEBMIN_CRON"} = 1;
5260 $ENV{"DOCUMENT_ROOT"} = $root0;
5261 $ENV{"DOCUMENT_REALROOT"} = $root0;
5262 $ENV{"MINISERV_CONFIG"} = $config_file;
5263 $ENV{"HTTPS"} = "ON" if ($use_ssl);
5264 $ENV{"MINISERV_PID"} = $miniserv_main_pid;
5265 $ENV{"SCRIPT_FILENAME"} = $config{'webmincron_wrapper'};
5266 if ($ENV{"SCRIPT_FILENAME"} =~ /^\Q$root0\E(\/.*)$/) {
5267 $ENV{"SCRIPT_NAME"} = $1;
5269 $config{'webmincron_wrapper'} =~ /^(.*)\//;
5271 foreach $k (keys %config) {
5272 if ($k =~ /^env_(\S+)$/) {
5273 $ENV{$1} = $config{$k};
5277 $SIG{'CHLD'} = 'DEFAULT';
5279 # Have SOCK closed if the perl exec's something
5281 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
5284 # Run the wrapper script by evaling it
5285 $pkg = "webmincron";
5286 $0 = $config{'webmincron_wrapper'};
5288 $main_process_id = $$;
5292 do \$miniserv::config{'webmincron_wrapper'};
5296 print STDERR "Perl cron failure : $@\n";
5301 push(@childpids, $pid);
5305 # Write out file containing last run times
5306 &write_file($config{'webmincron_last'}, \%webmincron_last);
5310 # matches_cron(cron-spec, time)
5311 # Checks if some minute or hour matches some cron spec, which can be * or a list
5315 my ($spec, $tm) = @_;
5320 foreach my $s (split(/,/, $spec)) {
5322 $s =~ /^(\d+)\-(\d+)$/ && $tm >= $1 && $tm <= $2) {
5330 # read_webmin_crons()
5331 # Read all scheduled webmin cron functions and store them in the @webmincrons
5333 sub read_webmin_crons
5336 opendir(CRONS, $config{'webmincron_dir'});
5337 print DEBUG "Reading crons from $config{'webmincron_dir'}\n";
5338 foreach my $f (readdir(CRONS)) {
5339 if ($f =~ /^(\d+)\.cron$/) {
5341 &read_file("$config{'webmincron_dir'}/$f", \%cron);
5344 foreach my $n ('module', 'func') {
5346 print STDERR "Cron $1 missing $n\n";
5350 if (!$cron{'interval'} && !$cron{'mins'} && !$cron{'special'}) {
5351 print STDERR "Cron $1 missing any time spec\n";
5354 if ($cron{'special'} eq 'hourly') {
5355 # Run every hour on the hour
5357 $cron{'hours'} = '*';
5358 $cron{'days'} = '*';
5359 $cron{'months'} = '*';
5360 $cron{'weekdays'} = '*';
5362 elsif ($cron{'special'} eq 'daily') {
5363 # Run every day at midnight
5365 $cron{'hours'} = '0';
5366 $cron{'days'} = '*';
5367 $cron{'months'} = '*';
5368 $cron{'weekdays'} = '*';
5370 elsif ($cron{'special'} eq 'monthly') {
5371 # Run every month on the 1st
5373 $cron{'hours'} = '0';
5374 $cron{'days'} = '1';
5375 $cron{'months'} = '*';
5376 $cron{'weekdays'} = '*';
5378 elsif ($cron{'special'} eq 'weekly') {
5379 # Run every month on the 1st
5381 $cron{'hours'} = '0';
5382 $cron{'days'} = '*';
5383 $cron{'months'} = '*';
5384 $cron{'weekdays'} = '0';
5386 elsif ($cron{'special'} eq 'yearly' ||
5387 $cron{'special'} eq 'annually') {
5388 # Run every year on 1st january
5390 $cron{'hours'} = '0';
5391 $cron{'days'} = '1';
5392 $cron{'months'} = '1';
5393 $cron{'weekdays'} = '*';
5395 elsif ($cron{'special'}) {
5396 print STDERR "Cron $1 invalid special time $cron{'special'}\n";
5399 if ($cron{'special'}) {
5400 delete($cron{'special'});
5403 print DEBUG "adding cron id=$cron{'id'} module=$cron{'module'} func=$cron{'func'}\n";
5404 push(@webmincrons, \%cron);