tbacct.in 29.7 KB
Newer Older
1 2 3
#!/usr/bin/perl -wT

#
4
# Copyright (c) 2000-2018 University of Utah and the Flux Group.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# 
# {{{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/>.
# 
# }}}
24 25 26
#
use English;
use Getopt::Std;
27

28 29 30 31 32 33 34 35 36
#
# Deal with user accounts. This script does not deal with group stuff.
# Just add/del/mod/passwd/freeze/thaw/ stuff. We do give users an
# initial group of course, which will be guest if not in any groups.
#
# This script is setuid. We farm stuff out to subscripts though, and need
# to be wary of what the UID/EUID is when those scripts are invoked. The
# subscripts are not generally setuid, but of course the web interface
# allows users to do things on behalf of other users, and we want to track
37
# that in the audit log.
38
#
39 40 41
# Use -u for update mode, which skips the checks on current status,
# and forces the target user into that state. Eventually, this should
# be the default mode of operation (independent of web interface).
42
#
43 44
sub usage()
{
45
    print("Usage: tbacct [-f] [-b] [-u] [-v] ".
46
	  "<add|del|mod|passwd|wpasswd|email|freeze|thaw|verify|revoke|dots|deactivate|reactivate> ".
47
	  "<user> [args]\n");
48 49
    exit(-1);
}
50
my $optlist = "fbuvs";
51 52
my $force   = 0;
my $batch   = 0;
53
my $update  = 0;
54
my $verified= 0;
55
my $silent  = 0;
56 57 58 59 60 61 62

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS	= "@TBOPSEMAIL@";
my $TBLOGS	= "@TBLOGSEMAIL@";
63
my $TBAUDIT	= "@TBAUDITEMAIL@";
64 65
my $CONTROL	= "@USERNODE@";
my $BOSSNODE	= "@BOSSNODE@";
66
my $WINSUPPORT  = @WINSUPPORT@;
67
my $WITHZFS     = @WITHZFS@;
68
my $ZFS_NOEXPORT= @ZFS_NOEXPORT@;
69
my $WIKISUPPORT = @WIKISUPPORT@;
70
my $TRACSUPPORT = @TRACSUPPORT@;
71
my $BUGDBSUPPORT= @BUGDBSUPPORT@;
72
my $OPSDBSUPPORT= @OPSDBSUPPORT@;
73
my $CHATSUPPORT = @CHATSUPPORT@;
74
my $MAILMANSUPPORT= @MAILMANSUPPORT@;
75
my $EXPIRE_PASSWORDS = @EXPIRE_PASSWORDS@;
76
my $THISHOMEBASE= "@THISHOMEBASE@";
77
my $PROTOUSER   = 'elabman';
78
my $ELABINELAB  = @ELABINELAB@;
79
my $PGENISUPPORT= @PROTOGENI_SUPPORT@;
80
my $GENIRACK    = @PROTOGENI_GENIRACK@;
81

82 83 84
my $SAMBANODE	= "fs";  # DNS makes this do the right thing in E-in-E.
my $SMBPASSWD	= "/usr/local/bin/smbpasswd";

85 86 87 88 89 90
my $USERPATH	= "$TB/bin";
my $ADDKEY	= "$TB/sbin/addpubkey";
my $USERADD	= "/usr/sbin/pw useradd";
my $USERDEL	= "/usr/sbin/pw userdel";
my $USERMOD	= "/usr/sbin/pw usermod";
my $CHPASS	= "/usr/bin/chpass";
91
my $ACCOUNTPROXY= "$TB/sbin/accountsetup";
92
my $GENELISTS	= "$TB/sbin/genelists";
93
my $MKUSERCERT	= "$TB/sbin/mkusercert";
94
my $PBAG	= "$TB/sbin/paperbag";
95
my $EXPORTSSETUP= "$TB/sbin/exports_setup";
96 97
my $ADDWIKIUSER = "$TB/sbin/addwikiuser";
my $DELWIKIUSER = "$TB/sbin/delwikiuser";
98 99
my $ADDTRACUSER = "$TB/sbin/tracuser";
my $DELTRACUSER = "$TB/sbin/tracuser -r";
100 101
my $ADDBUGDBUSER= "$TB/sbin/addbugdbuser";
my $DELBUGDBUSER= "$TB/sbin/delbugdbuser";
102 103
my $ADDCHATUSER = "$TB/sbin/addjabberuser";
my $DELCHATUSER = "$TB/sbin/deljabberuser";
104 105 106
my $MMMODIFYUSER= "$TB/sbin/mmmodifymember";
my $ADDMMUSER   = "$TB/sbin/addmmuser";
my $DELMMUSER   = "$TB/sbin/delmmuser";
107
my $OPSDBCONTROL= "$TB/sbin/opsdb_control";
108
my $ADDHOOK     = "$TB/sbin/adduserhook";
109
my $SETGROUPS   = "$TB/sbin/setgroups";
110
my $NOLOGIN	= "/sbin/nologin";
111
my $POSTCRL     = "$TB/sbin/protogeni/postcrl";
112
my $SSH		= "$TB/bin/sshtb";
113 114 115
my $SAVEUID	= $UID;
my $NOSUCHUSER  = 67;
my $USEREXISTS  = 65;
116 117
# Nasty. Should do this with /etc/pw.conf shellpath.
my %shellpaths  = ("csh"  => "/bin/csh", "sh" => "/bin/sh",
118
		   "tcsh" => "/bin/tcsh", "bash" => "/usr/local/bin/bash",
119 120
		   "zsh" => "/usr/local/bin/zsh",
		   "nologin" => "/usr/sbin/nologin");
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136

