Annotation of loncom/lcuseradd, revision 1.26

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.20      foxr        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.
1.16      harris41   16: #
1.26    ! foxr       17: # $Id: lcuseradd,v 1.25 2003/02/03 18:03:52 harris41 Exp $
1.16      harris41   18: ###
1.15      harris41   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: ###############################################################################
1.1       harris41   41: 
                     42: use strict;
                     43: 
1.15      harris41   44: # ------------------------------------------------------- Description of script
                     45: #
1.1       harris41   46: # This script is a setuid script that should
1.20      foxr       47: # be run by user 'www'.  It creates a /home/USERNAME directory.
1.15      harris41   48: # It adds a user to the unix system.
1.2       harris41   49: # Passwords are set with lcpasswd.
                     50: # www becomes a member of this user group.
1.1       harris41   51: 
1.15      harris41   52: # -------------- Invoking script (standard input versus command-line arguments)
1.26    ! foxr       53: #                Otherwise sensitive information will be available to ps-ers for
        !            54: #                a small but exploitable time window.
1.15      harris41   55: #
                     56: # Standard input (STDIN) usage
1.1       harris41   57: # First line is USERNAME
                     58: # Second line is PASSWORD
1.3       harris41   59: # Third line is PASSWORD
1.26    ! foxr       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: #  
1.15      harris41   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: #
1.7       harris41   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{|}~
1.15      harris41   79: #
1.7       harris41   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).
1.15      harris41   84: # User names must begin with an alphabetical character
                     85: # (A-Z,a-z).
1.7       harris41   86: 
1.15      harris41   87: # ---------------------------------- Example usage inside another piece of code
1.4       harris41   88: # Usage within code
                     89: #
1.26    ! foxr       90: # $Exitcode=
1.15      harris41   91: #      system("/home/httpd/perl/lcuseradd","NAME","PASSWORD1","PASSWORD2")/256;
1.26    ! foxr       92: # print "uh-oh" if $Exitcode;
1.4       harris41   93: 
1.15      harris41   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
1.26    ! foxr      100: # These are the Exit codes.
1.13      harris41  101: # ( (0,"ok"),
                    102: # (1,"User ID mismatch.  This program must be run as user 'www'"),
1.15      harris41  103: # (2,"Error. This program needs 3 command-line arguments (username, ".
                    104: #    "password 1, password 2)."),
1.13      harris41  105: # (3,"Error. Three lines should be entered into standard input."),
1.15      harris41  106: # (4,"Error. Too many other simultaneous password change requests being ".
                    107: #    "made."),
1.13      harris41  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.),
1.15      harris41  111: # (8,"Error. Cannot set password."),
1.13      harris41  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.),
1.15      harris41  115: # (12,"Error. Something went wrong with the addition of user ".
                    116: #     "\"$safeusername\"."),
1.13      harris41  117: # (13,"Error. Password mismatch."),
1.26    ! foxr      118: # (14, "Error filename is invalid")
1.4       harris41  119: 
1.15      harris41  120: # ------------------------------------------------------------- Initializations
1.1       harris41  121: # Security
1.15      harris41  122: $ENV{'PATH'}='/bin/:/usr/bin:/usr/local/sbin:/home/httpd/perl'; # Nullify path
                    123:                                                                 # information
1.16      harris41  124: delete @ENV{qw(IFS CDPATH ENV BASH_ENV)}; # nullify potential taints
1.2       harris41  125: 
1.15      harris41  126: # Do not print error messages.
                    127: my $noprint=1;
                    128: 
1.26    ! foxr      129: #  Error file:
        !           130: 
        !           131: my $error_file;			# This is either the error file name or undef.
        !           132: 
1.23      foxr      133: print "In lcuseradd\n" unless $noprint;
                    134: 
1.15      harris41  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;
1.26    ! foxr      141:     &Exit(1);
1.4       harris41  142: }
1.15      harris41  143: 
                    144: # ----------------------------------- Start running script with www permissions
1.4       harris41  145: &disable_root_capability;
                    146: 
