Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

rsa.c 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. /*
  2. * Copyright (C) 2012 Michael Brown <mbrown@fensystems.co.uk>.
  3. *
  4. * This program is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU General Public License as
  6. * published by the Free Software Foundation; either version 2 of the
  7. * License, or any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful, but
  10. * WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  17. * 02110-1301, USA.
  18. *
  19. * You can also choose to distribute this program under the terms of
  20. * the Unmodified Binary Distribution Licence (as given in the file
  21. * COPYING.UBDL), provided that you have satisfied its requirements.
  22. */
  23. FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL );
  24. #include <stdint.h>
  25. #include <stdlib.h>
  26. #include <stdarg.h>
  27. #include <string.h>
  28. #include <errno.h>
  29. #include <ipxe/asn1.h>
  30. #include <ipxe/crypto.h>
  31. #include <ipxe/bigint.h>
  32. #include <ipxe/random_nz.h>
  33. #include <ipxe/rsa.h>
  34. /** @file
  35. *
  36. * RSA public-key cryptography
  37. *
  38. * RSA is documented in RFC 3447.
  39. */
  40. /* Disambiguate the various error causes */
  41. #define EACCES_VERIFY \
  42. __einfo_error ( EINFO_EACCES_VERIFY )
  43. #define EINFO_EACCES_VERIFY \
  44. __einfo_uniqify ( EINFO_EACCES, 0x01, "RSA signature incorrect" )
  45. /** "rsaEncryption" object identifier */
  46. static uint8_t oid_rsa_encryption[] = { ASN1_OID_RSAENCRYPTION };
  47. /** "rsaEncryption" OID-identified algorithm */
  48. struct asn1_algorithm rsa_encryption_algorithm __asn1_algorithm = {
  49. .name = "rsaEncryption",
  50. .pubkey = &rsa_algorithm,
  51. .digest = NULL,
  52. .oid = ASN1_OID_CURSOR ( oid_rsa_encryption ),
  53. };
  54. /**
  55. * Identify RSA prefix
  56. *
  57. * @v digest Digest algorithm
  58. * @ret prefix RSA prefix, or NULL
  59. */
  60. static struct rsa_digestinfo_prefix *
  61. rsa_find_prefix ( struct digest_algorithm *digest ) {
  62. struct rsa_digestinfo_prefix *prefix;
  63. for_each_table_entry ( prefix, RSA_DIGESTINFO_PREFIXES ) {
  64. if ( prefix->digest == digest )
  65. return prefix;
  66. }
  67. return NULL;
  68. }
  69. /**
  70. * Free RSA dynamic storage
  71. *
  72. * @v context RSA context
  73. */
  74. static void rsa_free ( struct rsa_context *context ) {
  75. free ( context->dynamic );
  76. context->dynamic = NULL;
  77. }
  78. /**
  79. * Allocate RSA dynamic storage
  80. *
  81. * @v context RSA context
  82. * @v modulus_len Modulus length
  83. * @v exponent_len Exponent length
  84. * @ret rc Return status code
  85. */
  86. static int rsa_alloc ( struct rsa_context *context, size_t modulus_len,
  87. size_t exponent_len ) {
  88. unsigned int size = bigint_required_size ( modulus_len );
  89. unsigned int exponent_size = bigint_required_size ( exponent_len );
  90. bigint_t ( size ) *modulus;
  91. bigint_t ( exponent_size ) *exponent;
  92. size_t tmp_len = bigint_mod_exp_tmp_len ( modulus, exponent );
  93. struct {
  94. bigint_t ( size ) modulus;
  95. bigint_t ( exponent_size ) exponent;
  96. bigint_t ( size ) input;
  97. bigint_t ( size ) output;
  98. uint8_t tmp[tmp_len];
  99. } __attribute__ (( packed )) *dynamic;
  100. /* Free any existing dynamic storage */
  101. rsa_free ( context );
  102. /* Allocate dynamic storage */
  103. dynamic = malloc ( sizeof ( *dynamic ) );
  104. if ( ! dynamic )
  105. return -ENOMEM;
  106. /* Assign dynamic storage */
  107. context->dynamic = dynamic;
  108. context->modulus0 = &dynamic->modulus.element[0];
  109. context->size = size;
  110. context->max_len = modulus_len;
  111. context->exponent0 = &dynamic->exponent.element[0];
  112. context->exponent_size = exponent_size;
  113. context->input0 = &dynamic->input.element[0];
  114. context->output0 = &dynamic->output.element[0];
  115. context->tmp = &dynamic->tmp;
  116. return 0;
  117. }
  118. /**
  119. * Parse RSA integer
  120. *
  121. * @v integer Integer to fill in
  122. * @v raw ASN.1 cursor
  123. * @ret rc Return status code
  124. */
  125. static int rsa_parse_integer ( struct asn1_cursor *integer,
  126. const struct asn1_cursor *raw ) {
  127. /* Enter integer */
  128. memcpy ( integer, raw, sizeof ( *integer ) );
  129. asn1_enter ( integer, ASN1_INTEGER );
  130. /* Skip initial sign byte if applicable */
  131. if ( ( integer->len > 1 ) &&
  132. ( *( ( uint8_t * ) integer->data ) == 0x00 ) ) {
  133. integer->data++;
  134. integer->len--;
  135. }
  136. /* Fail if cursor or integer are invalid */
  137. if ( ! integer->len )
  138. return -EINVAL;
  139. return 0;
  140. }
  141. /**
  142. * Parse RSA modulus and exponent
  143. *
  144. * @v modulus Modulus to fill in
  145. * @v exponent Exponent to fill in
  146. * @v raw ASN.1 cursor
  147. * @ret rc Return status code
  148. */
  149. static int rsa_parse_mod_exp ( struct asn1_cursor *modulus,
  150. struct asn1_cursor *exponent,
  151. const struct asn1_cursor *raw ) {
  152. struct asn1_bit_string bits;
  153. struct asn1_cursor cursor;
  154. int is_private;
  155. int rc;
  156. /* Enter subjectPublicKeyInfo/RSAPrivateKey */
  157. memcpy ( &cursor, raw, sizeof ( cursor ) );
  158. asn1_enter ( &cursor, ASN1_SEQUENCE );
  159. /* Determine key format */
  160. if ( asn1_type ( &cursor ) == ASN1_INTEGER ) {
  161. /* Private key */
  162. is_private = 1;
  163. /* Skip version */
  164. asn1_skip_any ( &cursor );
  165. } else {
  166. /* Public key */
  167. is_private = 0;
  168. /* Skip algorithm */
  169. asn1_skip ( &cursor, ASN1_SEQUENCE );
  170. /* Enter subjectPublicKey */
  171. if ( ( rc = asn1_integral_bit_string ( &cursor, &bits ) ) != 0 )
  172. return rc;
  173. cursor.data = bits.data;
  174. cursor.len = bits.len;
  175. /* Enter RSAPublicKey */
  176. asn1_enter ( &cursor, ASN1_SEQUENCE );
  177. }
  178. /* Extract modulus */
  179. if ( ( rc = rsa_parse_integer ( modulus, &cursor ) ) != 0 )
  180. return rc;
  181. asn1_skip_any ( &cursor );
  182. /* Skip public exponent, if applicable */
  183. if ( is_private )
  184. asn1_skip ( &cursor, ASN1_INTEGER );
  185. /* Extract publicExponent/privateExponent */
  186. if ( ( rc = rsa_parse_integer ( exponent, &cursor ) ) != 0 )
  187. return rc;
  188. return 0;
  189. }
  190. /**
  191. * Initialise RSA cipher
  192. *
  193. * @v ctx RSA context
  194. * @v key Key
  195. * @v key_len Length of key
  196. * @ret rc Return status code
  197. */
  198. static int rsa_init ( void *ctx, const void *key, size_t key_len ) {
  199. struct rsa_context *context = ctx;
  200. struct asn1_cursor modulus;
  201. struct asn1_cursor exponent;
  202. struct asn1_cursor cursor;
  203. int rc;
  204. /* Initialise context */
  205. memset ( context, 0, sizeof ( *context ) );
  206. /* Initialise cursor */
  207. cursor.data = key;
  208. cursor.len = key_len;
  209. /* Parse modulus and exponent */
  210. if ( ( rc = rsa_parse_mod_exp ( &modulus, &exponent, &cursor ) ) != 0 ){
  211. DBGC ( context, "RSA %p invalid modulus/exponent:\n", context );
  212. DBGC_HDA ( context, 0, cursor.data, cursor.len );
  213. goto err_parse;
  214. }
  215. DBGC ( context, "RSA %p modulus:\n", context );
  216. DBGC_HDA ( context, 0, modulus.data, modulus.len );
  217. DBGC ( context, "RSA %p exponent:\n", context );
  218. DBGC_HDA ( context, 0, exponent.data, exponent.len );
  219. /* Allocate dynamic storage */
  220. if ( ( rc = rsa_alloc ( context, modulus.len, exponent.len ) ) != 0 )
  221. goto err_alloc;
  222. /* Construct big integers */
  223. bigint_init ( ( ( bigint_t ( context->size ) * ) context->modulus0 ),
  224. modulus.data, modulus.len );
  225. bigint_init ( ( ( bigint_t ( context->exponent_size ) * )
  226. context->exponent0 ), exponent.data, exponent.len );
  227. return 0;
  228. rsa_free ( context );
  229. err_alloc:
  230. err_parse:
  231. return rc;
  232. }
  233. /**
  234. * Calculate RSA maximum output length
  235. *
  236. * @v ctx RSA context
  237. * @ret max_len Maximum output length
  238. */
  239. static size_t rsa_max_len ( void *ctx ) {
  240. struct rsa_context *context = ctx;
  241. return context->max_len;
  242. }
  243. /**
  244. * Perform RSA cipher operation
  245. *
  246. * @v context RSA context
  247. * @v in Input buffer
  248. * @v out Output buffer
  249. */
  250. static void rsa_cipher ( struct rsa_context *context,
  251. const void *in, void *out ) {
  252. bigint_t ( context->size ) *input = ( ( void * ) context->input0 );
  253. bigint_t ( context->size ) *output = ( ( void * ) context->output0 );
  254. bigint_t ( context->size ) *modulus = ( ( void * ) context->modulus0 );
  255. bigint_t ( context->exponent_size ) *exponent =
  256. ( ( void * ) context->exponent0 );
  257. /* Initialise big integer */
  258. bigint_init ( input, in, context->max_len );
  259. /* Perform modular exponentiation */
  260. bigint_mod_exp ( input, modulus, exponent, output, context->tmp );
  261. /* Copy out result */
  262. bigint_done ( output, out, context->max_len );
  263. }
  264. /**
  265. * Encrypt using RSA
  266. *
  267. * @v ctx RSA context
  268. * @v plaintext Plaintext
  269. * @v plaintext_len Length of plaintext
  270. * @v ciphertext Ciphertext
  271. * @ret ciphertext_len Length of ciphertext, or negative error
  272. */
  273. static int rsa_encrypt ( void *ctx, const void *plaintext,
  274. size_t plaintext_len, void *ciphertext ) {
  275. struct rsa_context *context = ctx;
  276. void *temp;
  277. uint8_t *encoded;
  278. size_t max_len = ( context->max_len - 11 );
  279. size_t random_nz_len = ( max_len - plaintext_len + 8 );
  280. int rc;
  281. /* Sanity check */
  282. if ( plaintext_len > max_len ) {
  283. DBGC ( context, "RSA %p plaintext too long (%zd bytes, max "
  284. "%zd)\n", context, plaintext_len, max_len );
  285. return -ERANGE;
  286. }
  287. DBGC ( context, "RSA %p encrypting:\n", context );
  288. DBGC_HDA ( context, 0, plaintext, plaintext_len );
  289. /* Construct encoded message (using the big integer output
  290. * buffer as temporary storage)
  291. */
  292. temp = context->output0;
  293. encoded = temp;
  294. encoded[0] = 0x00;
  295. encoded[1] = 0x02;
  296. if ( ( rc = get_random_nz ( &encoded[2], random_nz_len ) ) != 0 ) {
  297. DBGC ( context, "RSA %p could not generate random data: %s\n",
  298. context, strerror ( rc ) );
  299. return rc;
  300. }
  301. encoded[ 2 + random_nz_len ] = 0x00;
  302. memcpy ( &encoded[ context->max_len - plaintext_len ],
  303. plaintext, plaintext_len );
  304. /* Encipher the encoded message */
  305. rsa_cipher ( context, encoded, ciphertext );
  306. DBGC ( context, "RSA %p encrypted:\n", context );
  307. DBGC_HDA ( context, 0, ciphertext, context->max_len );
  308. return context->max_len;
  309. }
  310. /**
  311. * Decrypt using RSA
  312. *
  313. * @v ctx RSA context
  314. * @v ciphertext Ciphertext
  315. * @v ciphertext_len Ciphertext length
  316. * @v plaintext Plaintext
  317. * @ret plaintext_len Plaintext length, or negative error
  318. */
  319. static int rsa_decrypt ( void *ctx, const void *ciphertext,
  320. size_t ciphertext_len, void *plaintext ) {
  321. struct rsa_context *context = ctx;
  322. void *temp;
  323. uint8_t *encoded;
  324. uint8_t *end;
  325. uint8_t *zero;
  326. uint8_t *start;
  327. size_t plaintext_len;
  328. /* Sanity check */
  329. if ( ciphertext_len != context->max_len ) {
  330. DBGC ( context, "RSA %p ciphertext incorrect length (%zd "
  331. "bytes, should be %zd)\n",
  332. context, ciphertext_len, context->max_len );
  333. return -ERANGE;
  334. }
  335. DBGC ( context, "RSA %p decrypting:\n", context );
  336. DBGC_HDA ( context, 0, ciphertext, ciphertext_len );
  337. /* Decipher the message (using the big integer input buffer as
  338. * temporary storage)
  339. */
  340. temp = context->input0;
  341. encoded = temp;
  342. rsa_cipher ( context, ciphertext, encoded );
  343. /* Parse the message */
  344. end = ( encoded + context->max_len );
  345. if ( ( encoded[0] != 0x00 ) || ( encoded[1] != 0x02 ) )
  346. goto invalid;
  347. zero = memchr ( &encoded[2], 0, ( end - &encoded[2] ) );
  348. if ( ! zero )
  349. goto invalid;
  350. start = ( zero + 1 );
  351. plaintext_len = ( end - start );
  352. /* Copy out message */
  353. memcpy ( plaintext, start, plaintext_len );
  354. DBGC ( context, "RSA %p decrypted:\n", context );
  355. DBGC_HDA ( context, 0, plaintext, plaintext_len );
  356. return plaintext_len;
  357. invalid:
  358. DBGC ( context, "RSA %p invalid decrypted message:\n", context );
  359. DBGC_HDA ( context, 0, encoded, context->max_len );
  360. return -EINVAL;
  361. }
  362. /**
  363. * Encode RSA digest
  364. *
  365. * @v context RSA context
  366. * @v digest Digest algorithm
  367. * @v value Digest value
  368. * @v encoded Encoded digest
  369. * @ret rc Return status code
  370. */
  371. static int rsa_encode_digest ( struct rsa_context *context,
  372. struct digest_algorithm *digest,
  373. const void *value, void *encoded ) {
  374. struct rsa_digestinfo_prefix *prefix;
  375. size_t digest_len = digest->digestsize;
  376. uint8_t *temp = encoded;
  377. size_t digestinfo_len;
  378. size_t max_len;
  379. size_t pad_len;
  380. /* Identify prefix */
  381. prefix = rsa_find_prefix ( digest );
  382. if ( ! prefix ) {
  383. DBGC ( context, "RSA %p has no prefix for %s\n",
  384. context, digest->name );
  385. return -ENOTSUP;
  386. }
  387. digestinfo_len = ( prefix->len + digest_len );
  388. /* Sanity check */
  389. max_len = ( context->max_len - 11 );
  390. if ( digestinfo_len > max_len ) {
  391. DBGC ( context, "RSA %p %s digestInfo too long (%zd bytes, max"
  392. "%zd)\n",
  393. context, digest->name, digestinfo_len, max_len );
  394. return -ERANGE;
  395. }
  396. DBGC ( context, "RSA %p encoding %s digest:\n",
  397. context, digest->name );
  398. DBGC_HDA ( context, 0, value, digest_len );
  399. /* Construct encoded message */
  400. *(temp++) = 0x00;
  401. *(temp++) = 0x01;
  402. pad_len = ( max_len - digestinfo_len + 8 );
  403. memset ( temp, 0xff, pad_len );
  404. temp += pad_len;
  405. *(temp++) = 0x00;
  406. memcpy ( temp, prefix->data, prefix->len );
  407. temp += prefix->len;
  408. memcpy ( temp, value, digest_len );
  409. temp += digest_len;
  410. assert ( temp == ( encoded + context->max_len ) );
  411. DBGC ( context, "RSA %p encoded %s digest:\n", context, digest->name );
  412. DBGC_HDA ( context, 0, encoded, context->max_len );
  413. return 0;
  414. }
  415. /**
  416. * Sign digest value using RSA
  417. *
  418. * @v ctx RSA context
  419. * @v digest Digest algorithm
  420. * @v value Digest value
  421. * @v signature Signature
  422. * @ret signature_len Signature length, or negative error
  423. */
  424. static int rsa_sign ( void *ctx, struct digest_algorithm *digest,
  425. const void *value, void *signature ) {
  426. struct rsa_context *context = ctx;
  427. void *temp;
  428. int rc;
  429. DBGC ( context, "RSA %p signing %s digest:\n", context, digest->name );
  430. DBGC_HDA ( context, 0, value, digest->digestsize );
  431. /* Encode digest (using the big integer output buffer as
  432. * temporary storage)
  433. */
  434. temp = context->output0;
  435. if ( ( rc = rsa_encode_digest ( context, digest, value, temp ) ) != 0 )
  436. return rc;
  437. /* Encipher the encoded digest */
  438. rsa_cipher ( context, temp, signature );
  439. DBGC ( context, "RSA %p signed %s digest:\n", context, digest->name );
  440. DBGC_HDA ( context, 0, signature, context->max_len );
  441. return context->max_len;
  442. }
  443. /**
  444. * Verify signed digest value using RSA
  445. *
  446. * @v ctx RSA context
  447. * @v digest Digest algorithm
  448. * @v value Digest value
  449. * @v signature Signature
  450. * @v signature_len Signature length
  451. * @ret rc Return status code
  452. */
  453. static int rsa_verify ( void *ctx, struct digest_algorithm *digest,
  454. const void *value, const void *signature,
  455. size_t signature_len ) {
  456. struct rsa_context *context = ctx;
  457. void *temp;
  458. void *expected;
  459. void *actual;
  460. int rc;
  461. /* Sanity check */
  462. if ( signature_len != context->max_len ) {
  463. DBGC ( context, "RSA %p signature incorrect length (%zd "
  464. "bytes, should be %zd)\n",
  465. context, signature_len, context->max_len );
  466. return -ERANGE;
  467. }
  468. DBGC ( context, "RSA %p verifying %s digest:\n",
  469. context, digest->name );
  470. DBGC_HDA ( context, 0, value, digest->digestsize );
  471. DBGC_HDA ( context, 0, signature, signature_len );
  472. /* Decipher the signature (using the big integer input buffer
  473. * as temporary storage)
  474. */
  475. temp = context->input0;
  476. expected = temp;
  477. rsa_cipher ( context, signature, expected );
  478. DBGC ( context, "RSA %p deciphered signature:\n", context );
  479. DBGC_HDA ( context, 0, expected, context->max_len );
  480. /* Encode digest (using the big integer output buffer as
  481. * temporary storage)
  482. */
  483. temp = context->output0;
  484. actual = temp;
  485. if ( ( rc = rsa_encode_digest ( context, digest, value, actual ) ) !=0 )
  486. return rc;
  487. /* Verify the signature */
  488. if ( memcmp ( actual, expected, context->max_len ) != 0 ) {
  489. DBGC ( context, "RSA %p signature verification failed\n",
  490. context );
  491. return -EACCES_VERIFY;
  492. }
  493. DBGC ( context, "RSA %p signature verified successfully\n", context );
  494. return 0;
  495. }
  496. /**
  497. * Finalise RSA cipher
  498. *
  499. * @v ctx RSA context
  500. */
  501. static void rsa_final ( void *ctx ) {
  502. struct rsa_context *context = ctx;
  503. rsa_free ( context );
  504. }
  505. /**
  506. * Check for matching RSA public/private key pair
  507. *
  508. * @v private_key Private key
  509. * @v private_key_len Private key length
  510. * @v public_key Public key
  511. * @v public_key_len Public key length
  512. * @ret rc Return status code
  513. */
  514. static int rsa_match ( const void *private_key, size_t private_key_len,
  515. const void *public_key, size_t public_key_len ) {
  516. struct asn1_cursor private_modulus;
  517. struct asn1_cursor private_exponent;
  518. struct asn1_cursor private_cursor;
  519. struct asn1_cursor public_modulus;
  520. struct asn1_cursor public_exponent;
  521. struct asn1_cursor public_cursor;
  522. int rc;
  523. /* Initialise cursors */
  524. private_cursor.data = private_key;
  525. private_cursor.len = private_key_len;
  526. public_cursor.data = public_key;
  527. public_cursor.len = public_key_len;
  528. /* Parse moduli and exponents */
  529. if ( ( rc = rsa_parse_mod_exp ( &private_modulus, &private_exponent,
  530. &private_cursor ) ) != 0 )
  531. return rc;
  532. if ( ( rc = rsa_parse_mod_exp ( &public_modulus, &public_exponent,
  533. &public_cursor ) ) != 0 )
  534. return rc;
  535. /* Compare moduli */
  536. if ( asn1_compare ( &private_modulus, &public_modulus ) != 0 )
  537. return -ENOTTY;
  538. return 0;
  539. }
  540. /** RSA public-key algorithm */
  541. struct pubkey_algorithm rsa_algorithm = {
  542. .name = "rsa",
  543. .ctxsize = sizeof ( struct rsa_context ),
  544. .init = rsa_init,
  545. .max_len = rsa_max_len,
  546. .encrypt = rsa_encrypt,
  547. .decrypt = rsa_decrypt,
  548. .sign = rsa_sign,
  549. .verify = rsa_verify,
  550. .final = rsa_final,
  551. .match = rsa_match,
  552. };