verifygenicred.in 11.4 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2008-2013 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 23 24 25 26 27 28
# 
# {{{GENIPUBLIC-LICENSE
# 
# GENI Public License
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Work, and to permit persons to whom the Work
# is furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Work.
# 
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
# 
# }}}
29 30 31 32 33 34
#
use strict;
use English;
use Getopt::Std;
use XML::LibXML;
use Data::Dumper;
35 36
use Date::Parse;
use Time::Local;
37
use Cwd qw(realpath);
38 39

#
40
# Verify a GENI credential.
41 42 43
# 
sub usage()
{
44
    print("Usage: verifygenicred [-d] [-o file] <credfile>\n");
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 76 77
    exit(-1);
}
my $optlist = "do:";
my $debug   = 0;
my $outfile;
my $xmlfile;

#
# Configure variables
#
my $TB		= "@prefix@";
my $TBOPS	= "@TBOPSEMAIL@";
my $TBLOGS	= "@TBLOGSEMAIL@";
my $OURDOMAIN   = "@OURDOMAIN@";
my $CONTROL	= "@USERNODE@";
my $BOSSNODE	= "@BOSSNODE@";

#
# Load the Testbed support stuff.
#
use lib "@prefix@/lib";
use libtestbed;

#
# Turn off line buffering on output
#
$| = 1;

# Locals
my $USERDIR	= USERROOT();
my $SSLDIR      = "$TB/lib/ssl";
my $EMULAB_CERT = "$TB/etc/emulab.pem";
my $EMULAB_KEY  = "$TB/etc/emulab.key";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
78
my $GENICERTS   = "$TB/etc/genicacerts";
79
my $REVOKED     = "$TB/etc/genicrl.serials";
80
my $OPENSSL     = "/usr/bin/openssl";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
81 82 83
my $XMLLINT     = "/usr/local/bin/xmllint";
my $XMLSEC1     = "/usr/local/bin/xmlsec1";
my $SCHEMA      = "$TB/lib/protogeni/security/credential.xsd";
84 85 86 87 88
my $certfile;
my $keyfile;
my $deletefiles = 0;
my $certificate;
my $privkey;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
89
my %credentials = ();
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

#
# 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.
#
if ($UID == 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'};

#
# Function prototypes
#
sub fatal($);
sub cleanup();
119
sub lookup($$);
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151

#
# 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{"o"})) {
    $outfile = $options{"o"};
    
    if ($outfile =~ /^([-\w\.\/]+)$/) {
	$outfile = $1;
    }
    else {
	fatal("Tainted filename: $outfile");
    }
}
usage()
    if (!@ARGV);
$xmlfile = shift(@ARGV);
if ($xmlfile =~ /^([-\w\.\/]+)$/) {
    $xmlfile = $1;
}
else {
    fatal("Tainted filename: $xmlfile");
}
# Use realpath to resolve any symlinks.
152
my $translated = realpath($xmlfile);
153 154 155 156 157 158 159 160
if ($translated =~ /^(\/tmp\/[-\w\.\/]+)$/) {
    $xmlfile = $1;
}
else {
    fatal("Bad data in translated pathname: $xmlfile");
}

#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
161 162 163 164 165 166 167 168 169 170
# Verify that the credential conforms to the schema. The wrinkle is that it
# might already be a signed credential and we just need to add another
# signature to it, but either way it should still pass the schema check.
#
if (system("$XMLLINT -noout -schema $SCHEMA $xmlfile > /dev/null 2>&1")) {
    fatal("$xmlfile does not conform to schema $SCHEMA");
}

#
# Bring in the credential file so we can mess with it.
171 172 173
#
my $parser = XML::LibXML->new;
my $doc    = $parser->parse_file($xmlfile);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
174
my $root   = $doc->documentElement();
175

Leigh B. Stoller's avatar
Leigh B. Stoller committed
176 177 178 179 180 181
#
# Find the credential node, and then break up the hierarchy so that we
# can look at each part and then verify the chain of delegations.
#
my ($credentials_node) = $root->getElementsByTagName("credential");
my ($signatures_node)  = $root->getElementsByTagName("signatures");
182

Leigh B. Stoller's avatar
Leigh B. Stoller committed
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
if (! (defined($credentials_node) && defined($signatures_node))) {
    fatal("Malformed signed credentials input");
}
# Record the outermost credential in the array, indexed by name.
my ($xmlid_attribute) = $credentials_node->attributes();
my $xmlid = $xmlid_attribute->getValue();
$credentials{$xmlid} = { "node" => $credentials_node };

