2 # A very simple perl web server used by Webmin
4 # Require basic libraries
10 @itoa64 = split(//, "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
12 # Find and read config file
14 die "Usage: miniserv.pl <config file>";
16 if ($ARGV[0] =~ /^([a-z]:)?\//i) {
17 $config_file = $ARGV[0];
21 $config_file = "$pwd/$ARGV[0]";
23 %config = &read_config_file($config_file);
24 if ($config{'perllib'}) {
25 push(@INC, split(/:/, $config{'perllib'}));
26 $ENV{'PERLLIB'} .= ':'.$config{'perllib'};
29 # Check is SSL is enabled and available
31 eval "use Net::SSLeay";
34 # These functions only exist for SSLeay 1.0
35 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
36 eval "Net::SSLeay::load_error_strings()";
37 if ($config{'no_ssl2'}) {
38 eval "Net::SSLeay::CTX_set_options($ctx,&Net::SSLeay::OP_NO_SSLv2)";
40 if (defined(&Net::SSLeay::X509_STORE_CTX_get_current_cert) &&
41 defined(&Net::SSLeay::CTX_load_verify_locations) &&
42 defined(&Net::SSLeay::CTX_set_verify)) {
48 # Check if the syslog module is available to log hacking attempts
49 if ($config{'syslog'} && !$config{'inetd'}) {
50 eval "use Sys::Syslog qw(:DEFAULT setlogsock)";
56 # check if the TCP-wrappers module is available
57 if ($config{'libwrap'}) {
58 eval "use Authen::Libwrap qw(hosts_ctl STRING_UNKNOWN)";
64 # Check if the MD5 perl module is available
70 eval "use Digest::MD5";
72 $use_md5 = "Digest::MD5";
76 # Get miniserv's perl path and location
78 open(SOURCE, $miniserv_path);
79 <SOURCE> =~ /^#!(\S+)/;
86 $linked_perl_path = readlink($perl_path);
88 @miniserv_argv = @ARGV;
90 # Check vital config options
91 &update_vital_config();
93 $sidname = $config{'sidname'};
94 die "Session authentication cannot be used in inetd mode"
95 if ($config{'inetd'} && $config{'session'});
97 # check if the PAM module is available to authenticate
98 if (!$config{'no_pam'}) {
99 eval "use Authen::PAM;";
101 # check if the PAM authentication can be used by opening a
104 if (ref($pamh = new Authen::PAM($config{'pam'}, "root",
106 # Now test a login to see if /etc/pam.d/XXX is set
108 $pam_conv_func_called = 0;
109 $pam_username = "test";
110 $pam_password = "test";
111 $pamh->pam_authenticate();
112 if ($pam_conv_func_called) {
113 $pam_msg = "PAM authentication enabled";
117 $pam_msg = "PAM test failed - maybe /etc/pam.d/$config{'pam'} does not exist";
121 $pam_msg = "PAM initialization of Authen::PAM failed";
125 $pam_msg = "Perl module Authen::PAM needed for PAM is not installed : $@";
128 if ($config{'pam_only'} && !$use_pam) {
129 print STDERR $pam_msg;
130 print STDERR "PAM use is mandatory, but could not be enabled!\n";
133 elsif ($pam_msg && !$use_pam) {
134 $pam_msg2 = "Continuing without the Authen::PAM perl module";
137 # Check if the User::Utmp perl module is installed
138 if ($config{'utmp'}) {
139 eval "use User::Utmp;";
142 $utmp_msg = "UTMP logging enabled";
145 $utmp_msg = "Perl module User::Utmp needed for Utmp logging is not installed : $@";
149 # See if the crypt function fails
150 eval "crypt('foo', 'xx')";
152 eval "use Crypt::UnixCrypt";
155 $crypt_msg = "Using Crypt::UnixCrypt for password encryption\n";
158 $crypt_msg = "crypt() function un-implemented, and Crypt::UnixCrypt not installed - password authentication will probably fail\n";
162 # Check if /dev/urandom really generates random IDs, by calling it twice
163 local $rand1 = &generate_random_id("foo", 1);
164 local $rand2 = &generate_random_id("foo", 2);
166 if ($rand1 eq $rand2) {
168 $rand_msg = "Random number generator file /dev/urandom is not reliable";
171 # Check if we can call sudo
172 if ($config{'sudo'} && &has_command("sudo")) {
178 $sudo_msg = "Perl module IO::Pty needed for calling sudo is not installed : $@";
182 # init days and months for http_date
183 @weekday = ( "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" );
184 @month = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun",
185 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" );
187 # Change dir to the server root
188 @roots = ( $config{'root'} );
189 for($i=0; defined($config{"extraroot_$i"}); $i++) {
190 push(@roots, $config{"extraroot_$i"});
193 eval { $user_homedir = (getpwuid($<))[7]; };
195 # getpwuid doesn't work on windows
196 $user_homedir = $ENV{"HOME"} || $ENV{"USERPROFILE"} || "/";
203 # Setup SSL if possible and if requested
204 if (!-r $config{'keyfile'} ||
205 $config{'certfile'} && !-r $config{'certfile'}) {
206 # Key file doesn't exist!
209 @ipkeys = &get_ipkeys(\%config);
211 if ($config{'ssl_version'}) {
212 # Force an SSL version
213 $Net::SSLeay::version = $config{'ssl_version'};
214 $Net::SSLeay::ssl_version = $config{'ssl_version'};
216 $client_certs = 0 if (!-r $config{'ca'} || !%certs);
217 $ssl_contexts{"*"} = &create_ssl_context($config{'keyfile'},
218 $config{'certfile'});
219 foreach $ipkey (@ipkeys) {
220 $ctx = &create_ssl_context($ipkey->{'key'}, $ipkey->{'cert'});
221 foreach $ip (@{$ipkey->{'ips'}}) {
222 $ssl_contexts{$ip} = $ctx;
227 # Setup syslog support if possible and if requested
229 open(ERRDUP, ">&STDERR");
230 open(STDERR, ">/dev/null");
231 $log_socket = $config{"logsock"} || "unix";
232 eval 'openlog($config{"pam"}, "cons,pid,ndelay", "authpriv"); setlogsock($log_socket)';
237 local $msg = ucfirst($config{'pam'})." starting";
238 eval { syslog("info", "%s", $msg); };
242 syslog("info", "%s", $msg);
245 # All attempts to use syslog have failed..
250 open(STDERR, ">&ERRDUP");
254 # Read MIME types file and add extra types
258 if ($config{'log'}) {
259 local(@gmt, @lct, $days, $hours, $mins);
260 @gmt = gmtime(time());
261 @lct = localtime(time());
262 $days = $lct[3] - $gmt[3];
263 $hours = ($days < -1 ? 24 : 1 < $days ? -24 : $days * 24) +
265 $mins = $hours * 60 + $lct[1] - $gmt[1];
266 $timezone = ($mins < 0 ? "-" : "+"); $mins = abs($mins);
267 $timezone .= sprintf "%2.2d%2.2d", $mins/60, $mins%60;
270 # Build various maps from the config files
271 &build_config_mappings();
273 # start up external authentication program, if needed
274 if ($config{'extauth'}) {
275 socketpair(EXTAUTH, EXTAUTH2, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
276 if (!($extauth = fork())) {
280 open(STDIN, "<&EXTAUTH2");
281 open(STDOUT, ">&EXTAUTH2");
282 exec($config{'extauth'}) or die "exec failed : $!\n";
285 local $os = select(EXTAUTH);
289 # Pre-load any libraries
290 foreach $pl (split(/\s+/, $config{'preload'})) {
291 ($pkg, $lib) = split(/=/, $pl);
292 $pkg =~ s/[^A-Za-z0-9]/_/g;
293 eval "package $pkg; do '$config{'root'}/$lib'";
295 print STDERR "Failed to pre-load $lib in $pkg : $@\n";
298 print STDERR "Pre-loaded $lib in $pkg\n";
301 foreach $pl (split(/\s+/, $config{'premodules'})) {
303 ($dir, $mod) = split(/\//, $pl);
306 ($dir, $mod) = (undef, $pl);
308 push(@INC, "$config{'root'}/$dir");
309 eval "package $mod; use $mod ()";
311 print STDERR "Failed to pre-load $mod : $@\n";
314 print STDERR "Pre-loaded $mod\n";
318 # Open debug log if set
319 if ($config{'debuglog'}) {
320 open(DEBUG, ">>$config{'debuglog'}");
321 chmod(0700, $config{'debuglog'});
322 select(DEBUG); $| = 1; select(STDOUT);
323 print DEBUG "miniserv.pl starting ..\n";
326 # Write out (empty) blocked hosts file
327 &write_blocked_file();
329 # Re-direct STDERR to a log file
330 if ($config{'errorlog'} ne '-') {
331 open(STDERR, ">>$config{'errorlog'}") || die "failed to open $config{'errorlog'} : $!";
332 if ($config{'logperms'}) {
333 chmod(oct($config{'logperms'}), $config{'errorlog'});
336 select(STDERR); $| = 1; select(STDOUT);
338 if ($config{'inetd'}) {
339 # We are being run from inetd - go direct to handling the request
340 $SIG{'HUP'} = 'IGNORE';
341 $SIG{'TERM'} = 'DEFAULT';
342 $SIG{'PIPE'} = 'DEFAULT';
343 open(SOCK, "+>&STDIN");
345 # Check if it is time for the logfile to be cleared
346 if ($config{'logclear'}) {
347 local $write_logtime = 0;
348 local @st = stat("$config{'logfile'}.time");
350 if ($st[9]+$config{'logtime'}*60*60 < time()){
353 unlink($config{'logfile'});
356 else { $write_logtime = 1; }
357 if ($write_logtime) {
358 open(LOGTIME, ">$config{'logfile'}.time");
359 print LOGTIME time(),"\n";
364 # Initialize SSL for this connection
366 $ssl_con = &ssl_connection_for_ip(SOCK);
370 # Work out the hostname for this web server
371 $host = &get_socket_name(SOCK);
373 $port = $config{'port'};
374 $acptaddr = getpeername(SOCK);
377 print DEBUG "main: Starting handle_request loop pid=$$\n";
378 while(&handle_request($acptaddr, getsockname(SOCK))) { }
379 print DEBUG "main: Done handle_request loop pid=$$\n";
384 # Build list of sockets to listen on
385 if ($config{"bind"} && $config{"bind"} ne "*") {
386 push(@sockets, [ inet_aton($config{'bind'}), $config{'port'} ]);
389 push(@sockets, [ INADDR_ANY, $config{'port'} ]);
391 foreach $s (split(/\s+/, $config{'sockets'})) {
392 if ($s =~ /^(\d+)$/) {
393 # Just listen on another port on the main IP
394 push(@sockets, [ $sockets[0]->[0], $s ]);
396 elsif ($s =~ /^(\S+):(\d+)$/) {
397 # Listen on a specific port and IP
398 push(@sockets, [ $1 eq "*" ? INADDR_ANY : inet_aton($1), $2 ]);
400 elsif ($s =~ /^([0-9\.]+):\*$/ || $s =~ /^([0-9\.]+)$/) {
401 # Listen on the main port on another IP
402 push(@sockets, [ inet_aton($1), $sockets[0]->[1] ]);
406 # Open all the sockets
407 $proto = getprotobyname('tcp');
409 $tried_inaddr_any = 0;
410 for($i=0; $i<@sockets; $i++) {
412 socket($fh, PF_INET, SOCK_STREAM, $proto) ||
413 die "Failed to open socket : $!";
414 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
415 for($j=0; $j<5; $j++) {
416 last if (bind($fh, pack_sockaddr_in($sockets[$i]->[1],
417 $sockets[$i]->[0])));
421 # All attempts failed .. give up
422 if ($sockets[$i]->[0] eq INADDR_ANY) {
423 push(@sockerrs, "Failed to bind to port $sockets[$i]->[1] : $!");
424 $tried_inaddr_any = 1;
427 $ip = inet_ntoa($sockets[$i]->[0]);
428 push(@sockerrs, "Failed to bind to IP $ip port $sockets[$i]->[1] : $!");
432 listen($fh, SOMAXCONN);
433 push(@socketfhs, $fh);
436 foreach $se (@sockerrs) {
437 print STDERR $se,"\n";
440 # If all binds failed, try binding to any address
441 if (!@socketfhs && !$tried_inaddr_any) {
442 print STDERR "Falling back to listening on any address\n";
444 socket($fh, PF_INET, SOCK_STREAM, $proto) ||
445 die "Failed to open socket : $!";
446 setsockopt($fh, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
447 bind($fh, pack_sockaddr_in($sockets[0]->[1], INADDR_ANY)) ||
448 die "Failed to bind to port $sockets[0]->[1] : $!";
449 listen($fh, SOMAXCONN);
450 push(@socketfhs, $fh);
452 elsif (!@socketfhs && $tried_inaddr_any) {
453 die "Could not listen on any ports";
456 if ($config{'listen'}) {
457 # Open the socket that allows other webmin servers to find this one
458 $proto = getprotobyname('udp');
459 if (socket(LISTEN, PF_INET, SOCK_DGRAM, $proto)) {
460 setsockopt(LISTEN, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
461 bind(LISTEN, pack_sockaddr_in($config{'listen'}, INADDR_ANY));
462 listen(LISTEN, SOMAXCONN);
465 $config{'listen'} = 0;
469 # Split from the controlling terminal, unless configured not to
470 if (!$config{'nofork'}) {
471 if (fork()) { exit; }
473 eval { setsid(); }; # may not work on Windows
475 # Close standard file handles
476 open(STDIN, "</dev/null");
477 open(STDOUT, ">/dev/null");
478 &log_error("miniserv.pl started");
479 &log_error($pam_msg) if ($pam_msg);
480 &log_error($pam_msg2) if ($pam_msg2);
481 &log_error($utmp_msg) if ($utmp_msg);
482 &log_error($crypt_msg) if ($crypt_msg);
483 &log_error($sudo_msg) if ($sudo_msg);
484 &log_error($rand_msg) if ($rand_msg);
486 # write out the PID file
489 # Start the log-clearing process, if needed. This checks every minute
490 # to see if the log has passed its reset time, and if so clears it
491 if ($config{'logclear'}) {
492 if (!($logclearer = fork())) {
493 &close_all_sockets();
496 local $write_logtime = 0;
497 local @st = stat("$config{'logfile'}.time");
499 if ($st[9]+$config{'logtime'}*60*60 < time()){
502 unlink($config{'logfile'});
505 else { $write_logtime = 1; }
506 if ($write_logtime) {
507 open(LOGTIME, ">$config{'logfile'}.time");
508 print LOGTIME time(),"\n";
515 push(@childpids, $logclearer);
518 # Setup the logout time dbm if needed
519 if ($config{'session'}) {
520 eval "use SDBM_File";
521 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
522 eval "\$sessiondb{'1111111111'} = 'foo bar';";
524 dbmclose(%sessiondb);
525 eval "use NDBM_File";
526 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
529 delete($sessiondb{'1111111111'});
534 $SIG{'HUP'} = 'miniserv::trigger_restart';
535 $SIG{'TERM'} = 'miniserv::term_handler';
536 $SIG{'USR1'} = 'miniserv::trigger_reload';
537 $SIG{'PIPE'} = 'IGNORE';
538 local $remove_session_count = 0;
539 $need_pipes = $config{'passdelay'} || $config{'session'};
540 $last_pid_time = time();
542 # wait for a new connection, or a message from a child process
544 if (@childpids <= $config{'maxconns'}) {
545 # Only accept new main socket connects when ready
547 foreach $s (@socketfhs) {
548 vec($rmask, fileno($s), 1) = 1;
552 printf STDERR "too many children (%d > %d)\n",
553 scalar(@childpids), $config{'maxconns'};
556 for($i=0; $i<@passin; $i++) {
557 vec($rmask, fileno($passin[$i]), 1) = 1;
560 vec($rmask, fileno(LISTEN), 1) = 1 if ($config{'listen'});
562 # Wait for a connection
563 local $sel = select($rmask, undef, undef, 10);
565 # Check the flag files
566 if ($config{'restartflag'} && -r $config{'restartflag'}) {
567 print STDERR "restart flag file detected\n";
568 unlink($config{'restartflag'});
571 if ($config{'reloadflag'} && -r $config{'reloadflag'}) {
572 unlink($config{'reloadflag'});
577 # Got a HUP signal while in select() .. restart now
581 # Got a USR1 signal while in select() .. re-read config
583 &reload_config_file();
585 local $time_now = time();
587 # Write the PID every 10 seconds
588 if ($time_now - $last_pid_time > 10) {
590 $last_pid_time = $time_now;
593 # Clean up finished processes
595 do { $pid = waitpid(-1, WNOHANG);
596 @childpids = grep { $_ != $pid } @childpids;
597 } while($pid != 0 && $pid != -1);
599 # run the unblocking procedure to check if enough time has passed to
600 # unblock hosts that heve been blocked because of password failures
602 if ($config{'blockhost_failures'}) {
604 while ($i <= $#deny) {
605 if ($blockhosttime{$deny[$i]} &&
606 $config{'blockhost_time'} != 0 &&
607 ($time_now - $blockhosttime{$deny[$i]}) >=
608 $config{'blockhost_time'}) {
609 # the host can be unblocked now
610 $hostfail{$deny[$i]} = 0;
611 splice(@deny, $i, 1);
618 # Do the same for blocked users
619 if ($config{'blockuser_failures'}) {
621 while ($i <= $#deny) {
622 if ($blockusertime{$deny[$i]} &&
623 $config{'blockuser_time'} != 0 &&
624 ($time_now - $blockusertime{$deny[$i]}) >=
625 $config{'blockuser_time'}) {
626 # the user can be unblocked now
627 $userfail{$deny[$i]} = 0;
628 splice(@denyusers, $i, 1);
635 &write_blocked_file();
638 if ($config{'session'} && (++$remove_session_count%50) == 0) {
639 # Remove sessions with more than 7 days of inactivity,
641 foreach $s (keys %sessiondb) {
642 local ($user, $ltime, $lip) =
643 split(/\s+/, $sessiondb{$s});
644 if ($time_now - $ltime > 7*24*60*60) {
645 &run_logout_script($s, $user);
646 &write_logout_utmp($user, $lip);
647 delete($sessiondb{$s});
650 "Timeout of session for $user");
656 if ($use_pam && $config{'pam_conv'}) {
657 # Remove PAM sessions with more than 5 minutes of inactivity
659 foreach $c (values %conversations) {
660 if ($time_now - $c->{'time'} > 5*60) {
661 &end_pam_conversation($c);
663 syslog("info", "%s", "Timeout of PAM ".
664 "session for $c->{'user'}");
670 # Don't check any sockets if there is no activity
673 # Check if any of the main sockets have received a new connection
675 foreach $s (@socketfhs) {
676 if (vec($rmask, fileno($s), 1)) {
678 $acptaddr = accept(SOCK, $s);
679 if (!$acptaddr) { next; }
680 binmode(SOCK); # turn off any Perl IO stuff
683 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
685 ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw) =
689 # Check username of connecting user
690 local ($peerp, $peera) = unpack_sockaddr_in($acptaddr);
691 $localauth_user = undef;
692 if ($config{'localauth'} && inet_ntoa($peera) eq "127.0.0.1") {
693 if (open(TCP, "/proc/net/tcp")) {
694 # Get the info direct from the kernel
697 local @t = split(/[\s:]+/, $_);
698 if ($t[1] eq '0100007F' &&
699 $t[2] eq sprintf("%4.4X", $peerp)) {
700 $localauth_user = getpwuid($t[11]);
706 if (!$localauth_user) {
707 # Call lsof for the info
708 local $lsofpid = open(LSOF,
709 "$config{'localauth'} -i TCP\@127.0.0.1:$peerp |");
711 if (/^(\S+)\s+(\d+)\s+(\S+)/ &&
712 $2 != $$ && $2 != $lsofpid) {
713 $localauth_user = $3;
720 # Work out the hostname for this web server
721 $host = &get_socket_name(SOCK);
723 print STDERR "Failed to get local socket name : $!\n";
727 $port = $sockets[$sn]->[1];
729 # fork the subprocess
731 if (!($handpid = fork())) {
732 # setup signal handlers
733 $SIG{'TERM'} = 'DEFAULT';
734 $SIG{'PIPE'} = 'DEFAULT';
735 #$SIG{'CHLD'} = 'IGNORE';
736 $SIG{'HUP'} = 'IGNORE';
737 $SIG{'USR1'} = 'IGNORE';
739 # Initialize SSL for this connection
741 $ssl_con = &ssl_connection_for_ip(SOCK);
745 # Close the file handle for the session DBM
746 dbmclose(%sessiondb);
748 # close useless pipes
751 close($PASSINr); close($PASSOUTw);
753 &close_all_sockets();
757 "main: Starting handle_request loop pid=$$\n";
758 while(&handle_request($acptaddr,
759 getsockname(SOCK))) { }
761 "main: Done handle_request loop pid=$$\n";
764 close($PASSINw); close($PASSOUTw);
767 push(@childpids, $handpid);
769 close($PASSINw); close($PASSOUTr);
770 push(@passin, $PASSINr);
771 push(@passout, $PASSOUTw);
778 if ($config{'listen'} && vec($rmask, fileno(LISTEN), 1)) {
779 # Got UDP packet from another webmin server
781 local $from = recv(LISTEN, $rcvbuf, 1024, 0);
783 local $fromip = inet_ntoa((unpack_sockaddr_in($from))[1]);
784 local $toip = inet_ntoa((unpack_sockaddr_in(
785 getsockname(LISTEN)))[1]);
786 if ((!@deny || !&ip_match($fromip, $toip, @deny)) &&
787 (!@allow || &ip_match($fromip, $toip, @allow))) {
788 local $listenhost = &get_socket_name(LISTEN);
789 send(LISTEN, "$listenhost:$config{'port'}:".
790 ($use_ssl || $config{'inetd_ssl'} ? 1 : 0).":".
791 ($config{'listenhost'} ?
792 &get_system_hostname() : ""),
798 # check for session, password-timeout and PAM messages from subprocesses
799 for($i=0; $i<@passin; $i++) {
800 if (vec($rmask, fileno($passin[$i]), 1)) {
801 # this sub-process is asking about a password
802 local $infd = $passin[$i];
803 local $outfd = $passout[$i];
804 #local $inline = <$infd>;
805 local $inline = &sysread_line($infd);
807 print DEBUG "main: inline $inline";
810 print DEBUG "main: inline EOF\n";
812 if ($inline =~ /^delay\s+(\S+)\s+(\S+)\s+(\d+)/) {
813 # Got a delay request from a subprocess.. for
814 # valid logins, there is no delay (to prevent
815 # denial of service attacks), but for invalid
816 # logins the delay increases with each failed
819 # login OK.. no delay
820 print $outfd "0 0\n";
821 $wasblocked = $hostfail{$2} ||
826 &write_blocked_file();
835 # add the host to the block list,
837 if ($config{'blockhost_failures'} &&
839 $config{'blockhost_failures'}) {
841 $blockhosttime{$2} = $time_now;
844 local $logtext = "Security alert: Host $2 blocked after $config{'blockhost_failures'} failed logins for user $1";
850 # add the user to the user block list,
852 if ($config{'blockuser_failures'} &&
854 $config{'blockuser_failures'}) {
855 push(@denyusers, $1);
856 $blockusertime{$1} = $time_now;
859 local $logtext = "Security alert: User $1 blocked after $config{'blockuser_failures'} failed logins";
865 # Lock out the user's password, if enabled
866 if ($config{'blocklock'} &&
868 $config{'blockuser_failures'}) {
869 my $lk = &lock_user_password($1);
872 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";
879 $dl = $userdlay{$1} -
880 int(($time_now - $userlast{$1})/50);
881 $dl = $dl < 0 ? 0 : $dl+1;
882 print $outfd "$dl $blocked\n";
885 # Write out blocked status file
887 &write_blocked_file();
890 $userlast{$1} = $time_now;
892 elsif ($inline =~ /^verify\s+(\S+)\s+(\S+)/) {
893 # Verifying a session ID
894 local $session_id = $1;
895 local $notimeout = $2;
896 local $skey = $sessiondb{$session_id} ?
898 &hash_session_id($session_id);
899 if (!defined($sessiondb{$skey})) {
900 # Session doesn't exist
901 print $outfd "0 0\n";
904 local ($user, $ltime) =
905 split(/\s+/, $sessiondb{$skey});
906 local $lot = &get_logout_time($user, $session_id);
908 $time_now - $ltime > $lot*60 &&
910 # Session has timed out
911 print $outfd "1 ",$time_now - $ltime,"\n";
912 #delete($sessiondb{$skey});
916 print $outfd "2 $user\n";
920 $sessiondb{$skey} = "$user $time_now";
925 elsif ($inline =~ /^new\s+(\S+)\s+(\S+)\s+(\S+)/) {
926 # Creating a new session
927 local $session_id = $1;
930 $sessiondb{&hash_session_id($session_id)} =
931 "$user $time_now $ip";
933 elsif ($inline =~ /^delete\s+(\S+)/) {
934 # Logging out a session
935 local $session_id = $1;
936 local $skey = $sessiondb{$session_id} ?
938 &hash_session_id($session_id);
939 local @sdb = split(/\s+/, $sessiondb{$skey});
940 print $outfd $sdb[0],"\n";
941 delete($sessiondb{$skey});
943 elsif ($inline =~ /^pamstart\s+(\S+)\s+(\S+)\s+(.*)/) {
944 # Starting a new PAM conversation
945 local ($cid, $host, $user) = ($1, $2, $3);
947 # Does this user even need PAM?
948 local ($realuser, $canlogin) =
949 &can_user_login($user, undef, $host);
951 if ($canlogin == 0) {
953 print $outfd "0 Invalid username\n";
955 elsif ($canlogin != 2) {
956 # Not using PAM .. so just ask for
958 $conv = { 'user' => $realuser,
963 print $outfd "3 Password\n";
966 # Start the PAM conversation
967 # sub-process, and get a question
968 $conv = { 'user' => $realuser,
972 local ($PAMINr, $PAMINw, $PAMOUTr,
973 $PAMOUTw) = &allocate_pipes();
974 local $pampid = fork();
976 close($PAMOUTr); close($PAMINw);
977 &pam_conversation_process(
981 close($PAMOUTw); close($PAMINr);
982 $conv->{'pid'} = $pampid;
983 $conv->{'PAMOUTr'} = $PAMOUTr;
984 $conv->{'PAMINw'} = $PAMINw;
985 push(@childpids, $pampid);
987 # Get the first PAM question
988 local $pok = &recv_pam_question(
991 &end_pam_conversation($conv);
995 $conversations{$cid} = $conv if ($conv);
997 elsif ($inline =~ /^pamanswer\s+(\S+)\s+(.*)/) {
998 # A response to a PAM question
999 local ($cid, $answer) = ($1, $2);
1000 local $conv = $conversations{$cid};
1002 # No such conversation?
1003 print $outfd "0 Bad login session\n";
1005 elsif ($conv->{'pid'}) {
1006 # Send the PAM response and get
1008 &send_pam_answer($conv, $answer);
1009 local $pok = &recv_pam_question($conv, $outfd);
1011 &end_pam_conversation($conv);
1015 # This must be the password .. try it
1016 # and send back the results
1017 local ($vu, $expired, $nonexist) =
1018 &validate_user($conv->{'user'},
1021 local $ok = $vu ? 1 : 0;
1022 print $outfd "2 $conv->{'user'} $ok $expired $notexist\n";
1023 &end_pam_conversation($conv);
1026 elsif ($inline =~ /^writesudo\s+(\S+)\s+(\d+)/) {
1027 # Store the fact that some user can sudo to root
1028 local ($user, $ok) = ($1, $2);
1029 $sudocache{$user} = $ok." ".time();
1031 elsif ($inline =~ /^readsudo\s+(\S+)/) {
1032 # Query the user sudo cache (valid for 1 minute)
1034 local ($ok, $last) =
1035 split(/\s+/, $sudocache{$user});
1036 if ($last < time()-60) {
1041 # Tell client OK or not
1042 print $outfd "$ok\n";
1045 elsif ($inline =~ /\S/) {
1046 # Unknown line from pipe?
1047 print DEBUG "main: Unknown line from pipe $inline\n";
1048 print STDERR "Unknown line from pipe $inline\n";
1052 close($infd); close($outfd);
1053 $passin[$i] = $passout[$i] = undef;
1057 @passin = grep { defined($_) } @passin;
1058 @passout = grep { defined($_) } @passout;
1061 # handle_request(remoteaddress, localaddress)
1062 # Where the real work is done
1065 $acptip = inet_ntoa((unpack_sockaddr_in($_[0]))[1]);
1066 $localip = $_[1] ? inet_ntoa((unpack_sockaddr_in($_[1]))[1]) : undef;
1067 print DEBUG "handle_request: from $acptip to $localip\n";
1068 if ($config{'loghost'}) {
1069 $acpthost = gethostbyaddr(inet_aton($acptip), AF_INET);
1070 $acpthost = $acptip if (!$acpthost);
1073 $acpthost = $acptip;
1075 $datestr = &http_date(time());
1077 $ok_message = "Document follows";
1078 $logged_code = undef;
1079 $reqline = $request_uri = $page = undef;
1083 # check address against access list
1084 if (@deny && &ip_match($acptip, $localip, @deny) ||
1085 @allow && !&ip_match($acptip, $localip, @allow)) {
1086 &http_error(403, "Access denied for $acptip");
1091 # Check address with TCP-wrappers
1092 if (!hosts_ctl($config{'pam'}, STRING_UNKNOWN,
1093 $acptip, STRING_UNKNOWN)) {
1094 &http_error(403, "Access denied for $acptip by TCP wrappers");
1098 print DEBUG "handle_request: passed IP checks\n";
1100 # Compute a timeout for the start of headers, based on the number of
1101 # child processes. As this increases, we use a shorter timeout to avoid
1102 # an attacker overloading the system.
1103 local $header_timeout = 60 + ($config{'maxconns'} - @childpids) * 10;
1105 # Wait at most 60 secs for start of headers for initial requests, or
1106 # 10 minutes for kept-alive connections
1108 vec($rmask, fileno(SOCK), 1) = 1;
1109 local $to = $checked_timeout ? 10*60 : $header_timeout;
1110 local $sel = select($rmask, undef, undef, $to);
1112 if ($checked_timeout) {
1113 print DEBUG "handle_request: exiting due to timeout of $to\n";
1117 &http_error(400, "Timeout",
1118 "Waited for that $to seconds for start of headers");
1122 print DEBUG "handle_request: passed timeout check\n";
1124 # Read the HTTP request and headers
1125 local $origreqline = &read_line();
1126 ($reqline = $origreqline) =~ s/\r|\n//g;
1127 $method = $page = $request_uri = undef;
1128 print DEBUG "handle_request reqline=$reqline\n";
1129 if (!$reqline && (!$use_ssl || $checked_timeout > 1)) {
1130 # An empty request .. just close the connection
1131 print DEBUG "handle_request: rejecting empty request\n";
1134 elsif ($reqline !~ /^(\S+)\s+(.*)\s+HTTP\/1\..$/) {
1135 print DEBUG "handle_request: invalid reqline=$reqline\n";
1137 # This could be an http request when it should be https
1139 local $url = $config{'musthost'} ?
1140 "https://$config{'musthost'}:$port/" :
1141 "https://$host:$port/";
1142 if ($config{'ssl_redirect'}) {
1143 # Just re-direct to the correct URL
1144 sleep(1); # Give browser a change to finish
1145 # sending its request
1146 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1147 &write_data("Date: $datestr\r\n");
1148 &write_data("Server: $config{'server'}\r\n");
1149 &write_data("Location: $url\r\n");
1150 &write_keep_alive(0);
1151 &write_data("\r\n");
1155 # Tell user the correct URL
1156 &http_error(200, "Bad Request", "This web server is running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1159 elsif (ord(substr($reqline, 0, 1)) == 128 && !$use_ssl) {
1160 # This could be an https request when it should be http ..
1161 # need to fake a HTTP response
1164 eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
1165 eval "Net::SSLeay::load_error_strings()";
1166 $ssl_ctx = Net::SSLeay::CTX_new();
1167 Net::SSLeay::CTX_use_RSAPrivateKey_file(
1168 $ssl_ctx, $config{'keyfile'},
1169 &Net::SSLeay::FILETYPE_PEM);
1170 Net::SSLeay::CTX_use_certificate_file(
1172 $config{'certfile'} || $config{'keyfile'},
1173 &Net::SSLeay::FILETYPE_PEM);
1174 $ssl_con = Net::SSLeay::new($ssl_ctx);
1178 select(SSLw); $| = 1; select(STDOUT);
1179 print SSLw $origreqline;
1181 while(sysread(SOCK, $buf, 1) > 0) {
1188 Net::SSLeay::set_wfd($ssl_con, fileno(SOCK));
1189 Net::SSLeay::set_rfd($ssl_con, fileno(SSLr));
1190 Net::SSLeay::accept($ssl_con) || die "accept() failed";
1192 local $url = $config{'musthost'} ?
1193 "https://$config{'musthost'}:$port/" :
1194 "https://$host:$port/";
1195 if ($config{'ssl_redirect'}) {
1196 # Just re-direct to the correct URL
1197 sleep(1); # Give browser a change to
1198 # finish sending its request
1199 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1200 &write_data("Date: $datestr\r\n");
1201 &write_data("Server: $config{'server'}\r\n");
1202 &write_data("Location: $url\r\n");
1203 &write_keep_alive(0);
1204 &write_data("\r\n");
1208 # Tell user the correct URL
1209 &http_error(200, "Bad Request", "This web server is not running in SSL mode. Try the URL <a href='$url'>$url</a> instead.<br>");
1213 &http_error(400, "Bad Request");
1217 &http_error(400, "Bad Request");
1221 $request_uri = $page = $2;
1225 ($headline = &read_line()) =~ s/\r|\n//g;
1226 last if ($headline eq "");
1227 print DEBUG "handle_request: got headline $headline\n";
1228 if ($headline =~ /^(\S+):\s*(.*)$/) {
1229 $header{$lastheader = lc($1)} = $2;
1231 elsif ($headline =~ /^\s+(.*)$/) {
1232 $header{$lastheader} .= $headline;
1235 &http_error(400, "Bad Header $headline");
1238 if (defined($header{'host'})) {
1239 if ($header{'host'} =~ /^([^:]+):([0-9]+)$/) {
1240 ($host, $port) = ($1, $2);
1243 $host = $header{'host'};
1245 if ($config{'musthost'} && $host ne $config{'musthost'}) {
1246 # Disallowed hostname used
1247 &http_error(400, "Invalid HTTP hostname");
1251 if ($page =~ /^([^\?]+)\?(.*)$/) {
1252 # There is some query string information
1255 print DEBUG "handle_request: querystring=$querystring\n";
1256 if ($querystring !~ /=/) {
1257 $queryargs = $querystring;
1258 $queryargs =~ s/\+/ /g;
1259 $queryargs =~ s/%(..)/pack("c",hex($1))/ge;
1263 # Parse query-string parameters
1264 local @in = split(/\&/, $querystring);
1266 local ($k, $v) = split(/=/, $i, 2);
1267 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1268 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1273 $posted_data = undef;
1274 if ($method eq 'POST' &&
1275 $header{'content-type'} eq 'application/x-www-form-urlencoded') {
1276 # Read in posted query string information, up the configured maximum
1277 # post request length
1278 $clen = $header{"content-length"};
1279 $clen_read = $clen > $config{'max_post'} ? $config{'max_post'} : $clen;
1280 while(length($posted_data) < $clen_read) {
1281 $buf = &read_data($clen_read - length($posted_data));
1282 if (!length($buf)) {
1283 &http_error(500, "Failed to read POST request");
1285 chomp($posted_data);
1286 $posted_data =~ s/\015$//mg;
1287 $posted_data .= $buf;
1289 print DEBUG "clen_read=$clen_read clen=$clen posted_data=",length($posted_data),"\n";
1290 if ($clen_read != $clen && length($posted_data) > $clen) {
1291 # If the client sent more data than we asked for, chop the
1293 $posted_data = substr($posted_data, 0, $clen);
1295 if (length($posted_data) > $clen) {
1296 # When the client sent too much, delay so that it gets headers
1299 if ($header{'user-agent'} =~ /MSIE/ &&
1300 $header{'user-agent'} !~ /Opera/i) {
1301 # MSIE includes an extra newline in the data
1302 $posted_data =~ s/\r|\n//g;
1304 local @in = split(/\&/, $posted_data);
1306 local ($k, $v) = split(/=/, $i, 2);
1308 $k =~ s/\+/ /g; $k =~ s/%(..)/pack("c",hex($1))/ge;
1309 $v =~ s/\+/ /g; $v =~ s/%(..)/pack("c",hex($1))/ge;
1312 print DEBUG "handle_request: posted_data=$posted_data\n";
1315 # replace %XX sequences in page
1316 $page =~ s/%(..)/pack("c",hex($1))/ge;
1318 # Check if the browser's user agent indicates a mobile device
1319 $mobile_device = &is_mobile_useragent($header{'user-agent'});
1321 # Check if Host: header is for a mobile URL
1322 foreach my $m (@mobile_prefixes) {
1323 if ($header{'host'} =~ /^\Q$m\E/i) {
1328 # check for the logout flag file, and if existant deny authentication
1329 if ($config{'logout'} && -r $config{'logout'}.$in{'miniserv_logout_id'}) {
1330 print DEBUG "handle_request: logout flag set\n";
1331 $deny_authentication++;
1332 open(LOGOUT, $config{'logout'}.$in{'miniserv_logout_id'});
1333 chop($count = <LOGOUT>);
1337 open(LOGOUT, ">$config{'logout'}$in{'miniserv_logout_id'}");
1338 print LOGOUT "$count\n";
1342 unlink($config{'logout'}.$in{'miniserv_logout_id'});
1346 # check for any redirect for the requested URL
1347 foreach my $pfx (@strip_prefix) {
1348 my $l = length($pfx);
1349 if(length($page) >= $l &&
1350 substr($page,0,$l) eq $pfx) {
1351 $page=substr($page,$l);
1355 $simple = &simplify_path($page, $bogus);
1357 $rpath .= "&".$querystring if (defined($querystring));
1358 $redir = $redirect{$rpath};
1359 if (defined($redir)) {
1360 print DEBUG "handle_request: redir=$redir\n";
1361 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1362 &write_data("Date: $datestr\r\n");
1363 &write_data("Server: $config{'server'}\r\n");
1364 local $ssl = $use_ssl || $config{'inetd_ssl'};
1365 $portstr = $port == 80 && !$ssl ? "" :
1366 $port == 443 && $ssl ? "" : ":$port";
1367 $prot = $ssl ? "https" : "http";
1368 &write_data("Location: $prot://$host$portstr$redir\r\n");
1369 &write_keep_alive(0);
1370 &write_data("\r\n");
1374 # Check for a DAV request
1376 foreach my $d (@davpaths) {
1377 if ($simple eq $d || $simple =~ /^\Q$d\E\//) {
1382 if (!$davpath && ($method eq "SEARCH" || $method eq "PUT")) {
1383 &http_error(400, "Bad Request method $method");
1386 # Check for password if needed
1388 print DEBUG "handle_request: Need authentication\n";
1392 # Session authentication is never used for connections by
1393 # another webmin server, or for specified pages, or for DAV, or XMLRPC,
1394 # or mobile browsers if requested.
1395 if ($header{'user-agent'} =~ /webmin/i ||
1396 $header{'user-agent'} =~ /$config{'agents_nosession'}/i ||
1397 $sessiononly{$simple} || $davpath ||
1398 $simple eq "/xmlrpc.cgi" ||
1399 $acptip eq $config{'host_nosession'} ||
1400 $mobile_device && $config{'mobile_nosession'}) {
1401 print DEBUG "handle_request: Forcing HTTP authentication\n";
1402 $config{'session'} = 0;
1405 # check for SSL authentication
1406 if ($use_ssl && $verified_client) {
1407 $peername = Net::SSLeay::X509_NAME_oneline(
1408 Net::SSLeay::X509_get_subject_name(
1409 Net::SSLeay::get_peer_certificate(
1411 local $peername2 = $peername;
1412 $peername2 =~ s/Email=/emailAddress=/ ||
1413 $peername2 =~ s/emailAddress=/Email=/;
1414 foreach $u (keys %certs) {
1415 if ($certs{$u} eq $peername ||
1416 $certs{$u} eq $peername2) {
1419 #syslog("info", "%s", "SSL login as $authuser from $acpthost") if ($use_syslog);
1423 if ($use_syslog && !$validated) {
1424 syslog("crit", "%s",
1425 "Unknown SSL certificate $peername");
1429 if (!$validated && !$deny_authentication) {
1430 # check for IP-based authentication
1432 foreach $a (keys %ipaccess) {
1433 if ($acptip eq $a) {
1434 # It does! Auth as the user
1436 $baseauthuser = $authuser =
1442 # Check for normal HTTP authentication
1443 if (!$validated && !$deny_authentication && !$config{'session'} &&
1444 $header{authorization} =~ /^basic\s+(\S+)$/i) {
1445 # authorization given..
1446 ($authuser, $authpass) = split(/:/, &b64decode($1), 2);
1447 print DEBUG "handle_request: doing basic auth check authuser=$authuser authpass=$authpass\n";
1448 local ($vu, $expired, $nonexist) =
1449 &validate_user($authuser, $authpass, $host);
1450 print DEBUG "handle_request: vu=$vu expired=$expired nonexist=$nonexist\n";
1451 if ($vu && (!$expired || $config{'passwd_mode'} == 1)) {
1458 if ($use_syslog && !$validated) {
1459 syslog("crit", "%s",
1460 ($nonexist ? "Non-existent" :
1461 $expired ? "Expired" : "Invalid").
1462 " login as $authuser from $acpthost");
1464 if ($authuser =~ /\r|\n|\s/) {
1465 &http_error(500, "Invalid username",
1466 "Username contains invalid characters");
1468 if ($authpass =~ /\r|\n/) {
1469 &http_error(500, "Invalid password",
1470 "Password contains invalid characters");
1473 if ($config{'passdelay'} && !$config{'inetd'}) {
1474 # check with main process for delay
1475 print DEBUG "handle_request: about to ask for password delay\n";
1476 print $PASSINw "delay $authuser $acptip $validated\n";
1477 <$PASSOUTr> =~ /(\d+) (\d+)/;
1479 print DEBUG "handle_request: password delay $1 $2\n";
1484 # Check for a visit to the special session login page
1485 if ($config{'session'} && !$deny_authentication &&
1486 $page eq $config{'session_login'}) {
1487 if ($in{'logout'} && $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1488 # Logout clicked .. remove the session
1490 print $PASSINw "delete $sid\n";
1491 local $louser = <$PASSOUTr>;
1494 $already_session_id = undef;
1495 $authuser = $baseauthuser = undef;
1498 syslog("info", "%s", "Logout by $louser from $acpthost");
1500 &run_logout_script($louser, $sid,
1502 &write_logout_utmp($louser, $actphost);
1507 if ($in{'user'} =~ /\r|\n|\s/) {
1508 &http_error(500, "Invalid username",
1509 "Username contains invalid characters");
1511 if ($in{'pass'} =~ /\r|\n/) {
1512 &http_error(500, "Invalid password",
1513 "Password contains invalid characters");
1516 local ($vu, $expired, $nonexist) =
1517 &validate_user($in{'user'}, $in{'pass'}, $host);
1518 local $hrv = &handle_login(
1519 $vu || $in{'user'}, $vu ? 1 : 0,
1520 $expired, $nonexist, $in{'pass'},
1521 $in{'notestingcookie'});
1522 return $hrv if (defined($hrv));
1526 # Check for a visit to the special PAM login page
1527 if ($config{'session'} && !$deny_authentication &&
1528 $use_pam && $config{'pam_conv'} && $page eq $config{'pam_login'} &&
1530 # A question has been entered .. submit it to the main process
1531 print DEBUG "handle_request: Got call to $page ($in{'cid'})\n";
1532 print DEBUG "handle_request: For PAM, authuser=$authuser\n";
1533 if ($in{'answer'} =~ /\r|\n/ || $in{'cid'} =~ /\r|\n|\s/) {
1534 &http_error(500, "Invalid response",
1535 "Response contains invalid characters");
1539 # Start of a new conversation - answer must be username
1540 $cid = &generate_random_id($in{'answer'});
1541 print $PASSINw "pamstart $cid $host $in{'answer'}\n";
1544 # A response to a previous question
1546 print $PASSINw "pamanswer $cid $in{'answer'}\n";
1549 # Read back the response, and the next question (if any)
1550 local $line = <$PASSOUTr>;
1551 $line =~ s/\r|\n//g;
1552 local ($rv, $question) = split(/\s+/, $line, 2);
1555 local $hrv = &handle_login(
1556 !$in{'cid'} && $in{'answer'} ? $in{'answer'}
1559 return $hrv if (defined($hrv));
1561 elsif ($rv == 1 || $rv == 3) {
1562 # Another question .. force use of PAM CGI
1565 $querystring .= "&cid=$cid&question=".
1567 $querystring .= "&password=1" if ($rv == 3);
1569 $page = $config{'pam_login'};
1570 $miniserv_internal = 1;
1574 # Got back a final ok or failure
1575 local ($user, $ok, $expired, $nonexist) =
1576 split(/\s+/, $question);
1577 local $hrv = &handle_login(
1578 $user, $ok, $expired, $nonexist, undef,
1579 $in{'notestingcookie'});
1580 return $hrv if (defined($hrv));
1583 # A message from PAM .. tell the user
1586 $querystring .= "&cid=$cid&message=".
1589 $page = $config{'pam_login'};
1590 $miniserv_internal = 1;
1595 # Check for a visit to the special password change page
1596 if ($config{'session'} && !$deny_authentication &&
1597 $page eq $config{'password_change'} && !$validated) {
1598 # Just let this slide ..
1600 $miniserv_internal = 3;
1603 # Check for an existing session
1604 if ($config{'session'} && !$validated) {
1605 if ($already_session_id) {
1606 $session_id = $already_session_id;
1607 $authuser = $already_authuser;
1610 elsif (!$deny_authentication &&
1611 $header{'cookie'} =~ /(^|\s)$sidname=([a-f0-9]+)/) {
1613 local $notimeout = $in{'webmin_notimeout'} ? 1 : 0;
1614 print $PASSINw "verify $session_id $notimeout\n";
1615 <$PASSOUTr> =~ /(\d+)\s+(\S+)/;
1617 # Valid session continuation
1620 #$already_session_id = $session_id;
1621 $already_authuser = $authuser;
1628 # Invalid session ID .. don't set verified
1633 # Check for local authentication
1634 if ($localauth_user && !$header{'x-forwarded-for'} && !$header{'via'}) {
1635 if (defined($users{$localauth_user})) {
1636 # Local user exists in webmin users file
1638 $authuser = $localauth_user;
1641 # Check if local user is allowed by unixauth
1642 local @can = &can_user_login($localauth_user,
1646 $authuser = $localauth_user;
1649 $localauth_user = undef;
1655 # Check if this path allows anonymous access
1657 foreach $a (keys %anonymous) {
1658 if (substr($simple, 0, length($a)) eq $a) {
1659 # It does! Auth as the user, if IP access
1660 # control allows him.
1661 if (&check_user_ip($anonymous{$a}) &&
1662 &check_user_time($anonymous{$a})) {
1664 $baseauthuser = $authuser =
1672 # Check if this path allows unauthenticated access
1673 local ($u, $unauth);
1674 foreach $u (@unauth) {
1675 $unauth++ if ($simple =~ /$u/);
1677 if (!$bogus && $unauth) {
1678 # Unauthenticated directory or file request - approve it
1680 $baseauthuser = $authuser = undef;
1685 if ($blocked == 0) {
1686 # No password given.. ask
1687 if ($config{'pam_conv'} && $use_pam) {
1688 # Force CGI for PAM question, starting with
1689 # the username which is always needed
1692 $querystring .= "&initial=1&question=".
1693 &urlize("Username");
1694 $querystring .= "&failed=$failed_user" if ($failed_user);
1695 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1697 $page = $config{'pam_login'};
1698 $miniserv_internal = 1;
1701 elsif ($config{'session'}) {
1702 # Force CGI for session login
1705 $querystring .= "&logout=1&page=/";
1708 # Re-direct to current module only
1709 local $rpage = $request_uri;
1710 if (!$config{'loginkeeppage'}) {
1711 $rpage =~ s/\?.*$//;
1712 $rpage =~ s/[^\/]+$//
1714 $querystring = "page=".&urlize($rpage);
1717 $querystring .= "&failed=$failed_user" if ($failed_user);
1718 $querystring .= "&timed_out=$timed_out" if ($timed_out);
1720 $page = $config{'session_login'};
1721 $miniserv_internal = 1;
1725 # Ask for login with HTTP authentication
1726 &write_data("HTTP/1.0 401 Unauthorized\r\n");
1727 &write_data("Date: $datestr\r\n");
1728 &write_data("Server: $config{'server'}\r\n");
1729 &write_data("WWW-authenticate: Basic ".
1730 "realm=\"$config{'realm'}\"\r\n");
1731 &write_keep_alive(0);
1732 &write_data("Content-type: text/html\r\n");
1733 &write_data("\r\n");
1734 &reset_byte_count();
1735 &write_data("<html>\n");
1736 &write_data("<head><title>Unauthorized</title></head>\n");
1737 &write_data("<body><h1>Unauthorized</h1>\n");
1738 &write_data("A password is required to access this\n");
1739 &write_data("web server. Please try again. <p>\n");
1740 &write_data("</body></html>\n");
1741 &log_request($acpthost, undef, $reqline, 401, &byte_count());
1745 elsif ($blocked == 1) {
1746 # when the host has been blocked, give it an error
1747 &http_error(403, "Access denied for $acptip. The host ".
1748 "has been blocked because of too ".
1749 "many authentication failures.");
1751 elsif ($blocked == 2) {
1752 # when the user has been blocked, give it an error
1753 &http_error(403, "Access denied. The user ".
1754 "has been blocked because of too ".
1755 "many authentication failures.");
1759 # Get the real Webmin username
1760 local @can = &can_user_login($authuser, undef, $host);
1761 $baseauthuser = $can[3] || $authuser;
1763 if ($config{'remoteuser'} && !$< && $validated) {
1764 # Switch to the UID of the remote user (if he exists)
1765 local @u = getpwnam($authuser);
1766 if (@u && $< != $u[2]) {
1767 $( = $u[3]; $) = "$u[3] $u[3]";
1768 ($>, $<) = ($u[2], $u[2]);
1771 &http_error(500, "Unix user $authuser does not exist");
1777 # Check per-user IP access control
1778 if (!&check_user_ip($baseauthuser)) {
1779 &http_error(403, "Access denied for $acptip for $baseauthuser");
1783 # Check per-user allowed times
1784 if (!&check_user_time($baseauthuser)) {
1785 &http_error(403, "Access denied at the current time");
1790 # Validate the path, and convert to canonical form
1792 $simple = &simplify_path($page, $bogus);
1793 print DEBUG "handle_request: page=$page simple=$simple\n";
1795 &http_error(400, "Invalid path");
1798 # Check for a DAV request
1800 return &handle_dav_request($davpath);
1803 # Work out the active theme(s)
1804 local $preroots = $mobile_device && defined($config{'mobile_preroot'}) ?
1805 $config{'mobile_preroot'} :
1806 $authuser && defined($config{'preroot_'.$authuser}) ?
1807 $config{'preroot_'.$authuser} :
1808 $authuser && $baseauthuser &&
1809 defined($config{'preroot_'.$baseauthuser}) ?
1810 $config{'preroot_'.$baseauthuser} :
1812 local @preroots = reverse(split(/\s+/, $preroots));
1814 # Canonicalize the directories
1815 foreach my $preroot (@preroots) {
1816 # Always under the current webmin root
1817 $preroot =~ s/^.*\///g;
1818 $preroot = $roots[0].'/'.$preroot;
1821 # Look in the theme root directories first
1822 local ($full, @stfull);
1824 foreach my $preroot (@preroots) {
1827 $full = $preroot.$sofar;
1828 $scriptname = $simple;
1829 foreach $b (split(/\//, $simple)) {
1830 if ($b ne "") { $sofar .= "/$b"; }
1831 $full = $preroot.$sofar;
1832 @stfull = stat($full);
1833 if (!@stfull) { undef($full); last; }
1835 # Check if this is a directory
1837 # It is.. go on parsing
1845 # Check if this is a CGI program
1846 if (&get_type($full) eq "internal/cgi") {
1847 $pathinfo = substr($simple, length($sofar));
1848 $pathinfo .= "/" if ($page =~ /\/$/);
1849 $scriptname = $sofar;
1854 # Don't stop at a directory unless this is the last theme, which
1855 # is the 'real' one that provides the .cgi scripts
1856 if ($is_directory && $preroot ne $preroots[$#preroots]) {
1863 $cgi_pwd = $roots[0];
1865 elsif ($is_directory) {
1866 $cgi_pwd = "$roots[0]$sofar";
1869 "$roots[0]$sofar" =~ /^(.*\/)[^\/]+$/;
1872 $foundroot = $preroot;
1873 if ($is_directory) {
1874 # Check for index files in the directory
1876 foreach $idx (split(/\s+/, $config{"index_docs"})) {
1877 $idxfull = "$full/$idx";
1878 local @stidxfull = stat($idxfull);
1879 if (-r _ && !-d _) {
1881 @stfull = @stidxfull;
1884 if ($scriptname ne "/");
1889 @stfull = stat($full) if (!$foundidx);
1892 last if ($foundroot);
1894 print DEBUG "handle_request: initial full=$full\n";
1896 # Look in the real root directories, stopping when we find a file or directory
1897 if (!$full || $is_directory) {
1898 ROOT: foreach $root (@roots) {
1900 $full = $root.$sofar;
1901 $scriptname = $simple;
1902 foreach $b ($simple eq "/" ? ( "" ) : split(/\//, $simple)) {
1903 if ($b ne "") { $sofar .= "/$b"; }
1904 $full = $root.$sofar;
1905 @stfull = stat($full);
1910 # Check if this is a directory
1912 # It is.. go on parsing
1916 # Check if this is a CGI program
1917 if (&get_type($full) eq "internal/cgi") {
1918 $pathinfo = substr($simple, length($sofar));
1919 $pathinfo .= "/" if ($page =~ /\/$/);
1920 $scriptname = $sofar;
1925 # Run CGI in the same directory as whatever file
1927 $full =~ /^(.*\/)[^\/]+$/; $cgi_pwd = $1;
1936 if (!@stfull) { &http_error(404, "File not found"); }
1938 print DEBUG "handle_request: full=$full\n";
1939 @stfull = stat($full) if (!@stfull);
1941 # check filename against denyfile regexp
1942 local $denyfile = $config{'denyfile'};
1943 if ($denyfile && $full =~ /$denyfile/) {
1944 &http_error(403, "Access denied to $page");
1948 # Reached the end of the path OK.. see what we've got
1950 # See if the URL ends with a / as it should
1951 print DEBUG "handle_request: found a directory\n";
1952 if ($page !~ /\/$/) {
1953 # It doesn't.. redirect
1954 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
1955 $ssl = $use_ssl || $config{'inetd_ssl'};
1956 $portstr = $port == 80 && !$ssl ? "" :
1957 $port == 443 && $ssl ? "" : ":$port";
1958 &write_data("Date: $datestr\r\n");
1959 &write_data("Server: $config{server}\r\n");
1960 $prot = $ssl ? "https" : "http";
1961 &write_data("Location: $prot://$host$portstr$page/\r\n");
1962 &write_keep_alive(0);
1963 &write_data("\r\n");
1964 &log_request($acpthost, $authuser, $reqline, 302, 0);
1967 # A directory.. check for index files
1969 foreach $idx (split(/\s+/, $config{"index_docs"})) {
1970 $idxfull = "$full/$idx";
1971 @stidxfull = stat($idxfull);
1972 if (-r _ && !-d _) {
1975 @stfull = @stidxfull;
1976 $scriptname .= "/" if ($scriptname ne "/");
1981 @stfull = stat($full) if (!$foundidx);
1984 # This is definately a directory.. list it
1985 print DEBUG "handle_request: listing directory\n";
1986 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
1987 "Date: $datestr\r\n".
1988 "Server: $config{server}\r\n".
1989 "Content-type: text/html\r\n";
1991 &write_keep_alive(0);
1992 &write_data("\r\n");
1993 &reset_byte_count();
1994 &write_data("<h1>Index of $simple</h1>\n");
1995 &write_data("<pre>\n");
1996 &write_data(sprintf "%-35.35s %-20.20s %-10.10s\n",
1997 "Name", "Last Modified", "Size");
1998 &write_data("<hr>\n");
1999 opendir(DIR, $full);
2000 while($df = readdir(DIR)) {
2001 if ($df =~ /^\./) { next; }
2002 $fulldf = $full eq "/" ? $full.$df : $full."/".$df;
2003 (@stbuf = stat($fulldf)) || next;
2004 if (-d _) { $df .= "/"; }
2005 @tm = localtime($stbuf[9]);
2006 $fdate = sprintf "%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d",
2007 $tm[3],$tm[4]+1,$tm[5]+1900,
2008 $tm[0],$tm[1],$tm[2];
2009 $len = length($df); $rest = " "x(35-$len);
2011 "<a href=\"%s\">%-${len}.${len}s</a>$rest %-20.20s %-10.10s\n",
2012 $df, $df, $fdate, $stbuf[7]);
2015 &log_request($acpthost, $authuser, $reqline, $ok_code, &byte_count());
2019 # CGI or normal file
2021 if (&get_type($full) eq "internal/cgi" && $validated != 4) {
2022 # A CGI program to execute
2023 print DEBUG "handle_request: executing CGI\n";
2024 $envtz = $ENV{"TZ"};
2025 $envuser = $ENV{"USER"};
2026 $envpath = $ENV{"PATH"};
2027 $envlang = $ENV{"LANG"};
2028 $envroot = $ENV{"SystemRoot"};
2029 $envperllib = $ENV{'PERLLIB'};
2030 foreach my $k (keys %ENV) {
2033 $ENV{"PATH"} = $envpath if ($envpath);
2034 $ENV{"TZ"} = $envtz if ($envtz);
2035 $ENV{"USER"} = $envuser if ($envuser);
2036 $ENV{"OLD_LANG"} = $envlang if ($envlang);
2037 $ENV{"SystemRoot"} = $envroot if ($envroot);
2038 $ENV{'PERLLIB'} = $envperllib if ($envperllib);
2039 $ENV{"HOME"} = $user_homedir;
2040 $ENV{"SERVER_SOFTWARE"} = $config{"server"};
2041 $ENV{"SERVER_NAME"} = $host;
2042 $ENV{"SERVER_ADMIN"} = $config{"email"};
2043 $ENV{"SERVER_ROOT"} = $roots[0];
2044 $ENV{"SERVER_REALROOT"} = $realroot;
2045 $ENV{"SERVER_PORT"} = $port;
2046 $ENV{"REMOTE_HOST"} = $acpthost;
2047 $ENV{"REMOTE_ADDR"} = $acptip;
2048 $ENV{"REMOTE_USER"} = $authuser;
2049 $ENV{"BASE_REMOTE_USER"} = $authuser ne $baseauthuser ?
2050 $baseauthuser : undef;
2051 $ENV{"REMOTE_PASS"} = $authpass if (defined($authpass) &&
2052 $config{'pass_password'});
2053 print DEBUG "REMOTE_USER = ",$ENV{"REMOTE_USER"},"\n";
2054 print DEBUG "BASE_REMOTE_USER = ",$ENV{"BASE_REMOTE_USER"},"\n";
2055 $ENV{"SSL_USER"} = $peername if ($validated == 2);
2056 $ENV{"ANONYMOUS_USER"} = "1" if ($validated == 3 || $validated == 4);
2057 $ENV{"DOCUMENT_ROOT"} = $roots[0];
2058 $ENV{"DOCUMENT_REALROOT"} = $realroot;
2059 $ENV{"GATEWAY_INTERFACE"} = "CGI/1.1";
2060 $ENV{"SERVER_PROTOCOL"} = "HTTP/1.0";
2061 $ENV{"REQUEST_METHOD"} = $method;
2062 $ENV{"SCRIPT_NAME"} = $scriptname;
2063 $ENV{"SCRIPT_FILENAME"} = $full;
2064 $ENV{"REQUEST_URI"} = $request_uri;
2065 $ENV{"PATH_INFO"} = $pathinfo;
2067 $ENV{"PATH_TRANSLATED"} = "$roots[0]$pathinfo";
2068 $ENV{"PATH_REALTRANSLATED"} = "$realroot$pathinfo";
2070 $ENV{"QUERY_STRING"} = $querystring;
2071 $ENV{"MINISERV_CONFIG"} = $config_file;
2072 $ENV{"HTTPS"} = "ON" if ($use_ssl || $config{'inetd_ssl'});
2073 $ENV{"SESSION_ID"} = $session_id if ($session_id);
2074 $ENV{"LOCAL_USER"} = $localauth_user if ($localauth_user);
2075 $ENV{"MINISERV_INTERNAL"} = $miniserv_internal if ($miniserv_internal);
2076 if (defined($header{"content-length"})) {
2077 $ENV{"CONTENT_LENGTH"} = $header{"content-length"};
2079 if (defined($header{"content-type"})) {
2080 $ENV{"CONTENT_TYPE"} = $header{"content-type"};
2082 foreach $h (keys %header) {
2083 ($hname = $h) =~ tr/a-z/A-Z/;
2085 $ENV{"HTTP_$hname"} = $header{$h};
2087 $ENV{"PWD"} = $cgi_pwd;
2088 foreach $k (keys %config) {
2089 if ($k =~ /^env_(\S+)$/) {
2090 $ENV{$1} = $config{$k};
2093 delete($ENV{'HTTP_AUTHORIZATION'});
2094 $ENV{'HTTP_COOKIE'} =~ s/;?\s*$sidname=([a-f0-9]+)//;
2095 $ENV{'MOBILE_DEVICE'} = 1 if ($mobile_device);
2097 # Check if the CGI can be handled internally
2099 local $first = <CGI>;
2101 $first =~ s/[#!\r\n]//g;
2102 $nph_script = ($full =~ /\/nph-([^\/]+)$/);
2104 if (!$config{'forkcgis'} &&
2105 ($first eq $perl_path || $first eq $linked_perl_path) &&
2107 $config{'internalcgis'}) {
2108 # setup environment for eval
2110 @ARGV = split(/\s+/, $queryargs);
2113 # Already read the post input
2114 $postinput = $posted_data;
2116 $clen = $header{"content-length"};
2117 $SIG{'CHLD'} = 'DEFAULT';
2119 # Have SOCK closed if the perl exec's something
2121 fcntl(SOCK, F_SETFD, FD_CLOEXEC);
2125 if ($config{'log'}) {
2126 open(MINISERVLOG, ">>$config{'logfile'}");
2127 if ($config{'logperms'}) {
2128 chmod(oct($config{'logperms'}),
2129 $config{'logfile'});
2132 chmod(0600, $config{'logfile'});
2136 $main_process_id = $$;
2138 if ($full =~ /^\Q$foundroot\E\/([^\/]+)\//) {
2139 # Eval in package from Webmin module name
2141 $pkg =~ s/[^A-Za-z0-9]/_/g;
2146 tie(*STDOUT, 'miniserv');
2147 tie(*STDIN, 'miniserv');
2148 do \$miniserv::full;
2154 &http_error(500, "Perl execution failed",
2155 $config{'noshowstderr'} ? undef : $@);
2157 elsif (!$doneheaders && !$nph_script) {
2158 &http_error(500, "Missing Headers");
2165 # fork the process that actually executes the CGI
2166 pipe(CGIINr, CGIINw);
2167 pipe(CGIOUTr, CGIOUTw);
2168 pipe(CGIERRr, CGIERRw);
2169 if (!($cgipid = fork())) {
2170 @execargs = ( $full, split(/\s+/, $queryargs) );
2173 open(STDIN, "<&CGIINr");
2174 open(STDOUT, ">&CGIOUTw");
2175 open(STDERR, ">&CGIERRw");
2176 close(CGIINw); close(CGIOUTr); close(CGIERRr);
2178 die "Failed to exec $full : $!\n";
2181 close(CGIINr); close(CGIOUTw); close(CGIERRw);
2184 # write CGI input to a temp file
2185 $infile = "$config{'tempbase'}.$$";
2186 open(CGIINw, ">$infile");
2187 # NOT binary mode, as CGIs don't read in it!
2192 # already read the posted data
2193 print CGIINw $posted_data;
2195 $clen = $header{"content-length"};
2196 if ($method eq "POST" && $clen_read < $clen) {
2197 $SIG{'PIPE'} = 'IGNORE';
2199 while($got < $clen) {
2200 $buf = &read_data($clen-$got);
2201 if (!length($buf)) {
2202 kill('TERM', $cgipid);
2203 unlink($infile) if ($infile);
2204 &http_error(500, "Failed to read ".
2207 $got += length($buf);
2208 local ($wrote) = (print CGIINw $buf);
2211 # If the CGI terminated early, we still need to read
2212 # from the browser and throw away
2213 while($got < $clen) {
2214 $buf = &read_data($clen-$got);
2215 if (!length($buf)) {
2216 kill('TERM', $cgipid);
2217 unlink($infile) if ($infile);
2218 &http_error(500, "Failed to read ".
2221 $got += length($buf);
2223 $SIG{'PIPE'} = 'DEFAULT';
2229 # Run the CGI program, and feed it input
2231 local $qqueryargs = join(" ", map { "\"$_\"" }
2232 split(/\s+/, $queryargs));
2233 if ($first =~ /(perl|perl.exe)$/i) {
2234 # On Windows, run with Perl
2235 open(CGIOUTr, "$perl_path \"$full\" $qqueryargs <$infile |");
2238 open(CGIOUTr, "\"$full\" $qqueryargs <$infile |");
2244 # read back cgi headers
2245 select(CGIOUTr); $|=1; select(STDOUT);
2249 $line =~ s/\r|\n//g;
2251 if ($got_blank || %cgiheader) { last; }
2255 if ($line !~ /^(\S+):\s+(.*)$/) {
2256 $errs = &read_errors(CGIERRr);
2257 close(CGIOUTr); close(CGIERRr);
2258 unlink($infile) if ($infile);
2259 &http_error(500, "Bad Header", $errs);
2261 $cgiheader{lc($1)} = $2;
2262 push(@cgiheader, [ $1, $2 ]);
2264 if ($cgiheader{"location"}) {
2265 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
2266 &write_data("Date: $datestr\r\n");
2267 &write_data("Server: $config{'server'}\r\n");
2268 &write_keep_alive(0);
2269 # ignore the rest of the output. This is a hack,
2270 # but is necessary for IE in some cases :(
2271 close(CGIOUTr); close(CGIERRr);
2273 elsif ($cgiheader{"content-type"} eq "") {
2274 close(CGIOUTr); close(CGIERRr);
2275 unlink($infile) if ($infile);
2276 $errs = &read_errors(CGIERRr);
2277 &http_error(500, "Missing Content-Type Header",
2278 $config{'noshowstderr'} ? undef : $errs);
2281 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2282 &write_data("Date: $datestr\r\n");
2283 &write_data("Server: $config{'server'}\r\n");
2284 &write_keep_alive(0);
2286 foreach $h (@cgiheader) {
2287 &write_data("$h->[0]: $h->[1]\r\n");
2289 &write_data("\r\n");
2291 &reset_byte_count();
2292 while($line = <CGIOUTr>) {
2297 unlink($infile) if ($infile);
2303 print DEBUG "handle_request: outputting file\n";
2304 open(FILE, $full) || &http_error(404, "Failed to open file");
2306 local $resp = "HTTP/1.0 $ok_code $ok_message\r\n".
2307 "Date: $datestr\r\n".
2308 "Server: $config{server}\r\n".
2309 "Content-type: ".&get_type($full)."\r\n".
2310 "Content-length: $stfull[7]\r\n".
2311 "Last-Modified: ".&http_date($stfull[9])."\r\n".
2312 "Expires: ".&http_date(time()+$config{'expires'})."\r\n";
2314 $rv = &write_keep_alive();
2315 &write_data("\r\n");
2316 &reset_byte_count();
2317 while(read(FILE, $buf, 1024) > 0) {
2324 &log_request($acpthost, $authuser, $reqline,
2325 $logged_code ? $logged_code :
2326 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2330 # http_error(code, message, body, [dontexit])
2333 local $eh = $error_handler_recurse ? undef :
2334 $config{"error_handler_$_[0]"} ? $config{"error_handler_$_[0]"} :
2335 $config{'error_handler'} ? $config{'error_handler'} : undef;
2336 print DEBUG "http_error code=$_[0] message=$_[1] body=$_[2]\n";
2338 # Call a CGI program for the error
2340 $querystring = "code=$_[0]&message=".&urlize($_[1]).
2341 "&body=".&urlize($_[2]);
2342 $error_handler_recurse++;
2344 $ok_message = $_[1];
2348 # Use the standard error message display
2349 &write_data("HTTP/1.0 $_[0] $_[1]\r\n");
2350 &write_data("Server: $config{server}\r\n");
2351 &write_data("Date: $datestr\r\n");
2352 &write_data("Content-type: text/html\r\n");
2353 &write_keep_alive(0);
2354 &write_data("\r\n");
2355 &reset_byte_count();
2356 &write_data("<h1>Error - $_[1]</h1>\n");
2358 &write_data("<pre>$_[2]</pre>\n");
2361 &log_request($acpthost, $authuser, $reqline, $_[0], &byte_count())
2363 &log_error($_[1], $_[2] ? " : $_[2]" : "");
2370 if ($_[0] =~ /\.([A-z0-9]+)$/) {
2376 return "text/plain";
2379 # simplify_path(path, bogus)
2380 # Given a path, maybe containing stuff like ".." and "." convert it to a
2381 # clean, absolute form.
2384 local($dir, @bits, @fixedbits, $b);
2386 $dir =~ s/\\/\//g; # fix windows \ in path
2389 $dir =~ s/\0//g; # remove null bytes
2390 @bits = split(/\/+/, $dir);
2393 foreach $b (@bits) {
2397 elsif ($b eq ".." || $b eq "...") {
2399 if (scalar(@fixedbits) == 0) {
2407 push(@fixedbits, $b);
2410 return "/" . join('/', @fixedbits);
2414 # Converts a string from base64 format to normal
2417 local($str) = $_[0];
2419 $str =~ tr|A-Za-z0-9+=/||cd;
2421 $str =~ tr|A-Za-z0-9+/| -_|;
2422 while ($str =~ /(.{1,60})/gs) {
2423 my $len = chr(32 + length($1)*3/4);
2424 $res .= unpack("u", $len . $1 );
2429 # ip_match(remoteip, localip, [match]+)
2430 # Checks an IP address against a list of IPs, networks and networks/masks
2433 local(@io, @mo, @ms, $i, $j, $hn, $needhn);
2434 @io = split(/\./, $_[0]);
2435 for($i=2; $i<@_; $i++) {
2436 $needhn++ if ($_[$i] =~ /^\*(\S+)$/);
2438 if ($needhn && !defined($hn = $ip_match_cache{$_[0]})) {
2439 $hn = gethostbyaddr(inet_aton($_[0]), AF_INET);
2440 $hn = "" if (&to_ipaddress($hn) ne $_[0]);
2441 $ip_match_cache{$_[0]} = $hn;
2443 for($i=2; $i<@_; $i++) {
2444 local $mismatch = 0;
2445 if ($_[$i] =~ /^(\S+)\/(\d+)$/) {
2446 # Convert CIDR to netmask format
2447 $_[$i] = $1."/".&prefix_to_mask($2);
2449 if ($_[$i] =~ /^(\S+)\/(\S+)$/) {
2450 # Compare with network/mask
2451 @mo = split(/\./, $1); @ms = split(/\./, $2);
2452 for($j=0; $j<4; $j++) {
2453 if ((int($io[$j]) & int($ms[$j])) != int($mo[$j])) {
2458 elsif ($_[$i] =~ /^\*(\S+)$/) {
2459 # Compare with hostname regexp
2460 $mismatch = 1 if ($hn !~ /$1$/);
2462 elsif ($_[$i] eq 'LOCAL') {
2463 # Compare with local network
2464 local @lo = split(/\./, $_[1]);
2466 $mismatch = 1 if ($lo[0] != $io[0]);
2468 elsif ($lo[0] < 192) {
2469 $mismatch = 1 if ($lo[0] != $io[0] ||
2473 $mismatch = 1 if ($lo[0] != $io[0] ||
2478 elsif ($_[$i] !~ /^[0-9\.]+$/) {
2479 # Compare with hostname
2480 $mismatch = 1 if ($_[0] ne &to_ipaddress($_[$i]));
2483 # Compare with IP or network
2484 @mo = split(/\./, $_[$i]);
2485 while(@mo && !$mo[$#mo]) { pop(@mo); }
2486 for($j=0; $j<@mo; $j++) {
2487 if ($mo[$j] != $io[$j]) {
2492 return 1 if (!$mismatch);
2497 # users_match(&uinfo, user, ...)
2498 # Returns 1 if a user is in a list of users and groups
2501 local $uinfo = shift(@_);
2503 local @ginfo = getgrgid($uinfo->[3]);
2505 if ($u =~ /^\@(\S+)$/) {
2506 return 1 if (&is_group_member($uinfo, $1));
2508 elsif ($u =~ /^(\d*)-(\d*)$/ && ($1 || $2)) {
2509 return (!$1 || $uinfo[2] >= $1) &&
2510 (!$2 || $uinfo[2] <= $2);
2513 return 1 if ($u eq $uinfo->[0]);
2519 # restart_miniserv()
2520 # Called when a SIGHUP is received to restart the web server. This is done
2521 # by exec()ing perl with the same command line as was originally used
2522 sub restart_miniserv
2524 print STDERR "restarting miniserv\n";
2525 &log_error("Restarting");
2527 &close_all_sockets();
2529 dbmclose(%sessiondb);
2530 kill('KILL', $logclearer) if ($logclearer);
2531 kill('KILL', $extauth) if ($extauth);
2532 exec($perl_path, $miniserv_path, @miniserv_argv);
2533 die "Failed to restart miniserv with $perl_path $miniserv_path";
2550 if ($i =~ /(\S+)\/(\S+)/ || $i =~ /^\*\S+$/ ||
2551 $i eq 'LOCAL' || $i =~ /^[0-9\.]+$/) { push(@rv, $i); }
2552 else { push(@rv, join('.', unpack("CCCC", inet_aton($i)))); }
2554 return wantarray ? @rv : $rv[0];
2557 # read_line(no-wait, no-limit)
2558 # Reads one line from SOCK or SSL
2561 local ($nowait, $nolimit) = @_;
2562 local($idx, $more, $rv);
2563 while(($idx = index($main::read_buffer, "\n")) < 0) {
2564 if (length($main::read_buffer) > 10000 && !$nolimit) {
2565 &http_error(414, "Request too long",
2566 "Received excessive line <pre>$main::read_buffer</pre>");
2569 # need to read more..
2570 &wait_for_data_error() if (!$nowait);
2572 $more = Net::SSLeay::read($ssl_con);
2575 local $ok = sysread(SOCK, $more, 1024);
2576 $more = undef if ($ok <= 0);
2580 $rv = $main::read_buffer;
2581 undef($main::read_buffer);
2584 $main::read_buffer .= $more;
2586 $rv = substr($main::read_buffer, 0, $idx+1);
2587 $main::read_buffer = substr($main::read_buffer, $idx+1);
2592 # Reads up to some amount of data from SOCK or the SSL connection
2596 if (length($main::read_buffer)) {
2597 if (length($main::read_buffer) > $_[0]) {
2598 # Return the first part of the buffer
2599 $rv = substr($main::read_buffer, 0, $_[0]);
2600 $main::read_buffer = substr($main::read_buffer, $_[0]);
2604 # Return the whole buffer
2605 $rv = $main::read_buffer;
2606 undef($main::read_buffer);
2611 # Call SSL read function
2612 return Net::SSLeay::read($ssl_con, $_[0]);
2615 # Just do a normal read
2617 sysread(SOCK, $buf, $_[0]) || return undef;
2623 # Read a line from a file handle, using sysread to get a byte at a time
2630 $got = sysread($fh, $buf, 1);
2631 last if ($got <= 0);
2633 last if ($buf eq "\n");
2638 # wait_for_data(secs)
2639 # Waits at most the given amount of time for some data on SOCK, returning
2640 # 0 if not found, 1 if some arrived.
2644 vec($rmask, fileno(SOCK), 1) = 1;
2645 local $got = select($rmask, undef, undef, $_[0]);
2646 return $got == 0 ? 0 : 1;
2649 # wait_for_data_error()
2650 # Waits 60 seconds for data on SOCK, and fails if none arrives
2651 sub wait_for_data_error
2653 local $got = &wait_for_data(60);
2655 &http_error(400, "Timeout",
2656 "Waited more than 60 seconds for request data");
2660 # write_data(data, ...)
2661 # Writes a string to SOCK or the SSL connection
2664 local $str = join("", @_);
2666 Net::SSLeay::write($ssl_con, $str);
2669 syswrite(SOCK, $str, length($str));
2671 # Intentionally introduce a small delay to avoid problems where IE reports
2672 # the page as empty / DNS failed when it get a large response too quickly!
2673 select(undef, undef, undef, .01) if ($write_data_count%10 == 0);
2674 $write_data_count += length($str);
2677 # reset_byte_count()
2678 sub reset_byte_count { $write_data_count = 0; }
2681 sub byte_count { return $write_data_count; }
2683 # log_request(hostname, user, request, code, bytes)
2686 if ($config{'log'}) {
2687 local ($user, $ident, $headers);
2688 if ($config{'logident'}) {
2689 # add support for rfc1413 identity checking here
2691 else { $ident = "-"; }
2692 $user = $_[1] ? $_[1] : "-";
2693 local $dstr = &make_datestr();
2694 if (fileno(MINISERVLOG)) {
2695 seek(MINISERVLOG, 0, 2);
2698 open(MINISERVLOG, ">>$config{'logfile'}");
2699 chmod(0600, $config{'logfile'});
2701 if (defined($config{'logheaders'})) {
2702 foreach $h (split(/\s+/, $config{'logheaders'})) {
2703 $headers .= " $h=\"$header{$h}\"";
2706 elsif ($config{'logclf'}) {
2707 $headers = " \"$header{'referer'}\" \"$header{'user-agent'}\"";
2712 print MINISERVLOG "$_[0] $ident $user [$dstr] \"$_[2]\" ",
2713 "$_[3] $_[4]$headers\n";
2721 local @tm = localtime(time());
2722 return sprintf "%2.2d/%s/%4.4d:%2.2d:%2.2d:%2.2d %s",
2723 $tm[3], $month[$tm[4]], $tm[5]+1900,
2724 $tm[2], $tm[1], $tm[0], $timezone;
2727 # log_error(message)
2731 print STDERR "[",&make_datestr(),"] ",
2732 $acpthost ? ( "[",$acpthost,"] " ) : ( ),
2733 $page ? ( $page," : " ) : ( ),
2737 # read_errors(handle)
2738 # Read and return all input from some filehandle
2741 local($fh, $_, $rv);
2743 while(<$fh>) { $rv .= $_; }
2747 sub write_keep_alive
2750 if ($config{'nokeepalive'}) {
2751 # Keep alives have been disabled in config
2754 elsif (@childpids > $config{'maxconns'}*.8) {
2755 # Disable because nearing process limit
2759 # Keep alive specified by caller
2763 # Keep alive determined by browser
2764 $mode = $header{'connection'} =~ /keep-alive/i;
2766 &write_data("Connection: ".($mode ? "Keep-Alive" : "close")."\r\n");
2772 kill('TERM', @childpids) if (@childpids);
2773 kill('KILL', $logclearer) if ($logclearer);
2774 kill('KILL', $extauth) if ($extauth);
2780 local @tm = gmtime($_[0]);
2781 return sprintf "%s, %d %s %d %2.2d:%2.2d:%2.2d GMT",
2782 $weekday[$tm[6]], $tm[3], $month[$tm[4]], $tm[5]+1900,
2783 $tm[2], $tm[1], $tm[0];
2788 my $i; bless \$i, shift;
2794 my($buf,$len,$offset) = @_;
2795 &write_to_sock(substr($buf, $offset, $len));
2802 my $buf = join(defined($,) ? $, : "", @_);
2803 $buf .= $\ if defined($\);
2804 &write_to_sock($buf);
2811 &write_to_sock(sprintf $fmt, @_);
2814 # Send back already read data while we have it, then read from SOCK
2818 my $bufref = \$_[0];
2821 if ($postpos < length($postinput)) {
2822 # Reading from already fetched array
2823 my $left = length($postinput) - $postpos;
2824 my $canread = $len > $left ? $left : $len;
2825 substr($$bufref, $offset, $canread) =
2826 substr($postinput, $postpos, $canread);
2827 $postpos += $canread;
2831 # Read from network socket
2832 local $data = &read_data($len);
2833 if ($data eq '' && $len) {
2835 print STDERR "finished reading - shutting down socket\n";
2838 substr($$bufref, $offset, length($data)) = $data;
2839 return length($data);
2845 #print STDERR "open() called - should never happen!\n";
2848 # Read a line of input
2852 if ($postpos < length($postinput) &&
2853 ($idx = index($postinput, "\n", $postpos)) >= 0) {
2854 # A line exists in the memory buffer .. use it
2855 my $line = substr($postinput, $postpos, $idx-$postpos+1);
2860 # Need to read from the socket
2862 if ($postpos < length($postinput)) {
2863 # Start with in-memory data
2864 $line = substr($postinput, $postpos);
2865 $postpos = length($postinput);
2867 my $nl = &read_line(0, 1);
2870 print STDERR "finished reading - shutting down socket\n";
2873 $line .= $nl if (defined($nl));
2878 # Read one character of input
2883 my $got = READ($r, \$buf, 1, 0);
2884 return $got > 0 ? $buf : undef;
2889 return fileno(SOCK);
2896 # write_to_sock(data, ...)
2901 if ($doneheaders || $miniserv::nph_script) {
2906 while(!$doneheaders && $headers =~ s/^([^\r\n]*)(\r)?\n//) {
2907 if ($1 =~ /^(\S+):\s+(.*)$/) {
2908 $cgiheader{lc($1)} = $2;
2909 push(@cgiheader, [ $1, $2 ]);
2911 elsif ($1 !~ /\S/) {
2915 &http_error(500, "Bad Header");
2919 if ($cgiheader{"location"}) {
2921 "HTTP/1.0 302 Moved Temporarily\r\n");
2922 &write_data("Date: $datestr\r\n");
2923 &write_data("Server: $config{server}\r\n");
2924 &write_keep_alive(0);
2926 elsif ($cgiheader{"content-type"} eq "") {
2927 &http_error(500, "Missing Content-Type Header");
2930 &write_data("HTTP/1.0 $ok_code $ok_message\r\n");
2931 &write_data("Date: $datestr\r\n");
2932 &write_data("Server: $config{server}\r\n");
2933 &write_keep_alive(0);
2935 foreach $h (@cgiheader) {
2936 &write_data("$h->[0]: $h->[1]\r\n");
2938 &write_data("\r\n");
2939 &reset_byte_count();
2940 &write_data($headers);
2948 local $cert = Net::SSLeay::X509_STORE_CTX_get_current_cert($_[1]);
2950 local $errnum = Net::SSLeay::X509_STORE_CTX_get_error($_[1]);
2951 $verified_client = 1 if (!$errnum);
2958 if ($doing_eval && $$ == $main_process_id) {
2959 # A CGI program called exit! This is a horrible hack to
2960 # finish up before really exiting
2963 close($PASSINw); close($PASSOUTw);
2964 &log_request($acpthost, $authuser, $reqline,
2965 $cgiheader{"location"} ? "302" : $ok_code, &byte_count());
2970 # Convert a string to a form ok for putting in a URL
2972 local($tmp, $tmp2, $c);
2975 while(($c = chop($tmp)) ne "") {
2976 if ($c !~ /[A-z0-9]/) {
2977 $c = sprintf("%%%2.2X", ord($c));
2984 # validate_user(username, password, host)
2985 # Checks if some username and password are valid. Returns the modified username,
2986 # the expired / temp pass flag, and the non-existence flag
2989 local ($user, $pass, $host) = @_;
2990 return ( ) if (!$user);
2991 print DEBUG "validate_user: user=$user pass=$pass host=$host\n";
2992 local ($canuser, $canmode, $notexist, $webminuser, $sudo) =
2993 &can_user_login($user, undef, $host);
2994 print DEBUG "validate_user: canuser=$canuser canmode=$canmode notexist=$notexist webminuser=$webminuser sudo=$sudo\n";
2996 # User doesn't even exist, so go no further
2997 return ( undef, 0, 1 );
2999 elsif ($canmode == 0) {
3000 # User does exist but cannot login
3001 return ( $canuser, 0, 0 );
3003 elsif ($canmode == 1) {
3004 # Attempt Webmin authentication
3005 if ($users{$webminuser} eq
3006 &password_crypt($pass, $users{$webminuser})) {
3007 # Password is valid .. but check for expiry
3008 local $lc = $lastchanges{$user};
3009 if ($config{'pass_maxdays'} && $lc && !$nochange{$user}) {
3010 local $daysold = (time() - $lc)/(24*60*60);
3011 print DEBUG "maxdays=$config{'pass_maxdays'} daysold=$daysold temppass=$temppass{$user}\n";
3012 if ($config{'pass_lockdays'} &&
3013 $daysold > $config{'pass_lockdays'}) {
3014 # So old that the account is locked
3015 return ( undef, 0, 0 );
3017 elsif ($daysold > $config{'pass_maxdays'}) {
3018 # Password has expired
3019 return ( $user, 1, 0 );
3022 if ($temppass{$user}) {
3023 # Temporary password - force change now
3024 return ( $user, 2, 0 );
3026 return ( $user, 0, 0 );
3029 return ( undef, 0, 0 );
3032 elsif ($canmode == 2 || $canmode == 3) {
3033 # Attempt PAM or passwd file authentication
3034 local $val = &validate_unix_user($canuser, $pass);
3035 print DEBUG "validate_user: unix val=$val\n";
3036 if ($val && $sudo) {
3037 # Need to check if this Unix user can sudo
3038 if (!&check_sudo_permissions($canuser, $pass)) {
3039 print DEBUG "validate_user: sudo failed\n";
3043 print DEBUG "validate_user: sudo passed\n";
3046 return $val == 2 ? ( $canuser, 1, 0 ) :
3047 $val == 1 ? ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3049 elsif ($canmode == 4) {
3050 # Attempt external authentication
3051 return &validate_external_user($canuser, $pass) ?
3052 ( $canuser, 0, 0 ) : ( undef, 0, 0 );
3060 # validate_unix_user(user, password)
3061 # Returns 1 if a username and password are valid under unix, 0 if not,
3062 # or 2 if the account has expired.
3063 # Checks PAM if available, and falls back to reading the system password
3065 sub validate_unix_user
3069 $pam_username = $_[0];
3070 $pam_password = $_[1];
3071 local $pamh = new Authen::PAM($config{'pam'}, $pam_username,
3074 local $pam_ret = $pamh->pam_authenticate();
3075 if ($pam_ret == PAM_SUCCESS()) {
3076 # Logged in OK .. make sure password hasn't expired
3077 local $acct_ret = $pamh->pam_acct_mgmt();
3078 if ($acct_ret == PAM_SUCCESS()) {
3079 $pamh->pam_open_session();
3082 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3083 $acct_ret == PAM_ACCT_EXPIRED()) {
3087 print STDERR "Unknown pam_acct_mgmt return value : $acct_ret\n";
3094 elsif ($config{'pam_only'}) {
3095 # Pam is not available, but configuration forces it's use!
3098 elsif ($config{'passwd_file'}) {
3099 # Check in a password file
3101 open(FILE, $config{'passwd_file'});
3102 if ($config{'passwd_file'} eq '/etc/security/passwd') {
3103 # Assume in AIX format
3106 if (/^\s*(\S+):/ && $1 eq $_[0]) {
3108 if (/^\s*password\s*=\s*(\S+)\s*$/) {
3109 $rv = $1 eq &password_crypt($_[1], $1) ?
3117 # Read the system password or shadow file
3119 local @l = split(/:/, $_, -1);
3120 local $u = $l[$config{'passwd_uindex'}];
3121 local $p = $l[$config{'passwd_pindex'}];
3123 $rv = $p eq &password_crypt($_[1], $p) ? 1 : 0;
3124 if ($config{'passwd_cindex'} ne '' && $rv) {
3125 # Password may have expired!
3126 local $c = $l[$config{'passwd_cindex'}];
3127 local $m = $l[$config{'passwd_mindex'}];
3128 local $day = time()/(24*60*60);
3129 if ($c =~ /^\d+/ && $m =~ /^\d+/ &&
3135 if ($p eq "" && $config{'passwd_blank'}) {
3136 # Force password change
3144 return $rv if ($rv);
3147 # Fallback option - check password returned by getpw*
3148 local @uinfo = getpwnam($_[0]);
3149 if ($uinfo[1] ne '' && &password_crypt($_[1], $uinfo[1]) eq $uinfo[1]) {
3153 return 0; # Totally failed
3156 # validate_external_user(user, pass)
3157 # Validate a user by passing the username and password to an external
3158 # squid-style authentication program
3159 sub validate_external_user
3161 return 0 if (!$config{'extauth'});
3163 local $str = "$_[0] $_[1]\n";
3164 syswrite(EXTAUTH, $str, length($str));
3165 local $resp = <EXTAUTH>;
3167 return $resp =~ /^OK/i ? 1 : 0;
3170 # can_user_login(username, no-append, host)
3171 # Checks if a user can login or not.
3172 # First return value is the username.
3173 # Second is 0 if cannot login, 1 if using Webmin pass, 2 if PAM, 3 if password
3174 # file, 4 if external.
3175 # Third is 1 if the user does not exist at all, 0 if he does.
3176 # Fourth is the Webmin username whose permissions apply, based on unixauth.
3177 # Fifth is a flag indicating if a sudo check is needed.
3180 if (!$users{$_[0]}) {
3181 # See if this user exists in Unix and can be validated by the same
3182 # method as the unixauth webmin user
3183 local $realuser = $unixauth{$_[0]};
3187 eval { @uinfo = getpwnam($_[0]); }; # may fail on windows
3188 if (!$realuser && @uinfo) {
3189 # No unixauth entry for the username .. try his groups
3190 foreach my $ua (keys %unixauth) {
3191 if ($ua =~ /^\@(.*)$/) {
3192 if (&is_group_member(\@uinfo, $1)) {
3193 $realuser = $unixauth{$ua};
3199 if (!$realuser && @uinfo) {
3200 # Fall back to unix auth for all Unix users
3201 $realuser = $unixauth{"*"};
3203 if (!$realuser && $use_sudo && @uinfo) {
3204 # Allow login effectively as root, if sudo permits it
3208 if (!$realuser && !@uinfo && $config{'pamany'}) {
3209 # If the user completely doesn't exist, we can still allow
3210 # him to authenticate via PAM
3211 $realuser = $config{'pamany'};
3215 # For Usermin, always fall back to unix auth for any user,
3216 # so that later checks with domain added / removed are done.
3217 $realuser = $unixauth{"*"};
3219 return (undef, 0, 1, undef) if (!$realuser);
3220 local $up = $users{$realuser};
3221 return (undef, 0, 1, undef) if (!defined($up));
3223 # Work out possible domain names from the hostname
3224 local @doms = ( $_[2] );
3225 if ($_[2] =~ /^([^\.]+)\.(\S+)$/) {
3229 if ($config{'user_mapping'} && !defined(%user_mapping)) {
3230 # Read the user mapping file
3232 open(MAPPING, $config{'user_mapping'});
3236 if (/^(\S+)\s+(\S+)/) {
3237 if ($config{'user_mapping_reverse'}) {
3238 $user_mapping{$1} = $2;
3241 $user_mapping{$2} = $1;
3248 # Check the user mapping file to see if there is an entry for the
3249 # user login in which specifies a new effective user
3251 foreach my $d (@doms) {
3252 $um ||= $user_mapping{"$_[0]\@$d"};
3254 $um ||= $user_mapping{$_[0]};
3255 if (defined($um) && ($_[1]&4) == 0) {
3256 # A mapping exists - use it!
3257 return &can_user_login($um, $_[1]+4, $_[2]);
3260 # Check if a user with the entered login and the domains appended
3261 # or prepended exists, and if so take it to be the effective user
3262 if (!@uinfo && $config{'domainuser'}) {
3263 # Try again with name.domain and name.firstpart
3264 local @firsts = map { /^([^\.]+)/; $1 } @doms;
3265 if (($_[1]&1) == 0) {
3267 foreach $a (@firsts, @doms) {
3268 foreach $p ("$_[0].${a}", "$_[0]-${a}",
3269 "${a}.$_[0]", "${a}-$_[0]",
3270 "$_[0]_${a}", "${a}_$_[0]") {
3271 local @vu = &can_user_login(
3272 $p, $_[1]+1, $_[2]);
3273 return @vu if ($vu[1]);
3279 # Check if the user entered a domain at the end of his username when
3280 # he really shouldn't have, and if so try without it
3281 if (!@uinfo && $config{'domainstrip'} &&
3282 $_[0] =~ /^(\S+)\@(\S+)$/ && ($_[1]&2) == 0) {
3283 local ($stripped, $dom) = ($1, $2);
3284 local @vu = &can_user_login($stripped, $_[1] + 2, $_[2]);
3285 return @vu if ($vu[1]);
3286 local @vu = &can_user_login($stripped, $_[1] + 2, $dom);
3287 return @vu if ($vu[1]);
3290 return ( undef, 0, 1, undef ) if (!@uinfo && !$pamany);
3293 if (defined(@allowusers)) {
3294 # Only allow people on the allow list
3295 return ( undef, 0, 0, undef )
3296 if (!&users_match(\@uinfo, @allowusers));
3298 elsif (defined(@denyusers)) {
3299 # Disallow people on the deny list
3300 return ( undef, 0, 0, undef )
3301 if (&users_match(\@uinfo, @denyusers));
3303 if ($config{'shells_deny'}) {
3305 open(SHELLS, $config{'shells_deny'});
3309 $found++ if ($_ eq $uinfo[8]);
3312 return ( undef, 0, 0, undef ) if (!$found);
3317 # PAM or passwd file authentication
3318 return ( $_[0], $use_pam ? 2 : 3, 0, $realuser, $sudo );
3320 elsif ($up eq 'e') {
3321 # External authentication
3322 return ( $_[0], 4, 0, $realuser, $sudo );
3325 # Fixed Webmin password
3326 return ( $_[0], 1, 0, $realuser, $sudo );
3329 elsif ($users{$_[0]} eq 'x') {
3330 # Webmin user authenticated via PAM or password file
3331 return ( $_[0], $use_pam ? 2 : 3, 0, $_[0] );
3333 elsif ($users{$_[0]} eq 'e') {
3334 # Webmin user authenticated externally
3335 return ( $_[0], 4, 0, $_[0] );
3338 # Normal Webmin user
3339 return ( $_[0], 1, 0, $_[0] );
3343 # the PAM conversation function for interactive logins
3346 $pam_conv_func_called++;
3353 $ans = $pam_username if ($code == PAM_PROMPT_ECHO_ON() );
3354 $ans = $pam_password if ($code == PAM_PROMPT_ECHO_OFF() );
3356 push @res, PAM_SUCCESS();
3359 push @res, PAM_SUCCESS();
3368 # get_socket_name(handle)
3369 # Returns the local hostname or IP address of some connection
3372 return $config{'host'} if ($config{'host'});
3373 local $sn = getsockname($_[0]);
3374 return undef if (!$sn);
3375 local $myaddr = (unpack_sockaddr_in($sn))[1];
3376 if (!$get_socket_name_cache{$myaddr}) {
3378 if (!$config{'no_resolv_myname'}) {
3379 $myname = gethostbyaddr($myaddr, AF_INET);
3381 if ($myname eq "") {
3382 $myname = inet_ntoa($myaddr);
3384 $get_socket_name_cache{$myaddr} = $myname;
3386 return $get_socket_name_cache{$myaddr};
3389 # run_login_script(username, sid, remoteip, localip)
3390 sub run_login_script
3392 if ($config{'login_script'}) {
3393 system($config{'login_script'}.
3394 " ".join(" ", map { quotemeta($_) } @_).
3395 " >/dev/null 2>&1 </dev/null");
3399 # run_logout_script(username, sid, remoteip, localip)
3400 sub run_logout_script
3402 if ($config{'logout_script'}) {
3403 system($config{'logout_script'}.
3404 " ".join(" ", map { quotemeta($_) } @_).
3405 " >/dev/null 2>&1 </dev/null");
3409 # close_all_sockets()
3410 # Closes all the main listening sockets
3411 sub close_all_sockets
3414 foreach $s (@socketfhs) {
3420 # Close all pipes for talking to sub-processes
3424 foreach $p (@passin) { close($p); }
3425 foreach $p (@passout) { close($p); }
3426 foreach $p (values %conversations) {
3427 if ($p->{'PAMOUTr'}) {
3428 close($p->{'PAMOUTr'});
3429 close($p->{'PAMINw'});
3434 # check_user_ip(user)
3435 # Returns 1 if some user is allowed to login from the accepting IP, 0 if not
3439 &ip_match($acptip, $localip, @{$deny{$_[0]}}) ||
3441 !&ip_match($acptip, $localip, @{$allow{$_[0]}})) {
3447 # check_user_time(user)
3448 # Returns 1 if some user is allowed to login at the current date and time
3451 return 1 if (!$allowdays{$_[0]} && !$allowhours{$_[0]});
3452 local @tm = localtime(time());
3453 if ($allowdays{$_[0]}) {
3454 # Make sure day is allowed
3455 return 0 if (&indexof($tm[6], @{$allowdays{$_[0]}}) < 0);
3457 if ($allowhours{$_[0]}) {
3458 # Make sure time is allowed
3459 local $m = $tm[2]*60+$tm[1];
3460 return 0 if ($m < $allowhours{$_[0]}->[0] ||
3461 $m > $allowhours{$_[0]}->[1]);
3466 # generate_random_id(password, [force-urandom])
3467 # Returns a random session ID number
3468 sub generate_random_id
3470 local ($pass, $force_urandom) = @_;
3472 if (!$bad_urandom) {
3473 # First try /dev/urandom, unless we have marked it as bad
3474 $SIG{ALRM} = "miniserv::urandom_timeout";
3476 if (open(RANDOM, "/dev/urandom")) {
3478 if (read(RANDOM, $tmpsid, 16) == 16) {
3479 $sid = lc(unpack('h*',$tmpsid));
3485 if (!$sid && !$force_urandom) {
3488 foreach $c (split(//, &unix_crypt($pass, substr($$, -2)))) {
3489 $sid += ord($c) * $mul;
3496 # handle_login(username, ok, expired, not-exists, password, [no-test-cookie])
3497 # Called from handle_session to either mark a user as logged in, or not
3500 local ($vu, $ok, $expired, $nonexist, $pass, $notest) = @_;
3501 $authuser = $vu if ($ok);
3503 # check if the test cookie is set
3504 if ($header{'cookie'} !~ /testing=1/ && $vu &&
3505 !$config{'no_testing_cookie'} && !$notest) {
3506 &http_error(500, "No cookies",
3507 "Your browser does not support cookies, ".
3508 "which are required for this web server to ".
3509 "work in session authentication mode");
3512 # check with main process for delay
3513 if ($config{'passdelay'} && $vu) {
3514 print $PASSINw "delay $vu $acptip $ok\n";
3515 <$PASSOUTr> =~ /(\d+) (\d+)/;
3520 if ($ok && (!$expired ||
3521 $config{'passwd_mode'} == 1)) {
3522 # Logged in OK! Tell the main process about
3524 local $sid = &generate_random_id($pass);
3525 print $PASSINw "new $sid $authuser $acptip\n";
3527 # Run the post-login script, if any
3528 &run_login_script($authuser, $sid,
3531 # Check for a redirect URL for the user
3532 local $rurl = &login_redirect($authuser, $pass, $host);
3534 # Got one .. go to it
3535 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3536 &write_data("Date: $datestr\r\n");
3537 &write_data("Server: $config{'server'}\r\n");
3538 &write_data("Location: $rurl\r\n");
3539 &write_keep_alive(0);
3540 &write_data("\r\n");
3541 &log_request($acpthost, $authuser, $reqline, 302, 0);
3544 # Set cookie and redirect to originally requested page
3545 &write_data("HTTP/1.0 302 Moved Temporarily\r\n");
3546 &write_data("Date: $datestr\r\n");
3547 &write_data("Server: $config{'server'}\r\n");
3548 local $ssl = $use_ssl || $config{'inetd_ssl'};
3549 $portstr = $port == 80 && !$ssl ? "" :
3550 $port == 443 && $ssl ? "" : ":$port";
3551 $prot = $ssl ? "https" : "http";
3552 local $sec = $ssl ? "; secure" : "";
3553 #$sec .= "; httpOnly";
3555 &write_data("Set-Cookie: $sidname=$sid; path=/; expires=\"Thu, 31-Dec-2037 00:00:00\"$sec\r\n");
3558 &write_data("Set-Cookie: $sidname=$sid; path=/$sec\r\n");
3560 &write_data("Location: $prot://$host$portstr$in{'page'}\r\n");
3561 &write_keep_alive(0);
3562 &write_data("\r\n");
3563 &log_request($acpthost, $authuser, $reqline, 302, 0);
3564 syslog("info", "%s", "Successful login as $authuser from $acpthost") if ($use_syslog);
3565 &write_login_utmp($authuser, $acpthost);
3569 elsif ($ok && $expired &&
3570 ($config{'passwd_mode'} == 2 || $expired == 2)) {
3571 # Login was ok, but password has expired or was temporary. Need
3572 # to force display of password change form.
3575 $querystring = "&user=".&urlize($vu).
3577 "&expired=".$expired;
3580 $page = $config{'password_form'};
3582 $miniserv_internal = 2;
3583 syslog("crit", "%s",
3584 "Expired login as $vu ".
3585 "from $acpthost") if ($use_syslog);
3588 # Login failed, or password has expired. The login form will be
3589 # displayed again by later code
3591 $request_uri = $in{'page'};
3592 $already_session_id = undef;
3594 $authuser = $baseauthuser = undef;
3595 syslog("crit", "%s",
3596 ($nonexist ? "Non-existent" :
3597 $expired ? "Expired" : "Invalid").
3598 " login as $vu from $acpthost")
3604 # write_login_utmp(user, host)
3605 # Record the login by some user in utmp
3606 sub write_login_utmp
3609 # Write utmp record for login
3610 %utmp = ( 'ut_host' => $_[1],
3611 'ut_time' => time(),
3613 'ut_type' => 7, # user process
3614 'ut_pid' => $main_process_id,
3615 'ut_line' => $config{'pam'},
3617 if (defined(&User::Utmp::putut)) {
3618 User::Utmp::putut(\%utmp);
3621 User::Utmp::pututline(\%utmp);
3626 # write_logout_utmp(user, host)
3627 # Record the logout by some user in utmp
3628 sub write_logout_utmp
3631 # Write utmp record for logout
3632 %utmp = ( 'ut_host' => $_[1],
3633 'ut_time' => time(),
3635 'ut_type' => 8, # dead process
3636 'ut_pid' => $main_process_id,
3637 'ut_line' => $config{'pam'},
3639 if (defined(&User::Utmp::putut)) {
3640 User::Utmp::putut(\%utmp);
3643 User::Utmp::pututline(\%utmp);
3648 # pam_conversation_process(username, write-pipe, read-pipe)
3649 # This function is called inside a sub-process to communicate with PAM. It sends
3650 # questions down one pipe, and reads responses from another
3651 sub pam_conversation_process
3653 local ($user, $writer, $reader) = @_;
3654 $miniserv::pam_conversation_process_writer = $writer;
3655 $miniserv::pam_conversation_process_reader = $reader;
3656 local $convh = new Authen::PAM(
3657 $config{'pam'}, $user, \&miniserv::pam_conversation_process_func);
3658 local $pam_ret = $convh->pam_authenticate();
3659 if ($pam_ret == PAM_SUCCESS()) {
3660 local $acct_ret = $convh->pam_acct_mgmt();
3661 if ($acct_ret == PAM_SUCCESS()) {
3662 $convh->pam_open_session();
3663 print $writer "x2 $user 1 0 0\n";
3665 elsif ($acct_ret == PAM_NEW_AUTHTOK_REQD() ||
3666 $acct_ret == PAM_ACCT_EXPIRED()) {
3667 print $writer "x2 $user 1 1 0\n";
3670 print $writer "x0 Unknown PAM account status $acct_ret\n";
3674 print $writer "x2 $user 0 0 0\n";
3679 # pam_conversation_process_func(type, message, [type, message, ...])
3680 # A pipe that talks to both PAM and the master process
3681 sub pam_conversation_process_func
3684 select($miniserv::pam_conversation_process_writer); $| = 1; select(STDOUT);
3686 local ($type, $msg) = (shift, shift);
3688 local $ok = (print $miniserv::pam_conversation_process_writer "$type $msg\n");
3689 print $miniserv::pam_conversation_process_writer "\n";
3690 local $answer = <$miniserv::pam_conversation_process_reader>;
3691 $answer =~ s/\r|\n//g;
3692 push(@rv, PAM_SUCCESS(), $answer);
3694 push(@rv, PAM_SUCCESS());
3699 # Returns 4 new pipe file handles
3702 local ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3704 local %taken = ( (map { $_, 1 } @passin),
3705 (map { $_->{'PASSINr'} } values %conversations) );
3706 for($p=0; $taken{"PASSINr$p"}; $p++) { }
3707 $PASSINr = "PASSINr$p";
3708 $PASSINw = "PASSINw$p";
3709 $PASSOUTr = "PASSOUTr$p";
3710 $PASSOUTw = "PASSOUTw$p";
3711 pipe($PASSINr, $PASSINw);
3712 pipe($PASSOUTr, $PASSOUTw);
3713 select($PASSINw); $| = 1;
3714 select($PASSINr); $| = 1;
3715 select($PASSOUTw); $| = 1;
3716 select($PASSOUTw); $| = 1;
3718 return ($PASSINr, $PASSINw, $PASSOUTr, $PASSOUTw);
3721 # recv_pam_question(&conv, fd)
3722 # Reads one PAM question from the sub-process, and sends it to the HTTP handler.
3723 # Returns 0 if the conversation is over, 1 if not.
3724 sub recv_pam_question
3726 local ($conf, $fh) = @_;
3727 local $pr = $conf->{'PAMOUTr'};
3728 select($pr); $| = 1; select(STDOUT);
3729 local $line = <$pr>;
3730 $line =~ s/\r|\n//g;
3733 $line =~ s/\r|\n//g;
3735 $conf->{'last'} = time();
3738 print $fh "0 PAM conversation error\n";
3742 local ($type, $msg) = split(/\s+/, $line, 2);
3743 if ($type =~ /^x(\d+)/) {
3744 # Pass this status code through
3745 print $fh "$1 $msg\n";
3746 return $1 == 2 || $1 == 0 ? 0 : 1;
3748 elsif ($type == PAM_PROMPT_ECHO_ON()) {
3750 print $fh "1 $msg\n";
3753 elsif ($type == PAM_PROMPT_ECHO_OFF()) {
3755 print $fh "3 $msg\n";
3758 elsif ($type == PAM_ERROR_MSG() || $type == PAM_TEXT_INFO()) {
3759 # A message that does not require a response
3760 print $fh "4 $msg\n";
3765 print $fh "0 Unknown PAM message type $type\n";
3771 # send_pam_answer(&conv, answer)
3772 # Sends a response from the user to the PAM sub-process
3775 local ($conf, $answer) = @_;
3776 local $pw = $conf->{'PAMINw'};
3777 $conf->{'last'} = time();
3778 print $pw "$answer\n";
3781 # end_pam_conversation(&conv)
3782 # Clean up PAM conversation pipes and processes
3783 sub end_pam_conversation
3786 kill('KILL', $conv->{'pid'}) if ($conv->{'pid'});
3787 if ($conv->{'PAMINr'}) {
3788 close($conv->{'PAMINr'});
3789 close($conv->{'PAMOUTr'});
3790 close($conv->{'PAMINw'});
3791 close($conv->{'PAMOUTw'});
3793 delete($conversations{$conv->{'cid'}});
3796 # get_ipkeys(&miniserv)
3797 # Returns a list of IP address to key file mappings from a miniserv.conf entry
3801 foreach $k (keys %{$_[0]}) {
3802 if ($k =~ /^ipkey_(\S+)/) {
3803 local $ipkey = { 'ips' => [ split(/,/, $1) ],
3804 'key' => $_[0]->{$k},
3805 'index' => scalar(@rv) };
3806 $ipkey->{'cert'} = $_[0]->{'ipcert_'.$1};
3813 # create_ssl_context(keyfile, [certfile])
3814 sub create_ssl_context
3816 local ($keyfile, $certfile) = @_;
3818 eval { $ssl_ctx = Net::SSLeay::new_x_ctx() };
3819 $ssl_ctx ||= Net::SSLeay::CTX_new();
3820 $ssl_ctx || die "Failed to create SSL context : $!";
3821 if ($client_certs) {
3822 Net::SSLeay::CTX_load_verify_locations(
3823 $ssl_ctx, $config{'ca'}, "");
3824 Net::SSLeay::CTX_set_verify(
3825 $ssl_ctx, &Net::SSLeay::VERIFY_PEER, \&verify_client);
3827 if ($config{'extracas'}) {
3829 foreach $p (split(/\s+/, $config{'extracas'})) {
3830 Net::SSLeay::CTX_load_verify_locations(
3835 Net::SSLeay::CTX_use_RSAPrivateKey_file(
3837 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL key $keyfile";
3838 Net::SSLeay::CTX_use_certificate_file(
3839 $ssl_ctx, $certfile || $keyfile,
3840 &Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL cert $certfile";
3845 # ssl_connection_for_ip(socket)
3846 # Returns a new SSL connection object for some socket, or undef if failed
3847 sub ssl_connection_for_ip
3850 local $sn = getsockname($sock);
3852 print STDERR "Failed to get address for socket $sock\n";
3855 local $myip = inet_ntoa((unpack_sockaddr_in($sn))[1]);
3856 local $ssl_ctx = $ssl_contexts{$myip} || $ssl_contexts{"*"};
3857 local $ssl_con = Net::SSLeay::new($ssl_ctx);
3858 if ($config{'ssl_cipher_list'}) {
3859 # Force use of ciphers
3860 eval "Net::SSLeay::set_cipher_list(
3861 \$ssl_con, \$config{'ssl_cipher_list'})";
3863 print STDERR "SSL cipher $config{'ssl_cipher_list'} failed : ",
3869 Net::SSLeay::set_fd($ssl_con, fileno($sock));
3870 if (!Net::SSLeay::accept($ssl_con)) {
3871 print STDERR "Failed to initialize SSL connection\n";
3877 # login_redirect(username, password, host)
3878 # Calls the login redirect script (if configured), which may output a URL to
3879 # re-direct a user to after logging in.
3882 return undef if (!$config{'login_redirect'});
3883 local $quser = quotemeta($_[0]);
3884 local $qpass = quotemeta($_[1]);
3885 local $qhost = quotemeta($_[2]);
3886 local $url = `$config{'login_redirect'} $quser $qpass $qhost`;
3891 # reload_config_file()
3892 # Re-read %config, and call post-config actions
3893 sub reload_config_file
3895 &log_error("Reloading configuration");
3896 %config = &read_config_file($config_file);
3897 &update_vital_config();
3900 &build_config_mappings();
3901 if ($config{'session'}) {
3902 dbmclose(%sessiondb);
3903 dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
3907 # read_config_file(file)
3908 # Reads the given config file, and returns a hash of values
3909 sub read_config_file
3912 open(CONF, $_[0]) || die "Failed to open config file $_[0] : $!";
3915 if (/^#/ || !/\S/) { next; }
3917 $name = $1; $val = $2;
3918 $name =~ s/^\s+//g; $name =~ s/\s+$//g;
3919 $val =~ s/^\s+//g; $val =~ s/\s+$//g;
3926 # update_vital_config()
3927 # Updates %config with defaults, and dies if something vital is missing
3928 sub update_vital_config
3930 my %vital = ("port", 80,
3932 "server", "MiniServ/0.01",
3933 "index_docs", "index.html index.htm index.cgi index.php",
3934 "addtype_html", "text/html",
3935 "addtype_txt", "text/plain",
3936 "addtype_gif", "image/gif",
3937 "addtype_jpg", "image/jpeg",
3938 "addtype_jpeg", "image/jpeg",
3939 "realm", "MiniServ",
3940 "session_login", "/session_login.cgi",
3941 "pam_login", "/pam_login.cgi",
3942 "password_form", "/password_form.cgi",
3943 "password_change", "/password_change.cgi",
3947 "unauth", "^/unauthenticated/ ^[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\$",
3949 "expires", 7*24*60*60,
3951 foreach my $v (keys %vital) {
3953 if ($vital{$v} eq "") {
3954 die "Missing config option $v";
3956 $config{$v} = $vital{$v};
3959 if (!$config{'sessiondb'}) {
3960 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3961 $config{'sessiondb'} = "$1/sessiondb";
3963 if (!$config{'errorlog'}) {
3964 $config{'logfile'} =~ /^(.*)\/[^\/]+$/;
3965 $config{'errorlog'} = "$1/miniserv.error";
3967 if (!$config{'tempbase'}) {
3968 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3969 $config{'tempbase'} = "$1/cgitemp";
3971 if (!$config{'blockedfile'}) {
3972 $config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
3973 $config{'blockedfile'} = "$1/blocked";
3978 # Fills the %users and %certs hashes from the users file in %config
3987 undef(%lastchanges);
3990 if ($config{'userfile'}) {
3991 open(USERS, $config{'userfile'});
3994 local @user = split(/:/, $_, -1);
3995 $users{$user[0]} = $user[1];
3996 $certs{$user[0]} = $user[3] if ($user[3]);
3997 if ($user[4] =~ /^allow\s+(.*)/) {
3998 $allow{$user[0]} = $config{'alwaysresolve'} ?
3999 [ split(/\s+/, $1) ] :
4000 [ &to_ipaddress(split(/\s+/, $1)) ];
4002 elsif ($user[4] =~ /^deny\s+(.*)/) {
4003 $deny{$user[0]} = $config{'alwaysresolve'} ?
4004 [ split(/\s+/, $1) ] :
4005 [ &to_ipaddress(split(/\s+/, $1)) ];
4007 if ($user[5] =~ /days\s+(\S+)/) {
4008 $allowdays{$user[0]} = [ split(/,/, $1) ];
4010 if ($user[5] =~ /hours\s+(\d+)\.(\d+)-(\d+).(\d+)/) {
4011 $allowhours{$user[0]} = [ $1*60+$2, $3*60+$4 ];
4013 $lastchanges{$user[0]} = $user[6];
4014 $nochange{$user[0]} = $user[9];
4015 $temppass{$user[0]} = $user[10];
4022 # Fills %mime with entries from file in %config and extra settings in %config
4026 if ($config{"mimetypes"} ne "") {
4027 open(MIME, $config{"mimetypes"});
4030 if (/^(\S+)\s+(.*)$/) {
4032 my @exts = split(/\s+/, $2);
4033 foreach my $ext (@exts) {
4034 $mime{$ext} = $type;
4040 foreach my $k (keys %config) {
4041 if ($k !~ /^addtype_(.*)$/) { next; }
4042 $mime{$1} = $config{$k};
4046 # build_config_mappings()
4047 # Build the anonymous access list, IP access list, unauthenticated URLs list,
4048 # redirect mapping and allow and deny lists from %config
4049 sub build_config_mappings
4051 # build anonymous access list
4053 foreach my $a (split(/\s+/, $config{'anonymous'})) {
4054 if ($a =~ /^([^=]+)=(\S+)$/) {
4055 $anonymous{$1} = $2;
4059 # build IP access list
4061 foreach my $a (split(/\s+/, $config{'ipaccess'})) {
4062 if ($a =~ /^([^=]+)=(\S+)$/) {
4067 # build unauthenticated URLs list
4068 @unauth = split(/\s+/, $config{'unauth'});
4070 # build redirect mapping
4072 foreach my $r (split(/\s+/, $config{'redirect'})) {
4073 if ($r =~ /^([^=]+)=(\S+)$/) {
4078 # build prefixes to be stripped
4079 undef(@strip_prefix);
4080 foreach my $r (split(/\s+/, $config{'strip_prefix'})) {
4081 push(@strip_prefix, $r);
4084 # Init allow and deny lists
4085 @deny = split(/\s+/, $config{"deny"});
4086 @deny = &to_ipaddress(@deny) if (!$config{'alwaysresolve'});
4087 @allow = split(/\s+/, $config{"allow"});
4088 @allow = &to_ipaddress(@allow) if (!$config{'alwaysresolve'});
4091 if ($config{'allowusers'}) {
4092 @allowusers = split(/\s+/, $config{'allowusers'});
4094 elsif ($config{'denyusers'}) {
4095 @denyusers = split(/\s+/, $config{'denyusers'});
4098 # Build list of unixauth mappings
4100 foreach my $ua (split(/\s+/, $config{'unixauth'})) {
4101 if ($ua =~ /^(\S+)=(\S+)$/) {
4105 $unixauth{"*"} = $ua;
4109 # Build list of non-session-auth pages
4110 undef(%sessiononly);
4111 foreach my $sp (split(/\s+/, $config{'sessiononly'})) {
4112 $sessiononly{$sp} = 1;
4115 # Build list of logout times
4116 undef(@logouttimes);
4117 foreach my $a (split(/\s+/, $config{'logouttimes'})) {
4118 if ($a =~ /^([^=]+)=(\S+)$/) {
4119 push(@logouttimes, [ $1, $2 ]);
4122 push(@logouttimes, [ undef, $config{'logouttime'} ]);
4124 # Build list of DAV pathss
4126 foreach my $d (split(/\s+/, $config{'davpaths'})) {
4127 push(@davpaths, $d);
4129 @davusers = split(/\s+/, $config{'dav_users'});
4131 # Mobile agent substrings and hostname prefixes
4132 @mobile_agents = split(/\t+/, $config{'mobile_agents'});
4133 @mobile_prefixes = split(/\s+/, $config{'mobile_prefixes'});
4137 if ($config{'debug'}) {
4138 open(DEBUG, ">>$config{'debug'}");
4141 open(DEBUG, ">/dev/null");
4144 # Reset cache of sudo checks
4148 # is_group_member(&uinfo, groupname)
4149 # Returns 1 if some user is a primary or secondary member of a group
4152 local ($uinfo, $group) = @_;
4153 local @ginfo = getgrnam($group);
4154 return 0 if (!@ginfo);
4155 return 1 if ($ginfo[2] == $uinfo->[3]); # primary member
4156 foreach my $m (split(/\s+/, $ginfo[3])) {
4157 return 1 if ($m eq $uinfo->[0]);
4162 # prefix_to_mask(prefix)
4163 # Converts a number like 24 to a mask like 255.255.255.0
4166 return $_[0] >= 24 ? "255.255.255.".(256-(2 ** (32-$_[0]))) :
4167 $_[0] >= 16 ? "255.255.".(256-(2 ** (24-$_[0]))).".0" :
4168 $_[0] >= 8 ? "255.".(256-(2 ** (16-$_[0]))).".0.0" :
4169 (256-(2 ** (8-$_[0]))).".0.0.0";
4172 # get_logout_time(user, session-id)
4173 # Given a username, returns the idle time before he will be logged out
4176 local ($user, $sid) = @_;
4177 if (!defined($logout_time_cache{$user,$sid})) {
4179 foreach my $l (@logouttimes) {
4180 if ($l->[0] =~ /^\@(.*)$/) {
4181 # Check group membership
4182 local @uinfo = getpwnam($user);
4183 if (@uinfo && &is_group_member(\@uinfo, $1)) {
4187 elsif ($l->[0] =~ /^\//) {
4188 # Check file contents
4189 open(FILE, $l->[0]);
4206 if ($l->[0] eq $user) {
4210 last if (defined($time));
4212 $logout_time_cache{$user,$sid} = $time;
4214 return $logout_time_cache{$user,$sid};
4217 # password_crypt(password, salt)
4218 # If the salt looks like MD5 and we have a library for it, perform MD5 hashing
4219 # of a password. Otherwise, do Unix crypt.
4222 local ($pass, $salt) = @_;
4223 if ($salt =~ /^\$1\$/ && $use_md5) {
4224 return &encrypt_md5($pass, $salt);
4227 return &unix_crypt($pass, $salt);
4231 # unix_crypt(password, salt)
4232 # Performs standard Unix hashing for a password
4235 local ($pass, $salt) = @_;
4236 if ($use_perl_crypt) {
4237 return Crypt::UnixCrypt::crypt($pass, $salt);
4240 return crypt($pass, $salt);
4244 # handle_dav_request(davpath)
4245 # Pass a request on to the Net::DAV::Server module
4246 sub handle_dav_request
4249 eval "use Filesys::Virtual::Plain";
4250 eval "use Net::DAV::Server";
4251 eval "use HTTP::Request";
4252 eval "use HTTP::Headers";
4254 if ($Net::DAV::Server::VERSION eq '1.28' && $config{'dav_nolock'}) {
4255 delete $Net::DAV::Server::implemented{lock};
4256 delete $Net::DAV::Server::implemented{unlock};
4259 # Read in request data
4260 if (!$posted_data) {
4261 local $clen = $header{"content-length"};
4262 while(length($posted_data) < $clen) {
4263 $buf = &read_data($clen - length($posted_data));
4264 if (!length($buf)) {
4265 &http_error(500, "Failed to read POST request");
4267 chomp($posted_data);
4268 #$posted_data =~ s/\015$//mg;
4269 $posted_data .= $buf;
4273 # For subsequent logging
4274 open(MINISERVLOG, ">>$config{'logfile'}");
4278 local @u = getpwnam($authuser);
4279 if ($config{'dav_remoteuser'} && !$< && $validated) {
4282 $( = $u[3]; $) = "$u[3] $u[3]";
4283 ($>, $<) = ($u[2], $u[2]);
4285 if ($config{'dav_root'} eq '*') {
4290 &http_error(500, "Unix user $authuser does not exist");
4294 $root ||= $config{'dav_root'};
4297 # Check if this user can use DAV
4299 &users_match(\@u, @davusers) ||
4300 &http_error(500, "You are not allowed to access DAV");
4304 my $filesys = Filesys::Virtual::Plain->new({root_path => $root});
4305 my $webdav = Net::DAV::Server->new();
4306 $webdav->filesys($filesys);
4308 # Make up a request object, and feed to DAV
4309 local $ho = HTTP::Headers->new;
4310 foreach my $h (keys %header) {
4311 next if (lc($h) eq "connection");
4312 $ho->header($h => $header{$h});
4315 $request_uri =~ s/^\Q$path\E//;
4316 $request_uri = "/" if ($request_uri eq "");
4318 my $request = HTTP::Request->new($method, $request_uri, $ho,
4320 if ($config{'dav_debug'}) {
4321 print STDERR "DAV request :\n";
4322 print STDERR "---------------------------------------------\n";
4323 print STDERR $request->as_string();
4324 print STDERR "---------------------------------------------\n";
4326 my $response = $webdav->run($request);
4328 # Send back the reply
4329 &write_data("HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n");
4330 local $content = $response->content();
4332 $content =~ s|href>/(.+)<|href>$path/$1<|g;
4333 $content =~ s|href>/<|href>$path<|g;
4335 foreach my $h ($response->header_field_names) {
4336 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4337 &write_data("$h: ",$response->header($h),"\r\n");
4339 &write_data("Content-length: ",length($content),"\r\n");
4340 local $rv = &write_keep_alive(0);
4341 &write_data("\r\n");
4342 &write_data($content);
4344 if ($config{'dav_debug'}) {
4345 print STDERR "DAV reply :\n";
4346 print STDERR "---------------------------------------------\n";
4347 print STDERR "HTTP/1.1 ",$response->code()," ",$response->message(),"\r\n";
4348 foreach my $h ($response->header_field_names) {
4349 next if (lc($h) eq "connection" || lc($h) eq "content-length");
4350 print STDERR "$h: ",$response->header($h),"\r\n";
4352 print STDERR "Content-length: ",length($content),"\r\n";
4353 print STDERR "\r\n";
4354 print STDERR $content;
4355 print STDERR "---------------------------------------------\n";
4359 &log_request($acpthost, $authuser, $reqline, $response->code(),
4360 length($response->content()));
4363 # get_system_hostname()
4364 # Returns the hostname of this system, for reporting to listeners
4365 sub get_system_hostname
4367 # On Windows, try computername environment variable
4368 return $ENV{'computername'} if ($ENV{'computername'});
4369 return $ENV{'COMPUTERNAME'} if ($ENV{'COMPUTERNAME'});
4371 # If a specific command is set, use it first
4372 if ($config{'hostname_command'}) {
4373 local $out = `($config{'hostname_command'}) 2>&1`;
4380 # First try the hostname command
4381 local $out = `hostname 2>&1`;
4382 if (!$? && $out =~ /\S/) {
4387 # Try the Sys::Hostname module
4388 eval "use Sys::Hostname";
4390 local $rv = eval "hostname()";
4396 # Must use net name on Windows
4397 local $out = `net name 2>&1`;
4398 if ($out =~ /\-+\r?\n(\S+)/) {
4405 # indexof(string, array)
4406 # Returns the index of some value in an array, or -1
4409 for($i=1; $i <= $#_; $i++) {
4410 if ($_[$i] eq $_[0]) { return $i - 1; }
4416 # has_command(command)
4417 # Returns the full path if some command is in the path, undef if not
4421 if (!$_[0]) { return undef; }
4422 if (exists($has_command_cache{$_[0]})) {
4423 return $has_command_cache{$_[0]};
4426 if ($_[0] =~ /^\//) {
4427 $rv = -x $_[0] ? $_[0] : undef;
4430 local $sp = $on_windows ? ';' : ':';
4431 foreach $d (split($sp, $ENV{PATH})) {
4432 if (-x "$d/$_[0]") {
4437 foreach my $sfx (".exe", ".com", ".bat") {
4438 if (-r "$d/$_[0]".$sfx) {
4439 $rv = "$d/$_[0]".$sfx;
4446 $has_command_cache{$_[0]} = $rv;
4450 # check_sudo_permissions(user, pass)
4451 # Returns 1 if some user can run any command via sudo
4452 sub check_sudo_permissions
4454 local ($user, $pass) = @_;
4456 # First try the pipes
4458 print DEBUG "check_sudo_permissions: querying cache for $user\n";
4459 print $PASSINw "readsudo $user\n";
4460 local $can = <$PASSOUTr>;
4462 print DEBUG "check_sudo_permissions: cache said $can\n";
4463 if ($can =~ /^\d+$/ && $can != 2) {
4468 local $ptyfh = new IO::Pty;
4469 print DEBUG "check_sudo_permissions: ptyfh=$ptyfh\n";
4471 print STDERR "Failed to create new PTY with IO::Pty\n";
4474 local @uinfo = getpwnam($user);
4476 print STDERR "Unix user $user does not exist for sudo\n";
4480 # Execute sudo in a sub-process, via a pty
4481 local $ttyfh = $ptyfh->slave();
4482 print DEBUG "check_sudo_permissions: ttyfh=$ttyfh\n";
4483 local $tty = $ptyfh->ttyname();
4484 print DEBUG "check_sudo_permissions: tty=$tty\n";
4485 chown($uinfo[2], $uinfo[3], $tty);
4487 print DEBUG "check_sudo_permissions: about to fork..\n";
4488 local $pid = fork();
4489 print DEBUG "check_sudo_permissions: fork=$pid pid=$$\n";
4491 print STDERR "fork for sudo failed : $!\n";
4496 $ptyfh->make_slave_controlling_terminal();
4497 close(STDIN); close(STDOUT); close(STDERR);
4498 untie(*STDIN); untie(*STDOUT); untie(*STDERR);
4499 close($PASSINw); close($PASSOUTr);
4500 $( = $uinfo[3]; $) = "$uinfo[3] $uinfo[3]";
4501 ($>, $<) = ($uinfo[2], $uinfo[2]);
4506 open(STDIN, "<&SUDOr");
4507 open(STDOUT, ">$tty");
4508 open(STDERR, ">&STDOUT");
4511 print "Exec failed : $!\n";
4514 print DEBUG "check_sudo_permissions: pid=$pid\n";
4516 $ptyfh->close_slave();
4518 # Send password, and get back response
4519 local $oldfh = select(SUDOw);
4522 print DEBUG "check_sudo_permissions: about to send pass\n";
4523 local $SIG{'PIPE'} = 'ignore'; # Sometimes sudo doesn't ask for a password
4524 print SUDOw $pass,"\n";
4525 print DEBUG "check_sudo_permissions: sent pass=$pass\n";
4529 print DEBUG "check_sudo_permissions: got $_";
4535 local ($ok) = ($out =~ /\(ALL\)\s+ALL/ ? 1 : 0);
4539 print $PASSINw "writesudo $user $ok\n";
4545 # is_mobile_useragent(agent)
4546 # Returns 1 if some user agent looks like a cellphone or other mobile device,
4548 sub is_mobile_useragent
4550 local ($agent) = @_;
4552 "UP.Link", # Openwave
4553 "Nokia", # All Nokias start with Nokia
4554 "MOT-", # All Motorola phones start with MOT-
4555 "SAMSUNG", # Samsung browsers
4556 "Samsung", # Samsung browsers
4557 "SEC-", # Samsung browsers
4558 "AU-MIC", # Samsung browsers
4559 "AUDIOVOX", # Audiovox
4560 "BlackBerry", # BlackBerry
4561 "hiptop", # Danger hiptop Sidekick
4562 "SonyEricsson", # Sony Ericsson
4563 "Ericsson", # Old Ericsson browsers , mostly WAP
4564 "Mitsu/1.1.A", # Mitsubishi phones
4565 "Panasonic WAP", # Panasonic old WAP phones
4566 "DoCoMo", # DoCoMo phones
4567 "Lynx", # Lynx text-mode linux browser
4568 "Links", # Another text-mode linux browser
4570 local @substrings = (
4571 "UP.Browser", # Openwave
4572 "MobilePhone", # NetFront
4573 "AU-MIC-A700", # Samsung A700 Obigo browsers
4574 "Danger hiptop", # Danger Sidekick hiptop
4575 "Windows CE", # Windows CE Pocket PC
4576 "IEMobile", # Windows mobile browser
4577 "Blazer", # Palm Treo Blazer
4578 "BlackBerry", # BlackBerries can emulate other browsers, but
4579 # they still keep this string in the UserAgent
4580 "SymbianOS", # New Series60 browser has safari in it and
4581 # SymbianOS is the only distinguishing string
4582 "iPhone", # Apple iPhone KHTML browser
4583 "iPod", # iPod touch browser
4584 "MobileSafari", # HTTP client in iPhone
4586 "Opera Mini", # Opera Mini
4587 "HTC_P3700", # HTC mobile device
4589 foreach my $p (@prefixes) {
4590 return 1 if ($agent =~ /^\Q$p\E/);
4592 foreach my $s (@substrings, @mobile_agents) {
4593 return 1 if ($agent =~ /\Q$s\E/);
4598 # write_blocked_file()
4599 # Writes out a text file of blocked hosts and users
4600 sub write_blocked_file
4602 open(BLOCKED, ">$config{'blockedfile'}");
4603 foreach my $d (grep { $hostfail{$_} } @deny) {
4604 print BLOCKED "host $d $hostfail{$d} $blockhosttime{$d}\n";
4606 foreach my $d (grep { $userfail{$_} } @denyusers) {
4607 print BLOCKED "user $d $userfail{$d} $blockusertime{$d}\n";
4610 chmod(0700, $config{'blockedfile'});
4615 open(PIDFILE, ">$config{'pidfile'}");
4616 printf PIDFILE "%d\n", getpid();
4620 # lock_user_password(user)
4621 # Updates a user's password file entry to lock it, both in memory and on disk.
4622 # Returns 1 if done, -1 if no such user, 0 if already locked
4623 sub lock_user_password
4626 if ($users{$user}) {
4627 if ($users{$user} !~ /^\!/) {
4629 $users{$user} = "!".$users{$user};
4630 open(USERS, $config{'userfile'});
4631 local @ufile = <USERS>;
4633 foreach my $u (@ufile) {
4634 local @uinfo = split(/:/, $u);
4635 if ($uinfo[0] eq $user) {
4636 $uinfo[1] = $users{$user};
4638 $u = join(":", @uinfo);
4640 open(USERS, ">$config{'userfile'}");
4650 # hash_session_id(sid)
4651 # Returns an MD5 or Unix-crypted session ID
4655 if (!$hash_session_id_cache{$sid}) {
4658 $hash_session_id_cache{$sid} = &encrypt_md5($sid);
4662 $hash_session_id_cache{$sid} = &unix_crypt($sid, "XX");
4665 return $hash_session_id_cache{$sid};
4668 # encrypt_md5(string, [salt])
4669 # Returns a string encrypted in MD5 format
4672 local ($passwd, $salt) = @_;
4673 local $magic = '$1$';
4674 if ($salt =~ /^\$1\$([^\$]+)/) {
4675 # Extract actual salt from already encrypted password
4680 local $ctx = eval "new $use_md5";
4687 # Add some more stuff from the hash of the password and salt
4688 local $ctx1 = eval "new $use_md5";
4689 $ctx1->add($passwd);
4693 $ctx1->add($passwd);
4694 local $final = $ctx1->digest();
4695 for($pl=length($passwd); $pl>0; $pl-=16) {
4696 $ctx->add($pl > 16 ? $final : substr($final, 0, $pl));
4699 # This piece of code seems rather pointless, but it's in the C code that
4700 # does MD5 in PAM so it has to go in!
4703 for($i=length($passwd); $i; $i >>= 1) {
4708 $ctx->add(substr($passwd, $j, 1));
4711 $final = $ctx->digest();
4714 # This loop exists only to waste time
4715 for($i=0; $i<1000; $i++) {
4716 $ctx1 = eval "new $use_md5";
4717 $ctx1->add($i & 1 ? $passwd : $final);
4718 $ctx1->add($salt) if ($i % 3);
4719 $ctx1->add($passwd) if ($i % 7);
4720 $ctx1->add($i & 1 ? $final : $passwd);
4721 $final = $ctx1->digest();
4725 # Convert the 16-byte final string into a readable form
4727 local @final = map { ord($_) } split(//, $final);
4728 $l = ($final[ 0]<<16) + ($final[ 6]<<8) + $final[12];
4729 $rv .= &to64($l, 4);
4730 $l = ($final[ 1]<<16) + ($final[ 7]<<8) + $final[13];
4731 $rv .= &to64($l, 4);
4732 $l = ($final[ 2]<<16) + ($final[ 8]<<8) + $final[14];
4733 $rv .= &to64($l, 4);
4734 $l = ($final[ 3]<<16) + ($final[ 9]<<8) + $final[15];
4735 $rv .= &to64($l, 4);
4736 $l = ($final[ 4]<<16) + ($final[10]<<8) + $final[ 5];
4737 $rv .= &to64($l, 4);
4739 $rv .= &to64($l, 2);
4741 # Add salt if needed
4743 return $magic.$salt.'$'.$rv;
4752 local ($v, $n) = @_;
4755 $r .= $itoa64[$v & 0x3f];