moduserinfo.in 13.7 KB
Newer Older
1 2 3
#!/usr/bin/perl -wT
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2000-2012 University of Utah and the Flux Group.
5 6 7 8 9 10 11 12 13 14 15 16 17
# All rights reserved.
#
use English;
use strict;
use Getopt::Std;
use XML::Simple;
use Data::Dumper;

#
# Change the user profile from a XML description.
#
sub usage()
{
18
    print("Usage: moduserinfo [-d] [-v] [-u <uid>] <xmlfile>\n");
19 20
    exit(-1);
}
21
my $optlist = "dvu:s";
22
my $debug   = 0;
23 24 25 26
my $verify  = 0;	# Check data and return status only.
my $silent  = 0;	# No email.
my $uidopt;		# Use -u to override uid in the xml. 
my @keyfiles = ();
27 28 29 30 31 32 33 34

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS       = "@TBOPSEMAIL@";
my $TBAUDIT	= "@TBAUDITEMAIL@";
my $checkpass   = "$TB/libexec/checkpass";
35
my $addpubkey   = "$TB/sbin/addpubkey";
36 37 38 39 40 41 42 43 44 45 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

#
# 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;

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

#
# 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;
}
if (defined($options{"v"})) {
    $verify = 1;
}
76 77 78 79 80 81
if (defined($options{"s"})) {
    $silent = 1;
}
if (defined($options{"u"})) {
    $uidopt = $options{"u"};
}
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
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 the
# current user context is "implied" (see tbauth.php3).
#
my $this_user;

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

    if (! defined($this_user)) {
	fatal("You ($UID) do not exist!");
    }
    # You don't need admin privileges to manage your own profile.
}
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.
    my $translated = `realpath $xmlfile`;
    if ($translated =~ /^(\/tmp\/[-\w\.\/]+)$/) {
	$xmlfile = $1;
    }
    else {
	fatal("Bad data in translated pathname: $xmlfile");
    }

    # The web interface (and in the future the xmlrpc interface) sets this.
    $this_user = User->ImpliedUser();

    if (! defined($this_user)) {
	fatal("Cannot determine implied user!");
    }
}

#
# These are the fields that we allow to come in from the XMLfile.
#
my $SLOT_OPTIONAL	= 0x1;	# The field is not required.
my $SLOT_REQUIRED	= 0x2;  # The field is required and must be non-null.
my $SLOT_ADMINONLY	= 0x4;  # Only admins can set this field.
137 138
my $SLOT_SKIP		= 0x8;  # Handled specially so skip

139 140 141 142 143 144
#
# XXX We should encode all of this in the DB so that we can generate the
# forms on the fly, as well as this checking code.
#
my %xmlfields =
    # XML Field Name        DB slot name         Flags             Default
