File:  [LON-CAPA] / loncom / Attic / lcuseradd
Revision 1.35: download - view: text, annotated - select for diffs
Thu Jan 27 11:52:46 2005 UTC (19 years, 4 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
use File::Find::find to recurse the public_html dir ensuring that all
subdirs get 02770 mode.
(defect 3853)

    1: #!/usr/bin/perl
    2: 
    3: # The Learning Online Network with CAPA
    4: #
    5: # lcuseradd - LON-CAPA setuid script to coordinate all actions
    6: #             with adding a user with filesystem privileges (e.g. author)
    7: #
    8: #
    9: # $Id: lcuseradd,v 1.35 2005/01/27 11:52:46 foxr Exp $
   10: ###
   11: 
   12: ###############################################################################
   13: ##                                                                           ##
   14: ## ORGANIZATION OF THIS PERL SCRIPT                                          ##
   15: ##                                                                           ##
   16: ## 1. Description of script                                                  ##
   17: ## 2. Invoking script (standard input)                                       ##
   18: ## 3. Example usage inside another piece of code                             ##
   19: ## 4. Description of functions                                               ##
   20: ## 5. Exit codes                                                             ##
   21: ## 6. Initializations                                                        ##
   22: ## 7. Make sure this process is running from user=www                        ##
   23: ## 8. Start running script with www permissions                              ##
   24: ## 9. Handle case of another lcpasswd process (locking)                      ##
   25: ## 10. Error-check input, need 3 values (user name, password 1, password 2)  ##
   26: ## 11. Start running script with root permissions                            ##
   27: ## 12. Add user and make www a member of the user-specific group             ##
   28: ## 13. Set password                                                          ##
   29: ## 14. Make final modifications to the user directory                        ##
   30: ## 15. Exit script (unlock)                                                  ##
   31: ##                                                                           ##
   32: ###############################################################################
   33: 
   34: use strict;
   35: use File::Find;
   36: 
   37: 
   38: # ------------------------------------------------------- Description of script
   39: #
   40: # This script is a setuid script that should
   41: # be run by user 'www'.  It creates a /home/USERNAME directory.
   42: # It adds a user to the unix system.
   43: # Passwords are set with lcpasswd.
   44: # www becomes a member of this user group.
   45: 
   46: # -------------- Invoking script (standard input versus command-line arguments)
   47: #                Otherwise sensitive information will be available to ps-ers for
   48: #                a small but exploitable time window.
   49: #
   50: # Standard input (STDIN) usage
   51: # First line is USERNAME
   52: # Second line is PASSWORD
   53: # Third line is PASSWORD
   54: # Fouth line is the name of a file to which an error code will be written.
   55: #            If the fourth line is omitted, no error file will be written.
   56: #            In either case, the program Exits with the code as its Exit status.
   57: #            The error file will just be a single line containing an
   58: #            error code.
   59: #            
   60: #  
   61: #
   62: # Command-line arguments [USERNAME] [PASSWORD] [PASSWORD]
   63: # Yes, but be very careful here (don't pass shell commands)
   64: # and this is only supported to allow perl-system calls.
   65: #
   66: # Valid passwords must consist of the
   67: # ascii characters within the inclusive
   68: # range of 0x20 (32) to 0x7E (126).
   69: # These characters are:
   70: # SPACE and
   71: # !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO
   72: # PQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
   73: #
   74: # Valid user names must consist of ascii
   75: # characters that are alphabetical characters
   76: # (A-Z,a-z), numeric (0-9), or the underscore
   77: # mark (_). (Essentially, the perl regex \w).
   78: # User names must begin with an alphabetical character
   79: # (A-Z,a-z).
   80: 
   81: # ---------------------------------- Example usage inside another piece of code
   82: # Usage within code
   83: #
   84: # $Exitcode=
   85: #      system("/home/httpd/perl/lcuseradd","NAME","PASSWORD1","PASSWORD2")/256;
   86: # print "uh-oh" if $Exitcode;
   87: 
   88: # ---------------------------------------------------- Description of functions
   89: # enable_root_capability() : have setuid script run as root
   90: # disable_root_capability() : have setuid script run as www
   91: # try_to_lock() : make sure that another lcpasswd process isn't running
   92: 
   93: # ------------------------------------------------------------------ Exit codes
   94: # These are the Exit codes.
   95: # ( (0,"ok"),
   96: # (1,"User ID mismatch.  This program must be run as user 'www'"),
   97: # (2,"Error. This program needs 3 command-line arguments (username, ".
   98: #    "password 1, password 2)."),
   99: # (3,"Error. Three lines should be entered into standard input."),
  100: # (4,"Error. Too many other simultaneous password change requests being ".
  101: #    "made."),
  102: # (5,"Error. User $username does not exist."),
  103: # (6,"Error. Could not make www a member of the group \"$safeusername\"."),
  104: # (7,"Error. Root was not successfully enabled.),
  105: # (8,"Error. Cannot set password."),
  106: # (9,"Error. The user name specified has invalid characters."),
  107: # (10,"Error. A password entry had an invalid character."),
  108: # (11,"Error. User already exists.),
  109: # (12,"Error. Something went wrong with the addition of user ".
  110: #     "\"$safeusername\"."),
  111: # (13,"Error. Password mismatch."),
  112: # (14, "Error filename is invalid")
  113: 
  114: # ------------------------------------------------------------- Initializations
  115: # Security
  116: $ENV{'PATH'}='/bin/:/usr/bin:/usr/local/sbin:/home/httpd/perl'; # Nullify path
  117:                                                                 # information
  118: delete @ENV{qw(IFS CDPATH ENV BASH_ENV)}; # nullify potential taints
  119: 
  120: # Do not print error messages.
  121: my $noprint=1;
  122: 
  123: #  Error file:
  124: 
  125: my $error_file;			# This is either the error file name or undef.
  126: 
  127: print "In lcuseradd\n" unless $noprint;
  128: 
  129: # ----------------------------- Make sure this process is running from user=www
  130: my $wwwid=getpwnam('www');
  131: &disable_root_capability;
  132: if ($wwwid!=$>) {
  133:     print("User ID mismatch.  This program must be run as user 'www'\n")
  134: 	unless $noprint;
  135:     &Exit(1);
  136: }
  137: 
  138: # ----------------------------------- Start running script with www permissions
  139: &disable_root_capability;
  140: 
  141: # --------------------------- Handle case of another lcpasswd process (locking)
  142: unless (&try_to_lock("/tmp/lock_lcpasswd")) {
  143:     print "Error. Too many other simultaneous password change requests being ".
  144: 	"made.\n" unless $noprint;
  145:     &Exit(4);
  146: }
  147: 
  148: # ------- Error-check input, need 3 values (user name, password 1, password 2).
  149: my @input;
  150: if (@ARGV>=3) {
  151:     @input=@ARGV;
  152: } elsif (@ARGV) {
  153:     print("Error. This program needs at least 3 command-line arguments (username, ".
  154: 	  "password 1, password 2 [errorfile]).\n") unless $noprint;
  155:     unlink('/tmp/lock_lcpasswd');
  156:     &Exit(2);
  157: } else {
  158:     @input=<>;
  159:     if (@input < 3) {
  160: 	print("Error. At least three lines should be entered into standard input.\n")
  161: 	    unless $noprint;
  162: 	unlink('/tmp/lock_lcpasswd');
  163: 	&Exit(3);
  164:     }
  165:     foreach (@input) {chomp;}
  166: }
  167: 
  168: my ($username,$password1,$password2, $error_file)=@input;
  169: print "Username = ".$username."\n" unless $noprint;
  170: $username=~/^(\w+)$/;
  171: print "Username after substitution - ".$username unless $noprint;
  172: my $safeusername=$1;
  173: print "Safe username = $safeusername \n" unless $noprint;
  174: 
  175: if (($username ne $safeusername) or ($safeusername!~/^[A-Za-z]/)) {
  176:     print "Error. The user name specified $username $safeusername  has invalid characters.\n"
  177: 	unless $noprint;
  178:     unlink('/tmp/lock_lcpasswd');
  179:     &Exit(9);
  180: }
  181: my $pbad=0;
  182: foreach (split(//,$password1)) {if ((ord($_)<32)||(ord($_)>126)){$pbad=1;}}
  183: foreach (split(//,$password2)) {if ((ord($_)<32)||(ord($_)>126)){$pbad=1;}}
  184: if ($pbad) {
  185:     print "Error. A password entry had an invalid character.\n" unless $noprint;
  186:     unlink('/tmp/lock_lcpasswd');
  187:     &Exit(10);
  188: }
  189: 
  190: #
  191: #   Safe the filename.  For our case, it must only have alpha, numeric, period
  192: #   and path sparators..
  193: #
  194: 
  195: print "Error file is $error_file \n" unless $noprint;
  196: 
  197: if($error_file) {
  198:     if($error_file =~ /^([(\w)(\d)\.\/]+)$/) {
  199: 	print "Error file matched pattern $error_file : $1\n" unless $noprint;
  200: 	my $safe_error_file = $1;	# Untainted I think.
  201: 	print "Error file after transform $safe_error_file\n"
  202: 	    unless $noprint;
  203: 	if($error_file == $safe_error_file) {
  204: 	    $error_file = $safe_error_file; # untainted error_file.
  205: 	} else {
  206: 	    $error_file ="";
  207: 	    print "Invalid error filename\n" unless $noprint;
  208: 	    Exit(14);
  209: 	}
  210: 
  211:     } else {
  212: 	$error_file="";
  213: 	print "Invalid error filename\n" unless $noprint;
  214: 	Exit(14);
  215:     }
  216: }
  217: 
  218: 
  219: # -- Only add the user if they are >not< in /etc/passwd.
  220: #    Used to look for the ability to create a new directory for the
  221: #    user, however that disallows authentication changes from i
  222: #    internal->fs.. so just check the passwd file instead.
  223: #
  224: my $not_found = system("cut -d: -f1 /etc/passwd | grep -q \"^$safeusername\$\" ");
  225: if (!$not_found) {
  226:     print "Error user already exists\n" unless $noprint;
  227:     unlink('/tmp/lock_lcpasswd');
  228:     &Exit(11);
  229: }
  230: 
  231: 
  232: 
  233: # -- Only add user if the two password arguments match.
  234: 
  235: if ($password1 ne $password2) {
  236:     print "Error. Password mismatch.\n" unless $noprint;
  237:     unlink('/tmp/lock_lcpasswd');
  238:     &Exit(13);
  239: }
  240: print "enabling root\n" unless $noprint;
  241: # ---------------------------------- Start running script with root permissions
  242: &enable_root_capability;
  243: 
  244: # ------------------- Add user and make www a member of the user-specific group
  245: # -- Add user
  246: 
  247: print "adding user: $safeusername \n" unless $noprint;
  248: my $status = system('/usr/sbin/useradd','-c','LON-CAPA user',$safeusername);
  249: if ($status) {
  250:     print "Error.  Something went wrong with the addition of user ".
  251: 	  "\"$safeusername\".\n" unless $noprint;
  252:     print "Final status of useradd = $status";
  253:     unlink('/tmp/lock_lcpasswd');
  254:     &Exit(12);
  255: }
  256: print "Done adding user\n" unless $noprint;
  257: # Make www a member of that user group.
  258: my $groups=`/usr/bin/groups www` or &Exit(6);
  259: # untaint
  260: my ($safegroups)=($groups=~/:\s*([\s\w]+)/);
  261: $groups=$safegroups;
  262: chomp $groups; $groups=~s/^\S+\s+\:\s+//;
  263: my @grouplist=split(/\s+/,$groups);
  264: my @ugrouplist=grep {!/www|$safeusername/} @grouplist;
  265: my $gl=join(',',(@ugrouplist,$safeusername));
  266: print "Putting user in its own group\n" unless $noprint;
  267: if (system('/usr/sbin/usermod','-G',$gl,'www')) {
  268:     print "Error. Could not make www a member of the group ".
  269: 	  "\"$safeusername\".\n" unless $noprint;
  270:     unlink('/tmp/lock_lcpasswd');
  271:     &Exit(6);
  272: }
  273: 
  274: # ---------------------------------------------------------------- Set password
  275: # Set password with lcpasswd (which creates smbpasswd entry).
  276: 
  277: unlink('/tmp/lock_lcpasswd');
  278: &disable_root_capability;
  279: ($>,$<)=($wwwid,$wwwid);
  280: print "Opening lcpasswd pipeline\n" unless $noprint;
  281: open OUT,"|/home/httpd/perl/lcpasswd";
  282: print OUT $safeusername;
  283: print OUT "\n";
  284: print OUT $password1;
  285: print OUT "\n";
  286: print OUT $password1;
  287: print OUT "\n";
  288: close OUT;
  289: if ($?) {
  290:     print "abnormal Exit from close lcpasswd\n" unless $noprint;
  291:     &Exit(8);
  292: }
  293: ($>,$<)=($wwwid,0);
  294: &enable_root_capability;
  295: 
  296: # -- Don't add public_html... that can be added either by the user
  297: #    or by lchtmldir when the user is granted an authorship role.
  298: 
  299: # ------------------------------ Make final modifications to the user directory
  300: # -- Add a public_html file with a stand-in index.html file
  301: 
  302:  system('/bin/chmod','-R','0660',"/home/$safeusername");
  303: system('/bin/chmod','0710',"/home/$safeusername");
  304: mkdir "/home/$safeusername/public_html",0755;
  305: open OUT,">/home/$safeusername/public_html/index.html";
  306: print OUT<<END;
  307: <html>
  308: <head>
  309: <title>$safeusername</title>
  310: </head>
  311: <body>
  312: <h1>Construction Space</h1>
  313: <h3>$safeusername</h3>
  314: </body>
  315: </html>
  316: END
  317: close OUT;
  318: 
  319: #
  320: #   In order to allow the loncapa daemons appropriate access
  321: #   to public_html, Top level and public_html directories should
  322: #   be owned by safeusername:safeusername as should the smaple index.html..
  323: print "lcuseradd ownership\n" unless $noprint;
  324: system('/bin/chown','-R',"$safeusername:$safeusername","/home/$safeusername"); # First set std ownership on everything.
  325: &set_public_html_permissions("/home/$safeusername/public_html");
  326: #  system('/bin/chown',"$safeusername:www","/home/$safeusername");	# Now adust top level...
  327: #  system('/bin/chown','-R',"$safeusername:www","/home/$safeusername/public_html"); # And web dir.
  328: # ---------------------------------------------------- Gracefull Apache Restart
  329: if (-e '/var/run/httpd.pid') {
  330:     print "lcuseradd Apache restart\n" unless $noprint;
  331:     open(PID,'/var/run/httpd.pid');
  332:     my $pid=<PID>;
  333:     close(PID);
  334:     my  $pid=~ /(\D+)/;
  335:     my $safepid = $1;
  336:     if ($pid) {
  337: 	system('kill','-USR1',"$safepid");
  338:     }
  339: }
  340: # -------------------------------------------------------- Exit script
  341: print "lcuseradd Exiting\n" unless $noprint;
  342: &disable_root_capability;
  343: &Exit(0);
  344: 
  345: # ---------------------------------------------- Have setuid script run as root
  346: sub enable_root_capability {
  347:     if ($wwwid==$>) {
  348: 	($<,$>)=($>,0);
  349: 	($(,$))=($),0);
  350:     } else {
  351: 	# root capability is already enabled
  352:     }
  353:     return $>;
  354: }
  355: 
  356: # ----------------------------------------------- Have setuid script run as www
  357: sub disable_root_capability {
  358:     if ($wwwid==$<) {
  359: 	($<,$>)=($>,$<);
  360: 	($(,$))=($),$();
  361:     } else {
  362: 	# root capability is already disabled
  363:     }
  364: }
  365: 
  366: # ----------------------- Make sure that another lcpasswd process isn't running
  367: sub try_to_lock {
  368:     my ($lockfile)=@_;
  369:     my $currentpid;
  370:     my $lastpid;
  371:     # Do not manipulate lock file as root
  372:     if ($>==0) {
  373: 	return 0;
  374:     }
  375:     # Try to generate lock file.
  376:     # Wait 3 seconds.  If same process id is in
  377:     # lock file, then assume lock file is stale, and
  378:     # go ahead.  If process id's fluctuate, try
  379:     # for a maximum of 10 times.
  380:     for (0..10) {
  381: 	if (-e $lockfile) {
  382: 	    open(LOCK,"<$lockfile");
  383: 	    $currentpid=<LOCK>;
  384: 	    close LOCK;
  385: 	    if ($currentpid==$lastpid) {
  386: 		last;
  387: 	    }
  388: 	    sleep 3;
  389: 	    $lastpid=$currentpid;
  390: 	} else {
  391: 	    last;
  392: 	}
  393: 	if ($_==10) {
  394: 	    return 0;
  395: 	}
  396:     }
  397:     open(LOCK,">$lockfile");
  398:     print LOCK $$;
  399:     close LOCK;
  400:     return 1;
  401: }
  402: #    Called by File::Find::find for each file examined.
  403: #
  404: #     Untaint the file and, if it is a directory,
  405: #     chmod it to 02770
  406: #
  407: sub set_permission {
  408:     $File::Find::name =~ /^(.*)$/;
  409:     my $safe_name = $1;		# Untainted filename...
  410:     
  411:     print "$safe_name" unless $noprint;
  412:     if(-d $safe_name) {
  413: 	print " - directory" unless $noprint;
  414: 	chmod(02770, $safe_name);
  415:     }
  416:     print "\n" unless $noprint;
  417: 
  418: }
  419: #
  420: #    Set up the correct permissions for all files in the 
  421: #    user's public htmldir. We just do a chmod -R 0660 ... for
  422: #    the ordinary files.  The we use File::Find
  423: #    to pop through the directory tree changing directories only
  424: #    to 02770:
  425: #
  426: sub set_public_html_permissions {
  427:     my ($topdir) = @_;
  428: 
  429:     #   Set the top level dir permissions (I'm not sure if find 
  430:     #   will enumerate it specifically), correctly and all
  431:     #   files and dirs to the 'ordinary' file permissions:
  432: 
  433:     system("chmod -R 0660 $topdir");
  434:     chmod(02770, $topdir);
  435: 
  436:     #  Now use find to locate all directories under $topdir
  437:     #  and set their modes to 02770...
  438:     #
  439:     print "Find file\n " unless $noprint;
  440:     File::Find::find({"untaint"         => 1,
  441: 		      "untaint_pattern" => qr(/^(.*)$/),
  442: 		      "untaint_skip"    => 1,
  443: 		      "no_chdir"         => 1,
  444: 		      "wanted"          => \&set_permission }, "$topdir");
  445: 
  446: 
  447: }
  448: 
  449: #-------------------------- Exit...
  450: #
  451: #   Write the file if the error_file is defined.  Regardless
  452: #   Exit with the status code.
  453: #
  454: sub Exit {
  455:     my ($code) = @_;		# Status code.
  456: 
  457:     print "Exiting with status $code error file is $error_file\n" unless $noprint;
  458:     if($error_file) {
  459: 	open(FH, ">$error_file");
  460: 	print FH  "$code\n";
  461: 	close(FH);
  462:     }
  463:     exit $code;
  464: }
  465: 
  466: =head1 NAME
  467: 
  468: lcuseradd - LON-CAPA setuid script to coordinate all actions
  469:             with adding a user with filesystem privileges (e.g. author)
  470: 
  471: =head1 DESCRIPTION
  472: 
  473: lcuseradd - LON-CAPA setuid script to coordinate all actions
  474:             with adding a user with filesystem privileges (e.g. author)
  475: 
  476: =head1 README
  477: 
  478: lcuseradd - LON-CAPA setuid script to coordinate all actions
  479:             with adding a user with filesystem privileges (e.g. author)
  480: 
  481: =head1 PREREQUISITES
  482: 
  483: =head1 COREQUISITES
  484: 
  485: =pod OSNAMES
  486: 
  487: linux
  488: 
  489: =pod SCRIPT CATEGORIES
  490: 
  491: LONCAPA/Administrative
  492: 
  493: =cut

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