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

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