File:  [LON-CAPA] / loncom / Attic / lchtmldir
Revision 1.15: download - view: text, annotated - select for diffs
Wed Jan 26 12:13:58 2005 UTC (19 years, 3 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Fix some safing issues with the pid for httpd that prevented the
kill -USR1 from being sent to the right pid.

Ensure that lond invokes lchtmldir for authors that switch both in and
out of filesystem auth mode.

    1: #!/usr/bin/perl
    2: 
    3: # The Learning Online Network with CAPA
    4: #
    5: # Copyright Michigan State University Board of Trustees
    6: #
    7: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    8: #
    9: # LON-CAPA is free software; you can redistribute it and/or modify
   10: # it under the terms of the GNU General Public License as published by
   11: # the Free Software Foundation; either version 2 of the License, or
   12: # (at your option) any later version.
   13: #
   14: # LON-CAPA is distributed in the hope that it will be useful,
   15: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   16: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   17: # GNU General Public License for more details.
   18: #
   19: # You should have received a copy of the GNU General Public License
   20: # along with LON-CAPA; if not, write to the Free Software
   21: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   22: #
   23: # /home/httpd/html/adm/gpl.txt
   24: #
   25: # http://www.lon-capa.org/
   26: #
   27: #  lchtmldir - LONC-CAPA setuid script to:
   28: #              o If necessary, add a public_html directory 
   29: #                to the specified user home directory.
   30: #              o Set the permissions according to the authentication type.
   31: #
   32: #  Motivations:
   33: #     Originally, account creation would create a public_html
   34: #     directory for unix authorized people only.  It is possible to have
   35: #     Kerberos, internal and locally authorized 'users' which may be authors
   36: #     and hence need a properly owned an protected public_html directory
   37: #     to serve as their construction space.
   38: #
   39: #  Author:
   40: #    Ron Fox
   41: #    NSCL
   42: #    Michigan State University8
   43: #    East Lansing, MI 48824-1321
   44: 
   45: #   General flow of control:
   46: #   1. Validate process state (must be run as www).
   47: #   2. Validate parameters:  Need two parameters:
   48: #         o Homedir  - Home diretory of user 
   49: #         o Username - Name of the user.
   50: #         o AuthMode - Authentication mode, can be:
   51: #                      - unix
   52: #                      - internal
   53: #                      - krb4
   54: #                      - localauth
   55: #  3. Untaint the usename and home directory
   56: #
   57: #  4. As root if necessary, create $Homedir/public_html
   58: #  5. Set ownership/permissions according to authentication mode (AuthMode)
   59: #       - unix - ~owner:www/2775
   60: #       - krb4 - ~owner:www/2775
   61: #       - internal - www:www/2775
   62: #       - local    - www:www/2775
   63: #
   64: 
   65: #
   66: #   Take a few precautions to be sure that we're not vulnerable to trojan
   67: #   horses and other fine issues:
   68: #
   69: use strict; 
   70: use Fcntl qw(:mode);
   71: use DirHandle;
   72: use POSIX;
   73: 
   74: $ENV{'PATH'} = '/bin:/usr/bin:/usr/local/sbin:/home/httpd/perl';
   75: delete @ENV{qw{IFS CDPATH ENV BASH_ENV}};
   76: 
   77: my $DEBUG = 1;                         # .nonzero -> Debug printing enabled.
   78: my $path_sep = "/";		# Unix like operating systems.
   79: 
   80: 
   81: # If the UID of the running process is not www exit with error.
   82: 
   83: if ($DEBUG) {
   84:     print("Checking uid...\n");
   85: }
   86: my $wwwid = getpwnam('www');
   87: &DisableRoot;
   88: if($wwwid != $>) {
   89:     if ($DEBUG) {
   90: 	print("User ID incorrect.  This program must be run as user 'www'\n");
   91:     }
   92:     exit 1;			# Exit with error status.
   93: }
   94: 
   95: # There must be three 'command line' parameters.  The first
   96: # is the home directory of the user.
   97: # The second is the name of the user.  This is only referenced
   98: # in code branches dealing with unix mode authentication.
   99: # The last is the authentication mode which must be one of unix, internal
  100: # krb4 or localauth.
  101: #   If there is an error in the argument count or countents, we exit with an
  102: # error.
  103: 
  104: if ($DEBUG) {
  105:     print("Checking parameters: \n");
  106: }
  107: if(@ARGV != 3) {
  108:     if($DEBUG) {
  109: 	print("Error: lchtmldir need 3 parameters \n");
  110:     }
  111:     exit 2;
  112: }
  113: my ($dir,$username,$authentication) = @ARGV;
  114: 
  115: if($DEBUG) {
  116:     print ("Directory = $dir \n");
  117:     print ("User      = $username \n");
  118:     print ("Authmode  = $authentication \n");
  119: 
  120: }
  121: 
  122: if( $authentication ne "unix:"     &&
  123:     $authentication ne "internal:" &&
  124:     $authentication !~ /^krb(4|5):(.*)/ &&
  125:     $authentication ne "localauth:") {
  126:     if($DEBUG) {
  127: 	print("Invalid authentication parameter: ".$authentication."\n");
  128: 	print("Should be one of: unix, internal, krb4, localauth\n");
  129:     }
  130:     exit 3;
  131: }
  132: 
  133: # Untaint the username.
  134: 
  135: my $match = $username =~ /^(\w+)$/;
  136: my $patt  = $1;
  137:  
  138: if($DEBUG) {
  139:    print("Username word match flag = ".$match."\n");
  140:     print("Match value = ".$patt."\n");
  141: }
  142: 
  143: my $safeuser = $patt;
  144: if($DEBUG) {
  145:     print("Save username = $safeuser \n");
  146: }
  147: if(($username ne $safeuser) or ($safeuser!~/^[A-za-z]/)) {
  148:     if($DEBUG) {
  149: 	print("User name $username had illegal characters\n");
  150:     }
  151:     exit 4;
  152: }
  153: 
  154: #untaint the base directory require that the dir contain only 
  155: # alphas, / numbers or underscores, and end in /$safeuser
  156: 
  157: $dir =~ /(^([\w\/]+))/;
  158: 
  159: my $dirtry1 = $1;
  160: 
  161: $dir =~ /$\/$safeuser/;
  162: my $dirtry2 = $1;
  163: 
  164: if(($dirtry1 ne $dir) or ($dirtry2 ne $dir)) {
  165:     if ($DEBUG) {
  166: 	print("Directory $dir is not a valid home for $safeuser\n");
  167:     }
  168:     exit 5;
  169: }
  170: 
  171: 
  172: # As root, create the directory.
  173: 
  174: my $homedir = $dirtry1;
  175: my $fulldir = $homedir."/public_html";
  176: 
  177: if($DEBUG) {
  178:     print("Full directory path is: $fulldir \n");
  179: }
  180: if(!( -e $dirtry1)) {
  181:     if($DEBUG) {
  182: 	print("User's home directory $dirtry1 does not exist\n");
  183:     }
  184:     if ($authentication eq "unix:") {
  185:         exit 6;
  186:     }
  187: }
  188: &EnableRoot;
  189: 
  190: &System("/bin/mkdir -p $fulldir")   unless (-e $fulldir);
  191:     unless(-e $fulldir."/index.html") {
  192: 	open OUT,">".$fulldir."/index.html";
  193: 	print OUT<<END;
  194: 	<html>
  195: 	<head>
  196: 	<title>$safeuser</title>
  197:         </head>
  198:         <body bgcolor="#ccffdd">
  199:         <h1>$safeuser Construction Space</h1>
  200:           <h2>
  201:             The Learning<i>Online</i> Network with Computer-Assisted Personalized Approach
  202:           </h2>
  203:           <p>
  204: This is your construction space within LON-CAPA, where you would construct resources which are meant to be
  205: used across courses and institutions.
  206:           </p>
  207:           <p>
  208: Material within this area can only be seen and edited by $safeuser and designated co-authors. To make
  209: it available to students and other instructors, the material needs to be published.
  210:           </p>
  211:         </body>
  212:        </html>
  213: END
  214:     close OUT;
  215:     }
  216: 
  217: &System("/bin/chmod  02770  $fulldir");
  218: &System("/bin/chmod  0770  $fulldir"."/index.html");
  219: 
  220: 
  221: # Based on the authentiation mode, set the ownership of the directory.
  222: 
  223: if($authentication eq "unix:") {	# Unix mode authentication...
  224:     print "Unix auth\n";
  225:     &System("/bin/chown -R   $safeuser:$safeuser"." ".$fulldir);
  226:     &JoinGroup($safeuser);
  227: } else {
  228:     # Internal, Kerberos, and Local authentication are for users
  229:     # who do not have unix accounts on the system.  Therefore we
  230:     # will give ownership of their public_html directories to www:www
  231:     # If the user is an internal auth user, the rest of the directory tree
  232:     # gets owned by root.  This chown is needed in case what's really happening
  233:     # is that a file system user is being demoted to internal user...
  234: 
  235:     if($authentication eq "internal:") {
  236: 	#  In case the user was a unix/filesystem authenticated user,
  237: 	#  we'll take a bit of time here to write  a script in the
  238: 	#  user's home directory that can reset ownerships and permissions
  239: 	#  back the way the used to be.
  240: 
  241: 	# This can take long enough for lond to time out, so we'll do it
  242: 	# in a separate process that we'll not wait for.
  243: 	#
  244: 	my $fpid = fork;
  245: 	if($fpid) {
  246: 	    &DisableRoot;
  247: 	    exit 0;
  248: 	} else {
  249: 	    print "Forked\n";
  250: 	    POSIX::setsid();	# Disassociate from parent.
  251: 	    print "Separate session\n";
  252: 	    &write_restore_script($homedir);
  253: 	    print "Restore script written\n";
  254: 	    &System("/bin/chown -R root:root ".$homedir);
  255: 	    &System("/bin/chown -R www:www  ".$fulldir);
  256: 	    print "Exiting\n";
  257: 	    exit 0;
  258: 	}
  259:     } else {
  260: 	&System("/bin/chown -R www:www  ".$fulldir);
  261:     }
  262: 
  263: }
  264: &DisableRoot;
  265: 
  266: exit 0;
  267: 
  268: #----------------------------------------------------------------------
  269: #
  270: #  Local utility procedures.
  271: #  These include:
  272: #     EnableRoot - Start running as root.
  273: #     DisableRoot- Stop running as root.
  274: #     JoinGroup  - Join www to the specified group.
  275: 
  276: # Turn on as root:
  277: 
  278: sub EnableRoot {
  279:     if ($wwwid==$>) {
  280: 	($<,$>)=($>,$<);
  281: 	($(,$))=($),$();
  282:     }
  283:     else {
  284: 	# root capability is already enabled
  285:     }
  286:     if($DEBUG) {
  287: 	print("Enable Root - id =  $> $<\n");
  288:     }
  289:     return $>;  
  290: }
  291: 
  292: sub DisableRoot {
  293:     if ($wwwid==$<) {
  294: 	($<,$>)=($>,$<);
  295: 	($(,$))=($),$();
  296:     }
  297:     else {
  298: 	# root capability is already disabled
  299:     }
  300:     if($DEBUG) {
  301: 	print("Disable root: id = ".$>."\n");
  302:     }
  303: }
  304: #
  305: #  Join the www user to the user's group.
  306: #  we must be running with euid as root at this time.
  307: #
  308: sub JoinGroup {
  309:     my $usergroup = shift;
  310: 
  311:     my $groups = `/usr/bin/groups www`;
  312:     # untaint
  313:     my ($safegroups)=($groups=~/:\s+([\s\w]+)/);
  314:     $groups=$safegroups;
  315:     chomp $groups; $groups=~s/^\S+\s+\:\s+//;
  316:     my @grouplist=split(/\s+/,$groups);
  317:     my @ugrouplist=grep {!/www|$usergroup/} @grouplist;
  318:     my $gl=join(',',(@ugrouplist,$usergroup));
  319:     if (&System('/usr/sbin/usermod','-G',$gl,'www')) {
  320: 	if($DEBUG) {
  321: 	    print "Error. Could not make www a member of the group ".
  322: 		"\"$usergroup\".\n";
  323: 	}
  324: 	exit 6;
  325:     }
  326:     if (-e '/var/run/httpd.pid') {
  327: 	open(PID,'/var/run/httpd.pid');
  328: 	my $pid=<PID>;
  329: 	close(PID);
  330: 	my ($safepid) = $pid=~ /(\d+)/;
  331: 	$pid = $safepid;
  332: 	if ($pid) {
  333: 	    my $status = system("kill -USR1 $safepid");
  334: 	}
  335:     }
  336: }
  337: 
  338: 
  339: 
  340: sub System {
  341:     my ($command,@args) = @_;
  342:     if($DEBUG) {
  343: 	print("system: $command with args ".join(' ',@args)."\n");
  344:     }
  345:     system($command,@args);
  346: }
  347: 
  348: 
  349: 
  350: 
  351: 
  352: #
  353: #   This file contains code to recursively process
  354: #   a Directory.  This is a bit more powerful
  355: #   than File::Find in that we pass the full
  356: #   stat info to the processing function.
  357: #     For each file in the specified directory subtree, 
  358: #   The user's Code reference is invoked for all files, regular and otherwise
  359: #   except:
  360: #      ., ..
  361: #
  362: #  Parameters:
  363: #     code_ref    - Code reference, invoked for each file in the tree.
  364: #                   as follows:  CodeRef(directory, name, statinfo)
  365: #                   directory the path to the directory holding the file.
  366: #                   name      the name of the file within Directory.
  367: #                   statinfo  a reference to the stat of the file.
  368: #     start_dir   - The starting point of the directory walk.
  369: #
  370: # NOTE:
  371: #   Yes, we could have just used File::Find, but since we have to get the
  372: #   stat anyway, this is actually simpler, as File::Find would have gotten
  373: #   the stat to figure out the file type and then we would have gotten it
  374: #   again.
  375: #
  376: 
  377: sub process_tree {
  378:     my ($code_ref, $start_dir)  = @_;
  379: 
  380:     my $dir = new DirHandle $start_dir; 
  381:     if (!defined($dir)) {
  382:         print "Failed to  open dirhandle: $start_dir\n";
  383:     }
  384: 
  385:     # Now iterate through this level of the tree:
  386: 
  387:     while (defined (my $name = $dir->read)) {
  388: 	next if $name =~/^\.\.?$/;       # Skip ., .. (see cookbook pg 319)
  389: 	
  390: 	my $full_name   = $start_dir.$path_sep.$name; # Full filename path.
  391: 	my @stat_info  = lstat($full_name);
  392: 	my $mode       = $stat_info[2];
  393: 	my $type       = $mode & 0170000; #  File type.
  394: 
  395: 	# Unless the file type is a symlink, call the user code:
  396: 
  397: 	unless ($type == S_IFLNK) {
  398: 	    &$code_ref($start_dir, $name, \@stat_info);
  399: 	}
  400: 
  401: 	# If the entry is a directory, we need to recurse:
  402: 
  403: 
  404: 	if (($type ==  S_IFDIR) != 0) {
  405: 	    &process_tree($code_ref, $full_name);
  406: 	}
  407:     }
  408: 
  409: }
  410: #
  411: #   Callback from process_tree to write the script lines
  412: #   requried to restore files to current ownership and permission.
  413: # Parameters:
  414: #    dir         - Name of the directory the file lives in.
  415: #    name        - Name of the file itself.
  416: #    statinfo    - Array from lstat called on the file.
  417: #
  418: #
  419: sub write_script {
  420:     my ($dir, $name, $statinfo) = @_;
  421: 
  422:     my $fullname = $dir.$path_sep.$name;
  423: 
  424:     #  We're going to '' the name, but we need to deal with embedded
  425:     #  ' characters.  Using " is much worse as we'd then have to
  426:     #  escape all the shell escapes too.  This way all we need
  427:     #  to do is replace ' with '\''
  428: 
  429:     $fullname =~ s/\'/\'\\\'\'/g;
  430: 
  431:     my $perms    = $statinfo->[2] & 0777; # Just permissions.
  432:     printf CHMODSCRIPT "chmod 0%o '%s'\n", $perms, $fullname;
  433:     printf CHMODSCRIPT "chown %d:%d '%s'\n", $statinfo->[4], $statinfo->[5], 
  434:                                          $fullname
  435: 
  436: 
  437: }
  438: # 
  439: #    Write a script in the user's home directory that can restore
  440: #    the permissions and ownerhips of all the files in the directory
  441: #    tree to their current ownerships and permissions.  This is done
  442: #    prior to making the user into an internally authenticated user
  443: #    in case they were previously file system authenticated and
  444: #    need to go back.
  445: #      The file we will create will be of the form
  446: #        restore_n.sh  Where n is a number that we will keep
  447: #   incrementing as needed until there isn't a file by that name.
  448: #   
  449: # Parameters:
  450: #    dir      - Path to the user's home directory.
  451: #
  452: sub write_restore_script {
  453:     my ($dir)   = @_;
  454: 
  455:     #   Create a unique file:
  456: 
  457:     my $version_number     = 0;
  458:     my $filename           = 'restore_'.$version_number.'.sh';
  459:     my $full_name           = $dir.$path_sep.$filename;
  460: 
  461:     while(-e $full_name) {
  462: 	$version_number++;
  463: 	$filename         = 'restore_'.$version_number.'.sh';
  464: 	$full_name        = $dir.$path_sep.$filename;
  465:     }
  466:     # $full_name is the full path of a file that does not yet exist
  467:     # of the form we want:
  468: 
  469:     open(CHMODSCRIPT, "> $full_name");
  470: 
  471:     &process_tree(\&write_script, $dir);
  472: 
  473:     close(CHMODSCRIPT);
  474: 
  475:     chmod(0750, $full_name);
  476: 
  477: }
  478: 
  479: 
  480: 
  481: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>