newuser.in 14.8 KB
Newer Older
1
#!/usr/bin/perl -w
2
#
Leigh B Stoller's avatar
Leigh B Stoller committed
3
# Copyright (c) 2000-2018 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
23 24 25 26 27 28
#
use English;
use strict;
use Getopt::Std;
use XML::Simple;
use Data::Dumper;
29
use Cwd qw(realpath);
30 31 32 33 34 35

#
# Create a new user from a XML description. 
#
sub usage()
{
36
    print("Usage: newuser [-s] -t <type> <xmlfile>\n");
37 38
    exit(-1);
}
39
my $optlist = "dt:nsp";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
40
my $debug   = 0;
41
my $impotent= 0;
42
my $type    = "";
43
my $silent  = 0;
44
my $portal;
45
my @keyfiles = ();
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS       = "@TBOPSEMAIL@";
my $TBAPPROVAL  = "@TBAPPROVALEMAIL@";
my $TBAUDIT	= "@TBAUDITEMAIL@";
my $TBBASE      = "@TBBASE@";
my $TBWWW       = "@TBWWW@";
my $WIKISUPPORT = @WIKISUPPORT@;
my $TBADMINGROUP= "@TBADMINGROUP@";
my $checkpass   = "$TB/libexec/checkpass";
my $addpubkey   = "$TB/sbin/addpubkey";

#
# This script is setuid, so please do not run it as root. Hard to track
# what has happened.
#
if ($EUID == 0) {
    die("*** $0:\n".
	"    Please do not run this as root!\n");
}

#
# Untaint the path
#
$ENV{'PATH'} = "$TB/bin:$TB/sbin:/bin:/usr/bin:/usr/bin:/usr/sbin";
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

#
# Turn off line buffering on output
#
$| = 1;

#
# Load the Testbed support stuff.
#
use lib "@prefix@/lib";
use libdb;
use libtestbed;
use User;
88
use EmulabConstants();
89
use emutil;
Leigh B Stoller's avatar
Leigh B Stoller committed
90
use Brand;
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110

# Protos
sub fatal($);
sub UserError($);
sub escapeshellarg($);

# Locals
my $SAVEUID	= $UID;

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
my %options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"d"})) {
    $debug = 1;
}
111 112 113 114 115 116
if (defined($options{"n"})) {
    $impotent = 1;
}
if (defined($options{"s"})) {
    $silent = 1;
}
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
if (defined($options{"t"})) {
    $type = $options{"t"};
}
if (@ARGV != 1) {
    usage();
}
my $xmlfile  = shift(@ARGV);

#
# Map invoking user to object. 
# If invoked as "nobody" we are coming from the web interface and there
# is no current user context.
#
my $this_user;

if (getpwuid($UID) ne "nobody") {
    $this_user = User->ThisUser();

    if (! defined($this_user)) {
	fatal("You ($UID) do not exist!");
    }
    fatal("You must have admin privledges to create new users")
Leigh B Stoller's avatar
Leigh B Stoller committed
139
	if (!$this_user->IsAdmin());
140 141 142 143 144 145 146 147 148 149 150 151 152 153
}
else {
    #
    # Check the filename when invoked from the web interface; must be a
    # file in /tmp.
    #
    if ($xmlfile =~ /^([-\w\.\/]+)$/) {
	$xmlfile = $1;
    }
    else {
	fatal("Bad data in pathname: $xmlfile");
    }

    # Use realpath to resolve any symlinks.
154
    my $translated = realpath($xmlfile);
155 156 157 158 159 160 161 162 163 164
    if ($translated =~ /^(\/tmp\/[-\w\.\/]+)$/) {
	$xmlfile = $1;
    }
    else {
	fatal("Bad data in translated pathname: $xmlfile");
    }
}

#
# These are the fields that we allow to come in from the XMLfile.
165
# This first set is required by all types of users
166 167
#
my %required = ("name"		=> "usr_name",
168
		"email"		=> "usr_email");
169

170
my %optional = ("uid"		=> "uid",
171 172 173
		"address2"	=> "usr_addr2",
		"URL"		=> "usr_URL",
		"shell"		=> "usr_shell",
174
		"password"	=> undef,
175
		"passphrase"	=> "initial_passphrase",
176 177
		"pubkey"        => undef,
		"pubkeys"       => undef);
178

179 180 181 182 183 184 185 186 187 188
#
# These are required for most users, but are optional for wiki-only users
# 
my %usually_required = ("address"	=> "usr_addr",
 		        "city"		=> "usr_city",
 		        "state"	        => "usr_state",
		        "zip"		=> "usr_zip",
		        "country"	=> "usr_country",
		        "phone"	        => "usr_phone",
		        "title"	        => "usr_title",
189 190
		        "affiliation"	=> "usr_affil",
		        "affiliation_abbreviation" => "usr_affil_abbrev");
