sign-file 12 KB

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