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