145
    ("uid"		=> ["uid_idx",		$SLOT_REQUIRED],
146 147 148 149 150

     # The rest are optional, so we can skip passing ones that are not changing.
     "usr_name"		=> ["usr_name",		$SLOT_OPTIONAL],
     "usr_title"	=> ["usr_title",	$SLOT_OPTIONAL],
     "usr_affil"	=> ["usr_affil",	$SLOT_OPTIONAL],
151
     "usr_affil_abbrev"	=> ["usr_affil_abbrev",	$SLOT_OPTIONAL],
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
     "usr_shell"	=> ["usr_shell",	$SLOT_OPTIONAL],
     "usr_URL"		=> ["usr_URL",		$SLOT_OPTIONAL],
     "usr_email"	=> ["usr_email",	$SLOT_OPTIONAL],
     "usr_addr"		=> ["usr_addr",		$SLOT_OPTIONAL],
     "usr_addr2"	=> ["usr_addr2",	$SLOT_OPTIONAL],
     "usr_city"		=> ["usr_city",		$SLOT_OPTIONAL],
     "usr_state"	=> ["usr_state",	$SLOT_OPTIONAL],
     "usr_zip"		=> ["usr_zip",		$SLOT_OPTIONAL],
     "usr_country"	=> ["usr_country",	$SLOT_OPTIONAL],
     "usr_phone"	=> ["usr_phone",	$SLOT_OPTIONAL],
     "password1"	=> ["password1",	$SLOT_OPTIONAL],
     "password2"	=> ["password2",	$SLOT_OPTIONAL],
     "w_password1"	=> ["w_password1",	$SLOT_OPTIONAL],
     "w_password2"	=> ["w_password2",	$SLOT_OPTIONAL],
     "user_interface"	=> ["user_interface",	$SLOT_OPTIONAL],
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
     "pubkeys"		=> ["pubkeys",		$SLOT_SKIP],
     "wikiname"		=> ["pubkeys",		$SLOT_SKIP],
     # These are alternates.
     "name"		=> ["usr_name",		$SLOT_OPTIONAL],
     "title"	        => ["usr_title",	$SLOT_OPTIONAL],
     "affiliation"	=> ["usr_affil",	$SLOT_OPTIONAL],
     "affiliation_abbreviation"	=> ["usr_affil_abbrev",	$SLOT_OPTIONAL],
     "shell"		=> ["usr_shell",	$SLOT_OPTIONAL],
     "URL"		=> ["usr_URL",		$SLOT_OPTIONAL],
     "email"		=> ["usr_email",	$SLOT_OPTIONAL],
     "address"		=> ["usr_addr",		$SLOT_OPTIONAL],
     "address2"		=> ["usr_addr2",	$SLOT_OPTIONAL],
     "city"		=> ["usr_city",		$SLOT_OPTIONAL],
     "state"		=> ["usr_state",	$SLOT_OPTIONAL],
     "zip"		=> ["usr_zip",		$SLOT_OPTIONAL],
     "country"		=> ["usr_country",	$SLOT_OPTIONAL],
     "phone"		=> ["usr_phone",	$SLOT_OPTIONAL],
184
     "notes"		=> ["notes",		$SLOT_OPTIONAL],
185
    );
186

187 188 189 190
#
# Must wrap the parser in eval since it exits on error.
#
my $xmlparse = eval { XMLin($xmlfile,
191
			    ForceArray => ["pubkeys"],
192 193 194 195 196 197 198 199 200 201 202 203 204
			    VarAttr => 'name',
			    ContentKey => '-content',
			    SuppressEmpty => undef); };
fatal($@)
    if ($@);

#
# Process and dump the errors (formatted for the web interface).
# We should probably XML format the errors instead but not sure I want
# to go there yet.
#
my %errors = ();

205 206 207 208 209 210
# Insert the user override.
if (defined($uidopt)) {
    $xmlparse->{'attribute'}->{"uid"} = {};
    $xmlparse->{'attribute'}->{"uid"}->{"value"} = $uidopt;
}

211 212 213
#
# Make sure all the required arguments were provided.
#
214 215
my $key;
foreach $key (keys(%xmlfields)) {
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
    my (undef, $required, undef) = @{$xmlfields{$key}};

    $errors{$key} = "Required value not provided"
	if ($required & $SLOT_REQUIRED  &&
	    ! exists($xmlparse->{'attribute'}->{"$key"}));
}
UserError()
    if (keys(%errors));

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

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
#
# Wildcard keys have one or more *'s in them like simple glob patterns.
# This allows multiple key instances for categories of attributes, and
# putting a "type signature" in the key for arg checking, as well.
#
# Wildcards are made into regex's by anchoring the ends and changing each * to
# a "word" (group of alphahumeric.)  A tail * means "the rest", allowing
# multiple words separated by underscores or dashes.
#
my $wordpat = '[a-zA-Z0-9]+';
my $tailpat = '[-\w]+';
my %wildcards;
foreach $key (keys(%xmlfields)) {
    if (index($key, "*") >= 0) {
	my $regex = '^' . $key . '$';
	$regex =~ s/\*\$$/$tailpat/;
	$regex =~ s/\*/$wordpat/g;
	$wildcards{$key} = $regex;
    }
}
# Key ordering is lost in a hash.
# Put longer matching wildcard keys before their prefix.
my @wildkeys = reverse(sort(keys(%wildcards)));

