newuser.in 15.1 KB
Newer Older
1
#!/usr/bin/perl -w
2
#
Leigh Stoller's avatar
Leigh 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:nsprP";
Leigh Stoller's avatar
Leigh Stoller committed
40
my $debug   = 0;
41
my $impotent= 0;
42
my $type    = "";
43
my $silent  = 0;
44 45
my $relaxed = 0;
my $dopass  = 0;
46
my $portal;
47
my $passhash;
48
my @keyfiles = ();
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 88 89 90

#
# 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;
91
use EmulabConstants();
92
use emutil;
Leigh Stoller's avatar
Leigh Stoller committed
93
use Brand;
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113

# 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;
}
114 115 116 117 118 119
if (defined($options{"n"})) {
    $impotent = 1;
}
if (defined($options{"s"})) {
    $silent = 1;
}
120 121 122
if (defined($options{"t"})) {
    $type = $options{"t"};
}
123 124 125 126 127 128
if (defined($options{"r"})) {
    $relaxed = 1;
}
if (defined($options{"P"})) {
    $dopass = 1;
}
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
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 Stoller's avatar
Leigh Stoller committed
148
	if (!$this_user->IsAdmin());
149 150 151 152 153 154 155 156 157 158 159 160 161 162
}
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.
163
    my $translated = realpath($xmlfile);
164 165 166 167 168 169 170 171 172 173
    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.
174
# This first set is required by all types of users
175 176
#
my %required = ("name"		=> "usr_name",
177
		"email"		=> "usr_email");
178

179
my %optional = ("uid"		=> "uid",
180 181 182
		"address2"	=> "usr_addr2",
		"URL"		=> "usr_URL",
		"shell"		=> "usr_shell",
183
		"password"	=> undef,
184
		"passphrase"	=> "initial_passphrase",
185 186
		"pubkey"        => undef,
		"pubkeys"       => undef);
187

188 189 190 191 192 193 194
my %relaxed_fields = ("affiliation_abbreviation" => 1,
		      "phone"    => 1,
		      "title"    => 1,
		      "address"  => 1,
		      "zip"      => 1,
		      "wikiname" => 1);

195 196 197 198 199 200 201 202 203 204
#
# 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",
205 206
		        "affiliation"	=> "usr_affil",
		        "affiliation_abbreviation" => "usr_affil_abbrev");
207 208
if ($type eq "wikionly") {
    %optional = (%optional, %usually_required);
209 210
}
elsif ($type ne "nonlocal") {
211 212 213
    %required = (%required, %usually_required);
}

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

216 217 218 219
#
# Must wrap the parser in eval since it exits on error.
#
my $xmlparse = eval { XMLin($xmlfile,
220
			    ForceArray => ["pubkeys"],
221 222 223 224 225 226
			    VarAttr => 'name',
			    ContentKey => '-content',
			    SuppressEmpty => undef); };
fatal($@)
    if ($@);

227 228
print STDERR Dumper($xmlparse)
    if ($debug);
229

230
# APT flag. Notice and delete.
231 232 233
if (exists($xmlparse->{'attribute'}->{"portal"})) {
    $portal = $xmlparse->{'attribute'}->{"portal"}->{'value'};
    delete($xmlparse->{'attribute'}->{"portal"});
Leigh Stoller's avatar
Leigh Stoller committed
234 235
    my $brand = Brand->Create($portal);
    if (!defined($brand)) {
236
	fatal("Bad portal: $portal");
237
    }
238
    $relaxed = 1;
239 240
}

241 242 243 244
#
# Make sure all the required arguments were provided.
#
foreach my $key (keys(%required)) {
245 246
    next
	if ($relaxed && exists($relaxed_fields{$key}));
247 248 249 250
    
    fatal("Missing required attribute '$key'")
	if (! exists($xmlparse->{'attribute'}->{"$key"}));
}
251
#
252 253
# Used by the portal code but we ignore it unless explicitly told
# not to.
254
#
255 256 257 258 259 260
if (exists($xmlparse->{'attribute'}->{"passhash"})) {
    if ($dopass) {
	$passhash = $xmlparse->{'attribute'}->{"passhash"}->{'value'};
    }
    delete($xmlparse->{'attribute'}->{"passhash"});
}
261 262 263 264 265 266 267 268 269

#
# 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'};
270 271 272
    if (!defined($value)) {	# Empty string comes from XML as an undef value.
	$xmlparse->{'attribute'}->{"$key"}->{'value'} = $value = "";
    }
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 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320

    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!")
321
	if (User->Lookup($newuser_args{'uid'}));
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
    
    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!")
340 341
	if (exists($newuser_args{'wikiname'}) &&
	    User->LookupByWikiName($newuser_args{'wikiname'}));
342 343 344 345 346 347
}

#
# And the email address has to be unique.
#
UserError("Email address already in use; please pick another!")
348 349
    if ($newuser_args{'usr_email'} ne $TBOPS &&
	User->LookupByEmail($newuser_args{'usr_email'}));
