Merge tag 'locks-v3.16-2' of git://git.samba.org/jlayton/linux
[linux/fpc-iii.git] / scripts / sign-file
blob2b7c4484d46cd5e28a9570fb3c8ff414213fff75
1 #!/usr/bin/perl -w
3 # Sign a module file using the given key.
6 my $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";
10 use strict;
11 use FileHandle;
12 use IPC::Open2;
13 use Getopt::Std;
15 my %opts;
16 getopts('vs:', \%opts) or die $USAGE;
17 my $verbose = $opts{'v'};
18 my $signature_file = $opts{'s'};
20 die $USAGE if ($#ARGV > 4);
21 die $USAGE if (!$signature_file && $#ARGV < 3 || $signature_file && $#ARGV < 2);
23 my $dgst = shift @ARGV;
24 my $private_key;
25 if (!$signature_file) {
26 $private_key = shift @ARGV;
28 my $x509 = shift @ARGV;
29 my $module = shift @ARGV;
30 my ($dest, $keep_orig);
31 if (@ARGV) {
32 $dest = $ARGV[0];
33 $keep_orig = 1;
34 } else {
35 $dest = $module . "~";
38 die "Can't read private key\n" if (!$signature_file && !-r $private_key);
39 die "Can't read signature file\n" if ($signature_file && !-r $signature_file);
40 die "Can't read X.509 certificate\n" unless (-r $x509);
41 die "Can't read module\n" unless (-r $module);
44 # Function to read the contents of a file into a variable.
46 sub read_file($)
48 my ($file) = @_;
49 my $contents;
50 my $len;
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;
63 ###############################################################################
65 # First of all, we have to parse the X.509 certificate to find certain details
66 # about it.
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.
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.
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.
79 ###############################################################################
80 my $x509_certificate = read_file($x509);
82 my $UNIV = 0 << 6;
83 my $APPL = 1 << 6;
84 my $CONT = 2 << 6;
85 my $PRIV = 3 << 6;
87 my $CONS = 0x20;
89 my $BOOLEAN = 0x01;
90 my $INTEGER = 0x02;
91 my $BIT_STRING = 0x03;
92 my $OCTET_STRING = 0x04;
93 my $NULL = 0x05;
94 my $OBJ_ID = 0x06;
95 my $UTF8String = 0x0c;
96 my $SEQUENCE = 0x10;
97 my $SET = 0x11;
98 my $UTCTime = 0x17;
99 my $GeneralizedTime = 0x18;
101 my %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"
114 ###############################################################################
116 # Extract an ASN.1 element from a string and return information about it.
118 ###############################################################################
119 sub asn1_extract($$@)
121 my ($cursor, $expected_tag, $optional) = @_;
123 return [ -1 ]
124 if ($cursor->[1] == 0 && $optional);
126 die $x509, ": ", $cursor->[0], ": ASN.1 data underrun (elem ", $cursor->[1], ")\n"
127 if ($cursor->[1] < 2);
129 my ($tag, $len) = unpack("CC", substr(${$cursor->[2]}, $cursor->[0], 2));
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";
138 $cursor->[0] += 2;
139 $cursor->[1] -= 2;
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);
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);
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";
164 $cursor->[0] += $l;
165 $cursor->[1] -= $l;
168 die $x509, ": ", $cursor->[0], ": ASN.1 data underrun (", $len, ")\n"
169 if ($cursor->[1] < $len);
171 my $ret = [ $tag, [ $cursor->[0], $len, $cursor->[2] ] ];
172 $cursor->[0] += $len;
173 $cursor->[1] -= $len;
175 return $ret;
178 ###############################################################################
180 # Retrieve the data referred to by a cursor
182 ###############################################################################
183 sub asn1_retrieve($)
185 my ($cursor) = @_;
186 my ($offset, $len, $data) = @$cursor;
187 return substr($$data, $offset, $len);
190 ###############################################################################
192 # Roughly parse the X.509 certificate
194 ###############################################################################
195 my $cursor = [ 0, length($x509_certificate), \$x509_certificate ];
197 my $cert = asn1_extract($cursor, $UNIV | $CONS | $SEQUENCE);
198 my $tbs = asn1_extract($cert->[1], $UNIV | $CONS | $SEQUENCE);
199 my $version = asn1_extract($tbs->[1], $CONT | $CONS | 0, 1);
200 my $serial_number = asn1_extract($tbs->[1], $UNIV | $INTEGER);
201 my $sig_type = asn1_extract($tbs->[1], $UNIV | $CONS | $SEQUENCE);
202 my $issuer = asn1_extract($tbs->[1], $UNIV | $CONS | $SEQUENCE);
203 my $validity = asn1_extract($tbs->[1], $UNIV | $CONS | $SEQUENCE);
204 my $subject = asn1_extract($tbs->[1], $UNIV | $CONS | $SEQUENCE);
205 my $key = asn1_extract($tbs->[1], $UNIV | $CONS | $SEQUENCE);
206 my $issuer_uid = asn1_extract($tbs->[1], $CONT | $CONS | 1, 1);
207 my $subject_uid = asn1_extract($tbs->[1], $CONT | $CONS | 2, 1);
208 my $extension_list = asn1_extract($tbs->[1], $CONT | $CONS | 3, 1);
210 my $subject_key_id = ();
211 my $authority_key_id = ();
214 # Parse the extension list
216 if ($extension_list->[0] != -1) {
217 my $extensions = asn1_extract($extension_list->[1], $UNIV | $CONS | $SEQUENCE);
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);
225 my $raw_oid = asn1_retrieve($x_oid->[1]);
226 next if (!exists($OIDs{$raw_oid}));
227 my $x_type = $OIDs{$raw_oid};
229 my $raw_value = asn1_retrieve($x_val->[1]);
231 if ($x_type eq "subjectKeyIdentifier") {
232 my $vcursor = [ 0, length($raw_value), \$raw_value ];
234 $subject_key_id = asn1_extract($vcursor, $UNIV | $OCTET_STRING);
239 ###############################################################################
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.
244 ###############################################################################
245 my $org = "";
246 my $cn = "";
247 my $email = "";
249 while ($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);
255 my $raw_oid = asn1_retrieve($n_oid->[1]);
256 next if (!exists($OIDs{$raw_oid}));
257 my $n_type = $OIDs{$raw_oid};
259 my $raw_value = asn1_retrieve($n_val->[1]);
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;
270 my $signers_name = $email;
272 if ($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;
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;
288 $signers_name = $org . ": " . $cn;
289 } elsif ($org) {
290 $signers_name = $org;
291 } elsif ($cn) {
292 $signers_name = $cn;
295 got_id_name:
297 die $x509, ": ", "X.509: Couldn't find the Subject Key Identifier extension\n"
298 if (!$subject_key_id);
300 my $key_identifier = asn1_retrieve($subject_key_id->[1]);
302 ###############################################################################
304 # Create and attach the module signature
306 ###############################################################################
309 # Signature parameters
311 my $algo = 1; # Public-key crypto algorithm: RSA
312 my $hash = 0; # Digest algorithm
313 my $id_type = 1; # Identifier type: X.509
316 # Digest the data
318 my $prologue;
319 if ($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";
353 my $signature;
354 if ($signature_file) {
355 $signature = read_file($signature_file);
356 } else {
358 # Generate the digest and read from openssl's stdout
360 my $digest;
361 $digest = readpipe("openssl dgst -$dgst -binary $module") || die "openssl dgst";
364 # Generate the binary signature, which will be just the integer that
365 # comprises the signature with no metadata attached.
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";
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);
381 $signature = pack("n", length($signature)) . $signature,
384 # Build the signed binary
386 my $unsigned_module = read_file($module);
388 my $magic_number = "~Module signature appended~\n";
390 my $info = pack("CCCCCxxxN",
391 $algo, $hash, $id_type,
392 length($signers_name),
393 length($key_identifier),
394 length($signature));
396 if ($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 informaton : ", 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";
407 open(FD, ">$dest") || die $dest;
408 binmode FD;
409 print FD
410 $unsigned_module,
411 $signers_name,
412 $key_identifier,
413 $signature,
414 $info,
415 $magic_number
417 close FD || die $dest;
419 if (!$keep_orig) {
420 rename($dest, $module) || die $module;