foreach $key (keys(%{ $xmlparse->{'attribute'} })) {
256
    my $value = $xmlparse->{'attribute'}->{"$key"}->{'value'};
257 258 259
    if (!defined($value)) {	# Empty string comes from XML as an undef value.
	$xmlparse->{'attribute'}->{"$key"}->{'value'} = $value = "";
    }
260

261 262 263 264 265 266
    print STDERR "User attribute: '$key' -> '$value'\n"
	if ($debug);

    my $field = $key;
    my $wild;
    if (!exists($xmlfields{$key})) {
267

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
	# Not a regular key; look for a wildcard regex match.
        foreach my $wildkey (@wildkeys) {
	    my $regex = $wildcards{$wildkey};
	    if ($wild = $key =~ /$regex/) {
		$field = $wildkey;
		print STDERR "Wildcard: '$key' matches '$wildkey'\n"
		    if ($debug);
		last; # foreach $wildkey
	    }
	}
	if (!$wild) {
	    $errors{$key} = "Unknown attribute";
	    next; # foreach $key
	}
    }
283

284
    my ($dbslot, $required, $default) = @{$xmlfields{$field}};
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306

    if ($required & $SLOT_REQUIRED) {
	# A slot that must be provided, so do not allow a null value.
	if (!defined($value)) {
	    $errors{$key} = "Must provide a non-null value";
	    next;
	}
    }
    if ($required & $SLOT_OPTIONAL) {
	# Optional slot. If value is null skip it. Might not be the correct
	# thing to do all the time?
	if (!defined($value)) {
	    next
		if (!defined($default));
	    $value = $default;
	}
    }
    if ($required & $SLOT_ADMINONLY) {
	# Admin implies optional, but thats probably not correct approach.
	$errors{$key} = "Administrators only"
	    if (! $this_user->IsAdmin());
    }
307 308
    next
	if ($required & $SLOT_SKIP);
309 310
	
    # Now check that the value is legal.
311 312
    if (! TBcheck_dbslot($value, "users",
			 $dbslot, TBDB_CHECKDBSLOT_ERROR)) {
313 314 315 316
	$errors{$key} = TBFieldErrorString();
	next;
    }

317
    $moduserinfo_args{$key} = $value;
318 319 320 321 322 323 324 325 326 327
}
UserError()
    if (keys(%errors));

#
# Now do special checks.
#
my $target_uid = $moduserinfo_args{"uid"};
my $target_user = User->Lookup($target_uid);
if (!defined($target_user)) {
328
    UserError("uid: No such user ($target_uid)");
329 330 331 332
}
if (!$target_user->AccessCheck($this_user, TB_USERINFO_MODIFYINFO())) {
    UserError("UserInfo: Not enough permission");
}
333
my $target_name  = $target_user->name();
334
my $target_email = $target_user->email();
335 336
my $target_idx   = $target_user->uid_idx();
$target_uid = $target_user->uid();
337 338

# Make sure the user name has at least two tokens!
Russ Fish's avatar
Russ Fish committed
339
if (exists($moduserinfo_args{"usr_name"}) &&
340 341 342 343
    $moduserinfo_args{"usr_name"} !~ /\S\s+\S/) {
    UserError("FullName: Please provide a first and last name");
}

Russ Fish's avatar
Russ Fish committed
344
if (exists($moduserinfo_args{"URL"})) {
345 346 347
    if ($moduserinfo_args{"URL"} !~ /^http:\/\//) {
	UserError("URL: malformed - Must begin with http://");
    }
Russ Fish's avatar
Russ Fish committed
348
    if ($moduserinfo_args{"URL"} =~ /\s/) {
349 350 351 352
	UserError("URL: malformed - Spaces are not allowed.");
    }
}

Russ Fish's avatar
Russ Fish committed
353
if (exists($moduserinfo_args{"usr_email"})) {
354 355 356 357 358 359
    my $temp_user = User->LookupByEmail($moduserinfo_args{"usr_email"});
    if ($temp_user && !$target_user->SameUser($temp_user)) {
	UserError("EmailAddress: Already in use by another user!");
    }
}

Russ Fish's avatar
Russ Fish committed
360 361 362 363 364 365 366
my $is_pwd1 = exists($moduserinfo_args{"password1"});
my $is_pwd2 = exists($moduserinfo_args{"password2"});
if ($is_pwd1 || $is_pwd2) {
    my $pwd1 = $moduserinfo_args{"password1"};
    my $pwd2 = $moduserinfo_args{"password2"};
    if (($is_pwd1 && $pwd1 ne "") xor ($is_pwd2 && $pwd2 ne "")) {
	UserError("Password: must confirm");
367
    }
Russ Fish's avatar
Russ Fish committed
368 369 370 371 372 373 374 375
    if ($is_pwd1 && $is_pwd2) {
	if ($pwd1 ne $pwd2) {
	    UserError("Password: Two passwords do not match");
	}
	if ($pwd2) {
	    CheckPassword("", $target_uid, $pwd2, 
			  $target_name, $target_email);
	}
376 377 378 379 380
    }
}

