sign-file 12 KB

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