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

#
# Parse ssh public keys and enter into the DB. The default format is
# openssh, but if the key is not in that format, then use ssh-keygen
# to see if it can be converted from either SSH2 or SECSH format into
# openssh format. This gets called from the webpage to parse keys
# uploaded by users.
#
sub usage()
{
19 20
    print "Usage: addpubkeys [-k | -f] [-n | -u <user>] [<keyfile> | <key>]\n";
    print "       addpubkeys [-i [-r] | -w] <user>\n";
21 22
    print "Options:\n";
    print " -k      Indicates that key was passed in on the command line\n";
23
    print " -f      Indicates that key was passed in as a filename\n";
24
    print " -n      Verify key format only; do not enter into into DB\n";
25 26
    print " -w      Generate new authkeys (protocol 1 and 2) file for user\n";
    print " -i      Initialize mode; generate initial key for user\n";
27
    print " -r      Force a regenerate of initial key for user\n";
28 29
    exit(-1);
}
30
my $optlist   = "kniwfu:r";
31 32
my $iskey     = 0;
my $verify    = 0;
33
my $initmode  = 0;
Leigh Stoller's avatar
Leigh Stoller committed
34
my $force     = 0;
35 36 37
my $genmode   = 0;
my $nobody    = 0;
my $noemail   = 0;
38 39 40 41 42 43 44

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS       = "@TBOPSEMAIL@";
my $TBAUDIT     = "@TBAUDITEMAIL@";
Leigh Stoller's avatar
Leigh Stoller committed
45
my $OURDOMAIN   = "@OURDOMAIN@";
46 47 48 49 50
my $KEYGEN	= "/usr/bin/ssh-keygen";
my $USERUID;

# Locals
my $user;
51 52
my $this_user;
my $target_user;
53 54 55 56 57 58
my $keyfile;
my $keyline;
my $key;
my $comment;
my $user_name;
my $user_email;
59 60
my $user_dbid;
my $user_uid;
61 62 63 64 65

#
# Testbed Support libraries
#
use lib "@prefix@/lib";
66
use libaudit;
67 68 69
use libdb;
use libtestbed;

70 71 72 73 74
#
# Function prototypes
#
sub ParseKey($);
sub InitUser();
Leigh Stoller's avatar
Leigh Stoller committed
75
sub GenerateKeyFile();
76 77
sub fatal($);

78 79
my $HOMEDIR = USERROOT();

80 81 82 83 84 85 86 87 88 89 90
#
# Turn off line buffering on output
#
$| = 1;

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

91 92 93 94 95 96 97 98
#
# 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");
}

99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
#
# Please do not run it as root. Hard to track what has happened.
# 
if ($UID == 0) {
    die("*** $0:\n".
	"    Please do not run this as root!\n");
}

#
# 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{"k"})) {
    $iskey = 1;
}
118 119 120
if (defined($options{"f"})) {
    $iskey = 0;
}
121 122 123
if (defined($options{"n"})) {
    $verify = 1;
}
124 125 126
if (defined($options{"i"})) {
    $initmode = 1;
}
127
if (defined($options{"r"})) {
Leigh Stoller's avatar
Leigh Stoller committed
128 129
    $force = 1;
}
130 131
if (defined($options{"w"})) {
    $genmode = 1;
132
}
133 134 135
if (defined($options{"u"})) {
    $user = $options{"u"};
}
136
if ($verify && $genmode) {
137 138
    usage();
}
139
if ($initmode || $genmode) {
140 141 142 143
    usage()
	if (@ARGV != 1);

    $user = $ARGV[0];
144 145
}
else {
146 147 148 149 150 151 152
    usage()
	if (@ARGV != 1);
    usage()
	if (!$verify && !defined($user));
    
    $keyfile = $ARGV[0];
}
153 154 155 156

#
# Untaint the arguments.
#
157
if (defined($user)) {
158
    if ($user =~ /^([-\w]+)$/i) {
159 160 161 162 163
	$user = $1;
    }
    else {
	fatal("Tainted username: $user");
    }
164 165 166 167 168 169 170 171 172 173
    # Map user to object.
    $target_user = User->Lookup($user);
    if (! defined($target_user)) {
	fatal("$user does not exist!")
    }

    $user_name  = $target_user->name();
    $user_email = $target_user->email();
    $user_dbid  = $target_user->dbid();
    $user_uid   = $target_user->uid();
Leigh Stoller's avatar
Leigh Stoller committed
174
    $USERUID    = $target_user->unix_uid();
175 176 177
}

