Annotation of loncom/lchtmldir, revision 1.19

1.7       albertel    1: #!/usr/bin/perl
1.1       foxr        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
1.17      foxr       44: #
1.1       foxr       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: #
1.17      foxr       64: #
1.1       foxr       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; 
1.10      foxr       70: use Fcntl qw(:mode);
                     71: use DirHandle;
1.12      foxr       72: use POSIX;
1.18      raeburn    73: use lib '/home/httpd/lib/perl/';
                     74: use LONCAPA qw(:match);
1.1       foxr       75: 
                     76: $ENV{'PATH'} = '/bin:/usr/bin:/usr/local/sbin:/home/httpd/perl';
                     77: delete @ENV{qw{IFS CDPATH ENV BASH_ENV}};
                     78: 
1.12      foxr       79: my $DEBUG = 1;                         # .nonzero -> Debug printing enabled.
1.10      foxr       80: my $path_sep = "/";		# Unix like operating systems.
1.1       foxr       81: 
                     82: 
                     83: # If the UID of the running process is not www exit with error.
                     84: 
                     85: if ($DEBUG) {
                     86:     print("Checking uid...\n");
                     87: }
                     88: my $wwwid = getpwnam('www');
                     89: &DisableRoot;
                     90: if($wwwid != $>) {
                     91:     if ($DEBUG) {
                     92: 	print("User ID incorrect.  This program must be run as user 'www'\n");
                     93:     }
                     94:     exit 1;			# Exit with error status.
                     95: }
                     96: 
                     97: # There must be three 'command line' parameters.  The first
                     98: # is the home directory of the user.
                     99: # The second is the name of the user.  This is only referenced
                    100: # in code branches dealing with unix mode authentication.
                    101: # The last is the authentication mode which must be one of unix, internal
                    102: # krb4 or localauth.
                    103: #   If there is an error in the argument count or countents, we exit with an
                    104: # error.
                    105: 
                    106: if ($DEBUG) {
                    107:     print("Checking parameters: \n");
                    108: }
                    109: if(@ARGV != 3) {
                    110:     if($DEBUG) {
                    111: 	print("Error: lchtmldir need 3 parameters \n");
                    112:     }
                    113:     exit 2;
                    114: }
                    115: my ($dir,$username,$authentication) = @ARGV;
                    116: 
                    117: if($DEBUG) {
                    118:     print ("Directory = $dir \n");
                    119:     print ("User      = $username \n");
                    120:     print ("Authmode  = $authentication \n");
                    121: 
                    122: }
                    123: 
1.2       foxr      124: if( $authentication ne "unix:"     &&
                    125:     $authentication ne "internal:" &&
1.4       matthew   126:     $authentication !~ /^krb(4|5):(.*)/ &&
1.2       foxr      127:     $authentication ne "localauth:") {
1.1       foxr      128:     if($DEBUG) {
                    129: 	print("Invalid authentication parameter: ".$authentication."\n");
                    130: 	print("Should be one of: unix, internal, krb4, localauth\n");
                    131:     }
                    132:     exit 3;
                    133: }
                    134: 
                    135: # Untaint the username.
                    136: 
1.18      raeburn   137: my $match = $username =~ /^($match_username)$/;
1.1       foxr      138: my $patt  = $1;
                    139:  
                    140: if($DEBUG) {
                    141:    print("Username word match flag = ".$match."\n");
                    142:     print("Match value = ".$patt."\n");
                    143: }
                    144: 
                    145: my $safeuser = $patt;
                    146: if($DEBUG) {
                    147:     print("Save username = $safeuser \n");
                    148: }
1.18      raeburn   149: if($username ne $safeuser) {
1.1       foxr      150:     if($DEBUG) {
                    151: 	print("User name $username had illegal characters\n");
                    152:     }
                    153:     exit 4;
                    154: }
                    155: 
                    156: #untaint the base directory require that the dir contain only 
                    157: # alphas, / numbers or underscores, and end in /$safeuser
                    158: 
                    159: 
                    160: 
1.19    ! albertel  161: my ($allowed_dir) = ($dir =~ m{(^([/]|$match_username)+)});
1.1       foxr      162: 
1.19    ! albertel  163: my $has_correct_end = ($dir =~ m{/\Q$safeuser\E$});
        !           164: 
        !           165: if(($allowed_dir ne $dir) or (!$has_correct_end)) {
1.1       foxr      166:     if ($DEBUG) {
                    167: 	print("Directory $dir is not a valid home for $safeuser\n");
                    168:     }
                    169:     exit 5;
                    170: }
                    171: 
                    172: # As root, create the directory.
                    173: 
