newuser.in 14.8 KB
Newer Older
1
#!/usr/bin/perl -w
2
#
3
# Copyright (c) 2000-2016 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 Stoller's avatar
Leigh 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;
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109

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

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

178 179 180 181 182 183 184 185 186 187
#
# 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",
188 189
		        "affiliation"	=> "usr_affil",
		        "affiliation_abbreviation" => "usr_affil_abbrev");
190 191
if ($type eq "wikionly") {
    %optional = (%optional, %usually_required);
192 193
}
elsif ($type ne "nonlocal") {
194 195 196
    %required = (%required, %usually_required);
}

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

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

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

213
# APT flag. Notice and delete.
214 215 216 217 218 219
if (exists($xmlparse->{'attribute'}->{"portal"})) {
    $portal = $xmlparse->{'attribute'}->{"portal"}->{'value'};
    delete($xmlparse->{'attribute'}->{"portal"});
    if (! ($portal eq "aptlab" || $portal eq "cloudlab" || 
	   $portal eq "phantomnet" || $portal eq "emulab")) {
	fatal("Bad portal: $portal");
220
    }
221 222 223 224 225 226 227 228 229
    # 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"});
}

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

#
# 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'};
252 253 254
    if (!defined($value)) {	# Empty string comes from XML as an undef value.
	$xmlparse->{'attribute'}->{"$key"}->{'value'} = $value = "";
    }
255 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

    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!")
303
	if (User->Lookup($newuser_args{'uid'}));
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
    
    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!")
322 323
	if (exists($newuser_args{'wikiname'}) &&
	    User->LookupByWikiName($newuser_args{'wikiname'}));
324 325 326 327 328 329
}

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

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

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

367 368 369 370
#
# Check the passphrase if supplied.
#
if (exists($xmlparse->{'attribute'}->{'passphrase'}) &&
371
    $xmlparse->{'attribute'}->{'passphrase'}->{'value'} ne "") {
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
    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;
}

392 393 394 395
#
# 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.
#
396 397
if (exists($xmlparse->{'attribute'}->{'pubkey'}) ||
    exists($xmlparse->{'pubkeys'})) {
398

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

403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
    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);
    }
422 423 424 425 426 427
}

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

431 432 433 434 435 436
my $new_uid;

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

#
# 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;
}
456 457
elsif ($type eq "nonlocal") {
    $flags = $User::NEWUSER_FLAGS_NONLOCAL;
458
}
459 460 461 462
my $newuser = User->Create($new_uid, $flags, \%newuser_args);
if (!defined($newuser)) {
    fatal("Could not create new user!");
}
463
if (defined($portal)) {
464 465
    $newuser->SetStatus(USERSTATUS_UNAPPROVED());
}
Leigh Stoller's avatar
Leigh Stoller committed
466 467 468 469 470 471
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();
	    
472 473 474 475 476 477 478 479
#
# 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.
    #
480 481 482
    if ($firstinitstate eq "createproject") {
	DBQueryFatal("update users set ".
		     " admin=1,status='". $User::USERSTATUS_UNAPPROVED . "' " .
483
		     "where uid_idx='$usr_idx'");
484

485
	DBQueryFatal("insert into unixgroup_membership set ".
486
		     "uid='$new_uid', uid_idx='$usr_idx', gid='wheel'");
487
    
488
	DBQueryFatal("insert into unixgroup_membership set ".
489
		     "uid='$new_uid', uid_idx='$usr_idx', gid='$TBADMINGROUP'");
490
	
Leigh Stoller's avatar
Leigh Stoller committed
491 492
	# The web interface requires this line to be printed!
	print "User $usr_uid/$usr_idx has been created\n";
493 494
	exit(0);
    }
495 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
}

#
# 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",
533
	 "Bcc: $TBAUDIT")
534
    if (!($silent || defined($portal)));
535 536 537 538 539

#
# Do we have a keyfile? If so, rerun addpubkey for real now that the
# user is created and email is sent.
#
540
if (@keyfiles) {
541
    # Set the implied user for addpubkey.
Leigh Stoller's avatar
Leigh Stoller committed
542
    $ENV{'HTTP_INVOKING_USER'} = $usr_idx;
543 544 545 546 547 548 549 550 551 552 553
    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);
    }
554 555 556
}

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

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

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

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

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

    print $mesg;
    exit(1);
}

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

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