rsa.c 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038
  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;
  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. if (exponent < 3 || nbits % 2 != 0) {
  892. ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  893. goto cleanup;
  894. }
  895. if (nbits < MBEDTLS_RSA_GEN_KEY_MIN_BITS) {
  896. ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  897. goto cleanup;
  898. }
  899. /*
  900. * find primes P and Q with Q < P so that:
  901. * 1. |P-Q| > 2^( nbits / 2 - 100 )
  902. * 2. GCD( E, (P-1)*(Q-1) ) == 1
  903. * 3. E^-1 mod LCM(P-1, Q-1) > 2^( nbits / 2 )
  904. */
  905. MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&ctx->E, exponent));
  906. do {
  907. MBEDTLS_MPI_CHK(mbedtls_mpi_gen_prime(&ctx->P, nbits >> 1,
  908. prime_quality, f_rng, p_rng));
  909. MBEDTLS_MPI_CHK(mbedtls_mpi_gen_prime(&ctx->Q, nbits >> 1,
  910. prime_quality, f_rng, p_rng));
  911. /* make sure the difference between p and q is not too small (FIPS 186-4 §B.3.3 step 5.4) */
  912. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&H, &ctx->P, &ctx->Q));
  913. if (mbedtls_mpi_bitlen(&H) <= ((nbits >= 200) ? ((nbits >> 1) - 99) : 0)) {
  914. continue;
  915. }
  916. /* not required by any standards, but some users rely on the fact that P > Q */
  917. if (H.s < 0) {
  918. mbedtls_mpi_swap(&ctx->P, &ctx->Q);
  919. }
  920. /* Compute D = E^-1 mod LCM(P-1, Q-1) (FIPS 186-4 §B.3.1 criterion 3(b))
  921. * if it exists (FIPS 186-4 §B.3.1 criterion 2(a)) */
  922. ret = mbedtls_rsa_deduce_private_exponent(&ctx->P, &ctx->Q, &ctx->E, &ctx->D);
  923. if (ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) {
  924. mbedtls_mpi_lset(&ctx->D, 0); /* needed for the next call */
  925. continue;
  926. }
  927. if (ret != 0) {
  928. goto cleanup;
  929. }
  930. /* (FIPS 186-4 §B.3.1 criterion 3(a)) */
  931. if (mbedtls_mpi_bitlen(&ctx->D) <= ((nbits + 1) / 2)) {
  932. continue;
  933. }
  934. break;
  935. } while (1);
  936. /* N = P * Q */
  937. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->N, &ctx->P, &ctx->Q));
  938. ctx->len = mbedtls_mpi_size(&ctx->N);
  939. #if !defined(MBEDTLS_RSA_NO_CRT)
  940. /*
  941. * DP = D mod (P - 1)
  942. * DQ = D mod (Q - 1)
  943. * QP = Q^-1 mod P
  944. */
  945. MBEDTLS_MPI_CHK(mbedtls_rsa_deduce_crt(&ctx->P, &ctx->Q, &ctx->D,
  946. &ctx->DP, &ctx->DQ, &ctx->QP));
  947. #endif /* MBEDTLS_RSA_NO_CRT */
  948. /* Double-check */
  949. MBEDTLS_MPI_CHK(mbedtls_rsa_check_privkey(ctx));
  950. cleanup:
  951. mbedtls_mpi_free(&H);
  952. if (ret != 0) {
  953. mbedtls_rsa_free(ctx);
  954. if ((-ret & ~0x7f) == 0) {
  955. ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_KEY_GEN_FAILED, ret);
  956. }
  957. return ret;
  958. }
  959. return 0;
  960. }
  961. #endif /* MBEDTLS_GENPRIME */
  962. /*
  963. * Check a public RSA key
  964. */
  965. int mbedtls_rsa_check_pubkey(const mbedtls_rsa_context *ctx)
  966. {
  967. if (rsa_check_context(ctx, 0 /* public */, 0 /* no blinding */) != 0) {
  968. return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
  969. }
  970. if (mbedtls_mpi_bitlen(&ctx->N) < 128) {
  971. return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
  972. }
  973. if (mbedtls_mpi_get_bit(&ctx->E, 0) == 0 ||
  974. mbedtls_mpi_bitlen(&ctx->E) < 2 ||
  975. mbedtls_mpi_cmp_mpi(&ctx->E, &ctx->N) >= 0) {
  976. return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
  977. }
  978. return 0;
  979. }
  980. /*
  981. * Check for the consistency of all fields in an RSA private key context
  982. */
  983. int mbedtls_rsa_check_privkey(const mbedtls_rsa_context *ctx)
  984. {
  985. if (mbedtls_rsa_check_pubkey(ctx) != 0 ||
  986. rsa_check_context(ctx, 1 /* private */, 1 /* blinding */) != 0) {
  987. return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
  988. }
  989. if (mbedtls_rsa_validate_params(&ctx->N, &ctx->P, &ctx->Q,
  990. &ctx->D, &ctx->E, NULL, NULL) != 0) {
  991. return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
  992. }
  993. #if !defined(MBEDTLS_RSA_NO_CRT)
  994. else if (mbedtls_rsa_validate_crt(&ctx->P, &ctx->Q, &ctx->D,
  995. &ctx->DP, &ctx->DQ, &ctx->QP) != 0) {
  996. return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
  997. }
  998. #endif
  999. return 0;
  1000. }
  1001. /*
  1002. * Check if contexts holding a public and private key match
  1003. */
  1004. int mbedtls_rsa_check_pub_priv(const mbedtls_rsa_context *pub,
  1005. const mbedtls_rsa_context *prv)
  1006. {
  1007. if (mbedtls_rsa_check_pubkey(pub) != 0 ||
  1008. mbedtls_rsa_check_privkey(prv) != 0) {
  1009. return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
  1010. }
  1011. if (mbedtls_mpi_cmp_mpi(&pub->N, &prv->N) != 0 ||
  1012. mbedtls_mpi_cmp_mpi(&pub->E, &prv->E) != 0) {
  1013. return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
  1014. }
  1015. return 0;
  1016. }
  1017. /*
  1018. * Do an RSA public key operation
  1019. */
  1020. int mbedtls_rsa_public(mbedtls_rsa_context *ctx,
  1021. const unsigned char *input,
  1022. unsigned char *output)
  1023. {
  1024. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1025. size_t olen;
  1026. mbedtls_mpi T;
  1027. if (rsa_check_context(ctx, 0 /* public */, 0 /* no blinding */)) {
  1028. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1029. }
  1030. mbedtls_mpi_init(&T);
  1031. #if defined(MBEDTLS_THREADING_C)
  1032. if ((ret = mbedtls_mutex_lock(&ctx->mutex)) != 0) {
  1033. return ret;
  1034. }
  1035. #endif
  1036. MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&T, input, ctx->len));
  1037. if (mbedtls_mpi_cmp_mpi(&T, &ctx->N) >= 0) {
  1038. ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  1039. goto cleanup;
  1040. }
  1041. olen = ctx->len;
  1042. MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod_unsafe(&T, &T, &ctx->E, &ctx->N, &ctx->RN));
  1043. MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&T, output, olen));
  1044. cleanup:
  1045. #if defined(MBEDTLS_THREADING_C)
  1046. if (mbedtls_mutex_unlock(&ctx->mutex) != 0) {
  1047. return MBEDTLS_ERR_THREADING_MUTEX_ERROR;
  1048. }
  1049. #endif
  1050. mbedtls_mpi_free(&T);
  1051. if (ret != 0) {
  1052. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_PUBLIC_FAILED, ret);
  1053. }
  1054. return 0;
  1055. }
  1056. /*
  1057. * Generate or update blinding values, see section 10 of:
  1058. * KOCHER, Paul C. Timing attacks on implementations of Diffie-Hellman, RSA,
  1059. * DSS, and other systems. In : Advances in Cryptology-CRYPTO'96. Springer
  1060. * Berlin Heidelberg, 1996. p. 104-113.
  1061. */
  1062. static int rsa_prepare_blinding(mbedtls_rsa_context *ctx,
  1063. int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
  1064. {
  1065. int ret, count = 0;
  1066. mbedtls_mpi R;
  1067. mbedtls_mpi_init(&R);
  1068. if (ctx->Vf.p != NULL) {
  1069. /* We already have blinding values, just update them by squaring */
  1070. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vi, &ctx->Vi, &ctx->Vi));
  1071. MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vi, &ctx->Vi, &ctx->N));
  1072. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vf, &ctx->Vf, &ctx->Vf));
  1073. MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vf, &ctx->Vf, &ctx->N));
  1074. goto cleanup;
  1075. }
  1076. /* Unblinding value: Vf = random number, invertible mod N */
  1077. mbedtls_mpi_lset(&R, 0);
  1078. do {
  1079. if (count++ > 10) {
  1080. ret = MBEDTLS_ERR_RSA_RNG_FAILED;
  1081. goto cleanup;
  1082. }
  1083. MBEDTLS_MPI_CHK(mbedtls_mpi_random(&ctx->Vf, 1, &ctx->N, f_rng, p_rng));
  1084. MBEDTLS_MPI_CHK(mbedtls_mpi_gcd_modinv_odd(&R, &ctx->Vi, &ctx->Vf, &ctx->N));
  1085. } while (mbedtls_mpi_cmp_int(&R, 1) != 0);
  1086. /* Blinding value: Vi = Vf^(-e) mod N
  1087. * (Vi already contains Vf^-1 at this point) */
  1088. MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&ctx->Vi, &ctx->Vi, &ctx->E, &ctx->N, &ctx->RN));
  1089. cleanup:
  1090. mbedtls_mpi_free(&R);
  1091. return ret;
  1092. }
  1093. /*
  1094. * Unblind
  1095. * T = T * Vf mod N
  1096. */
  1097. static int rsa_unblind(mbedtls_mpi *T, mbedtls_mpi *Vf, const mbedtls_mpi *N)
  1098. {
  1099. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1100. const mbedtls_mpi_uint mm = mbedtls_mpi_core_montmul_init(N->p);
  1101. const size_t nlimbs = N->n;
  1102. const size_t tlimbs = mbedtls_mpi_core_montmul_working_limbs(nlimbs);
  1103. mbedtls_mpi RR, M_T;
  1104. mbedtls_mpi_init(&RR);
  1105. mbedtls_mpi_init(&M_T);
  1106. MBEDTLS_MPI_CHK(mbedtls_mpi_core_get_mont_r2_unsafe(&RR, N));
  1107. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&M_T, tlimbs));
  1108. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(T, nlimbs));
  1109. MBEDTLS_MPI_CHK(mbedtls_mpi_grow(Vf, nlimbs));
  1110. /* T = T * Vf mod N
  1111. * Reminder: montmul(A, B, N) = A * B * R^-1 mod N
  1112. * Usually both operands are multiplied by R mod N beforehand (by calling
  1113. * `to_mont_rep()` on them), yielding a result that's also * R mod N (aka
  1114. * "in the Montgomery domain"). Here we only multiply one operand by R mod
  1115. * N, so the result is directly what we want - no need to call
  1116. * `from_mont_rep()` on it. */
  1117. mbedtls_mpi_core_to_mont_rep(T->p, T->p, N->p, nlimbs, mm, RR.p, M_T.p);
  1118. mbedtls_mpi_core_montmul(T->p, T->p, Vf->p, nlimbs, N->p, nlimbs, mm, M_T.p);
  1119. cleanup:
  1120. mbedtls_mpi_free(&RR);
  1121. mbedtls_mpi_free(&M_T);
  1122. return ret;
  1123. }
  1124. /*
  1125. * Exponent blinding supposed to prevent side-channel attacks using multiple
  1126. * traces of measurements to recover the RSA key. The more collisions are there,
  1127. * the more bits of the key can be recovered. See [3].
  1128. *
  1129. * Collecting n collisions with m bit long blinding value requires 2^(m-m/n)
  1130. * observations on average.
  1131. *
  1132. * For example with 28 byte blinding to achieve 2 collisions the adversary has
  1133. * to make 2^112 observations on average.
  1134. *
  1135. * (With the currently (as of 2017 April) known best algorithms breaking 2048
  1136. * bit RSA requires approximately as much time as trying out 2^112 random keys.
  1137. * Thus in this sense with 28 byte blinding the security is not reduced by
  1138. * side-channel attacks like the one in [3])
  1139. *
  1140. * This countermeasure does not help if the key recovery is possible with a
  1141. * single trace.
  1142. */
  1143. #define RSA_EXPONENT_BLINDING 28
  1144. /*
  1145. * Do an RSA private key operation
  1146. */
  1147. int mbedtls_rsa_private(mbedtls_rsa_context *ctx,
  1148. int (*f_rng)(void *, unsigned char *, size_t),
  1149. void *p_rng,
  1150. const unsigned char *input,
  1151. unsigned char *output)
  1152. {
  1153. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1154. size_t olen;
  1155. /* Temporary holding the result */
  1156. mbedtls_mpi T;
  1157. /* Temporaries holding P-1, Q-1 and the
  1158. * exponent blinding factor, respectively. */
  1159. mbedtls_mpi P1, Q1, R;
  1160. #if !defined(MBEDTLS_RSA_NO_CRT)
  1161. /* Temporaries holding the results mod p resp. mod q. */
  1162. mbedtls_mpi TP, TQ;
  1163. /* Temporaries holding the blinded exponents for
  1164. * the mod p resp. mod q computation (if used). */
  1165. mbedtls_mpi DP_blind, DQ_blind;
  1166. #else
  1167. /* Temporary holding the blinded exponent (if used). */
  1168. mbedtls_mpi D_blind;
  1169. #endif /* MBEDTLS_RSA_NO_CRT */
  1170. /* Temporaries holding the initial input and the double
  1171. * checked result; should be the same in the end. */
  1172. mbedtls_mpi input_blinded, check_result_blinded;
  1173. if (f_rng == NULL) {
  1174. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1175. }
  1176. if (rsa_check_context(ctx, 1 /* private key checks */,
  1177. 1 /* blinding on */) != 0) {
  1178. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1179. }
  1180. #if defined(MBEDTLS_THREADING_C)
  1181. if ((ret = mbedtls_mutex_lock(&ctx->mutex)) != 0) {
  1182. return ret;
  1183. }
  1184. #endif
  1185. /* MPI Initialization */
  1186. mbedtls_mpi_init(&T);
  1187. mbedtls_mpi_init(&P1);
  1188. mbedtls_mpi_init(&Q1);
  1189. mbedtls_mpi_init(&R);
  1190. #if defined(MBEDTLS_RSA_NO_CRT)
  1191. mbedtls_mpi_init(&D_blind);
  1192. #else
  1193. mbedtls_mpi_init(&DP_blind);
  1194. mbedtls_mpi_init(&DQ_blind);
  1195. #endif
  1196. #if !defined(MBEDTLS_RSA_NO_CRT)
  1197. mbedtls_mpi_init(&TP); mbedtls_mpi_init(&TQ);
  1198. #endif
  1199. mbedtls_mpi_init(&input_blinded);
  1200. mbedtls_mpi_init(&check_result_blinded);
  1201. /* End of MPI initialization */
  1202. MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&T, input, ctx->len));
  1203. if (mbedtls_mpi_cmp_mpi(&T, &ctx->N) >= 0) {
  1204. ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
  1205. goto cleanup;
  1206. }
  1207. /*
  1208. * Blinding
  1209. * T = T * Vi mod N
  1210. */
  1211. MBEDTLS_MPI_CHK(rsa_prepare_blinding(ctx, f_rng, p_rng));
  1212. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&T, &T, &ctx->Vi));
  1213. MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&T, &T, &ctx->N));
  1214. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&input_blinded, &T));
  1215. /*
  1216. * Exponent blinding
  1217. */
  1218. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&P1, &ctx->P, 1));
  1219. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&Q1, &ctx->Q, 1));
  1220. #if defined(MBEDTLS_RSA_NO_CRT)
  1221. /*
  1222. * D_blind = ( P - 1 ) * ( Q - 1 ) * R + D
  1223. */
  1224. MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING,
  1225. f_rng, p_rng));
  1226. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&D_blind, &P1, &Q1));
  1227. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&D_blind, &D_blind, &R));
  1228. MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&D_blind, &D_blind, &ctx->D));
  1229. #else
  1230. /*
  1231. * DP_blind = ( P - 1 ) * R + DP
  1232. */
  1233. MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING,
  1234. f_rng, p_rng));
  1235. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&DP_blind, &P1, &R));
  1236. MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&DP_blind, &DP_blind,
  1237. &ctx->DP));
  1238. /*
  1239. * DQ_blind = ( Q - 1 ) * R + DQ
  1240. */
  1241. MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING,
  1242. f_rng, p_rng));
  1243. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&DQ_blind, &Q1, &R));
  1244. MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&DQ_blind, &DQ_blind,
  1245. &ctx->DQ));
  1246. #endif /* MBEDTLS_RSA_NO_CRT */
  1247. #if defined(MBEDTLS_RSA_NO_CRT)
  1248. MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&T, &T, &D_blind, &ctx->N, &ctx->RN));
  1249. #else
  1250. /*
  1251. * Faster decryption using the CRT
  1252. *
  1253. * TP = input ^ dP mod P
  1254. * TQ = input ^ dQ mod Q
  1255. */
  1256. MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&TP, &T, &DP_blind, &ctx->P, &ctx->RP));
  1257. MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&TQ, &T, &DQ_blind, &ctx->Q, &ctx->RQ));
  1258. /*
  1259. * T = (TP - TQ) * (Q^-1 mod P) mod P
  1260. */
  1261. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&T, &TP, &TQ));
  1262. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&TP, &T, &ctx->QP));
  1263. MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&T, &TP, &ctx->P));
  1264. /*
  1265. * T = TQ + T * Q
  1266. */
  1267. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&TP, &T, &ctx->Q));
  1268. MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&T, &TQ, &TP));
  1269. #endif /* MBEDTLS_RSA_NO_CRT */
  1270. /* Verify the result to prevent glitching attacks. */
  1271. MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&check_result_blinded, &T, &ctx->E,
  1272. &ctx->N, &ctx->RN));
  1273. if (mbedtls_mpi_cmp_mpi(&check_result_blinded, &input_blinded) != 0) {
  1274. ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
  1275. goto cleanup;
  1276. }
  1277. /*
  1278. * Unblind
  1279. * T = T * Vf mod N
  1280. */
  1281. MBEDTLS_MPI_CHK(rsa_unblind(&T, &ctx->Vf, &ctx->N));
  1282. olen = ctx->len;
  1283. MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&T, output, olen));
  1284. cleanup:
  1285. #if defined(MBEDTLS_THREADING_C)
  1286. if (mbedtls_mutex_unlock(&ctx->mutex) != 0) {
  1287. return MBEDTLS_ERR_THREADING_MUTEX_ERROR;
  1288. }
  1289. #endif
  1290. mbedtls_mpi_free(&P1);
  1291. mbedtls_mpi_free(&Q1);
  1292. mbedtls_mpi_free(&R);
  1293. #if defined(MBEDTLS_RSA_NO_CRT)
  1294. mbedtls_mpi_free(&D_blind);
  1295. #else
  1296. mbedtls_mpi_free(&DP_blind);
  1297. mbedtls_mpi_free(&DQ_blind);
  1298. #endif
  1299. mbedtls_mpi_free(&T);
  1300. #if !defined(MBEDTLS_RSA_NO_CRT)
  1301. mbedtls_mpi_free(&TP); mbedtls_mpi_free(&TQ);
  1302. #endif
  1303. mbedtls_mpi_free(&check_result_blinded);
  1304. mbedtls_mpi_free(&input_blinded);
  1305. if (ret != 0 && ret >= -0x007f) {
  1306. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_PRIVATE_FAILED, ret);
  1307. }
  1308. return ret;
  1309. }
  1310. #if defined(MBEDTLS_PKCS1_V21)
  1311. /**
  1312. * Generate and apply the MGF1 operation (from PKCS#1 v2.1) to a buffer.
  1313. *
  1314. * \param dst buffer to mask
  1315. * \param dlen length of destination buffer
  1316. * \param src source of the mask generation
  1317. * \param slen length of the source buffer
  1318. * \param md_alg message digest to use
  1319. */
  1320. static int mgf_mask(unsigned char *dst, size_t dlen, unsigned char *src,
  1321. size_t slen, mbedtls_md_type_t md_alg)
  1322. {
  1323. unsigned char counter[4];
  1324. unsigned char *p;
  1325. unsigned int hlen;
  1326. size_t i, use_len;
  1327. unsigned char mask[MBEDTLS_MD_MAX_SIZE];
  1328. int ret = 0;
  1329. const mbedtls_md_info_t *md_info;
  1330. mbedtls_md_context_t md_ctx;
  1331. mbedtls_md_init(&md_ctx);
  1332. md_info = mbedtls_md_info_from_type(md_alg);
  1333. if (md_info == NULL) {
  1334. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1335. }
  1336. mbedtls_md_init(&md_ctx);
  1337. if ((ret = mbedtls_md_setup(&md_ctx, md_info, 0)) != 0) {
  1338. goto exit;
  1339. }
  1340. hlen = mbedtls_md_get_size(md_info);
  1341. memset(mask, 0, sizeof(mask));
  1342. memset(counter, 0, 4);
  1343. /* Generate and apply dbMask */
  1344. p = dst;
  1345. while (dlen > 0) {
  1346. use_len = hlen;
  1347. if (dlen < hlen) {
  1348. use_len = dlen;
  1349. }
  1350. if ((ret = mbedtls_md_starts(&md_ctx)) != 0) {
  1351. goto exit;
  1352. }
  1353. if ((ret = mbedtls_md_update(&md_ctx, src, slen)) != 0) {
  1354. goto exit;
  1355. }
  1356. if ((ret = mbedtls_md_update(&md_ctx, counter, 4)) != 0) {
  1357. goto exit;
  1358. }
  1359. if ((ret = mbedtls_md_finish(&md_ctx, mask)) != 0) {
  1360. goto exit;
  1361. }
  1362. for (i = 0; i < use_len; ++i) {
  1363. *p++ ^= mask[i];
  1364. }
  1365. counter[3]++;
  1366. dlen -= use_len;
  1367. }
  1368. exit:
  1369. mbedtls_platform_zeroize(mask, sizeof(mask));
  1370. mbedtls_md_free(&md_ctx);
  1371. return ret;
  1372. }
  1373. /**
  1374. * Generate Hash(M') as in RFC 8017 page 43 points 5 and 6.
  1375. *
  1376. * \param hash the input hash
  1377. * \param hlen length of the input hash
  1378. * \param salt the input salt
  1379. * \param slen length of the input salt
  1380. * \param out the output buffer - must be large enough for \p md_alg
  1381. * \param md_alg message digest to use
  1382. */
  1383. static int hash_mprime(const unsigned char *hash, size_t hlen,
  1384. const unsigned char *salt, size_t slen,
  1385. unsigned char *out, mbedtls_md_type_t md_alg)
  1386. {
  1387. const unsigned char zeros[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
  1388. mbedtls_md_context_t md_ctx;
  1389. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1390. const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(md_alg);
  1391. if (md_info == NULL) {
  1392. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1393. }
  1394. mbedtls_md_init(&md_ctx);
  1395. if ((ret = mbedtls_md_setup(&md_ctx, md_info, 0)) != 0) {
  1396. goto exit;
  1397. }
  1398. if ((ret = mbedtls_md_starts(&md_ctx)) != 0) {
  1399. goto exit;
  1400. }
  1401. if ((ret = mbedtls_md_update(&md_ctx, zeros, sizeof(zeros))) != 0) {
  1402. goto exit;
  1403. }
  1404. if ((ret = mbedtls_md_update(&md_ctx, hash, hlen)) != 0) {
  1405. goto exit;
  1406. }
  1407. if ((ret = mbedtls_md_update(&md_ctx, salt, slen)) != 0) {
  1408. goto exit;
  1409. }
  1410. if ((ret = mbedtls_md_finish(&md_ctx, out)) != 0) {
  1411. goto exit;
  1412. }
  1413. exit:
  1414. mbedtls_md_free(&md_ctx);
  1415. return ret;
  1416. }
  1417. /**
  1418. * Compute a hash.
  1419. *
  1420. * \param md_alg algorithm to use
  1421. * \param input input message to hash
  1422. * \param ilen input length
  1423. * \param output the output buffer - must be large enough for \p md_alg
  1424. */
  1425. static int compute_hash(mbedtls_md_type_t md_alg,
  1426. const unsigned char *input, size_t ilen,
  1427. unsigned char *output)
  1428. {
  1429. const mbedtls_md_info_t *md_info;
  1430. md_info = mbedtls_md_info_from_type(md_alg);
  1431. if (md_info == NULL) {
  1432. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1433. }
  1434. return mbedtls_md(md_info, input, ilen, output);
  1435. }
  1436. #endif /* MBEDTLS_PKCS1_V21 */
  1437. #if defined(MBEDTLS_PKCS1_V21)
  1438. /*
  1439. * Implementation of the PKCS#1 v2.1 RSAES-OAEP-ENCRYPT function
  1440. */
  1441. int mbedtls_rsa_rsaes_oaep_encrypt(mbedtls_rsa_context *ctx,
  1442. int (*f_rng)(void *, unsigned char *, size_t),
  1443. void *p_rng,
  1444. const unsigned char *label, size_t label_len,
  1445. size_t ilen,
  1446. const unsigned char *input,
  1447. unsigned char *output)
  1448. {
  1449. size_t olen;
  1450. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1451. unsigned char *p = output;
  1452. unsigned int hlen;
  1453. if (f_rng == NULL) {
  1454. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1455. }
  1456. hlen = mbedtls_md_get_size_from_type((mbedtls_md_type_t) ctx->hash_id);
  1457. if (hlen == 0) {
  1458. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1459. }
  1460. olen = ctx->len;
  1461. /* first comparison checks for overflow */
  1462. if (ilen + 2 * hlen + 2 < ilen || olen < ilen + 2 * hlen + 2) {
  1463. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1464. }
  1465. memset(output, 0, olen);
  1466. *p++ = 0;
  1467. /* Generate a random octet string seed */
  1468. if ((ret = f_rng(p_rng, p, hlen)) != 0) {
  1469. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_RNG_FAILED, ret);
  1470. }
  1471. p += hlen;
  1472. /* Construct DB */
  1473. ret = compute_hash((mbedtls_md_type_t) ctx->hash_id, label, label_len, p);
  1474. if (ret != 0) {
  1475. return ret;
  1476. }
  1477. p += hlen;
  1478. p += olen - 2 * hlen - 2 - ilen;
  1479. *p++ = 1;
  1480. if (ilen != 0) {
  1481. memcpy(p, input, ilen);
  1482. }
  1483. /* maskedDB: Apply dbMask to DB */
  1484. if ((ret = mgf_mask(output + hlen + 1, olen - hlen - 1, output + 1, hlen,
  1485. (mbedtls_md_type_t) ctx->hash_id)) != 0) {
  1486. return ret;
  1487. }
  1488. /* maskedSeed: Apply seedMask to seed */
  1489. if ((ret = mgf_mask(output + 1, hlen, output + hlen + 1, olen - hlen - 1,
  1490. (mbedtls_md_type_t) ctx->hash_id)) != 0) {
  1491. return ret;
  1492. }
  1493. return mbedtls_rsa_public(ctx, output, output);
  1494. }
  1495. #endif /* MBEDTLS_PKCS1_V21 */
  1496. #if defined(MBEDTLS_PKCS1_V15)
  1497. /*
  1498. * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-ENCRYPT function
  1499. */
  1500. int mbedtls_rsa_rsaes_pkcs1_v15_encrypt(mbedtls_rsa_context *ctx,
  1501. int (*f_rng)(void *, unsigned char *, size_t),
  1502. void *p_rng, size_t ilen,
  1503. const unsigned char *input,
  1504. unsigned char *output)
  1505. {
  1506. size_t nb_pad, olen;
  1507. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1508. unsigned char *p = output;
  1509. olen = ctx->len;
  1510. /* first comparison checks for overflow */
  1511. if (ilen + 11 < ilen || olen < ilen + 11) {
  1512. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1513. }
  1514. nb_pad = olen - 3 - ilen;
  1515. *p++ = 0;
  1516. if (f_rng == NULL) {
  1517. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1518. }
  1519. *p++ = MBEDTLS_RSA_CRYPT;
  1520. while (nb_pad-- > 0) {
  1521. int rng_dl = 100;
  1522. do {
  1523. ret = f_rng(p_rng, p, 1);
  1524. } while (*p == 0 && --rng_dl && ret == 0);
  1525. /* Check if RNG failed to generate data */
  1526. if (rng_dl == 0 || ret != 0) {
  1527. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_RNG_FAILED, ret);
  1528. }
  1529. p++;
  1530. }
  1531. *p++ = 0;
  1532. if (ilen != 0) {
  1533. memcpy(p, input, ilen);
  1534. }
  1535. return mbedtls_rsa_public(ctx, output, output);
  1536. }
  1537. #endif /* MBEDTLS_PKCS1_V15 */
  1538. /*
  1539. * Add the message padding, then do an RSA operation
  1540. */
  1541. int mbedtls_rsa_pkcs1_encrypt(mbedtls_rsa_context *ctx,
  1542. int (*f_rng)(void *, unsigned char *, size_t),
  1543. void *p_rng,
  1544. size_t ilen,
  1545. const unsigned char *input,
  1546. unsigned char *output)
  1547. {
  1548. switch (ctx->padding) {
  1549. #if defined(MBEDTLS_PKCS1_V15)
  1550. case MBEDTLS_RSA_PKCS_V15:
  1551. return mbedtls_rsa_rsaes_pkcs1_v15_encrypt(ctx, f_rng, p_rng,
  1552. ilen, input, output);
  1553. #endif
  1554. #if defined(MBEDTLS_PKCS1_V21)
  1555. case MBEDTLS_RSA_PKCS_V21:
  1556. return mbedtls_rsa_rsaes_oaep_encrypt(ctx, f_rng, p_rng, NULL, 0,
  1557. ilen, input, output);
  1558. #endif
  1559. default:
  1560. return MBEDTLS_ERR_RSA_INVALID_PADDING;
  1561. }
  1562. }
  1563. #if defined(MBEDTLS_PKCS1_V21)
  1564. /*
  1565. * Implementation of the PKCS#1 v2.1 RSAES-OAEP-DECRYPT function
  1566. */
  1567. int mbedtls_rsa_rsaes_oaep_decrypt(mbedtls_rsa_context *ctx,
  1568. int (*f_rng)(void *, unsigned char *, size_t),
  1569. void *p_rng,
  1570. const unsigned char *label, size_t label_len,
  1571. size_t *olen,
  1572. const unsigned char *input,
  1573. unsigned char *output,
  1574. size_t output_max_len)
  1575. {
  1576. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1577. size_t ilen, i, pad_len;
  1578. unsigned char *p;
  1579. mbedtls_ct_condition_t bad, in_padding;
  1580. unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
  1581. unsigned char lhash[MBEDTLS_MD_MAX_SIZE];
  1582. unsigned int hlen;
  1583. /*
  1584. * Parameters sanity checks
  1585. */
  1586. if (ctx->padding != MBEDTLS_RSA_PKCS_V21) {
  1587. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1588. }
  1589. ilen = ctx->len;
  1590. if (ilen < 16 || ilen > sizeof(buf)) {
  1591. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1592. }
  1593. hlen = mbedtls_md_get_size_from_type((mbedtls_md_type_t) ctx->hash_id);
  1594. if (hlen == 0) {
  1595. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1596. }
  1597. // checking for integer underflow
  1598. if (2 * hlen + 2 > ilen) {
  1599. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1600. }
  1601. /*
  1602. * RSA operation
  1603. */
  1604. ret = mbedtls_rsa_private(ctx, f_rng, p_rng, input, buf);
  1605. if (ret != 0) {
  1606. goto cleanup;
  1607. }
  1608. /*
  1609. * Unmask data and generate lHash
  1610. */
  1611. /* seed: Apply seedMask to maskedSeed */
  1612. if ((ret = mgf_mask(buf + 1, hlen, buf + hlen + 1, ilen - hlen - 1,
  1613. (mbedtls_md_type_t) ctx->hash_id)) != 0 ||
  1614. /* DB: Apply dbMask to maskedDB */
  1615. (ret = mgf_mask(buf + hlen + 1, ilen - hlen - 1, buf + 1, hlen,
  1616. (mbedtls_md_type_t) ctx->hash_id)) != 0) {
  1617. goto cleanup;
  1618. }
  1619. /* Generate lHash */
  1620. ret = compute_hash((mbedtls_md_type_t) ctx->hash_id,
  1621. label, label_len, lhash);
  1622. if (ret != 0) {
  1623. goto cleanup;
  1624. }
  1625. /*
  1626. * Check contents, in "constant-time"
  1627. */
  1628. p = buf;
  1629. bad = mbedtls_ct_bool(*p++); /* First byte must be 0 */
  1630. p += hlen; /* Skip seed */
  1631. /* Check lHash */
  1632. bad = mbedtls_ct_bool_or(bad, mbedtls_ct_bool(mbedtls_ct_memcmp(lhash, p, hlen)));
  1633. p += hlen;
  1634. /* Get zero-padding len, but always read till end of buffer
  1635. * (minus one, for the 01 byte) */
  1636. pad_len = 0;
  1637. in_padding = MBEDTLS_CT_TRUE;
  1638. for (i = 0; i < ilen - 2 * hlen - 2; i++) {
  1639. in_padding = mbedtls_ct_bool_and(in_padding, mbedtls_ct_uint_eq(p[i], 0));
  1640. pad_len += mbedtls_ct_uint_if_else_0(in_padding, 1);
  1641. }
  1642. p += pad_len;
  1643. bad = mbedtls_ct_bool_or(bad, mbedtls_ct_uint_ne(*p++, 0x01));
  1644. /*
  1645. * The only information "leaked" is whether the padding was correct or not
  1646. * (eg, no data is copied if it was not correct). This meets the
  1647. * recommendations in PKCS#1 v2.2: an opponent cannot distinguish between
  1648. * the different error conditions.
  1649. */
  1650. if (bad != MBEDTLS_CT_FALSE) {
  1651. ret = MBEDTLS_ERR_RSA_INVALID_PADDING;
  1652. goto cleanup;
  1653. }
  1654. if (ilen - ((size_t) (p - buf)) > output_max_len) {
  1655. ret = MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE;
  1656. goto cleanup;
  1657. }
  1658. *olen = ilen - ((size_t) (p - buf));
  1659. if (*olen != 0) {
  1660. memcpy(output, p, *olen);
  1661. }
  1662. ret = 0;
  1663. cleanup:
  1664. mbedtls_platform_zeroize(buf, sizeof(buf));
  1665. mbedtls_platform_zeroize(lhash, sizeof(lhash));
  1666. return ret;
  1667. }
  1668. #endif /* MBEDTLS_PKCS1_V21 */
  1669. #if defined(MBEDTLS_PKCS1_V15)
  1670. /*
  1671. * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-DECRYPT function
  1672. */
  1673. int mbedtls_rsa_rsaes_pkcs1_v15_decrypt(mbedtls_rsa_context *ctx,
  1674. int (*f_rng)(void *, unsigned char *, size_t),
  1675. void *p_rng,
  1676. size_t *olen,
  1677. const unsigned char *input,
  1678. unsigned char *output,
  1679. size_t output_max_len)
  1680. {
  1681. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1682. size_t ilen;
  1683. unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
  1684. ilen = ctx->len;
  1685. if (ctx->padding != MBEDTLS_RSA_PKCS_V15) {
  1686. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1687. }
  1688. if (ilen < 16 || ilen > sizeof(buf)) {
  1689. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1690. }
  1691. ret = mbedtls_rsa_private(ctx, f_rng, p_rng, input, buf);
  1692. if (ret != 0) {
  1693. goto cleanup;
  1694. }
  1695. ret = mbedtls_ct_rsaes_pkcs1_v15_unpadding(buf, ilen,
  1696. output, output_max_len, olen);
  1697. cleanup:
  1698. mbedtls_platform_zeroize(buf, sizeof(buf));
  1699. return ret;
  1700. }
  1701. #endif /* MBEDTLS_PKCS1_V15 */
  1702. /*
  1703. * Do an RSA operation, then remove the message padding
  1704. */
  1705. int mbedtls_rsa_pkcs1_decrypt(mbedtls_rsa_context *ctx,
  1706. int (*f_rng)(void *, unsigned char *, size_t),
  1707. void *p_rng,
  1708. size_t *olen,
  1709. const unsigned char *input,
  1710. unsigned char *output,
  1711. size_t output_max_len)
  1712. {
  1713. switch (ctx->padding) {
  1714. #if defined(MBEDTLS_PKCS1_V15)
  1715. case MBEDTLS_RSA_PKCS_V15:
  1716. return mbedtls_rsa_rsaes_pkcs1_v15_decrypt(ctx, f_rng, p_rng, olen,
  1717. input, output, output_max_len);
  1718. #endif
  1719. #if defined(MBEDTLS_PKCS1_V21)
  1720. case MBEDTLS_RSA_PKCS_V21:
  1721. return mbedtls_rsa_rsaes_oaep_decrypt(ctx, f_rng, p_rng, NULL, 0,
  1722. olen, input, output,
  1723. output_max_len);
  1724. #endif
  1725. default:
  1726. return MBEDTLS_ERR_RSA_INVALID_PADDING;
  1727. }
  1728. }
  1729. #if defined(MBEDTLS_PKCS1_V21)
  1730. static int rsa_rsassa_pss_sign_no_mode_check(mbedtls_rsa_context *ctx,
  1731. int (*f_rng)(void *, unsigned char *, size_t),
  1732. void *p_rng,
  1733. mbedtls_md_type_t md_alg,
  1734. unsigned int hashlen,
  1735. const unsigned char *hash,
  1736. int saltlen,
  1737. unsigned char *sig)
  1738. {
  1739. size_t olen;
  1740. unsigned char *p = sig;
  1741. unsigned char *salt = NULL;
  1742. size_t slen, min_slen, hlen, offset = 0;
  1743. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1744. size_t msb;
  1745. mbedtls_md_type_t hash_id;
  1746. if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
  1747. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1748. }
  1749. if (f_rng == NULL) {
  1750. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1751. }
  1752. olen = ctx->len;
  1753. if (md_alg != MBEDTLS_MD_NONE) {
  1754. /* Gather length of hash to sign */
  1755. size_t exp_hashlen = mbedtls_md_get_size_from_type(md_alg);
  1756. if (exp_hashlen == 0) {
  1757. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1758. }
  1759. if (hashlen != exp_hashlen) {
  1760. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1761. }
  1762. }
  1763. hash_id = (mbedtls_md_type_t) ctx->hash_id;
  1764. if (hash_id == MBEDTLS_MD_NONE) {
  1765. hash_id = md_alg;
  1766. }
  1767. hlen = mbedtls_md_get_size_from_type(hash_id);
  1768. if (hlen == 0) {
  1769. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1770. }
  1771. if (saltlen == MBEDTLS_RSA_SALT_LEN_ANY) {
  1772. /* Calculate the largest possible salt length, up to the hash size.
  1773. * Normally this is the hash length, which is the maximum salt length
  1774. * according to FIPS 185-4 §5.5 (e) and common practice. If there is not
  1775. * enough room, use the maximum salt length that fits. The constraint is
  1776. * that the hash length plus the salt length plus 2 bytes must be at most
  1777. * the key length. This complies with FIPS 186-4 §5.5 (e) and RFC 8017
  1778. * (PKCS#1 v2.2) §9.1.1 step 3. */
  1779. min_slen = hlen - 2;
  1780. if (olen < hlen + min_slen + 2) {
  1781. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1782. } else if (olen >= hlen + hlen + 2) {
  1783. slen = hlen;
  1784. } else {
  1785. slen = olen - hlen - 2;
  1786. }
  1787. } else if ((saltlen < 0) || (saltlen + hlen + 2 > olen)) {
  1788. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1789. } else {
  1790. slen = (size_t) saltlen;
  1791. }
  1792. memset(sig, 0, olen);
  1793. /* Note: EMSA-PSS encoding is over the length of N - 1 bits */
  1794. msb = mbedtls_mpi_bitlen(&ctx->N) - 1;
  1795. p += olen - hlen - slen - 2;
  1796. *p++ = 0x01;
  1797. /* Generate salt of length slen in place in the encoded message */
  1798. salt = p;
  1799. if ((ret = f_rng(p_rng, salt, slen)) != 0) {
  1800. return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_RNG_FAILED, ret);
  1801. }
  1802. p += slen;
  1803. /* Generate H = Hash( M' ) */
  1804. ret = hash_mprime(hash, hashlen, salt, slen, p, hash_id);
  1805. if (ret != 0) {
  1806. return ret;
  1807. }
  1808. /* Compensate for boundary condition when applying mask */
  1809. if (msb % 8 == 0) {
  1810. offset = 1;
  1811. }
  1812. /* maskedDB: Apply dbMask to DB */
  1813. ret = mgf_mask(sig + offset, olen - hlen - 1 - offset, p, hlen, hash_id);
  1814. if (ret != 0) {
  1815. return ret;
  1816. }
  1817. msb = mbedtls_mpi_bitlen(&ctx->N) - 1;
  1818. sig[0] &= 0xFF >> (olen * 8 - msb);
  1819. p += hlen;
  1820. *p++ = 0xBC;
  1821. return mbedtls_rsa_private(ctx, f_rng, p_rng, sig, sig);
  1822. }
  1823. static int rsa_rsassa_pss_sign(mbedtls_rsa_context *ctx,
  1824. int (*f_rng)(void *, unsigned char *, size_t),
  1825. void *p_rng,
  1826. mbedtls_md_type_t md_alg,
  1827. unsigned int hashlen,
  1828. const unsigned char *hash,
  1829. int saltlen,
  1830. unsigned char *sig)
  1831. {
  1832. if (ctx->padding != MBEDTLS_RSA_PKCS_V21) {
  1833. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1834. }
  1835. if ((ctx->hash_id == MBEDTLS_MD_NONE) && (md_alg == MBEDTLS_MD_NONE)) {
  1836. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1837. }
  1838. return rsa_rsassa_pss_sign_no_mode_check(ctx, f_rng, p_rng, md_alg, hashlen, hash, saltlen,
  1839. sig);
  1840. }
  1841. int mbedtls_rsa_rsassa_pss_sign_no_mode_check(mbedtls_rsa_context *ctx,
  1842. int (*f_rng)(void *, unsigned char *, size_t),
  1843. void *p_rng,
  1844. mbedtls_md_type_t md_alg,
  1845. unsigned int hashlen,
  1846. const unsigned char *hash,
  1847. unsigned char *sig)
  1848. {
  1849. return rsa_rsassa_pss_sign_no_mode_check(ctx, f_rng, p_rng, md_alg,
  1850. hashlen, hash, MBEDTLS_RSA_SALT_LEN_ANY, sig);
  1851. }
  1852. /*
  1853. * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function with
  1854. * the option to pass in the salt length.
  1855. */
  1856. int mbedtls_rsa_rsassa_pss_sign_ext(mbedtls_rsa_context *ctx,
  1857. int (*f_rng)(void *, unsigned char *, size_t),
  1858. void *p_rng,
  1859. mbedtls_md_type_t md_alg,
  1860. unsigned int hashlen,
  1861. const unsigned char *hash,
  1862. int saltlen,
  1863. unsigned char *sig)
  1864. {
  1865. return rsa_rsassa_pss_sign(ctx, f_rng, p_rng, md_alg,
  1866. hashlen, hash, saltlen, sig);
  1867. }
  1868. /*
  1869. * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function
  1870. */
  1871. int mbedtls_rsa_rsassa_pss_sign(mbedtls_rsa_context *ctx,
  1872. int (*f_rng)(void *, unsigned char *, size_t),
  1873. void *p_rng,
  1874. mbedtls_md_type_t md_alg,
  1875. unsigned int hashlen,
  1876. const unsigned char *hash,
  1877. unsigned char *sig)
  1878. {
  1879. return rsa_rsassa_pss_sign(ctx, f_rng, p_rng, md_alg,
  1880. hashlen, hash, MBEDTLS_RSA_SALT_LEN_ANY, sig);
  1881. }
  1882. #endif /* MBEDTLS_PKCS1_V21 */
  1883. #if defined(MBEDTLS_PKCS1_V15)
  1884. /*
  1885. * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-V1_5-SIGN function
  1886. */
  1887. /* Construct a PKCS v1.5 encoding of a hashed message
  1888. *
  1889. * This is used both for signature generation and verification.
  1890. *
  1891. * Parameters:
  1892. * - md_alg: Identifies the hash algorithm used to generate the given hash;
  1893. * MBEDTLS_MD_NONE if raw data is signed.
  1894. * - hashlen: Length of hash. Must match md_alg if that's not NONE.
  1895. * - hash: Buffer containing the hashed message or the raw data.
  1896. * - dst_len: Length of the encoded message.
  1897. * - dst: Buffer to hold the encoded message.
  1898. *
  1899. * Assumptions:
  1900. * - hash has size hashlen.
  1901. * - dst points to a buffer of size at least dst_len.
  1902. *
  1903. */
  1904. static int rsa_rsassa_pkcs1_v15_encode(mbedtls_md_type_t md_alg,
  1905. unsigned int hashlen,
  1906. const unsigned char *hash,
  1907. size_t dst_len,
  1908. unsigned char *dst)
  1909. {
  1910. size_t oid_size = 0;
  1911. size_t nb_pad = dst_len;
  1912. unsigned char *p = dst;
  1913. const char *oid = NULL;
  1914. /* Are we signing hashed or raw data? */
  1915. if (md_alg != MBEDTLS_MD_NONE) {
  1916. unsigned char md_size = mbedtls_md_get_size_from_type(md_alg);
  1917. if (md_size == 0) {
  1918. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1919. }
  1920. if (mbedtls_oid_get_oid_by_md(md_alg, &oid, &oid_size) != 0) {
  1921. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1922. }
  1923. if (hashlen != md_size) {
  1924. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1925. }
  1926. /* Double-check that 8 + hashlen + oid_size can be used as a
  1927. * 1-byte ASN.1 length encoding and that there's no overflow. */
  1928. if (8 + hashlen + oid_size >= 0x80 ||
  1929. 10 + hashlen < hashlen ||
  1930. 10 + hashlen + oid_size < 10 + hashlen) {
  1931. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1932. }
  1933. /*
  1934. * Static bounds check:
  1935. * - Need 10 bytes for five tag-length pairs.
  1936. * (Insist on 1-byte length encodings to protect against variants of
  1937. * Bleichenbacher's forgery attack against lax PKCS#1v1.5 verification)
  1938. * - Need hashlen bytes for hash
  1939. * - Need oid_size bytes for hash alg OID.
  1940. */
  1941. if (nb_pad < 10 + hashlen + oid_size) {
  1942. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1943. }
  1944. nb_pad -= 10 + hashlen + oid_size;
  1945. } else {
  1946. if (nb_pad < hashlen) {
  1947. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1948. }
  1949. nb_pad -= hashlen;
  1950. }
  1951. /* Need space for signature header and padding delimiter (3 bytes),
  1952. * and 8 bytes for the minimal padding */
  1953. if (nb_pad < 3 + 8) {
  1954. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  1955. }
  1956. nb_pad -= 3;
  1957. /* Now nb_pad is the amount of memory to be filled
  1958. * with padding, and at least 8 bytes long. */
  1959. /* Write signature header and padding */
  1960. *p++ = 0;
  1961. *p++ = MBEDTLS_RSA_SIGN;
  1962. memset(p, 0xFF, nb_pad);
  1963. p += nb_pad;
  1964. *p++ = 0;
  1965. /* Are we signing raw data? */
  1966. if (md_alg == MBEDTLS_MD_NONE) {
  1967. memcpy(p, hash, hashlen);
  1968. return 0;
  1969. }
  1970. /* Signing hashed data, add corresponding ASN.1 structure
  1971. *
  1972. * DigestInfo ::= SEQUENCE {
  1973. * digestAlgorithm DigestAlgorithmIdentifier,
  1974. * digest Digest }
  1975. * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
  1976. * Digest ::= OCTET STRING
  1977. *
  1978. * Schematic:
  1979. * TAG-SEQ + LEN [ TAG-SEQ + LEN [ TAG-OID + LEN [ OID ]
  1980. * TAG-NULL + LEN [ NULL ] ]
  1981. * TAG-OCTET + LEN [ HASH ] ]
  1982. */
  1983. *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
  1984. *p++ = (unsigned char) (0x08 + oid_size + hashlen);
  1985. *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
  1986. *p++ = (unsigned char) (0x04 + oid_size);
  1987. *p++ = MBEDTLS_ASN1_OID;
  1988. *p++ = (unsigned char) oid_size;
  1989. memcpy(p, oid, oid_size);
  1990. p += oid_size;
  1991. *p++ = MBEDTLS_ASN1_NULL;
  1992. *p++ = 0x00;
  1993. *p++ = MBEDTLS_ASN1_OCTET_STRING;
  1994. *p++ = (unsigned char) hashlen;
  1995. memcpy(p, hash, hashlen);
  1996. p += hashlen;
  1997. /* Just a sanity-check, should be automatic
  1998. * after the initial bounds check. */
  1999. if (p != dst + dst_len) {
  2000. mbedtls_platform_zeroize(dst, dst_len);
  2001. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2002. }
  2003. return 0;
  2004. }
  2005. /*
  2006. * Do an RSA operation to sign the message digest
  2007. */
  2008. int mbedtls_rsa_rsassa_pkcs1_v15_sign(mbedtls_rsa_context *ctx,
  2009. int (*f_rng)(void *, unsigned char *, size_t),
  2010. void *p_rng,
  2011. mbedtls_md_type_t md_alg,
  2012. unsigned int hashlen,
  2013. const unsigned char *hash,
  2014. unsigned char *sig)
  2015. {
  2016. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2017. unsigned char *sig_try = NULL, *verif = NULL;
  2018. if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
  2019. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2020. }
  2021. if (ctx->padding != MBEDTLS_RSA_PKCS_V15) {
  2022. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2023. }
  2024. /*
  2025. * Prepare PKCS1-v1.5 encoding (padding and hash identifier)
  2026. */
  2027. if ((ret = rsa_rsassa_pkcs1_v15_encode(md_alg, hashlen, hash,
  2028. ctx->len, sig)) != 0) {
  2029. return ret;
  2030. }
  2031. /* Private key operation
  2032. *
  2033. * In order to prevent Lenstra's attack, make the signature in a
  2034. * temporary buffer and check it before returning it.
  2035. */
  2036. sig_try = mbedtls_calloc(1, ctx->len);
  2037. if (sig_try == NULL) {
  2038. return MBEDTLS_ERR_MPI_ALLOC_FAILED;
  2039. }
  2040. verif = mbedtls_calloc(1, ctx->len);
  2041. if (verif == NULL) {
  2042. mbedtls_free(sig_try);
  2043. return MBEDTLS_ERR_MPI_ALLOC_FAILED;
  2044. }
  2045. MBEDTLS_MPI_CHK(mbedtls_rsa_private(ctx, f_rng, p_rng, sig, sig_try));
  2046. MBEDTLS_MPI_CHK(mbedtls_rsa_public(ctx, sig_try, verif));
  2047. if (mbedtls_ct_memcmp(verif, sig, ctx->len) != 0) {
  2048. ret = MBEDTLS_ERR_RSA_PRIVATE_FAILED;
  2049. goto cleanup;
  2050. }
  2051. memcpy(sig, sig_try, ctx->len);
  2052. cleanup:
  2053. mbedtls_zeroize_and_free(sig_try, ctx->len);
  2054. mbedtls_zeroize_and_free(verif, ctx->len);
  2055. if (ret != 0) {
  2056. memset(sig, '!', ctx->len);
  2057. }
  2058. return ret;
  2059. }
  2060. #endif /* MBEDTLS_PKCS1_V15 */
  2061. /*
  2062. * Do an RSA operation to sign the message digest
  2063. */
  2064. int mbedtls_rsa_pkcs1_sign(mbedtls_rsa_context *ctx,
  2065. int (*f_rng)(void *, unsigned char *, size_t),
  2066. void *p_rng,
  2067. mbedtls_md_type_t md_alg,
  2068. unsigned int hashlen,
  2069. const unsigned char *hash,
  2070. unsigned char *sig)
  2071. {
  2072. if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
  2073. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2074. }
  2075. switch (ctx->padding) {
  2076. #if defined(MBEDTLS_PKCS1_V15)
  2077. case MBEDTLS_RSA_PKCS_V15:
  2078. return mbedtls_rsa_rsassa_pkcs1_v15_sign(ctx, f_rng, p_rng,
  2079. md_alg, hashlen, hash, sig);
  2080. #endif
  2081. #if defined(MBEDTLS_PKCS1_V21)
  2082. case MBEDTLS_RSA_PKCS_V21:
  2083. return mbedtls_rsa_rsassa_pss_sign(ctx, f_rng, p_rng, md_alg,
  2084. hashlen, hash, sig);
  2085. #endif
  2086. default:
  2087. return MBEDTLS_ERR_RSA_INVALID_PADDING;
  2088. }
  2089. }
  2090. #if defined(MBEDTLS_PKCS1_V21)
  2091. /*
  2092. * Implementation of the PKCS#1 v2.1 RSASSA-PSS-VERIFY function
  2093. */
  2094. int mbedtls_rsa_rsassa_pss_verify_ext(mbedtls_rsa_context *ctx,
  2095. mbedtls_md_type_t md_alg,
  2096. unsigned int hashlen,
  2097. const unsigned char *hash,
  2098. mbedtls_md_type_t mgf1_hash_id,
  2099. int expected_salt_len,
  2100. const unsigned char *sig)
  2101. {
  2102. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2103. size_t siglen;
  2104. unsigned char *p;
  2105. unsigned char *hash_start;
  2106. unsigned char result[MBEDTLS_MD_MAX_SIZE];
  2107. unsigned int hlen;
  2108. size_t observed_salt_len, msb;
  2109. unsigned char buf[MBEDTLS_MPI_MAX_SIZE] = { 0 };
  2110. if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
  2111. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2112. }
  2113. siglen = ctx->len;
  2114. if (siglen < 16 || siglen > sizeof(buf)) {
  2115. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2116. }
  2117. ret = mbedtls_rsa_public(ctx, sig, buf);
  2118. if (ret != 0) {
  2119. return ret;
  2120. }
  2121. p = buf;
  2122. if (buf[siglen - 1] != 0xBC) {
  2123. return MBEDTLS_ERR_RSA_INVALID_PADDING;
  2124. }
  2125. if (md_alg != MBEDTLS_MD_NONE) {
  2126. /* Gather length of hash to sign */
  2127. size_t exp_hashlen = mbedtls_md_get_size_from_type(md_alg);
  2128. if (exp_hashlen == 0) {
  2129. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2130. }
  2131. if (hashlen != exp_hashlen) {
  2132. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2133. }
  2134. }
  2135. hlen = mbedtls_md_get_size_from_type(mgf1_hash_id);
  2136. if (hlen == 0) {
  2137. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2138. }
  2139. /*
  2140. * Note: EMSA-PSS verification is over the length of N - 1 bits
  2141. */
  2142. msb = mbedtls_mpi_bitlen(&ctx->N) - 1;
  2143. if (buf[0] >> (8 - siglen * 8 + msb)) {
  2144. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2145. }
  2146. /* Compensate for boundary condition when applying mask */
  2147. if (msb % 8 == 0) {
  2148. p++;
  2149. siglen -= 1;
  2150. }
  2151. if (siglen < hlen + 2) {
  2152. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2153. }
  2154. hash_start = p + siglen - hlen - 1;
  2155. ret = mgf_mask(p, siglen - hlen - 1, hash_start, hlen, mgf1_hash_id);
  2156. if (ret != 0) {
  2157. return ret;
  2158. }
  2159. buf[0] &= 0xFF >> (siglen * 8 - msb);
  2160. while (p < hash_start - 1 && *p == 0) {
  2161. p++;
  2162. }
  2163. if (*p++ != 0x01) {
  2164. return MBEDTLS_ERR_RSA_INVALID_PADDING;
  2165. }
  2166. observed_salt_len = (size_t) (hash_start - p);
  2167. if (expected_salt_len != MBEDTLS_RSA_SALT_LEN_ANY &&
  2168. observed_salt_len != (size_t) expected_salt_len) {
  2169. return MBEDTLS_ERR_RSA_INVALID_PADDING;
  2170. }
  2171. /*
  2172. * Generate H = Hash( M' )
  2173. */
  2174. ret = hash_mprime(hash, hashlen, p, observed_salt_len,
  2175. result, mgf1_hash_id);
  2176. if (ret != 0) {
  2177. return ret;
  2178. }
  2179. if (memcmp(hash_start, result, hlen) != 0) {
  2180. return MBEDTLS_ERR_RSA_VERIFY_FAILED;
  2181. }
  2182. return 0;
  2183. }
  2184. /*
  2185. * Simplified PKCS#1 v2.1 RSASSA-PSS-VERIFY function
  2186. */
  2187. int mbedtls_rsa_rsassa_pss_verify(mbedtls_rsa_context *ctx,
  2188. mbedtls_md_type_t md_alg,
  2189. unsigned int hashlen,
  2190. const unsigned char *hash,
  2191. const unsigned char *sig)
  2192. {
  2193. mbedtls_md_type_t mgf1_hash_id;
  2194. if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
  2195. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2196. }
  2197. mgf1_hash_id = (ctx->hash_id != MBEDTLS_MD_NONE)
  2198. ? (mbedtls_md_type_t) ctx->hash_id
  2199. : md_alg;
  2200. return mbedtls_rsa_rsassa_pss_verify_ext(ctx,
  2201. md_alg, hashlen, hash,
  2202. mgf1_hash_id,
  2203. MBEDTLS_RSA_SALT_LEN_ANY,
  2204. sig);
  2205. }
  2206. #endif /* MBEDTLS_PKCS1_V21 */
  2207. #if defined(MBEDTLS_PKCS1_V15)
  2208. /*
  2209. * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-v1_5-VERIFY function
  2210. */
  2211. int mbedtls_rsa_rsassa_pkcs1_v15_verify(mbedtls_rsa_context *ctx,
  2212. mbedtls_md_type_t md_alg,
  2213. unsigned int hashlen,
  2214. const unsigned char *hash,
  2215. const unsigned char *sig)
  2216. {
  2217. int ret = 0;
  2218. size_t sig_len;
  2219. unsigned char *encoded = NULL, *encoded_expected = NULL;
  2220. if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
  2221. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2222. }
  2223. sig_len = ctx->len;
  2224. /*
  2225. * Prepare expected PKCS1 v1.5 encoding of hash.
  2226. */
  2227. if ((encoded = mbedtls_calloc(1, sig_len)) == NULL ||
  2228. (encoded_expected = mbedtls_calloc(1, sig_len)) == NULL) {
  2229. ret = MBEDTLS_ERR_MPI_ALLOC_FAILED;
  2230. goto cleanup;
  2231. }
  2232. if ((ret = rsa_rsassa_pkcs1_v15_encode(md_alg, hashlen, hash, sig_len,
  2233. encoded_expected)) != 0) {
  2234. goto cleanup;
  2235. }
  2236. /*
  2237. * Apply RSA primitive to get what should be PKCS1 encoded hash.
  2238. */
  2239. ret = mbedtls_rsa_public(ctx, sig, encoded);
  2240. if (ret != 0) {
  2241. goto cleanup;
  2242. }
  2243. /*
  2244. * Compare
  2245. */
  2246. if ((ret = mbedtls_ct_memcmp(encoded, encoded_expected,
  2247. sig_len)) != 0) {
  2248. ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
  2249. goto cleanup;
  2250. }
  2251. cleanup:
  2252. if (encoded != NULL) {
  2253. mbedtls_zeroize_and_free(encoded, sig_len);
  2254. }
  2255. if (encoded_expected != NULL) {
  2256. mbedtls_zeroize_and_free(encoded_expected, sig_len);
  2257. }
  2258. return ret;
  2259. }
  2260. #endif /* MBEDTLS_PKCS1_V15 */
  2261. /*
  2262. * Do an RSA operation and check the message digest
  2263. */
  2264. int mbedtls_rsa_pkcs1_verify(mbedtls_rsa_context *ctx,
  2265. mbedtls_md_type_t md_alg,
  2266. unsigned int hashlen,
  2267. const unsigned char *hash,
  2268. const unsigned char *sig)
  2269. {
  2270. if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
  2271. return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
  2272. }
  2273. switch (ctx->padding) {
  2274. #if defined(MBEDTLS_PKCS1_V15)
  2275. case MBEDTLS_RSA_PKCS_V15:
  2276. return mbedtls_rsa_rsassa_pkcs1_v15_verify(ctx, md_alg,
  2277. hashlen, hash, sig);
  2278. #endif
  2279. #if defined(MBEDTLS_PKCS1_V21)
  2280. case MBEDTLS_RSA_PKCS_V21:
  2281. return mbedtls_rsa_rsassa_pss_verify(ctx, md_alg,
  2282. hashlen, hash, sig);
  2283. #endif
  2284. default:
  2285. return MBEDTLS_ERR_RSA_INVALID_PADDING;
  2286. }
  2287. }
  2288. /*
  2289. * Copy the components of an RSA key
  2290. */
  2291. int mbedtls_rsa_copy(mbedtls_rsa_context *dst, const mbedtls_rsa_context *src)
  2292. {
  2293. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2294. dst->len = src->len;
  2295. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->N, &src->N));
  2296. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->E, &src->E));
  2297. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->D, &src->D));
  2298. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->P, &src->P));
  2299. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Q, &src->Q));
  2300. #if !defined(MBEDTLS_RSA_NO_CRT)
  2301. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->DP, &src->DP));
  2302. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->DQ, &src->DQ));
  2303. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->QP, &src->QP));
  2304. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RP, &src->RP));
  2305. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RQ, &src->RQ));
  2306. #endif
  2307. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RN, &src->RN));
  2308. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Vi, &src->Vi));
  2309. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Vf, &src->Vf));
  2310. dst->padding = src->padding;
  2311. dst->hash_id = src->hash_id;
  2312. cleanup:
  2313. if (ret != 0) {
  2314. mbedtls_rsa_free(dst);
  2315. }
  2316. return ret;
  2317. }
  2318. /*
  2319. * Free the components of an RSA key
  2320. */
  2321. void mbedtls_rsa_free(mbedtls_rsa_context *ctx)
  2322. {
  2323. if (ctx == NULL) {
  2324. return;
  2325. }
  2326. mbedtls_mpi_free(&ctx->Vi);
  2327. mbedtls_mpi_free(&ctx->Vf);
  2328. mbedtls_mpi_free(&ctx->RN);
  2329. mbedtls_mpi_free(&ctx->D);
  2330. mbedtls_mpi_free(&ctx->Q);
  2331. mbedtls_mpi_free(&ctx->P);
  2332. mbedtls_mpi_free(&ctx->E);
  2333. mbedtls_mpi_free(&ctx->N);
  2334. #if !defined(MBEDTLS_RSA_NO_CRT)
  2335. mbedtls_mpi_free(&ctx->RQ);
  2336. mbedtls_mpi_free(&ctx->RP);
  2337. mbedtls_mpi_free(&ctx->QP);
  2338. mbedtls_mpi_free(&ctx->DQ);
  2339. mbedtls_mpi_free(&ctx->DP);
  2340. #endif /* MBEDTLS_RSA_NO_CRT */
  2341. #if defined(MBEDTLS_THREADING_C)
  2342. /* Free the mutex, but only if it hasn't been freed already. */
  2343. if (ctx->ver != 0) {
  2344. mbedtls_mutex_free(&ctx->mutex);
  2345. ctx->ver = 0;
  2346. }
  2347. #endif
  2348. }
  2349. #endif /* !MBEDTLS_RSA_ALT */
  2350. #if defined(MBEDTLS_SELF_TEST)
  2351. /*
  2352. * Example RSA-1024 keypair, for test purposes
  2353. */
  2354. #define KEY_LEN 128
  2355. #define RSA_N "9292758453063D803DD603D5E777D788" \
  2356. "8ED1D5BF35786190FA2F23EBC0848AEA" \
  2357. "DDA92CA6C3D80B32C4D109BE0F36D6AE" \
  2358. "7130B9CED7ACDF54CFC7555AC14EEBAB" \
  2359. "93A89813FBF3C4F8066D2D800F7C38A8" \
  2360. "1AE31942917403FF4946B0A83D3D3E05" \
  2361. "EE57C6F5F5606FB5D4BC6CD34EE0801A" \
  2362. "5E94BB77B07507233A0BC7BAC8F90F79"
  2363. #define RSA_E "10001"
  2364. #define RSA_D "24BF6185468786FDD303083D25E64EFC" \
  2365. "66CA472BC44D253102F8B4A9D3BFA750" \
  2366. "91386C0077937FE33FA3252D28855837" \
  2367. "AE1B484A8A9A45F7EE8C0C634F99E8CD" \
  2368. "DF79C5CE07EE72C7F123142198164234" \
  2369. "CABB724CF78B8173B9F880FC86322407" \
  2370. "AF1FEDFDDE2BEB674CA15F3E81A1521E" \
  2371. "071513A1E85B5DFA031F21ECAE91A34D"
  2372. #define RSA_P "C36D0EB7FCD285223CFB5AABA5BDA3D8" \
  2373. "2C01CAD19EA484A87EA4377637E75500" \
  2374. "FCB2005C5C7DD6EC4AC023CDA285D796" \
  2375. "C3D9E75E1EFC42488BB4F1D13AC30A57"
  2376. #define RSA_Q "C000DF51A7C77AE8D7C7370C1FF55B69" \
  2377. "E211C2B9E5DB1ED0BF61D0D9899620F4" \
  2378. "910E4168387E3C30AA1E00C339A79508" \
  2379. "8452DD96A9A5EA5D9DCA68DA636032AF"
  2380. #define PT_LEN 24
  2381. #define RSA_PT "\xAA\xBB\xCC\x03\x02\x01\x00\xFF\xFF\xFF\xFF\xFF" \
  2382. "\x11\x22\x33\x0A\x0B\x0C\xCC\xDD\xDD\xDD\xDD\xDD"
  2383. #if defined(MBEDTLS_PKCS1_V15)
  2384. static int myrand(void *rng_state, unsigned char *output, size_t len)
  2385. {
  2386. #if !defined(__OpenBSD__) && !defined(__NetBSD__)
  2387. size_t i;
  2388. if (rng_state != NULL) {
  2389. rng_state = NULL;
  2390. }
  2391. for (i = 0; i < len; ++i) {
  2392. output[i] = rand();
  2393. }
  2394. #else
  2395. if (rng_state != NULL) {
  2396. rng_state = NULL;
  2397. }
  2398. arc4random_buf(output, len);
  2399. #endif /* !OpenBSD && !NetBSD */
  2400. return 0;
  2401. }
  2402. #endif /* MBEDTLS_PKCS1_V15 */
  2403. /*
  2404. * Checkup routine
  2405. */
  2406. int mbedtls_rsa_self_test(int verbose)
  2407. {
  2408. int ret = 0;
  2409. #if defined(MBEDTLS_PKCS1_V15)
  2410. size_t len;
  2411. mbedtls_rsa_context rsa;
  2412. unsigned char rsa_plaintext[PT_LEN];
  2413. unsigned char rsa_decrypted[PT_LEN];
  2414. unsigned char rsa_ciphertext[KEY_LEN];
  2415. #if defined(MBEDTLS_MD_CAN_SHA1)
  2416. unsigned char sha1sum[20];
  2417. #endif
  2418. mbedtls_mpi K;
  2419. mbedtls_mpi_init(&K);
  2420. mbedtls_rsa_init(&rsa);
  2421. MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_N));
  2422. MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, &K, NULL, NULL, NULL, NULL));
  2423. MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_P));
  2424. MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, &K, NULL, NULL, NULL));
  2425. MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_Q));
  2426. MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, &K, NULL, NULL));
  2427. MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_D));
  2428. MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, NULL, &K, NULL));
  2429. MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_E));
  2430. MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, NULL, NULL, &K));
  2431. MBEDTLS_MPI_CHK(mbedtls_rsa_complete(&rsa));
  2432. if (verbose != 0) {
  2433. mbedtls_printf(" RSA key validation: ");
  2434. }
  2435. if (mbedtls_rsa_check_pubkey(&rsa) != 0 ||
  2436. mbedtls_rsa_check_privkey(&rsa) != 0) {
  2437. if (verbose != 0) {
  2438. mbedtls_printf("failed\n");
  2439. }
  2440. ret = 1;
  2441. goto cleanup;
  2442. }
  2443. if (verbose != 0) {
  2444. mbedtls_printf("passed\n PKCS#1 encryption : ");
  2445. }
  2446. memcpy(rsa_plaintext, RSA_PT, PT_LEN);
  2447. if (mbedtls_rsa_pkcs1_encrypt(&rsa, myrand, NULL,
  2448. PT_LEN, rsa_plaintext,
  2449. rsa_ciphertext) != 0) {
  2450. if (verbose != 0) {
  2451. mbedtls_printf("failed\n");
  2452. }
  2453. ret = 1;
  2454. goto cleanup;
  2455. }
  2456. if (verbose != 0) {
  2457. mbedtls_printf("passed\n PKCS#1 decryption : ");
  2458. }
  2459. if (mbedtls_rsa_pkcs1_decrypt(&rsa, myrand, NULL,
  2460. &len, rsa_ciphertext, rsa_decrypted,
  2461. sizeof(rsa_decrypted)) != 0) {
  2462. if (verbose != 0) {
  2463. mbedtls_printf("failed\n");
  2464. }
  2465. ret = 1;
  2466. goto cleanup;
  2467. }
  2468. if (memcmp(rsa_decrypted, rsa_plaintext, len) != 0) {
  2469. if (verbose != 0) {
  2470. mbedtls_printf("failed\n");
  2471. }
  2472. ret = 1;
  2473. goto cleanup;
  2474. }
  2475. if (verbose != 0) {
  2476. mbedtls_printf("passed\n");
  2477. }
  2478. #if defined(MBEDTLS_MD_CAN_SHA1)
  2479. if (verbose != 0) {
  2480. mbedtls_printf(" PKCS#1 data sign : ");
  2481. }
  2482. if (mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_SHA1),
  2483. rsa_plaintext, PT_LEN, sha1sum) != 0) {
  2484. if (verbose != 0) {
  2485. mbedtls_printf("failed\n");
  2486. }
  2487. return 1;
  2488. }
  2489. if (mbedtls_rsa_pkcs1_sign(&rsa, myrand, NULL,
  2490. MBEDTLS_MD_SHA1, 20,
  2491. sha1sum, rsa_ciphertext) != 0) {
  2492. if (verbose != 0) {
  2493. mbedtls_printf("failed\n");
  2494. }
  2495. ret = 1;
  2496. goto cleanup;
  2497. }
  2498. if (verbose != 0) {
  2499. mbedtls_printf("passed\n PKCS#1 sig. verify: ");
  2500. }
  2501. if (mbedtls_rsa_pkcs1_verify(&rsa, MBEDTLS_MD_SHA1, 20,
  2502. sha1sum, rsa_ciphertext) != 0) {
  2503. if (verbose != 0) {
  2504. mbedtls_printf("failed\n");
  2505. }
  2506. ret = 1;
  2507. goto cleanup;
  2508. }
  2509. if (verbose != 0) {
  2510. mbedtls_printf("passed\n");
  2511. }
  2512. #endif /* MBEDTLS_MD_CAN_SHA1 */
  2513. if (verbose != 0) {
  2514. mbedtls_printf("\n");
  2515. }
  2516. cleanup:
  2517. mbedtls_mpi_free(&K);
  2518. mbedtls_rsa_free(&rsa);
  2519. #else /* MBEDTLS_PKCS1_V15 */
  2520. ((void) verbose);
  2521. #endif /* MBEDTLS_PKCS1_V15 */
  2522. return ret;
  2523. }
  2524. #endif /* MBEDTLS_SELF_TEST */
  2525. #endif /* MBEDTLS_RSA_C */