File:  [LON-CAPA] / loncom / Attic / lcuseradd
Revision 1.26: download - view: text, annotated - select for diffs
Thu Aug 5 10:56:55 2004 UTC (19 years, 10 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Add capability (optional for compatibilty with existing code)
to write the error code to a file passed in to lcuseradd. NOte
that the file must be in a directory that is writable by www
I recommend /tmp -- and that the reader of that file unlink it.

This is my way to get around the fact that runing lcuseradd on a pipe
prevents you from getting the exit status of the program, which in turn
prevents the loncapa UI from knowing that adding a user has actually failed!

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

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