# We often get the previous Windows password without a confirmation,
# because it is shown in the form input field.
Russ Fish's avatar
Russ Fish committed
381 382 383 384 385 386 387 388 389 390 391 392 393
my $is_w_pwd1 = exists($moduserinfo_args{"w_password1"});
my $is_w_pwd2 = exists($moduserinfo_args{"w_password2"});
if ($is_pwd1 || $is_pwd2) {
    my $w_pwd1 = $moduserinfo_args{"w_password1"};
    my $w_pwd2 = $moduserinfo_args{"w_password2"};
    if ($is_w_pwd1 && $is_w_pwd2) {
	if ($w_pwd2 ne "" && $w_pwd1 ne $w_pwd2) {
	    UserError("WindowsPassword: Two passwords do not match");
	}
	if ($w_pwd2) {
	    CheckPassword("Windows", $target_uid, $w_pwd2, 
			  $target_name, $target_email);
	}
394 395 396
    }
}

Russ Fish's avatar
Russ Fish committed
397 398 399 400 401 402
if (exists($moduserinfo_args{"user_interface"})) {
    my $ui = $moduserinfo_args{"user_interface"};
    if ($ui && $ui ne TBDB_USER_INTERFACE_EMULAB &&
	$ui ne TBDB_USER_INTERFACE_PLAB) {
	UserError("UserInterface: Invalid");
    }
403 404
}

405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
#
# Do a check on the pubkeys if supplied. The safest thing to do is generate
# a temporary file and pass that to addpubkey to check.
#
if (exists($xmlparse->{'pubkeys'})) {
    my @keys = @{ $xmlparse->{'pubkeys'} };

    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);
    }
}

433 434 435 436 437 438 439 440 441 442 443 444 445 446
exit(0)
    if ($verify);

#
# Now safe to make the changes.
#
my $usrerr;
my $mod_val = User->ModUserInfo($this_user, $target_user,
				\%moduserinfo_args, \$usrerr);
UserError($usrerr)
    if (defined($usrerr));
fatal("Could not modify user profile!")
    if (!defined($mod_val));

447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
#
# Do we have a keyfile? If so, rerun addpubkey for real now that the
# user is created and email is sent.
#
if (@keyfiles) {
    $target_user->DeleteSSHKeys();
    my $opt = ($silent ? "-s" : "");
    
    # Set the implied user for addpubkey.
    $ENV{'HTTP_INVOKING_USER'} = $target_idx;

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

469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
exit(0);

sub fatal($)
{
    my ($mesg) = @_;

    print STDERR "*** $0:\n".
	         "    $mesg\n";
    # Exit with negative status so web interface treats it as system error.
    exit(-1);
}

sub UserError(;$)
{
    my ($mesg) = @_;

    if (keys(%errors)) {
	foreach my $key (keys(%errors)) {
	    my $val = $errors{$key};
	    print "${key}: $val\n";
	}
    }
    print "$mesg\n"
	if (defined($mesg));

    # Exit with positive status so web interface treats it as user error.
    exit(1);
}

sub CheckPassword($$$$$)
{
    my ($prefix, $uid, $password, $name, $email) = @_;
    my $checkpass_args = escapeshellarg($password)
	. " " . $uid . " " . escapeshellarg($name . ":" . $email);
Leigh Stoller's avatar
Leigh Stoller committed
503 504 505 506 507

    # Make taint check happy.
    if ($checkpass_args =~ /^(.*)$/) {
	$checkpass_args = $1;
    }
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
    my $pwokay = `$checkpass $checkpass_args`;
    if ($?) {
	chomp($pwokay);
	if (! ($pwokay =~ /^ok$/)) {
	    UserError("$prefix$pwokay");
	}
	fatal("Checkpass failed with $?");
    }
}

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

    $str =~ s/[^[:alnum:]]/\\$&/g;
    return $str;
}