signgenicred.in 9.01 KB
Newer Older
1 2
#!/usr/bin/perl -w
#
3
# Copyright (c) 2008-2011 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 35 36 37 38 39 40
#
use strict;
use English;
use Getopt::Std;
use XML::LibXML;
use Data::Dumper;

#
# Sign a GENI credential
# 
sub usage()
{
Leigh B. Stoller's avatar
Leigh B. Stoller committed
41
    print("Usage: signgenicred [-d] [-o file] [-c cert] <capfile> [<user>]\n");
42 43
    exit(-1);
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
44
my $optlist = "do:c:";
45
my $debug   = 0;
46 47
my $outfile;
my $capfile;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
48
my $certificate;
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65

#
# 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 libaudit;
use libtestbed;
66
use GeniUtil();
67 68 69 70 71 72 73 74
#
# Turn off line buffering on output
#
$| = 1;

# Locals
my $USERDIR	= USERROOT();
my $SSLDIR      = "$TB/lib/ssl";
Leigh B. Stoller's avatar
Leigh B. Stoller committed
75 76
my $EMULAB_CERT = "$TB/etc/genisa.pem";
my $EMULAB_KEY  = "$TB/etc/genisa.pem";
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
my $SCHEMA      = "$TB/lib/protogeni/security/credential.xsd";
my $OPENSSL     = "/usr/bin/openssl";
my $XMLLINT     = "/usr/local/bin/xmllint";
my $XMLSEC1     = "/usr/local/bin/xmlsec1";
my $SAVEUID	= $UID;
my $tmpfile     = "/tmp/signcred$$";
my $certfile;
my $keyfile;
my $sigid;
my $deletefiles = 0;

#
# This is a template for the xmlsec library.
#
my $sigtmpl =
    "<Signature xml:id=\"%s\" >\n".
    " <SignedInfo>\n".
    "  <CanonicalizationMethod ".
    "     Algorithm=\"http://www.w3.org/TR/2001/REC-xml-c14n-20010315\"/>\n".
    "  <SignatureMethod ".
    "     Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\"/>\n".
Leigh B. Stoller's avatar
Leigh B. Stoller committed
98
    "  <Reference URI=\"#%s\">\n".
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 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
    "    <Transforms>\n".
    "      <Transform ".
    "        Algorithm=\"http://www.w3.org/2000/09/xmldsig#".
    "enveloped-signature\" />\n".
    "    </Transforms>\n".
    "    <DigestMethod ".
    "       Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\"/>\n".
    "    <DigestValue></DigestValue>\n".
    "    </Reference>\n".
    " </SignedInfo>\n".
    " <SignatureValue />\n".
    " <KeyInfo>\n".
    "  <X509Data >\n".
    "   <X509SubjectName/>\n".
    "   <X509IssuerSerial/>\n".
    "   <X509Certificate/>\n".
    "  </X509Data>\n".
    "  <KeyValue />\n".
    " </KeyInfo>\n".
    "</Signature>\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();

#
# 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");
    }
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
153 154 155 156 157 158 159 160 161 162 163 164
if (defined($options{"c"})) {
    $certificate = $options{"c"};
    
    if ($certificate =~ /^([-\w\.\/]+)$/) {
	$certificate = $1;
    }
    else {
	fatal("Tainted filename: $certificate");
    }
    fatal("$certificate does not exist or cannot be read.")
	if (! -r $certificate);
}
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
usage()
    if (!@ARGV);
$capfile = shift(@ARGV);
if ($capfile =~ /^([-\w\.\/]+)$/) {
    $capfile = $1;
}
else {
    fatal("Tainted filename: $capfile");
}

#
# This script is always audited. Mail is sent automatically upon exit.
#
if (0 && AuditStart(0)) {
    #
    # Parent exits normally
    #
    exit(0);
}

#
# 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.
#
Leigh B. Stoller's avatar
Leigh B. Stoller committed
190 191 192 193 194 195 196 197
my $xmlint_output = "";

open(TMP, "$XMLLINT -noout -schema $SCHEMA $capfile 2>&1 |")
    or fatal("Could not start $XMLLINT on $capfile");
while(<TMP>) {
    $xmlint_output .= $_;
}
if (!close(TMP)) {
198
    print STDERR $xmlint_output;
199 200 201 202 203 204 205 206 207 208 209 210
    fatal("$capfile does not conform to schema $SCHEMA");
}

#
# Bring in the credential file so we can mess with it.
#
my $parser = XML::LibXML->new;
my $doc    = $parser->parse_file($capfile);
my $root   = $doc->documentElement();

#
# The certficate used to sign the credential is either the Emulab certificate
Leigh B. Stoller's avatar
Leigh B. Stoller committed
211 212
# or that of the user delegating the credential, or a certificate specified
# on the command line.
213
#
214 215 216
if (defined($certificate)) {
    $keyfile  = $certificate;
    $certfile = $certificate;
Leigh B. Stoller's avatar
Leigh B. Stoller committed
217 218 219 220 221
}
else {
    $keyfile  = $EMULAB_KEY;
    $certfile = $EMULAB_CERT;
}
222

Leigh B. Stoller's avatar
Leigh B. Stoller committed
223 224 225 226 227 228
#
# Find or create these two nodes.
#
my $credentials_node;
my $signatures_node;

