Annotation of loncom/lcuseradd, revision 1.43

1.1       harris41    1: #!/usr/bin/perl
1.16      harris41    2: 
                      3: # The Learning Online Network with CAPA
1.1       harris41    4: #
1.16      harris41    5: # lcuseradd - LON-CAPA setuid script to coordinate all actions
                      6: #             with adding a user with filesystem privileges (e.g. author)
1.1       harris41    7: #
1.16      harris41    8: #
1.43    ! raeburn     9: # $Id: lcuseradd,v 1.42 2011/10/24 21:30:09 www Exp $
1.16      harris41   10: ###
1.15      harris41   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: ###############################################################################
1.1       harris41   33: 
                     34: use strict;
1.35      foxr       35: use File::Find;
                     36: 
1.1       harris41   37: 
1.15      harris41   38: # ------------------------------------------------------- Description of script
                     39: #
1.1       harris41   40: # This script is a setuid script that should
1.20      foxr       41: # be run by user 'www'.  It creates a /home/USERNAME directory.
1.15      harris41   42: # It adds a user to the unix system.
1.2       harris41   43: # Passwords are set with lcpasswd.
                     44: # www becomes a member of this user group.
1.1       harris41   45: 
1.15      harris41   46: # -------------- Invoking script (standard input versus command-line arguments)
1.26      foxr       47: #                Otherwise sensitive information will be available to ps-ers for
                     48: #                a small but exploitable time window.
1.15      harris41   49: #
                     50: # Standard input (STDIN) usage
1.1       harris41   51: # First line is USERNAME
1.42      www        52: # Second line is DOMAIN
1.3       harris41   53: # Third line is PASSWORD
1.42      www        54: # Fourth line is PASSWORD
                     55: # Fifth line is the name of a file to which an error code will be written.
1.26      foxr       56: #            If the fourth line is omitted, no error file will be written.
                     57: #            In either case, the program Exits with the code as its Exit status.
                     58: #            The error file will just be a single line containing an
                     59: #            error code.
                     60: #            
                     61: #  
1.15      harris41   62: #
1.42      www        63: # Command-line arguments [USERNAME] [DOMAIN] [PASSWORD] [PASSWORD]
1.15      harris41   64: # Yes, but be very careful here (don't pass shell commands)
                     65: # and this is only supported to allow perl-system calls.
                     66: #
1.7       harris41   67: # Valid passwords must consist of the
                     68: # ascii characters within the inclusive
                     69: # range of 0x20 (32) to 0x7E (126).
                     70: # These characters are:
                     71: # SPACE and
                     72: # !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO
                     73: # PQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
1.15      harris41   74: #
1.7       harris41   75: # Valid user names must consist of ascii
                     76: # characters that are alphabetical characters
                     77: # (A-Z,a-z), numeric (0-9), or the underscore
                     78: # mark (_). (Essentially, the perl regex \w).
1.15      harris41   79: # User names must begin with an alphabetical character
                     80: # (A-Z,a-z).
1.7       harris41   81: 
1.15      harris41   82: # ---------------------------------- Example usage inside another piece of code
1.4       harris41   83: # Usage within code
                     84: #
1.26      foxr       85: # $Exitcode=
1.42      www        86: #      system("/home/httpd/perl/lcuseradd","NAME","DOMAIN","PASSWORD1","PASSWORD2")/256;
1.26      foxr       87: # print "uh-oh" if $Exitcode;
1.4       harris41   88: 
1.15      harris41   89: # ---------------------------------------------------- Description of functions
                     90: # enable_root_capability() : have setuid script run as root
                     91: # disable_root_capability() : have setuid script run as www
                     92: # try_to_lock() : make sure that another lcpasswd process isn't running
                     93: 
                     94: # ------------------------------------------------------------------ Exit codes
1.26      foxr       95: # These are the Exit codes.
1.13      harris41   96: # ( (0,"ok"),
                     97: # (1,"User ID mismatch.  This program must be run as user 'www'"),
1.15      harris41   98: # (2,"Error. This program needs 3 command-line arguments (username, ".
                     99: #    "password 1, password 2)."),
1.13      harris41  100: # (3,"Error. Three lines should be entered into standard input."),
1.15      harris41  101: # (4,"Error. Too many other simultaneous password change requests being ".
                    102: #    "made."),