350 351 352 353

#
# Check the password.
#
354 355
my $pswd = (exists($xmlparse->{'attribute'}->{'password'}) ?
	    $xmlparse->{'attribute'}->{'password'}->{'value'} : "*");
356 357

# Admins can "star" the password entry.
358
if ($pswd eq "*") {
359
    if ($type ne "nonlocal" && defined($this_user) && $this_user->IsAdmin()) {
360 361 362 363 364
	$newuser_args{'usr_pswd'} = "*";
    }
    else {
	UserError("Only admins can star the password entry");
    }
365 366 367 368 369 370 371
}
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'});
372
    
373 374 375
    my $pwokay = `$checkpass $checkpass_args`;
    if ($?) {
	chomp($pwokay);
376
    
377 378 379 380
	if (! ($pwokay =~ /^ok$/)) {
	    UserError("$pwokay");
	}
	fatal("Checkpass failed with $?");
381
    }
382
    $newuser_args{'usr_pswd'} = PassWordHash($pswd);    
383 384
}

385 386 387 388
#
# Check the passphrase if supplied.
#
if (exists($xmlparse->{'attribute'}->{'passphrase'}) &&
389
    $xmlparse->{'attribute'}->{'passphrase'}->{'value'} ne "") {
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
    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;
}

410 411 412 413
#
# 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.
#
414 415
if (exists($xmlparse->{'attribute'}->{'pubkey'}) ||
    exists($xmlparse->{'pubkeys'})) {
416

417 418 419
    my @keys = (exists($xmlparse->{'pubkeys'}) ? 
		@{ $xmlparse->{'pubkeys'} } :
		($xmlparse->{'attribute'}->{'pubkey'}->{'value'}));
420

421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
    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);
    }
440 441 442 443 444 445
}

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

449 450 451 452 453 454
my $new_uid;

if (exists($newuser_args{'uid'})) {
    $new_uid = $newuser_args{'uid'};
    delete($newuser_args{'uid'});
}
455 456 457
# Portal (Emulab, APT, CloudLab or PhantomNet)
$newuser_args{'portal'} = $portal
    if (defined($portal));
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473

#
# 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;
}
474 475
elsif ($type eq "nonlocal") {
    $flags = $User::NEWUSER_FLAGS_NONLOCAL;
476
}
477 478 479 480
my $newuser = User->Create($new_uid, $flags, \%newuser_args);
if (!defined($newuser)) {
    fatal("Could not create new user!");
}
481
if (defined($portal)) {
482 483
    $newuser->SetStatus(USERSTATUS_UNAPPROVED());
}
484 485 486
if (defined($passhash)) {
    $newuser->SetPassword($passhash);
}
Leigh Stoller's avatar
Leigh Stoller committed
487 488 489 490 491 492
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();
	    
493 494 495 496 497 498 499 500
#
# 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.
    #
501 502 503
    if ($firstinitstate eq "createproject") {
	DBQueryFatal("update users set ".
		     " admin=1,status='". $User::USERSTATUS_UNAPPROVED . "' " .
504
		     "where uid_idx='$usr_idx'");
505

506
	DBQueryFatal("insert into unixgroup_membership set ".
507
		     "uid='$new_uid', uid_idx='$usr_idx', gid='wheel'");
508
    
509
	DBQueryFatal("insert into unixgroup_membership set ".
510
		     "uid='$new_uid', uid_idx='$usr_idx', gid='$TBADMINGROUP'");
511
	
Leigh Stoller's avatar
Leigh Stoller committed
512 513
	# The web interface requires this line to be printed!
	print "User $usr_uid/$usr_idx has been created\n";
514 515
	exit(0);
    }
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
}

#
# 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",
554
	 "Bcc: $TBAUDIT")
555
    if (!($silent || defined($portal)));
556 557 558 559 560

#
# Do we have a keyfile? If so, rerun addpubkey for real now that the
# user is created and email is sent.
#
561
if (@keyfiles) {
562
    # Set the implied user for addpubkey.
Leigh Stoller's avatar
Leigh Stoller committed
563
    $ENV{'HTTP_INVOKING_USER'} = $usr_idx;
564 565 566 567 568 569 570 571 572 573 574
    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);
    }
575 576 577
}

# The web interface requires this line to be printed!
Leigh Stoller's avatar
Leigh Stoller committed
578
print "User $usr_uid/$usr_idx has been created\n";
579 580 581 582 583
exit(0);

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

584 585 586 587 588
    if (@keyfiles && !$debug) {
	foreach my $keyfile (@keyfiles) {
	    unlink($keyfile)
	}
    }
589 590 591 592 593 594 595 596

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

597 598 599 600 601
    if (@keyfiles && !$debug) {
	foreach my $keyfile (@keyfiles) {
	    unlink($keyfile)
	}
    }
602 603 604 605 606 607 608 609 610

    print $mesg;
    exit(1);
}

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

611
    $str =~ s/[^[:alnum:]]/\\$&/g;
612 613 614 615 616
    return $str;
}