my $errors      = 0;
my @row;
my $query_result;

#
# We don't want to run this script unless its the real version.
#
if ($EUID != 0) {
    die("*** $0:\n".
	"    Must be setuid! Maybe its a development version?\n");
}

#
# This script is setuid, so please do not run it as root. Hard to track
# what has happened.
137
#
138 139 140 141 142 143 144
if ($UID == 0) {
    die("*** $0:\n".
	"    Please do not run this as root! Its already setuid!\n");
}

#
# Untaint the path
145
#
146 147 148 149 150 151 152 153 154
$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;

#
155
# Load the Testbed support stuff.
156 157 158 159 160
#
use lib "@prefix@/lib";
use libaudit;
use libdb;
use libtestbed;
161
use User;
162
use Project;
163
use emutil;
164

165 166 167 168 169 170 171 172 173 174
#
# Function prototypes
#
sub AddUser();
sub DelUser();
sub UpdatePassword();
sub UpdateWindowsPassword();
sub UpdateUser(;$);
sub FreezeUser();
sub ThawUser();
175 176
sub DeactivateUser();
sub ReactivateUser();
177
sub VerifyUser();
178
sub UpdateEmail();
179
sub CheckDotFiles();
180
sub RevokeUser();
181 182
sub fatal($);

183 184
my $HOMEDIR	= USERROOT();

185 186 187
#
# Rewrite audit version of ARGV to prevent password in mail logs.
#
188
if (scalar(@ARGV) == 3 && $ARGV[0] eq "passwd") {
189 190 191 192 193 194
    my @NEWARGV = @ARGV;

    $NEWARGV[scalar(@NEWARGV) - 1] = "**********";
    AuditSetARGV(@NEWARGV);
}

195 196 197 198 199 200 201 202 203 204 205
#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
%options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (defined($options{"f"})) {
    $force = 1;
}
206 207 208
if (defined($options{"b"})) {
    $batch = 1;
}
209 210 211
if (defined($options{"u"})) {
    $update = 1;
}
212 213 214
if (defined($options{"v"})) {
    $verified = 1;
}
215 216 217
if (defined($options{"s"})) {
    $silent = 1;
}
218
if (@ARGV < 2) {
219 220
    usage();
}
221 222
my $cmd  = shift(@ARGV);
my $user = shift(@ARGV);
223 224 225 226

#
# Untaint the arguments.
#
227
if ($user =~ /^([-\w]+)$/i) {
228 229 230 231 232
    $user = $1;
}
else {
    die("Tainted argument: $user\n");
}
233
if ($cmd =~
234
    /^(add|del|mod|freeze|passwd|wpasswd|thaw|email|verify|revoke|dots|deactivate|reactivate)$/) {
235 236 237 238 239 240 241 242 243 244 245
    $cmd = $1;
}
else {
    usage();
}

# Only admins can use force mode.
if ($force && ! TBAdmin($UID)) {
    fatal("Only admins can use force mode!");
}

246 247 248 249 250 251
# Map target user to object.
my $target_user = User->Lookup($user);
if (! defined($target_user)) {
    fatal("$user does not exist!");
}

252 253 254 255 256 257 258 259 260
#
# Map invoking user to object. 
# If invoked as "nobody" its for a user with no actual account, and so
# just set the current user to that user. If we make any callouts it will
# fail (verbosely of course).
#
my $this_user;

if (getpwuid($UID) eq "nobody") {
261 262
    # The web interface sets this.
    $this_user = User->ImpliedUser();
263 264 265 266
    # This can happen using the forget password link; user not logged in.
    if (!defined($this_user)) {
	$this_user = $target_user;
    }
Leigh Stoller's avatar
Leigh Stoller committed
267
}
268
else {
269
    $this_user = User->ThisUser();
270 271 272 273

    if (! defined($this_user)) {
	fatal("You ($UID) do not exist!");
    }
274 275
}

276 277 278
#
# This script is always audited. Mail is sent automatically upon exit.
#
279
if (!$silent && AuditStart(0)) {
280 281 282 283 284 285 286 287 288
    #
    # Parent exits normally
    #
    exit(0);
}

#
# Get the user info (the user being operated on).
#
289
my $dbid        = $target_user->dbid();
290 291 292 293 294 295 296 297 298 299
my $pswd        = $target_user->pswd();
my $user_number = $target_user->unix_uid();
my $fullname    = $target_user->name();
my $user_email  = $target_user->email();
my $status      = $target_user->status();
my $webonly     = $target_user->webonly();
my $usr_shell   = $target_user->shell();
my $usr_admin   = $target_user->admin();
my $wpswd       = $target_user->w_pswd();
my $wikionly    = $target_user->wikionly();
300 301
my $isnonlocal  = $target_user->IsNonLocal();
my $nocollabtools = $target_user->nocollabtools();
302 303
$usr_shell = "nologin"
    if (!defined($usr_shell));