1.13      harris41  103: # (5,"Error. User $username does not exist."),
                    104: # (6,"Error. Could not make www a member of the group \"$safeusername\"."),
                    105: # (7,"Error. Root was not successfully enabled.),
1.15      harris41  106: # (8,"Error. Cannot set password."),
1.13      harris41  107: # (9,"Error. The user name specified has invalid characters."),
                    108: # (10,"Error. A password entry had an invalid character."),
                    109: # (11,"Error. User already exists.),
1.15      harris41  110: # (12,"Error. Something went wrong with the addition of user ".
                    111: #     "\"$safeusername\"."),
1.13      harris41  112: # (13,"Error. Password mismatch."),
1.38      raeburn   113: # (14, "Error filename is invalid"),
                    114: # (15, "Error. Could not add home directory.")
1.4       harris41  115: 
1.15      harris41  116: # ------------------------------------------------------------- Initializations
1.1       harris41  117: # Security
1.15      harris41  118: $ENV{'PATH'}='/bin/:/usr/bin:/usr/local/sbin:/home/httpd/perl'; # Nullify path
                    119:                                                                 # information
1.16      harris41  120: delete @ENV{qw(IFS CDPATH ENV BASH_ENV)}; # nullify potential taints
1.2       harris41  121: 
1.15      harris41  122: # Do not print error messages.
                    123: my $noprint=1;
                    124: 
1.23      foxr      125: print "In lcuseradd\n" unless $noprint;
                    126: 
1.15      harris41  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;
1.26      foxr      133:     &Exit(1);
1.4       harris41  134: }
1.15      harris41  135: 
                    136: # ----------------------------------- Start running script with www permissions
1.4       harris41  137: &disable_root_capability;
                    138: 
1.15      harris41  139: # --------------------------- Handle case of another lcpasswd process (locking)
1.4       harris41  140: unless (&try_to_lock("/tmp/lock_lcpasswd")) {
1.15      harris41  141:     print "Error. Too many other simultaneous password change requests being ".
                    142: 	"made.\n" unless $noprint;
1.26      foxr      143:     &Exit(4);
1.4       harris41  144: }
                    145: 
1.15      harris41  146: # ------- Error-check input, need 3 values (user name, password 1, password 2).
1.4       harris41  147: my @input;
1.26      foxr      148: if (@ARGV>=3) {
1.4       harris41  149:     @input=@ARGV;
1.28      foxr      150: } elsif (@ARGV) {
1.26      foxr      151:     print("Error. This program needs at least 3 command-line arguments (username, ".
                    152: 	  "password 1, password 2 [errorfile]).\n") unless $noprint;
1.4       harris41  153:     unlink('/tmp/lock_lcpasswd');
1.26      foxr      154:     &Exit(2);
1.28      foxr      155: } else {
1.4       harris41  156:     @input=<>;
1.26      foxr      157:     if (@input < 3) {
                    158: 	print("Error. At least three lines should be entered into standard input.\n")
1.15      harris41  159: 	    unless $noprint;
1.4       harris41  160: 	unlink('/tmp/lock_lcpasswd');
1.26      foxr      161: 	&Exit(3);
1.4       harris41  162:     }
1.19      harris41  163:     foreach (@input) {chomp;}
1.4       harris41  164: }
                    165: 
1.42      www       166: my ($username,$domain,$password1,$password2, $error_file)=@input;
1.23      foxr      167: print "Username = ".$username."\n" unless $noprint;
1.4       harris41  168: $username=~/^(\w+)$/;
1.22      foxr      169: print "Username after substitution - ".$username unless $noprint;
1.4       harris41  170: my $safeusername=$1;
1.23      foxr      171: print "Safe username = $safeusername \n" unless $noprint;
1.22      foxr      172: 
1.42      www       173: print "Domain = ".$domain."\n" unless $noprint;
                    174: 
1.15      harris41  175: if (($username ne $safeusername) or ($safeusername!~/^[A-Za-z]/)) {
1.22      foxr      176:     print "Error. The user name specified $username $safeusername  has invalid characters.\n"
1.15      harris41  177: 	unless $noprint;
1.8       harris41  178:     unlink('/tmp/lock_lcpasswd');
1.26      foxr      179:     &Exit(9);
1.8       harris41  180: }
                    181: my $pbad=0;
