rsa.c 78 KB

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