1.15      harris41  147: # --------------------------- Handle case of another lcpasswd process (locking)
1.4       harris41  148: unless (&try_to_lock("/tmp/lock_lcpasswd")) {
1.15      harris41  149:     print "Error. Too many other simultaneous password change requests being ".
                    150: 	"made.\n" unless $noprint;
1.26    ! foxr      151:     &Exit(4);
1.4       harris41  152: }
                    153: 
1.15      harris41  154: # ------- Error-check input, need 3 values (user name, password 1, password 2).
1.4       harris41  155: my @input;
1.26    ! foxr      156: if (@ARGV>=3) {
1.4       harris41  157:     @input=@ARGV;
                    158: }
                    159: elsif (@ARGV) {
1.26    ! foxr      160:     print("Error. This program needs at least 3 command-line arguments (username, ".
        !           161: 	  "password 1, password 2 [errorfile]).\n") unless $noprint;
1.4       harris41  162:     unlink('/tmp/lock_lcpasswd');
1.26    ! foxr      163:     &Exit(2);
1.4       harris41  164: }
                    165: else {
                    166:     @input=<>;
1.26    ! foxr      167:     if (@input < 3) {
        !           168: 	print("Error. At least three lines should be entered into standard input.\n")
1.15      harris41  169: 	    unless $noprint;
1.4       harris41  170: 	unlink('/tmp/lock_lcpasswd');
1.26    ! foxr      171: 	&Exit(3);
1.4       harris41  172:     }
1.19      harris41  173:     foreach (@input) {chomp;}
1.4       harris41  174: }
                    175: 
1.26    ! foxr      176: my ($username,$password1,$password2, $error_file)=@input;
1.23      foxr      177: print "Username = ".$username."\n" unless $noprint;
1.4       harris41  178: $username=~/^(\w+)$/;
1.22      foxr      179: print "Username after substitution - ".$username unless $noprint;
1.4       harris41  180: my $safeusername=$1;
1.23      foxr      181: print "Safe username = $safeusername \n" unless $noprint;
1.22      foxr      182: 
1.15      harris41  183: if (($username ne $safeusername) or ($safeusername!~/^[A-Za-z]/)) {
1.22      foxr      184:     print "Error. The user name specified $username $safeusername  has invalid characters.\n"
1.15      harris41  185: 	unless $noprint;
1.8       harris41  186:     unlink('/tmp/lock_lcpasswd');
1.26    ! foxr      187:     &Exit(9);
1.8       harris41  188: }
                    189: my $pbad=0;
