1#!/usr/bin/perl -w 2# 3# Sign a module file using the given key. 4# 5 6my $USAGE = 7"Usage: scripts/sign-file [-v] <hash algo> <key> <x509> <module> [<dest>]\n" . 8" scripts/sign-file [-v] -s <raw sig> <hash algo> <x509> <module> [<dest>]\n"; 9 10use strict; 11use FileHandle; 12use IPC::Open2; 13use Getopt::Std; 14 15my %opts; 16getopts('vs:', \%opts) or die $USAGE; 17my $verbose = $opts{'v'}; 18my $signature_file = $opts{'s'}; 19 20die $USAGE if ($#ARGV > 4); 21die $USAGE if (!$signature_file && $#ARGV < 3 || $signature_file && $#ARGV < 2); 22 23my $dgst = shift @ARGV; 24my $private_key; 25if (!$signature_file) { 26 $private_key = shift @ARGV; 27} 28my $x509 = shift @ARGV; 29my $module = shift @ARGV; 30my ($dest, $keep_orig); 31if (@ARGV) { 32 $dest = $ARGV[0]; 33 $keep_orig = 1; 34} else { 35 $dest = $module . "~"; 36} 37 38die "Can't read private key\n" if (!$signature_file && !-r $private_key); 39die "Can't read signature file\n" if ($signature_file && !-r $signature_file); 40die "Can't read X.509 certificate\n" unless (-r $x509); 41die "Can't read module\n" unless (-r $module); 42 43# 44# Function to read the contents of a file into a variable. 45# 46sub read_file($) 47{ 48 my ($file) = @_; 49 my $contents; 50 my $len; 51 52 open(FD, "<$file") || die $file; 53 binmode FD; 54 my @st = stat(FD); 55 die $file if (!@st); 56 $len = read(FD, $contents, $st[7]) || die $file; 57 close(FD) || die $file; 58 die "$file: Wanted length ", $st[7], ", got ", $len, "\n" 59 if ($len != $st[7]); 60 return $contents; 61} 62 63############################################################################### 64# 65# First of all, we have to parse the X.509 certificate to find certain details 66# about it. 67# 68# We read the DER-encoded X509 certificate and parse it to extract the Subject 69# name and Subject Key Identifier. Theis provides the data we need to build 70# the certificate identifier. 71# 72# The signer's name part of the identifier is fabricated from the commonName, 73# the organizationName or the emailAddress components of the X.509 subject 74# name. 75# 76# The subject key ID is used to select which of that signer's certificates 77# we're intending to use to sign the module. 78# 79############################################################################### 80my $x509_certificate = read_file($x509); 81 82my $UNIV = 0 << 6; 83my $APPL = 1 << 6; 84my $CONT = 2 << 6; 85my $PRIV = 3 << 6; 86 87my $CONS = 0x20; 88 89my $BOOLEAN = 0x01; 90my $INTEGER = 0x02; 91my $BIT_STRING = 0x03; 92my $OCTET_STRING = 0x04; 93my $NULL = 0x05; 94my $OBJ_ID = 0x06; 95my $UTF8String = 0x0c; 96my $SEQUENCE = 0x10; 97my $SET = 0x11; 98my $UTCTime = 0x17; 99my $GeneralizedTime = 0x18; 100 101my %OIDs = ( 102 pack("CCC", 85, 4, 3) => "commonName", 103 pack("CCC", 85, 4, 6) => "countryName", 104 pack("CCC", 85, 4, 10) => "organizationName", 105 pack("CCC", 85, 4, 11) => "organizationUnitName", 106 pack("CCCCCCCCC", 42, 134, 72, 134, 247, 13, 1, 1, 1) => "rsaEncryption", 107 pack("CCCCCCCCC", 42, 134, 72, 134, 247, 13, 1, 1, 5) => "sha1WithRSAEncryption", 108 pack("CCCCCCCCC", 42, 134, 72, 134, 247, 13, 1, 9, 1) => "emailAddress", 109 pack("CCC", 85, 29, 35) => "authorityKeyIdentifier", 110 pack("CCC", 85, 29, 14) => "subjectKeyIdentifier", 111 pack("CCC", 85, 29, 19) => "basicConstraints" 112); 113 114############################################################################### 115# 116# Extract an ASN.1 element from a string and return information about it. 117# 118############################################################################### 119sub asn1_extract($$@) 120{ 121 my ($cursor, $expected_tag, $optional) = @_; 122 123 return [ -1 ] 124 if ($cursor->[1] == 0 && $optional); 125 126 die $x509, ": ", $cursor->[0], ": ASN.1 data underrun (elem ", $cursor->[1], ")\n" 127 if ($cursor->[1] < 2); 128 129 my ($tag, $len) = unpack("CC", substr(${$cursor->[2]}, $cursor->[0], 2)); 130 131 if ($expected_tag != -1 && $tag != $expected_tag) { 132 return [ -1 ] 133 if ($optional); 134 die $x509, ": ", $cursor->[0], ": ASN.1 unexpected tag (", $tag, 135 " not ", $expected_tag, ")\n"; 136 } 137 138 $cursor->[0] += 2; 139 $cursor->[1] -= 2; 140 141 die $x509, ": ", $cursor->[0], ": ASN.1 long tag\n" 142 if (($tag & 0x1f) == 0x1f); 143 die $x509, ": ", $cursor->[0], ": ASN.1 indefinite length\n" 144 if ($len == 0x80); 145 146 if ($len > 0x80) { 147 my $l = $len - 0x80; 148 die $x509, ": ", $cursor->[0], ": ASN.1 data underrun (len len $l)\n" 149 if ($cursor->[1] < $l); 150 151 if ($l == 0x1) { 152 $len = unpack("C", substr(${$cursor->[2]}, $cursor->[0], 1)); 153 } elsif ($l == 0x2) { 154 $len = unpack("n", substr(${$cursor->[2]}, $cursor->[0], 2)); 155 } elsif ($l == 0x3) { 156 $len = unpack("C", substr(${$cursor->[2]}, $cursor->[0], 1)) << 16; 157 $len = unpack("n", substr(${$cursor->[2]}, $cursor->[0] + 1, 2)); 158 } elsif ($l == 0x4) { 159 $len = unpack("N", substr(${$cursor->[2]}, $cursor->[0], 4)); 160 } else { 161 die $x509, ": ", $cursor->[0], ": ASN.1 element too long (", $l, ")\n"; 162 } 163 164 $cursor->[0] += $l; 165 $cursor->[1] -= $l; 166 } 167 168 die $x509, ": ", $cursor->[0], ": ASN.1 data underrun (", $len, ")\n" 169 if ($cursor->[1] < $len); 170 171 my $ret = [ $tag, [ $cursor->[0], $len, $cursor->[2] ] ]; 172 $cursor->[0] += $len; 173 $cursor->[1] -= $len; 174 175 return $ret; 176} 177 178############################################################################### 179# 180# Retrieve the data referred to by a cursor 181# 182############################################################################### 183sub asn1_retrieve($) 184{ 185 my ($cursor) = @_; 186 my ($offset, $len, $data) = @$cursor; 187 return substr($$data, $offset, $len); 188} 189 190############################################################################### 191# 192# Roughly parse the X.509 certificate 193# 194############################################################################### 195my $cursor = [ 0, length($x509_certificate), \$x509_certificate ]; 196 197my $cert = asn1_extract($cursor, $UNIV | $CONS | $SEQUENCE); 198my $tbs = asn1_extract($cert->[1], $UNIV | $CONS | $SEQUENCE); 199my $version = asn1_extract($tbs->[1], $CONT | $CONS | 0, 1); 200my $serial_number = asn1_extract($tbs->[1], $UNIV | $INTEGER); 201my $sig_type = asn1_extract($tbs->[1], $UNIV | $CONS | $SEQUENCE); 202my $issuer = asn1_extract($tbs->[1], $UNIV | $CONS | $SEQUENCE); 203my $validity = asn1_extract($tbs->[1], $UNIV | $CONS | $SEQUENCE); 204my $subject = asn1_extract($tbs->[1], $UNIV | $CONS | $SEQUENCE); 205my $key = asn1_extract($tbs->[1], $UNIV | $CONS | $SEQUENCE); 206my $issuer_uid = asn1_extract($tbs->[1], $CONT | $CONS | 1, 1); 207my $subject_uid = asn1_extract($tbs->[1], $CONT | $CONS | 2, 1); 208my $extension_list = asn1_extract($tbs->[1], $CONT | $CONS | 3, 1); 209 210my $subject_key_id = (); 211my $authority_key_id = (); 212 213# 214# Parse the extension list 215# 216if ($extension_list->[0] != -1) { 217 my $extensions = asn1_extract($extension_list->[1], $UNIV | $CONS | $SEQUENCE); 218 219 while ($extensions->[1]->[1] > 0) { 220 my $ext = asn1_extract($extensions->[1], $UNIV | $CONS | $SEQUENCE); 221 my $x_oid = asn1_extract($ext->[1], $UNIV | $OBJ_ID); 222 my $x_crit = asn1_extract($ext->[1], $UNIV | $BOOLEAN, 1); 223 my $x_val = asn1_extract($ext->[1], $UNIV | $OCTET_STRING); 224 225 my $raw_oid = asn1_retrieve($x_oid->[1]); 226 next if (!exists($OIDs{$raw_oid})); 227 my $x_type = $OIDs{$raw_oid}; 228 229 my $raw_value = asn1_retrieve($x_val->[1]); 230 231 if ($x_type eq "subjectKeyIdentifier") { 232 my $vcursor = [ 0, length($raw_value), \$raw_value ]; 233 234 $subject_key_id = asn1_extract($vcursor, $UNIV | $OCTET_STRING); 235 } 236 } 237} 238 239############################################################################### 240# 241# Determine what we're going to use as the signer's name. In order of 242# preference, take one of: commonName, organizationName or emailAddress. 243# 244############################################################################### 245my $org = ""; 246my $cn = ""; 247my $email = ""; 248 249while ($subject->[1]->[1] > 0) { 250 my $rdn = asn1_extract($subject->[1], $UNIV | $CONS | $SET); 251 my $attr = asn1_extract($rdn->[1], $UNIV | $CONS | $SEQUENCE); 252 my $n_oid = asn1_extract($attr->[1], $UNIV | $OBJ_ID); 253 my $n_val = asn1_extract($attr->[1], -1); 254 255 my $raw_oid = asn1_retrieve($n_oid->[1]); 256 next if (!exists($OIDs{$raw_oid})); 257 my $n_type = $OIDs{$raw_oid}; 258 259 my $raw_value = asn1_retrieve($n_val->[1]); 260 261 if ($n_type eq "organizationName") { 262 $org = $raw_value; 263 } elsif ($n_type eq "commonName") { 264 $cn = $raw_value; 265 } elsif ($n_type eq "emailAddress") { 266 $email = $raw_value; 267 } 268} 269 270my $signers_name = $email; 271 272if ($org && $cn) { 273 # Don't use the organizationName if the commonName repeats it 274 if (length($org) <= length($cn) && 275 substr($cn, 0, length($org)) eq $org) { 276 $signers_name = $cn; 277 goto got_id_name; 278 } 279 280 # Or a signifcant chunk of it 281 if (length($org) >= 7 && 282 length($cn) >= 7 && 283 substr($cn, 0, 7) eq substr($org, 0, 7)) { 284 $signers_name = $cn; 285 goto got_id_name; 286 } 287 288 $signers_name = $org . ": " . $cn; 289} elsif ($org) { 290 $signers_name = $org; 291} elsif ($cn) { 292 $signers_name = $cn; 293} 294 295got_id_name: 296 297die $x509, ": ", "X.509: Couldn't find the Subject Key Identifier extension\n" 298 if (!$subject_key_id); 299 300my $key_identifier = asn1_retrieve($subject_key_id->[1]); 301 302############################################################################### 303# 304# Create and attach the module signature 305# 306############################################################################### 307 308# 309# Signature parameters 310# 311my $algo = 1; # Public-key crypto algorithm: RSA 312my $hash = 0; # Digest algorithm 313my $id_type = 1; # Identifier type: X.509 314 315# 316# Digest the data 317# 318my $prologue; 319if ($dgst eq "sha1") { 320 $prologue = pack("C*", 321 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 322 0x2B, 0x0E, 0x03, 0x02, 0x1A, 323 0x05, 0x00, 0x04, 0x14); 324 $hash = 2; 325} elsif ($dgst eq "sha224") { 326 $prologue = pack("C*", 327 0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 328 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 329 0x05, 0x00, 0x04, 0x1C); 330 $hash = 7; 331} elsif ($dgst eq "sha256") { 332 $prologue = pack("C*", 333 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 334 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 335 0x05, 0x00, 0x04, 0x20); 336 $hash = 4; 337} elsif ($dgst eq "sha384") { 338 $prologue = pack("C*", 339 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 340 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 341 0x05, 0x00, 0x04, 0x30); 342 $hash = 5; 343} elsif ($dgst eq "sha512") { 344 $prologue = pack("C*", 345 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 346 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 347 0x05, 0x00, 0x04, 0x40); 348 $hash = 6; 349} else { 350 die "Unknown hash algorithm: $dgst\n"; 351} 352 353my $signature; 354if ($signature_file) { 355 $signature = read_file($signature_file); 356} else { 357 # 358 # Generate the digest and read from openssl's stdout 359 # 360 my $digest; 361 $digest = readpipe("openssl dgst -$dgst -binary $module") || die "openssl dgst"; 362 363 # 364 # Generate the binary signature, which will be just the integer that 365 # comprises the signature with no metadata attached. 366 # 367 my $pid; 368 $pid = open2(*read_from, *write_to, 369 "openssl rsautl -sign -inkey $private_key -keyform PEM") || 370 die "openssl rsautl"; 371 binmode write_to; 372 print write_to $prologue . $digest || die "pipe to openssl rsautl"; 373 close(write_to) || die "pipe to openssl rsautl"; 374 375 binmode read_from; 376 read(read_from, $signature, 4096) || die "pipe from openssl rsautl"; 377 close(read_from) || die "pipe from openssl rsautl"; 378 waitpid($pid, 0) || die; 379 die "openssl rsautl died: $?" if ($? >> 8); 380} 381$signature = pack("n", length($signature)) . $signature, 382 383# 384# Build the signed binary 385# 386my $unsigned_module = read_file($module); 387 388my $magic_number = "~Module signature appended~\n"; 389 390my $info = pack("CCCCCxxxN", 391 $algo, $hash, $id_type, 392 length($signers_name), 393 length($key_identifier), 394 length($signature)); 395 396if ($verbose) { 397 print "Size of unsigned module: ", length($unsigned_module), "\n"; 398 print "Size of signer's name : ", length($signers_name), "\n"; 399 print "Size of key identifier : ", length($key_identifier), "\n"; 400 print "Size of signature : ", length($signature), "\n"; 401 print "Size of information : ", length($info), "\n"; 402 print "Size of magic number : ", length($magic_number), "\n"; 403 print "Signer's name : '", $signers_name, "'\n"; 404 print "Digest : $dgst\n"; 405} 406 407open(FD, ">$dest") || die $dest; 408binmode FD; 409print FD 410 $unsigned_module, 411 $signers_name, 412 $key_identifier, 413 $signature, 414 $info, 415 $magic_number 416 ; 417close FD || die $dest; 418 419if (!$keep_orig) { 420 rename($dest, $module) || die $module; 421} 422