File:  [LON-CAPA] / loncom / Attic / lcuseradd
Revision 1.27: download - view: text, annotated - select for diffs
Thu Aug 5 20:47:27 2004 UTC (19 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG#3238 was not properly handling taint

    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.27 2004/08/05 20:47:27 albertel 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: }
  151: elsif (@ARGV) {
  152:     print("Error. This program needs at least 3 command-line arguments (username, ".
  153: 	  "password 1, password 2 [errorfile]).\n") unless $noprint;
  154:     unlink('/tmp/lock_lcpasswd');
  155:     &Exit(2);
  156: }
  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:     } 
  212:     else {
  213: 	$error_file="";
  214: 	print "Invalid error filename\n" unless $noprint;
  215: 	Exit(14);
  216:     }
  217: }
  218: 
  219: 
  220: # -- Only add user if we can create a brand new home directory (/home/username)
  221: if (-e "/home/$safeusername") {
  222:     print "Error. User already exists.\n" unless $noprint;
  223:     unlink('/tmp/lock_lcpasswd');
  224:     &Exit(11);
  225: }
  226: 
  227: # -- Only add user if the two password arguments match.
  228: 
  229: if ($password1 ne $password2) {
  230:     print "Error. Password mismatch.\n" unless $noprint;
  231:     unlink('/tmp/lock_lcpasswd');
  232:     &Exit(13);
  233: }
  234: print "enabling root\n" unless $noprint;
  235: # ---------------------------------- Start running script with root permissions
  236: &enable_root_capability;
  237: 
  238: # ------------------- Add user and make www a member of the user-specific group
  239: # -- Add user
  240: 
  241: print "adding user: $safeusername \n" unless $noprint;
  242: my $status = system('/usr/sbin/useradd','-c','LON-CAPA user',$safeusername);
  243: if ($status) {
  244:     print "Error.  Something went wrong with the addition of user ".
  245: 	  "\"$safeusername\".\n" unless $noprint;
  246:     print "Final status of useradd = $status";
  247:     unlink('/tmp/lock_lcpasswd');
  248:     &Exit(12);
  249: }
  250: print "Done adding user\n" unless $noprint;
  251: # Make www a member of that user group.
  252: my $groups=`/usr/bin/groups www` or &Exit(6);
  253: # untaint
  254: my ($safegroups)=($groups=~/([\s\w]+)/);
  255: $groups=$safegroups;
  256: chomp $groups; $groups=~s/^\S+\s+\:\s+//;
  257: my @grouplist=split(/\s+/,$groups);
  258: my @ugrouplist=grep {!/www|$safeusername/} @grouplist;
  259: my $gl=join(',',(@ugrouplist,$safeusername));
  260: print "Putting user in its own group\n" unless $noprint;
  261: if (system('/usr/sbin/usermod','-G',$gl,'www')) {
  262:     print "Error. Could not make www a member of the group ".
  263: 	  "\"$safeusername\".\n" unless $noprint;
  264:     unlink('/tmp/lock_lcpasswd');
  265:     &Exit(6);
  266: }
  267: 
  268: # ---------------------------------------------------------------- Set password
  269: # Set password with lcpasswd (which creates smbpasswd entry).
  270: 
  271: unlink('/tmp/lock_lcpasswd');
  272: &disable_root_capability;
  273: ($>,$<)=($wwwid,$wwwid);
  274: print "Opening lcpasswd pipeline\n" unless $noprint;
  275: open OUT,"|/home/httpd/perl/lcpasswd";
  276: print OUT $safeusername;
  277: print OUT "\n";
  278: print OUT $password1;
  279: print OUT "\n";
  280: print OUT $password1;
  281: print OUT "\n";
  282: close OUT;
  283: if ($?) {
  284:     print "abnormal Exit from close lcpasswd\n" unless $noprint;
  285:     &Exit(8);
  286: }
  287: ($>,$<)=($wwwid,0);
  288: &enable_root_capability;
  289: 
  290: # -- Don't add public_html... that can be added either by the user
  291: #    or by lchtmldir when the user is granted an authorship role.
  292: 
  293: # ------------------------------ Make final modifications to the user directory
  294: # -- Add a public_html file with a stand-in index.html file
  295: 
  296:  system('/bin/chmod','-R','0660',"/home/$safeusername");
  297: system('/bin/chmod','0710',"/home/$safeusername");
  298: mkdir "/home/$safeusername/public_html",0755;
  299: system('/bin/chmod','02770',"/home/$safeusername/public_html");
  300: open OUT,">/home/$safeusername/public_html/index.html";
  301: print OUT<<END;
  302: <html>
  303: <head>
  304: <title>$safeusername</title>
  305: </head>
  306: <body>
  307: <h1>Construction Space</h1>
  308: <h3>$safeusername</h3>
  309: </body>
  310: </html>
  311: END
  312: close OUT;
  313: 
  314: print "lcuseradd ownership\n" unless $noprint;
  315: system('/bin/chown','-R',"$safeusername:$safeusername","/home/$safeusername");
  316: # ---------------------------------------------------- Gracefull Apache Restart
  317: if (-e '/var/run/httpd.pid') {
  318:     print "lcuseradd Apache restart\n" unless $noprint;
  319:     open(PID,'/var/run/httpd.pid');
  320:     my $pid=<PID>;
  321:     close(PID);
  322:     my ($safepid)=($pid=~s/(\D+)//g);
  323:     if ($pid) {
  324: 	system('kill','-USR1',"$safepid");
  325:     }
  326: }
  327: # -------------------------------------------------------- Exit script
  328: print "lcuseradd Exiting\n" unless $noprint;
  329: &disable_root_capability;
  330: &Exit(0);
  331: 
  332: # ---------------------------------------------- Have setuid script run as root
  333: sub enable_root_capability {
  334:     if ($wwwid==$>) {
  335: 	($<,$>)=($>,0);
  336: 	($(,$))=($),0);
  337:     }
  338:     else {
  339: 	# root capability is already enabled
  340:     }
  341:     return $>;
  342: }
  343: 
  344: # ----------------------------------------------- Have setuid script run as www
  345: sub disable_root_capability {
  346:     if ($wwwid==$<) {
  347: 	($<,$>)=($>,$<);
  348: 	($(,$))=($),$();
  349:     }
  350:     else {
  351: 	# root capability is already disabled
  352:     }
  353: }
  354: 
  355: # ----------------------- Make sure that another lcpasswd process isn't running
  356: sub try_to_lock {
  357:     my ($lockfile)=@_;
  358:     my $currentpid;
  359:     my $lastpid;
  360:     # Do not manipulate lock file as root
  361:     if ($>==0) {
  362: 	return 0;
  363:     }
  364:     # Try to generate lock file.
  365:     # Wait 3 seconds.  If same process id is in
  366:     # lock file, then assume lock file is stale, and
  367:     # go ahead.  If process id's fluctuate, try
  368:     # for a maximum of 10 times.
  369:     for (0..10) {
  370: 	if (-e $lockfile) {
  371: 	    open(LOCK,"<$lockfile");
  372: 	    $currentpid=<LOCK>;
  373: 	    close LOCK;
  374: 	    if ($currentpid==$lastpid) {
  375: 		last;
  376: 	    }
  377: 	    sleep 3;
  378: 	    $lastpid=$currentpid;
  379: 	}
  380: 	else {
  381: 	    last;
  382: 	}
  383: 	if ($_==10) {
  384: 	    return 0;
  385: 	}
  386:     }
  387:     open(LOCK,">$lockfile");
  388:     print LOCK $$;
  389:     close LOCK;
  390:     return 1;
  391: }
  392: #-------------------------- Exit...
  393: #
  394: #   Write the file if the error_file is defined.  Regardless
  395: #   Exit with the status code.
  396: #
  397: sub Exit {
  398:     my ($code) = @_;		# Status code.
  399: 
  400:     print "Exiting with status $code error file is $error_file\n" unless $noprint;
  401:     if($error_file) {
  402: 	open(FH, ">$error_file");
  403: 	print FH  "$code\n";
  404: 	close(FH);
  405:     }
  406:     exit $code;
  407: }
  408: 
  409: =head1 NAME
  410: 
  411: lcuseradd - LON-CAPA setuid script to coordinate all actions
  412:             with adding a user with filesystem privileges (e.g. author)
  413: 
  414: =head1 DESCRIPTION
  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 README
  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 PREREQUISITES
  425: 
  426: =head1 COREQUISITES
  427: 
  428: =pod OSNAMES
  429: 
  430: linux
  431: 
  432: =pod SCRIPT CATEGORIES
  433: 
  434: LONCAPA/Administrative
  435: 
  436: =cut

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