rsa.c 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067
  1. /*
  2. * The RSA public-key cryptosystem
  3. *
  4. * Copyright The Mbed TLS Contributors
  5. * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  6. */
  7. /*
  8. * The following sources were referenced in the design of this implementation
  9. * of the RSA algorithm:
  10. *
  11. * [1] A method for obtaining digital signatures and public-key cryptosystems
  12. * R Rivest, A Shamir, and L Adleman
  13. * http://people.csail.mit.edu/rivest/pubs.html#RSA78
  14. *
  15. * [2] Handbook of Applied Cryptography - 1997, Chapter 8
  16. * Menezes, van Oorschot and Vanstone
  17. *
  18. * [3] Malware Guard Extension: Using SGX to Conceal Cache Attacks
  19. * Michael Schwarz, Samuel Weiser, Daniel Gruss, Clémentine Maurice and
  20. * Stefan Mangard
  21. * https://arxiv.org/abs/1702.08719v2
  22. *
  23. */
  24. #include "common.h"
  25. #if defined(MBEDTLS_RSA_C)
  26. #include "mbedtls/rsa.h"
  27. #include "bignum_core.h"
  28. #include "bignum_internal.h"
  29. #include "rsa_alt_helpers.h"
  30. #include "rsa_internal.h"
  31. #include "mbedtls/oid.h"
  32. #include "mbedtls/asn1write.h"
  33. #include "mbedtls/platform_util.h"
  34. #include "mbedtls/error.h"
  35. #include "constant_time_internal.h"
  36. #include "mbedtls/constant_time.h"
  37. #include "md_psa.h"
  38. #include <string.h>
  39. #if defined(MBEDTLS_PKCS1_V15) && !defined(__OpenBSD__) && !defined(__NetBSD__)
  40. #include <stdlib.h>
  41. #endif
  42. #include "mbedtls/platform.h"
  43. /*
  44. * Wrapper around mbedtls_asn1_get_mpi() that rejects zero.
  45. *
  46. * The value zero is:
  47. * - never a valid value for an RSA parameter
  48. * - interpreted as "omitted, please reconstruct" by mbedtls_rsa_complete().
  49. *
  50. * Since values can't be omitted in PKCS#1, passing a zero value to
  51. * rsa_complete() would be incorrect, so reject zero values early.
  52. */
  53. static int asn1_get_nonzero_mpi(unsigned char **p,
  54. const unsigned char *end,
  55. mbedtls_mpi *X)
  56. {
  57. int ret;
  58. ret = mbedtls_asn1_get_mpi(p, end, X);
  59. if (ret != 0) {
  60. return ret;
  61. }
  62. if (mbedtls_mpi_cmp_int(X, 0) == 0) {
  63. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  64. }
  65. return 0;
  66. }
  67. int mbedtls_rsa_parse_key(mbedtls_rsa_context *rsa, const unsigned char *key, size_t keylen)
  68. {
  69. int ret, version;
  70. size_t len;
  71. unsigned char *p, *end;
  72. mbedtls_mpi T;
  73. mbedtls_mpi_init(&T);
  74. p = (unsigned char *) key;
  75. end = p + keylen;
  76. /*
  77. * This function parses the RSAPrivateKey (PKCS#1)
  78. *
  79. * RSAPrivateKey ::= SEQUENCE {
  80. * version Version,
  81. * modulus INTEGER, -- n
  82. * publicExponent INTEGER, -- e
  83. * privateExponent INTEGER, -- d
  84. * prime1 INTEGER, -- p
  85. * prime2 INTEGER, -- q
  86. * exponent1 INTEGER, -- d mod (p-1)
  87. * exponent2 INTEGER, -- d mod (q-1)
  88. * coefficient INTEGER, -- (inverse of q) mod p
  89. * otherPrimeInfos OtherPrimeInfos OPTIONAL
  90. * }
  91. */
  92. if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
  93. MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
  94. return ret;
  95. }
  96. if (end != p + len) {
  97. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  98. }
  99. if ((ret = mbedtls_asn1_get_int(&p, end, &version)) != 0) {
  100. return ret;
  101. }
  102. if (version != 0) {
  103. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  104. }
  105. /* Import N */
  106. if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
  107. (ret = mbedtls_rsa_import(rsa, &T, NULL, NULL,
  108. NULL, NULL)) != 0) {
  109. goto cleanup;
  110. }
  111. /* Import E */
  112. if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
  113. (ret = mbedtls_rsa_import(rsa, NULL, NULL, NULL,
  114. NULL, &T)) != 0) {
  115. goto cleanup;
  116. }
  117. /* Import D */
  118. if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
  119. (ret = mbedtls_rsa_import(rsa, NULL, NULL, NULL,
  120. &T, NULL)) != 0) {
  121. goto cleanup;
  122. }
  123. /* Import P */
  124. if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
  125. (ret = mbedtls_rsa_import(rsa, NULL, &T, NULL,
  126. NULL, NULL)) != 0) {
  127. goto cleanup;
  128. }
  129. /* Import Q */
  130. if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
  131. (ret = mbedtls_rsa_import(rsa, NULL, NULL, &T,
  132. NULL, NULL)) != 0) {
  133. goto cleanup;
  134. }
  135. #if !defined(MBEDTLS_RSA_NO_CRT) && !defined(MBEDTLS_RSA_ALT)
  136. /*
  137. * The RSA CRT parameters DP, DQ and QP are nominally redundant, in
  138. * that they can be easily recomputed from D, P and Q. However by
  139. * parsing them from the PKCS1 structure it is possible to avoid
  140. * recalculating them which both reduces the overhead of loading
  141. * RSA private keys into memory and also avoids side channels which
  142. * can arise when computing those values, since all of D, P, and Q
  143. * are secret. See https://eprint.iacr.org/2020/055 for a
  144. * description of one such attack.
  145. */
  146. /* Import DP */
  147. if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
  148. (ret = mbedtls_mpi_copy(&rsa->DP, &T)) != 0) {
  149. goto cleanup;
  150. }
  151. /* Import DQ */
  152. if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
  153. (ret = mbedtls_mpi_copy(&rsa->DQ, &T)) != 0) {
  154. goto cleanup;
  155. }
  156. /* Import QP */
  157. if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
  158. (ret = mbedtls_mpi_copy(&rsa->QP, &T)) != 0) {
  159. goto cleanup;
  160. }
  161. #else
  162. /* Verify existence of the CRT params */
  163. if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
  164. (ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
  165. (ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0) {
  166. goto cleanup;
  167. }
  168. #endif
  169. /* rsa_complete() doesn't complete anything with the default
  170. * implementation but is still called:
  171. * - for the benefit of alternative implementation that may want to
  172. * pre-compute stuff beyond what's provided (eg Montgomery factors)
  173. * - as is also sanity-checks the key
  174. *
  175. * Furthermore, we also check the public part for consistency with
  176. * mbedtls_pk_parse_pubkey(), as it includes size minima for example.
  177. */
  178. if ((ret = mbedtls_rsa_complete(rsa)) != 0 ||
  179. (ret = mbedtls_rsa_check_pubkey(rsa)) != 0) {
  180. goto cleanup;
  181. }
  182. if (p != end) {
  183. ret = MBEDTLS_ERR_ASN1_LENGTH_MISMATCH;
  184. }
  185. cleanup:
  186. mbedtls_mpi_free(&T);
  187. if (ret != 0) {
  188. mbedtls_rsa_free(rsa);
  189. }
  190. return ret;
  191. }
  192. int mbedtls_rsa_parse_pubkey(mbedtls_rsa_context *rsa, const unsigned char *key, size_t keylen)
  193. {
  194. unsigned char *p = (unsigned char *) key;
  195. unsigned char *end = (unsigned char *) (key + keylen);
  196. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  197. size_t len;
  198. /*
  199. * RSAPublicKey ::= SEQUENCE {
  200. * modulus INTEGER, -- n
  201. * publicExponent INTEGER -- e
  202. * }
  203. */
  204. if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
  205. MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
  206. return ret;
  207. }
  208. if (end != p + len) {
  209. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  210. }
  211. /* Import N */
  212. if ((ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_INTEGER)) != 0) {
  213. return ret;
  214. }
  215. if ((ret = mbedtls_rsa_import_raw(rsa, p, len, NULL, 0, NULL, 0,
  216. NULL, 0, NULL, 0)) != 0) {
  217. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  218. }
  219. p += len;
  220. /* Import E */
  221. if ((ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_INTEGER)) != 0) {
  222. return ret;
  223. }
  224. if ((ret = mbedtls_rsa_import_raw(rsa, NULL, 0, NULL, 0, NULL, 0,
  225. NULL, 0, p, len)) != 0) {
  226. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  227. }
  228. p += len;
  229. if (mbedtls_rsa_complete(rsa) != 0 ||
  230. mbedtls_rsa_check_pubkey(rsa) != 0) {
  231. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  232. }
  233. if (p != end) {
  234. return MBEDTLS_ERR_ASN1_LENGTH_MISMATCH;
  235. }
  236. return 0;
  237. }
  238. int mbedtls_rsa_write_key(const mbedtls_rsa_context *rsa, unsigned char *start,
  239. unsigned char **p)
  240. {
  241. size_t len = 0;
  242. int ret;
  243. mbedtls_mpi T; /* Temporary holding the exported parameters */
  244. /*
  245. * Export the parameters one after another to avoid simultaneous copies.
  246. */
  247. mbedtls_mpi_init(&T);
  248. /* Export QP */
  249. if ((ret = mbedtls_rsa_export_crt(rsa, NULL, NULL, &T)) != 0 ||
  250. (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
  251. goto end_of_export;
  252. }
  253. len += ret;
  254. /* Export DQ */
  255. if ((ret = mbedtls_rsa_export_crt(rsa, NULL, &T, NULL)) != 0 ||
  256. (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
  257. goto end_of_export;
  258. }
  259. len += ret;
  260. /* Export DP */
  261. if ((ret = mbedtls_rsa_export_crt(rsa, &T, NULL, NULL)) != 0 ||
  262. (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
  263. goto end_of_export;
  264. }
  265. len += ret;
  266. /* Export Q */
  267. if ((ret = mbedtls_rsa_export(rsa, NULL, NULL, &T, NULL, NULL)) != 0 ||
  268. (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
  269. goto end_of_export;
  270. }
  271. len += ret;
  272. /* Export P */
  273. if ((ret = mbedtls_rsa_export(rsa, NULL, &T, NULL, NULL, NULL)) != 0 ||
  274. (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
  275. goto end_of_export;
  276. }
  277. len += ret;
  278. /* Export D */
  279. if ((ret = mbedtls_rsa_export(rsa, NULL, NULL, NULL, &T, NULL)) != 0 ||
  280. (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
  281. goto end_of_export;
  282. }
  283. len += ret;
  284. /* Export E */
  285. if ((ret = mbedtls_rsa_export(rsa, NULL, NULL, NULL, NULL, &T)) != 0 ||
  286. (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
  287. goto end_of_export;
  288. }
  289. len += ret;
  290. /* Export N */
  291. if ((ret = mbedtls_rsa_export(rsa, &T, NULL, NULL, NULL, NULL)) != 0 ||
  292. (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
  293. goto end_of_export;
  294. }
  295. len += ret;
  296. end_of_export:
  297. mbedtls_mpi_free(&T);
  298. if (ret < 0) {
  299. return ret;
  300. }
  301. MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_int(p, start, 0));
  302. MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(p, start, len));
  303. MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(p, start,
  304. MBEDTLS_ASN1_CONSTRUCTED |
  305. MBEDTLS_ASN1_SEQUENCE));
  306. return (int) len;
  307. }
  308. /*
  309. * RSAPublicKey ::= SEQUENCE {
  310. * modulus INTEGER, -- n
  311. * publicExponent INTEGER -- e
  312. * }
  313. */
  314. int mbedtls_rsa_write_pubkey(const mbedtls_rsa_context *rsa, unsigned char *start,
  315. unsigned char **p)
  316. {
  317. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  318. size_t len = 0;
  319. mbedtls_mpi T;
  320. mbedtls_mpi_init(&T);
  321. /* Export E */
  322. if ((ret = mbedtls_rsa_export(rsa, NULL, NULL, NULL, NULL, &T)) != 0 ||
  323. (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
  324. goto end_of_export;
  325. }
  326. len += ret;
  327. /* Export N */
  328. if ((ret = mbedtls_rsa_export(rsa, &T, NULL, NULL, NULL, NULL)) != 0 ||
  329. (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
  330. goto end_of_export;
  331. }
  332. len += ret;
  333. end_of_export:
  334. mbedtls_mpi_free(&T);
  335. if (ret < 0) {
  336. return ret;
  337. }
  338. MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(p, start, len));
  339. MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(p, start, MBEDTLS_ASN1_CONSTRUCTED |
  340. MBEDTLS_ASN1_SEQUENCE));
  341. return (int) len;
  342. }
  343. #if defined(MBEDTLS_PKCS1_V15) && defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_RSA_ALT)
  344. /** This function performs the unpadding part of a PKCS#1 v1.5 decryption
  345. * operation (EME-PKCS1-v1_5 decoding).
  346. *
  347. * \note The return value from this function is a sensitive value
  348. * (this is unusual). #MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE shouldn't happen
  349. * in a well-written application, but 0 vs #MBEDTLS_ERR_RSA_INVALID_PADDING
  350. * is often a situation that an attacker can provoke and leaking which
  351. * one is the result is precisely the information the attacker wants.
  352. *
  353. * \param input The input buffer which is the payload inside PKCS#1v1.5
  354. * encryption padding, called the "encoded message EM"
  355. * by the terminology.
  356. * \param ilen The length of the payload in the \p input buffer.
  357. * \param output The buffer for the payload, called "message M" by the
  358. * PKCS#1 terminology. This must be a writable buffer of
  359. * length \p output_max_len bytes.
  360. * \param olen The address at which to store the length of
  361. * the payload. This must not be \c NULL.
  362. * \param output_max_len The length in bytes of the output buffer \p output.
  363. *
  364. * \return \c 0 on success.
  365. * \return #MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE
  366. * The output buffer is too small for the unpadded payload.
  367. * \return #MBEDTLS_ERR_RSA_INVALID_PADDING
  368. * The input doesn't contain properly formatted padding.
  369. */
  370. static int mbedtls_ct_rsaes_pkcs1_v15_unpadding(unsigned char *input,
  371. size_t ilen,
  372. unsigned char *output,
  373. size_t output_max_len,
  374. size_t *olen)
  375. {
  376. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  377. size_t i, plaintext_max_size;
  378. /* The following variables take sensitive values: their value must
  379. * not leak into the observable behavior of the function other than
  380. * the designated outputs (output, olen, return value). Otherwise
  381. * this would open the execution of the function to
  382. * side-channel-based variants of the Bleichenbacher padding oracle
  383. * attack. Potential side channels include overall timing, memory
  384. * access patterns (especially visible to an adversary who has access
  385. * to a shared memory cache), and branches (especially visible to
  386. * an adversary who has access to a shared code cache or to a shared
  387. * branch predictor). */
  388. size_t pad_count = 0;
  389. mbedtls_ct_condition_t bad;
  390. mbedtls_ct_condition_t pad_done;
  391. size_t plaintext_size = 0;
  392. mbedtls_ct_condition_t output_too_large;
  393. plaintext_max_size = (output_max_len > ilen - 11) ? ilen - 11
  394. : output_max_len;
  395. /* Check and get padding length in constant time and constant
  396. * memory trace. The first byte must be 0. */
  397. bad = mbedtls_ct_bool(input[0]);
  398. /* Decode EME-PKCS1-v1_5 padding: 0x00 || 0x02 || PS || 0x00
  399. * where PS must be at least 8 nonzero bytes. */
  400. bad = mbedtls_ct_bool_or(bad, mbedtls_ct_uint_ne(input[1], MBEDTLS_RSA_CRYPT));
  401. /* Read the whole buffer. Set pad_done to nonzero if we find
  402. * the 0x00 byte and remember the padding length in pad_count. */
  403. pad_done = MBEDTLS_CT_FALSE;
  404. for (i = 2; i < ilen; i++) {
  405. mbedtls_ct_condition_t found = mbedtls_ct_uint_eq(input[i], 0);
  406. pad_done = mbedtls_ct_bool_or(pad_done, found);
  407. pad_count += mbedtls_ct_uint_if_else_0(mbedtls_ct_bool_not(pad_done), 1);
  408. }
  409. /* If pad_done is still zero, there's no data, only unfinished padding. */
  410. bad = mbedtls_ct_bool_or(bad, mbedtls_ct_bool_not(pad_done));
  411. /* There must be at least 8 bytes of padding. */
  412. bad = mbedtls_ct_bool_or(bad, mbedtls_ct_uint_gt(8, pad_count));
  413. /* If the padding is valid, set plaintext_size to the number of
  414. * remaining bytes after stripping the padding. If the padding
  415. * is invalid, avoid leaking this fact through the size of the
  416. * output: use the maximum message size that fits in the output
  417. * buffer. Do it without branches to avoid leaking the padding
  418. * validity through timing. RSA keys are small enough that all the
  419. * size_t values involved fit in unsigned int. */
  420. plaintext_size = mbedtls_ct_uint_if(
  421. bad, (unsigned) plaintext_max_size,
  422. (unsigned) (ilen - pad_count - 3));
  423. /* Set output_too_large to 0 if the plaintext fits in the output
  424. * buffer and to 1 otherwise. */
  425. output_too_large = mbedtls_ct_uint_gt(plaintext_size,
  426. plaintext_max_size);
  427. /* Set ret without branches to avoid timing attacks. Return:
  428. * - INVALID_PADDING if the padding is bad (bad != 0).
  429. * - OUTPUT_TOO_LARGE if the padding is good but the decrypted
  430. * plaintext does not fit in the output buffer.
  431. * - 0 if the padding is correct. */
  432. ret = mbedtls_ct_error_if(
  433. bad,
  434. MBEDTLS_ERR_RSA_INVALID_PADDING,
  435. mbedtls_ct_error_if_else_0(output_too_large, MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE)
  436. );
  437. /* If the padding is bad or the plaintext is too large, zero the
  438. * data that we're about to copy to the output buffer.
  439. * We need to copy the same amount of data
  440. * from the same buffer whether the padding is good or not to
  441. * avoid leaking the padding validity through overall timing or
  442. * through memory or cache access patterns. */
  443. mbedtls_ct_zeroize_if(mbedtls_ct_bool_or(bad, output_too_large), input + 11, ilen - 11);
  444. /* If the plaintext is too large, truncate it to the buffer size.
  445. * Copy anyway to avoid revealing the length through timing, because
  446. * revealing the length is as bad as revealing the padding validity
  447. * for a Bleichenbacher attack. */
  448. plaintext_size = mbedtls_ct_uint_if(output_too_large,
  449. (unsigned) plaintext_max_size,
  450. (unsigned) plaintext_size);
  451. /* Move the plaintext to the leftmost position where it can start in
  452. * the working buffer, i.e. make it start plaintext_max_size from
  453. * the end of the buffer. Do this with a memory access trace that
  454. * does not depend on the plaintext size. After this move, the
  455. * starting location of the plaintext is no longer sensitive
  456. * information. */
  457. mbedtls_ct_memmove_left(input + ilen - plaintext_max_size,
  458. plaintext_max_size,
  459. plaintext_max_size - plaintext_size);
  460. /* Finally copy the decrypted plaintext plus trailing zeros into the output
  461. * buffer. If output_max_len is 0, then output may be an invalid pointer
  462. * and the result of memcpy() would be undefined; prevent undefined
  463. * behavior making sure to depend only on output_max_len (the size of the
  464. * user-provided output buffer), which is independent from plaintext
  465. * length, validity of padding, success of the decryption, and other
  466. * secrets. */
  467. if (output_max_len != 0) {
  468. memcpy(output, input + ilen - plaintext_max_size, plaintext_max_size);
  469. }
  470. /* Report the amount of data we copied to the output buffer. In case
  471. * of errors (bad padding or output too large), the value of *olen
  472. * when this function returns is not specified. Making it equivalent
  473. * to the good case limits the risks of leaking the padding validity. */
  474. *olen = plaintext_size;
  475. return ret;
  476. }
  477. #endif /* MBEDTLS_PKCS1_V15 && MBEDTLS_RSA_C && ! MBEDTLS_RSA_ALT */
  478. #if !defined(MBEDTLS_RSA_ALT)
  479. int mbedtls_rsa_import(mbedtls_rsa_context *ctx,
  480. const mbedtls_mpi *N,
  481. const mbedtls_mpi *P, const mbedtls_mpi *Q,
  482. const mbedtls_mpi *D, const mbedtls_mpi *E)
  483. {
  484. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  485. if ((N != NULL && (ret = mbedtls_mpi_copy(&ctx->N, N)) != 0) ||
  486. (P != NULL && (ret = mbedtls_mpi_copy(&ctx->P, P)) != 0) ||
  487. (Q != NULL && (ret = mbedtls_mpi_copy(&ctx->Q, Q)) != 0) ||
  488. (D != NULL && (ret = mbedtls_mpi_copy(&ctx->D, D)) != 0) ||
  489. (E != NULL && (ret = mbedtls_mpi_copy(&ctx->E, E)) != 0)) {
  490. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
  491. }
  492. if (N != NULL) {
  493. ctx->len = mbedtls_mpi_size(&ctx->N);
  494. }
  495. return 0;
  496. }
  497. int mbedtls_rsa_import_raw(mbedtls_rsa_context *ctx,
  498. unsigned char const *N, size_t N_len,
  499. unsigned char const *P, size_t P_len,
  500. unsigned char const *Q, size_t Q_len,
  501. unsigned char const *D, size_t D_len,
  502. unsigned char const *E, size_t E_len)
  503. {
  504. int ret = 0;
  505. if (N != NULL) {
  506. MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->N, N, N_len));
  507. ctx->len = mbedtls_mpi_size(&ctx->N);
  508. }
  509. if (P != NULL) {
  510. MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->P, P, P_len));
  511. }
  512. if (Q != NULL) {
  513. MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->Q, Q, Q_len));
  514. }
  515. if (D != NULL) {
  516. MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->D, D, D_len));
  517. }
  518. if (E != NULL) {
  519. MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->E, E, E_len));
  520. }
  521. cleanup:
  522. if (ret != 0) {
  523. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
  524. }
  525. return 0;
  526. }
  527. /*
  528. * Checks whether the context fields are set in such a way
  529. * that the RSA primitives will be able to execute without error.
  530. * It does *not* make guarantees for consistency of the parameters.
  531. */
  532. static int rsa_check_context(mbedtls_rsa_context const *ctx, int is_priv,
  533. int blinding_needed)
  534. {
  535. #if !defined(MBEDTLS_RSA_NO_CRT)
  536. /* blinding_needed is only used for NO_CRT to decide whether
  537. * P,Q need to be present or not. */
  538. ((void) blinding_needed);
  539. #endif
  540. if (ctx->len != mbedtls_mpi_size(&ctx->N) ||
  541. ctx->len > MBEDTLS_MPI_MAX_SIZE) {
  542. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  543. }
  544. /*
  545. * 1. Modular exponentiation needs positive, odd moduli.
  546. */
  547. /* Modular exponentiation wrt. N is always used for
  548. * RSA public key operations. */
  549. if (mbedtls_mpi_cmp_int(&ctx->N, 0) <= 0 ||
  550. mbedtls_mpi_get_bit(&ctx->N, 0) == 0) {
  551. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  552. }
  553. #if !defined(MBEDTLS_RSA_NO_CRT)
  554. /* Modular exponentiation for P and Q is only
  555. * used for private key operations and if CRT
  556. * is used. */
  557. if (is_priv &&
  558. (mbedtls_mpi_cmp_int(&ctx->P, 0) <= 0 ||
  559. mbedtls_mpi_get_bit(&ctx->P, 0) == 0 ||
  560. mbedtls_mpi_cmp_int(&ctx->Q, 0) <= 0 ||
  561. mbedtls_mpi_get_bit(&ctx->Q, 0) == 0)) {
  562. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  563. }
  564. #endif /* !MBEDTLS_RSA_NO_CRT */
  565. /*
  566. * 2. Exponents must be positive
  567. */
  568. /* Always need E for public key operations */
  569. if (mbedtls_mpi_cmp_int(&ctx->E, 0) <= 0) {
  570. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  571. }
  572. #if defined(MBEDTLS_RSA_NO_CRT)
  573. /* For private key operations, use D or DP & DQ
  574. * as (unblinded) exponents. */
  575. if (is_priv && mbedtls_mpi_cmp_int(&ctx->D, 0) <= 0) {
  576. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  577. }
  578. #else
  579. if (is_priv &&
  580. (mbedtls_mpi_cmp_int(&ctx->DP, 0) <= 0 ||
  581. mbedtls_mpi_cmp_int(&ctx->DQ, 0) <= 0)) {
  582. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  583. }
  584. #endif /* MBEDTLS_RSA_NO_CRT */
  585. /* Blinding shouldn't make exponents negative either,
  586. * so check that P, Q >= 1 if that hasn't yet been
  587. * done as part of 1. */
  588. #if defined(MBEDTLS_RSA_NO_CRT)
  589. if (is_priv && blinding_needed &&
  590. (mbedtls_mpi_cmp_int(&ctx->P, 0) <= 0 ||
  591. mbedtls_mpi_cmp_int(&ctx->Q, 0) <= 0)) {
  592. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  593. }
  594. #endif
  595. /* It wouldn't lead to an error if it wasn't satisfied,
  596. * but check for QP >= 1 nonetheless. */
  597. #if !defined(MBEDTLS_RSA_NO_CRT)
  598. if (is_priv &&
  599. mbedtls_mpi_cmp_int(&ctx->QP, 0) <= 0) {
  600. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  601. }
  602. #endif
  603. return 0;
  604. }
  605. int mbedtls_rsa_complete(mbedtls_rsa_context *ctx)
  606. {
  607. int ret = 0;
  608. int have_N, have_P, have_Q, have_D, have_E;
  609. #if !defined(MBEDTLS_RSA_NO_CRT)
  610. int have_DP, have_DQ, have_QP;
  611. #endif
  612. int n_missing, pq_missing, d_missing, is_pub, is_priv;
  613. have_N = (mbedtls_mpi_cmp_int(&ctx->N, 0) != 0);
  614. have_P = (mbedtls_mpi_cmp_int(&ctx->P, 0) != 0);
  615. have_Q = (mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0);
  616. have_D = (mbedtls_mpi_cmp_int(&ctx->D, 0) != 0);
  617. have_E = (mbedtls_mpi_cmp_int(&ctx->E, 0) != 0);
  618. #if !defined(MBEDTLS_RSA_NO_CRT)
  619. have_DP = (mbedtls_mpi_cmp_int(&ctx->DP, 0) != 0);
  620. have_DQ = (mbedtls_mpi_cmp_int(&ctx->DQ, 0) != 0);
  621. have_QP = (mbedtls_mpi_cmp_int(&ctx->QP, 0) != 0);
  622. #endif
  623. /*
  624. * Check whether provided parameters are enough
  625. * to deduce all others. The following incomplete
  626. * parameter sets for private keys are supported:
  627. *
  628. * (1) P, Q missing.
  629. * (2) D and potentially N missing.
  630. *
  631. */
  632. n_missing = have_P && have_Q && have_D && have_E;
  633. pq_missing = have_N && !have_P && !have_Q && have_D && have_E;
  634. d_missing = have_P && have_Q && !have_D && have_E;
  635. is_pub = have_N && !have_P && !have_Q && !have_D && have_E;
  636. /* These three alternatives are mutually exclusive */
  637. is_priv = n_missing || pq_missing || d_missing;
  638. if (!is_priv && !is_pub) {
  639. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  640. }
  641. /*
  642. * Step 1: Deduce N if P, Q are provided.
  643. */
  644. if (!have_N && have_P && have_Q) {
  645. if ((ret = mbedtls_mpi_mul_mpi(&ctx->N, &ctx->P,
  646. &ctx->Q)) != 0) {
  647. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
  648. }
  649. ctx->len = mbedtls_mpi_size(&ctx->N);
  650. }
  651. /*
  652. * Step 2: Deduce and verify all remaining core parameters.
  653. */
  654. if (pq_missing) {
  655. ret = mbedtls_rsa_deduce_primes(&ctx->N, &ctx->E, &ctx->D,
  656. &ctx->P, &ctx->Q);
  657. if (ret != 0) {
  658. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
  659. }
  660. } else if (d_missing) {
  661. if ((ret = mbedtls_rsa_deduce_private_exponent(&ctx->P,
  662. &ctx->Q,
  663. &ctx->E,
  664. &ctx->D)) != 0) {
  665. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
  666. }
  667. }
  668. /*
  669. * Step 3: Deduce all additional parameters specific
  670. * to our current RSA implementation.
  671. */
  672. #if !defined(MBEDTLS_RSA_NO_CRT)
  673. if (is_priv && !(have_DP && have_DQ && have_QP)) {
  674. ret = mbedtls_rsa_deduce_crt(&ctx->P, &ctx->Q, &ctx->D,
  675. &ctx->DP, &ctx->DQ, &ctx->QP);
  676. if (ret != 0) {
  677. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
  678. }
  679. }
  680. #endif /* MBEDTLS_RSA_NO_CRT */
  681. /*
  682. * Step 3: Basic sanity checks
  683. */
  684. return rsa_check_context(ctx, is_priv, 1);
  685. }
  686. int mbedtls_rsa_export_raw(const mbedtls_rsa_context *ctx,
  687. unsigned char *N, size_t N_len,
  688. unsigned char *P, size_t P_len,
  689. unsigned char *Q, size_t Q_len,
  690. unsigned char *D, size_t D_len,
  691. unsigned char *E, size_t E_len)
  692. {
  693. int ret = 0;
  694. int is_priv;
  695. /* Check if key is private or public */
  696. is_priv =
  697. mbedtls_mpi_cmp_int(&ctx->N, 0) != 0 &&
  698. mbedtls_mpi_cmp_int(&ctx->P, 0) != 0 &&
  699. mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0 &&
  700. mbedtls_mpi_cmp_int(&ctx->D, 0) != 0 &&
  701. mbedtls_mpi_cmp_int(&ctx->E, 0) != 0;
  702. if (!is_priv) {
  703. /* If we're trying to export private parameters for a public key,
  704. * something must be wrong. */
  705. if (P != NULL || Q != NULL || D != NULL) {
  706. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  707. }
  708. }
  709. if (N != NULL) {
  710. MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->N, N, N_len));
  711. }
  712. if (P != NULL) {
  713. MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->P, P, P_len));
  714. }
  715. if (Q != NULL) {
  716. MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->Q, Q, Q_len));
  717. }
  718. if (D != NULL) {
  719. MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->D, D, D_len));
  720. }
  721. if (E != NULL) {
  722. MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->E, E, E_len));
  723. }
  724. cleanup:
  725. return ret;
  726. }
  727. int mbedtls_rsa_export(const mbedtls_rsa_context *ctx,
  728. mbedtls_mpi *N, mbedtls_mpi *P, mbedtls_mpi *Q,
  729. mbedtls_mpi *D, mbedtls_mpi *E)
  730. {
  731. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  732. int is_priv;
  733. /* Check if key is private or public */
  734. is_priv =
  735. mbedtls_mpi_cmp_int(&ctx->N, 0) != 0 &&
  736. mbedtls_mpi_cmp_int(&ctx->P, 0) != 0 &&
  737. mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0 &&
  738. mbedtls_mpi_cmp_int(&ctx->D, 0) != 0 &&
  739. mbedtls_mpi_cmp_int(&ctx->E, 0) != 0;
  740. if (!is_priv) {
  741. /* If we're trying to export private parameters for a public key,
  742. * something must be wrong. */
  743. if (P != NULL || Q != NULL || D != NULL) {
  744. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  745. }
  746. }
  747. /* Export all requested core parameters. */
  748. if ((N != NULL && (ret = mbedtls_mpi_copy(N, &ctx->N)) != 0) ||
  749. (P != NULL && (ret = mbedtls_mpi_copy(P, &ctx->P)) != 0) ||
  750. (Q != NULL && (ret = mbedtls_mpi_copy(Q, &ctx->Q)) != 0) ||
  751. (D != NULL && (ret = mbedtls_mpi_copy(D, &ctx->D)) != 0) ||
  752. (E != NULL && (ret = mbedtls_mpi_copy(E, &ctx->E)) != 0)) {
  753. return ret;
  754. }
  755. return 0;
  756. }
  757. /*
  758. * Export CRT parameters
  759. * This must also be implemented if CRT is not used, for being able to
  760. * write DER encoded RSA keys. The helper function mbedtls_rsa_deduce_crt
  761. * can be used in this case.
  762. */
  763. int mbedtls_rsa_export_crt(const mbedtls_rsa_context *ctx,
  764. mbedtls_mpi *DP, mbedtls_mpi *DQ, mbedtls_mpi *QP)
  765. {
  766. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  767. int is_priv;
  768. /* Check if key is private or public */
  769. is_priv =
  770. mbedtls_mpi_cmp_int(&ctx->N, 0) != 0 &&
  771. mbedtls_mpi_cmp_int(&ctx->P, 0) != 0 &&
  772. mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0 &&
  773. mbedtls_mpi_cmp_int(&ctx->D, 0) != 0 &&
  774. mbedtls_mpi_cmp_int(&ctx->E, 0) != 0;
  775. if (!is_priv) {
  776. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  777. }
  778. #if !defined(MBEDTLS_RSA_NO_CRT)
  779. /* Export all requested blinding parameters. */
  780. if ((DP != NULL && (ret = mbedtls_mpi_copy(DP, &ctx->DP)) != 0) ||
  781. (DQ != NULL && (ret = mbedtls_mpi_copy(DQ, &ctx->DQ)) != 0) ||
  782. (QP != NULL && (ret = mbedtls_mpi_copy(QP, &ctx->QP)) != 0)) {
  783. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
  784. }
  785. #else
  786. if ((ret = mbedtls_rsa_deduce_crt(&ctx->P, &ctx->Q, &ctx->D,
  787. DP, DQ, QP)) != 0) {
  788. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
  789. }
  790. #endif
  791. return 0;
  792. }
  793. /*
  794. * Initialize an RSA context
  795. */
  796. void mbedtls_rsa_init(mbedtls_rsa_context *ctx)
  797. {
  798. memset(ctx, 0, sizeof(mbedtls_rsa_context));
  799. ctx->padding = MBEDTLS_RSA_PKCS_V15;
  800. ctx->hash_id = MBEDTLS_MD_NONE;
  801. #if defined(MBEDTLS_THREADING_C)
  802. /* Set ctx->ver to nonzero to indicate that the mutex has been
  803. * initialized and will need to be freed. */
  804. ctx->ver = 1;
  805. mbedtls_mutex_init(&ctx->mutex);
  806. #endif
  807. }
  808. /*
  809. * Set padding for an existing RSA context
  810. */
  811. int mbedtls_rsa_set_padding(mbedtls_rsa_context *ctx, int padding,
  812. mbedtls_md_type_t hash_id)
  813. {
  814. switch (padding) {
  815. #if defined(MBEDTLS_PKCS1_V15)
  816. case MBEDTLS_RSA_PKCS_V15:
  817. break;
  818. #endif
  819. #if defined(MBEDTLS_PKCS1_V21)
  820. case MBEDTLS_RSA_PKCS_V21:
  821. break;
  822. #endif
  823. default:
  824. return MBEDTLS_ERR_RSA_INVALID_PADDING;
  825. }
  826. #if defined(MBEDTLS_PKCS1_V21)
  827. if ((padding == MBEDTLS_RSA_PKCS_V21) &&
  828. (hash_id != MBEDTLS_MD_NONE)) {
  829. /* Just make sure this hash is supported in this build. */
  830. if (mbedtls_md_info_from_type(hash_id) == NULL) {
  831. return MBEDTLS_ERR_RSA_INVALID_PADDING;
  832. }
  833. }
  834. #endif /* MBEDTLS_PKCS1_V21 */
  835. ctx->padding = padding;
  836. ctx->hash_id = hash_id;
  837. return 0;
  838. }
  839. /*
  840. * Get padding mode of initialized RSA context
  841. */
  842. int mbedtls_rsa_get_padding_mode(const mbedtls_rsa_context *ctx)
  843. {
  844. return ctx->padding;
  845. }
  846. /*
  847. * Get hash identifier of mbedtls_md_type_t type
  848. */
  849. int mbedtls_rsa_get_md_alg(const mbedtls_rsa_context *ctx)
  850. {
  851. return ctx->hash_id;
  852. }
  853. /*
  854. * Get length in bits of RSA modulus
  855. */
  856. size_t mbedtls_rsa_get_bitlen(const mbedtls_rsa_context *ctx)
  857. {
  858. return mbedtls_mpi_bitlen(&ctx->N);
  859. }
  860. /*
  861. * Get length in bytes of RSA modulus
  862. */
  863. size_t mbedtls_rsa_get_len(const mbedtls_rsa_context *ctx)
  864. {
  865. return ctx->len;
  866. }
  867. #if defined(MBEDTLS_GENPRIME)
  868. /*
  869. * Generate an RSA keypair
  870. *
  871. * This generation method follows the RSA key pair generation procedure of
  872. * FIPS 186-4 if 2^16 < exponent < 2^256 and nbits = 2048 or nbits = 3072.
  873. */
  874. int mbedtls_rsa_gen_key(mbedtls_rsa_context *ctx,
  875. int (*f_rng)(void *, unsigned char *, size_t),
  876. void *p_rng,
  877. unsigned int nbits, int exponent)
  878. {
  879. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  880. mbedtls_mpi H, G, L;
  881. int prime_quality = 0;
  882. /*
  883. * If the modulus is 1024 bit long or shorter, then the security strength of
  884. * the RSA algorithm is less than or equal to 80 bits and therefore an error
  885. * rate of 2^-80 is sufficient.
  886. */
  887. if (nbits > 1024) {
  888. prime_quality = MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR;
  889. }
  890. mbedtls_mpi_init(&H);
  891. mbedtls_mpi_init(&G);
  892. mbedtls_mpi_init(&L);
  893. if (exponent < 3 || nbits % 2 != 0) {
  894. ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  895. goto cleanup;
  896. }
  897. if (nbits < MBEDTLS_RSA_GEN_KEY_MIN_BITS) {
  898. ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  899. goto cleanup;
  900. }
  901. /*
  902. * find primes P and Q with Q < P so that:
  903. * 1. |P-Q| > 2^( nbits / 2 - 100 )
  904. * 2. GCD( E, (P-1)*(Q-1) ) == 1
  905. * 3. E^-1 mod LCM(P-1, Q-1) > 2^( nbits / 2 )
  906. */
  907. MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&ctx->E, exponent));
  908. do {
  909. MBEDTLS_MPI_CHK(mbedtls_mpi_gen_prime(&ctx->P, nbits >> 1,
  910. prime_quality, f_rng, p_rng));
  911. MBEDTLS_MPI_CHK(mbedtls_mpi_gen_prime(&ctx->Q, nbits >> 1,
  912. prime_quality, f_rng, p_rng));
  913. /* make sure the difference between p and q is not too small (FIPS 186-4 §B.3.3 step 5.4) */
  914. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&H, &ctx->P, &ctx->Q));
  915. if (mbedtls_mpi_bitlen(&H) <= ((nbits >= 200) ? ((nbits >> 1) - 99) : 0)) {
  916. continue;
  917. }
  918. /* not required by any standards, but some users rely on the fact that P > Q */
  919. if (H.s < 0) {
  920. mbedtls_mpi_swap(&ctx->P, &ctx->Q);
  921. }
  922. /* Temporarily replace P,Q by P-1, Q-1 */
  923. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&ctx->P, &ctx->P, 1));
  924. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&ctx->Q, &ctx->Q, 1));
  925. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&H, &ctx->P, &ctx->Q));
  926. /* check GCD( E, (P-1)*(Q-1) ) == 1 (FIPS 186-4 §B.3.1 criterion 2(a)) */
  927. MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(&G, &ctx->E, &H));
  928. if (mbedtls_mpi_cmp_int(&G, 1) != 0) {
  929. continue;
  930. }
  931. /* compute smallest possible D = E^-1 mod LCM(P-1, Q-1) (FIPS 186-4 §B.3.1 criterion 3(b)) */
  932. MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(&G, &ctx->P, &ctx->Q));
  933. MBEDTLS_MPI_CHK(mbedtls_mpi_div_mpi(&L, NULL, &H, &G));
  934. MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod(&ctx->D, &ctx->E, &L));
  935. if (mbedtls_mpi_bitlen(&ctx->D) <= ((nbits + 1) / 2)) { // (FIPS 186-4 §B.3.1 criterion 3(a))
  936. continue;
  937. }
  938. break;
  939. } while (1);
  940. /* Restore P,Q */
  941. MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(&ctx->P, &ctx->P, 1));
  942. MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(&ctx->Q, &ctx->Q, 1));
  943. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->N, &ctx->P, &ctx->Q));
  944. ctx->len = mbedtls_mpi_size(&ctx->N);
  945. #if !defined(MBEDTLS_RSA_NO_CRT)
  946. /*
  947. * DP = D mod (P - 1)
  948. * DQ = D mod (Q - 1)
  949. * QP = Q^-1 mod P
  950. */
  951. MBEDTLS_MPI_CHK(mbedtls_rsa_deduce_crt(&ctx->P, &ctx->Q, &ctx->D,
  952. &ctx->DP, &ctx->DQ, &ctx->QP));
  953. #endif /* MBEDTLS_RSA_NO_CRT */
  954. /* Double-check */
  955. MBEDTLS_MPI_CHK(mbedtls_rsa_check_privkey(ctx));
  956. cleanup:
  957. mbedtls_mpi_free(&H);
  958. mbedtls_mpi_free(&G);
  959. mbedtls_mpi_free(&L);
  960. if (ret != 0) {
  961. mbedtls_rsa_free(ctx);
  962. if ((-ret & ~0x7f) == 0) {
  963. ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_KEY_GEN_FAILED, ret);
  964. }
  965. return ret;
  966. }
  967. return 0;
  968. }
  969. #endif /* MBEDTLS_GENPRIME */
  970. /*
  971. * Check a public RSA key
  972. */
  973. int mbedtls_rsa_check_pubkey(const mbedtls_rsa_context *ctx)
  974. {
  975. if (rsa_check_context(ctx, 0 /* public */, 0 /* no blinding */) != 0) {
  976. return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
  977. }
  978. if (mbedtls_mpi_bitlen(&ctx->N) < 128) {
  979. return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
  980. }
  981. if (mbedtls_mpi_get_bit(&ctx->E, 0) == 0 ||
  982. mbedtls_mpi_bitlen(&ctx->E) < 2 ||
  983. mbedtls_mpi_cmp_mpi(&ctx->E, &ctx->N) >= 0) {
  984. return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
  985. }
  986. return 0;
  987. }
  988. /*
  989. * Check for the consistency of all fields in an RSA private key context
  990. */
  991. int mbedtls_rsa_check_privkey(const mbedtls_rsa_context *ctx)
  992. {
  993. if (mbedtls_rsa_check_pubkey(ctx) != 0 ||
  994. rsa_check_context(ctx, 1 /* private */, 1 /* blinding */) != 0) {
  995. return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
  996. }
  997. if (mbedtls_rsa_validate_params(&ctx->N, &ctx->P, &ctx->Q,
  998. &ctx->D, &ctx->E, NULL, NULL) != 0) {
  999. return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
  1000. }
  1001. #if !defined(MBEDTLS_RSA_NO_CRT)
  1002. else if (mbedtls_rsa_validate_crt(&ctx->P, &ctx->Q, &ctx->D,
  1003. &ctx->DP, &ctx->DQ, &ctx->QP) != 0) {
  1004. return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
  1005. }
  1006. #endif
  1007. return 0;
  1008. }
  1009. /*
  1010. * Check if contexts holding a public and private key match
  1011. */
  1012. int mbedtls_rsa_check_pub_priv(const mbedtls_rsa_context *pub,
  1013. const mbedtls_rsa_context *prv)
  1014. {
  1015. if (mbedtls_rsa_check_pubkey(pub) != 0 ||
  1016. mbedtls_rsa_check_privkey(prv) != 0) {
  1017. return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
  1018. }
  1019. if (mbedtls_mpi_cmp_mpi(&pub->N, &prv->N) != 0 ||
  1020. mbedtls_mpi_cmp_mpi(&pub->E, &prv->E) != 0) {
  1021. return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
  1022. }
  1023. return 0;
  1024. }
  1025. /*
  1026. * Do an RSA public key operation
  1027. */
  1028. int mbedtls_rsa_public(mbedtls_rsa_context *ctx,
  1029. const unsigned char *input,
  1030. unsigned char *output)
  1031. {
  1032. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1033. size_t olen;
  1034. mbedtls_mpi T;
  1035. if (rsa_check_context(ctx, 0 /* public */, 0 /* no blinding */)) {
  1036. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1037. }
  1038. mbedtls_mpi_init(&T);
  1039. #if defined(MBEDTLS_THREADING_C)
  1040. if ((ret = mbedtls_mutex_lock(&ctx->mutex)) != 0) {
  1041. return ret;
  1042. }
  1043. #endif
  1044. MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&T, input, ctx->len));
  1045. if (mbedtls_mpi_cmp_mpi(&T, &ctx->N) >= 0) {
  1046. ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  1047. goto cleanup;
  1048. }
  1049. olen = ctx->len;
  1050. MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod_unsafe(&T, &T, &ctx->E, &ctx->N, &ctx->RN));
  1051. MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&T, output, olen));
  1052. cleanup:
  1053. #if defined(MBEDTLS_THREADING_C)
  1054. if (mbedtls_mutex_unlock(&ctx->mutex) != 0) {
  1055. return MBEDTLS_ERR_THREADING_MUTEX_ERROR;
  1056. }
  1057. #endif
  1058. mbedtls_mpi_free(&T);
  1059. if (ret != 0) {
  1060. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_PUBLIC_FAILED, ret);
  1061. }
  1062. return 0;
  1063. }
  1064. /*
  1065. * Generate or update blinding values, see section 10 of:
  1066. * KOCHER, Paul C. Timing attacks on implementations of Diffie-Hellman, RSA,
  1067. * DSS, and other systems. In : Advances in Cryptology-CRYPTO'96. Springer
  1068. * Berlin Heidelberg, 1996. p. 104-113.
  1069. */
  1070. static int rsa_prepare_blinding(mbedtls_rsa_context *ctx,
  1071. int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
  1072. {
  1073. int ret, count = 0;
  1074. mbedtls_mpi R;
  1075. mbedtls_mpi_init(&R);
  1076. if (ctx->Vf.p != NULL) {
  1077. /* We already have blinding values, just update them by squaring */
  1078. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vi, &ctx->Vi, &ctx->Vi));
  1079. MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vi, &ctx->Vi, &ctx->N));
  1080. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vf, &ctx->Vf, &ctx->Vf));
  1081. MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vf, &ctx->Vf, &ctx->N));
  1082. goto cleanup;
  1083. }
  1084. /* Unblinding value: Vf = random number, invertible mod N */
  1085. do {
  1086. if (count++ > 10) {
  1087. ret = MBEDTLS_ERR_RSA_RNG_FAILED;
  1088. goto cleanup;
  1089. }
  1090. MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&ctx->Vf, ctx->len - 1, f_rng, p_rng));
  1091. /* Compute Vf^-1 as R * (R Vf)^-1 to avoid leaks from inv_mod. */
  1092. MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, ctx->len - 1, f_rng, p_rng));
  1093. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vi, &ctx->Vf, &R));
  1094. MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vi, &ctx->Vi, &ctx->N));
  1095. /* At this point, Vi is invertible mod N if and only if both Vf and R
  1096. * are invertible mod N. If one of them isn't, we don't need to know
  1097. * which one, we just loop and choose new values for both of them.
  1098. * (Each iteration succeeds with overwhelming probability.) */
  1099. ret = mbedtls_mpi_inv_mod(&ctx->Vi, &ctx->Vi, &ctx->N);
  1100. if (ret != 0 && ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) {
  1101. goto cleanup;
  1102. }
  1103. } while (ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE);
  1104. /* Finish the computation of Vf^-1 = R * (R Vf)^-1 */
  1105. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vi, &ctx->Vi, &R));
  1106. MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vi, &ctx->Vi, &ctx->N));
  1107. /* Blinding value: Vi = Vf^(-e) mod N
  1108. * (Vi already contains Vf^-1 at this point) */
  1109. MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&ctx->Vi, &ctx->Vi, &ctx->E, &ctx->N, &ctx->RN));
  1110. cleanup:
  1111. mbedtls_mpi_free(&R);
  1112. return ret;
  1113. }
  1114. /*
  1115. * Unblind
  1116. * T = T * Vf mod N
  1117. */
  1118. static int rsa_unblind(mbedtls_mpi *T, mbedtls_mpi *Vf, const mbedtls_mpi *N)
  1119. {
  1120. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1121. const mbedtls_mpi_uint mm = mbedtls_mpi_core_montmul_init(N->p);
  1122. const size_t nlimbs = N->n;
  1123. const size_t tlimbs = mbedtls_mpi_core_montmul_working_limbs(nlimbs);
  1124. mbedtls_mpi RR, M_T;
  1125. mbedtls_mpi_init(&RR);
  1126. mbedtls_mpi_init(&M_T);
  1127. MBEDTLS_MPI_CHK(mbedtls_mpi_core_get_mont_r2_unsafe(&RR, N));
  1128. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&M_T, tlimbs));
  1129. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(T, nlimbs));
  1130. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(Vf, nlimbs));
  1131. /* T = T * Vf mod N
  1132. * Reminder: montmul(A, B, N) = A * B * R^-1 mod N
  1133. * Usually both operands are multiplied by R mod N beforehand (by calling
  1134. * `to_mont_rep()` on them), yielding a result that's also * R mod N (aka
  1135. * "in the Montgomery domain"). Here we only multiply one operand by R mod
  1136. * N, so the result is directly what we want - no need to call
  1137. * `from_mont_rep()` on it. */
  1138. mbedtls_mpi_core_to_mont_rep(T->p, T->p, N->p, nlimbs, mm, RR.p, M_T.p);
  1139. mbedtls_mpi_core_montmul(T->p, T->p, Vf->p, nlimbs, N->p, nlimbs, mm, M_T.p);
  1140. cleanup:
  1141. mbedtls_mpi_free(&RR);
  1142. mbedtls_mpi_free(&M_T);
  1143. return ret;
  1144. }
  1145. /*
  1146. * Exponent blinding supposed to prevent side-channel attacks using multiple
  1147. * traces of measurements to recover the RSA key. The more collisions are there,
  1148. * the more bits of the key can be recovered. See [3].
  1149. *
  1150. * Collecting n collisions with m bit long blinding value requires 2^(m-m/n)
  1151. * observations on average.
  1152. *
  1153. * For example with 28 byte blinding to achieve 2 collisions the adversary has
  1154. * to make 2^112 observations on average.
  1155. *
  1156. * (With the currently (as of 2017 April) known best algorithms breaking 2048
  1157. * bit RSA requires approximately as much time as trying out 2^112 random keys.
  1158. * Thus in this sense with 28 byte blinding the security is not reduced by
  1159. * side-channel attacks like the one in [3])
  1160. *
  1161. * This countermeasure does not help if the key recovery is possible with a
  1162. * single trace.
  1163. */
  1164. #define RSA_EXPONENT_BLINDING 28
  1165. /*
  1166. * Do an RSA private key operation
  1167. */
  1168. int mbedtls_rsa_private(mbedtls_rsa_context *ctx,
  1169. int (*f_rng)(void *, unsigned char *, size_t),
  1170. void *p_rng,
  1171. const unsigned char *input,
  1172. unsigned char *output)
  1173. {
  1174. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1175. size_t olen;
  1176. /* Temporary holding the result */
  1177. mbedtls_mpi T;
  1178. /* Temporaries holding P-1, Q-1 and the
  1179. * exponent blinding factor, respectively. */
  1180. mbedtls_mpi P1, Q1, R;
  1181. #if !defined(MBEDTLS_RSA_NO_CRT)
  1182. /* Temporaries holding the results mod p resp. mod q. */
  1183. mbedtls_mpi TP, TQ;
  1184. /* Temporaries holding the blinded exponents for
  1185. * the mod p resp. mod q computation (if used). */
  1186. mbedtls_mpi DP_blind, DQ_blind;
  1187. #else
  1188. /* Temporary holding the blinded exponent (if used). */
  1189. mbedtls_mpi D_blind;
  1190. #endif /* MBEDTLS_RSA_NO_CRT */
  1191. /* Temporaries holding the initial input and the double
  1192. * checked result; should be the same in the end. */
  1193. mbedtls_mpi input_blinded, check_result_blinded;
  1194. if (f_rng == NULL) {
  1195. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1196. }
  1197. if (rsa_check_context(ctx, 1 /* private key checks */,
  1198. 1 /* blinding on */) != 0) {
  1199. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1200. }
  1201. #if defined(MBEDTLS_THREADING_C)
  1202. if ((ret = mbedtls_mutex_lock(&ctx->mutex)) != 0) {
  1203. return ret;
  1204. }
  1205. #endif
  1206. /* MPI Initialization */
  1207. mbedtls_mpi_init(&T);
  1208. mbedtls_mpi_init(&P1);
  1209. mbedtls_mpi_init(&Q1);
  1210. mbedtls_mpi_init(&R);
  1211. #if defined(MBEDTLS_RSA_NO_CRT)
  1212. mbedtls_mpi_init(&D_blind);
  1213. #else
  1214. mbedtls_mpi_init(&DP_blind);
  1215. mbedtls_mpi_init(&DQ_blind);
  1216. #endif
  1217. #if !defined(MBEDTLS_RSA_NO_CRT)
  1218. mbedtls_mpi_init(&TP); mbedtls_mpi_init(&TQ);
  1219. #endif
  1220. mbedtls_mpi_init(&input_blinded);
  1221. mbedtls_mpi_init(&check_result_blinded);
  1222. /* End of MPI initialization */
  1223. MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&T, input, ctx->len));
  1224. if (mbedtls_mpi_cmp_mpi(&T, &ctx->N) >= 0) {
  1225. ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  1226. goto cleanup;
  1227. }
  1228. /*
  1229. * Blinding
  1230. * T = T * Vi mod N
  1231. */
  1232. MBEDTLS_MPI_CHK(rsa_prepare_blinding(ctx, f_rng, p_rng));
  1233. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&T, &T, &ctx->Vi));
  1234. MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&T, &T, &ctx->N));
  1235. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&input_blinded, &T));
  1236. /*
  1237. * Exponent blinding
  1238. */
  1239. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&P1, &ctx->P, 1));
  1240. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&Q1, &ctx->Q, 1));
  1241. #if defined(MBEDTLS_RSA_NO_CRT)
  1242. /*
  1243. * D_blind = ( P - 1 ) * ( Q - 1 ) * R + D
  1244. */
  1245. MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING,
  1246. f_rng, p_rng));
  1247. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&D_blind, &P1, &Q1));
  1248. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&D_blind, &D_blind, &R));
  1249. MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&D_blind, &D_blind, &ctx->D));
  1250. #else
  1251. /*
  1252. * DP_blind = ( P - 1 ) * R + DP
  1253. */
  1254. MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING,
  1255. f_rng, p_rng));
  1256. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&DP_blind, &P1, &R));
  1257. MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&DP_blind, &DP_blind,
  1258. &ctx->DP));
  1259. /*
  1260. * DQ_blind = ( Q - 1 ) * R + DQ
  1261. */
  1262. MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING,
  1263. f_rng, p_rng));
  1264. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&DQ_blind, &Q1, &R));
  1265. MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&DQ_blind, &DQ_blind,
  1266. &ctx->DQ));
  1267. #endif /* MBEDTLS_RSA_NO_CRT */
  1268. #if defined(MBEDTLS_RSA_NO_CRT)
  1269. MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&T, &T, &D_blind, &ctx->N, &ctx->RN));
  1270. #else
  1271. /*
  1272. * Faster decryption using the CRT
  1273. *
  1274. * TP = input ^ dP mod P
  1275. * TQ = input ^ dQ mod Q
  1276. */
  1277. MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&TP, &T, &DP_blind, &ctx->P, &ctx->RP));
  1278. MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&TQ, &T, &DQ_blind, &ctx->Q, &ctx->RQ));
  1279. /*
  1280. * T = (TP - TQ) * (Q^-1 mod P) mod P
  1281. */
  1282. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&T, &TP, &TQ));
  1283. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&TP, &T, &ctx->QP));
  1284. MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&T, &TP, &ctx->P));
  1285. /*
  1286. * T = TQ + T * Q
  1287. */
  1288. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&TP, &T, &ctx->Q));
  1289. MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&T, &TQ, &TP));
  1290. #endif /* MBEDTLS_RSA_NO_CRT */
  1291. /* Verify the result to prevent glitching attacks. */
  1292. MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&check_result_blinded, &T, &ctx->E,
  1293. &ctx->N, &ctx->RN));
  1294. if (mbedtls_mpi_cmp_mpi(&check_result_blinded, &input_blinded) != 0) {
  1295. ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
  1296. goto cleanup;
  1297. }
  1298. /*
  1299. * Unblind
  1300. * T = T * Vf mod N
  1301. */
  1302. MBEDTLS_MPI_CHK(rsa_unblind(&T, &ctx->Vf, &ctx->N));
  1303. olen = ctx->len;
  1304. MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&T, output, olen));
  1305. cleanup:
  1306. #if defined(MBEDTLS_THREADING_C)
  1307. if (mbedtls_mutex_unlock(&ctx->mutex) != 0) {
  1308. return MBEDTLS_ERR_THREADING_MUTEX_ERROR;
  1309. }
  1310. #endif
  1311. mbedtls_mpi_free(&P1);
  1312. mbedtls_mpi_free(&Q1);
  1313. mbedtls_mpi_free(&R);
  1314. #if defined(MBEDTLS_RSA_NO_CRT)
  1315. mbedtls_mpi_free(&D_blind);
  1316. #else
  1317. mbedtls_mpi_free(&DP_blind);
  1318. mbedtls_mpi_free(&DQ_blind);
  1319. #endif
  1320. mbedtls_mpi_free(&T);
  1321. #if !defined(MBEDTLS_RSA_NO_CRT)
  1322. mbedtls_mpi_free(&TP); mbedtls_mpi_free(&TQ);
  1323. #endif
  1324. mbedtls_mpi_free(&check_result_blinded);
  1325. mbedtls_mpi_free(&input_blinded);
  1326. if (ret != 0 && ret >= -0x007f) {
  1327. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_PRIVATE_FAILED, ret);
  1328. }
  1329. return ret;
  1330. }
  1331. #if defined(MBEDTLS_PKCS1_V21)
  1332. /**
  1333. * Generate and apply the MGF1 operation (from PKCS#1 v2.1) to a buffer.
  1334. *
  1335. * \param dst buffer to mask
  1336. * \param dlen length of destination buffer
  1337. * \param src source of the mask generation
  1338. * \param slen length of the source buffer
  1339. * \param md_alg message digest to use
  1340. */
  1341. static int mgf_mask(unsigned char *dst, size_t dlen, unsigned char *src,
  1342. size_t slen, mbedtls_md_type_t md_alg)
  1343. {
  1344. unsigned char counter[4];
  1345. unsigned char *p;
  1346. unsigned int hlen;
  1347. size_t i, use_len;
  1348. unsigned char mask[MBEDTLS_MD_MAX_SIZE];
  1349. int ret = 0;
  1350. const mbedtls_md_info_t *md_info;
  1351. mbedtls_md_context_t md_ctx;
  1352. mbedtls_md_init(&md_ctx);
  1353. md_info = mbedtls_md_info_from_type(md_alg);
  1354. if (md_info == NULL) {
  1355. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1356. }
  1357. mbedtls_md_init(&md_ctx);
  1358. if ((ret = mbedtls_md_setup(&md_ctx, md_info, 0)) != 0) {
  1359. goto exit;
  1360. }
  1361. hlen = mbedtls_md_get_size(md_info);
  1362. memset(mask, 0, sizeof(mask));
  1363. memset(counter, 0, 4);
  1364. /* Generate and apply dbMask */
  1365. p = dst;
  1366. while (dlen > 0) {
  1367. use_len = hlen;
  1368. if (dlen < hlen) {
  1369. use_len = dlen;
  1370. }
  1371. if ((ret = mbedtls_md_starts(&md_ctx)) != 0) {
  1372. goto exit;
  1373. }
  1374. if ((ret = mbedtls_md_update(&md_ctx, src, slen)) != 0) {
  1375. goto exit;
  1376. }
  1377. if ((ret = mbedtls_md_update(&md_ctx, counter, 4)) != 0) {
  1378. goto exit;
  1379. }
  1380. if ((ret = mbedtls_md_finish(&md_ctx, mask)) != 0) {
  1381. goto exit;
  1382. }
  1383. for (i = 0; i < use_len; ++i) {
  1384. *p++ ^= mask[i];
  1385. }
  1386. counter[3]++;
  1387. dlen -= use_len;
  1388. }
  1389. exit:
  1390. mbedtls_platform_zeroize(mask, sizeof(mask));
  1391. mbedtls_md_free(&md_ctx);
  1392. return ret;
  1393. }
  1394. /**
  1395. * Generate Hash(M') as in RFC 8017 page 43 points 5 and 6.
  1396. *
  1397. * \param hash the input hash
  1398. * \param hlen length of the input hash
  1399. * \param salt the input salt
  1400. * \param slen length of the input salt
  1401. * \param out the output buffer - must be large enough for \p md_alg
  1402. * \param md_alg message digest to use
  1403. */
  1404. static int hash_mprime(const unsigned char *hash, size_t hlen,
  1405. const unsigned char *salt, size_t slen,
  1406. unsigned char *out, mbedtls_md_type_t md_alg)
  1407. {
  1408. const unsigned char zeros[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
  1409. mbedtls_md_context_t md_ctx;
  1410. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1411. const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(md_alg);
  1412. if (md_info == NULL) {
  1413. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1414. }
  1415. mbedtls_md_init(&md_ctx);
  1416. if ((ret = mbedtls_md_setup(&md_ctx, md_info, 0)) != 0) {
  1417. goto exit;
  1418. }
  1419. if ((ret = mbedtls_md_starts(&md_ctx)) != 0) {
  1420. goto exit;
  1421. }
  1422. if ((ret = mbedtls_md_update(&md_ctx, zeros, sizeof(zeros))) != 0) {
  1423. goto exit;
  1424. }
  1425. if ((ret = mbedtls_md_update(&md_ctx, hash, hlen)) != 0) {
  1426. goto exit;
  1427. }
  1428. if ((ret = mbedtls_md_update(&md_ctx, salt, slen)) != 0) {
  1429. goto exit;
  1430. }
  1431. if ((ret = mbedtls_md_finish(&md_ctx, out)) != 0) {
  1432. goto exit;
  1433. }
  1434. exit:
  1435. mbedtls_md_free(&md_ctx);
  1436. return ret;
  1437. }
  1438. /**
  1439. * Compute a hash.
  1440. *
  1441. * \param md_alg algorithm to use
  1442. * \param input input message to hash
  1443. * \param ilen input length
  1444. * \param output the output buffer - must be large enough for \p md_alg
  1445. */
  1446. static int compute_hash(mbedtls_md_type_t md_alg,
  1447. const unsigned char *input, size_t ilen,
  1448. unsigned char *output)
  1449. {
  1450. const mbedtls_md_info_t *md_info;
  1451. md_info = mbedtls_md_info_from_type(md_alg);
  1452. if (md_info == NULL) {
  1453. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1454. }
  1455. return mbedtls_md(md_info, input, ilen, output);
  1456. }
  1457. #endif /* MBEDTLS_PKCS1_V21 */
  1458. #if defined(MBEDTLS_PKCS1_V21)
  1459. /*
  1460. * Implementation of the PKCS#1 v2.1 RSAES-OAEP-ENCRYPT function
  1461. */
  1462. int mbedtls_rsa_rsaes_oaep_encrypt(mbedtls_rsa_context *ctx,
  1463. int (*f_rng)(void *, unsigned char *, size_t),
  1464. void *p_rng,
  1465. const unsigned char *label, size_t label_len,
  1466. size_t ilen,
  1467. const unsigned char *input,
  1468. unsigned char *output)
  1469. {
  1470. size_t olen;
  1471. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1472. unsigned char *p = output;
  1473. unsigned int hlen;
  1474. if (f_rng == NULL) {
  1475. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1476. }
  1477. hlen = mbedtls_md_get_size_from_type((mbedtls_md_type_t) ctx->hash_id);
  1478. if (hlen == 0) {
  1479. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1480. }
  1481. olen = ctx->len;
  1482. /* first comparison checks for overflow */
  1483. if (ilen + 2 * hlen + 2 < ilen || olen < ilen + 2 * hlen + 2) {
  1484. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1485. }
  1486. memset(output, 0, olen);
  1487. *p++ = 0;
  1488. /* Generate a random octet string seed */
  1489. if ((ret = f_rng(p_rng, p, hlen)) != 0) {
  1490. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_RNG_FAILED, ret);
  1491. }
  1492. p += hlen;
  1493. /* Construct DB */
  1494. ret = compute_hash((mbedtls_md_type_t) ctx->hash_id, label, label_len, p);
  1495. if (ret != 0) {
  1496. return ret;
  1497. }
  1498. p += hlen;
  1499. p += olen - 2 * hlen - 2 - ilen;
  1500. *p++ = 1;
  1501. if (ilen != 0) {
  1502. memcpy(p, input, ilen);
  1503. }
  1504. /* maskedDB: Apply dbMask to DB */
  1505. if ((ret = mgf_mask(output + hlen + 1, olen - hlen - 1, output + 1, hlen,
  1506. (mbedtls_md_type_t) ctx->hash_id)) != 0) {
  1507. return ret;
  1508. }
  1509. /* maskedSeed: Apply seedMask to seed */
  1510. if ((ret = mgf_mask(output + 1, hlen, output + hlen + 1, olen - hlen - 1,
  1511. (mbedtls_md_type_t) ctx->hash_id)) != 0) {
  1512. return ret;
  1513. }
  1514. return mbedtls_rsa_public(ctx, output, output);
  1515. }
  1516. #endif /* MBEDTLS_PKCS1_V21 */
  1517. #if defined(MBEDTLS_PKCS1_V15)
  1518. /*
  1519. * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-ENCRYPT function
  1520. */
  1521. int mbedtls_rsa_rsaes_pkcs1_v15_encrypt(mbedtls_rsa_context *ctx,
  1522. int (*f_rng)(void *, unsigned char *, size_t),
  1523. void *p_rng, size_t ilen,
  1524. const unsigned char *input,
  1525. unsigned char *output)
  1526. {
  1527. size_t nb_pad, olen;
  1528. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1529. unsigned char *p = output;
  1530. olen = ctx->len;
  1531. /* first comparison checks for overflow */
  1532. if (ilen + 11 < ilen || olen < ilen + 11) {
  1533. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1534. }
  1535. nb_pad = olen - 3 - ilen;
  1536. *p++ = 0;
  1537. if (f_rng == NULL) {
  1538. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1539. }
  1540. *p++ = MBEDTLS_RSA_CRYPT;
  1541. while (nb_pad-- > 0) {
  1542. int rng_dl = 100;
  1543. do {
  1544. ret = f_rng(p_rng, p, 1);
  1545. } while (*p == 0 && --rng_dl && ret == 0);
  1546. /* Check if RNG failed to generate data */
  1547. if (rng_dl == 0 || ret != 0) {
  1548. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_RNG_FAILED, ret);
  1549. }
  1550. p++;
  1551. }
  1552. *p++ = 0;
  1553. if (ilen != 0) {
  1554. memcpy(p, input, ilen);
  1555. }
  1556. return mbedtls_rsa_public(ctx, output, output);
  1557. }
  1558. #endif /* MBEDTLS_PKCS1_V15 */
  1559. /*
  1560. * Add the message padding, then do an RSA operation
  1561. */
  1562. int mbedtls_rsa_pkcs1_encrypt(mbedtls_rsa_context *ctx,
  1563. int (*f_rng)(void *, unsigned char *, size_t),
  1564. void *p_rng,
  1565. size_t ilen,
  1566. const unsigned char *input,
  1567. unsigned char *output)
  1568. {
  1569. switch (ctx->padding) {
  1570. #if defined(MBEDTLS_PKCS1_V15)
  1571. case MBEDTLS_RSA_PKCS_V15:
  1572. return mbedtls_rsa_rsaes_pkcs1_v15_encrypt(ctx, f_rng, p_rng,
  1573. ilen, input, output);
  1574. #endif
  1575. #if defined(MBEDTLS_PKCS1_V21)
  1576. case MBEDTLS_RSA_PKCS_V21:
  1577. return mbedtls_rsa_rsaes_oaep_encrypt(ctx, f_rng, p_rng, NULL, 0,
  1578. ilen, input, output);
  1579. #endif
  1580. default:
  1581. return MBEDTLS_ERR_RSA_INVALID_PADDING;
  1582. }
  1583. }
  1584. #if defined(MBEDTLS_PKCS1_V21)
  1585. /*
  1586. * Implementation of the PKCS#1 v2.1 RSAES-OAEP-DECRYPT function
  1587. */
  1588. int mbedtls_rsa_rsaes_oaep_decrypt(mbedtls_rsa_context *ctx,
  1589. int (*f_rng)(void *, unsigned char *, size_t),
  1590. void *p_rng,
  1591. const unsigned char *label, size_t label_len,
  1592. size_t *olen,
  1593. const unsigned char *input,
  1594. unsigned char *output,
  1595. size_t output_max_len)
  1596. {
  1597. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1598. size_t ilen, i, pad_len;
  1599. unsigned char *p;
  1600. mbedtls_ct_condition_t bad, in_padding;
  1601. unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
  1602. unsigned char lhash[MBEDTLS_MD_MAX_SIZE];
  1603. unsigned int hlen;
  1604. /*
  1605. * Parameters sanity checks
  1606. */
  1607. if (ctx->padding != MBEDTLS_RSA_PKCS_V21) {
  1608. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1609. }
  1610. ilen = ctx->len;
  1611. if (ilen < 16 || ilen > sizeof(buf)) {
  1612. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1613. }
  1614. hlen = mbedtls_md_get_size_from_type((mbedtls_md_type_t) ctx->hash_id);
  1615. if (hlen == 0) {
  1616. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1617. }
  1618. // checking for integer underflow
  1619. if (2 * hlen + 2 > ilen) {
  1620. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1621. }
  1622. /*
  1623. * RSA operation
  1624. */
  1625. ret = mbedtls_rsa_private(ctx, f_rng, p_rng, input, buf);
  1626. if (ret != 0) {
  1627. goto cleanup;
  1628. }
  1629. /*
  1630. * Unmask data and generate lHash
  1631. */
  1632. /* seed: Apply seedMask to maskedSeed */
  1633. if ((ret = mgf_mask(buf + 1, hlen, buf + hlen + 1, ilen - hlen - 1,
  1634. (mbedtls_md_type_t) ctx->hash_id)) != 0 ||
  1635. /* DB: Apply dbMask to maskedDB */
  1636. (ret = mgf_mask(buf + hlen + 1, ilen - hlen - 1, buf + 1, hlen,
  1637. (mbedtls_md_type_t) ctx->hash_id)) != 0) {
  1638. goto cleanup;
  1639. }
  1640. /* Generate lHash */
  1641. ret = compute_hash((mbedtls_md_type_t) ctx->hash_id,
  1642. label, label_len, lhash);
  1643. if (ret != 0) {
  1644. goto cleanup;
  1645. }
  1646. /*
  1647. * Check contents, in "constant-time"
  1648. */
  1649. p = buf;
  1650. bad = mbedtls_ct_bool(*p++); /* First byte must be 0 */
  1651. p += hlen; /* Skip seed */
  1652. /* Check lHash */
  1653. bad = mbedtls_ct_bool_or(bad, mbedtls_ct_bool(mbedtls_ct_memcmp(lhash, p, hlen)));
  1654. p += hlen;
  1655. /* Get zero-padding len, but always read till end of buffer
  1656. * (minus one, for the 01 byte) */
  1657. pad_len = 0;
  1658. in_padding = MBEDTLS_CT_TRUE;
  1659. for (i = 0; i < ilen - 2 * hlen - 2; i++) {
  1660. in_padding = mbedtls_ct_bool_and(in_padding, mbedtls_ct_uint_eq(p[i], 0));
  1661. pad_len += mbedtls_ct_uint_if_else_0(in_padding, 1);
  1662. }
  1663. p += pad_len;
  1664. bad = mbedtls_ct_bool_or(bad, mbedtls_ct_uint_ne(*p++, 0x01));
  1665. /*
  1666. * The only information "leaked" is whether the padding was correct or not
  1667. * (eg, no data is copied if it was not correct). This meets the
  1668. * recommendations in PKCS#1 v2.2: an opponent cannot distinguish between
  1669. * the different error conditions.
  1670. */
  1671. if (bad != MBEDTLS_CT_FALSE) {
  1672. ret = MBEDTLS_ERR_RSA_INVALID_PADDING;
  1673. goto cleanup;
  1674. }
  1675. if (ilen - ((size_t) (p - buf)) > output_max_len) {
  1676. ret = MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE;
  1677. goto cleanup;
  1678. }
  1679. *olen = ilen - ((size_t) (p - buf));
  1680. if (*olen != 0) {
  1681. memcpy(output, p, *olen);
  1682. }
  1683. ret = 0;
  1684. cleanup:
  1685. mbedtls_platform_zeroize(buf, sizeof(buf));
  1686. mbedtls_platform_zeroize(lhash, sizeof(lhash));
  1687. return ret;
  1688. }
  1689. #endif /* MBEDTLS_PKCS1_V21 */
  1690. #if defined(MBEDTLS_PKCS1_V15)
  1691. /*
  1692. * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-DECRYPT function
  1693. */
  1694. int mbedtls_rsa_rsaes_pkcs1_v15_decrypt(mbedtls_rsa_context *ctx,
  1695. int (*f_rng)(void *, unsigned char *, size_t),
  1696. void *p_rng,
  1697. size_t *olen,
  1698. const unsigned char *input,
  1699. unsigned char *output,
  1700. size_t output_max_len)
  1701. {
  1702. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1703. size_t ilen;
  1704. unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
  1705. ilen = ctx->len;
  1706. if (ctx->padding != MBEDTLS_RSA_PKCS_V15) {
  1707. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1708. }
  1709. if (ilen < 16 || ilen > sizeof(buf)) {
  1710. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1711. }
  1712. ret = mbedtls_rsa_private(ctx, f_rng, p_rng, input, buf);
  1713. if (ret != 0) {
  1714. goto cleanup;
  1715. }
  1716. ret = mbedtls_ct_rsaes_pkcs1_v15_unpadding(buf, ilen,
  1717. output, output_max_len, olen);
  1718. cleanup:
  1719. mbedtls_platform_zeroize(buf, sizeof(buf));
  1720. return ret;
  1721. }
  1722. #endif /* MBEDTLS_PKCS1_V15 */
  1723. /*
  1724. * Do an RSA operation, then remove the message padding
  1725. */
  1726. int mbedtls_rsa_pkcs1_decrypt(mbedtls_rsa_context *ctx,
  1727. int (*f_rng)(void *, unsigned char *, size_t),
  1728. void *p_rng,
  1729. size_t *olen,
  1730. const unsigned char *input,
  1731. unsigned char *output,
  1732. size_t output_max_len)
  1733. {
  1734. switch (ctx->padding) {
  1735. #if defined(MBEDTLS_PKCS1_V15)
  1736. case MBEDTLS_RSA_PKCS_V15:
  1737. return mbedtls_rsa_rsaes_pkcs1_v15_decrypt(ctx, f_rng, p_rng, olen,
  1738. input, output, output_max_len);
  1739. #endif
  1740. #if defined(MBEDTLS_PKCS1_V21)
  1741. case MBEDTLS_RSA_PKCS_V21:
  1742. return mbedtls_rsa_rsaes_oaep_decrypt(ctx, f_rng, p_rng, NULL, 0,
  1743. olen, input, output,
  1744. output_max_len);
  1745. #endif
  1746. default:
  1747. return MBEDTLS_ERR_RSA_INVALID_PADDING;
  1748. }
  1749. }
  1750. #if defined(MBEDTLS_PKCS1_V21)
  1751. static int rsa_rsassa_pss_sign_no_mode_check(mbedtls_rsa_context *ctx,
  1752. int (*f_rng)(void *, unsigned char *, size_t),
  1753. void *p_rng,
  1754. mbedtls_md_type_t md_alg,
  1755. unsigned int hashlen,
  1756. const unsigned char *hash,
  1757. int saltlen,
  1758. unsigned char *sig)
  1759. {
  1760. size_t olen;
  1761. unsigned char *p = sig;
  1762. unsigned char *salt = NULL;
  1763. size_t slen, min_slen, hlen, offset = 0;
  1764. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1765. size_t msb;
  1766. mbedtls_md_type_t hash_id;
  1767. if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
  1768. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1769. }
  1770. if (f_rng == NULL) {
  1771. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1772. }
  1773. olen = ctx->len;
  1774. if (md_alg != MBEDTLS_MD_NONE) {
  1775. /* Gather length of hash to sign */
  1776. size_t exp_hashlen = mbedtls_md_get_size_from_type(md_alg);
  1777. if (exp_hashlen == 0) {
  1778. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1779. }
  1780. if (hashlen != exp_hashlen) {
  1781. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1782. }
  1783. }
  1784. hash_id = (mbedtls_md_type_t) ctx->hash_id;
  1785. if (hash_id == MBEDTLS_MD_NONE) {
  1786. hash_id = md_alg;
  1787. }
  1788. hlen = mbedtls_md_get_size_from_type(hash_id);
  1789. if (hlen == 0) {
  1790. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1791. }
  1792. if (saltlen == MBEDTLS_RSA_SALT_LEN_ANY) {
  1793. /* Calculate the largest possible salt length, up to the hash size.
  1794. * Normally this is the hash length, which is the maximum salt length
  1795. * according to FIPS 185-4 §5.5 (e) and common practice. If there is not
  1796. * enough room, use the maximum salt length that fits. The constraint is
  1797. * that the hash length plus the salt length plus 2 bytes must be at most
  1798. * the key length. This complies with FIPS 186-4 §5.5 (e) and RFC 8017
  1799. * (PKCS#1 v2.2) §9.1.1 step 3. */
  1800. min_slen = hlen - 2;
  1801. if (olen < hlen + min_slen + 2) {
  1802. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1803. } else if (olen >= hlen + hlen + 2) {
  1804. slen = hlen;
  1805. } else {
  1806. slen = olen - hlen - 2;
  1807. }
  1808. } else if ((saltlen < 0) || (saltlen + hlen + 2 > olen)) {
  1809. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1810. } else {
  1811. slen = (size_t) saltlen;
  1812. }
  1813. memset(sig, 0, olen);
  1814. /* Note: EMSA-PSS encoding is over the length of N - 1 bits */
  1815. msb = mbedtls_mpi_bitlen(&ctx->N) - 1;
  1816. p += olen - hlen - slen - 2;
  1817. *p++ = 0x01;
  1818. /* Generate salt of length slen in place in the encoded message */
  1819. salt = p;
  1820. if ((ret = f_rng(p_rng, salt, slen)) != 0) {
  1821. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_RNG_FAILED, ret);
  1822. }
  1823. p += slen;
  1824. /* Generate H = Hash( M' ) */
  1825. ret = hash_mprime(hash, hashlen, salt, slen, p, hash_id);
  1826. if (ret != 0) {
  1827. return ret;
  1828. }
  1829. /* Compensate for boundary condition when applying mask */
  1830. if (msb % 8 == 0) {
  1831. offset = 1;
  1832. }
  1833. /* maskedDB: Apply dbMask to DB */
  1834. ret = mgf_mask(sig + offset, olen - hlen - 1 - offset, p, hlen, hash_id);
  1835. if (ret != 0) {
  1836. return ret;
  1837. }
  1838. msb = mbedtls_mpi_bitlen(&ctx->N) - 1;
  1839. sig[0] &= 0xFF >> (olen * 8 - msb);
  1840. p += hlen;
  1841. *p++ = 0xBC;
  1842. return mbedtls_rsa_private(ctx, f_rng, p_rng, sig, sig);
  1843. }
  1844. static int rsa_rsassa_pss_sign(mbedtls_rsa_context *ctx,
  1845. int (*f_rng)(void *, unsigned char *, size_t),
  1846. void *p_rng,
  1847. mbedtls_md_type_t md_alg,
  1848. unsigned int hashlen,
  1849. const unsigned char *hash,
  1850. int saltlen,
  1851. unsigned char *sig)
  1852. {
  1853. if (ctx->padding != MBEDTLS_RSA_PKCS_V21) {
  1854. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1855. }
  1856. if ((ctx->hash_id == MBEDTLS_MD_NONE) && (md_alg == MBEDTLS_MD_NONE)) {
  1857. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1858. }
  1859. return rsa_rsassa_pss_sign_no_mode_check(ctx, f_rng, p_rng, md_alg, hashlen, hash, saltlen,
  1860. sig);
  1861. }
  1862. int mbedtls_rsa_rsassa_pss_sign_no_mode_check(mbedtls_rsa_context *ctx,
  1863. int (*f_rng)(void *, unsigned char *, size_t),
  1864. void *p_rng,
  1865. mbedtls_md_type_t md_alg,
  1866. unsigned int hashlen,
  1867. const unsigned char *hash,
  1868. unsigned char *sig)
  1869. {
  1870. return rsa_rsassa_pss_sign_no_mode_check(ctx, f_rng, p_rng, md_alg,
  1871. hashlen, hash, MBEDTLS_RSA_SALT_LEN_ANY, sig);
  1872. }
  1873. /*
  1874. * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function with
  1875. * the option to pass in the salt length.
  1876. */
  1877. int mbedtls_rsa_rsassa_pss_sign_ext(mbedtls_rsa_context *ctx,
  1878. int (*f_rng)(void *, unsigned char *, size_t),
  1879. void *p_rng,
  1880. mbedtls_md_type_t md_alg,
  1881. unsigned int hashlen,
  1882. const unsigned char *hash,
  1883. int saltlen,
  1884. unsigned char *sig)
  1885. {
  1886. return rsa_rsassa_pss_sign(ctx, f_rng, p_rng, md_alg,
  1887. hashlen, hash, saltlen, sig);
  1888. }
  1889. /*
  1890. * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function
  1891. */
  1892. int mbedtls_rsa_rsassa_pss_sign(mbedtls_rsa_context *ctx,
  1893. int (*f_rng)(void *, unsigned char *, size_t),
  1894. void *p_rng,
  1895. mbedtls_md_type_t md_alg,
  1896. unsigned int hashlen,
  1897. const unsigned char *hash,
  1898. unsigned char *sig)
  1899. {
  1900. return rsa_rsassa_pss_sign(ctx, f_rng, p_rng, md_alg,
  1901. hashlen, hash, MBEDTLS_RSA_SALT_LEN_ANY, sig);
  1902. }
  1903. #endif /* MBEDTLS_PKCS1_V21 */
  1904. #if defined(MBEDTLS_PKCS1_V15)
  1905. /*
  1906. * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-V1_5-SIGN function
  1907. */
  1908. /* Construct a PKCS v1.5 encoding of a hashed message
  1909. *
  1910. * This is used both for signature generation and verification.
  1911. *
  1912. * Parameters:
  1913. * - md_alg: Identifies the hash algorithm used to generate the given hash;
  1914. * MBEDTLS_MD_NONE if raw data is signed.
  1915. * - hashlen: Length of hash. Must match md_alg if that's not NONE.
  1916. * - hash: Buffer containing the hashed message or the raw data.
  1917. * - dst_len: Length of the encoded message.
  1918. * - dst: Buffer to hold the encoded message.
  1919. *
  1920. * Assumptions:
  1921. * - hash has size hashlen.
  1922. * - dst points to a buffer of size at least dst_len.
  1923. *
  1924. */
  1925. static int rsa_rsassa_pkcs1_v15_encode(mbedtls_md_type_t md_alg,
  1926. unsigned int hashlen,
  1927. const unsigned char *hash,
  1928. size_t dst_len,
  1929. unsigned char *dst)
  1930. {
  1931. size_t oid_size = 0;
  1932. size_t nb_pad = dst_len;
  1933. unsigned char *p = dst;
  1934. const char *oid = NULL;
  1935. /* Are we signing hashed or raw data? */
  1936. if (md_alg != MBEDTLS_MD_NONE) {
  1937. unsigned char md_size = mbedtls_md_get_size_from_type(md_alg);
  1938. if (md_size == 0) {
  1939. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1940. }
  1941. if (mbedtls_oid_get_oid_by_md(md_alg, &oid, &oid_size) != 0) {
  1942. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1943. }
  1944. if (hashlen != md_size) {
  1945. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1946. }
  1947. /* Double-check that 8 + hashlen + oid_size can be used as a
  1948. * 1-byte ASN.1 length encoding and that there's no overflow. */
  1949. if (8 + hashlen + oid_size >= 0x80 ||
  1950. 10 + hashlen < hashlen ||
  1951. 10 + hashlen + oid_size < 10 + hashlen) {
  1952. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1953. }
  1954. /*
  1955. * Static bounds check:
  1956. * - Need 10 bytes for five tag-length pairs.
  1957. * (Insist on 1-byte length encodings to protect against variants of
  1958. * Bleichenbacher's forgery attack against lax PKCS#1v1.5 verification)
  1959. * - Need hashlen bytes for hash
  1960. * - Need oid_size bytes for hash alg OID.
  1961. */
  1962. if (nb_pad < 10 + hashlen + oid_size) {
  1963. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1964. }
  1965. nb_pad -= 10 + hashlen + oid_size;
  1966. } else {
  1967. if (nb_pad < hashlen) {
  1968. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1969. }
  1970. nb_pad -= hashlen;
  1971. }
  1972. /* Need space for signature header and padding delimiter (3 bytes),
  1973. * and 8 bytes for the minimal padding */
  1974. if (nb_pad < 3 + 8) {
  1975. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1976. }
  1977. nb_pad -= 3;
  1978. /* Now nb_pad is the amount of memory to be filled
  1979. * with padding, and at least 8 bytes long. */
  1980. /* Write signature header and padding */
  1981. *p++ = 0;
  1982. *p++ = MBEDTLS_RSA_SIGN;
  1983. memset(p, 0xFF, nb_pad);
  1984. p += nb_pad;
  1985. *p++ = 0;
  1986. /* Are we signing raw data? */
  1987. if (md_alg == MBEDTLS_MD_NONE) {
  1988. memcpy(p, hash, hashlen);
  1989. return 0;
  1990. }
  1991. /* Signing hashed data, add corresponding ASN.1 structure
  1992. *
  1993. * DigestInfo ::= SEQUENCE {
  1994. * digestAlgorithm DigestAlgorithmIdentifier,
  1995. * digest Digest }
  1996. * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
  1997. * Digest ::= OCTET STRING
  1998. *
  1999. * Schematic:
  2000. * TAG-SEQ + LEN [ TAG-SEQ + LEN [ TAG-OID + LEN [ OID ]
  2001. * TAG-NULL + LEN [ NULL ] ]
  2002. * TAG-OCTET + LEN [ HASH ] ]
  2003. */
  2004. *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
  2005. *p++ = (unsigned char) (0x08 + oid_size + hashlen);
  2006. *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
  2007. *p++ = (unsigned char) (0x04 + oid_size);
  2008. *p++ = MBEDTLS_ASN1_OID;
  2009. *p++ = (unsigned char) oid_size;
  2010. memcpy(p, oid, oid_size);
  2011. p += oid_size;
  2012. *p++ = MBEDTLS_ASN1_NULL;
  2013. *p++ = 0x00;
  2014. *p++ = MBEDTLS_ASN1_OCTET_STRING;
  2015. *p++ = (unsigned char) hashlen;
  2016. memcpy(p, hash, hashlen);
  2017. p += hashlen;
  2018. /* Just a sanity-check, should be automatic
  2019. * after the initial bounds check. */
  2020. if (p != dst + dst_len) {
  2021. mbedtls_platform_zeroize(dst, dst_len);
  2022. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2023. }
  2024. return 0;
  2025. }
  2026. /*
  2027. * Do an RSA operation to sign the message digest
  2028. */
  2029. int mbedtls_rsa_rsassa_pkcs1_v15_sign(mbedtls_rsa_context *ctx,
  2030. int (*f_rng)(void *, unsigned char *, size_t),
  2031. void *p_rng,
  2032. mbedtls_md_type_t md_alg,
  2033. unsigned int hashlen,
  2034. const unsigned char *hash,
  2035. unsigned char *sig)
  2036. {
  2037. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2038. unsigned char *sig_try = NULL, *verif = NULL;
  2039. if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
  2040. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2041. }
  2042. if (ctx->padding != MBEDTLS_RSA_PKCS_V15) {
  2043. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2044. }
  2045. /*
  2046. * Prepare PKCS1-v1.5 encoding (padding and hash identifier)
  2047. */
  2048. if ((ret = rsa_rsassa_pkcs1_v15_encode(md_alg, hashlen, hash,
  2049. ctx->len, sig)) != 0) {
  2050. return ret;
  2051. }
  2052. /* Private key operation
  2053. *
  2054. * In order to prevent Lenstra's attack, make the signature in a
  2055. * temporary buffer and check it before returning it.
  2056. */
  2057. sig_try = mbedtls_calloc(1, ctx->len);
  2058. if (sig_try == NULL) {
  2059. return MBEDTLS_ERR_MPI_ALLOC_FAILED;
  2060. }
  2061. verif = mbedtls_calloc(1, ctx->len);
  2062. if (verif == NULL) {
  2063. mbedtls_free(sig_try);
  2064. return MBEDTLS_ERR_MPI_ALLOC_FAILED;
  2065. }
  2066. MBEDTLS_MPI_CHK(mbedtls_rsa_private(ctx, f_rng, p_rng, sig, sig_try));
  2067. MBEDTLS_MPI_CHK(mbedtls_rsa_public(ctx, sig_try, verif));
  2068. if (mbedtls_ct_memcmp(verif, sig, ctx->len) != 0) {
  2069. ret = MBEDTLS_ERR_RSA_PRIVATE_FAILED;
  2070. goto cleanup;
  2071. }
  2072. memcpy(sig, sig_try, ctx->len);
  2073. cleanup:
  2074. mbedtls_zeroize_and_free(sig_try, ctx->len);
  2075. mbedtls_zeroize_and_free(verif, ctx->len);
  2076. if (ret != 0) {
  2077. memset(sig, '!', ctx->len);
  2078. }
  2079. return ret;
  2080. }
  2081. #endif /* MBEDTLS_PKCS1_V15 */
  2082. /*
  2083. * Do an RSA operation to sign the message digest
  2084. */
  2085. int mbedtls_rsa_pkcs1_sign(mbedtls_rsa_context *ctx,
  2086. int (*f_rng)(void *, unsigned char *, size_t),
  2087. void *p_rng,
  2088. mbedtls_md_type_t md_alg,
  2089. unsigned int hashlen,
  2090. const unsigned char *hash,
  2091. unsigned char *sig)
  2092. {
  2093. if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
  2094. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2095. }
  2096. switch (ctx->padding) {
  2097. #if defined(MBEDTLS_PKCS1_V15)
  2098. case MBEDTLS_RSA_PKCS_V15:
  2099. return mbedtls_rsa_rsassa_pkcs1_v15_sign(ctx, f_rng, p_rng,
  2100. md_alg, hashlen, hash, sig);
  2101. #endif
  2102. #if defined(MBEDTLS_PKCS1_V21)
  2103. case MBEDTLS_RSA_PKCS_V21:
  2104. return mbedtls_rsa_rsassa_pss_sign(ctx, f_rng, p_rng, md_alg,
  2105. hashlen, hash, sig);
  2106. #endif
  2107. default:
  2108. return MBEDTLS_ERR_RSA_INVALID_PADDING;
  2109. }
  2110. }
  2111. #if defined(MBEDTLS_PKCS1_V21)
  2112. /*
  2113. * Implementation of the PKCS#1 v2.1 RSASSA-PSS-VERIFY function
  2114. */
  2115. int mbedtls_rsa_rsassa_pss_verify_ext(mbedtls_rsa_context *ctx,
  2116. mbedtls_md_type_t md_alg,
  2117. unsigned int hashlen,
  2118. const unsigned char *hash,
  2119. mbedtls_md_type_t mgf1_hash_id,
  2120. int expected_salt_len,
  2121. const unsigned char *sig)
  2122. {
  2123. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2124. size_t siglen;
  2125. unsigned char *p;
  2126. unsigned char *hash_start;
  2127. unsigned char result[MBEDTLS_MD_MAX_SIZE];
  2128. unsigned int hlen;
  2129. size_t observed_salt_len, msb;
  2130. unsigned char buf[MBEDTLS_MPI_MAX_SIZE] = { 0 };
  2131. if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
  2132. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2133. }
  2134. siglen = ctx->len;
  2135. if (siglen < 16 || siglen > sizeof(buf)) {
  2136. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2137. }
  2138. ret = mbedtls_rsa_public(ctx, sig, buf);
  2139. if (ret != 0) {
  2140. return ret;
  2141. }
  2142. p = buf;
  2143. if (buf[siglen - 1] != 0xBC) {
  2144. return MBEDTLS_ERR_RSA_INVALID_PADDING;
  2145. }
  2146. if (md_alg != MBEDTLS_MD_NONE) {
  2147. /* Gather length of hash to sign */
  2148. size_t exp_hashlen = mbedtls_md_get_size_from_type(md_alg);
  2149. if (exp_hashlen == 0) {
  2150. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2151. }
  2152. if (hashlen != exp_hashlen) {
  2153. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2154. }
  2155. }
  2156. hlen = mbedtls_md_get_size_from_type(mgf1_hash_id);
  2157. if (hlen == 0) {
  2158. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2159. }
  2160. /*
  2161. * Note: EMSA-PSS verification is over the length of N - 1 bits
  2162. */
  2163. msb = mbedtls_mpi_bitlen(&ctx->N) - 1;
  2164. if (buf[0] >> (8 - siglen * 8 + msb)) {
  2165. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2166. }
  2167. /* Compensate for boundary condition when applying mask */
  2168. if (msb % 8 == 0) {
  2169. p++;
  2170. siglen -= 1;
  2171. }
  2172. if (siglen < hlen + 2) {
  2173. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2174. }
  2175. hash_start = p + siglen - hlen - 1;
  2176. ret = mgf_mask(p, siglen - hlen - 1, hash_start, hlen, mgf1_hash_id);
  2177. if (ret != 0) {
  2178. return ret;
  2179. }
  2180. buf[0] &= 0xFF >> (siglen * 8 - msb);
  2181. while (p < hash_start - 1 && *p == 0) {
  2182. p++;
  2183. }
  2184. if (*p++ != 0x01) {
  2185. return MBEDTLS_ERR_RSA_INVALID_PADDING;
  2186. }
  2187. observed_salt_len = (size_t) (hash_start - p);
  2188. if (expected_salt_len != MBEDTLS_RSA_SALT_LEN_ANY &&
  2189. observed_salt_len != (size_t) expected_salt_len) {
  2190. return MBEDTLS_ERR_RSA_INVALID_PADDING;
  2191. }
  2192. /*
  2193. * Generate H = Hash( M' )
  2194. */
  2195. ret = hash_mprime(hash, hashlen, p, observed_salt_len,
  2196. result, mgf1_hash_id);
  2197. if (ret != 0) {
  2198. return ret;
  2199. }
  2200. if (memcmp(hash_start, result, hlen) != 0) {
  2201. return MBEDTLS_ERR_RSA_VERIFY_FAILED;
  2202. }
  2203. return 0;
  2204. }
  2205. /*
  2206. * Simplified PKCS#1 v2.1 RSASSA-PSS-VERIFY function
  2207. */
  2208. int mbedtls_rsa_rsassa_pss_verify(mbedtls_rsa_context *ctx,
  2209. mbedtls_md_type_t md_alg,
  2210. unsigned int hashlen,
  2211. const unsigned char *hash,
  2212. const unsigned char *sig)
  2213. {
  2214. mbedtls_md_type_t mgf1_hash_id;
  2215. if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
  2216. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2217. }
  2218. mgf1_hash_id = (ctx->hash_id != MBEDTLS_MD_NONE)
  2219. ? (mbedtls_md_type_t) ctx->hash_id
  2220. : md_alg;
  2221. return mbedtls_rsa_rsassa_pss_verify_ext(ctx,
  2222. md_alg, hashlen, hash,
  2223. mgf1_hash_id,
  2224. MBEDTLS_RSA_SALT_LEN_ANY,
  2225. sig);
  2226. }
  2227. #endif /* MBEDTLS_PKCS1_V21 */
  2228. #if defined(MBEDTLS_PKCS1_V15)
  2229. /*
  2230. * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-v1_5-VERIFY function
  2231. */
  2232. int mbedtls_rsa_rsassa_pkcs1_v15_verify(mbedtls_rsa_context *ctx,
  2233. mbedtls_md_type_t md_alg,
  2234. unsigned int hashlen,
  2235. const unsigned char *hash,
  2236. const unsigned char *sig)
  2237. {
  2238. int ret = 0;
  2239. size_t sig_len;
  2240. unsigned char *encoded = NULL, *encoded_expected = NULL;
  2241. if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
  2242. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2243. }
  2244. sig_len = ctx->len;
  2245. /*
  2246. * Prepare expected PKCS1 v1.5 encoding of hash.
  2247. */
  2248. if ((encoded = mbedtls_calloc(1, sig_len)) == NULL ||
  2249. (encoded_expected = mbedtls_calloc(1, sig_len)) == NULL) {
  2250. ret = MBEDTLS_ERR_MPI_ALLOC_FAILED;
  2251. goto cleanup;
  2252. }
  2253. if ((ret = rsa_rsassa_pkcs1_v15_encode(md_alg, hashlen, hash, sig_len,
  2254. encoded_expected)) != 0) {
  2255. goto cleanup;
  2256. }
  2257. /*
  2258. * Apply RSA primitive to get what should be PKCS1 encoded hash.
  2259. */
  2260. ret = mbedtls_rsa_public(ctx, sig, encoded);
  2261. if (ret != 0) {
  2262. goto cleanup;
  2263. }
  2264. /*
  2265. * Compare
  2266. */
  2267. if ((ret = mbedtls_ct_memcmp(encoded, encoded_expected,
  2268. sig_len)) != 0) {
  2269. ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
  2270. goto cleanup;
  2271. }
  2272. cleanup:
  2273. if (encoded != NULL) {
  2274. mbedtls_zeroize_and_free(encoded, sig_len);
  2275. }
  2276. if (encoded_expected != NULL) {
  2277. mbedtls_zeroize_and_free(encoded_expected, sig_len);
  2278. }
  2279. return ret;
  2280. }
  2281. #endif /* MBEDTLS_PKCS1_V15 */
  2282. /*
  2283. * Do an RSA operation and check the message digest
  2284. */
  2285. int mbedtls_rsa_pkcs1_verify(mbedtls_rsa_context *ctx,
  2286. mbedtls_md_type_t md_alg,
  2287. unsigned int hashlen,
  2288. const unsigned char *hash,
  2289. const unsigned char *sig)
  2290. {
  2291. if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
  2292. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2293. }
  2294. switch (ctx->padding) {
  2295. #if defined(MBEDTLS_PKCS1_V15)
  2296. case MBEDTLS_RSA_PKCS_V15:
  2297. return mbedtls_rsa_rsassa_pkcs1_v15_verify(ctx, md_alg,
  2298. hashlen, hash, sig);
  2299. #endif
  2300. #if defined(MBEDTLS_PKCS1_V21)
  2301. case MBEDTLS_RSA_PKCS_V21:
  2302. return mbedtls_rsa_rsassa_pss_verify(ctx, md_alg,
  2303. hashlen, hash, sig);
  2304. #endif
  2305. default:
  2306. return MBEDTLS_ERR_RSA_INVALID_PADDING;
  2307. }
  2308. }
  2309. /*
  2310. * Copy the components of an RSA key
  2311. */
  2312. int mbedtls_rsa_copy(mbedtls_rsa_context *dst, const mbedtls_rsa_context *src)
  2313. {
  2314. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2315. dst->len = src->len;
  2316. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->N, &src->N));
  2317. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->E, &src->E));
  2318. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->D, &src->D));
  2319. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->P, &src->P));
  2320. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Q, &src->Q));
  2321. #if !defined(MBEDTLS_RSA_NO_CRT)
  2322. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->DP, &src->DP));
  2323. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->DQ, &src->DQ));
  2324. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->QP, &src->QP));
  2325. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RP, &src->RP));
  2326. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RQ, &src->RQ));
  2327. #endif
  2328. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RN, &src->RN));
  2329. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Vi, &src->Vi));
  2330. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Vf, &src->Vf));
  2331. dst->padding = src->padding;
  2332. dst->hash_id = src->hash_id;
  2333. cleanup:
  2334. if (ret != 0) {
  2335. mbedtls_rsa_free(dst);
  2336. }
  2337. return ret;
  2338. }
  2339. /*
  2340. * Free the components of an RSA key
  2341. */
  2342. void mbedtls_rsa_free(mbedtls_rsa_context *ctx)
  2343. {
  2344. if (ctx == NULL) {
  2345. return;
  2346. }
  2347. mbedtls_mpi_free(&ctx->Vi);
  2348. mbedtls_mpi_free(&ctx->Vf);
  2349. mbedtls_mpi_free(&ctx->RN);
  2350. mbedtls_mpi_free(&ctx->D);
  2351. mbedtls_mpi_free(&ctx->Q);
  2352. mbedtls_mpi_free(&ctx->P);
  2353. mbedtls_mpi_free(&ctx->E);
  2354. mbedtls_mpi_free(&ctx->N);
  2355. #if !defined(MBEDTLS_RSA_NO_CRT)
  2356. mbedtls_mpi_free(&ctx->RQ);
  2357. mbedtls_mpi_free(&ctx->RP);
  2358. mbedtls_mpi_free(&ctx->QP);
  2359. mbedtls_mpi_free(&ctx->DQ);
  2360. mbedtls_mpi_free(&ctx->DP);
  2361. #endif /* MBEDTLS_RSA_NO_CRT */
  2362. #if defined(MBEDTLS_THREADING_C)
  2363. /* Free the mutex, but only if it hasn't been freed already. */
  2364. if (ctx->ver != 0) {
  2365. mbedtls_mutex_free(&ctx->mutex);
  2366. ctx->ver = 0;
  2367. }
  2368. #endif
  2369. }
  2370. #endif /* !MBEDTLS_RSA_ALT */
  2371. #if defined(MBEDTLS_SELF_TEST)
  2372. /*
  2373. * Example RSA-1024 keypair, for test purposes
  2374. */
  2375. #define KEY_LEN 128
  2376. #define RSA_N "9292758453063D803DD603D5E777D788" \
  2377. "8ED1D5BF35786190FA2F23EBC0848AEA" \
  2378. "DDA92CA6C3D80B32C4D109BE0F36D6AE" \
  2379. "7130B9CED7ACDF54CFC7555AC14EEBAB" \
  2380. "93A89813FBF3C4F8066D2D800F7C38A8" \
  2381. "1AE31942917403FF4946B0A83D3D3E05" \
  2382. "EE57C6F5F5606FB5D4BC6CD34EE0801A" \
  2383. "5E94BB77B07507233A0BC7BAC8F90F79"
  2384. #define RSA_E "10001"
  2385. #define RSA_D "24BF6185468786FDD303083D25E64EFC" \
  2386. "66CA472BC44D253102F8B4A9D3BFA750" \
  2387. "91386C0077937FE33FA3252D28855837" \
  2388. "AE1B484A8A9A45F7EE8C0C634F99E8CD" \
  2389. "DF79C5CE07EE72C7F123142198164234" \
  2390. "CABB724CF78B8173B9F880FC86322407" \
  2391. "AF1FEDFDDE2BEB674CA15F3E81A1521E" \
  2392. "071513A1E85B5DFA031F21ECAE91A34D"
  2393. #define RSA_P "C36D0EB7FCD285223CFB5AABA5BDA3D8" \
  2394. "2C01CAD19EA484A87EA4377637E75500" \
  2395. "FCB2005C5C7DD6EC4AC023CDA285D796" \
  2396. "C3D9E75E1EFC42488BB4F1D13AC30A57"
  2397. #define RSA_Q "C000DF51A7C77AE8D7C7370C1FF55B69" \
  2398. "E211C2B9E5DB1ED0BF61D0D9899620F4" \
  2399. "910E4168387E3C30AA1E00C339A79508" \
  2400. "8452DD96A9A5EA5D9DCA68DA636032AF"
  2401. #define PT_LEN 24
  2402. #define RSA_PT "\xAA\xBB\xCC\x03\x02\x01\x00\xFF\xFF\xFF\xFF\xFF" \
  2403. "\x11\x22\x33\x0A\x0B\x0C\xCC\xDD\xDD\xDD\xDD\xDD"
  2404. #if defined(MBEDTLS_PKCS1_V15)
  2405. static int myrand(void *rng_state, unsigned char *output, size_t len)
  2406. {
  2407. #if !defined(__OpenBSD__) && !defined(__NetBSD__)
  2408. size_t i;
  2409. if (rng_state != NULL) {
  2410. rng_state = NULL;
  2411. }
  2412. for (i = 0; i < len; ++i) {
  2413. output[i] = rand();
  2414. }
  2415. #else
  2416. if (rng_state != NULL) {
  2417. rng_state = NULL;
  2418. }
  2419. arc4random_buf(output, len);
  2420. #endif /* !OpenBSD && !NetBSD */
  2421. return 0;
  2422. }
  2423. #endif /* MBEDTLS_PKCS1_V15 */
  2424. /*
  2425. * Checkup routine
  2426. */
  2427. int mbedtls_rsa_self_test(int verbose)
  2428. {
  2429. int ret = 0;
  2430. #if defined(MBEDTLS_PKCS1_V15)
  2431. size_t len;
  2432. mbedtls_rsa_context rsa;
  2433. unsigned char rsa_plaintext[PT_LEN];
  2434. unsigned char rsa_decrypted[PT_LEN];
  2435. unsigned char rsa_ciphertext[KEY_LEN];
  2436. #if defined(MBEDTLS_MD_CAN_SHA1)
  2437. unsigned char sha1sum[20];
  2438. #endif
  2439. mbedtls_mpi K;
  2440. mbedtls_mpi_init(&K);
  2441. mbedtls_rsa_init(&rsa);
  2442. MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_N));
  2443. MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, &K, NULL, NULL, NULL, NULL));
  2444. MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_P));
  2445. MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, &K, NULL, NULL, NULL));
  2446. MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_Q));
  2447. MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, &K, NULL, NULL));
  2448. MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_D));
  2449. MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, NULL, &K, NULL));
  2450. MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_E));
  2451. MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, NULL, NULL, &K));
  2452. MBEDTLS_MPI_CHK(mbedtls_rsa_complete(&rsa));
  2453. if (verbose != 0) {
  2454. mbedtls_printf(" RSA key validation: ");
  2455. }
  2456. if (mbedtls_rsa_check_pubkey(&rsa) != 0 ||
  2457. mbedtls_rsa_check_privkey(&rsa) != 0) {
  2458. if (verbose != 0) {
  2459. mbedtls_printf("failed\n");
  2460. }
  2461. ret = 1;
  2462. goto cleanup;
  2463. }
  2464. if (verbose != 0) {
  2465. mbedtls_printf("passed\n PKCS#1 encryption : ");
  2466. }
  2467. memcpy(rsa_plaintext, RSA_PT, PT_LEN);
  2468. if (mbedtls_rsa_pkcs1_encrypt(&rsa, myrand, NULL,
  2469. PT_LEN, rsa_plaintext,
  2470. rsa_ciphertext) != 0) {
  2471. if (verbose != 0) {
  2472. mbedtls_printf("failed\n");
  2473. }
  2474. ret = 1;
  2475. goto cleanup;
  2476. }
  2477. if (verbose != 0) {
  2478. mbedtls_printf("passed\n PKCS#1 decryption : ");
  2479. }
  2480. if (mbedtls_rsa_pkcs1_decrypt(&rsa, myrand, NULL,
  2481. &len, rsa_ciphertext, rsa_decrypted,
  2482. sizeof(rsa_decrypted)) != 0) {
  2483. if (verbose != 0) {
  2484. mbedtls_printf("failed\n");
  2485. }
  2486. ret = 1;
  2487. goto cleanup;
  2488. }
  2489. if (memcmp(rsa_decrypted, rsa_plaintext, len) != 0) {
  2490. if (verbose != 0) {
  2491. mbedtls_printf("failed\n");
  2492. }
  2493. ret = 1;
  2494. goto cleanup;
  2495. }
  2496. if (verbose != 0) {
  2497. mbedtls_printf("passed\n");
  2498. }
  2499. #if defined(MBEDTLS_MD_CAN_SHA1)
  2500. if (verbose != 0) {
  2501. mbedtls_printf(" PKCS#1 data sign : ");
  2502. }
  2503. if (mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_SHA1),
  2504. rsa_plaintext, PT_LEN, sha1sum) != 0) {
  2505. if (verbose != 0) {
  2506. mbedtls_printf("failed\n");
  2507. }
  2508. return 1;
  2509. }
  2510. if (mbedtls_rsa_pkcs1_sign(&rsa, myrand, NULL,
  2511. MBEDTLS_MD_SHA1, 20,
  2512. sha1sum, rsa_ciphertext) != 0) {
  2513. if (verbose != 0) {
  2514. mbedtls_printf("failed\n");
  2515. }
  2516. ret = 1;
  2517. goto cleanup;
  2518. }
  2519. if (verbose != 0) {
  2520. mbedtls_printf("passed\n PKCS#1 sig. verify: ");
  2521. }
  2522. if (mbedtls_rsa_pkcs1_verify(&rsa, MBEDTLS_MD_SHA1, 20,
  2523. sha1sum, rsa_ciphertext) != 0) {
  2524. if (verbose != 0) {
  2525. mbedtls_printf("failed\n");
  2526. }
  2527. ret = 1;
  2528. goto cleanup;
  2529. }
  2530. if (verbose != 0) {
  2531. mbedtls_printf("passed\n");
  2532. }
  2533. #endif /* MBEDTLS_MD_CAN_SHA1 */
  2534. if (verbose != 0) {
  2535. mbedtls_printf("\n");
  2536. }
  2537. cleanup:
  2538. mbedtls_mpi_free(&K);
  2539. mbedtls_rsa_free(&rsa);
  2540. #else /* MBEDTLS_PKCS1_V15 */
  2541. ((void) verbose);
  2542. #endif /* MBEDTLS_PKCS1_V15 */
  2543. return ret;
  2544. }
  2545. #endif /* MBEDTLS_SELF_TEST */
  2546. #endif /* MBEDTLS_RSA_C */