Annotation of loncom/lcuseradd, revision 1.42

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.42    ! www         9: # $Id: lcuseradd,v 1.41 2007/03/28 20:43:37 albertel 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.15      harris41  322: # ------------------------------ Make final modifications to the user directory
1.42    ! www       323: # -- Add a construction space
        !           324:         
        !           325: my $path="/home/httpd/html/priv/".$domain;
        !           326: unless (-e $path) {
        !           327:    mkdir($path);
        !           328: }
        !           329: unless (-e $path.'/'.$safeusername) {
        !           330:    mkdir($path.'/'.$safeusername);
        !           331: }
1.8       harris41  332: 
1.35      foxr      333: 
1.24      www       334: # ---------------------------------------------------- Gracefull Apache Restart
1.40      raeburn   335: my $pidfile;
1.24      www       336: if (-e '/var/run/httpd.pid') {
1.40      raeburn   337:     $pidfile = '/var/run/httpd.pid';
                    338: } elsif (-e '/var/run/httpd2.pid') {   #Apache 2 on SuSE 10.1 and SLES10 
                    339:     $pidfile = '/var/run/httpd2.pid';
                    340: } 
                    341: 
                    342: if ($pidfile) {
1.24      www       343:     print "lcuseradd Apache restart\n" unless $noprint;
1.41      albertel  344:     open(PID,"<$pidfile");
1.24      www       345:     my $pid=<PID>;
                    346:     close(PID);
1.39      albertel  347:     $pid=~ /(\D+)/;
1.35      foxr      348:     my $safepid = $1;
1.24      www       349:     if ($pid) {
1.27      albertel  350: 	system('kill','-USR1',"$safepid");
1.24      www       351:     }
                    352: }
1.15      harris41  353: # -------------------------------------------------------- Exit script
1.26      foxr      354: print "lcuseradd Exiting\n" unless $noprint;
1.8       harris41  355: &disable_root_capability;
1.26      foxr      356: &Exit(0);
1.1       harris41  357: 
1.15      harris41  358: # ---------------------------------------------- Have setuid script run as root
1.5       harris41  359: sub enable_root_capability {
                    360:     if ($wwwid==$>) {
1.23      foxr      361: 	($<,$>)=($>,0);
                    362: 	($(,$))=($),0);
1.28      foxr      363:     } else {
1.5       harris41  364: 	# root capability is already enabled
                    365:     }
1.41      albertel  366:     if ($wwwid == $>) {
                    367: 	print("Failed to become root\n") unless $noprint;
                    368:     } else {
                    369: 	print("Became root\n") unless $noprint;
                    370:     }
1.5       harris41  371:     return $>;
                    372: }
                    373: 
1.15      harris41  374: # ----------------------------------------------- Have setuid script run as www
1.5       harris41  375: sub disable_root_capability {
                    376:     if ($wwwid==$<) {
                    377: 	($<,$>)=($>,$<);
                    378: 	($(,$))=($),$();
1.28      foxr      379:     } else {
1.5       harris41  380: 	# root capability is already disabled
                    381:     }
                    382: }
                    383: 
1.15      harris41  384: # ----------------------- Make sure that another lcpasswd process isn't running
1.5       harris41  385: sub try_to_lock {
                    386:     my ($lockfile)=@_;
                    387:     my $currentpid;
                    388:     my $lastpid;
                    389:     # Do not manipulate lock file as root
                    390:     if ($>==0) {
                    391: 	return 0;
                    392:     }
                    393:     # Try to generate lock file.
                    394:     # Wait 3 seconds.  If same process id is in
                    395:     # lock file, then assume lock file is stale, and
                    396:     # go ahead.  If process id's fluctuate, try
                    397:     # for a maximum of 10 times.
                    398:     for (0..10) {
                    399: 	if (-e $lockfile) {
                    400: 	    open(LOCK,"<$lockfile");
                    401: 	    $currentpid=<LOCK>;
                    402: 	    close LOCK;
                    403: 	    if ($currentpid==$lastpid) {
                    404: 		last;
                    405: 	    }
                    406: 	    sleep 3;
                    407: 	    $lastpid=$currentpid;
1.28      foxr      408: 	} else {
1.5       harris41  409: 	    last;
                    410: 	}
                    411: 	if ($_==10) {
                    412: 	    return 0;
                    413: 	}
                    414:     }
                    415:     open(LOCK,">$lockfile");
                    416:     print LOCK $$;
                    417:     close LOCK;
                    418:     return 1;
                    419: }
1.35      foxr      420: #    Called by File::Find::find for each file examined.
                    421: #
                    422: #     Untaint the file and, if it is a directory,
                    423: #     chmod it to 02770
                    424: #
                    425: sub set_permission {
                    426:     $File::Find::name =~ /^(.*)$/;
                    427:     my $safe_name = $1;		# Untainted filename...
                    428:     
                    429:     print "$safe_name" unless $noprint;
                    430:     if(-d $safe_name) {
                    431: 	print " - directory" unless $noprint;
                    432: 	chmod(02770, $safe_name);
                    433:     }
                    434:     print "\n" unless $noprint;
                    435: 
                    436: }
                    437: 
1.26      foxr      438: #-------------------------- Exit...
                    439: #
                    440: #   Write the file if the error_file is defined.  Regardless
                    441: #   Exit with the status code.
                    442: #
                    443: sub Exit {
                    444:     my ($code) = @_;		# Status code.
                    445: 
1.37      foxr      446:     # TODO: Ensure the error file is owned/deletable by www:www:
                    447: 
                    448:     &disable_root_capability();	# We run unprivileged to write the error file.
                    449: 
1.26      foxr      450:     print "Exiting with status $code error file is $error_file\n" unless $noprint;
                    451:     if($error_file) {
                    452: 	open(FH, ">$error_file");
                    453: 	print FH  "$code\n";
                    454: 	close(FH);
                    455:     }
                    456:     exit $code;
                    457: }
1.16      harris41  458: 
                    459: =head1 NAME
                    460: 
                    461: lcuseradd - LON-CAPA setuid script to coordinate all actions
                    462:             with adding a user with filesystem privileges (e.g. author)
                    463: 
                    464: =head1 DESCRIPTION
                    465: 
                    466: lcuseradd - LON-CAPA setuid script to coordinate all actions
                    467:             with adding a user with filesystem privileges (e.g. author)
                    468: 
                    469: =head1 README
                    470: 
                    471: lcuseradd - LON-CAPA setuid script to coordinate all actions
                    472:             with adding a user with filesystem privileges (e.g. author)
                    473: 
                    474: =head1 PREREQUISITES
                    475: 
                    476: =head1 COREQUISITES
                    477: 
                    478: =pod OSNAMES
                    479: 
                    480: linux
                    481: 
                    482: =pod SCRIPT CATEGORIES
                    483: 
                    484: LONCAPA/Administrative
                    485: 
                    486: =cut

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