1.19    ! albertel  174: my $homedir = $allowed_dir;
1.9       foxr      175: my $fulldir = $homedir."/public_html";
                    176: 
1.1       foxr      177: if($DEBUG) {
                    178:     print("Full directory path is: $fulldir \n");
                    179: }
1.19    ! albertel  180: if(!( -e $homedir)) {
1.1       foxr      181:     if($DEBUG) {
1.19    ! albertel  182: 	print("User's home directory $homedir does not exist\n");
1.1       foxr      183:     }
1.4       matthew   184:     if ($authentication eq "unix:") {
                    185:         exit 6;
                    186:     }
1.1       foxr      187: }
1.16      albertel  188: if ($authentication eq "unix:") {
                    189:     # check whether group $safeuser exists.
                    190:     my $usergroups = `id -nG $safeuser`;
                    191:     if (! grep /^$safeuser$/, split(/\s+/,$usergroups)) { 
                    192:         if($DEBUG) {
                    193:             print("Group \"$safeuser\" does not exist or $safeuser is not a member of that group.\n");
                    194:         }
                    195:         exit 7;
                    196:     }
                    197: }
                    198: 
1.17      foxr      199: 
                    200: 
1.1       foxr      201: &EnableRoot;
                    202: 
1.17      foxr      203: #  If authentication is internal and the top level directory exists
                    204: #  give it the right permissions (in case this is a modification.
                    205: 
                    206: if ($authentication eq "internal:") {
                    207:     chmod(0711, $homedir);	# so www can enter ~/public_html.
                    208: }
                    209: 
1.3       foxr      210: &System("/bin/mkdir -p $fulldir")   unless (-e $fulldir);
1.1       foxr      211:     unless(-e $fulldir."/index.html") {
                    212: 	open OUT,">".$fulldir."/index.html";
                    213: 	print OUT<<END;
                    214: 	<html>
                    215: 	<head>
                    216: 	<title>$safeuser</title>
                    217:         </head>
1.5       www       218:         <body bgcolor="#ccffdd">
                    219:         <h1>$safeuser Construction Space</h1>
                    220:           <h2>
                    221:             The Learning<i>Online</i> Network with Computer-Assisted Personalized Approach
                    222:           </h2>
1.1       foxr      223:           <p>
1.5       www       224: This is your construction space within LON-CAPA, where you would construct resources which are meant to be
                    225: used across courses and institutions.
1.1       foxr      226:           </p>
                    227:           <p>
1.5       www       228: Material within this area can only be seen and edited by $safeuser and designated co-authors. To make
                    229: it available to students and other instructors, the material needs to be published.
1.1       foxr      230:           </p>
                    231:         </body>
                    232:        </html>
                    233: END
                    234:     close OUT;
                    235:     }
1.9       foxr      236: 
1.13      foxr      237: &System("/bin/chmod  02770  $fulldir");
                    238: &System("/bin/chmod  0770  $fulldir"."/index.html");
1.1       foxr      239: 
                    240: 
                    241: # Based on the authentiation mode, set the ownership of the directory.
                    242: 