191 192
if ($type eq "wikionly") {
    %optional = (%optional, %usually_required);
193 194
}
elsif ($type ne "nonlocal") {
195 196 197
    %required = (%required, %usually_required);
}

198 199
($WIKISUPPORT ? \%required : \%optional)->{"wikiname"} = "wikiname";

200 201 202 203
#
# Must wrap the parser in eval since it exits on error.
#
my $xmlparse = eval { XMLin($xmlfile,
204
			    ForceArray => ["pubkeys"],
205 206 207 208 209 210
			    VarAttr => 'name',
			    ContentKey => '-content',
			    SuppressEmpty => undef); };
fatal($@)
    if ($@);

211 212
print STDERR Dumper($xmlparse)
    if ($debug);
213

214
# APT flag. Notice and delete.
215 216 217
if (exists($xmlparse->{'attribute'}->{"portal"})) {
    $portal = $xmlparse->{'attribute'}->{"portal"}->{'value'};
    delete($xmlparse->{'attribute'}->{"portal"});
Leigh B Stoller's avatar
Leigh B Stoller committed
218 219
    my $brand = Brand->Create($portal);
    if (!defined($brand)) {
220
	fatal("Bad portal: $portal");
221
    }
222 223 224 225 226 227 228 229 230
    # Remove these, we do not require them on the APT path.
    delete($required{"affiliation_abbreviation"});
    delete($required{"phone"});
    delete($required{"title"});
    delete($required{"address"});
    delete($required{"zip"});
    delete($required{"wikiname"});
}

231 232 233 234 235 236 237 238
#
# Make sure all the required arguments were provided.
#
foreach my $key (keys(%required)) {
    
    fatal("Missing required attribute '$key'")
	if (! exists($xmlparse->{'attribute'}->{"$key"}));
}
239 240 241 242 243
#
# Always delete this. Used by the portal code but we ignore it.
#
delete($xmlparse->{'attribute'}->{"passhash"})
    if (exists($xmlparse->{'attribute'}->{"passhash"}));
244 245 246 247 248 249 250 251 252

#
# We build up an array of arguments to pass to User->Create() as we check
# the attributes.
#
my %newuser_args = ();