#
178 179 180
# If invoked as "nobody" we came from the web interface. We have to have
# a credential in the environment, unless its just a key verification
# operation, which anyone can do. 
181 182
# 
if (getpwuid($UID) eq "nobody") {
183 184 185 186
    $this_user = User->ImpliedUser();
    
    if (($initmode || $genmode || !$verify) && !defined($this_user)) {
	fatal("Bad usage from web interface");
187 188 189 190
    }
    $nobody = 1;
}
else {
191 192
    # From the command line; map invoking user to object.
    $this_user = User->ThisUser();
193 194 195 196

    if (! defined($this_user)) {
	fatal("You ($UID) do not exist!");
    }
197 198 199
}

#
200 201
# Initmode or genmode, do it and exit. Eventually get rid of the switch
# to the target user.
202 203 204
#
if ($initmode) {
    # Drop root privs, switch to target user.
205
    $EUID = $UID = $USERUID;
206 207 208 209
    exit InitUser();
}
if ($genmode) {
    # Drop root privs, switch to target user.
210
    $EUID = $UID = $USERUID;
Leigh Stoller's avatar
Leigh Stoller committed
211
    exit GenerateKeyFile();
212 213 214
}

# Else, key parse mode ...
215 216 217 218 219 220 221 222 223 224 225 226
if ($iskey) {
    if ($keyfile =~ /^([-\w\s\.\@\+\/\=]*)$/) {
	$keyfile = $1;
    }
    else {
	fatal("Tainted key: $keyfile");
    }
    $keyline = $keyfile;
}
else {
    if ($keyfile =~ /^([-\w\.\/]+)$/) {
	$keyfile = $1;
227
     }
228 229 230 231
    else {
	fatal("Tainted filename: $keyfile");
    }
    if (! -e $keyfile) {
232
	fatal("No such file: $keyfile\n");
233 234 235 236 237
    }
    $keyline = `head -1 $keyfile`;
}