1.2       foxr      243: if($authentication eq "unix:") {	# Unix mode authentication...
1.15      foxr      244:     print "Unix auth\n";
1.14      foxr      245:     &System("/bin/chown -R   $safeuser:$safeuser"." ".$fulldir);
1.6       albertel  246:     &JoinGroup($safeuser);
1.4       matthew   247: } else {
                    248:     # Internal, Kerberos, and Local authentication are for users
                    249:     # who do not have unix accounts on the system.  Therefore we
                    250:     # will give ownership of their public_html directories to www:www
1.9       foxr      251:     # If the user is an internal auth user, the rest of the directory tree
                    252:     # gets owned by root.  This chown is needed in case what's really happening
                    253:     # is that a file system user is being demoted to internal user...
                    254: 
                    255:     if($authentication eq "internal:") {
1.11      foxr      256: 	#  In case the user was a unix/filesystem authenticated user,
                    257: 	#  we'll take a bit of time here to write  a script in the
                    258: 	#  user's home directory that can reset ownerships and permissions
                    259: 	#  back the way the used to be.
                    260: 
1.12      foxr      261: 	# This can take long enough for lond to time out, so we'll do it
                    262: 	# in a separate process that we'll not wait for.
                    263: 	#
                    264: 	my $fpid = fork;
                    265: 	if($fpid) {
                    266: 	    &DisableRoot;
                    267: 	    exit 0;
                    268: 	} else {
                    269: 	    print "Forked\n";
                    270: 	    POSIX::setsid();	# Disassociate from parent.
                    271: 	    print "Separate session\n";
                    272: 	    &write_restore_script($homedir);
                    273: 	    print "Restore script written\n";
                    274: 	    &System("/bin/chown -R root:root ".$homedir);
                    275: 	    &System("/bin/chown -R www:www  ".$fulldir);
                    276: 	    print "Exiting\n";
                    277: 	    exit 0;
                    278: 	}
                    279:     } else {
                    280: 	&System("/bin/chown -R www:www  ".$fulldir);
                    281:     }
1.11      foxr      282: 
1.1       foxr      283: }
                    284: &DisableRoot;
                    285: 
                    286: exit 0;
                    287: 
                    288: #----------------------------------------------------------------------
                    289: #
                    290: #  Local utility procedures.
                    291: #  These include:
                    292: #     EnableRoot - Start running as root.
                    293: #     DisableRoot- Stop running as root.
                    294: #     JoinGroup  - Join www to the specified group.
                    295: 
                    296: # Turn on as root:
                    297: 
                    298: sub EnableRoot {
                    299:     if ($wwwid==$>) {
                    300: 	($<,$>)=($>,$<);
                    301: 	($(,$))=($),$();
                    302:     }
                    303:     else {
                    304: 	# root capability is already enabled
                    305:     }
                    306:     if($DEBUG) {
1.4       matthew   307: 	print("Enable Root - id =  $> $<\n");
1.1       foxr      308:     }
                    309:     return $>;  
                    310: }
                    311: 
                    312: sub DisableRoot {
                    313:     if ($wwwid==$<) {
                    314: 	($<,$>)=($>,$<);
                    315: 	($(,$))=($),$();
                    316:     }
                    317:     else {
                    318: 	# root capability is already disabled
                    319:     }
                    320:     if($DEBUG) {
                    321: 	print("Disable root: id = ".$>."\n");
                    322:     }
                    323: }
1.15      foxr      324: #
                    325: #  Join the www user to the user's group.
                    326: #  we must be running with euid as root at this time.
                    327: #
1.1       foxr      328: sub JoinGroup {
                    329:     my $usergroup = shift;
                    330: 
                    331:     my $groups = `/usr/bin/groups www`;
1.6       albertel  332:     # untaint
1.8       albertel  333:     my ($safegroups)=($groups=~/:\s+([\s\w]+)/);
1.6       albertel  334:     $groups=$safegroups;
1.1       foxr      335:     chomp $groups; $groups=~s/^\S+\s+\:\s+//;
                    336:     my @grouplist=split(/\s+/,$groups);
                    337:     my @ugrouplist=grep {!/www|$usergroup/} @grouplist;
                    338:     my $gl=join(',',(@ugrouplist,$usergroup));
                    339:     if (&System('/usr/sbin/usermod','-G',$gl,'www')) {
                    340: 	if($DEBUG) {
                    341: 	    print "Error. Could not make www a member of the group ".
                    342: 		"\"$usergroup\".\n";
                    343: 	}
                    344: 	exit 6;
                    345:     }
1.15      foxr      346:     if (-e '/var/run/httpd.pid') {
                    347: 	open(PID,'/var/run/httpd.pid');
                    348: 	my $pid=<PID>;
                    349: 	close(PID);
                    350: 	my ($safepid) = $pid=~ /(\d+)/;
                    351: 	$pid = $safepid;
                    352: 	if ($pid) {
                    353: 	    my $status = system("kill -USR1 $safepid");
                    354: 	}
                    355:     }
1.1       foxr      356: }
                    357: 
                    358: 
                    359: 
                    360: sub System {
1.6       albertel  361:     my ($command,@args) = @_;
1.1       foxr      362:     if($DEBUG) {
1.6       albertel  363: 	print("system: $command with args ".join(' ',@args)."\n");
1.1       foxr      364:     }
1.6       albertel  365:     system($command,@args);
1.1       foxr      366: }
                    367: 
                    368: 
                    369: 
                    370: 