229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
#
# Check the root.
#
if ($root->nodeName eq "credential") {
    #
    # If its a credential then this is the first signing. We have to
    # create a new document that wraps the credential up and adds the
    # signing template (see above). When done, it will look like;
    #
    # <signed-credential>
    #  <original capfile>
    #  <signatures>
    #   <signature></signature>
    #  </signatures>
    # </signed-credential>
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
245
    my $newroot       = XML::LibXML::Element->new('signed-credential');
246 247
    $newroot->setNamespace($GeniUtil::XSI_NS, "xsi", 0);
    $newroot->setAttributeNS($GeniUtil::XSI_NS, "noNamespaceSchemaLocation"
248
                           , $GeniUtil::CREDENTIAL_SCHEMA_LOCATION);
249 250 251 252
    $newroot->setAttributeNS($GeniUtil::XSI_NS, "schemaLocation"
                           , $GeniUtil::EXTENSIONS_NS . " " 
                           . $GeniUtil::EXTENSIONS_SCHEMA_LOCATION);

Leigh B. Stoller's avatar
Leigh B. Stoller committed
253 254
    $signatures_node  = XML::LibXML::Element->new('signatures');
    $credentials_node = $root;
255 256 257 258 259
    $newroot->addChild($root);
    $newroot->addChild($signatures_node);

    $root = $newroot;
    $doc->setDocumentElement($root);
Leigh B. Stoller's avatar
Leigh B. Stoller committed
260
    #print $root->toString(1) . "\n";
261 262
}
else {
263 264 265 266 267 268 269 270 271 272 273
    #
    # Must be consistent about namespaces or else the signature does
    # not verify later. 
    #
    $root->setNamespace($GeniUtil::XSI_NS, "xsi", 0);
    $root->setAttributeNS($GeniUtil::XSI_NS, "noNamespaceSchemaLocation"
			  , $GeniUtil::CREDENTIAL_SCHEMA_LOCATION);
    $root->setAttributeNS($GeniUtil::XSI_NS, "schemaLocation"
			  , $GeniUtil::EXTENSIONS_NS . " " 
			  . $GeniUtil::EXTENSIONS_SCHEMA_LOCATION);
    
Leigh B. Stoller's avatar
Leigh B. Stoller committed
274 275 276 277 278 279
    ($credentials_node) = $root->getElementsByTagName("credential");
    ($signatures_node)  = $root->getElementsByTagName("signatures");

    if (! (defined($credentials_node) && defined($signatures_node))) {
	fatal("Malformed signed credentials input");
    }
280 281
}

Leigh B. Stoller's avatar
Leigh B. Stoller committed
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
#
# We need the id of the toplevel credential so that we can stick
# it into the sig template above, in the References section. We
# also need to generate an id for the signature node so that we
# can find it and tell xmlsec about it.
#
my ($xmlid_attribute) = $credentials_node->attributes();
my $xmlid = $xmlid_attribute->getValue();
$sigid = "Sig_${xmlid}";
my $template = sprintf($sigtmpl, $sigid, $xmlid);

#
# Convert the template above into a document tree and add it to the
# signatures list.
#
my $tmpparser = XML::LibXML->new;
my $newdoc    = $tmpparser->parse_string($template);
my $sigroot   = $newdoc->documentElement();
$sigroot->setNamespace("http://www.w3.org/2000/09/xmldsig#");
$signatures_node->addChild($sigroot);
   
303 304 305 306 307
#
# So now we have a valid document that needs to be signed at the $sigid
# reference point. Must write this to a tmp file for xmlsec, and then
# use xmlsec to add the signature. 
#
308 309
# Paranoia.
unlink($tmpfile);
310
open(TMP, ">$tmpfile") or
311
    fatal("Could not open $tmpfile: $!");
312 313 314 315
print TMP $doc->toString(1) . "\n";
close(TMP);

# Fire up xmlsec and read back the results.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
316 317
my $signedcred = "";

318 319 320 321
open(SEC, "$XMLSEC1 --sign --node-id $sigid ".
     "       --privkey-pem $keyfile,$certfile $tmpfile |")
    or fatal("Could not start $XMLSEC1 on $tmpfile");
while (<SEC>) {
Leigh B. Stoller's avatar
Leigh B. Stoller committed
322
    $signedcred .= $_;
323
}
Leigh B. Stoller's avatar
Leigh B. Stoller committed
324 325 326
if (!close(SEC)) {
    fatal("$XMLSEC1 failed on $tmpfile");
}
327

Leigh B. Stoller's avatar
Leigh B. Stoller committed
328 329 330 331 332 333 334 335 336
if (!defined($outfile)) {
    print $signedcred;
}
else {
    open(TMP, ">$outfile") or
	fatal("Could not open $outfile");
    print TMP $signedcred;
    close(TMP);
}
337 338 339 340 341 342 343 344 345 346 347 348
cleanup();
exit(0);

sub cleanup()
{
    unlink($tmpfile)
	if (-e $tmpfile && !$debug);
}

sub fatal($)
{
    my($mesg) = $_[0];
349
    cleanup();
350 351 352
    die("*** $0:\n".
	"    $mesg\n");
}