304 305 306 307 308 309

#
# Get the users earliest project membership to use as the default group
# for the case that the account is being (re)created. We convert that to
# the unix info.
#
310
my $firstproject;
311 312 313
my $default_groupname;
my $default_groupgid;

314 315 316
if ($target_user->FirstApprovedProject(\$firstproject) < 0) {
    fatal("Could not determine first approved project for $target_user");
}
317

318 319 320
if (defined($firstproject)) {
    $default_groupname = $firstproject->unix_name();
    $default_groupgid  = $firstproject->unix_gid();
321 322 323
}
else {
    print "No group membership for $user; using the guest group!\n";
324

325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
    ($default_groupname,undef,$default_groupgid,undef) = getgrnam("guest");
}

#
# Now dispatch operation.
#
SWITCH: for ($cmd) {
    /^add$/ && do {
	AddUser();
	last SWITCH;
    };
    /^del$/ && do {
	DelUser();
	last SWITCH;
    };
    /^passwd$/ && do {
	UpdatePassword();
	last SWITCH;
    };
344 345 346 347
    /^wpasswd$/ && do {
	UpdateWindowsPassword();
	last SWITCH;
    };
348 349 350 351
    /^email$/ && do {
	UpdateEmail();
	last SWITCH;
    };
352 353 354 355 356 357 358 359 360 361 362 363
    /^mod$/ && do {
	UpdateUser();
	last SWITCH;
    };
    /^freeze$/ && do {
	FreezeUser();
	last SWITCH;
    };
    /^thaw$/ && do {
	ThawUser();
	last SWITCH;
    };
364 365 366 367 368 369 370 371
    /^deactivate$/ && do {
	DeactivateUser();
	last SWITCH;
    };
    /^reactivate$/ && do {
	ReactivateUser();
	last SWITCH;
    };
372 373 374 375
    /^revoke$/ && do {
	RevokeUser();
	last SWITCH;
    };
376 377 378 379
    /^verify$/ && do {
	VerifyUser();
	last SWITCH;
    };
380 381 382 383
    /^dots$/ && do {
	CheckDotFiles();
	last SWITCH;
    };
384 385 386 387 388 389 390
}

#
# Now schedule account updates on all the nodes that this person has
# an account on.
#
TBNodeUpdateAccountsByUID($user);
391 392 393 394
if ($PGENISUPPORT) {
    require APT_Utility;
    APT_Utility::UpdateInstancesByUser($target_user);
}
395 396 397 398 399 400 401 402 403 404 405

exit(0);