1.10      foxr      371: 
                    372: #
                    373: #   This file contains code to recursively process
                    374: #   a Directory.  This is a bit more powerful
                    375: #   than File::Find in that we pass the full
                    376: #   stat info to the processing function.
                    377: #     For each file in the specified directory subtree, 
                    378: #   The user's Code reference is invoked for all files, regular and otherwise
                    379: #   except:
                    380: #      ., ..
                    381: #
                    382: #  Parameters:
                    383: #     code_ref    - Code reference, invoked for each file in the tree.
                    384: #                   as follows:  CodeRef(directory, name, statinfo)
                    385: #                   directory the path to the directory holding the file.
                    386: #                   name      the name of the file within Directory.
                    387: #                   statinfo  a reference to the stat of the file.
                    388: #     start_dir   - The starting point of the directory walk.
                    389: #
                    390: # NOTE:
                    391: #   Yes, we could have just used File::Find, but since we have to get the
                    392: #   stat anyway, this is actually simpler, as File::Find would have gotten
                    393: #   the stat to figure out the file type and then we would have gotten it
                    394: #   again.
                    395: #
                    396: 
                    397: sub process_tree {
                    398:     my ($code_ref, $start_dir)  = @_;
                    399: 
                    400:     my $dir = new DirHandle $start_dir; 
                    401:     if (!defined($dir)) {
                    402:         print "Failed to  open dirhandle: $start_dir\n";
                    403:     }
                    404: 
                    405:     # Now iterate through this level of the tree:
                    406: 
                    407:     while (defined (my $name = $dir->read)) {
                    408: 	next if $name =~/^\.\.?$/;       # Skip ., .. (see cookbook pg 319)
                    409: 	
                    410: 	my $full_name   = $start_dir.$path_sep.$name; # Full filename path.
                    411: 	my @stat_info  = lstat($full_name);
                    412: 	my $mode       = $stat_info[2];
                    413: 	my $type       = $mode & 0170000; #  File type.
                    414: 
                    415: 	# Unless the file type is a symlink, call the user code:
                    416: 
                    417: 	unless ($type == S_IFLNK) {
                    418: 	    &$code_ref($start_dir, $name, \@stat_info);
                    419: 	}
                    420: 
                    421: 	# If the entry is a directory, we need to recurse:
                    422: 
                    423: 
                    424: 	if (($type ==  S_IFDIR) != 0) {
                    425: 	    &process_tree($code_ref, $full_name);
                    426: 	}
                    427:     }
                    428: 
                    429: }
                    430: #
1.11      foxr      431: #   Callback from process_tree to write the script lines
                    432: #   requried to restore files to current ownership and permission.
                    433: # Parameters:
                    434: #    dir         - Name of the directory the file lives in.
                    435: #    name        - Name of the file itself.
                    436: #    statinfo    - Array from lstat called on the file.
                    437: #
1.10      foxr      438: #
                    439: sub write_script {
                    440:     my ($dir, $name, $statinfo) = @_;
                    441: 
                    442:     my $fullname = $dir.$path_sep.$name;
                    443: 
                    444:     #  We're going to '' the name, but we need to deal with embedded
                    445:     #  ' characters.  Using " is much worse as we'd then have to
                    446:     #  escape all the shell escapes too.  This way all we need
                    447:     #  to do is replace ' with '\''
                    448: 
                    449:     $fullname =~ s/\'/\'\\\'\'/g;
                    450: 
                    451:     my $perms    = $statinfo->[2] & 0777; # Just permissions.
                    452:     printf CHMODSCRIPT "chmod 0%o '%s'\n", $perms, $fullname;
                    453:     printf CHMODSCRIPT "chown %d:%d '%s'\n", $statinfo->[4], $statinfo->[5], 
                    454:                                          $fullname
                    455: 
                    456: 
                    457: }
1.11      foxr      458: # 
                    459: #    Write a script in the user's home directory that can restore
                    460: #    the permissions and ownerhips of all the files in the directory
                    461: #    tree to their current ownerships and permissions.  This is done
                    462: #    prior to making the user into an internally authenticated user
                    463: #    in case they were previously file system authenticated and
                    464: #    need to go back.
                    465: #      The file we will create will be of the form
                    466: #        restore_n.sh  Where n is a number that we will keep
                    467: #   incrementing as needed until there isn't a file by that name.
                    468: #   
                    469: # Parameters:
                    470: #    dir      - Path to the user's home directory.
                    471: #
                    472: sub write_restore_script {
                    473:     my ($dir)   = @_;
                    474: 
                    475:     #   Create a unique file:
                    476: 
                    477:     my $version_number     = 0;
                    478:     my $filename           = 'restore_'.$version_number.'.sh';
                    479:     my $full_name           = $dir.$path_sep.$filename;
                    480: 
                    481:     while(-e $full_name) {
                    482: 	$version_number++;
                    483: 	$filename         = 'restore_'.$version_number.'.sh';
                    484: 	$full_name        = $dir.$path_sep.$filename;
                    485:     }
                    486:     # $full_name is the full path of a file that does not yet exist
                    487:     # of the form we want:
                    488: 
                    489:     open(CHMODSCRIPT, "> $full_name");
                    490: 
                    491:     &process_tree(\&write_script, $dir);
                    492: 
                    493:     close(CHMODSCRIPT);
                    494: 
                    495:     chmod(0750, $full_name);
                    496: 
                    497: }
1.10      foxr      498: 
                    499: 
                    500: 
                    501: 

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