1.19      harris41  190: foreach (split(//,$password1)) {if ((ord($_)<32)||(ord($_)>126)){$pbad=1;}}
                    191: foreach (split(//,$password2)) {if ((ord($_)<32)||(ord($_)>126)){$pbad=1;}}
1.8       harris41  192: if ($pbad) {
1.26    ! foxr      193:     print "Error. A password entry had an invalid character.\n" unless $noprint;
1.8       harris41  194:     unlink('/tmp/lock_lcpasswd');
1.26    ! foxr      195:     &Exit(10);
1.8       harris41  196: }
1.5       harris41  197: 
1.26    ! foxr      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: 
1.15      harris41  228: # -- Only add user if we can create a brand new home directory (/home/username)
1.7       harris41  229: if (-e "/home/$safeusername") {
                    230:     print "Error. User already exists.\n" unless $noprint;
                    231:     unlink('/tmp/lock_lcpasswd');
1.26    ! foxr      232:     &Exit(11);
1.7       harris41  233: }
                    234: 
1.15      harris41  235: # -- Only add user if the two password arguments match.
1.23      foxr      236: 
1.5       harris41  237: if ($password1 ne $password2) {
1.6       harris41  238:     print "Error. Password mismatch.\n" unless $noprint;
1.5       harris41  239:     unlink('/tmp/lock_lcpasswd');
1.26    ! foxr      240:     &Exit(13);
1.5       harris41  241: }
1.23      foxr      242: print "enabling root\n" unless $noprint;
1.15      harris41  243: # ---------------------------------- Start running script with root permissions
1.4       harris41  244: &enable_root_capability;
                    245: 
1.15      harris41  246: # ------------------- Add user and make www a member of the user-specific group
                    247: # -- Add user
1.23      foxr      248: 
                    249: print "adding user: $safeusername \n" unless $noprint;
                    250: my $status = system('/usr/sbin/useradd','-c','LON-CAPA user',$safeusername);
                    251: if ($status) {
1.15      harris41  252:     print "Error.  Something went wrong with the addition of user ".
                    253: 	  "\"$safeusername\".\n" unless $noprint;
1.23      foxr      254:     print "Final status of useradd = $status";
1.4       harris41  255:     unlink('/tmp/lock_lcpasswd');
1.26    ! foxr      256:     &Exit(12);
1.4       harris41  257: }
1.23      foxr      258: print "Done adding user\n" unless $noprint;
1.7       harris41  259: # Make www a member of that user group.
1.26    ! foxr      260: my $groups=`/usr/bin/groups www` or &Exit(6);
1.17      harris41  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));
1.23      foxr      265: print "Putting user in its own group\n" unless $noprint;
1.17      harris41  266: if (system('/usr/sbin/usermod','-G',$gl,'www')) {
1.15      harris41  267:     print "Error. Could not make www a member of the group ".
                    268: 	  "\"$safeusername\".\n" unless $noprint;
1.5       harris41  269:     unlink('/tmp/lock_lcpasswd');
1.26    ! foxr      270:     &Exit(6);
1.5       harris41  271: }
                    272: 
1.15      harris41  273: # ---------------------------------------------------------------- Set password
                    274: # Set password with lcpasswd (which creates smbpasswd entry).
1.2       harris41  275: 
1.15      harris41  276: unlink('/tmp/lock_lcpasswd');
                    277: &disable_root_capability;
1.16      harris41  278: ($>,$<)=($wwwid,$wwwid);
1.23      foxr      279: print "Opening lcpasswd pipeline\n" unless $noprint;
1.16      harris41  280: open OUT,"|/home/httpd/perl/lcpasswd";
1.15      harris41  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 ($?) {
1.26    ! foxr      289:     print "abnormal Exit from close lcpasswd\n" unless $noprint;
        !           290:     &Exit(8);
1.8       harris41  291: }
1.18      harris41  292: ($>,$<)=($wwwid,0);
1.15      harris41  293: &enable_root_capability;
1.8       harris41  294: 
1.20      foxr      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: 
1.15      harris41  298: # ------------------------------ Make final modifications to the user directory
                    299: # -- Add a public_html file with a stand-in index.html file
1.8       harris41  300: 
1.21      foxr      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>
1.24      www       312: <h1>Construction Space</h1>
                    313: <h3>$safeusername</h3>
1.21      foxr      314: </body>
                    315: </html>
                    316: END
                    317: close OUT;
1.20      foxr      318: 
1.24      www       319: print "lcuseradd ownership\n" unless $noprint;
1.11      harris41  320: system('/bin/chown','-R',"$safeusername:$safeusername","/home/$safeusername");
1.24      www       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: }
1.15      harris41  332: # -------------------------------------------------------- Exit script
1.26    ! foxr      333: print "lcuseradd Exiting\n" unless $noprint;
1.8       harris41  334: &disable_root_capability;
1.26    ! foxr      335: &Exit(0);
1.1       harris41  336: 
1.15      harris41  337: # ---------------------------------------------- Have setuid script run as root
1.5       harris41  338: sub enable_root_capability {
                    339:     if ($wwwid==$>) {
1.23      foxr      340: 	($<,$>)=($>,0);
                    341: 	($(,$))=($),0);
1.5       harris41  342:     }
                    343:     else {
                    344: 	# root capability is already enabled
                    345:     }
                    346:     return $>;
                    347: }
                    348: 
1.15      harris41  349: # ----------------------------------------------- Have setuid script run as www
1.5       harris41  350: sub disable_root_capability {
                    351:     if ($wwwid==$<) {
                    352: 	($<,$>)=($>,$<);
                    353: 	($(,$))=($),$();
                    354:     }
                    355:     else {
                    356: 	# root capability is already disabled
                    357:     }
                    358: }
                    359: 
1.15      harris41  360: # ----------------------- Make sure that another lcpasswd process isn't running
1.5       harris41  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: }
1.26    ! foxr      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: }
1.16      harris41  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>