# Remember the leaf node, and the root which might change below.
my $leaf_xmlid = $xmlid;
my $leaf_cred  = $credentials_node;
my $root_xmlid = $leaf_xmlid;
my $root_cred  = $leaf_cred;

#
# The last child of the credentials node will be a parent credential,
# if there is a parent. Loop through finding each parent and place it
# in the credentials array. This is basically a doubly linked list of
# structures, each one pointing to its parent and child credentials. 
#
my $temp = $credentials_node;
while (defined($temp)) {
    my @childnodes  = $temp->childNodes();
    undef($temp);

    foreach my $child (@childnodes) {
	if (defined($child->localname) && $child->localname eq "parent") {
	    my ($parent_cred) = $child->getElementsByTagName("credential");
	    #print $parent_cred->toString() . "\n";

	    my ($xmlid_attribute) = $parent_cred->attributes();
	    my $parent_xmlid = $xmlid_attribute->getValue();
	    $credentials{$parent_xmlid} = { "node"        => $parent_cred,
					    "child_xmlid" => $xmlid,
					    "child_cred"  => $temp };

	    # Add this to the last credential info
	    $credentials{$xmlid}->{"parent_xmlid"} = $parent_xmlid;
	    $credentials{$xmlid}->{"parent_cred"}  = $parent_cred;
	    $xmlid = $parent_xmlid;
	    $temp  = $parent_cred;

	    # Remember this, might be root.
	    $root_xmlid = $xmlid;
	    $root_cred  = $temp;
	    last;
	}
    }
}
232

233 234 235 236 237 238 239 240 241
# Check that credentials have been delegated correctly: at each level,
# the privileges must be a subset of the parent, and the target GIDs
# must be equal.  The "can_delegate" flag must be set in the parent on
# all privileges which are delegated.  We should also check that the
# owner GID is correctly identified and authenticated by the included
# X.509 certificate, but this is NOT yet implemented!
foreach my $credential ( keys( %credentials ) ) {
    my $node = $credentials{$credential}->{"node"};

242
    my $expiry = lookup( $node, "expires" )->textContent;
243 244 245 246
    if ($expiry =~ /^(\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d)(\.\d+)?Z?$/)
    {
	$expiry = $1 . 'Z';
    }
247 248
    my $dateregexp = '^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\dZ?$';

Leigh B Stoller's avatar
Leigh B Stoller committed
249
    fatal( "invalid credential (malformed expiry)" )
250 251
	if $expiry !~ $dateregexp;

Leigh B Stoller's avatar
Leigh B Stoller committed
252
    fatal("invalid credential (expired at $expiry)")
Leigh B Stoller's avatar
Leigh B Stoller committed
253
	if (time() > timegm(strptime($expiry)));
254

255 256 257 258 259 260
    if( $node != $root_cred ) {
	my $parent = $credentials{$credential}->{"parent_cred"};

	my $gid = lookup( $node, "target_gid" )->textContent;
	my $parent_gid = lookup( $parent, "target_gid" )->textContent;

261 262 263 264
	$gid =~ s/-.*-//g;
	$gid =~ s/\s//g;
	$parent_gid =~ s/-.*-//g;
	$parent_gid =~ s/\s//g;
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281

	fatal( "invalid delegation (GID mismatch)" )
	    if $gid ne $parent_gid;

	my $type = lookup( $node, "type" )->textContent;
	my $parent_type = lookup( $parent, "type" )->textContent;

	fatal( "invalid delegation (type mismatch)" )
	    if $type ne $parent_type;

	if( $type eq "privilege" ) {
	    my @privs = grep( $_->nodeName eq "privilege",
			      lookup( $node, "privileges" )->childNodes );
	    my @parent_privs = grep( $_->nodeName eq "privilege",
				     lookup( $parent, 
					     "privileges" )->childNodes );
	    my %allowed = ();
282 283 284
	    $allowed{ lookup( $_, "name" )->textContent } = 1
		foreach grep( lookup( $_, "can_delegate" )->textContent =~
			      /1|true/i, @parent_privs );
285 286 287 288 289 290 291 292

	    foreach my $priv ( @privs ) {
		my $name = lookup( $priv, "name" )->textContent;

		fatal( "invalid delegation (privilege not available)" )
		    unless $allowed{ $name } or $allowed{ "*" };
	    }		
	}
293

294
	my $parent_expiry = lookup( $parent, "expires" )->textContent;
295 296

	fatal( "invalid delegation (malformed expiry)" )
297
	    if $parent_expiry !~ $dateregexp;
298 299

	fatal( "invalid delegation (expiry violation)" )
Leigh B Stoller's avatar
Leigh B Stoller committed
300
	    if timegm(strptime($expiry)) gt timegm(strptime($parent_expiry));
301 302

	fatal("invalid delegation (parent credential is expired)")
Leigh B Stoller's avatar
Leigh B Stoller committed
303
	    if (time() > timegm(strptime($parent_expiry))); 
304 305 306
    }
}