#
# Add new user.
#
sub AddUser()
{
    #
    # Check status. Only active users get accounts built.
    #
406
    if ($webonly || $wikionly || $status ne USERSTATUS_ACTIVE) {
407 408 409
	if ($webonly) {
	    return 0;
	}
410 411 412 413 414 415 416
	#
	# Allow for users to be initialized to frozen in an inner Emulab.
	#
	if ($ELABINELAB && $status eq USERSTATUS_FROZEN) {
	    print STDERR "Ignoring frozen user in elabinelab\n";
	    return 0;
	}
417 418 419 420 421 422 423
	if ($wikionly) {
	    $EUID = $UID;

	    # And to the wiki if enabled.
	    system("$ADDWIKIUSER $user")
		if ($WIKISUPPORT && !$batch);
	    
424 425 426 427
	    # And to the bugdb if enabled.
	    system("$ADDBUGDBUSER $user")
		if ($BUGDBSUPPORT && !$batch);
	    
428 429 430
	    $EUID = 0;
	    return 0;
	}
431 432 433 434
	if ($force) {
	    $target_user->SetStatus(USERSTATUS_ACTIVE());
	    $status = USERSTATUS_ACTIVE();
	}
435 436 437 438
	else {
	    fatal("$user is not active! ".
		  "Cannot build an account! Use -f option.");
	}
439
    }
440

441 442 443
    $UID = 0;
    if (system("egrep -q -s '^${user}:' /etc/passwd")) {
	print "Adding user $user ($user_number) to local node.\n";
444

445 446
	if (runBusyLoop("$USERADD $user -u $user_number -c \"$fullname\" ".
			"-h - -d $HOMEDIR/$user ".
447 448 449 450 451 452 453 454 455 456 457
		   "-g $default_groupname -s $PBAG")) {
	    fatal("Could not add user $user to local node.");
	}
    }

    #
    # Quote special chars for ssh and the shell on the other side
    #
    $fullname =~ s/\"/\'/g;
    $fullname =~ s/([^\\])([\'\"\(\)])/$1\\$2/g;

458
    if (1) {
459 460 461
	print "Adding user $user ($user_number) to $CONTROL.\n";

	if (system("$SSH -host $CONTROL ".
462 463 464 465
		   "'$ACCOUNTPROXY adduser $user $user_number \"$fullname\" ".
		   "$HOMEDIR/$user $default_groupname ".
		   "$shellpaths{$usr_shell}'")) {
	    if ($?) {
466 467 468
		fatal("Could not add user $user ($user_number) to $CONTROL.");
	    }
	}
469

470 471 472
	#
	# Leave the password "starred" on elabinelab; safer.
	#
473
	if (!$ELABINELAB || $GENIRACK) {
474 475 476 477 478
	    # shell escape.
	    $pswd =~ s/\$/\\\$/g;
	    $pswd =~ s/\*/\\\*/g;

	    print "Initializing user $user password on $CONTROL.\n";
479 480
	    if (system("$SSH -host $CONTROL ".
		       "  \"$ACCOUNTPROXY chpass $user '$pswd'\"")) {
481 482
		fatal("Could not initialize password for $user on $CONTROL!");
	    }
483
	}
484 485 486 487 488 489 490 491 492 493

	#
	# Extra hook added for CMU. Generalize later.
	#
	if ($THISHOMEBASE =~ /^cmuemulab$/i) {
	    print "Running post create hook for user $user on $CONTROL.\n";

	    # Do not worry about failure. 
	    system("$SSH -host $CONTROL $ADDHOOK $user");
	}
494
    }
495 496 497
    $UID  = $SAVEUID;
    $EUID = $UID;

498
    if (0 && $WITHZFS) {
499 500 501 502 503 504 505 506 507 508
	if ($ZFS_NOEXPORT) {
	    #
	    # Have to force the new directories to be exported.
	    # See ZFS code in exports_setup
	    #
	    $target_user->BumpActivity();
	    system($EXPORTSSETUP) == 0 or
		fatal("$EXPORTSSETUP failed");
	}
	
509
	#
510
	# There is some lag before the automounter can mount the new volume.
511
	#
512
	if (emutil::waitForMount("$HOMEDIR/$user") < 0) {
513 514 515
	    fatal("Could not access new user directory");
	}
    }
516 517

    #
518
    # Do the ssh thing.
519
    #
520
    if ($user ne $PROTOUSER && system("$ADDKEY -i $user")) {
521 522
	fatal("Could not generate initial ssh key for $user");
    }
523 524 525

    #
    # And the mailman lists if enabled. All users must get this cause
Leigh Stoller's avatar
Leigh Stoller committed
526
    # mailman is used for project mail lists when MAILMANSUPPORT=1.
527 528 529 530
    #
    system("$ADDMMUSER $user")
	if ($MAILMANSUPPORT);
    
531 532 533
    # Generate the SSL cert for the user.
    system("$MKUSERCERT $user");

534 535 536 537 538
    if ($isnonlocal) {
	$EUID = 0;
	goto skipstuff;
    }
    
539 540 541 542 543 544 545 546
    #
    # If the user requested an initial encrypted SSL certificate, create
    # that too. Need to delete the initial_passphrase slot though, so that
    # we do not try to recreate it at some future time.
    #
    if (defined($target_user->initial_passphrase())) {
	my $pphrase = User::escapeshellarg($target_user->initial_passphrase());
	
547
	system("$MKUSERCERT -p $pphrase $user");
548 549 550
	if ($?) {
	    fatal("Could not create initial encrypted SSL certificate");
	}
551
	$target_user->Update({'initial_passphrase' => "NULL"});
552
    }
553
    
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
    if (!$nocollabtools) {
	# Add to elists.
	system("$GENELISTS -u $user")
	    if (! $batch);

	# And to the wiki if enabled.
	system("$ADDWIKIUSER $user")
	    if ($WIKISUPPORT && $user ne $PROTOUSER);

	# And to the bugdb if enabled.
	system("$ADDBUGDBUSER $user")
	    if ($BUGDBSUPPORT && $user ne $PROTOUSER);

	# And to the OPS db if enabled.
	system("$OPSDBCONTROL adduser $user")
	    if ($OPSDBSUPPORT && $user ne $PROTOUSER);

	# And to the chat server if enabled.
	system("$ADDCHATUSER $user")
	    if ($CHATSUPPORT && $user ne $PROTOUSER);

	# And to the trac system if enabled.
	system("$ADDTRACUSER $user")
	    if ($TRACSUPPORT && $user ne $PROTOUSER);
578
    }
579

580 581 582 583 584 585 586 587 588
    #
    # Must update the exports file or else nodes will complain.  There
    # is a bit of race in here since this update happens after the
    # user is marked "active", and in that time a node could suck over
    # the account info, but not be able to mount the directory. Short
    # window though. Do not worry about the exit value. Note that this
    # could hang for a while if another update is in progress. Hmm, I
    # do not like this.
    #
589 590 591 592
    if (! $batch) {
	print "Updating exports file.\n";
	system("$EXPORTSSETUP");
    }
593 594
    $EUID = 0;

595
  skipstuff:
596
    CheckDotFiles();
597
    return 0;
598 599 600 601 602 603 604 605
}

#
# Delete a user.
#
sub DelUser()
{
    #
606
    # Only admin people can do this.
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
    #
    if (! TBAdmin($UID)) {
	fatal("You do not have permission to delete user $user.");
    }
    #
    # Check status. Active indicates something is wrong.
    #
    if (!$force && $status eq USERSTATUS_ACTIVE) {
	fatal("$user is still active! Cannot delete the account!");
    }

    print "Deleting user $user ($user_number) from local node.\n";

    $UID = 0;

622
    if (runBusyLoop("$USERDEL $user")) {
623 624 625 626 627
	if (($? >> 8) != $NOSUCHUSER) {
	    fatal("Could not remove user $user from local node.");
	}
    }

628
    if (1) {
629
	print "Removing user $user from $CONTROL\n";
630

631 632 633
	if (system("$SSH -host $CONTROL ".
		   "   '$ACCOUNTPROXY deluser $user $HOMEDIR/$user'")) {
	    if ($?) {
634 635 636 637 638
		fatal("Could not remove user $user from $CONTROL.");
	    }
	}
    }
    $UID = $SAVEUID;
639

640 641 642
    goto skipstuff
	if ($isnonlocal || $nocollabtools);
    
643
    $EUID = $UID;
644 645 646 647 648 649 650
    #
    # Must update the exports file or else nodes will complain.  Note
    # that this could hang for a while if another update is in progress. 
    #
    print "Updating exports file.\n";
    system("$EXPORTSSETUP");

651
    # Remove from elists.
652
    system("$GENELISTS -u $user");
653 654 655 656 657

    # And to the wiki if enabled.
    system("$DELWIKIUSER $user")
	if ($WIKISUPPORT);
    
658 659 660 661
    # And the chat server if enabled.
    system("$DELCHATUSER $user")
	if ($CHATSUPPORT);
    
662 663 664 665
    # And the mailman lists if enabled.
    system("$DELMMUSER $user")
	if ($MAILMANSUPPORT);
    
666 667 668 669
    # And to the trac system if enabled.
    system("$DELTRACUSER $user")
	if ($TRACSUPPORT);

670
    $EUID = 0;
671

672
  skipstuff:
673 674 675 676 677
    return 0;
}

#
# Change a password for the user on the control node. The local password
678
# is not touched!
679 680 681 682
#
sub UpdatePassword()
{
    #
683
    # New password (encrypted) comes in on the command line. 
684
    #
685 686 687 688 689 690
    usage()
	if (! @ARGV);

    my $new_pswd  = shift(@ARGV);

    # Lets not do this if no changes.
691
    if ($new_pswd eq $target_user->pswd() && !$force) {
692
	print "Password has not changed ...\n";
693 694 695
	return 0;
    }

696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
    # Lets prevent any odd characters.
    if ($new_pswd =~ /[\'\\\"\&]+/) {
	fatal("Invalid characters in new password encryption string!");
    }

    #
    # Insert into database. When changing password for someone else,
    # always set the expiration to right now so that the target user
    # is "forced" to change it. 
    #
    my $expires;
    
    if (! $target_user->SameUser($this_user)) {
	$expires = "now()";
    }
711
    elsif ($EXPIRE_PASSWORDS) {
712 713 714 715 716 717 718
	$expires = "date_add(now(), interval 1 year)";
    }

    if ($target_user->SetPassword($new_pswd, $expires)) {
	fatal("Could not update password encryption string for $target_user");
    }

719 720 721 722
    # Go no further if a nonlocal user.
    return 0
	if ($isnonlocal);

723
    # Send auditing email before next step in case of failure.
724
    $target_user->SendEmail(
725 726
	     "Password for '$user' has been changed",
	     "\n".
727
	     "Password for '$user' has been changed by " .
728 729 730 731 732
	            $this_user->uid() ."\n".
	     "\n".
	     "Name:              " . $target_user->name()  . "\n".
	     "IDX:               " . $target_user->uid_idx()  . "\n".
	     "\n".
733 734 735
	     "If this is unexpected, please contact support ".
	     "(" . $target_user->OpsEmailAddress() . ") immediately!\n".
	     "\n");
736 737 738 739 740 741 742 743 744 745 746 747 748

    # Go no further if a webonly user.
    return 0
	if ($webonly);

    #
    # Go no further if user is not active or frozen.
    #
    return 0
	if (! ($status eq USERSTATUS_ACTIVE || $status eq USERSTATUS_FROZEN));

    #
    # Change on ops only if there is a real account there.
749
    # For ELABINELAB, safer to leave the password "starred".
750
    #
751
    if (!$wikionly && (!$ELABINELAB || $GENIRACK)) {
752 753 754 755 756 757 758 759
	#
	# Grab from the DB to avoid taint checking sillyness.
	#
	my $safe_pswd = $target_user->pswd();
	# shell escape.
	$safe_pswd    =~ s/\$/\\\$/g;
	$safe_pswd    =~ s/\*/\\\*/g;
	
760 761 762
	$UID = 0;
	if ($CONTROL ne $BOSSNODE) {
	    print "Updating user $user password on $CONTROL.\n";
763 764 765 766

	    if (system("$SSH -host $CONTROL ".
		       "  \"$ACCOUNTPROXY chpass $user '$safe_pswd'\"")) {
		fatal("Could not change password for $user on $CONTROL!");
767
	    }
768
	}
769
	$UID = $SAVEUID;
770
    }
771 772 773 774 775 776 777 778 779

    #
    # Ick. If invoked as "nobody" then the user was either frozen or
    # inactive. Lets skip the rest of this for now. Needs more thought
    # and cleanup in the web interface to this, since we cannot call
    # out to these scripts as "nobody" (yet).
    #
    return 0
	if (getpwuid($UID) eq "nobody");
780 781 782

    return 0
	if ($isnonlocal || $nocollabtools);
783
    
784
    $EUID = $UID;
785
    # And the wiki if enabled.
786
    system("$ADDWIKIUSER -u $user")
787
	if ($WIKISUPPORT && $user ne $PROTOUSER && !$webonly);
788 789 790

    # And to the bugdb if enabled.
    system("$ADDBUGDBUSER -m $user")
791
	if ($BUGDBSUPPORT && $user ne $PROTOUSER && ! ($wikionly || $webonly));
792

793 794 795
    system("$ADDTRACUSER -u $user")
	if ($TRACSUPPORT && $user ne $PROTOUSER && !$webonly);

796
    $EUID = 0;
797
    CheckDotFiles();
798

799 800 801
    return 0;
}

802 803 804 805 806 807 808
#
# Change a Windows password for the user on the Samba server node.
# The local password is not touched!
#
sub UpdateWindowsPassword()
{
    #
809
    # New password (encrypted) comes in on the command line. 
810
    #
811 812 813 814 815
    usage()
	if (! @ARGV);
    my $new_wpswd  = shift(@ARGV);

    # Lets not do this if no changes.
Leigh Stoller's avatar
Leigh Stoller committed
816 817
    if (defined($target_user->w_pswd()) &&
	$new_wpswd eq $target_user->w_pswd()) {
818
	print "Password has not changed ...\n";
819 820 821
	return 0;
    }

822 823 824 825 826 827
    #
    # Insert into database.
    #
    if ($target_user->SetWindowsPassword($new_wpswd)) {
	fatal("Could not update Windows password string for $target_user");
    }
828

829 830 831 832 833 834 835 836 837 838
    # Go no further if a webonly user.
    return 0
	if ($webonly);

    #
    # Go no further if user is not active or frozen.
    #
    return 0
	if (! ($status eq USERSTATUS_ACTIVE || $status eq USERSTATUS_FROZEN));

839 840 841 842 843 844
    #
    # Do nothing if we are not even doing windoze.
    #
    return 0
	if (! $WINSUPPORT);

845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
    #
    # Change on ops for Samba only if there is a real account there.
    #
    if (! $wikionly) {
	# shell escape.
	$new_wpswd     =~ s/\$/\\\$/g;

	$UID = 0;
	print "Updating user $user Samba password on $SAMBANODE.\n";
	# -s = silent, -a = add user if necessary.
	open( SPCMD, "| $SSH -host $SAMBANODE $SMBPASSWD -s -a $user")
	    || fatal("Opening $SMBPASSWD pipe, user $user on $SAMBANODE: $! $?");
	local $SIG{PIPE} = sub { die "smbpasswd spooler pipe broke" };
	print SPCMD "$new_wpswd\n$new_wpswd\n";
	close SPCMD 
	    || fatal("Closing $SMBPASSWD pipe, user $user on $SAMBANODE: $! $?");

	$UID = $SAVEUID;
    }
864 865 866
    return 0;
}

867 868 869 870 871 872 873 874
#
# Update user info. Allow for optional shell change for freeze/thaw.
#
sub UpdateUser(;$)
{
    my ($freezeopt) = @_;
    my $locshellarg = "";
    my $remshellarg = "";
875
    $freezeopt = 0 if (!defined($freezeopt));
876 877

    #
878
    # Sanity check.
879
    #
880
    if ($webonly || $isnonlocal) {
881 882
	return 0;
    }
883
    if (!$freezeopt && ($status ne USERSTATUS_ACTIVE)) {
884 885 886 887
	#
	# If doing a modification to a frozen user, then just ignore
	# it; the modification will happen later when the user is thawed.
	#
888 889
	if ($status eq USERSTATUS_FROZEN || $status eq USERSTATUS_INACTIVE) {
	    print "Ignoring update of frozen/inactive user $user\n";
890 891
	    return 0;
	}
892
	fatal("$user is not active! Cannot update the account!");
893 894 895
    }

    # Shell is different on local vs control node.
896
    if ($freezeopt) {
897
	$locshellarg = "-s $NOLOGIN";
898
	$remshellarg = "$NOLOGIN";
899 900
    }
    else {
901 902 903 904 905 906 907
	# Admin users get a local shell.
	if ($usr_admin) {
	    $locshellarg = "-s " . $shellpaths{"tcsh"};
	}
	else {
	    $locshellarg = "-s $PBAG"
	}
908 909
	if (!defined($usr_shell) ||
	    !exists($shellpaths{$usr_shell})) {
910
	    $remshellarg = $shellpaths{"tcsh"};
911
	}
912
	else  {
913
	    $remshellarg = $shellpaths{$usr_shell};
914 915 916
	}
    }
    print "Updating user $user ($user_number) on local node.\n";
917

918
    $UID = 0;
919
    if (runBusyLoop("$USERMOD $user $locshellarg -c \"$fullname\" ")) {
920 921
	fatal("Could not modify user $user on local node.");
    }
922

923 924 925 926 927 928 929 930
    #
    # Quote special chars for ssh and the shell on the other side
    #
    $fullname =~ s/\"/\'/g;
    $fullname =~ s/([^\\])([\'\"\(\)])/$1\\$2/g;

    if ($CONTROL ne $BOSSNODE) {
	print "Updating user $user ($user_number) on $CONTROL\n";
931

932
	if (system("$SSH -host $CONTROL ".
933
		   "'$ACCOUNTPROXY moduser $user $remshellarg \"$fullname\"'")){
934 935 936 937
	    fatal("Could not modify user $user record on $CONTROL.");
	}
    }
    $UID = $SAVEUID;
938

939 940 941
    return 0
	if ($isnonlocal || $nocollabtools);
    
942
    $EUID = $UID;
943 944 945 946
    # Update elists in case email changed.
    system("$MMMODIFYUSER $user")
	if ($MAILMANSUPPORT && !$batch);
    
947
    # Update elists in case email changed.
948
    system("$GENELISTS -m -u $user");
949
    $EUID = 0;
950 951
    CheckDotFiles()
	if (! $freezeopt);
952

953 954 955
    return 0;
}

956 957 958 959 960 961 962 963
#
# Change email address for user.
#
sub UpdateEmail()
{
    #
    # Only admin people can do this.
    #
964
    if (!TBAdmin($UID) && !$verified) {
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
	fatal("You do not have permission to update email for user $user.");
    }

    #
    # New email comes in on the command line. 
    #
    usage()
	if (! @ARGV);

    my $new_email = shift(@ARGV);

    # Lets not do this if no changes.
    return 0
	if ($new_email eq $user_email);

    # Must be valid.
    if (! TBcheck_dbslot($new_email, "users", "usr_email",
			 TBDB_CHECKDBSLOT_WARN|TBDB_CHECKDBSLOT_ERROR)) {
	fatal("Invalid characters in email address!");
    }

    my %args = ();
    $args{"usr_email"} = $new_email;

    if ($target_user->Update(\%args)) {
	fatal("Could not update email address for $target_user");
    }

993 994 995
    return 0
	if ($isnonlocal);

996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
    # Send auditing email before next step in case of failure.
    SENDMAIL("$fullname <$user_email>",
	     "Email Address for '$user' Modified",
	     "\n".
	     "Email Address for '$user' changed by " . $this_user->uid() ."\n".
	     "\n".
	     "Name:              " . $target_user->name()  . "\n".
	     "IDX:               " . $target_user->uid_idx()  . "\n".
	     "Old Email:         " . $user_email . "\n".
	     "New Email:         " . $new_email . "\n".
	     "\n".
	     "If this is unexpected, please contact Testbed Operations\n".
	     "($TBOPS) immediately!\n".
	     "\n",
	     "$TBOPS",
	     "CC: $new_email\n".
	     "Bcc: $TBAUDIT");

    # Change global in this script. 
    $user_email = $target_user->email();

    $EUID = $UID;

    # Update mailman elists.
    system("$MMMODIFYUSER $user")
	if ($MAILMANSUPPORT);
    
    # Update system elists.
    system("$GENELISTS -m -u $user");

    $EUID = 0;
1027
    CheckDotFiles();
1028 1029 1030
    return 0;
}

1031 1032 1033 1034 1035 1036
#
# Freeze a user.
#
sub FreezeUser()
{
    #
1037
    # Only admin people can do this.
1038 1039 1040 1041 1042 1043 1044 1045
    #
    if (! TBAdmin($UID)) {
	fatal("You do not have permission to freeze user $user.");
    }
    #
    # Check status.
    #
    if ($status ne USERSTATUS_FROZEN) {
1046 1047 1048
	fatal("$user is still active! Cannot freeze the account!")
	    if (!$update);

1049 1050
	$target_user->SetStatus(USERSTATUS_FROZEN());
	$status = USERSTATUS_FROZEN();
1051
    }
1052

1053 1054 1055 1056 1057 1058 1059 1060 1061
    return UpdateUser(1);
}

#
# Thaw a user.
#
sub ThawUser()
{
    #
1062
    # Only admin people can do this.
1063 1064 1065 1066 1067 1068 1069 1070
    #
    if (! TBAdmin($UID)) {
	fatal("You do not have permission to thaw user $user.");
    }
    #
    # Check status.
    #
    if ($status ne USERSTATUS_ACTIVE) {
1071 1072 1073
	fatal("$user is not active! Cannot thaw the account!")
	    if (!$update);
	$target_user->SetStatus(USERSTATUS_ACTIVE());
1074
	$status = USERSTATUS_ACTIVE();
1075
    }
1076

1077 1078 1079 1080 1081 1082
    #
    # This lets users start off as frozen in an ELABINELAB, and then
    # get created later. Saves a lot of time.
    #
    if ($ELABINELAB &&
	system("egrep -q -s '^${user}:' /etc/passwd")) {
1083 1084 1085 1086
	
	AddUser() == 0
	    or fatal("Cannot thaw $user");

1087
	runBusyLoop("$USERMOD -n $user -s /bin/tcsh");
1088
    }
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
    else {
	UpdateUser(0) == 0
	    or fatal("Cannot thaw $user");
    }

    #
    # Invoke as real user for auditing.
    #
    $EUID = $UID;
    system("$SETGROUPS $user");
    $EUID = 0;
    
    return 0;
1102 1103
}

1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
#
# Deactivate a user.
#
sub DeactivateUser()
{
    #
    # Only admin people can do this.
    #
    if (! TBAdmin($UID)) {
	fatal("You do not have permission to deactivate user $user.");
    }
    #
    # Check status.
    #
    if ($status ne USERSTATUS_INACTIVE) {
	fatal("$user is still active! Cannot deactivate the account!")
	    if (!$update);

	$target_user->SetStatus(USERSTATUS_INACTIVE());
	$status = USERSTATUS_INACTIVE();
    }
    #
    # Shell goes to nologin on the CONTROL node.
    #
    $UID = 0;
1129
    if (runBusyLoop("$USERMOD $user -s $NOLOGIN")) {
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
	fatal("Could not set shell to $NOLOGIN for $user on local node.");
    }
    if ($CONTROL ne $BOSSNODE) {
	print "Deactivating user $user ($user_number) on $CONTROL\n";

	if (system("$SSH -host $CONTROL '$ACCOUNTPROXY deactivateuser $user'")){
	    fatal("Could not deactivate $user on $CONTROL.");
	}
    }
    $UID = $SAVEUID;
    return 0;
}

#
# Reactivate a user.
#
sub ReactivateUser()
{
    #
1149 1150 1151
    # Only admin people can do this to another user, but we do allow a
    # user to reactivate themselves, as from the web interface when they
    # log in and the account has been deactivated for lack of use.
1152
    #
1153 1154 1155
    if (! (TBAdmin($UID) ||
	   ($target_user->SameUser($this_user) &&
	    $status eq USERSTATUS_ACTIVE))) {
1156 1157 1158 1159 1160 1161 1162
	fatal("You do not have permission to reactivate user $user.");
    }
    #
    # Check status.
    #
    if ($status ne USERSTATUS_ACTIVE) {
	fatal("$user is not active! Cannot reactivate the account!")
1163 1164 1165 1166 1167
	    if (! ($update || $force));
	if ($update) {
	    $target_user->SetStatus(USERSTATUS_ACTIVE());
	    $status = USERSTATUS_ACTIVE();
	}
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
    }
    $UID = 0;
    if ($CONTROL ne $BOSSNODE) {
	print "Reactivating user $user ($user_number) on $CONTROL\n";

	if (system("$SSH -host $CONTROL '$ACCOUNTPROXY reactivateuser $user'")){
	    fatal("Could not reactivate $user on $CONTROL.");
	}
    }
    $UID = $SAVEUID;
    # Similar to freeze/thaw for our purposes.
    UpdateUser(0) == 0
	or fatal("Cannot reactivate $user");

    return 0;
}

1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
#
# Verify a user. Converts status and sends email
#
sub VerifyUser()
{
    #
    # Only admin people can do this unless its the user himself.
    #
    if (! $target_user->SameUser($this_user) && ! TBAdmin()) {
	fatal("You do not have permission to verify user $user.");
    }

    if ($target_user->status() ne USERSTATUS_NEWUSER) {
Leigh Stoller's avatar
Leigh Stoller committed
1198
	fatal("$target_user is not a newuser! Cannot verify the account!");
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
    }

    my $newstatus = ($target_user->wikionly() ?
		     USERSTATUS_ACTIVE() : USERSTATUS_UNAPPROVED());

    $target_user->SetStatus($newstatus) == 0 or
	fatal("Could not set user status to '$newstatus' for $target_user");

    $target_user->SendVerifiedEmail() == 0 or
	fatal("Could not send verified email for $target_user");

    return 0;
}

1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
#
# Revoke user ssl certs
#
sub RevokeUser()
{
    #
    # Only admin people can do this.
    #
    if (! TBAdmin($UID)) {
	fatal("You do not have permission to thaw user $user.");
    }
    $target_user->RevokeSSLCerts();

    if ($PGENISUPPORT) {
	$UID = 0;
	system("$POSTCRL");
	if ($? >> 8 < 0) {
	    fatal("Could not post updated CRL");
	}
	$UID = $SAVEUID;
    }
    
    return 0;
}

1238 1239 1240 1241 1242
#
# Check dot files. We do this over and over ...
#
sub CheckDotFiles()
{
1243 1244 1245 1246 1247 1248
    $UID = 0;
    system("$SSH -host $CONTROL ".
	   "   '$ACCOUNTPROXY checkdotfiles $user $default_groupgid ".
	   "     $user_email'");
    if ($?) {
	fatal("Could not check dotfiles for user $user on $CONTROL.");
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
    }
    $UID = $SAVEUID;
    return 0;
}

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

    die("*** $0:\n".
	"    $mesg\n");
}