1.19      harris41  182: foreach (split(//,$password1)) {if ((ord($_)<32)||(ord($_)>126)){$pbad=1;}}
                    183: foreach (split(//,$password2)) {if ((ord($_)<32)||(ord($_)>126)){$pbad=1;}}
1.8       harris41  184: if ($pbad) {
1.26      foxr      185:     print "Error. A password entry had an invalid character.\n" unless $noprint;
1.8       harris41  186:     unlink('/tmp/lock_lcpasswd');
1.26      foxr      187:     &Exit(10);
1.8       harris41  188: }
1.5       harris41  189: 
1.26      foxr      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: 
1.28      foxr      211:     } else {
1.26      foxr      212: 	$error_file="";
                    213: 	print "Invalid error filename\n" unless $noprint;
                    214: 	Exit(14);
                    215:     }
                    216: }
                    217: 
                    218: 
1.31      foxr      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: #
1.34      foxr      224: my $not_found = system("cut -d: -f1 /etc/passwd | grep -q \"^$safeusername\$\" ");
1.31      foxr      225: if (!$not_found) {
                    226:     print "Error user already exists\n" unless $noprint;
1.7       harris41  227:     unlink('/tmp/lock_lcpasswd');
1.26      foxr      228:     &Exit(11);
1.7       harris41  229: }
                    230: 
1.31      foxr      231: 
                    232: 
1.15      harris41  233: # -- Only add user if the two password arguments match.
1.23      foxr      234: 
1.5       harris41  235: if ($password1 ne $password2) {
1.6       harris41  236:     print "Error. Password mismatch.\n" unless $noprint;
1.5       harris41  237:     unlink('/tmp/lock_lcpasswd');
1.26      foxr      238:     &Exit(13);
1.5       harris41  239: }
1.23      foxr      240: print "enabling root\n" unless $noprint;
1.15      harris41  241: # ---------------------------------- Start running script with root permissions
1.4       harris41  242: &enable_root_capability;
                    243: 
1.38      raeburn   244: # ------------------- Add group and user, and make www a member of the group
                    245: # -- Add group
                    246: 
                    247: print "adding group: $safeusername \n" unless $noprint;
                    248: my $status = system('/usr/sbin/groupadd', $safeusername);
                    249: if ($status) {
                    250:     print "Error.  Something went wrong with the addition of group ".
                    251:           "\"$safeusername\".\n" unless $noprint;
                    252:     print "Final status of groupadd = $status\n";
                    253:     unlink('/tmp/lock_lcpasswd');
                    254:     &Exit(12);
                    255: }
                    256: my $gid = getgrnam($safeusername);
                    257:                                                                                 
1.15      harris41  258: # -- Add user
1.23      foxr      259: 
                    260: print "adding user: $safeusername \n" unless $noprint;
1.38      raeburn   261: my $status = system('/usr/sbin/useradd','-c','LON-CAPA user','-g',$gid,$safeusername);
1.23      foxr      262: if ($status) {
1.15      harris41  263:     print "Error.  Something went wrong with the addition of user ".
                    264: 	  "\"$safeusername\".\n" unless $noprint;
1.38      raeburn   265:     system("/usr/sbin/groupdel $safeusername");
1.37      foxr      266:     print "Final status of useradd = $status\n";
1.4       harris41  267:     unlink('/tmp/lock_lcpasswd');
1.26      foxr      268:     &Exit(12);
1.4       harris41  269: }
1.36      albertel  270: 
1.23      foxr      271: print "Done adding user\n" unless $noprint;
1.7       harris41  272: # Make www a member of that user group.
1.26      foxr      273: my $groups=`/usr/bin/groups www` or &Exit(6);
1.27      albertel  274: # untaint
1.29      albertel  275: my ($safegroups)=($groups=~/:\s*([\s\w]+)/);
1.27      albertel  276: $groups=$safegroups;
1.17      harris41  277: chomp $groups; $groups=~s/^\S+\s+\:\s+//;
                    278: my @grouplist=split(/\s+/,$groups);
                    279: my @ugrouplist=grep {!/www|$safeusername/} @grouplist;
                    280: my $gl=join(',',(@ugrouplist,$safeusername));
1.38      raeburn   281: print "Putting www in user's group\n" unless $noprint;
1.17      harris41  282: if (system('/usr/sbin/usermod','-G',$gl,'www')) {
1.15      harris41  283:     print "Error. Could not make www a member of the group ".
                    284: 	  "\"$safeusername\".\n" unless $noprint;
1.5       harris41  285:     unlink('/tmp/lock_lcpasswd');
1.26      foxr      286:     &Exit(6);
1.5       harris41  287: }
                    288: 
1.15      harris41  289: # ---------------------------------------------------------------- Set password
                    290: # Set password with lcpasswd (which creates smbpasswd entry).
1.2       harris41  291: 
1.15      harris41  292: unlink('/tmp/lock_lcpasswd');
                    293: &disable_root_capability;
1.16      harris41  294: ($>,$<)=($wwwid,$wwwid);
1.23      foxr      295: print "Opening lcpasswd pipeline\n" unless $noprint;
1.16      harris41  296: open OUT,"|/home/httpd/perl/lcpasswd";
1.15      harris41  297: print OUT $safeusername;
                    298: print OUT "\n";
                    299: print OUT $password1;
                    300: print OUT "\n";
                    301: print OUT $password1;
                    302: print OUT "\n";
                    303: close OUT;
                    304: if ($?) {
1.26      foxr      305:     print "abnormal Exit from close lcpasswd\n" unless $noprint;
                    306:     &Exit(8);
1.8       harris41  307: }
1.18      harris41  308: ($>,$<)=($wwwid,0);
1.15      harris41  309: &enable_root_capability;
1.8       harris41  310: 
1.38      raeburn   311: # Check if home directory exists for user
                    312: # If not, create one.
                    313: if (!-e "/home/$safeusername") {
                    314:     if (!mkdir("/home/$safeusername",0710)) {
                    315:         print "Error. Could not add home directory for ".
                    316:           "\"$safeusername\".\n" unless $noprint;
                    317:         unlink('/tmp/lock_lcpasswd');
                    318:         &Exit(15);
                    319:     }
                    320: }
1.20      foxr      321: 
1.24      www       322: # ---------------------------------------------------- Gracefull Apache Restart
1.40      raeburn   323: my $pidfile;
1.24      www       324: if (-e '/var/run/httpd.pid') {
1.40      raeburn   325:     $pidfile = '/var/run/httpd.pid';
                    326: } elsif (-e '/var/run/httpd2.pid') {   #Apache 2 on SuSE 10.1 and SLES10 
                    327:     $pidfile = '/var/run/httpd2.pid';
                    328: } 
                    329: 
                    330: if ($pidfile) {
1.24      www       331:     print "lcuseradd Apache restart\n" unless $noprint;
1.41      albertel  332:     open(PID,"<$pidfile");
1.24      www       333:     my $pid=<PID>;
                    334:     close(PID);
1.39      albertel  335:     $pid=~ /(\D+)/;
1.35      foxr      336:     my $safepid = $1;
1.24      www       337:     if ($pid) {
1.27      albertel  338: 	system('kill','-USR1',"$safepid");
1.24      www       339:     }
                    340: }
1.15      harris41  341: # -------------------------------------------------------- Exit script
1.26      foxr      342: print "lcuseradd Exiting\n" unless $noprint;
1.8       harris41  343: &disable_root_capability;
1.26      foxr      344: &Exit(0);
1.1       harris41  345: 
1.15      harris41  346: # ---------------------------------------------- Have setuid script run as root
1.5       harris41  347: sub enable_root_capability {
                    348:     if ($wwwid==$>) {
1.23      foxr      349: 	($<,$>)=($>,0);
                    350: 	($(,$))=($),0);
1.28      foxr      351:     } else {
1.5       harris41  352: 	# root capability is already enabled
                    353:     }
1.41      albertel  354:     if ($wwwid == $>) {
                    355: 	print("Failed to become root\n") unless $noprint;
                    356:     } else {
                    357: 	print("Became root\n") unless $noprint;
                    358:     }
1.5       harris41  359:     return $>;
                    360: }
                    361: 
1.15      harris41  362: # ----------------------------------------------- Have setuid script run as www
1.5       harris41  363: sub disable_root_capability {
                    364:     if ($wwwid==$<) {
                    365: 	($<,$>)=($>,$<);
                    366: 	($(,$))=($),$();
1.28      foxr      367:     } else {
1.5       harris41  368: 	# root capability is already disabled
                    369:     }
                    370: }
                    371: 
1.15      harris41  372: # ----------------------- Make sure that another lcpasswd process isn't running
1.5       harris41  373: sub try_to_lock {
                    374:     my ($lockfile)=@_;
                    375:     my $currentpid;
                    376:     my $lastpid;
                    377:     # Do not manipulate lock file as root
                    378:     if ($>==0) {
                    379: 	return 0;
                    380:     }
                    381:     # Try to generate lock file.
                    382:     # Wait 3 seconds.  If same process id is in
                    383:     # lock file, then assume lock file is stale, and
                    384:     # go ahead.  If process id's fluctuate, try
                    385:     # for a maximum of 10 times.
                    386:     for (0..10) {
                    387: 	if (-e $lockfile) {
                    388: 	    open(LOCK,"<$lockfile");
                    389: 	    $currentpid=<LOCK>;
                    390: 	    close LOCK;
                    391: 	    if ($currentpid==$lastpid) {
                    392: 		last;
                    393: 	    }
                    394: 	    sleep 3;
                    395: 	    $lastpid=$currentpid;
1.28      foxr      396: 	} else {
1.5       harris41  397: 	    last;
                    398: 	}
                    399: 	if ($_==10) {
                    400: 	    return 0;
                    401: 	}
                    402:     }
                    403:     open(LOCK,">$lockfile");
                    404:     print LOCK $$;
                    405:     close LOCK;
                    406:     return 1;
                    407: }
1.35      foxr      408: #    Called by File::Find::find for each file examined.
                    409: #
                    410: #     Untaint the file and, if it is a directory,
                    411: #     chmod it to 02770
                    412: #
                    413: sub set_permission {
                    414:     $File::Find::name =~ /^(.*)$/;
                    415:     my $safe_name = $1;		# Untainted filename...
                    416:     
                    417:     print "$safe_name" unless $noprint;
                    418:     if(-d $safe_name) {
                    419: 	print " - directory" unless $noprint;
                    420: 	chmod(02770, $safe_name);
                    421:     }
                    422:     print "\n" unless $noprint;
                    423: 
                    424: }
                    425: 
1.26      foxr      426: #-------------------------- Exit...
                    427: #
                    428: #   Write the file if the error_file is defined.  Regardless
                    429: #   Exit with the status code.
                    430: #
                    431: sub Exit {
                    432:     my ($code) = @_;		# Status code.
                    433: 
1.37      foxr      434:     # TODO: Ensure the error file is owned/deletable by www:www:
                    435: 
                    436:     &disable_root_capability();	# We run unprivileged to write the error file.
                    437: 
1.26      foxr      438:     print "Exiting with status $code error file is $error_file\n" unless $noprint;
                    439:     if($error_file) {
                    440: 	open(FH, ">$error_file");
                    441: 	print FH  "$code\n";
                    442: 	close(FH);
                    443:     }
                    444:     exit $code;
                    445: }
1.16      harris41  446: 
                    447: =head1 NAME
                    448: 
                    449: lcuseradd - LON-CAPA setuid script to coordinate all actions
                    450:             with adding a user with filesystem privileges (e.g. author)
                    451: 
                    452: =head1 DESCRIPTION
                    453: 
                    454: lcuseradd - LON-CAPA setuid script to coordinate all actions
                    455:             with adding a user with filesystem privileges (e.g. author)
                    456: 
                    457: =head1 README
                    458: 
                    459: lcuseradd - LON-CAPA setuid script to coordinate all actions
                    460:             with adding a user with filesystem privileges (e.g. author)
                    461: 
                    462: =head1 PREREQUISITES
                    463: 
                    464: =head1 COREQUISITES
                    465: 
                    466: =pod OSNAMES
                    467: 
                    468: linux
                    469: 
                    470: =pod SCRIPT CATEGORIES
                    471: 
                    472: LONCAPA/Administrative
                    473: 
                    474: =cut

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