307 308 309 310 311 312 313 314 315 316 317
# Read in all entries from CRLs.
my %revoked = ();
if( -r $REVOKED ) {
    open( SERIALS, $REVOKED ) or fatal( "Cannot read $REVOKED" );
    while( <SERIALS> ) {
	chomp;
	$revoked{ $_ } = 1;
    }
    close( SERIALS );
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
318
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
319 320 321 322
# The certficate used to sign the credential was either the Emulab certificate
# or that of the user delegating the credential. For now we just worry about
# the emulab credentials. We have the trusted roots cached, so generate a list
# of them.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
323
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
324 325 326 327 328
opendir(DIR, "$GENICERTS") or
    fatal("Cannot opendir $GENICERTS: $!");
my @pemfiles = grep {/^.*\.pem$/} readdir(DIR);
closedir(DIR);

329
my $certarg = " " . join(" ", map("--trusted-pem $GENICERTS/$_", @pemfiles));
330

331 332 333 334 335 336 337
if( opendir( DIR, "$GENICERTS/local" ) ) {
    my @pemfiles = grep {/^.*\.pem$/} readdir(DIR);
    closedir(DIR);
    $certarg .= " " . join(" ", map("--trusted-pem $GENICERTS/local/$_",
				    @pemfiles));
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
338 339 340 341 342 343
#
# Lets first make sure that the data has not been messed with; for each
# credential in the hierarchy check the signature. Remember, the signature
# covers the credential and all the parents up to the top.
#
foreach my $sigid (keys(%credentials)) {
344 345
    my $nosigref = 0;
  again:
346
    my $cmd = "$XMLSEC1 --verify --store-signatures ";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
347 348
    $cmd .= "--print-debug "
	if ($debug);
349 350 351
    $cmd .= "--node-id ". ($nosigref ? $sigid : "Sig_${sigid}");

    $cmd .= "$certarg $xmlfile";
352
    print STDERR "$cmd\n"
Leigh B. Stoller's avatar
Leigh B. Stoller committed
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
	if ($debug);

    open(SEC, "$cmd 2>&1 |")
	or fatal("Could not start xmlsec1 on $xmlfile");

    #
    # xmlsec1 is really braindead. It returns zero status if the signature
    # verifies, even if the cert chain fails to verify. So, must get a single
    # line back, "OK" for us to consider it really okay.
    #
    my $bad  = 0;
    my $line = <SEC>;
    if (!defined($line) || !($line =~ /^OK$/)) {
	$bad = 1;
    }
368
    print STDERR $line
369
	if (defined($line) && ($debug || $bad));
370
    my $issuer = undef;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
371
    while (<SEC>) {
372
	print STDERR $_
Leigh B. Stoller's avatar
Leigh B. Stoller committed
373
	    if ($debug);
374 375 376 377 378 379
	$issuer = $1 if m{^==== Issuer Name:.+/CN=([^/]+)/};
	if( m{^==== Issuer Serial: (.+)} ) {
	    $issuer and $revoked{ "$issuer $1" } and
		fatal( "Certificate $issuer $1 has been revoked" );		
	    $issuer = undef;
	}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
380
    }
381 382 383 384 385 386 387 388 389 390 391 392
    if (!close(SEC)) {
	if (! $|) {
	    fatal("Error closing $XMLSEC1 pipe: $!");
	}
	if ($debug) {
	    print STDERR "Exit status $? from $XMLSEC1\n";
	}
    }
    if ($bad && !$nosigref) {
	$nosigref = 1;
	goto again;
    }
Leigh B. Stoller's avatar
Leigh B. Stoller committed
393 394
    fatal("$sigid in $xmlfile did not verify!")
	if ($bad);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
395
}
396 397 398 399 400 401 402 403 404 405 406 407 408
exit(0);

sub cleanup()
{
}

sub fatal($)
{
    my($mesg) = $_[0];
    cleanup();
    die("*** $0:\n".
	"    $mesg\n");
}
409 410 411 412 413 414 415 416

# Look up an element (which must exist exactly once) within a node.
sub lookup($$)
{
    my( $node, $name ) = @_;

    my @cnodes = grep( $_->nodeName eq $name, $node->childNodes );

417 418
    fatal( "invalid credential (found " . scalar( @cnodes ) . " $name " .
	   "nodes, expecting 1)" )
419 420 421 422
	if scalar( @cnodes ) != 1;

    return $cnodes[ 0 ];
}