foreach my $key (keys(%{ $xmlparse->{'attribute'} })) {
    my $value = $xmlparse->{'attribute'}->{"$key"}->{'value'};
253 254 255
    if (!defined($value)) {	# Empty string comes from XML as an undef value.
	$xmlparse->{'attribute'}->{"$key"}->{'value'} = $value = "";
    }
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303

    if ($debug) {
	print STDERR "User attribute: '$key' -> '$value'\n";
    }

    my $dbslot;

    # Must be in the allowed lists above, with exceptions handled below
    if (exists($required{$key})) {
	$dbslot = $required{$key};
	next
	    if (!defined($dbslot));
	fatal("Null value for required field $key")
	    if (!defined($value));
    }
    elsif (exists($optional{$key})) {
	$dbslot = $optional{$key};
	next
	    if (!defined($dbslot) || !defined($value));
    }
    else {
	fatal("Invalid attribute in XML: '$key' -> '$value'\n");
    }

    # Now check that the value is legal.
    if (! TBcheck_dbslot($value, "users", $dbslot,
			 TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
	UserError("Illegal data: $key - $value");
    }

    #
    # Do a taint check to avoid warnings, since the values are abviously okay.
    #
    if ($value =~ /^(.*)$/) {
	$value = $1;
    }
    $newuser_args{$dbslot} = $value;
}

#
# Now do special checks.
#

#
# If user selected his own uid, must be unique.
#
if (exists($newuser_args{'uid'})) {
    UserError("User already exists; pick another login name!")
304
	if (User->Lookup($newuser_args{'uid'}));
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
    
    UserError("Reserved user name; pick another login name!")
	if (getpwnam($newuser_args{'uid'}));
}

#
# User name must be at least two tokens.
#
my @foo = split(/\s+/, $newuser_args{'usr_name'});

UserError("User name must be more then a single token!")
    if (@foo < 2);

#
# Wikiname must be unique.
#
if ($WIKISUPPORT) {
    UserError("Wikiname already in use; please pick another!")
323 324
	if (exists($newuser_args{'wikiname'}) &&
	    User->LookupByWikiName($newuser_args{'wikiname'}));
325 326 327 328 329 330
}

#
# And the email address has to be unique.
#
UserError("Email address already in use; please pick another!")
331 332
    if ($newuser_args{'usr_email'} ne $TBOPS &&
	User->LookupByEmail($newuser_args{'usr_email'}));
333 334 335 336

#
# Check the password.
#
337 338
my $pswd = (exists($xmlparse->{'attribute'}->{'password'}) ?
	    $xmlparse->{'attribute'}->{'password'}->{'value'} : "*");
339 340

# Admins can "star" the password entry.
341
if ($pswd eq "*") {
342
    if ($type ne "nonlocal" && defined($this_user) && $this_user->IsAdmin()) {
343 344 345 346 347
	$newuser_args{'usr_pswd'} = "*";
    }
    else {
	UserError("Only admins can star the password entry");
    }
348 349 350 351 352 353 354
}
else {
    my $checkpass_args = escapeshellarg($pswd);
    $checkpass_args   .= " " .
	(exists($newuser_args{'uid'}) ? $newuser_args{'uid'} : "ignored");
    $checkpass_args   .= escapeshellarg($newuser_args{'usr_name'} . ":" .
					$newuser_args{'usr_email'});
355
    
356 357 358
    my $pwokay = `$checkpass $checkpass_args`;
    if ($?) {
	chomp($pwokay);
359
    
360 361 362 363
	if (! ($pwokay =~ /^ok$/)) {
	    UserError("$pwokay");
	}
	fatal("Checkpass failed with $?");
364
    }
365
    $newuser_args{'usr_pswd'} = PassWordHash($pswd);    
366 367
}

368 369 370 371
#
# Check the passphrase if supplied.
#
if (exists($xmlparse->{'attribute'}->{'passphrase'}) &&
Leigh B Stoller's avatar
Leigh B Stoller committed
372
    $xmlparse->{'attribute'}->{'passphrase'}->{'value'} ne "") {
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
    my $passphrase = $xmlparse->{'attribute'}->{'passphrase'}->{'value'};
    
    my $checkpass_args = escapeshellarg($passphrase);
    $checkpass_args   .= " " .
	(exists($newuser_args{'uid'}) ? $newuser_args{'uid'} : "ignored");
    $checkpass_args   .= escapeshellarg($newuser_args{'usr_name'} . ":" .
					$newuser_args{'usr_email'});
    
    my $pwokay = `$checkpass $checkpass_args`;
    if ($?) {
	chomp($pwokay);
    
	if (! ($pwokay =~ /^ok$/)) {
	    UserError("$pwokay");
	}
	fatal("Checkpass failed with $?");
    }
    $newuser_args{'initial_passphrase'} = $passphrase;
}

393 394 395 396
#
# Do a check on the pubkey if supplied. The safest thing to do is generate
# a temporary file and pass that to addpubkey to check.
#
397 398
if (exists($xmlparse->{'attribute'}->{'pubkey'}) ||
    exists($xmlparse->{'pubkeys'})) {
399

400 401 402
    my @keys = (exists($xmlparse->{'pubkeys'}) ? 
		@{ $xmlparse->{'pubkeys'} } :
		($xmlparse->{'attribute'}->{'pubkey'}->{'value'}));
403

404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
    foreach my $key (@keys) {
	my $keyfile = TBMakeTempFile("addpubkey");
	fatal("Could not create tempfile")
	    if ($?);

	open(KEY, ">> $keyfile") or
	    fatal("Could not open $keyfile");
	print KEY $key; 
	close($keyfile);

	if ($debug) {
	    print STDERR "Checking key in $keyfile ...\n";
	}
	my $result = `$addpubkey -n -f $keyfile`;
	chomp($result);
	UserError("Could not parse public key")
	    if ($?);
	push(@keyfiles, $keyfile);
    }
423 424 425 426 427 428
}

#
# Now safe to create the user. Move the uid out of the argument array
# since its actually an argument to the Create() routine.
#
429 430 431
exit(0)
    if ($impotent);

432 433 434 435 436 437
my $new_uid;

if (exists($newuser_args{'uid'})) {
    $new_uid = $newuser_args{'uid'};
    delete($newuser_args{'uid'});
}
438 439 440
# Portal (Emulab, APT, CloudLab or PhantomNet)
$newuser_args{'portal'} = $portal
    if (defined($portal));
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456

#
# The type modifier comes in on the command line since this is available
# only from the web interface or locally. The usual case is to create a
# normal user.
#
my $flags = 0;
if ($type eq "webonly") {
    $flags = $User::NEWUSER_FLAGS_WEBONLY;
}
elsif ($type eq "wikionly") {
    $flags = $User::NEWUSER_FLAGS_WIKIONLY;
}
elsif ($type eq "leader") {
    $flags = $User::NEWUSER_FLAGS_PROJLEADER;
}
457 458
elsif ($type eq "nonlocal") {
    $flags = $User::NEWUSER_FLAGS_NONLOCAL;
459
}
460 461 462 463
my $newuser = User->Create($new_uid, $flags, \%newuser_args);
if (!defined($newuser)) {
    fatal("Could not create new user!");
}
464
if (defined($portal)) {
465 466
    $newuser->SetStatus(USERSTATUS_UNAPPROVED());
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
467 468 469 470 471 472
my $key       = $newuser->verify_key();
my $usr_uid   = $newuser->uid();
my $usr_idx   = $newuser->uid_idx();
my $usr_name  = $newuser->name();
my $usr_email = $newuser->email();
	    
473 474 475 476 477 478 479 480
#
# See if we are in an initial Emulab setup. If so, no email sent.
#
my $firstinitstate;
if (TBGetSiteVar("general/firstinit/state", \$firstinitstate)) {
    #
    # The first user gets admin status and some extra groups, etc.
    #
481 482 483
    if ($firstinitstate eq "createproject") {
	DBQueryFatal("update users set ".
		     " admin=1,status='". $User::USERSTATUS_UNAPPROVED . "' " .
484
		     "where uid_idx='$usr_idx'");
485

486
	DBQueryFatal("insert into unixgroup_membership set ".
487
		     "uid='$new_uid', uid_idx='$usr_idx', gid='wheel'");
488
    
489
	DBQueryFatal("insert into unixgroup_membership set ".
490
		     "uid='$new_uid', uid_idx='$usr_idx', gid='$TBADMINGROUP'");
491
	
Leigh B. Stoller's avatar
Leigh B. Stoller committed
492 493
	# The web interface requires this line to be printed!
	print "User $usr_uid/$usr_idx has been created\n";
494 495
	exit(0);
    }
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
}

#
# Send the email notification.
#
SENDMAIL("$usr_name '$usr_uid' <$usr_email>",
	 "Your New User Key",
	 "\n".
	 "Dear $usr_name ($usr_uid):\n\n".
	 "This is your account verification key: $key\n\n".
	 "Please use this link to verify your user account:\n".
	 "\n".
	 "    ${TBBASE}/login.php3?vuid=$usr_uid&key=$key\n".
	 "\n".
	 ($type eq "wikionly" ?
	  "Once you have verified your account, you will be able to access\n".
	  "the Wiki. You MUST verify your account first!"
	  :
	  ($type eq "webonly" ?
	   "Once you have verified your account, Testbed Operations will be\n".
	   "able to approve you. You MUST verify your account first!"
	   :
	   ($type eq "leader" ?
	  "You will then be verified as a user. When you have been both\n".
	  "verified and approved by Testbed Operations, you will be marked\n".
	  "as an active user and granted full access to your account.\n".
	  "You MUST verify your account before your project can be approved!\n"
	    :
	    "Once you have verified your account, the project leader will\n".
	    "be able to approve you.\n\n".
	    "You MUST verify your account before the project leader can ".
	    "approve you\n".
	    "After project approval, you will be marked as an active user,\n".
	    "and will be granted full access to your user account."))) .
	 "\n\n".
	 "Thanks,\n".
	 "Testbed Operations\n",
	 "$TBAPPROVAL",
534
	 "Bcc: $TBAUDIT")
535
    if (!($silent || defined($portal)));
536 537 538 539 540

#
# Do we have a keyfile? If so, rerun addpubkey for real now that the
# user is created and email is sent.
#
541
if (@keyfiles) {
542
    # Set the implied user for addpubkey.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
543
    $ENV{'HTTP_INVOKING_USER'} = $usr_idx;
544 545 546 547 548 549 550 551 552 553 554
    my $opt = ($silent ? "-s" : "");

    foreach my $keyfile (@keyfiles) {
	my $result = `$addpubkey $opt -u $usr_uid -f $keyfile`;
	chomp($result);
	fatal("Could not parse public key: $result")
	    if ($?);
	
	unlink($keyfile)
	    if (! $debug);
    }
555 556 557
}

# The web interface requires this line to be printed!
Leigh B. Stoller's avatar
Leigh B. Stoller committed
558
print "User $usr_uid/$usr_idx has been created\n";
559 560 561 562 563
exit(0);

sub fatal($) {
    my($mesg) = $_[0];

564 565 566 567 568
    if (@keyfiles && !$debug) {
	foreach my $keyfile (@keyfiles) {
	    unlink($keyfile)
	}
    }
569 570 571 572 573 574 575 576

    print STDERR "*** $0:\n".
	         "    $mesg\n";
    exit(-1);
}
sub UserError($) {
    my($mesg) = $_[0];

577 578 579 580 581
    if (@keyfiles && !$debug) {
	foreach my $keyfile (@keyfiles) {
	    unlink($keyfile)
	}
    }
582 583 584 585 586 587 588 589 590

    print $mesg;
    exit(1);
}

sub escapeshellarg($)
{
    my ($str) = @_;

591
    $str =~ s/[^[:alnum:]]/\\$&/g;
592 593 594 595 596
    return $str;
}