#
238
# Check user
239
#
240 241
if (!$verify) {
    # If its the user himself, then we can generate a new authkeys file. 
242
    if (!$target_user->SameUser($this_user) && !TBAdmin()) {
243
	fatal("You are not allowed to set pubkeys for $target_user\n");
244
    }
245
    if (-d "$HOMEDIR/$user_uid/.ssh") {
246 247
	# Drop root privs, switch to target user.
	$EUID = $UID = $USERUID;
248 249
	$genmode = 1;
    }
250
    
251 252 253 254 255 256
    #
    # This script is audited when not in verify mode. Since all keys are first
    # checked with verify mode, this should not cause any extra email from bad
    # keys.
    #
    AuditStart(0);
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
#
# Grab the first line of the file. Parse it to see if its in the
# format we like (openssh), either protocol 1 or 2.
#
if (ParseKey($keyline)) {
    exit 0;
}
# If the key was entered on the command line, then nothing more to do.
if ($iskey) {
    exit 1;
}

#
# Run ssh-keygen over it and see if it can convert it. 
#
if (! open(KEYGEN, "ssh-keygen -i -f $keyfile 2>/dev/null |")) {
    fatal("*** $0:\n".
	  "    Could not start ssh-keygen\n");
}
$keyline = <KEYGEN>;
if (close(KEYGEN) && ParseKey($keyline)) {
    exit 0;
}
exit 1;

sub ParseKey($) {
    my ($keyline) = @_;
286

287
    # Remove trailing newlines which screws the patterns below.
288 289
    # First convert dos newlines since many people upload from windoze.
    $keyline =~ s/\r/\n/g;
290 291
    $keyline =~ s/\n//g;

292 293 294 295 296 297
    # Enforce a reasonable length on the key.
    if (length($keyline) > 4096) {
	print "Key is too long!\n";
	print "Key: $keyline\n";
	return 0;
    }
298
    
Leigh Stoller's avatar
Leigh Stoller committed
299
    if ($keyline =~ /^(\d*\s\d*\s[0-9a-zA-Z]*) ([-\w\@\.\ ]*)\s*$/) {
300 301 302 303 304 305 306 307 308 309 310
        # Protocol 1
	$type    = "ssh-rsa1";
	$key     = $1;
	$comment = $2;
    }
    elsif ($keyline =~ /^(\d*\s\d*\s[0-9a-zA-Z]*)\s*$/) {
        # Protocol 1 but no comment field.
	$type    = "ssh-rsa1";
	$key     = $1;
    }
    elsif ($keyline =~
311
	   /^(ssh-rsa|ssh-dss) ([-\w\.\@\+\/\=]*) ([-\w\@\.\ ]*)$/) {
312 313 314 315 316 317 318 319 320 321 322 323
        # Protocol 2
	$type    = $1;
	$key     = "$1 $2";
	$comment = $3;
    }
    elsif ($keyline =~ /^(ssh-rsa|ssh-dss) ([-\w\.\@\+\/\=]*)$/) {
        # Protocol 2 but no comment field
	$type    = $1;
	$key     = "$1 $2";
    }

    if (!defined($key)) {
324 325
	print "Key cannot be parsed!\n";
	print "Key: $keyline\n";
326 327
	return 0;
    }
328

329 330
    # Do not enter into DB if in verify mode.
    if ($verify) {
Leigh Stoller's avatar
Leigh Stoller committed
331
	print "Key was good: $type\n";
332 333 334 335
	return 1;
    }

    #
336
    # Make up a comment field for the DB. 
337 338 339 340 341 342 343
    #
    if (!defined($comment)) {
	$comment = "$type-${user_email}";
    }
    $key = "$key $comment";

    DBQueryFatal("replace into user_pubkeys ".
344 345
		 "values ('$user_uid', '$user_dbid', ".
		 "        0, '$key', now(), '$comment')");
346

347 348 349
    #
    # Mark user record as modified so nodes are updated.
    #
350
    TBNodeUpdateAccountsByUID($user_uid);
351

352 353 354 355 356 357 358 359
    my $chunked = "";

    while (length($key)) {
	$chunked .= substr($key, 0, 65, "");
	if (length($key)) {
	    $chunked .= "\n";
	}
    }
360 361
    print "SSH Public Key for '$user' added:\n";
    print "$chunked\n";
362
    
363 364
    # Generate new auth keys file. 
    if ($genmode) {
Leigh Stoller's avatar
Leigh Stoller committed
365
	GenerateKeyFile();
366 367 368 369
    }

    if (! $noemail) {
	SENDMAIL("$user_name <$user_email>",
370 371
		 "SSH Public Key for '$user_uid' Added",
		 "SSH Public Key for '$user_uid' added:\n".
372 373 374 375 376
		 "\n".
		 "$chunked\n",
		 "$TBOPS");
    }
    return 1;
377 378
}

379 380 381 382 383 384
#
# Init function for new users. Generate the first key for the user (which
# is loaded into the DB), and then generate the keyfiles. Note that the
# user might have preloaded personal keys.
#
sub InitUser()
385
{
386
    my $sshdir  = "$HOMEDIR/$user_uid/.ssh";
387 388

    #
389
    # Set up the ssh key, but only if not done so already.
390
    #
391 392 393 394
    if (! -e "$sshdir") {
	mkdir("$sshdir", 0700) or
	    fatal("Could not mkdir $sshdir: $!");
    }
Leigh Stoller's avatar
Leigh Stoller committed
395 396
    if (! -e "$sshdir/identity" || $force) {
	print "Creating ssh protocol 1 key for $user.\n";
Leigh Stoller's avatar
Leigh Stoller committed
397

Leigh Stoller's avatar
Leigh Stoller committed
398 399 400 401 402 403 404 405
	#
	# Want to delete existing key from DB.
	#
	if (-e "$sshdir/identity") {
	    my $ident = `cat $sshdir/identity.pub`;

	    if ($ident =~ /(\d*\s\d*\s[0-9a-zA-Z]*)\s([-\w\@\.]*)/) {
		DBQueryFatal("delete from user_pubkeys ".
406
			     "where uid_idx='$user_dbid' and pubkey='$1 $2'");
Leigh Stoller's avatar
Leigh Stoller committed
407 408 409
	    }
	    unlink("$sshdir/identity");
	}
410

Leigh Stoller's avatar
Leigh Stoller committed
411
	# Hmm, need to use -C option so comment field makes sense.
412
    
Leigh Stoller's avatar
Leigh Stoller committed
413 414 415
	if (system("$KEYGEN -t rsa1 -P '' ".
		   "-C '${user}" . "\@" . ${OURDOMAIN} . "' ".
		   "-f $sshdir/identity")) {
416 417 418 419 420 421 422 423
	    fatal("Failure in ssh-keygen!");
	}

	#
	# Grab a copy for the DB.
	# 
	my $ident = `cat $sshdir/identity.pub`;

Leigh Stoller's avatar
Leigh Stoller committed
424
	if ($ident =~ /(\d*\s\d*\s[0-9a-zA-Z]*)\s([-\w\@\.]*)/) {
425
	    DBQueryFatal("replace into user_pubkeys ".
426 427
			 "values ('$user_uid', '$user_dbid', ".
			 "        0, '$1 $2', now(), '$2')");
428 429
	}
	else {
Leigh Stoller's avatar
Leigh Stoller committed
430
	    fatal("Bad protocol 1 public key: $ident\n");
431 432
	}
    }
Leigh Stoller's avatar
Leigh Stoller committed
433 434 435 436 437
    #
    # Moving to V2 keys ...
    #
    if (! -e "$sshdir/id_rsa" || $force) {
	print "Creating ssh protocol 2 key for $user.\n";
438

Leigh Stoller's avatar
Leigh Stoller committed
439 440 441 442 443 444 445 446 447
	#
	# Want to delete existing key from DB.
	#
	if (-e "$sshdir/id_rsa") {
	    my $ident = `cat $sshdir/id_rsa.pub`;

	    if ($ident =~
		/^(ssh-rsa [-\w\.\@\+\/\=]*) ([-\w\@\.\ ]*)$/) {
		DBQueryFatal("delete from user_pubkeys ".
448
			     "where uid_idx='$user_dbid' and pubkey='$1 $2'");
Leigh Stoller's avatar
Leigh Stoller committed
449 450 451 452 453
	    }
	    unlink("$sshdir/id_rsa");
	}

	# Hmm, need to use -C option so comment field makes sense.
454
    
Leigh Stoller's avatar
Leigh Stoller committed
455 456 457 458 459
	if (system("$KEYGEN -t rsa -P '' ".
		   "-C '${user}" . "\@" . ${OURDOMAIN} . "' ".
		   "-f $sshdir/id_rsa")) {
	    fatal("Failure in ssh-keygen!");
	}
460

Leigh Stoller's avatar
Leigh Stoller committed
461 462 463 464
	#
	# Grab a copy for the DB.
	# 
	my $ident = `cat $sshdir/id_rsa.pub`;
465

Leigh Stoller's avatar
Leigh Stoller committed
466 467 468
	if ($ident =~
	    /^(ssh-rsa [-\w\.\@\+\/\=]*) ([-\w\@\.\ ]*)$/) {
	    DBQueryFatal("replace into user_pubkeys ".
469 470
			 "values ('$user_uid', '$user_dbid', ".
			 "        0, '$1 $2', now(), '$2')");
471 472
	}
	else {
Leigh Stoller's avatar
Leigh Stoller committed
473
	    fatal("Bad protocol 2 public key: $ident\n");
474 475
	}
    }
Leigh Stoller's avatar
Leigh Stoller committed
476
    return GenerateKeyFile();
477 478 479 480 481 482
}

#
# Generate ssh authorized_keys files. Either protocol 1 or 2.
# Returns 0 on success, -1 on failure.
#
Leigh Stoller's avatar
Leigh Stoller committed
483
sub GenerateKeyFile()
484
{
Leigh Stoller's avatar
Leigh Stoller committed
485
    my @pkeys   = ();
486
    my $sshdir  = "$HOMEDIR/$user_uid/.ssh";
487 488 489 490 491 492 493 494
    my $keyfile = "$sshdir/authorized_keys";
	
    if (! -e $sshdir) {
	if (! mkdir($sshdir, 0700)) {
	    warn("*** WARNING: Could not mkdir $sshdir: $!\n");
	    return -1;
	}
    }
Leigh Stoller's avatar
Leigh Stoller committed
495
    my $query_result =
496 497
	DBQueryFatal("select pubkey from user_pubkeys ".
		     "where uid_idx='$user_dbid'");
Leigh Stoller's avatar
Leigh Stoller committed
498 499 500

    while (my ($key) = $query_result->fetchrow_array()) {
	push(@pkeys, $key);
501
    }
Leigh Stoller's avatar
Leigh Stoller committed
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 534 535 536 537
    print "Generating $keyfile ...\n";

    if (!open(AUTHKEYS, "> ${keyfile}.new")) {
	warn("*** WARNING: Could not open ${keyfile}.new: $!\n");
	return -1;
    }
    print AUTHKEYS "#\n";
    print AUTHKEYS "# DO NOT EDIT! This file auto generated by ".
	"Emulab.Net account software.\n";
    print AUTHKEYS "#\n";
    print AUTHKEYS "# Please use the web interface to edit your ".
	"public key list.\n";
    print AUTHKEYS "#\n";
    
    foreach my $key (@pkeys) {
	print AUTHKEYS "$key\n";
    }
    close(AUTHKEYS);

    if (!chmod(0600, "${keyfile}.new")) {
	warn("*** WARNING: Could not chmod ${keyfile}.new: $!\n");
	return -1;
    }
    if (-e "${keyfile}") {
	if (system("cp -p -f ${keyfile} ${keyfile}.old")) {
	    warn("*** Could not save off ${keyfile}: $!\n");
	    return -1;
	}
	if (!chmod(0600, "${keyfile}.old")) {
	    warn("*** Could not chmod ${keyfile}.old: $!\n");
	}
    }
    if (system("mv -f ${keyfile}.new ${keyfile}")) {
	warn("*** Could not mv ${keyfile} to ${keyfile}.new: $!\n");
    }
Leigh Stoller's avatar
Leigh Stoller committed
538 539 540 541 542 543
    elsif (-e "$sshdir/authorized_keys2") {
	#
	# Save to remove deprecated authorized_keys2 file at this point.
	#
	unlink("$sshdir/authorized_keys2");
    }
544 545 546 547 548 549 550 551 552
    return 0;
}

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

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