2 # A very simple perl web server used by Webmin
4 # Require basic libraries
10 @itoa64 = split(//, "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
12 # Find and read config file
14 die "Usage: miniserv.pl <config file>";
16 if ($ARGV[0] =~ /^([a-z]:)?\//i) {
17 $config_file = $ARGV[0];
21 $config_file = "$pwd/$ARGV[0]";
23 %config = &read_config_file($config_file);
24 if ($config{'perllib'}) {
25 push(@INC, split(/:/, $config{'perllib'}));
26 $ENV{'PERLLIB'} .= ':'.$config{'perllib'};
30 # Check if SSL is enabled and available
32 eval "use Net::SSLeay";
35 # These functions only exist for SSLeay 1.0
36 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
37 eval "Net::SSLeay::load_error_strings()";
38 if ($config{'no_ssl2'}) {
39 eval "Net::SSLeay::CTX_set_options($ctx,&Net::SSLeay::OP_NO_SSLv2)";
41 if (defined(&Net::SSLeay::X509_STORE_CTX_get_current_cert) &&
42 defined(&Net::SSLeay::CTX_load_verify_locations) &&
43 defined(&Net::SSLeay::CTX_set_verify)) {
49 # Check if IPv6 is enabled and available
50 if ($config{'ipv6'}) {
53 push(@startup_msg, "IPv6 support enabled");
57 push(@startup_msg, "IPv6 support cannot be enabled without ".
58 "the Socket6 perl module");
62 # Check if the syslog module is available to log hacking attempts
63 if ($config{'syslog'} && !$config{'inetd'}) {
64 eval "use Sys::Syslog qw(:DEFAULT setlogsock)";
70 # check if the TCP-wrappers module is available
71 if ($config{'libwrap'}) {
72 eval "use Authen::Libwrap qw(hosts_ctl STRING_UNKNOWN)";
78 # Check if the MD5 perl module is available
84 eval "use Digest::MD5";
86 $use_md5 = "Digest::MD5";
90 # Get miniserv's perl path and location
92 open(SOURCE, $miniserv_path);
93 <SOURCE> =~ /^#!(\S+)/;
100 $linked_perl_path = readlink($perl_path);
102 @miniserv_argv = @ARGV;
104 # Check vital config options
105 &update_vital_config();
107 $sidname = $config{'sidname'};
108 die "Session authentication cannot be used in inetd mode"
109 if ($config{'inetd'} && $config{'session'});
111 # check if the PAM module is available to authenticate
112 if ($config{'assume_pam'}) {
113 # Just assume that it will work. This can also be used to work around
114 # a Solaris bug in which using PAM before forking caused it to fail
118 elsif (!$config{'no_pam'}) {
119 eval "use Authen::PAM;";
121 # check if the PAM authentication can be used by opening a
124 if (ref($pamh = new Authen::PAM($config{'pam'},
125 $config{'pam_test_user'},
127 # Now test a login to see if /etc/pam.d/webmin is set
129 $pam_conv_func_called = 0;
130 $pam_username = "test";
131 $pam_password = "test";
132 $pamh->pam_authenticate();
133 if ($pam_conv_func_called) {
135 "PAM authentication enabled");
140 "PAM test failed - maybe ".
141 "/etc/pam.d/$config{'pam'} does not exist");
146 "PAM initialization of Authen::PAM failed");
151 "Perl module Authen::PAM needed for PAM is ".
152 "not installed : $@");
155 if ($config{'pam_only'} && !$use_pam) {
156 print STDERR $startup_msg[0],"\n";
157 print STDERR "PAM use is mandatory, but could not be enabled!\n";
160 elsif ($pam_msg && !$use_pam) {
162 "Continuing without the Authen::PAM perl module");
165 # Check if the User::Utmp perl module is installed
166 if ($config{'utmp'}) {
167 eval "use User::Utmp;";
170 push(@startup_msg, "UTMP logging enabled");
174 "Perl module User::Utmp needed for Utmp logging is ".
175 "not installed : $@");
179 # See if the crypt function fails
180 eval "crypt('foo', 'xx')";
182 eval "use Crypt::UnixCrypt";
186 "Using Crypt::UnixCrypt for password encryption");
190 "crypt() function un-implemented, and Crypt::UnixCrypt ".
191 "not installed - password authentication will fail");
195 # Check if /dev/urandom really generates random IDs, by calling it twice
196 local $rand1 = &generate_random_id("foo", 1);
197 local $rand2 = &generate_random_id("foo", 2);
198 if ($rand1 eq $rand2) {
201 "Random number generator file /dev/urandom is not reliable");
204 # Check if we can call sudo
205 if ($config{'sudo'} && &has_command("sudo")) {
212 "Perl module IO::Pty needed for calling sudo is not ".
217 # init days and months for http_date
218 @weekday = ( "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" );
219 @month = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun",
220 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" );
222 # Change dir to the server root
223 @roots = ( $config{'root'} );
224 for($i=0; defined($config{"extraroot_$i"}); $i++) {
225 push(@roots, $config{"extraroot_$i"});
228 eval { $user_homedir = (getpwuid($<))[7]; };
230 # getpwuid doesn't work on windows
231 $user_homedir = $ENV{"HOME"} || $ENV{"USERPROFILE"} || "/";
238 # Setup SSL if possible and if requested
239 if (!-r $config{'keyfile'} ||
240 $config{'certfile'} && !-r $config{'certfile'}) {
241 # Key file doesn't exist!
244 @ipkeys = &get_ipkeys(\%config);
246 if ($config{'ssl_version'}) {
247 # Force an SSL version
248 $Net::SSLeay::version = $config{'ssl_version'};
249 $Net::SSLeay::ssl_version = $config{'ssl_version'};
251 $client_certs = 0 if (!-r $config{'ca'} || !%certs);
252 $ssl_contexts{"*"} = &create_ssl_context($config{'keyfile'},
253 $config{'certfile'});
254 foreach $ipkey (@ipkeys) {
255 $ctx = &create_ssl_context($ipkey->{'key'}, $ipkey->{'cert'});
256 foreach $ip (@{$ipkey->{'ips'}}) {
257 $ssl_contexts{$ip} = $ctx;
262 # Setup syslog support if possible and if requested
264 open(ERRDUP, ">&STDERR");
265 open(STDERR, ">/dev/null");
266 $log_socket = $config{"logsock"} || "unix";
267 eval 'openlog($config{"pam"}, "cons,pid,ndelay", "authpriv"); setlogsock($log_socket)';
272 local $msg = ucfirst($config{'pam'})." starting";
273 eval { syslog("info", "%s", $msg); };
277 syslog("info", "%s", $msg);
280 # All attempts to use syslog have failed..
285 open(STDERR, ">&ERRDUP");
289 # Read MIME types file and add extra types
293 if ($config{'log'}) {
294 local(@gmt, @lct, $days, $hours, $mins);
295 @gmt = gmtime(time());
296 @lct = localtime(time());
297 $days = $lct[3] - $gmt[3];
298 $hours = ($days < -1 ? 24 : 1 < $days ? -24 : $days * 24) +
300 $mins = $hours * 60 + $lct[1] - $gmt[1];
301 $timezone = ($mins < 0 ? "-" : "+"); $mins = abs($mins);
302 $timezone .= sprintf "%2.2d%2.2d", $mins/60, $mins%60;
305 # Build various maps from the config files
306 &build_config_mappings();
308 # start up external authentication program, if needed
309 if ($config{'extauth'}) {
310 socketpair(EXTAUTH, EXTAUTH2, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
311 if (!($extauth = fork())) {
315 open(STDIN, "<&EXTAUTH2");
316 open(STDOUT, ">&EXTAUTH2");
317 exec($config{'extauth'}) or die "exec failed : $!\n";
320 local $os = select(EXTAUTH);
324 # Pre-load any libraries
325 if (!$config{'inetd'}) {
326 foreach $pl (split(/\s+/, $config{'preload'})) {
327 ($pkg, $lib) = split(/=/, $pl);
328 $pkg =~ s/[^A-Za-z0-9]/_/g;
329 eval "package $pkg; do '$config{'root'}/$lib'";
331 print STDERR "Failed to pre-load $lib in $pkg : $@\n";
334 print STDERR "Pre-loaded $lib in $pkg\n";
337 foreach $pl (split(/\s+/, $config{'premodules'})) {
339 ($dir, $mod) = split(/\//, $pl);
342 ($dir, $mod) = (undef, $pl);
344 push(@INC, "$config{'root'}/$dir");
345 eval "package $mod; use $mod ()";
347 print STDERR "Failed to pre-load $mod : $@\n";
350 print STDERR "Pre-loaded $mod\n";
355 # Open debug log if set
356 if ($config{'debuglog'}) {
357 open(DEBUG, ">>$config{'debuglog'}");
358 chmod(0700, $config{'debuglog'});
359 select(DEBUG); $| = 1; select(STDOUT);
360 print DEBUG "miniserv.pl starting ..\n";
363 # Write out (empty) blocked hosts file
364 &write_blocked_file();
366 # Initially read webmin cron functions and last execution times
367 &read_webmin_crons();
368 %webmincron_last = ( );
369 &read_file($config{'webmincron_last'}, \%webmincron_last);
371 # Re-direct STDERR to a log file
372 if ($config{'errorlog'} ne '-') {
373 open(STDERR, ">>$config{'errorlog'}") || die "failed to open $config{'errorlog'} : $!";
374 if ($config{'logperms'}) {
375 chmod(oct($config{'logperms'}), $config{'errorlog'});
378 select(STDERR); $| = 1; select(STDOUT);
380 if ($config{'inetd'}) {
381 # We are being run from inetd - go direct to handling the request
382 $SIG{'HUP'} = 'IGNORE';
383 $SIG{'TERM'} = 'DEFAULT';
384 $SIG{'PIPE'} = 'DEFAULT';
385 open(SOCK, "+>&STDIN");
387 # Check if it is time for the logfile to be cleared
388 if ($config{'logclear'}) {
389 local $write_logtime = 0;
390 local @st = stat("$config{'logfile'}.time");
392 if ($st[9]+$config{'logtime'}*60*60 < time()){
395 unlink($config{'logfile'});
398 else { $write_logtime = 1; }
399 if ($write_logtime) {
400 open(LOGTIME, ">$config{'logfile'}.time");
401 print LOGTIME time(),"\n";
406 # Initialize SSL for this connection
408 $ssl_con = &ssl_connection_for_ip(SOCK);
412 # Work out the hostname for this web server
413 $host = &get_socket_name(SOCK);
415 $port = $config{'port'};
416 $acptaddr = getpeername(SOCK);
419 print DEBUG "main: Starting handle_request loop pid=$$\n";
420 while(&handle_request($acptaddr, getsockname(SOCK))) { }
421 print DEBUG "main: Done handle_request loop pid=$$\n";
426 # Build list of sockets to listen on
427 if ($config{"bind"} && $config{"bind"} ne "*") {
428 push(@sockets, [ inet_aton($config{'bind'}), $config{'port'},
433 # XXX v6 support - why can't listen on port 10000 on both protos?
434 push(@sockets, [ INADDR_ANY, $config{'port'}, PF_INET ]);
436 #push(@sockets, [ in6addr_any(), $config{'port'},
437 # Socket6::PF_INET6() ]);
440 foreach $s (split(/\s+/, $config{'sockets'})) {
441 if ($s =~ /^(\d+)$/) {
442 # Just listen on another port on the main IP
444 push(@sockets, [ $sockets[0]->[0], $s, $sockets[0]->[2] ]);
446 elsif ($s =~ /^([0-9\.]+):(\d+)$/) {
447 # Listen on a specific port and IP
449 push(@sockets, [ $1 eq "*" ? INADDR_ANY : inet_aton($1), $2,
452 elsif ($s =~ /^([0-9\.]+):\*$/ || $s =~ /^([0-9\.]+)$/) {
453 # Listen on the main port on another IPv4 address
454 push(@sockets, [ inet_aton($1), $sockets[0]->[1],
457 elsif (($s =~ /^([0-9a-f\:]+):\*$/ || $s =~ /^([0-9a-f\:]+)$/) &&
459 # Listen on the main port on another IPv6 address
460 push(@sockets, [ inet_pton(Socket6::AF_INET6(), $1),
462 Socket6::PF_INET6() ]);
466 # Open all the sockets
467 $proto = getprotobyname('tcp');
469 $tried_inaddr_any = 0;
470 for($i=0; $i<@sockets; $i++) {
471 print STDERR "socket=",join(" ", @{$sockets[$i]}),"\n";
473 socket($fh, $sockets[$i]->[2], SOCK_STREAM, $proto) ||
474 die "Failed to open socket family $sockets[$i]->[2] : $!";
475 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
476 $pack = $sockets[$i]->[2] eq PF_INET ?
477 pack_sockaddr_in($sockets[$i]->[1],
479 pack_sockaddr_in6($sockets[$i]->[1],
481 for($j=0; $j<5; $j++) {
482 last if (bind($fh, $pack));
486 # All attempts failed .. give up
487 if ($sockets[$i]->[0] eq INADDR_ANY ||
488 $use_ipv6 && $sockets[$i]->[0] eq in6addr_any()) {
490 "Failed to bind to port $sockets[$i]->[1] : $!");
491 $tried_inaddr_any = 1;
494 $ip = &network_to_address($sockets[$i]->[0]);
496 "Failed to bind to IP $ip port ".
497 "$sockets[$i]->[1] : $!");
501 listen($fh, SOMAXCONN);
502 push(@socketfhs, $fh);
505 foreach $se (@sockerrs) {
506 print STDERR $se,"\n";
509 # If all binds failed, try binding to any address
510 if (!@socketfhs && !$tried_inaddr_any) {
511 print STDERR "Falling back to listening on any address\n";
513 socket($fh, PF_INET, SOCK_STREAM, $proto) ||
514 die "Failed to open socket : $!";
515 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
516 bind($fh, pack_sockaddr_in($sockets[0]->[1], INADDR_ANY)) ||
517 die "Failed to bind to port $sockets[0]->[1] : $!";
518 listen($fh, SOMAXCONN);
519 push(@socketfhs, $fh);
521 elsif (!@socketfhs && $tried_inaddr_any) {
522 die "Could not listen on any ports";
525 if ($config{'listen'}) {
526 # Open the socket that allows other webmin servers to find this one
527 $proto = getprotobyname('udp');
528 if (socket(LISTEN, PF_INET, SOCK_DGRAM, $proto)) {
529 setsockopt(LISTEN, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
530 bind(LISTEN, pack_sockaddr_in($config{'listen'}, INADDR_ANY));
531 listen(LISTEN, SOMAXCONN);
534 $config{'listen'} = 0;
538 # Split from the controlling terminal, unless configured not to
539 if (!$config{'nofork'}) {
540 if (fork()) { exit; }
542 eval { setsid(); }; # may not work on Windows
544 # Close standard file handles
545 open(STDIN, "</dev/null");
546 open(STDOUT, ">/dev/null");
547 &log_error("miniserv.pl started");
548 foreach $msg (@startup_msg) {
552 # write out the PID file
555 # Start the log-clearing process, if needed. This checks every minute
556 # to see if the log has passed its reset time, and if so clears it
557 if ($config{'logclear'}) {
558 if (!($logclearer = fork())) {
559 &close_all_sockets();
562 local $write_logtime = 0;
563 local @st = stat("$config{'logfile'}.time");
565 if ($st[9]+$config{'logtime'}*60*60 < time()){
568 unlink($config{'logfile'});
571 else { $write_logtime = 1; }
572 if ($write_logtime) {
573 open(LOGTIME, ">$config{'logfile'}.time");
574 print LOGTIME time(),"\n";
581 push(@childpids, $logclearer);
584 # Setup the logout time dbm if needed
585 if ($config{'session'}) {
586 eval "use SDBM_File";
587 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
588 eval "\$sessiondb{'1111111111'} = 'foo bar';";
590 dbmclose(%sessiondb);
591 eval "use NDBM_File";
592 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
595 delete($sessiondb{'1111111111'});
600 $SIG{'HUP'} = 'miniserv::trigger_restart';
601 $SIG{'TERM'} = 'miniserv::term_handler';
602 $SIG{'USR1'} = 'miniserv::trigger_reload';
603 $SIG{'PIPE'} = 'IGNORE';
604 local $remove_session_count = 0;
605 $need_pipes = $config{'passdelay'} || $config{'session'};
607 # wait for a new connection, or a message from a child process
609 if (@childpids <= $config{'maxconns'}) {
610 # Only accept new main socket connects when ready
612 foreach $s (@socketfhs) {
613 vec($rmask, fileno($s), 1) = 1;
617 printf STDERR "too many children (%d > %d)\n",
618 scalar(@childpids), $config{'maxconns'};
621 for($i=0; $i<@passin; $i++) {
622 vec($rmask, fileno($passin[$i]), 1) = 1;
625 vec($rmask, fileno(LISTEN), 1) = 1 if ($config{'listen'});
627 # Wait for a connection
628 local $sel = select($rmask, undef, undef, 10);
630 # Check the flag files
631 if ($config{'restartflag'} && -r $config{'restartflag'}) {
632 print STDERR "restart flag file detected\n";
633 unlink($config{'restartflag'});
636 if ($config{'reloadflag'} && -r $config{'reloadflag'}) {
637 unlink($config{'reloadflag'});
642 # Got a HUP signal while in select() .. restart now
646 # Got a USR1 signal while in select() .. re-read config
648 &reload_config_file();
650 local $time_now = time();
652 # Clean up finished processes
654 do { $pid = waitpid(-1, WNOHANG);
655 @childpids = grep { $_ != $pid } @childpids;
656 } while($pid != 0 && $pid != -1);
658 # run the unblocking procedure to check if enough time has passed to
659 # unblock hosts that heve been blocked because of password failures
661 if ($config{'blockhost_failures'}) {
663 while ($i <= $#deny) {
664 if ($blockhosttime{$deny[$i]} &&
665 $config{'blockhost_time'} != 0 &&
666 ($time_now - $blockhosttime{$deny[$i]}) >=
667 $config{'blockhost_time'}) {
668 # the host can be unblocked now
669 $hostfail{$deny[$i]} = 0;
670 splice(@deny, $i, 1);
677 # Do the same for blocked users
678 if ($config{'blockuser_failures'}) {
680 while ($i <= $#deny) {
681 if ($blockusertime{$deny[$i]} &&
682 $config{'blockuser_time'} != 0 &&
683 ($time_now - $blockusertime{$deny[$i]}) >=
684 $config{'blockuser_time'}) {
685 # the user can be unblocked now
686 $userfail{$deny[$i]} = 0;
687 splice(@denyusers, $i, 1);
694 &write_blocked_file();
697 # Check if any webmin cron jobs are ready to run
698 &execute_ready_webmin_crons();
700 if ($config{'session'} && (++$remove_session_count%50) == 0) {
701 # Remove sessions with more than 7 days of inactivity,
703 foreach $s (keys %sessiondb) {
704 local ($user, $ltime, $lip) =
705 split(/\s+/, $sessiondb{$s});
706 if ($time_now - $ltime > 7*24*60*60) {
707 &run_logout_script($s, $user);
708 &write_logout_utmp($user, $lip);
709 delete($sessiondb{$s});
712 "Timeout of session for $user");
718 if ($use_pam && $config{'pam_conv'}) {
719 # Remove PAM sessions with more than 5 minutes of inactivity
721 foreach $c (values %conversations) {
722 if ($time_now - $c->{'time'} > 5*60) {
723 &end_pam_conversation($c);
725 syslog("info", "%s", "Timeout of PAM ".
726 "session for $c->{'user'}");
732 # Don't check any sockets if there is no activity
735 # Check if any of the main sockets have received a new connection
737 foreach $s (@socketfhs) {
738 if (vec($rmask, fileno($s), 1)) {
740 $acptaddr = accept(SOCK, $s);
741 if (!$acptaddr) { next; }
742 binmode(SOCK); # turn off any Perl IO stuff
745 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
747 ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw) =
751 # Check username of connecting user
752 local ($peerp, $peera) = unpack_sockaddr_in($acptaddr);
753 $localauth_user = undef;
754 if ($config{'localauth'} && inet_ntoa($peera) eq "127.0.0.1") {
755 if (open(TCP, "/proc/net/tcp")) {
756 # Get the info direct from the kernel
759 local @t = split(/[\s:]+/, $_);
760 if ($t[1] eq '0100007F' &&
761 $t[2] eq sprintf("%4.4X", $peerp)) {
762 $localauth_user = getpwuid($t[11]);
768 if (!$localauth_user) {
769 # Call lsof for the info
770 local $lsofpid = open(LSOF,
771 "$config{'localauth'} -i TCP\@127.0.0.1:$peerp |");
773 if (/^(\S+)\s+(\d+)\s+(\S+)/ &&
774 $2 != $$ && $2 != $lsofpid) {
775 $localauth_user = $3;
782 # Work out the hostname for this web server
783 $host = &get_socket_name(SOCK);
785 print STDERR "Failed to get local socket name : $!\n";
789 $port = $sockets[$sn]->[1];
791 # fork the subprocess
793 if (!($handpid = fork())) {
794 # setup signal handlers
795 $SIG{'TERM'} = 'DEFAULT';
796 $SIG{'PIPE'} = 'DEFAULT';
797 #$SIG{'CHLD'} = 'IGNORE';
798 $SIG{'HUP'} = 'IGNORE';
799 $SIG{'USR1'} = 'IGNORE';
801 # Initialize SSL for this connection
803 $ssl_con = &ssl_connection_for_ip(SOCK);
807 # Close the file handle for the session DBM
808 dbmclose(%sessiondb);
810 # close useless pipes
813 close($PASSINr); close($PASSOUTw);
815 &close_all_sockets();
819 "main: Starting handle_request loop pid=$$\n";
820 while(&handle_request($acptaddr,
821 getsockname(SOCK))) { }
823 "main: Done handle_request loop pid=$$\n";
826 close($PASSINw); close($PASSOUTw);
829 push(@childpids, $handpid);
831 close($PASSINw); close($PASSOUTr);
832 push(@passin, $PASSINr);
833 push(@passout, $PASSOUTw);
840 if ($config{'listen'} && vec($rmask, fileno(LISTEN), 1)) {
841 # Got UDP packet from another webmin server
843 local $from = recv(LISTEN, $rcvbuf, 1024, 0);
845 local $fromip = inet_ntoa((unpack_sockaddr_in($from))[1]);
846 local $toip = inet_ntoa((unpack_sockaddr_in(
847 getsockname(LISTEN)))[1]);
848 if ((!@deny || !&ip_match($fromip, $toip, @deny)) &&
849 (!@allow || &ip_match($fromip, $toip, @allow))) {
850 local $listenhost = &get_socket_name(LISTEN);
851 send(LISTEN, "$listenhost:$config{'port'}:".
852 ($use_ssl || $config{'inetd_ssl'} ? 1 : 0).":".
853 ($config{'listenhost'} ?
854 &get_system_hostname() : ""),
860 # check for session, password-timeout and PAM messages from subprocesses
861 for($i=0; $i<@passin; $i++) {
862 if (vec($rmask, fileno($passin[$i]), 1)) {
863 # this sub-process is asking about a password
864 local $infd = $passin[$i];
865 local $outfd = $passout[$i];
866 #local $inline = <$infd>;
867 local $inline = &sysread_line($infd);
869 print DEBUG "main: inline $inline";
872 print DEBUG "main: inline EOF\n";
874 if ($inline =~ /^delay\s+(\S+)\s+(\S+)\s+(\d+)/) {
875 # Got a delay request from a subprocess.. for
876 # valid logins, there is no delay (to prevent
877 # denial of service attacks), but for invalid
878 # logins the delay increases with each failed
881 # login OK.. no delay
882 print $outfd "0 0\n";
883 $wasblocked = $hostfail{$2} ||
888 &write_blocked_file();
897 # add the host to the block list,
899 if ($config{'blockhost_failures'} &&
901 $config{'blockhost_failures'}) {
903 $blockhosttime{$2} = $time_now;
906 local $logtext = "Security alert: Host $2 blocked after $config{'blockhost_failures'} failed logins for user $1";
912 # add the user to the user block list,
914 if ($config{'blockuser_failures'} &&
916 $config{'blockuser_failures'}) {
917 push(@denyusers, $1);
918 $blockusertime{$1} = $time_now;
921 local $logtext = "Security alert: User $1 blocked after $config{'blockuser_failures'} failed logins";
927 # Lock out the user's password, if enabled
928 if ($config{'blocklock'} &&
930 $config{'blockuser_failures'}) {
931 my $lk = &lock_user_password($1);
934 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";
941 $dl = $userdlay{$1} -
942 int(($time_now - $userlast{$1})/50);
943 $dl = $dl < 0 ? 0 : $dl+1;
944 print $outfd "$dl $blocked\n";
947 # Write out blocked status file
949 &write_blocked_file();
952 $userlast{$1} = $time_now;
954 elsif ($inline =~ /^verify\s+(\S+)\s+(\S+)/) {
955 # Verifying a session ID
956 local $session_id = $1;
957 local $notimeout = $2;
958 local $skey = $sessiondb{$session_id} ?
960 &hash_session_id($session_id);
961 if (!defined($sessiondb{$skey})) {
962 # Session doesn't exist
963 print $outfd "0 0\n";
966 local ($user, $ltime) =
967 split(/\s+/, $sessiondb{$skey});
968 local $lot = &get_logout_time($user, $session_id);
970 $time_now - $ltime > $lot*60 &&
972 # Session has timed out
973 print $outfd "1 ",$time_now - $ltime,"\n";
974 #delete($sessiondb{$skey});
978 print $outfd "2 $user\n";
982 $sessiondb{$skey} = "$user $time_now";
987 elsif ($inline =~ /^new\s+(\S+)\s+(\S+)\s+(\S+)/) {
988 # Creating a new session
989 local $session_id = $1;
992 $sessiondb{&hash_session_id($session_id)} =
993 "$user $time_now $ip";
995 elsif ($inline =~ /^delete\s+(\S+)/) {
996 # Logging out a session
997 local $session_id = $1;
998 local $skey = $sessiondb{$session_id} ?
1000 &hash_session_id($session_id);
1001 local @sdb = split(/\s+/, $sessiondb{$skey});
1002 print $outfd $sdb[0],"\n";
1003 delete($sessiondb{$skey});
1005 elsif ($inline =~ /^pamstart\s+(\S+)\s+(\S+)\s+(.*)/) {
1006 # Starting a new PAM conversation
1007 local ($cid, $host, $user) = ($1, $2, $3);
1009 # Does this user even need PAM?
1010 local ($realuser, $canlogin) =
1011 &can_user_login($user, undef, $host);
1013 if ($canlogin == 0) {
1014 # Cannot even login!
1015 print $outfd "0 Invalid username\n";
1017 elsif ($canlogin != 2) {
1018 # Not using PAM .. so just ask for
1020 $conv = { 'user' => $realuser,
1025 print $outfd "3 Password\n";
1028 # Start the PAM conversation
1029 # sub-process, and get a question
1030 $conv = { 'user' => $realuser,
1034 local ($PAMINr, $PAMINw, $PAMOUTr,
1035 $PAMOUTw) = &allocate_pipes();
1036 local $pampid = fork();
1038 close($PAMOUTr); close($PAMINw);
1039 &pam_conversation_process(
1043 close($PAMOUTw); close($PAMINr);
1044 $conv->{'pid'} = $pampid;
1045 $conv->{'PAMOUTr'} = $PAMOUTr;
1046 $conv->{'PAMINw'} = $PAMINw;
1047 push(@childpids, $pampid);
1049 # Get the first PAM question
1050 local $pok = &recv_pam_question(
1053 &end_pam_conversation($conv);
1057 $conversations{$cid} = $conv if ($conv);
1059 elsif ($inline =~ /^pamanswer\s+(\S+)\s+(.*)/) {
1060 # A response to a PAM question
1061 local ($cid, $answer) = ($1, $2);
1062 local $conv = $conversations{$cid};
1064 # No such conversation?
1065 print $outfd "0 Bad login session\n";
1067 elsif ($conv->{'pid'}) {
1068 # Send the PAM response and get
1070 &send_pam_answer($conv, $answer);
1071 local $pok = &recv_pam_question($conv, $outfd);
1073 &end_pam_conversation($conv);
1077 # This must be the password .. try it
1078 # and send back the results
1079 local ($vu, $expired, $nonexist) =
1080 &validate_user($conv->{'user'},
1083 local $ok = $vu ? 1 : 0;
1084 print $outfd "2 $conv->{'user'} $ok $expired $notexist\n";
1085 &end_pam_conversation($conv);
1088 elsif ($inline =~ /^writesudo\s+(\S+)\s+(\d+)/) {
1089 # Store the fact that some user can sudo to root
1090 local ($user, $ok) = ($1, $2);
1091 $sudocache{$user} = $ok." ".time();
1093 elsif ($inline =~ /^readsudo\s+(\S+)/) {
1094 # Query the user sudo cache (valid for 1 minute)
1096 local ($ok, $last) =
1097 split(/\s+/, $sudocache{$user});
1098 if ($last < time()-60) {
1103 # Tell client OK or not
1104 print $outfd "$ok\n";
1107 elsif ($inline =~ /\S/) {
1108 # Unknown line from pipe?
1109 print DEBUG "main: Unknown line from pipe $inline\n";
1110 print STDERR "Unknown line from pipe $inline\n";
1114 close($infd); close($outfd);
1115 $passin[$i] = $passout[$i] = undef;
1119 @passin = grep { defined($_) } @passin;
1120 @passout = grep { defined($_) } @passout;
1123 # handle_request(remoteaddress, localaddress)
1124 # Where the real work is done
1127 $acptip = inet_ntoa((unpack_sockaddr_in($_[0]))[1]);
1128 $localip = $_[1] ? inet_ntoa((unpack_sockaddr_in($_[1]))[1]) : undef;
1129 print DEBUG "handle_request: from $acptip to $localip\n";
1130 if ($config{'loghost'}) {
1131 $acpthost = gethostbyaddr(inet_aton($acptip), AF_INET);
1132 $acpthost = $acptip if (!$acpthost);
1135 $acpthost = $acptip;
1137 $datestr = &http_date(time());
1139 $ok_message = "Document follows";
1140 $logged_code = undef;
1141 $reqline = $request_uri = $page = undef;
1145 # check address against access list
1146 if (@deny && &ip_match($acptip, $localip, @deny) ||
1147 @allow && !&ip_match($acptip, $localip, @allow)) {
1148 &http_error(403, "Access denied for $acptip");
1153 # Check address with TCP-wrappers
1154 if (!hosts_ctl($config{'pam'}, STRING_UNKNOWN,
1155 $acptip, STRING_UNKNOWN)) {
1156 &http_error(403, "Access denied for $acptip by TCP wrappers");
1160 print DEBUG "handle_request: passed IP checks\n";
1162 # Compute a timeout for the start of headers, based on the number of
1163 # child processes. As this increases, we use a shorter timeout to avoid
1164 # an attacker overloading the system.
1165 local $header_timeout = 60 + ($config{'maxconns'} - @childpids) * 10;
1167 # Wait at most 60 secs for start of headers for initial requests, or
1168 # 10 minutes for kept-alive connections
1170 vec($rmask, fileno(SOCK), 1) = 1;
1171 local $to = $checked_timeout ? 10*60 : $header_timeout;
1172 local $sel = select($rmask, undef, undef, $to);
1174 if ($checked_timeout) {
1175 print DEBUG "handle_request: exiting due to timeout of $to\n";
1179 &http_error(400, "Timeout",
1180 "Waited for that $to seconds for start of headers");
1184 print DEBUG "handle_request: passed timeout check\n";
1186 # Read the HTTP request and headers
1187 local $origreqline = &read_line();
1188 ($reqline = $origreqline) =~ s/\r|\n//g;
1189 $method = $page = $request_uri = undef;
1190 print DEBUG "handle_request reqline=$reqline\n";
1191 if (!$reqline && (!$use_ssl || $checked_timeout > 1)) {
1192 # An empty request .. just close the connection
1193 print DEBUG "handle_request: rejecting empty request\n";
1196 elsif ($reqline !~ /^(\S+)\s+(.*)\s+HTTP\/1\..$/) {
1197 print DEBUG "handle_request: invalid reqline=$reqline\n";
1199 # This could be an http request when it should be https
1201 local $url = $config{'musthost'} ?
1202 "https://$config{'musthost'}:$port/" :
1203 "https://$host:$port/";
1204 if ($config{'ssl_redirect'}) {
1205 # Just re-direct to the correct URL
1206 sleep(1); # Give browser a change to finish
1207 # sending its request
1208 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1209 &write_data("Date: $datestr\r\n");
1210 &write_data("Server: $config{'server'}\r\n");
1211 &write_data("Location: $url\r\n");
1212 &write_keep_alive(0);
1213 &write_data("\r\n");
1217 # Tell user the correct URL
1218 &http_error(200, "Bad Request", "This web server is running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1221 elsif (ord(substr($reqline, 0, 1)) == 128 && !$use_ssl) {
1222 # This could be an https request when it should be http ..
1223 # need to fake a HTTP response
1226 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
1227 eval "Net::SSLeay::load_error_strings()";
1228 $ssl_ctx = Net::SSLeay::CTX_new();
1229 Net::SSLeay::CTX_use_RSAPrivateKey_file(
1230 $ssl_ctx, $config{'keyfile'},
1231 &Net::SSLeay::FILETYPE_PEM);
1232 Net::SSLeay::CTX_use_certificate_file(
1234 $config{'certfile'} || $config{'keyfile'},
1235 &Net::SSLeay::FILETYPE_PEM);
1236 $ssl_con = Net::SSLeay::new($ssl_ctx);
1240 select(SSLw); $| = 1; select(STDOUT);
1241 print SSLw $origreqline;
1243 while(sysread(SOCK, $buf, 1) > 0) {
1250 Net::SSLeay::set_wfd($ssl_con, fileno(SOCK));
1251 Net::SSLeay::set_rfd($ssl_con, fileno(SSLr));
1252 Net::SSLeay::accept($ssl_con) || die "accept() failed";
1254 local $url = $config{'musthost'} ?
1255 "https://$config{'musthost'}:$port/" :
1256 "https://$host:$port/";
1257 if ($config{'ssl_redirect'}) {
1258 # Just re-direct to the correct URL
1259 sleep(1); # Give browser a change to
1260 # finish sending its request
1261 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1262 &write_data("Date: $datestr\r\n");
1263 &write_data("Server: $config{'server'}\r\n");
1264 &write_data("Location: $url\r\n");
1265 &write_keep_alive(0);
1266 &write_data("\r\n");
1270 # Tell user the correct URL
1271 &http_error(200, "Bad Request", "This web server is not running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1275 &http_error(400, "Bad Request");
1279 &http_error(400, "Bad Request");
1283 $request_uri = $page = $2;
1287 ($headline = &read_line()) =~ s/\r|\n//g;
1288 last if ($headline eq "");
1289 print DEBUG "handle_request: got headline $headline\n";
1290 if ($headline =~ /^(\S+):\s*(.*)$/) {
1291 $header{$lastheader = lc($1)} = $2;
1293 elsif ($headline =~ /^\s+(.*)$/) {
1294 $header{$lastheader} .= $headline;
1297 &http_error(400, "Bad Header $headline");
1300 if (defined($header{'host'})) {
1301 if ($header{'host'} =~ /^([^:]+):([0-9]+)$/) {
1302 ($host, $port) = ($1, $2);
1305 $host = $header{'host'};
1307 if ($config{'musthost'} && $host ne $config{'musthost'}) {
1308 # Disallowed hostname used
1309 &http_error(400, "Invalid HTTP hostname");
1313 if ($page =~ /^([^\?]+)\?(.*)$/) {
1314 # There is some query string information
1317 print DEBUG "handle_request: querystring=$querystring\n";
1318 if ($querystring !~ /=/) {
1319 $queryargs = $querystring;
1320 $queryargs =~ s/\+/ /g;
1321 $queryargs =~ s/%(..)/pack("c",hex($1))/ge;
1325 # Parse query-string parameters
1326 local @in = split(/\&/, $querystring);
1328 local ($k, $v) = split(/=/, $i, 2);
1329 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1330 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1335 $posted_data = undef;
1336 if ($method eq 'POST' &&
1337 $header{'content-type'} eq 'application/x-www-form-urlencoded') {
1338 # Read in posted query string information, up the configured maximum
1339 # post request length
1340 $clen = $header{"content-length"};
1341 $clen_read = $clen > $config{'max_post'} ? $config{'max_post'} : $clen;
1342 while(length($posted_data) < $clen_read) {
1343 $buf = &read_data($clen_read - length($posted_data));
1344 if (!length($buf)) {
1345 &http_error(500, "Failed to read POST request");
1347 chomp($posted_data);
1348 $posted_data =~ s/\015$//mg;
1349 $posted_data .= $buf;
1351 print DEBUG "clen_read=$clen_read clen=$clen posted_data=",length($posted_data),"\n";
1352 if ($clen_read != $clen && length($posted_data) > $clen) {
1353 # If the client sent more data than we asked for, chop the
1355 $posted_data = substr($posted_data, 0, $clen);
1357 if (length($posted_data) > $clen) {
1358 # When the client sent too much, delay so that it gets headers
1361 if ($header{'user-agent'} =~ /MSIE/ &&
1362 $header{'user-agent'} !~ /Opera/i) {
1363 # MSIE includes an extra newline in the data
1364 $posted_data =~ s/\r|\n//g;
1366 local @in = split(/\&/, $posted_data);
1368 local ($k, $v) = split(/=/, $i, 2);
1370 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1371 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1374 print DEBUG "handle_request: posted_data=$posted_data\n";
1377 # replace %XX sequences in page
1378 $page =~ s/%(..)/pack("c",hex($1))/ge;
1380 # Check if the browser's user agent indicates a mobile device
1381 $mobile_device = &is_mobile_useragent($header{'user-agent'});
1383 # Check if Host: header is for a mobile URL
1384 foreach my $m (@mobile_prefixes) {
1385 if ($header{'host'} =~ /^\Q$m\E/i) {
1390 # check for the logout flag file, and if existant deny authentication
1391 if ($config{'logout'} && -r $config{'logout'}.$in{'miniserv_logout_id'}) {
1392 print DEBUG "handle_request: logout flag set\n";
1393 $deny_authentication++;
1394 open(LOGOUT, $config{'logout'}.$in{'miniserv_logout_id'});
1395 chop($count = <LOGOUT>);
1399 open(LOGOUT, ">$config{'logout'}$in{'miniserv_logout_id'}");
1400 print LOGOUT "$count\n";
1404 unlink($config{'logout'}.$in{'miniserv_logout_id'});
1408 # check for any redirect for the requested URL
1409 foreach my $pfx (@strip_prefix) {
1410 my $l = length($pfx);
1411 if(length($page) >= $l &&
1412 substr($page,0,$l) eq $pfx) {
1413 $page=substr($page,$l);
1417 $simple = &simplify_path($page, $bogus);
1419 $rpath .= "&".$querystring if (defined($querystring));
1420 $redir = $redirect{$rpath};
1421 if (defined($redir)) {
1422 print DEBUG "handle_request: redir=$redir\n";
1423 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1424 &write_data("Date: $datestr\r\n");
1425 &write_data("Server: $config{'server'}\r\n");
1426 local $ssl = $use_ssl || $config{'inetd_ssl'};
1427 $portstr = $port == 80 && !$ssl ? "" :
1428 $port == 443 && $ssl ? "" : ":$port";
1429 $prot = $ssl ? "https" : "http";
1430 &write_data("Location: $prot://$host$portstr$redir\r\n");
1431 &write_keep_alive(0);
1432 &write_data("\r\n");
1436 # Check for a DAV request
1438 foreach my $d (@davpaths) {
1439 if ($simple eq $d || $simple =~ /^\Q$d\E\//) {
1444 if (!$davpath && ($method eq "SEARCH" || $method eq "PUT")) {
1445 &http_error(400, "Bad Request method $method");
1448 # Check for password if needed
1449 if ($config{'userfile'}) {
1450 print DEBUG "handle_request: Need authentication\n";
1454 # Session authentication is never used for connections by
1455 # another webmin server, or for specified pages, or for DAV, or XMLRPC,
1456 # or mobile browsers if requested.
1457 if ($header{'user-agent'} =~ /webmin/i ||
1458 $header{'user-agent'} =~ /$config{'agents_nosession'}/i ||
1459 $sessiononly{$simple} || $davpath ||
1460 $simple eq "/xmlrpc.cgi" ||
1461 $acptip eq $config{'host_nosession'} ||
1462 $mobile_device && $config{'mobile_nosession'}) {
1463 print DEBUG "handle_request: Forcing HTTP authentication\n";
1464 $config{'session'} = 0;
1467 # Check for SSL authentication
1468 if ($use_ssl && $verified_client) {
1469 $peername = Net::SSLeay::X509_NAME_oneline(
1470 Net::SSLeay::X509_get_subject_name(
1471 Net::SSLeay::get_peer_certificate(
1473 $u = &find_user_by_cert($peername);
1478 if ($use_syslog && !$validated) {
1479 syslog("crit", "%s",
1480 "Unknown SSL certificate $peername");
1484 if (!$validated && !$deny_authentication) {
1485 # check for IP-based authentication
1487 foreach $a (keys %ipaccess) {
1488 if ($acptip eq $a) {
1489 # It does! Auth as the user
1491 $baseauthuser = $authuser =
1497 # Check for normal HTTP authentication
1498 if (!$validated && !$deny_authentication && !$config{'session'} &&
1499 $header{authorization} =~ /^basic\s+(\S+)$/i) {
1500 # authorization given..
1501 ($authuser, $authpass) = split(/:/, &b64decode($1), 2);
1502 print DEBUG "handle_request: doing basic auth check authuser=$authuser authpass=$authpass\n";
1503 local ($vu, $expired, $nonexist) =
1504 &validate_user($authuser, $authpass, $host);
1505 print DEBUG "handle_request: vu=$vu expired=$expired nonexist=$nonexist\n";
1506 if ($vu && (!$expired || $config{'passwd_mode'} == 1)) {
1513 if ($use_syslog && !$validated) {
1514 syslog("crit", "%s",
1515 ($nonexist ? "Non-existent" :
1516 $expired ? "Expired" : "Invalid").
1517 " login as $authuser from $acpthost");
1519 if ($authuser =~ /\r|\n|\s/) {
1520 &http_error(500, "Invalid username",
1521 "Username contains invalid characters");
1523 if ($authpass =~ /\r|\n/) {
1524 &http_error(500, "Invalid password",
1525 "Password contains invalid characters");
1528 if ($config{'passdelay'} && !$config{'inetd'} && $authuser) {
1529 # check with main process for delay
1530 print DEBUG "handle_request: about to ask for password delay\n";
1531 print $PASSINw "delay $authuser $acptip $validated\n";
1532 <$PASSOUTr> =~ /(\d+) (\d+)/;
1534 print DEBUG "handle_request: password delay $1 $2\n";
1539 # Check for a visit to the special session login page
1540 if ($config{'session'} && !$deny_authentication &&
1541 $page eq $config{'session_login'}) {
1542 if ($in{'logout'} && $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1543 # Logout clicked .. remove the session
1545 print $PASSINw "delete $sid\n";
1546 local $louser = <$PASSOUTr>;
1549 $already_session_id = undef;
1550 $authuser = $baseauthuser = undef;
1553 syslog("info", "%s", "Logout by $louser from $acpthost");
1555 &run_logout_script($louser, $sid,
1557 &write_logout_utmp($louser, $actphost);
1562 if ($in{'user'} =~ /\r|\n|\s/) {
1563 &http_error(500, "Invalid username",
1564 "Username contains invalid characters");
1566 if ($in{'pass'} =~ /\r|\n/) {
1567 &http_error(500, "Invalid password",
1568 "Password contains invalid characters");
1571 local ($vu, $expired, $nonexist) =
1572 &validate_user($in{'user'}, $in{'pass'}, $host);
1573 local $hrv = &handle_login(
1574 $vu || $in{'user'}, $vu ? 1 : 0,
1575 $expired, $nonexist, $in{'pass'},
1576 $in{'notestingcookie'});
1577 return $hrv if (defined($hrv));
1581 # Check for a visit to the special PAM login page
1582 if ($config{'session'} && !$deny_authentication &&
1583 $use_pam && $config{'pam_conv'} && $page eq $config{'pam_login'} &&
1585 # A question has been entered .. submit it to the main process
1586 print DEBUG "handle_request: Got call to $page ($in{'cid'})\n";
1587 print DEBUG "handle_request: For PAM, authuser=$authuser\n";
1588 if ($in{'answer'} =~ /\r|\n/ || $in{'cid'} =~ /\r|\n|\s/) {
1589 &http_error(500, "Invalid response",
1590 "Response contains invalid characters");
1594 # Start of a new conversation - answer must be username
1595 $cid = &generate_random_id($in{'answer'});
1596 print $PASSINw "pamstart $cid $host $in{'answer'}\n";
1599 # A response to a previous question
1601 print $PASSINw "pamanswer $cid $in{'answer'}\n";
1604 # Read back the response, and the next question (if any)
1605 local $line = <$PASSOUTr>;
1606 $line =~ s/\r|\n//g;
1607 local ($rv, $question) = split(/\s+/, $line, 2);
1610 local $hrv = &handle_login(
1611 !$in{'cid'} && $in{'answer'} ? $in{'answer'}
1614 return $hrv if (defined($hrv));
1616 elsif ($rv == 1 || $rv == 3) {
1617 # Another question .. force use of PAM CGI
1620 $querystring .= "&cid=$cid&question=".
1622 $querystring .= "&password=1" if ($rv == 3);
1624 $page = $config{'pam_login'};
1625 $miniserv_internal = 1;
1629 # Got back a final ok or failure
1630 local ($user, $ok, $expired, $nonexist) =
1631 split(/\s+/, $question);
1632 local $hrv = &handle_login(
1633 $user, $ok, $expired, $nonexist, undef,
1634 $in{'notestingcookie'});
1635 return $hrv if (defined($hrv));
1638 # A message from PAM .. tell the user
1641 $querystring .= "&cid=$cid&message=".
1644 $page = $config{'pam_login'};
1645 $miniserv_internal = 1;
1650 # Check for a visit to the special password change page
1651 if ($config{'session'} && !$deny_authentication &&
1652 $page eq $config{'password_change'} && !$validated) {
1653 # Just let this slide ..
1655 $miniserv_internal = 3;
1658 # Check for an existing session
1659 if ($config{'session'} && !$validated) {
1660 if ($already_session_id) {
1661 $session_id = $already_session_id;
1662 $authuser = $already_authuser;
1665 elsif (!$deny_authentication &&
1666 $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1667 # Try all session cookies
1668 local $cookie = $header{'cookie'};
1669 while($cookie =~ s/(^|\s)$sidname=([a-f0-9]+)//) {
1672 $in{'webmin_notimeout'} ? 1 : 0;
1673 print $PASSINw "verify $session_id $notimeout\n";
1674 <$PASSOUTr> =~ /(\d+)\s+(\S+)/;
1676 # Valid session continuation
1679 $already_authuser = $authuser;
1688 # Invalid session ID .. don't set
1695 # Check for local authentication
1696 if ($localauth_user && !$header{'x-forwarded-for'} && !$header{'via'}) {
1697 my $luser = &get_user_details($localauth_user);
1699 # Local user exists in webmin users file
1701 $authuser = $localauth_user;
1704 # Check if local user is allowed by unixauth
1705 local @can = &can_user_login($localauth_user,
1709 $authuser = $localauth_user;
1712 $localauth_user = undef;
1718 # Check if this path allows anonymous access
1720 foreach $a (keys %anonymous) {
1721 if (substr($simple, 0, length($a)) eq $a) {
1722 # It does! Auth as the user, if IP access
1723 # control allows him.
1724 if (&check_user_ip($anonymous{$a}) &&
1725 &check_user_time($anonymous{$a})) {
1727 $baseauthuser = $authuser =
1735 # Check if this path allows unauthenticated access
1736 local ($u, $unauth);
1737 foreach $u (@unauth) {
1738 $unauth++ if ($simple =~ /$u/);
1740 if (!$bogus && $unauth) {
1741 # Unauthenticated directory or file request - approve it
1743 $baseauthuser = $authuser = undef;
1748 if ($blocked == 0) {
1749 # No password given.. ask
1750 if ($config{'pam_conv'} && $use_pam) {
1751 # Force CGI for PAM question, starting with
1752 # the username which is always needed
1755 $querystring .= "&initial=1&question=".
1756 &urlize("Username");
1757 $querystring .= "&failed=$failed_user" if ($failed_user);
1758 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1760 $page = $config{'pam_login'};
1761 $miniserv_internal = 1;
1764 elsif ($config{'session'}) {
1765 # Force CGI for session login
1768 $querystring .= "&logout=1&page=/";
1771 # Re-direct to current module only
1772 local $rpage = $request_uri;
1773 if (!$config{'loginkeeppage'}) {
1774 $rpage =~ s/\?.*$//;
1775 $rpage =~ s/[^\/]+$//
1777 $querystring = "page=".&urlize($rpage);
1780 $querystring .= "&failed=$failed_user" if ($failed_user);
1781 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1783 $page = $config{'session_login'};
1784 $miniserv_internal = 1;
1788 # Ask for login with HTTP authentication
1789 &write_data("HTTP/1.0 401 Unauthorized\r\n");
1790 &write_data("Date: $datestr\r\n");
1791 &write_data("Server: $config{'server'}\r\n");
1792 &write_data("WWW-authenticate: Basic ".
1793 "realm=\"$config{'realm'}\"\r\n");
1794 &write_keep_alive(0);
1795 &write_data("Content-type: text/html\r\n");
1796 &write_data("\r\n");
1797 &reset_byte_count();
1798 &write_data("<html>\n");
1799 &write_data("<head><title>Unauthorized</title></head>\n");
1800 &write_data("<body><h1>Unauthorized</h1>\n");
1801 &write_data("A password is required to access this\n");
1802 &write_data("web server. Please try again. <p>\n");
1803 &write_data("</body></html>\n");
1804 &log_request($acpthost, undef, $reqline, 401, &byte_count());
1808 elsif ($blocked == 1) {
1809 # when the host has been blocked, give it an error
1810 &http_error(403, "Access denied for $acptip. The host ".
1811 "has been blocked because of too ".
1812 "many authentication failures.");
1814 elsif ($blocked == 2) {
1815 # when the user has been blocked, give it an error
1816 &http_error(403, "Access denied. The user ".
1817 "has been blocked because of too ".
1818 "many authentication failures.");
1822 # Get the real Webmin username
1823 local @can = &can_user_login($authuser, undef, $host);
1824 $baseauthuser = $can[3] || $authuser;
1826 if ($config{'remoteuser'} && !$< && $validated) {
1827 # Switch to the UID of the remote user (if he exists)
1828 local @u = getpwnam($authuser);
1829 if (@u && $< != $u[2]) {
1830 $( = $u[3]; $) = "$u[3] $u[3]";
1831 ($>, $<) = ($u[2], $u[2]);
1834 &http_error(500, "Unix user $authuser does not exist");
1840 # Check per-user IP access control
1841 if (!&check_user_ip($baseauthuser)) {
1842 &http_error(403, "Access denied for $acptip for $baseauthuser");
1846 # Check per-user allowed times
1847 if (!&check_user_time($baseauthuser)) {
1848 &http_error(403, "Access denied at the current time");
1852 $uinfo = &get_user_details($baseauthuser);
1854 # Validate the path, and convert to canonical form
1856 $simple = &simplify_path($page, $bogus);
1857 print DEBUG "handle_request: page=$page simple=$simple\n";
1859 &http_error(400, "Invalid path");
1862 # Check for a DAV request
1864 return &handle_dav_request($davpath);
1867 # Work out the active theme(s)
1868 local $preroots = $mobile_device && defined($config{'mobile_preroot'}) ?
1869 $config{'mobile_preroot'} :
1870 $authuser && defined($config{'preroot_'.$authuser}) ?
1871 $config{'preroot_'.$authuser} :
1872 $uinfo && defined($uinfo->{'preroot'}) ?
1873 $uinfo->{'preroot'} :
1875 local @preroots = reverse(split(/\s+/, $preroots));
1877 # Canonicalize the directories
1878 foreach my $preroot (@preroots) {
1879 # Always under the current webmin root
1880 $preroot =~ s/^.*\///g;
1881 $preroot = $roots[0].'/'.$preroot;
1884 # Look in the theme root directories first
1885 local ($full, @stfull);
1887 foreach my $preroot (@preroots) {
1890 $full = $preroot.$sofar;
1891 $scriptname = $simple;
1892 foreach $b (split(/\//, $simple)) {
1893 if ($b ne "") { $sofar .= "/$b"; }
1894 $full = $preroot.$sofar;
1895 @stfull = stat($full);
1896 if (!@stfull) { undef($full); last; }
1898 # Check if this is a directory
1900 # It is.. go on parsing
1908 # Check if this is a CGI program
1909 if (&get_type($full) eq "internal/cgi") {
1910 $pathinfo = substr($simple, length($sofar));
1911 $pathinfo .= "/" if ($page =~ /\/$/);
1912 $scriptname = $sofar;
1917 # Don't stop at a directory unless this is the last theme, which
1918 # is the 'real' one that provides the .cgi scripts
1919 if ($is_directory && $preroot ne $preroots[$#preroots]) {
1926 $cgi_pwd = $roots[0];
1928 elsif ($is_directory) {
1929 $cgi_pwd = "$roots[0]$sofar";
1932 "$roots[0]$sofar" =~ /^(.*\/)[^\/]+$/;
1935 $foundroot = $preroot;
1936 if ($is_directory) {
1937 # Check for index files in the directory
1939 foreach $idx (split(/\s+/, $config{"index_docs"})) {
1940 $idxfull = "$full/$idx";
1941 local @stidxfull = stat($idxfull);
1942 if (-r _ && !-d _) {
1944 @stfull = @stidxfull;
1947 if ($scriptname ne "/");
1952 @stfull = stat($full) if (!$foundidx);
1955 last if ($foundroot);
1957 print DEBUG "handle_request: initial full=$full\n";
1959 # Look in the real root directories, stopping when we find a file or directory
1960 if (!$full || $is_directory) {
1961 ROOT: foreach $root (@roots) {
1963 $full = $root.$sofar;
1964 $scriptname = $simple;
1965 foreach $b ($simple eq "/" ? ( "" ) : split(/\//, $simple)) {
1966 if ($b ne "") { $sofar .= "/$b"; }
1967 $full = $root.$sofar;
1968 @stfull = stat($full);
1973 # Check if this is a directory
1975 # It is.. go on parsing
1979 # Check if this is a CGI program
1980 if (&get_type($full) eq "internal/cgi") {
1981 $pathinfo = substr($simple, length($sofar));
1982 $pathinfo .= "/" if ($page =~ /\/$/);
1983 $scriptname = $sofar;
1988 # Run CGI in the same directory as whatever file
1990 $full =~ /^(.*\/)[^\/]+$/; $cgi_pwd = $1;
1999 if (!@stfull) { &http_error(404, "File not found"); }
2001 print DEBUG "handle_request: full=$full\n";
2002 @stfull = stat($full) if (!@stfull);
2004 # check filename against denyfile regexp
2005 local $denyfile = $config{'denyfile'};
2006 if ($denyfile && $full =~ /$denyfile/) {
2007 &http_error(403, "Access denied to $page");
2011 # Reached the end of the path OK.. see what we've got
2013 # See if the URL ends with a / as it should
2014 print DEBUG "handle_request: found a directory\n";
2015 if ($page !~ /\/$/) {
2016 # It doesn't.. redirect
2017 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2018 $ssl = $use_ssl || $config{'inetd_ssl'};
2019 $portstr = $port == 80 && !$ssl ? "" :
2020 $port == 443 && $ssl ? "" : ":$port";
2021 &write_data("Date: $datestr\r\n");
2022 &write_data("Server: $config{server}\r\n");
2023 $prot = $ssl ? "https" : "http";
2024 &write_data("Location: $prot://$host$portstr$page/\r\n");
2025 &write_keep_alive(0);
2026 &write_data("\r\n");
2027 &log_request($acpthost, $authuser, $reqline, 302, 0);
2030 # A directory.. check for index files
2032 foreach $idx (split(/\s+/, $config{"index_docs"})) {
2033 $idxfull = "$full/$idx";
2034 @stidxfull = stat($idxfull);
2035 if (-r _ && !-d _) {
2038 @stfull = @stidxfull;
2039 $scriptname .= "/" if ($scriptname ne "/");
2044 @stfull = stat($full) if (!$foundidx);
2047 # This is definately a directory.. list it
2048 print DEBUG "handle_request: listing directory\n";
2049 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2050 "Date: $datestr\r\n".
2051 "Server: $config{server}\r\n".
2052 "Content-type: text/html\r\n";
2054 &write_keep_alive(0);
2055 &write_data("\r\n");
2056 &reset_byte_count();
2057 &write_data("<h1>Index of $simple</h1>\n");
2058 &write_data("<pre>\n");
2059 &write_data(sprintf "%-35.35s %-20.20s %-10.10s\n",
2060 "Name", "Last Modified", "Size");
2061 &write_data("<hr>\n");
2062 opendir(DIR, $full);
2063 while($df = readdir(DIR)) {
2064 if ($df =~ /^\./) { next; }
2065 $fulldf = $full eq "/" ? $full.$df : $full."/".$df;
2066 (@stbuf = stat($fulldf)) || next;
2067 if (-d _) { $df .= "/"; }
2068 @tm = localtime($stbuf[9]);
2069 $fdate = sprintf "%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d",
2070 $tm[3],$tm[4]+1,$tm[5]+1900,
2071 $tm[0],$tm[1],$tm[2];
2072 $len = length($df); $rest = " "x(35-$len);
2074 "<a href=\"%s\">%-${len}.${len}s</a>$rest %-20.20s %-10.10s\n",
2075 $df, $df, $fdate, $stbuf[7]);
2078 &log_request($acpthost, $authuser, $reqline, $ok_code, &byte_count());
2082 # CGI or normal file
2084 if (&get_type($full) eq "internal/cgi" && $validated != 4) {
2085 # A CGI program to execute
2086 print DEBUG "handle_request: executing CGI\n";
2087 $envtz = $ENV{"TZ"};
2088 $envuser = $ENV{"USER"};
2089 $envpath = $ENV{"PATH"};
2090 $envlang = $ENV{"LANG"};
2091 $envroot = $ENV{"SystemRoot"};
2092 $envperllib = $ENV{'PERLLIB'};
2093 foreach my $k (keys %ENV) {
2096 $ENV{"PATH"} = $envpath if ($envpath);
2097 $ENV{"TZ"} = $envtz if ($envtz);
2098 $ENV{"USER"} = $envuser if ($envuser);
2099 $ENV{"OLD_LANG"} = $envlang if ($envlang);
2100 $ENV{"SystemRoot"} = $envroot if ($envroot);
2101 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
2102 $ENV{"HOME"} = $user_homedir;
2103 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
2104 $ENV{"SERVER_NAME"} = $host;
2105 $ENV{"SERVER_ADMIN"} = $config{"email"};
2106 $ENV{"SERVER_ROOT"} = $roots[0];
2107 $ENV{"SERVER_REALROOT"} = $realroot;
2108 $ENV{"SERVER_PORT"} = $port;
2109 $ENV{"REMOTE_HOST"} = $acpthost;
2110 $ENV{"REMOTE_ADDR"} = $acptip;
2111 $ENV{"REMOTE_USER"} = $authuser;
2112 $ENV{"BASE_REMOTE_USER"} = $authuser ne $baseauthuser ?
2113 $baseauthuser : undef;
2114 $ENV{"REMOTE_PASS"} = $authpass if (defined($authpass) &&
2115 $config{'pass_password'});
2116 if ($uinfo && $uinfo->{'proto'}) {
2117 $ENV{"REMOTE_USER_PROTO"} = $uinfo->{'proto'};
2118 $ENV{"REMOTE_USER_ID"} = $uinfo->{'id'};
2120 print DEBUG "REMOTE_USER = ",$ENV{"REMOTE_USER"},"\n";
2121 print DEBUG "BASE_REMOTE_USER = ",$ENV{"BASE_REMOTE_USER"},"\n";
2122 print DEBUG "proto=$uinfo->{'proto'} id=$uinfo->{'id'}\n" if ($uinfo);
2123 $ENV{"SSL_USER"} = $peername if ($validated == 2);
2124 $ENV{"ANONYMOUS_USER"} = "1" if ($validated == 3 || $validated == 4);
2125 $ENV{"DOCUMENT_ROOT"} = $roots[0];
2126 $ENV{"DOCUMENT_REALROOT"} = $realroot;
2127 $ENV{"GATEWAY_INTERFACE"} = "CGI/1.1";
2128 $ENV{"SERVER_PROTOCOL"} = "HTTP/1.0";
2129 $ENV{"REQUEST_METHOD"} = $method;
2130 $ENV{"SCRIPT_NAME"} = $scriptname;
2131 $ENV{"SCRIPT_FILENAME"} = $full;
2132 $ENV{"REQUEST_URI"} = $request_uri;
2133 $ENV{"PATH_INFO"} = $pathinfo;
2135 $ENV{"PATH_TRANSLATED"} = "$roots[0]$pathinfo";
2136 $ENV{"PATH_REALTRANSLATED"} = "$realroot$pathinfo";
2138 $ENV{"QUERY_STRING"} = $querystring;
2139 $ENV{"MINISERV_CONFIG"} = $config_file;
2140 $ENV{"HTTPS"} = "ON" if ($use_ssl || $config{'inetd_ssl'});
2141 $ENV{"MINISERV_PID"} = $miniserv_main_pid;
2142 $ENV{"SESSION_ID"} = $session_id if ($session_id);
2143 $ENV{"LOCAL_USER"} = $localauth_user if ($localauth_user);
2144 $ENV{"MINISERV_INTERNAL"} = $miniserv_internal if ($miniserv_internal);
2145 if (defined($header{"content-length"})) {
2146 $ENV{"CONTENT_LENGTH"} = $header{"content-length"};
2148 if (defined($header{"content-type"})) {
2149 $ENV{"CONTENT_TYPE"} = $header{"content-type"};
2151 foreach $h (keys %header) {
2152 ($hname = $h) =~ tr/a-z/A-Z/;
2154 $ENV{"HTTP_$hname"} = $header{$h};
2156 $ENV{"PWD"} = $cgi_pwd;
2157 foreach $k (keys %config) {
2158 if ($k =~ /^env_(\S+)$/) {
2159 $ENV{$1} = $config{$k};
2162 delete($ENV{'HTTP_AUTHORIZATION'});
2163 $ENV{'HTTP_COOKIE'} =~ s/;?\s*$sidname=([a-f0-9]+)//;
2164 $ENV{'MOBILE_DEVICE'} = 1 if ($mobile_device);
2166 # Check if the CGI can be handled internally
2168 local $first = <CGI>;
2170 $first =~ s/[#!\r\n]//g;
2171 $nph_script = ($full =~ /\/nph-([^\/]+)$/);
2173 if (!$config{'forkcgis'} &&
2174 ($first eq $perl_path || $first eq $linked_perl_path) &&
2176 $config{'internalcgis'}) {
2177 # setup environment for eval
2179 @ARGV = split(/\s+/, $queryargs);
2182 # Already read the post input
2183 $postinput = $posted_data;
2185 $clen = $header{"content-length"};
2186 $SIG{'CHLD'} = 'DEFAULT';
2188 # Have SOCK closed if the perl exec's something
2190 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
2194 if ($config{'log'}) {
2195 open(MINISERVLOG, ">>$config{'logfile'}");
2196 if ($config{'logperms'}) {
2197 chmod(oct($config{'logperms'}),
2198 $config{'logfile'});
2201 chmod(0600, $config{'logfile'});
2204 $doing_cgi_eval = 1;
2205 $main_process_id = $$;
2207 if ($full =~ /^\Q$foundroot\E\/([^\/]+)\//) {
2208 # Eval in package from Webmin module name
2210 $pkg =~ s/[^A-Za-z0-9]/_/g;
2215 tie(*STDOUT, 'miniserv');
2216 tie(*STDIN, 'miniserv');
2217 do \$miniserv::full;
2220 $doing_cgi_eval = 0;
2223 &http_error(500, "Perl execution failed",
2224 $config{'noshowstderr'} ? undef : $@);
2226 elsif (!$doneheaders && !$nph_script) {
2227 &http_error(500, "Missing Headers");
2234 # fork the process that actually executes the CGI
2235 pipe(CGIINr, CGIINw);
2236 pipe(CGIOUTr, CGIOUTw);
2237 pipe(CGIERRr, CGIERRw);
2238 if (!($cgipid = fork())) {
2239 @execargs = ( $full, split(/\s+/, $queryargs) );
2242 open(STDIN, "<&CGIINr");
2243 open(STDOUT, ">&CGIOUTw");
2244 open(STDERR, ">&CGIERRw");
2245 close(CGIINw); close(CGIOUTr); close(CGIERRr);
2247 die "Failed to exec $full : $!\n";
2250 close(CGIINr); close(CGIOUTw); close(CGIERRw);
2253 # write CGI input to a temp file
2254 $infile = "$config{'tempbase'}.$$";
2255 open(CGIINw, ">$infile");
2256 # NOT binary mode, as CGIs don't read in it!
2261 # already read the posted data
2262 print CGIINw $posted_data;
2264 $clen = $header{"content-length"};
2265 if ($method eq "POST" && $clen_read < $clen) {
2266 $SIG{'PIPE'} = 'IGNORE';
2268 while($got < $clen) {
2269 $buf = &read_data($clen-$got);
2270 if (!length($buf)) {
2271 kill('TERM', $cgipid);
2272 unlink($infile) if ($infile);
2273 &http_error(500, "Failed to read ".
2276 $got += length($buf);
2277 local ($wrote) = (print CGIINw $buf);
2280 # If the CGI terminated early, we still need to read
2281 # from the browser and throw away
2282 while($got < $clen) {
2283 $buf = &read_data($clen-$got);
2284 if (!length($buf)) {
2285 kill('TERM', $cgipid);
2286 unlink($infile) if ($infile);
2287 &http_error(500, "Failed to read ".
2290 $got += length($buf);
2292 $SIG{'PIPE'} = 'DEFAULT';
2298 # Run the CGI program, and feed it input
2300 local $qqueryargs = join(" ", map { "\"$_\"" }
2301 split(/\s+/, $queryargs));
2302 if ($first =~ /(perl|perl.exe)$/i) {
2303 # On Windows, run with Perl
2304 open(CGIOUTr, "$perl_path \"$full\" $qqueryargs <$infile |");
2307 open(CGIOUTr, "\"$full\" $qqueryargs <$infile |");
2313 # read back cgi headers
2314 select(CGIOUTr); $|=1; select(STDOUT);
2318 $line =~ s/\r|\n//g;
2320 if ($got_blank || %cgiheader) { last; }
2324 if ($line !~ /^(\S+):\s+(.*)$/) {
2325 $errs = &read_errors(CGIERRr);
2326 close(CGIOUTr); close(CGIERRr);
2327 unlink($infile) if ($infile);
2328 &http_error(500, "Bad Header", $errs);
2330 $cgiheader{lc($1)} = $2;
2331 push(@cgiheader, [ $1, $2 ]);
2333 if ($cgiheader{"location"}) {
2334 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2335 &write_data("Date: $datestr\r\n");
2336 &write_data("Server: $config{'server'}\r\n");
2337 &write_keep_alive(0);
2338 # ignore the rest of the output. This is a hack,
2339 # but is necessary for IE in some cases :(
2340 close(CGIOUTr); close(CGIERRr);
2342 elsif ($cgiheader{"content-type"} eq "") {
2343 close(CGIOUTr); close(CGIERRr);
2344 unlink($infile) if ($infile);
2345 $errs = &read_errors(CGIERRr);
2346 &http_error(500, "Missing Content-Type Header",
2347 $config{'noshowstderr'} ? undef : $errs);
2350 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2351 &write_data("Date: $datestr\r\n");
2352 &write_data("Server: $config{'server'}\r\n");
2353 &write_keep_alive(0);
2355 foreach $h (@cgiheader) {
2356 &write_data("$h->[0]: $h->[1]\r\n");
2358 &write_data("\r\n");
2360 &reset_byte_count();
2361 while($line = <CGIOUTr>) {
2366 unlink($infile) if ($infile);
2372 print DEBUG "handle_request: outputting file\n";
2373 open(FILE, $full) || &http_error(404, "Failed to open file");
2375 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2376 "Date: $datestr\r\n".
2377 "Server: $config{server}\r\n".
2378 "Content-type: ".&get_type($full)."\r\n".
2379 "Content-length: $stfull[7]\r\n".
2380 "Last-Modified: ".&http_date($stfull[9])."\r\n".
2381 "Expires: ".&http_date(time()+$config{'expires'})."\r\n";
2383 $rv = &write_keep_alive();
2384 &write_data("\r\n");
2385 &reset_byte_count();
2386 while(read(FILE, $buf, 1024) > 0) {
2393 &log_request($acpthost, $authuser, $reqline,
2394 $logged_code ? $logged_code :
2395 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2399 # http_error(code, message, body, [dontexit])
2402 local $eh = $error_handler_recurse ? undef :
2403 $config{"error_handler_$_[0]"} ? $config{"error_handler_$_[0]"} :
2404 $config{'error_handler'} ? $config{'error_handler'} : undef;
2405 print DEBUG "http_error code=$_[0] message=$_[1] body=$_[2]\n";
2407 # Call a CGI program for the error
2409 $querystring = "code=$_[0]&message=".&urlize($_[1]).
2410 "&body=".&urlize($_[2]);
2411 $error_handler_recurse++;
2413 $ok_message = $_[1];
2417 # Use the standard error message display
2418 &write_data("HTTP/1.0 $_[0] $_[1]\r\n");
2419 &write_data("Server: $config{server}\r\n");
2420 &write_data("Date: $datestr\r\n");
2421 &write_data("Content-type: text/html\r\n");
2422 &write_keep_alive(0);
2423 &write_data("\r\n");
2424 &reset_byte_count();
2425 &write_data("<h1>Error - $_[1]</h1>\n");
2427 &write_data("<pre>$_[2]</pre>\n");
2430 &log_request($acpthost, $authuser, $reqline, $_[0], &byte_count())
2432 &log_error($_[1], $_[2] ? " : $_[2]" : "");
2439 if ($_[0] =~ /\.([A-z0-9]+)$/) {
2445 return "text/plain";
2448 # simplify_path(path, bogus)
2449 # Given a path, maybe containing stuff like ".." and "." convert it to a
2450 # clean, absolute form.
2453 local($dir, @bits, @fixedbits, $b);
2455 $dir =~ s/\\/\//g; # fix windows \ in path
2458 $dir =~ s/\0//g; # remove null bytes
2459 @bits = split(/\/+/, $dir);
2462 foreach $b (@bits) {
2466 elsif ($b eq ".." || $b eq "...") {
2468 if (scalar(@fixedbits) == 0) {
2476 push(@fixedbits, $b);
2479 return "/" . join('/', @fixedbits);
2483 # Converts a string from base64 format to normal
2486 local($str) = $_[0];
2488 $str =~ tr|A-Za-z0-9+=/||cd;
2490 $str =~ tr|A-Za-z0-9+/| -_|;
2491 while ($str =~ /(.{1,60})/gs) {
2492 my $len = chr(32 + length($1)*3/4);
2493 $res .= unpack("u", $len . $1 );
2498 # ip_match(remoteip, localip, [match]+)
2499 # Checks an IP address against a list of IPs, networks and networks/masks
2502 local(@io, @mo, @ms, $i, $j, $hn, $needhn);
2503 @io = split(/\./, $_[0]);
2504 for($i=2; $i<@_; $i++) {
2505 $needhn++ if ($_[$i] =~ /^\*(\S+)$/);
2507 if ($needhn && !defined($hn = $ip_match_cache{$_[0]})) {
2508 $hn = gethostbyaddr(inet_aton($_[0]), AF_INET);
2509 $hn = "" if (&to_ipaddress($hn) ne $_[0]);
2510 $ip_match_cache{$_[0]} = $hn;
2512 for($i=2; $i<@_; $i++) {
2513 local $mismatch = 0;
2514 if ($_[$i] =~ /^(\S+)\/(\d+)$/) {
2515 # Convert CIDR to netmask format
2516 $_[$i] = $1."/".&prefix_to_mask($2);
2518 if ($_[$i] =~ /^(\S+)\/(\S+)$/) {
2519 # Compare with network/mask
2520 @mo = split(/\./, $1); @ms = split(/\./, $2);
2521 for($j=0; $j<4; $j++) {
2522 if ((int($io[$j]) & int($ms[$j])) != int($mo[$j])) {
2527 elsif ($_[$i] =~ /^\*(\S+)$/) {
2528 # Compare with hostname regexp
2529 $mismatch = 1 if ($hn !~ /$1$/);
2531 elsif ($_[$i] eq 'LOCAL') {
2532 # Compare with local network
2533 local @lo = split(/\./, $_[1]);
2535 $mismatch = 1 if ($lo[0] != $io[0]);
2537 elsif ($lo[0] < 192) {
2538 $mismatch = 1 if ($lo[0] != $io[0] ||
2542 $mismatch = 1 if ($lo[0] != $io[0] ||
2547 elsif ($_[$i] !~ /^[0-9\.]+$/) {
2548 # Compare with hostname
2549 $mismatch = 1 if ($_[0] ne &to_ipaddress($_[$i]));
2552 # Compare with IP or network
2553 @mo = split(/\./, $_[$i]);
2554 while(@mo && !$mo[$#mo]) { pop(@mo); }
2555 for($j=0; $j<@mo; $j++) {
2556 if ($mo[$j] != $io[$j]) {
2561 return 1 if (!$mismatch);
2566 # users_match(&uinfo, user, ...)
2567 # Returns 1 if a user is in a list of users and groups
2570 local $uinfo = shift(@_);
2572 local @ginfo = getgrgid($uinfo->[3]);
2574 if ($u =~ /^\@(\S+)$/) {
2575 return 1 if (&is_group_member($uinfo, $1));
2577 elsif ($u =~ /^(\d*)-(\d*)$/ && ($1 || $2)) {
2578 return (!$1 || $uinfo[2] >= $1) &&
2579 (!$2 || $uinfo[2] <= $2);
2582 return 1 if ($u eq $uinfo->[0]);
2588 # restart_miniserv()
2589 # Called when a SIGHUP is received to restart the web server. This is done
2590 # by exec()ing perl with the same command line as was originally used
2591 sub restart_miniserv
2593 print STDERR "restarting miniserv\n";
2594 &log_error("Restarting");
2596 &close_all_sockets();
2598 dbmclose(%sessiondb);
2599 kill('KILL', $logclearer) if ($logclearer);
2600 kill('KILL', $extauth) if ($extauth);
2601 exec($perl_path, $miniserv_path, @miniserv_argv);
2602 die "Failed to restart miniserv with $perl_path $miniserv_path";
2619 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2620 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/) { push(@rv, $i); }
2621 else { push(@rv, join('.', unpack("CCCC", inet_aton($i)))); }
2623 return wantarray ? @rv : $rv[0];
2626 # read_line(no-wait, no-limit)
2627 # Reads one line from SOCK or SSL
2630 local ($nowait, $nolimit) = @_;
2631 local($idx, $more, $rv);
2632 while(($idx = index($main::read_buffer, "\n")) < 0) {
2633 if (length($main::read_buffer) > 10000 && !$nolimit) {
2634 &http_error(414, "Request too long",
2635 "Received excessive line <pre>$main::read_buffer</pre>");
2638 # need to read more..
2639 &wait_for_data_error() if (!$nowait);
2641 $more = Net::SSLeay::read($ssl_con);
2644 local $ok = sysread(SOCK, $more, 1024);
2645 $more = undef if ($ok <= 0);
2649 $rv = $main::read_buffer;
2650 undef($main::read_buffer);
2653 $main::read_buffer .= $more;
2655 $rv = substr($main::read_buffer, 0, $idx+1);
2656 $main::read_buffer = substr($main::read_buffer, $idx+1);
2661 # Reads up to some amount of data from SOCK or the SSL connection
2665 if (length($main::read_buffer)) {
2666 if (length($main::read_buffer) > $_[0]) {
2667 # Return the first part of the buffer
2668 $rv = substr($main::read_buffer, 0, $_[0]);
2669 $main::read_buffer = substr($main::read_buffer, $_[0]);
2673 # Return the whole buffer
2674 $rv = $main::read_buffer;
2675 undef($main::read_buffer);
2680 # Call SSL read function
2681 return Net::SSLeay::read($ssl_con, $_[0]);
2684 # Just do a normal read
2686 sysread(SOCK, $buf, $_[0]) || return undef;
2692 # Read a line from a file handle, using sysread to get a byte at a time
2699 $got = sysread($fh, $buf, 1);
2700 last if ($got <= 0);
2702 last if ($buf eq "\n");
2707 # wait_for_data(secs)
2708 # Waits at most the given amount of time for some data on SOCK, returning
2709 # 0 if not found, 1 if some arrived.
2713 vec($rmask, fileno(SOCK), 1) = 1;
2714 local $got = select($rmask, undef, undef, $_[0]);
2715 return $got == 0 ? 0 : 1;
2718 # wait_for_data_error()
2719 # Waits 60 seconds for data on SOCK, and fails if none arrives
2720 sub wait_for_data_error
2722 local $got = &wait_for_data(60);
2724 &http_error(400, "Timeout",
2725 "Waited more than 60 seconds for request data");
2729 # write_data(data, ...)
2730 # Writes a string to SOCK or the SSL connection
2733 local $str = join("", @_);
2735 Net::SSLeay::write($ssl_con, $str);
2738 syswrite(SOCK, $str, length($str));
2740 # Intentionally introduce a small delay to avoid problems where IE reports
2741 # the page as empty / DNS failed when it get a large response too quickly!
2742 select(undef, undef, undef, .01) if ($write_data_count%10 == 0);
2743 $write_data_count += length($str);
2746 # reset_byte_count()
2747 sub reset_byte_count { $write_data_count = 0; }
2750 sub byte_count { return $write_data_count; }
2752 # log_request(hostname, user, request, code, bytes)
2755 if ($config{'log'}) {
2756 local ($user, $ident, $headers);
2757 if ($config{'logident'}) {
2758 # add support for rfc1413 identity checking here
2760 else { $ident = "-"; }
2761 $user = $_[1] ? $_[1] : "-";
2762 local $dstr = &make_datestr();
2763 if (fileno(MINISERVLOG)) {
2764 seek(MINISERVLOG, 0, 2);
2767 open(MINISERVLOG, ">>$config{'logfile'}");
2768 chmod(0600, $config{'logfile'});
2770 if (defined($config{'logheaders'})) {
2771 foreach $h (split(/\s+/, $config{'logheaders'})) {
2772 $headers .= " $h=\"$header{$h}\"";
2775 elsif ($config{'logclf'}) {
2776 $headers = " \"$header{'referer'}\" \"$header{'user-agent'}\"";
2781 print MINISERVLOG "$_[0] $ident $user [$dstr] \"$_[2]\" ",
2782 "$_[3] $_[4]$headers\n";
2790 local @tm = localtime(time());
2791 return sprintf "%2.2d/%s/%4.4d:%2.2d:%2.2d:%2.2d %s",
2792 $tm[3], $month[$tm[4]], $tm[5]+1900,
2793 $tm[2], $tm[1], $tm[0], $timezone;
2796 # log_error(message)
2800 print STDERR "[",&make_datestr(),"] ",
2801 $acpthost ? ( "[",$acpthost,"] " ) : ( ),
2802 $page ? ( $page," : " ) : ( ),
2806 # read_errors(handle)
2807 # Read and return all input from some filehandle
2810 local($fh, $_, $rv);
2812 while(<$fh>) { $rv .= $_; }
2816 sub write_keep_alive
2819 if ($config{'nokeepalive'}) {
2820 # Keep alives have been disabled in config
2823 elsif (@childpids > $config{'maxconns'}*.8) {
2824 # Disable because nearing process limit
2828 # Keep alive specified by caller
2832 # Keep alive determined by browser
2833 $mode = $header{'connection'} =~ /keep-alive/i;
2835 &write_data("Connection: ".($mode ? "Keep-Alive" : "close")."\r\n");
2841 kill('TERM', @childpids) if (@childpids);
2842 kill('KILL', $logclearer) if ($logclearer);
2843 kill('KILL', $extauth) if ($extauth);
2849 local @tm = gmtime($_[0]);
2850 return sprintf "%s, %d %s %d %2.2d:%2.2d:%2.2d GMT",
2851 $weekday[$tm[6]], $tm[3], $month[$tm[4]], $tm[5]+1900,
2852 $tm[2], $tm[1], $tm[0];
2857 my $i; bless \$i, shift;
2863 my($buf,$len,$offset) = @_;
2864 &write_to_sock(substr($buf, $offset, $len));
2871 my $buf = join(defined($,) ? $, : "", @_);
2872 $buf .= $\ if defined($\);
2873 &write_to_sock($buf);
2880 &write_to_sock(sprintf $fmt, @_);
2883 # Send back already read data while we have it, then read from SOCK
2887 my $bufref = \$_[0];
2890 if ($postpos < length($postinput)) {
2891 # Reading from already fetched array
2892 my $left = length($postinput) - $postpos;
2893 my $canread = $len > $left ? $left : $len;
2894 substr($$bufref, $offset, $canread) =
2895 substr($postinput, $postpos, $canread);
2896 $postpos += $canread;
2900 # Read from network socket
2901 local $data = &read_data($len);
2902 if ($data eq '' && $len) {
2904 print STDERR "finished reading - shutting down socket\n";
2907 substr($$bufref, $offset, length($data)) = $data;
2908 return length($data);
2914 #print STDERR "open() called - should never happen!\n";
2917 # Read a line of input
2921 if ($postpos < length($postinput) &&
2922 ($idx = index($postinput, "\n", $postpos)) >= 0) {
2923 # A line exists in the memory buffer .. use it
2924 my $line = substr($postinput, $postpos, $idx-$postpos+1);
2929 # Need to read from the socket
2931 if ($postpos < length($postinput)) {
2932 # Start with in-memory data
2933 $line = substr($postinput, $postpos);
2934 $postpos = length($postinput);
2936 my $nl = &read_line(0, 1);
2939 print STDERR "finished reading - shutting down socket\n";
2942 $line .= $nl if (defined($nl));
2947 # Read one character of input
2952 my $got = READ($r, \$buf, 1, 0);
2953 return $got > 0 ? $buf : undef;
2958 return fileno(SOCK);
2965 # write_to_sock(data, ...)
2970 if ($doneheaders || $miniserv::nph_script) {
2975 while(!$doneheaders && $headers =~ s/^([^\r\n]*)(\r)?\n//) {
2976 if ($1 =~ /^(\S+):\s+(.*)$/) {
2977 $cgiheader{lc($1)} = $2;
2978 push(@cgiheader, [ $1, $2 ]);
2980 elsif ($1 !~ /\S/) {
2984 &http_error(500, "Bad Header");
2988 if ($cgiheader{"location"}) {
2990 "HTTP/1.0 302 Moved Temporarily\r\n");
2991 &write_data("Date: $datestr\r\n");
2992 &write_data("Server: $config{server}\r\n");
2993 &write_keep_alive(0);
2995 elsif ($cgiheader{"content-type"} eq "") {
2996 &http_error(500, "Missing Content-Type Header");
2999 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
3000 &write_data("Date: $datestr\r\n");
3001 &write_data("Server: $config{server}\r\n");
3002 &write_keep_alive(0);
3004 foreach $h (@cgiheader) {
3005 &write_data("$h->[0]: $h->[1]\r\n");
3007 &write_data("\r\n");
3008 &reset_byte_count();
3009 &write_data($headers);
3017 local $cert = Net::SSLeay::X509_STORE_CTX_get_current_cert($_[1]);
3019 local $errnum = Net::SSLeay::X509_STORE_CTX_get_error($_[1]);
3020 $verified_client = 1 if (!$errnum);
3027 if ($doing_cgi_eval && $$ == $main_process_id) {
3028 # A CGI program called exit! This is a horrible hack to
3029 # finish up before really exiting
3032 close($PASSINw); close($PASSOUTw);
3033 &log_request($acpthost, $authuser, $reqline,
3034 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
3039 # Convert a string to a form ok for putting in a URL
3041 local($tmp, $tmp2, $c);
3044 while(($c = chop($tmp)) ne "") {
3045 if ($c !~ /[A-z0-9]/) {
3046 $c = sprintf("%%%2.2X", ord($c));
3053 # validate_user(username, password, host)
3054 # Checks if some username and password are valid. Returns the modified username,
3055 # the expired / temp pass flag, and the non-existence flag
3058 local ($user, $pass, $host) = @_;
3059 return ( ) if (!$user);
3060 print DEBUG "validate_user: user=$user pass=$pass host=$host\n";
3061 local ($canuser, $canmode, $notexist, $webminuser, $sudo) =
3062 &can_user_login($user, undef, $host);
3063 print DEBUG "validate_user: canuser=$canuser canmode=$canmode notexist=$notexist webminuser=$webminuser sudo=$sudo\n";
3065 # User doesn't even exist, so go no further
3066 return ( undef, 0, 1 );
3068 elsif ($canmode == 0) {
3069 # User does exist but cannot login
3070 return ( $canuser, 0, 0 );
3072 elsif ($canmode == 1) {
3073 # Attempt Webmin authentication
3074 my $uinfo = &get_user_details($webminuser);
3076 &password_crypt($pass, $uinfo->{'pass'}) eq $uinfo->{'pass'}) {
3077 # Password is valid .. but check for expiry
3078 local $lc = $uinfo->{'lastchanges'};
3079 print DEBUG "validate_user: Password is valid lc=$lc pass_maxdays=$config{'pass_maxdays'}\n";
3080 if ($config{'pass_maxdays'} && $lc && !$uinfo->{'nochange'}) {
3081 local $daysold = (time() - $lc)/(24*60*60);
3082 print DEBUG "maxdays=$config{'pass_maxdays'} daysold=$daysold temppass=$uinfo->{'temppass'}\n";
3083 if ($config{'pass_lockdays'} &&
3084 $daysold > $config{'pass_lockdays'}) {
3085 # So old that the account is locked
3086 return ( undef, 0, 0 );
3088 elsif ($daysold > $config{'pass_maxdays'}) {
3089 # Password has expired
3090 return ( $user, 1, 0 );
3093 if ($uinfo->{'temppass'}) {
3094 # Temporary password - force change now
3095 return ( $user, 2, 0 );
3097 return ( $user, 0, 0 );
3100 print DEBUG "validate_user: User $webminuser not found\n";
3101 return ( undef, 0, 0 );
3104 print DEBUG "validate_user: User $webminuser password mismatch $pass != $uinfo->{'pass'}\n";
3105 return ( undef, 0, 0 );
3108 elsif ($canmode == 2 || $canmode == 3) {
3109 # Attempt PAM or passwd file authentication
3110 local $val = &validate_unix_user($canuser, $pass);
3111 print DEBUG "validate_user: unix val=$val\n";
3112 if ($val && $sudo) {
3113 # Need to check if this Unix user can sudo
3114 if (!&check_sudo_permissions($canuser, $pass)) {
3115 print DEBUG "validate_user: sudo failed\n";
3119 print DEBUG "validate_user: sudo passed\n";
3122 return $val == 2 ? ( $canuser, 1, 0 ) :
3123 $val == 1 ? ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3125 elsif ($canmode == 4) {
3126 # Attempt external authentication
3127 return &validate_external_user($canuser, $pass) ?
3128 ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3136 # validate_unix_user(user, password)
3137 # Returns 1 if a username and password are valid under unix, 0 if not,
3138 # or 2 if the account has expired.
3139 # Checks PAM if available, and falls back to reading the system password
3141 sub validate_unix_user
3145 $pam_username = $_[0];
3146 $pam_password = $_[1];
3147 eval "use Authen::PAM;";
3148 local $pamh = new Authen::PAM($config{'pam'}, $pam_username,
3151 local $pam_ret = $pamh->pam_authenticate();
3152 if ($pam_ret == PAM_SUCCESS()) {
3153 # Logged in OK .. make sure password hasn't expired
3154 local $acct_ret = $pamh->pam_acct_mgmt();
3155 if ($acct_ret == PAM_SUCCESS()) {
3156 $pamh->pam_open_session();
3159 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3160 $acct_ret == PAM_ACCT_EXPIRED()) {
3164 print STDERR "Unknown pam_acct_mgmt return value : $acct_ret\n";
3171 elsif ($config{'pam_only'}) {
3172 # Pam is not available, but configuration forces it's use!
3175 elsif ($config{'passwd_file'}) {
3176 # Check in a password file
3178 open(FILE, $config{'passwd_file'});
3179 if ($config{'passwd_file'} eq '/etc/security/passwd') {
3180 # Assume in AIX format
3183 if (/^\s*(\S+):/ && $1 eq $_[0]) {
3185 if (/^\s*password\s*=\s*(\S+)\s*$/) {
3186 $rv = $1 eq &password_crypt($_[1], $1) ?
3194 # Read the system password or shadow file
3196 local @l = split(/:/, $_, -1);
3197 local $u = $l[$config{'passwd_uindex'}];
3198 local $p = $l[$config{'passwd_pindex'}];
3200 $rv = $p eq &password_crypt($_[1], $p) ? 1 : 0;
3201 if ($config{'passwd_cindex'} ne '' && $rv) {
3202 # Password may have expired!
3203 local $c = $l[$config{'passwd_cindex'}];
3204 local $m = $l[$config{'passwd_mindex'}];
3205 local $day = time()/(24*60*60);
3206 if ($c =~ /^\d+/ && $m =~ /^\d+/ &&
3212 if ($p eq "" && $config{'passwd_blank'}) {
3213 # Force password change
3221 return $rv if ($rv);
3224 # Fallback option - check password returned by getpw*
3225 local @uinfo = getpwnam($_[0]);
3226 if ($uinfo[1] ne '' && &password_crypt($_[1], $uinfo[1]) eq $uinfo[1]) {
3230 return 0; # Totally failed
3233 # validate_external_user(user, pass)
3234 # Validate a user by passing the username and password to an external
3235 # squid-style authentication program
3236 sub validate_external_user
3238 return 0 if (!$config{'extauth'});
3240 local $str = "$_[0] $_[1]\n";
3241 syswrite(EXTAUTH, $str, length($str));
3242 local $resp = <EXTAUTH>;
3244 return $resp =~ /^OK/i ? 1 : 0;
3247 # can_user_login(username, no-append, host)
3248 # Checks if a user can login or not.
3249 # First return value is the username.
3250 # Second is 0 if cannot login, 1 if using Webmin pass, 2 if PAM, 3 if password
3251 # file, 4 if external.
3252 # Third is 1 if the user does not exist at all, 0 if he does.
3253 # Fourth is the Webmin username whose permissions apply, based on unixauth.
3254 # Fifth is a flag indicating if a sudo check is needed.
3257 local $uinfo = &get_user_details($_[0]);
3259 # See if this user exists in Unix and can be validated by the same
3260 # method as the unixauth webmin user
3261 local $realuser = $unixauth{$_[0]};
3265 eval { @uinfo = getpwnam($_[0]); }; # may fail on windows
3266 if (!$realuser && @uinfo) {
3267 # No unixauth entry for the username .. try his groups
3268 foreach my $ua (keys %unixauth) {
3269 if ($ua =~ /^\@(.*)$/) {
3270 if (&is_group_member(\@uinfo, $1)) {
3271 $realuser = $unixauth{$ua};
3277 if (!$realuser && @uinfo) {
3278 # Fall back to unix auth for all Unix users
3279 $realuser = $unixauth{"*"};
3281 if (!$realuser && $use_sudo && @uinfo) {
3282 # Allow login effectively as root, if sudo permits it
3286 if (!$realuser && !@uinfo && $config{'pamany'}) {
3287 # If the user completely doesn't exist, we can still allow
3288 # him to authenticate via PAM
3289 $realuser = $config{'pamany'};
3293 # For Usermin, always fall back to unix auth for any user,
3294 # so that later checks with domain added / removed are done.
3295 $realuser = $unixauth{"*"};
3297 return (undef, 0, 1, undef) if (!$realuser);
3298 local $uinfo = &get_user_details($realuser);
3299 return (undef, 0, 1, undef) if (!$uinfo);
3300 local $up = $uinfo->{'pass'};
3302 # Work out possible domain names from the hostname
3303 local @doms = ( $_[2] );
3304 if ($_[2] =~ /^([^\.]+)\.(\S+)$/) {
3308 if ($config{'user_mapping'} && !%user_mapping) {
3309 # Read the user mapping file
3311 open(MAPPING, $config{'user_mapping'});
3315 if (/^(\S+)\s+(\S+)/) {
3316 if ($config{'user_mapping_reverse'}) {
3317 $user_mapping{$1} = $2;
3320 $user_mapping{$2} = $1;
3327 # Check the user mapping file to see if there is an entry for the
3328 # user login in which specifies a new effective user
3330 foreach my $d (@doms) {
3331 $um ||= $user_mapping{"$_[0]\@$d"};
3333 $um ||= $user_mapping{$_[0]};
3334 if (defined($um) && ($_[1]&4) == 0) {
3335 # A mapping exists - use it!
3336 return &can_user_login($um, $_[1]+4, $_[2]);
3339 # Check if a user with the entered login and the domains appended
3340 # or prepended exists, and if so take it to be the effective user
3341 if (!@uinfo && $config{'domainuser'}) {
3342 # Try again with name.domain and name.firstpart
3343 local @firsts = map { /^([^\.]+)/; $1 } @doms;
3344 if (($_[1]&1) == 0) {
3346 foreach $a (@firsts, @doms) {
3347 foreach $p ("$_[0].${a}", "$_[0]-${a}",
3348 "${a}.$_[0]", "${a}-$_[0]",
3349 "$_[0]_${a}", "${a}_$_[0]") {
3350 local @vu = &can_user_login(
3351 $p, $_[1]+1, $_[2]);
3352 return @vu if ($vu[1]);
3358 # Check if the user entered a domain at the end of his username when
3359 # he really shouldn't have, and if so try without it
3360 if (!@uinfo && $config{'domainstrip'} &&
3361 $_[0] =~ /^(\S+)\@(\S+)$/ && ($_[1]&2) == 0) {
3362 local ($stripped, $dom) = ($1, $2);
3363 local @vu = &can_user_login($stripped, $_[1] + 2, $_[2]);
3364 return @vu if ($vu[1]);
3365 local @vu = &can_user_login($stripped, $_[1] + 2, $dom);
3366 return @vu if ($vu[1]);
3369 return ( undef, 0, 1, undef ) if (!@uinfo && !$pamany);
3372 if (defined(@allowusers)) {
3373 # Only allow people on the allow list
3374 return ( undef, 0, 0, undef )
3375 if (!&users_match(\@uinfo, @allowusers));
3377 elsif (defined(@denyusers)) {
3378 # Disallow people on the deny list
3379 return ( undef, 0, 0, undef )
3380 if (&users_match(\@uinfo, @denyusers));
3382 if ($config{'shells_deny'}) {
3384 open(SHELLS, $config{'shells_deny'});
3388 $found++ if ($_ eq $uinfo[8]);
3391 return ( undef, 0, 0, undef ) if (!$found);
3396 # PAM or passwd file authentication
3397 print DEBUG "can_user_login: Validate with PAM\n";
3398 return ( $_[0], $use_pam ? 2 : 3, 0, $realuser, $sudo );
3400 elsif ($up eq 'e') {
3401 # External authentication
3402 print DEBUG "can_user_login: Validate externally\n";
3403 return ( $_[0], 4, 0, $realuser, $sudo );
3406 # Fixed Webmin password
3407 print DEBUG "can_user_login: Validate by Webmin\n";
3408 return ( $_[0], 1, 0, $realuser, $sudo );
3411 elsif ($uinfo->{'pass'} eq 'x') {
3412 # Webmin user authenticated via PAM or password file
3413 return ( $_[0], $use_pam ? 2 : 3, 0, $_[0] );
3415 elsif ($uinfo->{'pass'} eq 'e') {
3416 # Webmin user authenticated externally
3417 return ( $_[0], 4, 0, $_[0] );
3420 # Normal Webmin user
3421 return ( $_[0], 1, 0, $_[0] );
3425 # the PAM conversation function for interactive logins
3428 $pam_conv_func_called++;
3435 $ans = $pam_username if ($code == PAM_PROMPT_ECHO_ON() );
3436 $ans = $pam_password if ($code == PAM_PROMPT_ECHO_OFF() );
3438 push @res, PAM_SUCCESS();
3441 push @res, PAM_SUCCESS();
3450 # get_socket_name(handle)
3451 # Returns the local hostname or IP address of some connection
3454 return $config{'host'} if ($config{'host'});
3455 local $sn = getsockname($_[0]);
3456 return undef if (!$sn);
3457 local $myaddr = (unpack_sockaddr_in($sn))[1];
3458 if (!$get_socket_name_cache{$myaddr}) {
3460 if (!$config{'no_resolv_myname'}) {
3461 $myname = gethostbyaddr($myaddr, AF_INET);
3463 if ($myname eq "") {
3464 $myname = inet_ntoa($myaddr);
3466 $get_socket_name_cache{$myaddr} = $myname;
3468 return $get_socket_name_cache{$myaddr};
3471 # run_login_script(username, sid, remoteip, localip)
3472 sub run_login_script
3474 if ($config{'login_script'}) {
3475 system($config{'login_script'}.
3476 " ".join(" ", map { quotemeta($_) || '""' } @_).
3477 " >/dev/null 2>&1 </dev/null");
3481 # run_logout_script(username, sid, remoteip, localip)
3482 sub run_logout_script
3484 if ($config{'logout_script'}) {
3485 system($config{'logout_script'}.
3486 " ".join(" ", map { quotemeta($_) || '""' } @_).
3487 " >/dev/null 2>&1 </dev/null");
3491 # close_all_sockets()
3492 # Closes all the main listening sockets
3493 sub close_all_sockets
3496 foreach $s (@socketfhs) {
3502 # Close all pipes for talking to sub-processes
3506 foreach $p (@passin) { close($p); }
3507 foreach $p (@passout) { close($p); }
3508 foreach $p (values %conversations) {
3509 if ($p->{'PAMOUTr'}) {
3510 close($p->{'PAMOUTr'});
3511 close($p->{'PAMINw'});
3516 # check_user_ip(user)
3517 # Returns 1 if some user is allowed to login from the accepting IP, 0 if not
3520 local ($username) = @_;
3521 local $uinfo = &get_user_details($username);
3522 return 1 if (!$uinfo);
3523 if ($uinfo->{'deny'} &&
3524 &ip_match($acptip, $localip, @{$uinfo->{'deny'}}) ||
3525 $uinfo->{'allow'} &&
3526 !&ip_match($acptip, $localip, @{$uinfo->{'allow'}})) {
3532 # check_user_time(user)
3533 # Returns 1 if some user is allowed to login at the current date and time
3536 local ($username) = @_;
3537 local $uinfo = &get_user_details($username);
3538 return 1 if (!$uinfo || !$uinfo->{'allowdays'} && !$uinfo->{'allowhours'});
3539 local @tm = localtime(time());
3540 if ($uinfo->{'allowdays'}) {
3541 # Make sure day is allowed
3542 return 0 if (&indexof($tm[6], @{$uinfo->{'allowdays'}}) < 0);
3544 if ($uinfo->{'allowhours'}) {
3545 # Make sure time is allowed
3546 local $m = $tm[2]*60+$tm[1];
3547 return 0 if ($m < $uinfo->{'allowhours'}->[0] ||
3548 $m > $uinfo->{'allowhours'}->[1]);
3553 # generate_random_id(password, [force-urandom])
3554 # Returns a random session ID number
3555 sub generate_random_id
3557 local ($pass, $force_urandom) = @_;
3559 if (!$bad_urandom) {
3560 # First try /dev/urandom, unless we have marked it as bad
3561 $SIG{ALRM} = "miniserv::urandom_timeout";
3563 if (open(RANDOM, "/dev/urandom")) {
3565 if (read(RANDOM, $tmpsid, 16) == 16) {
3566 $sid = lc(unpack('h*',$tmpsid));
3572 if (!$sid && !$force_urandom) {
3575 foreach $c (split(//, &unix_crypt($pass, substr($$, -2)))) {
3576 $sid += ord($c) * $mul;
3583 # handle_login(username, ok, expired, not-exists, password, [no-test-cookie])
3584 # Called from handle_session to either mark a user as logged in, or not
3587 local ($vu, $ok, $expired, $nonexist, $pass, $notest) = @_;
3588 $authuser = $vu if ($ok);
3590 # check if the test cookie is set
3591 if ($header{'cookie'} !~ /testing=1/ && $vu &&
3592 !$config{'no_testing_cookie'} && !$notest) {
3593 &http_error(500, "No cookies",
3594 "Your browser does not support cookies, ".
3595 "which are required for this web server to ".
3596 "work in session authentication mode");
3599 # check with main process for delay
3600 if ($config{'passdelay'} && $vu) {
3601 print DEBUG "handle_login: requesting delay vu=$vu acptip=$acptip ok=$ok\n";
3602 print $PASSINw "delay $vu $acptip $ok\n";
3603 <$PASSOUTr> =~ /(\d+) (\d+)/;
3606 print DEBUG "handle_login: delay=$1 blocked=$2\n";
3609 if ($ok && (!$expired ||
3610 $config{'passwd_mode'} == 1)) {
3611 # Logged in OK! Tell the main process about
3613 local $sid = &generate_random_id($pass);
3614 print DEBUG "handle_login: sid=$sid\n";
3615 print $PASSINw "new $sid $authuser $acptip\n";
3617 # Run the post-login script, if any
3618 &run_login_script($authuser, $sid,
3621 # Check for a redirect URL for the user
3622 local $rurl = &login_redirect($authuser, $pass, $host);
3623 print DEBUG "handle_login: redirect URL rurl=$rurl\n";
3625 # Got one .. go to it
3626 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3627 &write_data("Date: $datestr\r\n");
3628 &write_data("Server: $config{'server'}\r\n");
3629 &write_data("Location: $rurl\r\n");
3630 &write_keep_alive(0);
3631 &write_data("\r\n");
3632 &log_request($acpthost, $authuser, $reqline, 302, 0);
3635 # Set cookie and redirect to originally requested page
3636 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3637 &write_data("Date: $datestr\r\n");
3638 &write_data("Server: $config{'server'}\r\n");
3639 local $ssl = $use_ssl || $config{'inetd_ssl'};
3640 $portstr = $port == 80 && !$ssl ? "" :
3641 $port == 443 && $ssl ? "" : ":$port";
3642 $prot = $ssl ? "https" : "http";
3643 local $sec = $ssl ? "; secure" : "";
3644 #$sec .= "; httpOnly";
3645 if ($in{'page'} !~ /^\/[A-Za-z0-9\/\.\-\_]+$/) {
3646 # Make redirect URL safe
3650 &write_data("Set-Cookie: $sidname=$sid; path=/; expires=\"Thu, 31-Dec-2037 00:00:00\"$sec\r\n");
3653 &write_data("Set-Cookie: $sidname=$sid; path=/$sec\r\n");
3655 &write_data("Location: $prot://$host$portstr$in{'page'}\r\n");
3656 &write_keep_alive(0);
3657 &write_data("\r\n");
3658 &log_request($acpthost, $authuser, $reqline, 302, 0);
3659 syslog("info", "%s", "Successful login as $authuser from $acpthost") if ($use_syslog);
3660 &write_login_utmp($authuser, $acpthost);
3664 elsif ($ok && $expired &&
3665 ($config{'passwd_mode'} == 2 || $expired == 2)) {
3666 # Login was ok, but password has expired or was temporary. Need
3667 # to force display of password change form.
3670 $querystring = "&user=".&urlize($vu).
3672 "&expired=".$expired;
3675 $page = $config{'password_form'};
3677 $miniserv_internal = 2;
3678 syslog("crit", "%s",
3679 "Expired login as $vu ".
3680 "from $acpthost") if ($use_syslog);
3683 # Login failed, or password has expired. The login form will be
3684 # displayed again by later code
3686 $request_uri = $in{'page'};
3687 $already_session_id = undef;
3689 $authuser = $baseauthuser = undef;
3690 syslog("crit", "%s",
3691 ($nonexist ? "Non-existent" :
3692 $expired ? "Expired" : "Invalid").
3693 " login as $vu from $acpthost")
3699 # write_login_utmp(user, host)
3700 # Record the login by some user in utmp
3701 sub write_login_utmp
3704 # Write utmp record for login
3705 %utmp = ( 'ut_host' => $_[1],
3706 'ut_time' => time(),
3708 'ut_type' => 7, # user process
3709 'ut_pid' => $main_process_id,
3710 'ut_line' => $config{'pam'},
3712 if (defined(&User::Utmp::putut)) {
3713 User::Utmp::putut(\%utmp);
3716 User::Utmp::pututline(\%utmp);
3721 # write_logout_utmp(user, host)
3722 # Record the logout by some user in utmp
3723 sub write_logout_utmp
3726 # Write utmp record for logout
3727 %utmp = ( 'ut_host' => $_[1],
3728 'ut_time' => time(),
3730 'ut_type' => 8, # dead process
3731 'ut_pid' => $main_process_id,
3732 'ut_line' => $config{'pam'},
3734 if (defined(&User::Utmp::putut)) {
3735 User::Utmp::putut(\%utmp);
3738 User::Utmp::pututline(\%utmp);
3743 # pam_conversation_process(username, write-pipe, read-pipe)
3744 # This function is called inside a sub-process to communicate with PAM. It sends
3745 # questions down one pipe, and reads responses from another
3746 sub pam_conversation_process
3748 local ($user, $writer, $reader) = @_;
3749 $miniserv::pam_conversation_process_writer = $writer;
3750 $miniserv::pam_conversation_process_reader = $reader;
3751 eval "use Authen::PAM;";
3752 local $convh = new Authen::PAM(
3753 $config{'pam'}, $user, \&miniserv::pam_conversation_process_func);
3754 local $pam_ret = $convh->pam_authenticate();
3755 if ($pam_ret == PAM_SUCCESS()) {
3756 local $acct_ret = $convh->pam_acct_mgmt();
3757 if ($acct_ret == PAM_SUCCESS()) {
3758 $convh->pam_open_session();
3759 print $writer "x2 $user 1 0 0\n";
3761 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3762 $acct_ret == PAM_ACCT_EXPIRED()) {
3763 print $writer "x2 $user 1 1 0\n";
3766 print $writer "x0 Unknown PAM account status $acct_ret\n";
3770 print $writer "x2 $user 0 0 0\n";
3775 # pam_conversation_process_func(type, message, [type, message, ...])
3776 # A pipe that talks to both PAM and the master process
3777 sub pam_conversation_process_func
3780 select($miniserv::pam_conversation_process_writer); $| = 1; select(STDOUT);
3782 local ($type, $msg) = (shift, shift);
3784 local $ok = (print $miniserv::pam_conversation_process_writer "$type $msg\n");
3785 print $miniserv::pam_conversation_process_writer "\n";
3786 local $answer = <$miniserv::pam_conversation_process_reader>;
3787 $answer =~ s/\r|\n//g;
3788 push(@rv, PAM_SUCCESS(), $answer);
3790 push(@rv, PAM_SUCCESS());
3795 # Returns 4 new pipe file handles
3798 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3800 local %taken = ( (map { $_, 1 } @passin),
3801 (map { $_->{'PASSINr'} } values %conversations) );
3802 for($p=0; $taken{"PASSINr$p"}; $p++) { }
3803 $PASSINr = "PASSINr$p";
3804 $PASSINw = "PASSINw$p";
3805 $PASSOUTr = "PASSOUTr$p";
3806 $PASSOUTw = "PASSOUTw$p";
3807 pipe($PASSINr, $PASSINw);
3808 pipe($PASSOUTr, $PASSOUTw);
3809 select($PASSINw); $| = 1;
3810 select($PASSINr); $| = 1;
3811 select($PASSOUTw); $| = 1;
3812 select($PASSOUTw); $| = 1;
3814 return ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3817 # recv_pam_question(&conv, fd)
3818 # Reads one PAM question from the sub-process, and sends it to the HTTP handler.
3819 # Returns 0 if the conversation is over, 1 if not.
3820 sub recv_pam_question
3822 local ($conf, $fh) = @_;
3823 local $pr = $conf->{'PAMOUTr'};
3824 select($pr); $| = 1; select(STDOUT);
3825 local $line = <$pr>;
3826 $line =~ s/\r|\n//g;
3829 $line =~ s/\r|\n//g;
3831 $conf->{'last'} = time();
3834 print $fh "0 PAM conversation error\n";
3838 local ($type, $msg) = split(/\s+/, $line, 2);
3839 if ($type =~ /^x(\d+)/) {
3840 # Pass this status code through
3841 print $fh "$1 $msg\n";
3842 return $1 == 2 || $1 == 0 ? 0 : 1;
3844 elsif ($type == PAM_PROMPT_ECHO_ON()) {
3846 print $fh "1 $msg\n";
3849 elsif ($type == PAM_PROMPT_ECHO_OFF()) {
3851 print $fh "3 $msg\n";
3854 elsif ($type == PAM_ERROR_MSG() || $type == PAM_TEXT_INFO()) {
3855 # A message that does not require a response
3856 print $fh "4 $msg\n";
3861 print $fh "0 Unknown PAM message type $type\n";
3867 # send_pam_answer(&conv, answer)
3868 # Sends a response from the user to the PAM sub-process
3871 local ($conf, $answer) = @_;
3872 local $pw = $conf->{'PAMINw'};
3873 $conf->{'last'} = time();
3874 print $pw "$answer\n";
3877 # end_pam_conversation(&conv)
3878 # Clean up PAM conversation pipes and processes
3879 sub end_pam_conversation
3882 kill('KILL', $conv->{'pid'}) if ($conv->{'pid'});
3883 if ($conv->{'PAMINr'}) {
3884 close($conv->{'PAMINr'});
3885 close($conv->{'PAMOUTr'});
3886 close($conv->{'PAMINw'});
3887 close($conv->{'PAMOUTw'});
3889 delete($conversations{$conv->{'cid'}});
3892 # get_ipkeys(&miniserv)
3893 # Returns a list of IP address to key file mappings from a miniserv.conf entry
3897 foreach $k (keys %{$_[0]}) {
3898 if ($k =~ /^ipkey_(\S+)/) {
3899 local $ipkey = { 'ips' => [ split(/,/, $1) ],
3900 'key' => $_[0]->{$k},
3901 'index' => scalar(@rv) };
3902 $ipkey->{'cert'} = $_[0]->{'ipcert_'.$1};
3909 # create_ssl_context(keyfile, [certfile])
3910 sub create_ssl_context
3912 local ($keyfile, $certfile) = @_;
3914 eval { $ssl_ctx = Net::SSLeay::new_x_ctx() };
3915 $ssl_ctx ||= Net::SSLeay::CTX_new();
3916 $ssl_ctx || die "Failed to create SSL context : $!";
3917 if ($client_certs) {
3918 Net::SSLeay::CTX_load_verify_locations(
3919 $ssl_ctx, $config{'ca'}, "");
3920 Net::SSLeay::CTX_set_verify(
3921 $ssl_ctx, &Net::SSLeay::VERIFY_PEER, \&verify_client);
3923 if ($config{'extracas'}) {
3925 foreach $p (split(/\s+/, $config{'extracas'})) {
3926 Net::SSLeay::CTX_load_verify_locations(
3931 Net::SSLeay::CTX_use_RSAPrivateKey_file(
3933 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL key $keyfile";
3934 Net::SSLeay::CTX_use_certificate_file(
3935 $ssl_ctx, $certfile || $keyfile,
3936 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL cert $certfile";
3941 # ssl_connection_for_ip(socket)
3942 # Returns a new SSL connection object for some socket, or undef if failed
3943 sub ssl_connection_for_ip
3946 local $sn = getsockname($sock);
3948 print STDERR "Failed to get address for socket $sock\n";
3951 local $myip = inet_ntoa((unpack_sockaddr_in($sn))[1]);
3952 local $ssl_ctx = $ssl_contexts{$myip} || $ssl_contexts{"*"};
3953 local $ssl_con = Net::SSLeay::new($ssl_ctx);
3954 if ($config{'ssl_cipher_list'}) {
3955 # Force use of ciphers
3956 eval "Net::SSLeay::set_cipher_list(
3957 \$ssl_con, \$config{'ssl_cipher_list'})";
3959 print STDERR "SSL cipher $config{'ssl_cipher_list'} failed : ",
3965 Net::SSLeay::set_fd($ssl_con, fileno($sock));
3966 if (!Net::SSLeay::accept($ssl_con)) {
3967 print STDERR "Failed to initialize SSL connection\n";
3973 # login_redirect(username, password, host)
3974 # Calls the login redirect script (if configured), which may output a URL to
3975 # re-direct a user to after logging in.
3978 return undef if (!$config{'login_redirect'});
3979 local $quser = quotemeta($_[0]);
3980 local $qpass = quotemeta($_[1]);
3981 local $qhost = quotemeta($_[2]);
3982 local $url = `$config{'login_redirect'} $quser $qpass $qhost`;
3987 # reload_config_file()
3988 # Re-read %config, and call post-config actions
3989 sub reload_config_file
3991 &log_error("Reloading configuration");
3992 %config = &read_config_file($config_file);
3993 &update_vital_config();
3996 &build_config_mappings();
3997 &read_webmin_crons();
3998 if ($config{'session'}) {
3999 dbmclose(%sessiondb);
4000 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
4004 # read_config_file(file)
4005 # Reads the given config file, and returns a hash of values
4006 sub read_config_file
4009 open(CONF, $_[0]) || die "Failed to open config file $_[0] : $!";
4012 if (/^#/ || !/\S/) { next; }
4014 $name = $1; $val = $2;
4015 $name =~ s/^\s+//g; $name =~ s/\s+$//g;
4016 $val =~ s/^\s+//g; $val =~ s/\s+$//g;
4023 # update_vital_config()
4024 # Updates %config with defaults, and dies if something vital is missing
4025 sub update_vital_config
4027 my %vital = ("port", 80,
4029 "server", "MiniServ/0.01",
4030 "index_docs", "index.html index.htm index.cgi index.php",
4031 "addtype_html", "text/html",
4032 "addtype_txt", "text/plain",
4033 "addtype_gif", "image/gif",
4034 "addtype_jpg", "image/jpeg",
4035 "addtype_jpeg", "image/jpeg",
4036 "realm", "MiniServ",
4037 "session_login", "/session_login.cgi",
4038 "pam_login", "/pam_login.cgi",
4039 "password_form", "/password_form.cgi",
4040 "password_change", "/password_change.cgi",
4044 "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\$",
4046 "expires", 7*24*60*60,
4047 "pam_test_user", "root",
4049 foreach my $v (keys %vital) {
4051 if ($vital{$v} eq "") {
4052 die "Missing config option $v";
4054 $config{$v} = $vital{$v};
4057 if (!$config{'sessiondb'}) {
4058 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4059 $config{'sessiondb'} = "$1/sessiondb";
4061 if (!$config{'errorlog'}) {
4062 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
4063 $config{'errorlog'} = "$1/miniserv.error";
4065 if (!$config{'tempbase'}) {
4066 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4067 $config{'tempbase'} = "$1/cgitemp";
4069 if (!$config{'blockedfile'}) {
4070 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
4071 $config{'blockedfile'} = "$1/blocked";
4073 if (!$config{'webmincron_dir'}) {
4074 $config_file =~ /^(.*)\/[^\/]+$/;
4075 $config{'webmincron_dir'} = "$1/webmincron/crons";
4077 if (!$config{'webmincron_last'}) {
4078 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
4079 $config{'webmincron_last'} = "$1/miniserv.lastcrons";
4081 if (!$config{'webmincron_wrapper'}) {
4082 $config{'webmincron_wrapper'} = $config{'root'}.
4083 "/webmincron/webmincron.pl";
4088 # Fills the %users and %certs hashes from the users file in %config
4097 undef(%lastchanges);
4100 if ($config{'userfile'}) {
4101 open(USERS, $config{'userfile'});
4104 local @user = split(/:/, $_, -1);
4105 $users{$user[0]} = $user[1];
4106 $certs{$user[0]} = $user[3] if ($user[3]);
4107 if ($user[4] =~ /^allow\s+(.*)/) {
4108 $allow{$user[0]} = $config{'alwaysresolve'} ?
4109 [ split(/\s+/, $1) ] :
4110 [ &to_ipaddress(split(/\s+/, $1)) ];
4112 elsif ($user[4] =~ /^deny\s+(.*)/) {
4113 $deny{$user[0]} = $config{'alwaysresolve'} ?
4114 [ split(/\s+/, $1) ] :
4115 [ &to_ipaddress(split(/\s+/, $1)) ];
4117 if ($user[5] =~ /days\s+(\S+)/) {
4118 $allowdays{$user[0]} = [ split(/,/, $1) ];
4120 if ($user[5] =~ /hours\s+(\d+)\.(\d+)-(\d+).(\d+)/) {
4121 $allowhours{$user[0]} = [ $1*60+$2, $3*60+$4 ];
4123 $lastchanges{$user[0]} = $user[6];
4124 $nochange{$user[0]} = $user[9];
4125 $temppass{$user[0]} = $user[10];
4130 # Test user DB, if configured
4131 if ($config{'userdb'}) {
4132 my $dbh = &connect_userdb($config{'userdb'});
4134 print STDERR "Failed to open users database : $dbh\n"
4137 &disconnect_userdb($config{'userdb'}, $dbh);
4142 # get_user_details(username)
4143 # Returns a hash ref of user details, either from config files or the user DB
4144 sub get_user_details
4146 my ($username) = @_;
4147 if (exists($users{$username})) {
4149 return { 'name' => $username,
4150 'pass' => $users{$username},
4151 'certs' => $certs{$username},
4152 'allow' => $allow{$username},
4153 'deny' => $deny{$username},
4154 'allowdays' => $allowdays{$username},
4155 'allowhours' => $allowhours{$username},
4156 'lastchanges' => $lastchanges{$username},
4157 'nochange' => $nochange{$username},
4158 'temppass' => $temppass{$username},
4159 'preroot' => $config{'preroot_'.$username},
4162 if ($config{'userdb'}) {
4163 # Try querying user database
4164 if (exists($get_user_details_cache{$username})) {
4166 return $get_user_details_cache{$username};
4168 print DEBUG "get_user_details: Connecting to user database\n";
4169 my ($dbh, $proto, $prefix, $args) = &connect_userdb($config{'userdb'});
4173 print DEBUG "get_user_details: Failed : $dbh\n";
4174 print STDERR "Failed to connect to user database : $dbh\n";
4176 elsif ($proto eq "mysql" || $proto eq "postgresql") {
4177 # Fetch user ID and password with SQL
4178 print DEBUG "get_user_details: Looking for $username in SQL\n";
4179 my $cmd = $dbh->prepare(
4180 "select id,pass from webmin_user where name = ?");
4181 if (!$cmd || !$cmd->execute($username)) {
4182 print STDERR "Failed to lookup user : ",
4186 my ($id, $pass) = $cmd->fetchrow();
4189 &disconnect_userdb($config{'userdb'}, $dbh);
4190 $get_user_details_cache{$username} = undef;
4191 print DEBUG "get_user_details: User not found\n";
4194 print DEBUG "get_user_details: id=$id pass=$pass\n";
4196 # Fetch attributes and add to user object
4197 print DEBUG "get_user_details: finding user attributes\n";
4198 my $cmd = $dbh->prepare(
4199 "select attr,value from webmin_user_attr where id = ?");
4200 if (!$cmd || !$cmd->execute($id)) {
4201 print STDERR "Failed to lookup user attrs : ",
4205 $user = { 'name' => $username,
4208 'proto' => $proto };
4209 while(my ($attr, $value) = $cmd->fetchrow()) {
4210 $attrs{$attr} = $value;
4214 elsif ($proto eq "ldap") {
4215 # Fetch user DN with LDAP
4216 print DEBUG "get_user_details: Looking for $username in LDAP\n";
4217 my $rv = $dbh->search(
4219 filter => '(&(cn='.$username.')(objectClass='.
4220 $args->{'userclass'}.'))',
4222 if (!$rv || $rv->code) {
4223 print STDERR "Failed to lookup user : ",
4224 ($rv ? $rv->error : "Unknown error"),"\n";
4227 my ($u) = $rv->all_entries();
4229 &disconnect_userdb($config{'userdb'}, $dbh);
4230 $get_user_details_cache{$username} = undef;
4231 print DEBUG "get_user_details: User not found\n";
4235 # Extract attributes
4236 my $pass = $u->get_value('webminPass');
4237 $user = { 'name' => $username,
4240 'proto' => $proto };
4241 foreach my $la ($u->get_value('webminAttr')) {
4242 my ($attr, $value) = split(/=/, $la, 2);
4243 $attrs{$attr} = $value;
4247 # Convert DB attributes into user object fields
4249 print DEBUG "get_user_details: got ",scalar(keys %attrs),
4251 $user->{'certs'} = $attrs{'cert'};
4252 if ($attrs{'allow'}) {
4253 $user->{'allow'} = $config{'alwaysresolve'} ?
4254 [ split(/\s+/, $attrs{'allow'}) ] :
4255 [ &to_ipaddress(split(/\s+/,$attrs{'allow'})) ];
4257 if ($attrs{'deny'}) {
4258 $user->{'deny'} = $config{'alwaysresolve'} ?
4259 [ split(/\s+/, $attrs{'deny'}) ] :
4260 [ &to_ipaddress(split(/\s+/,$attrs{'deny'})) ];
4262 if ($attrs{'days'}) {
4263 $user->{'allowdays'} = [ split(/,/, $attrs{'days'}) ];
4265 if ($attrs{'hoursfrom'} && $attrs{'hoursto'}) {
4266 my ($hf, $mf) = split(/\./, $attrs{'hoursfrom'});
4267 my ($ht, $mt) = split(/\./, $attrs{'hoursto'});
4268 $user->{'allowhours'} = [ $hf*60+$ht, $ht*60+$mt ];
4270 $user->{'lastchanges'} = $attrs{'lastchange'};
4271 $user->{'nochange'} = $attrs{'nochange'};
4272 $user->{'temppass'} = $attrs{'temppass'};
4273 $user->{'preroot'} = $attrs{'theme'};
4275 &disconnect_userdb($config{'userdb'}, $dbh);
4276 $get_user_details_cache{$user->{'name'}} = $user;
4282 # find_user_by_cert(cert)
4283 # Returns a username looked up by certificate
4284 sub find_user_by_cert
4286 my ($peername) = @_;
4287 my $peername2 = $peername;
4288 $peername2 =~ s/Email=/emailAddress=/ || $peername2 =~ s/emailAddress=/Email=/;
4290 # First check users in local files
4291 foreach my $username (keys %certs) {
4292 if ($certs{$username} eq $peername ||
4293 $certs{$username} eq $peername2) {
4299 if ($config{'userdb'}) {
4300 my ($dbh, $proto) = &connect_userdb($config{'userdb'});
4304 elsif ($proto eq "mysql" || $proto eq "postgresql") {
4306 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 = ?");
4307 return undef if (!$cmd);
4308 foreach my $p ($peername, $peername2) {
4310 if ($cmd->execute($p)) {
4311 ($username) = $cmd->fetchrow();
4314 return $username if ($username);
4317 elsif ($proto eq "ldap") {
4319 my $rv = $dbh->search(
4321 filter => '(objectClass='.
4322 $args->{'userclass'}.')',
4324 attrs => [ 'cn', 'webminAttr' ]);
4325 if ($rv && !$rv->code) {
4326 foreach my $u ($rv->all_entries) {
4327 my @attrs = $u->get_value('webminAttr');
4328 foreach my $la (@attrs) {
4329 my ($attr, $value) = split(/=/, $la, 2);
4330 if ($attr eq "cert" &&
4331 ($value eq $peername ||
4332 $value eq $peername2)) {
4333 return $u->get_value('cn');
4343 # connect_userdb(string)
4344 # Returns a handle for talking to a user database - may be a DBI or LDAP handle.
4345 # On failure returns an error message string. In an array context, returns the
4346 # protocol type too.
4350 my ($proto, $user, $pass, $host, $prefix, $args) = &split_userdb_string($str);
4351 if ($proto eq "mysql") {
4352 # Connect to MySQL with DBI
4353 my $drh = eval "use DBI; DBI->install_driver('mysql');";
4354 $drh || return $text{'sql_emysqldriver'};
4355 my ($host, $port) = split(/:/, $host);
4356 my $cstr = "database=$prefix;host=$host";
4357 $cstr .= ";port=$port" if ($port);
4358 print DEBUG "connect_userdb: Connecting to MySQL $cstr as $user\n";
4359 my $dbh = $drh->connect($cstr, $user, $pass, { });
4360 $dbh || return &text('sql_emysqlconnect', $drh->errstr);
4361 print DEBUG "connect_userdb: Connected OK\n";
4362 return wantarray ? ($dbh, $proto, $prefix, $args) : $dbh;
4364 elsif ($proto eq "postgresql") {
4365 # Connect to PostgreSQL with DBI
4366 my $drh = eval "use DBI; DBI->install_driver('Pg');";
4367 $drh || return $text{'sql_epostgresqldriver'};
4368 my ($host, $port) = split(/:/, $host);
4369 my $cstr = "dbname=$prefix;host=$host";
4370 $cstr .= ";port=$port" if ($port);
4371 print DEBUG "connect_userdb: Connecting to PostgreSQL $cstr as $user\n";
4372 my $dbh = $drh->connect($cstr, $user, $pass);
4373 $dbh || return &text('sql_epostgresqlconnect', $drh->errstr);
4374 print DEBUG "connect_userdb: Connected OK\n";
4375 return wantarray ? ($dbh, $proto, $prefix, $args) : $dbh;
4377 elsif ($proto eq "ldap") {
4378 # Connect with perl LDAP module
4379 eval "use Net::LDAP";
4380 $@ && return $text{'sql_eldapdriver'};
4381 my ($host, $port) = split(/:/, $host);
4382 my $scheme = $args->{'scheme'} || 'ldap';
4384 $port = $scheme eq 'ldaps' ? 636 : 389;
4386 my $ldap = Net::LDAP->new($host,
4388 'scheme' => $scheme);
4389 $ldap || return &text('sql_eldapconnect', $host);
4391 if ($args->{'tls'}) {
4392 # Switch to TLS mode
4393 eval { $mesg = $ldap->start_tls(); };
4394 if ($@ || !$mesg || $mesg->code) {
4395 return &text('sql_eldaptls',
4396 $@ ? $@ : $mesg ? $mesg->error : "Unknown error");
4399 # Login to the server
4401 $mesg = $ldap->bind(dn => $user, password => $pass);
4404 $mesg = $ldap->bind(dn => $user, anonymous => 1);
4406 if (!$mesg || $mesg->code) {
4407 return &text('sql_eldaplogin', $user,
4408 $mesg ? $mesg->error : "Unknown error");
4410 return wantarray ? ($ldap, $proto, $prefix, $args) : $ldap;
4413 return "Unknown protocol $proto";
4417 # split_userdb_string(string)
4418 # Converts a string like mysql://user:pass@host/db into separate parts
4419 sub split_userdb_string
4422 if ($str =~ /^([a-z]+):\/\/([^:]*):([^\@]*)\@([a-z0-9\.\-\_]+)\/([^\?]+)(\?(.*))?$/) {
4423 my ($proto, $user, $pass, $host, $prefix, $argstr) =
4424 ($1, $2, $3, $4, $5, $7);
4425 my %args = map { split(/=/, $_, 2) } split(/\&/, $argstr);
4426 return ($proto, $user, $pass, $host, $prefix, \%args);
4431 # disconnect_userdb(string, &handle)
4432 # Closes a handle opened by connect_userdb
4433 sub disconnect_userdb
4436 if ($str =~ /^(mysql|postgresql):/) {
4440 elsif ($str =~ /^ldap:/) {
4447 # Fills %mime with entries from file in %config and extra settings in %config
4451 if ($config{"mimetypes"} ne "") {
4452 open(MIME, $config{"mimetypes"});
4455 if (/^(\S+)\s+(.*)$/) {
4457 my @exts = split(/\s+/, $2);
4458 foreach my $ext (@exts) {
4459 $mime{$ext} = $type;
4465 foreach my $k (keys %config) {
4466 if ($k !~ /^addtype_(.*)$/) { next; }
4467 $mime{$1} = $config{$k};
4471 # build_config_mappings()
4472 # Build the anonymous access list, IP access list, unauthenticated URLs list,
4473 # redirect mapping and allow and deny lists from %config
4474 sub build_config_mappings
4476 # build anonymous access list
4478 foreach my $a (split(/\s+/, $config{'anonymous'})) {
4479 if ($a =~ /^([^=]+)=(\S+)$/) {
4480 $anonymous{$1} = $2;
4484 # build IP access list
4486 foreach my $a (split(/\s+/, $config{'ipaccess'})) {
4487 if ($a =~ /^([^=]+)=(\S+)$/) {
4492 # build unauthenticated URLs list
4493 @unauth = split(/\s+/, $config{'unauth'});
4495 # build redirect mapping
4497 foreach my $r (split(/\s+/, $config{'redirect'})) {
4498 if ($r =~ /^([^=]+)=(\S+)$/) {
4503 # build prefixes to be stripped
4504 undef(@strip_prefix);
4505 foreach my $r (split(/\s+/, $config{'strip_prefix'})) {
4506 push(@strip_prefix, $r);
4509 # Init allow and deny lists
4510 @deny = split(/\s+/, $config{"deny"});
4511 @deny = &to_ipaddress(@deny) if (!$config{'alwaysresolve'});
4512 @allow = split(/\s+/, $config{"allow"});
4513 @allow = &to_ipaddress(@allow) if (!$config{'alwaysresolve'});
4516 if ($config{'allowusers'}) {
4517 @allowusers = split(/\s+/, $config{'allowusers'});
4519 elsif ($config{'denyusers'}) {
4520 @denyusers = split(/\s+/, $config{'denyusers'});
4523 # Build list of unixauth mappings
4525 foreach my $ua (split(/\s+/, $config{'unixauth'})) {
4526 if ($ua =~ /^(\S+)=(\S+)$/) {
4530 $unixauth{"*"} = $ua;
4534 # Build list of non-session-auth pages
4535 undef(%sessiononly);
4536 foreach my $sp (split(/\s+/, $config{'sessiononly'})) {
4537 $sessiononly{$sp} = 1;
4540 # Build list of logout times
4541 undef(@logouttimes);
4542 foreach my $a (split(/\s+/, $config{'logouttimes'})) {
4543 if ($a =~ /^([^=]+)=(\S+)$/) {
4544 push(@logouttimes, [ $1, $2 ]);
4547 push(@logouttimes, [ undef, $config{'logouttime'} ]);
4549 # Build list of DAV pathss
4551 foreach my $d (split(/\s+/, $config{'davpaths'})) {
4552 push(@davpaths, $d);
4554 @davusers = split(/\s+/, $config{'dav_users'});
4556 # Mobile agent substrings and hostname prefixes
4557 @mobile_agents = split(/\t+/, $config{'mobile_agents'});
4558 @mobile_prefixes = split(/\s+/, $config{'mobile_prefixes'});
4562 if ($config{'debug'}) {
4563 open(DEBUG, ">>$config{'debug'}");
4566 open(DEBUG, ">/dev/null");
4569 # Reset cache of sudo checks
4573 # is_group_member(&uinfo, groupname)
4574 # Returns 1 if some user is a primary or secondary member of a group
4577 local ($uinfo, $group) = @_;
4578 local @ginfo = getgrnam($group);
4579 return 0 if (!@ginfo);
4580 return 1 if ($ginfo[2] == $uinfo->[3]); # primary member
4581 foreach my $m (split(/\s+/, $ginfo[3])) {
4582 return 1 if ($m eq $uinfo->[0]);
4587 # prefix_to_mask(prefix)
4588 # Converts a number like 24 to a mask like 255.255.255.0
4591 return $_[0] >= 24 ? "255.255.255.".(256-(2 ** (32-$_[0]))) :
4592 $_[0] >= 16 ? "255.255.".(256-(2 ** (24-$_[0]))).".0" :
4593 $_[0] >= 8 ? "255.".(256-(2 ** (16-$_[0]))).".0.0" :
4594 (256-(2 ** (8-$_[0]))).".0.0.0";
4597 # get_logout_time(user, session-id)
4598 # Given a username, returns the idle time before he will be logged out
4601 local ($user, $sid) = @_;
4602 if (!defined($logout_time_cache{$user,$sid})) {
4604 foreach my $l (@logouttimes) {
4605 if ($l->[0] =~ /^\@(.*)$/) {
4606 # Check group membership
4607 local @uinfo = getpwnam($user);
4608 if (@uinfo && &is_group_member(\@uinfo, $1)) {
4612 elsif ($l->[0] =~ /^\//) {
4613 # Check file contents
4614 open(FILE, $l->[0]);
4631 if ($l->[0] eq $user) {
4635 last if (defined($time));
4637 $logout_time_cache{$user,$sid} = $time;
4639 return $logout_time_cache{$user,$sid};
4642 # password_crypt(password, salt)
4643 # If the salt looks like MD5 and we have a library for it, perform MD5 hashing
4644 # of a password. Otherwise, do Unix crypt.
4647 local ($pass, $salt) = @_;
4648 if ($salt =~ /^\$1\$/ && $use_md5) {
4649 return &encrypt_md5($pass, $salt);
4652 return &unix_crypt($pass, $salt);
4656 # unix_crypt(password, salt)
4657 # Performs standard Unix hashing for a password
4660 local ($pass, $salt) = @_;
4661 if ($use_perl_crypt) {
4662 return Crypt::UnixCrypt::crypt($pass, $salt);
4665 return crypt($pass, $salt);
4669 # handle_dav_request(davpath)
4670 # Pass a request on to the Net::DAV::Server module
4671 sub handle_dav_request
4674 eval "use Filesys::Virtual::Plain";
4675 eval "use Net::DAV::Server";
4676 eval "use HTTP::Request";
4677 eval "use HTTP::Headers";
4679 if ($Net::DAV::Server::VERSION eq '1.28' && $config{'dav_nolock'}) {
4680 delete $Net::DAV::Server::implemented{lock};
4681 delete $Net::DAV::Server::implemented{unlock};
4684 # Read in request data
4685 if (!$posted_data) {
4686 local $clen = $header{"content-length"};
4687 while(length($posted_data) < $clen) {
4688 $buf = &read_data($clen - length($posted_data));
4689 if (!length($buf)) {
4690 &http_error(500, "Failed to read POST request");
4692 $posted_data .= $buf;
4696 # For subsequent logging
4697 open(MINISERVLOG, ">>$config{'logfile'}");
4701 local @u = getpwnam($authuser);
4702 if ($config{'dav_remoteuser'} && !$< && $validated) {
4705 $( = $u[3]; $) = "$u[3] $u[3]";
4706 ($>, $<) = ($u[2], $u[2]);
4708 if ($config{'dav_root'} eq '*') {
4713 &http_error(500, "Unix user $authuser does not exist");
4717 $root ||= $config{'dav_root'};
4720 # Check if this user can use DAV
4722 &users_match(\@u, @davusers) ||
4723 &http_error(500, "You are not allowed to access DAV");
4727 my $filesys = Filesys::Virtual::Plain->new({root_path => $root});
4728 my $webdav = Net::DAV::Server->new();
4729 $webdav->filesys($filesys);
4731 # Make up a request object, and feed to DAV
4732 local $ho = HTTP::Headers->new;
4733 foreach my $h (keys %header) {
4734 next if (lc($h) eq "connection");
4735 $ho->header($h => $header{$h});
4738 $request_uri =~ s/^\Q$path\E//;
4739 $request_uri = "/" if ($request_uri eq "");
4741 my $request = HTTP::Request->new($method, $request_uri, $ho,
4743 if ($config{'dav_debug'}) {
4744 print STDERR "DAV request :\n";
4745 print STDERR "---------------------------------------------\n";
4746 print STDERR $request->as_string();
4747 print STDERR "---------------------------------------------\n";
4749 my $response = $webdav->run($request);
4751 # Send back the reply
4752 &write_data("HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n");
4753 local $content = $response->content();
4755 $content =~ s|href>/(.+)<|href>$path/$1<|g;
4756 $content =~ s|href>/<|href>$path<|g;
4758 foreach my $h ($response->header_field_names) {
4759 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4760 &write_data("$h: ",$response->header($h),"\r\n");
4762 &write_data("Content-length: ",length($content),"\r\n");
4763 local $rv = &write_keep_alive(0);
4764 &write_data("\r\n");
4765 &write_data($content);
4767 if ($config{'dav_debug'}) {
4768 print STDERR "DAV reply :\n";
4769 print STDERR "---------------------------------------------\n";
4770 print STDERR "HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n";
4771 foreach my $h ($response->header_field_names) {
4772 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4773 print STDERR "$h: ",$response->header($h),"\r\n";
4775 print STDERR "Content-length: ",length($content),"\r\n";
4776 print STDERR "\r\n";
4777 print STDERR $content;
4778 print STDERR "---------------------------------------------\n";
4782 &log_request($acpthost, $authuser, $reqline, $response->code(),
4783 length($response->content()));
4786 # get_system_hostname()
4787 # Returns the hostname of this system, for reporting to listeners
4788 sub get_system_hostname
4790 # On Windows, try computername environment variable
4791 return $ENV{'computername'} if ($ENV{'computername'});
4792 return $ENV{'COMPUTERNAME'} if ($ENV{'COMPUTERNAME'});
4794 # If a specific command is set, use it first
4795 if ($config{'hostname_command'}) {
4796 local $out = `($config{'hostname_command'}) 2>&1`;
4803 # First try the hostname command
4804 local $out = `hostname 2>&1`;
4805 if (!$? && $out =~ /\S/) {
4810 # Try the Sys::Hostname module
4811 eval "use Sys::Hostname";
4813 local $rv = eval "hostname()";
4819 # Must use net name on Windows
4820 local $out = `net name 2>&1`;
4821 if ($out =~ /\-+\r?\n(\S+)/) {
4828 # indexof(string, array)
4829 # Returns the index of some value in an array, or -1
4832 for($i=1; $i <= $#_; $i++) {
4833 if ($_[$i] eq $_[0]) { return $i - 1; }
4839 # has_command(command)
4840 # Returns the full path if some command is in the path, undef if not
4844 if (!$_[0]) { return undef; }
4845 if (exists($has_command_cache{$_[0]})) {
4846 return $has_command_cache{$_[0]};
4849 if ($_[0] =~ /^\//) {
4850 $rv = -x $_[0] ? $_[0] : undef;
4853 local $sp = $on_windows ? ';' : ':';
4854 foreach $d (split($sp, $ENV{PATH})) {
4855 if (-x "$d/$_[0]") {
4860 foreach my $sfx (".exe", ".com", ".bat") {
4861 if (-r "$d/$_[0]".$sfx) {
4862 $rv = "$d/$_[0]".$sfx;
4869 $has_command_cache{$_[0]} = $rv;
4873 # check_sudo_permissions(user, pass)
4874 # Returns 1 if some user can run any command via sudo
4875 sub check_sudo_permissions
4877 local ($user, $pass) = @_;
4879 # First try the pipes
4881 print DEBUG "check_sudo_permissions: querying cache for $user\n";
4882 print $PASSINw "readsudo $user\n";
4883 local $can = <$PASSOUTr>;
4885 print DEBUG "check_sudo_permissions: cache said $can\n";
4886 if ($can =~ /^\d+$/ && $can != 2) {
4891 local $ptyfh = new IO::Pty;
4892 print DEBUG "check_sudo_permissions: ptyfh=$ptyfh\n";
4894 print STDERR "Failed to create new PTY with IO::Pty\n";
4897 local @uinfo = getpwnam($user);
4899 print STDERR "Unix user $user does not exist for sudo\n";
4903 # Execute sudo in a sub-process, via a pty
4904 local $ttyfh = $ptyfh->slave();
4905 print DEBUG "check_sudo_permissions: ttyfh=$ttyfh\n";
4906 local $tty = $ptyfh->ttyname();
4907 print DEBUG "check_sudo_permissions: tty=$tty\n";
4908 chown($uinfo[2], $uinfo[3], $tty);
4910 print DEBUG "check_sudo_permissions: about to fork..\n";
4911 local $pid = fork();
4912 print DEBUG "check_sudo_permissions: fork=$pid pid=$$\n";
4914 print STDERR "fork for sudo failed : $!\n";
4919 $ptyfh->make_slave_controlling_terminal();
4920 close(STDIN); close(STDOUT); close(STDERR);
4921 untie(*STDIN); untie(*STDOUT); untie(*STDERR);
4922 close($PASSINw); close($PASSOUTr);
4923 $( = $uinfo[3]; $) = "$uinfo[3] $uinfo[3]";
4924 ($>, $<) = ($uinfo[2], $uinfo[2]);
4929 open(STDIN, "<&SUDOr");
4930 open(STDOUT, ">$tty");
4931 open(STDERR, ">&STDOUT");
4934 print "Exec failed : $!\n";
4937 print DEBUG "check_sudo_permissions: pid=$pid\n";
4939 $ptyfh->close_slave();
4941 # Send password, and get back response
4942 local $oldfh = select(SUDOw);
4945 print DEBUG "check_sudo_permissions: about to send pass\n";
4946 local $SIG{'PIPE'} = 'ignore'; # Sometimes sudo doesn't ask for a password
4947 print SUDOw $pass,"\n";
4948 print DEBUG "check_sudo_permissions: sent pass=$pass\n";
4952 print DEBUG "check_sudo_permissions: got $_";
4958 local ($ok) = ($out =~ /\(ALL\)\s+ALL/ ? 1 : 0);
4962 print $PASSINw "writesudo $user $ok\n";
4968 # is_mobile_useragent(agent)
4969 # Returns 1 if some user agent looks like a cellphone or other mobile device,
4971 sub is_mobile_useragent
4973 local ($agent) = @_;
4975 "UP.Link", # Openwave
4976 "Nokia", # All Nokias start with Nokia
4977 "MOT-", # All Motorola phones start with MOT-
4978 "SAMSUNG", # Samsung browsers
4979 "Samsung", # Samsung browsers
4980 "SEC-", # Samsung browsers
4981 "AU-MIC", # Samsung browsers
4982 "AUDIOVOX", # Audiovox
4983 "BlackBerry", # BlackBerry
4984 "hiptop", # Danger hiptop Sidekick
4985 "SonyEricsson", # Sony Ericsson
4986 "Ericsson", # Old Ericsson browsers , mostly WAP
4987 "Mitsu/1.1.A", # Mitsubishi phones
4988 "Panasonic WAP", # Panasonic old WAP phones
4989 "DoCoMo", # DoCoMo phones
4990 "Lynx", # Lynx text-mode linux browser
4991 "Links", # Another text-mode linux browser
4993 local @substrings = (
4994 "UP.Browser", # Openwave
4995 "MobilePhone", # NetFront
4996 "AU-MIC-A700", # Samsung A700 Obigo browsers
4997 "Danger hiptop", # Danger Sidekick hiptop
4998 "Windows CE", # Windows CE Pocket PC
4999 "IEMobile", # Windows mobile browser
5000 "Blazer", # Palm Treo Blazer
5001 "BlackBerry", # BlackBerries can emulate other browsers, but
5002 # they still keep this string in the UserAgent
5003 "SymbianOS", # New Series60 browser has safari in it and
5004 # SymbianOS is the only distinguishing string
5005 "iPhone", # Apple iPhone KHTML browser
5006 "iPod", # iPod touch browser
5007 "MobileSafari", # HTTP client in iPhone
5009 "Opera Mini", # Opera Mini
5010 "HTC_P3700", # HTC mobile device
5012 "webOS/", # Palm WebOS
5013 "Nintendo DS", # DSi / DSi-XL
5015 foreach my $p (@prefixes) {
5016 return 1 if ($agent =~ /^\Q$p\E/);
5018 foreach my $s (@substrings, @mobile_agents) {
5019 return 1 if ($agent =~ /\Q$s\E/);
5024 # write_blocked_file()
5025 # Writes out a text file of blocked hosts and users
5026 sub write_blocked_file
5028 open(BLOCKED, ">$config{'blockedfile'}");
5029 foreach my $d (grep { $hostfail{$_} } @deny) {
5030 print BLOCKED "host $d $hostfail{$d} $blockhosttime{$d}\n";
5032 foreach my $d (grep { $userfail{$_} } @denyusers) {
5033 print BLOCKED "user $d $userfail{$d} $blockusertime{$d}\n";
5036 chmod(0700, $config{'blockedfile'});
5041 open(PIDFILE, ">$config{'pidfile'}");
5042 printf PIDFILE "%d\n", getpid();
5044 $miniserv_main_pid = getpid();
5047 # lock_user_password(user)
5048 # Updates a user's password file entry to lock it, both in memory and on disk.
5049 # Returns 1 if done, -1 if no such user, 0 if already locked
5050 sub lock_user_password
5053 local $uinfo = &get_user_details($user);
5058 if ($uinfo->{'pass'} =~ /^\!/) {
5062 if (!$uinfo->{'proto'}) {
5063 # Write to users file
5064 $users{$user} = "!".$users{$user};
5065 open(USERS, $config{'userfile'});
5066 local @ufile = <USERS>;
5068 foreach my $u (@ufile) {
5069 local @uinfo = split(/:/, $u);
5070 if ($uinfo[0] eq $user) {
5071 $uinfo[1] = $users{$user};
5073 $u = join(":", @uinfo);
5075 open(USERS, ">$config{'userfile'}");
5081 if ($config{'userdb'}) {
5083 my ($dbh, $proto, $prefix, $args) = &connect_userdb($config{'userdb'});
5087 elsif ($proto eq "mysql" || $proto eq "postgresql") {
5088 # Update user attribute
5089 my $cmd = $dbh->prepare(
5090 "update webmin_user set pass = ? where id = ?");
5091 if (!$cmd || !$cmd->execute("!".$uinfo->{'pass'},
5094 print STDERR "Failed to lock password : ",
5098 $cmd->finish() if ($cmd);
5100 elsif ($proto eq "ldap") {
5101 # Update LDAP object
5102 my $rv = $dbh->modify($uinfo->{'id'},
5103 replace => { 'webminPass' => '!'.$uinfo->{'pass'} });
5104 if (!$rv || $rv->code) {
5105 print STDERR "Failed to lock password : ",
5106 ($rv ? $rv->error : "Unknown error"),"\n";
5110 &disconnect_userdb($config{'userdb'}, $dbh);
5114 return -1; # This should never be reached
5117 # hash_session_id(sid)
5118 # Returns an MD5 or Unix-crypted session ID
5122 if (!$hash_session_id_cache{$sid}) {
5125 $hash_session_id_cache{$sid} = &encrypt_md5($sid);
5129 $hash_session_id_cache{$sid} = &unix_crypt($sid, "XX");
5132 return $hash_session_id_cache{$sid};
5135 # encrypt_md5(string, [salt])
5136 # Returns a string encrypted in MD5 format
5139 local ($passwd, $salt) = @_;
5140 local $magic = '$1$';
5141 if ($salt =~ /^\$1\$([^\$]+)/) {
5142 # Extract actual salt from already encrypted password
5147 local $ctx = eval "new $use_md5";
5154 # Add some more stuff from the hash of the password and salt
5155 local $ctx1 = eval "new $use_md5";
5156 $ctx1->add($passwd);
5160 $ctx1->add($passwd);
5161 local $final = $ctx1->digest();
5162 for($pl=length($passwd); $pl>0; $pl-=16) {
5163 $ctx->add($pl > 16 ? $final : substr($final, 0, $pl));
5166 # This piece of code seems rather pointless, but it's in the C code that
5167 # does MD5 in PAM so it has to go in!
5170 for($i=length($passwd); $i; $i >>= 1) {
5175 $ctx->add(substr($passwd, $j, 1));
5178 $final = $ctx->digest();
5181 # This loop exists only to waste time
5182 for($i=0; $i<1000; $i++) {
5183 $ctx1 = eval "new $use_md5";
5184 $ctx1->add($i & 1 ? $passwd : $final);
5185 $ctx1->add($salt) if ($i % 3);
5186 $ctx1->add($passwd) if ($i % 7);
5187 $ctx1->add($i & 1 ? $final : $passwd);
5188 $final = $ctx1->digest();
5192 # Convert the 16-byte final string into a readable form
5194 local @final = map { ord($_) } split(//, $final);
5195 $l = ($final[ 0]<<16) + ($final[ 6]<<8) + $final[12];
5196 $rv .= &to64($l, 4);
5197 $l = ($final[ 1]<<16) + ($final[ 7]<<8) + $final[13];
5198 $rv .= &to64($l, 4);
5199 $l = ($final[ 2]<<16) + ($final[ 8]<<8) + $final[14];
5200 $rv .= &to64($l, 4);
5201 $l = ($final[ 3]<<16) + ($final[ 9]<<8) + $final[15];
5202 $rv .= &to64($l, 4);
5203 $l = ($final[ 4]<<16) + ($final[10]<<8) + $final[ 5];
5204 $rv .= &to64($l, 4);
5206 $rv .= &to64($l, 2);
5208 # Add salt if needed
5210 return $magic.$salt.'$'.$rv;
5219 local ($v, $n) = @_;
5222 $r .= $itoa64[$v & 0x3f];
5228 # read_file(file, &assoc, [&order], [lowercase])
5229 # Fill an associative array with name=value pairs from a file
5232 open(ARFILE, $_[0]) || return 0;
5235 if (!/^#/ && /^([^=]*)=(.*)$/) {
5236 $_[1]->{$_[3] ? lc($1) : $1} = $2;
5237 push(@{$_[2]}, $1) if ($_[2]);
5244 # write_file(file, array)
5245 # Write out the contents of an associative array as name=value lines
5248 local(%old, @order);
5249 &read_file($_[0], \%old, \@order);
5250 open(ARFILE, ">$_[0]");
5251 foreach $k (@order) {
5252 print ARFILE $k,"=",$_[1]->{$k},"\n" if (exists($_[1]->{$k}));
5254 foreach $k (keys %{$_[1]}) {
5255 print ARFILE $k,"=",$_[1]->{$k},"\n" if (!exists($old{$k}));
5260 # execute_ready_webmin_crons()
5261 # Find and run any cron jobs that are due, based on their last run time and
5262 # execution interval
5263 sub execute_ready_webmin_crons
5267 foreach my $cron (@webmincrons) {
5269 if (!$webmincron_last{$cron->{'id'}}) {
5270 # If not ever run before, don't run right away
5271 $webmincron_last{$cron->{'id'}} = $now;
5274 elsif ($cron->{'interval'} &&
5275 $now - $webmincron_last{$cron->{'id'}} > $cron->{'interval'}) {
5276 # Older than interval .. time to run
5279 elsif ($cron->{'mins'}) {
5280 # Check if current time matches spec, and we haven't run in the
5282 my @tm = localtime($now);
5283 if (&matches_cron($cron->{'mins'}, $tm[1]) &&
5284 &matches_cron($cron->{'hours'}, $tm[2]) &&
5285 &matches_cron($cron->{'days'}, $tm[3]) &&
5286 &matches_cron($cron->{'months'}, $tm[4]+1) &&
5287 &matches_cron($cron->{'weekdays'}, $tm[6]) &&
5288 $now - $webmincron_last{$cron->{'id'}} > 60) {
5294 print DEBUG "Running cron id=$cron->{'id'} ".
5295 "module=$cron->{'module'} func=$cron->{'func'}\n";
5296 $webmincron_last{$cron->{'id'}} = $now;
5300 # Run via a wrapper command, which we run like a CGI
5302 # Setup CGI-like environment
5303 $envtz = $ENV{"TZ"};
5304 $envuser = $ENV{"USER"};
5305 $envpath = $ENV{"PATH"};
5306 $envlang = $ENV{"LANG"};
5307 $envroot = $ENV{"SystemRoot"};
5308 $envperllib = $ENV{'PERLLIB'};
5309 foreach my $k (keys %ENV) {
5312 $ENV{"PATH"} = $envpath if ($envpath);
5313 $ENV{"TZ"} = $envtz if ($envtz);
5314 $ENV{"USER"} = $envuser if ($envuser);
5315 $ENV{"OLD_LANG"} = $envlang if ($envlang);
5316 $ENV{"SystemRoot"} = $envroot if ($envroot);
5317 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
5318 $ENV{"HOME"} = $user_homedir;
5319 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
5320 $ENV{"SERVER_ADMIN"} = $config{"email"};
5322 $ENV{"SERVER_ROOT"} = $root0;
5323 $ENV{"SERVER_REALROOT"} = $root0;
5324 $ENV{"SERVER_PORT"} = $config{'port'};
5325 $ENV{"WEBMIN_CRON"} = 1;
5326 $ENV{"DOCUMENT_ROOT"} = $root0;
5327 $ENV{"DOCUMENT_REALROOT"} = $root0;
5328 $ENV{"MINISERV_CONFIG"} = $config_file;
5329 $ENV{"HTTPS"} = "ON" if ($use_ssl);
5330 $ENV{"MINISERV_PID"} = $miniserv_main_pid;
5331 $ENV{"SCRIPT_FILENAME"} = $config{'webmincron_wrapper'};
5332 if ($ENV{"SCRIPT_FILENAME"} =~ /^\Q$root0\E(\/.*)$/) {
5333 $ENV{"SCRIPT_NAME"} = $1;
5335 $config{'webmincron_wrapper'} =~ /^(.*)\//;
5337 foreach $k (keys %config) {
5338 if ($k =~ /^env_(\S+)$/) {
5339 $ENV{$1} = $config{$k};
5343 $SIG{'CHLD'} = 'DEFAULT';
5345 # Have SOCK closed if the perl exec's something
5347 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
5350 # Run the wrapper script by evaling it
5351 $pkg = "webmincron";
5352 $0 = $config{'webmincron_wrapper'};
5354 $main_process_id = $$;
5358 do \$miniserv::config{'webmincron_wrapper'};
5362 print STDERR "Perl cron failure : $@\n";
5367 push(@childpids, $pid);
5371 # Write out file containing last run times
5372 &write_file($config{'webmincron_last'}, \%webmincron_last);
5376 # matches_cron(cron-spec, time)
5377 # Checks if some minute or hour matches some cron spec, which can be * or a list
5381 my ($spec, $tm) = @_;
5386 foreach my $s (split(/,/, $spec)) {
5388 $s =~ /^(\d+)\-(\d+)$/ && $tm >= $1 && $tm <= $2) {
5396 # read_webmin_crons()
5397 # Read all scheduled webmin cron functions and store them in the @webmincrons
5399 sub read_webmin_crons
5402 opendir(CRONS, $config{'webmincron_dir'});
5403 print DEBUG "Reading crons from $config{'webmincron_dir'}\n";
5404 foreach my $f (readdir(CRONS)) {
5405 if ($f =~ /^(\d+)\.cron$/) {
5407 &read_file("$config{'webmincron_dir'}/$f", \%cron);
5410 foreach my $n ('module', 'func') {
5412 print STDERR "Cron $1 missing $n\n";
5416 if (!$cron{'interval'} && !$cron{'mins'} && !$cron{'special'}) {
5417 print STDERR "Cron $1 missing any time spec\n";
5420 if ($cron{'special'} eq 'hourly') {
5421 # Run every hour on the hour
5423 $cron{'hours'} = '*';
5424 $cron{'days'} = '*';
5425 $cron{'months'} = '*';
5426 $cron{'weekdays'} = '*';
5428 elsif ($cron{'special'} eq 'daily') {
5429 # Run every day at midnight
5431 $cron{'hours'} = '0';
5432 $cron{'days'} = '*';
5433 $cron{'months'} = '*';
5434 $cron{'weekdays'} = '*';
5436 elsif ($cron{'special'} eq 'monthly') {
5437 # Run every month on the 1st
5439 $cron{'hours'} = '0';
5440 $cron{'days'} = '1';
5441 $cron{'months'} = '*';
5442 $cron{'weekdays'} = '*';
5444 elsif ($cron{'special'} eq 'weekly') {
5445 # Run every month on the 1st
5447 $cron{'hours'} = '0';
5448 $cron{'days'} = '*';
5449 $cron{'months'} = '*';
5450 $cron{'weekdays'} = '0';
5452 elsif ($cron{'special'} eq 'yearly' ||
5453 $cron{'special'} eq 'annually') {
5454 # Run every year on 1st january
5456 $cron{'hours'} = '0';
5457 $cron{'days'} = '1';
5458 $cron{'months'} = '1';
5459 $cron{'weekdays'} = '*';
5461 elsif ($cron{'special'}) {
5462 print STDERR "Cron $1 invalid special time $cron{'special'}\n";
5465 if ($cron{'special'}) {
5466 delete($cron{'special'});
5469 print DEBUG "adding cron id=$cron{'id'} module=$cron{'module'} func=$cron{'func'}\n";
5470 push(@webmincrons, \%cron);
5476 # Check if some address is valid IPv4, returns 1 if so.
5479 return $_[0] =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/ &&
5480 $1 >= 0 && $1 <= 255 &&
5481 $2 >= 0 && $2 <= 255 &&
5482 $3 >= 0 && $3 <= 255 &&
5483 $4 >= 0 && $4 <= 255;
5486 # Check if some IPv6 address is properly formatted, and returns 1 if so.
5487 sub check_ip6address
5489 my @blocks = split(/:/, $_[0]);
5490 return 0 if (@blocks == 0 || @blocks > 8);
5492 my $where = index($blocks[$ib],"/");
5495 my $b = substr($blocks[$ib],0,$where);
5496 $m = substr($blocks[$ib],$where+1,length($blocks[$ib])-($where+1));
5499 return 0 if ($m <0 || $m >128);
5502 foreach $b (@blocks) {
5503 return 0 if ($b ne "" && $b !~ /^[0-9a-f]{1,4}$/i);
5504 $empty++ if ($b eq "");
5506 return 0 if ($empty > 1 && !($_[0] =~ /^::/ && $empty == 2));
5510 # network_to_address(binary)
5511 # Given a network address in binary IPv4 or v4 format, return the string form
5512 sub network_to_address
5515 if (length($addr) == 4 || !$use_ipv6) {
5516 return inet_ntoa($addr);
5519 return Socket6::inet_ntop(Socket6::AF_INET6(), $addr);