ecp.c 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618
  1. /*
  2. * Elliptic curves over GF(p): generic functions
  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. * References:
  21. *
  22. * SEC1 http://www.secg.org/index.php?action=secg,docs_secg
  23. * GECC = Guide to Elliptic Curve Cryptography - Hankerson, Menezes, Vanstone
  24. * FIPS 186-3 http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf
  25. * RFC 4492 for the related TLS structures and constants
  26. * RFC 7748 for the Curve448 and Curve25519 curve definitions
  27. *
  28. * [Curve25519] http://cr.yp.to/ecdh/curve25519-20060209.pdf
  29. *
  30. * [2] CORON, Jean-S'ebastien. Resistance against differential power analysis
  31. * for elliptic curve cryptosystems. In : Cryptographic Hardware and
  32. * Embedded Systems. Springer Berlin Heidelberg, 1999. p. 292-302.
  33. * <http://link.springer.com/chapter/10.1007/3-540-48059-5_25>
  34. *
  35. * [3] HEDABOU, Mustapha, PINEL, Pierre, et B'EN'ETEAU, Lucien. A comb method to
  36. * render ECC resistant against Side Channel Attacks. IACR Cryptology
  37. * ePrint Archive, 2004, vol. 2004, p. 342.
  38. * <http://eprint.iacr.org/2004/342.pdf>
  39. */
  40. #include "common.h"
  41. /**
  42. * \brief Function level alternative implementation.
  43. *
  44. * The MBEDTLS_ECP_INTERNAL_ALT macro enables alternative implementations to
  45. * replace certain functions in this module. The alternative implementations are
  46. * typically hardware accelerators and need to activate the hardware before the
  47. * computation starts and deactivate it after it finishes. The
  48. * mbedtls_internal_ecp_init() and mbedtls_internal_ecp_free() functions serve
  49. * this purpose.
  50. *
  51. * To preserve the correct functionality the following conditions must hold:
  52. *
  53. * - The alternative implementation must be activated by
  54. * mbedtls_internal_ecp_init() before any of the replaceable functions is
  55. * called.
  56. * - mbedtls_internal_ecp_free() must \b only be called when the alternative
  57. * implementation is activated.
  58. * - mbedtls_internal_ecp_init() must \b not be called when the alternative
  59. * implementation is activated.
  60. * - Public functions must not return while the alternative implementation is
  61. * activated.
  62. * - Replaceable functions are guarded by \c MBEDTLS_ECP_XXX_ALT macros and
  63. * before calling them an \code if( mbedtls_internal_ecp_grp_capable( grp ) )
  64. * \endcode ensures that the alternative implementation supports the current
  65. * group.
  66. */
  67. #if defined(MBEDTLS_ECP_INTERNAL_ALT)
  68. #endif
  69. #if defined(MBEDTLS_ECP_C)
  70. #include "mbedtls/ecp.h"
  71. #include "mbedtls/threading.h"
  72. #include "mbedtls/platform_util.h"
  73. #include "mbedtls/error.h"
  74. #include "bn_mul.h"
  75. #include "ecp_invasive.h"
  76. #include <string.h>
  77. #if !defined(MBEDTLS_ECP_ALT)
  78. #include "mbedtls/platform.h"
  79. #include "ecp_internal_alt.h"
  80. #if defined(MBEDTLS_SELF_TEST)
  81. /*
  82. * Counts of point addition and doubling, and field multiplications.
  83. * Used to test resistance of point multiplication to simple timing attacks.
  84. */
  85. static unsigned long add_count, dbl_count, mul_count;
  86. #endif
  87. #if defined(MBEDTLS_ECP_RESTARTABLE)
  88. /*
  89. * Maximum number of "basic operations" to be done in a row.
  90. *
  91. * Default value 0 means that ECC operations will not yield.
  92. * Note that regardless of the value of ecp_max_ops, always at
  93. * least one step is performed before yielding.
  94. *
  95. * Setting ecp_max_ops=1 can be suitable for testing purposes
  96. * as it will interrupt computation at all possible points.
  97. */
  98. static unsigned ecp_max_ops = 0;
  99. /*
  100. * Set ecp_max_ops
  101. */
  102. void mbedtls_ecp_set_max_ops(unsigned max_ops)
  103. {
  104. ecp_max_ops = max_ops;
  105. }
  106. /*
  107. * Check if restart is enabled
  108. */
  109. int mbedtls_ecp_restart_is_enabled(void)
  110. {
  111. return ecp_max_ops != 0;
  112. }
  113. /*
  114. * Restart sub-context for ecp_mul_comb()
  115. */
  116. struct mbedtls_ecp_restart_mul {
  117. mbedtls_ecp_point R; /* current intermediate result */
  118. size_t i; /* current index in various loops, 0 outside */
  119. mbedtls_ecp_point *T; /* table for precomputed points */
  120. unsigned char T_size; /* number of points in table T */
  121. enum { /* what were we doing last time we returned? */
  122. ecp_rsm_init = 0, /* nothing so far, dummy initial state */
  123. ecp_rsm_pre_dbl, /* precompute 2^n multiples */
  124. ecp_rsm_pre_norm_dbl, /* normalize precomputed 2^n multiples */
  125. ecp_rsm_pre_add, /* precompute remaining points by adding */
  126. ecp_rsm_pre_norm_add, /* normalize all precomputed points */
  127. ecp_rsm_comb_core, /* ecp_mul_comb_core() */
  128. ecp_rsm_final_norm, /* do the final normalization */
  129. } state;
  130. };
  131. /*
  132. * Init restart_mul sub-context
  133. */
  134. static void ecp_restart_rsm_init(mbedtls_ecp_restart_mul_ctx *ctx)
  135. {
  136. mbedtls_ecp_point_init(&ctx->R);
  137. ctx->i = 0;
  138. ctx->T = NULL;
  139. ctx->T_size = 0;
  140. ctx->state = ecp_rsm_init;
  141. }
  142. /*
  143. * Free the components of a restart_mul sub-context
  144. */
  145. static void ecp_restart_rsm_free(mbedtls_ecp_restart_mul_ctx *ctx)
  146. {
  147. unsigned char i;
  148. if (ctx == NULL) {
  149. return;
  150. }
  151. mbedtls_ecp_point_free(&ctx->R);
  152. if (ctx->T != NULL) {
  153. for (i = 0; i < ctx->T_size; i++) {
  154. mbedtls_ecp_point_free(ctx->T + i);
  155. }
  156. mbedtls_free(ctx->T);
  157. }
  158. ecp_restart_rsm_init(ctx);
  159. }
  160. /*
  161. * Restart context for ecp_muladd()
  162. */
  163. struct mbedtls_ecp_restart_muladd {
  164. mbedtls_ecp_point mP; /* mP value */
  165. mbedtls_ecp_point R; /* R intermediate result */
  166. enum { /* what should we do next? */
  167. ecp_rsma_mul1 = 0, /* first multiplication */
  168. ecp_rsma_mul2, /* second multiplication */
  169. ecp_rsma_add, /* addition */
  170. ecp_rsma_norm, /* normalization */
  171. } state;
  172. };
  173. /*
  174. * Init restart_muladd sub-context
  175. */
  176. static void ecp_restart_ma_init(mbedtls_ecp_restart_muladd_ctx *ctx)
  177. {
  178. mbedtls_ecp_point_init(&ctx->mP);
  179. mbedtls_ecp_point_init(&ctx->R);
  180. ctx->state = ecp_rsma_mul1;
  181. }
  182. /*
  183. * Free the components of a restart_muladd sub-context
  184. */
  185. static void ecp_restart_ma_free(mbedtls_ecp_restart_muladd_ctx *ctx)
  186. {
  187. if (ctx == NULL) {
  188. return;
  189. }
  190. mbedtls_ecp_point_free(&ctx->mP);
  191. mbedtls_ecp_point_free(&ctx->R);
  192. ecp_restart_ma_init(ctx);
  193. }
  194. /*
  195. * Initialize a restart context
  196. */
  197. void mbedtls_ecp_restart_init(mbedtls_ecp_restart_ctx *ctx)
  198. {
  199. ctx->ops_done = 0;
  200. ctx->depth = 0;
  201. ctx->rsm = NULL;
  202. ctx->ma = NULL;
  203. }
  204. /*
  205. * Free the components of a restart context
  206. */
  207. void mbedtls_ecp_restart_free(mbedtls_ecp_restart_ctx *ctx)
  208. {
  209. if (ctx == NULL) {
  210. return;
  211. }
  212. ecp_restart_rsm_free(ctx->rsm);
  213. mbedtls_free(ctx->rsm);
  214. ecp_restart_ma_free(ctx->ma);
  215. mbedtls_free(ctx->ma);
  216. mbedtls_ecp_restart_init(ctx);
  217. }
  218. /*
  219. * Check if we can do the next step
  220. */
  221. int mbedtls_ecp_check_budget(const mbedtls_ecp_group *grp,
  222. mbedtls_ecp_restart_ctx *rs_ctx,
  223. unsigned ops)
  224. {
  225. if (rs_ctx != NULL && ecp_max_ops != 0) {
  226. /* scale depending on curve size: the chosen reference is 256-bit,
  227. * and multiplication is quadratic. Round to the closest integer. */
  228. if (grp->pbits >= 512) {
  229. ops *= 4;
  230. } else if (grp->pbits >= 384) {
  231. ops *= 2;
  232. }
  233. /* Avoid infinite loops: always allow first step.
  234. * Because of that, however, it's not generally true
  235. * that ops_done <= ecp_max_ops, so the check
  236. * ops_done > ecp_max_ops below is mandatory. */
  237. if ((rs_ctx->ops_done != 0) &&
  238. (rs_ctx->ops_done > ecp_max_ops ||
  239. ops > ecp_max_ops - rs_ctx->ops_done)) {
  240. return MBEDTLS_ERR_ECP_IN_PROGRESS;
  241. }
  242. /* update running count */
  243. rs_ctx->ops_done += ops;
  244. }
  245. return 0;
  246. }
  247. /* Call this when entering a function that needs its own sub-context */
  248. #define ECP_RS_ENTER(SUB) do { \
  249. /* reset ops count for this call if top-level */ \
  250. if (rs_ctx != NULL && rs_ctx->depth++ == 0) \
  251. rs_ctx->ops_done = 0; \
  252. \
  253. /* set up our own sub-context if needed */ \
  254. if (mbedtls_ecp_restart_is_enabled() && \
  255. rs_ctx != NULL && rs_ctx->SUB == NULL) \
  256. { \
  257. rs_ctx->SUB = mbedtls_calloc(1, sizeof(*rs_ctx->SUB)); \
  258. if (rs_ctx->SUB == NULL) \
  259. return MBEDTLS_ERR_ECP_ALLOC_FAILED; \
  260. \
  261. ecp_restart_## SUB ##_init(rs_ctx->SUB); \
  262. } \
  263. } while (0)
  264. /* Call this when leaving a function that needs its own sub-context */
  265. #define ECP_RS_LEAVE(SUB) do { \
  266. /* clear our sub-context when not in progress (done or error) */ \
  267. if (rs_ctx != NULL && rs_ctx->SUB != NULL && \
  268. ret != MBEDTLS_ERR_ECP_IN_PROGRESS) \
  269. { \
  270. ecp_restart_## SUB ##_free(rs_ctx->SUB); \
  271. mbedtls_free(rs_ctx->SUB); \
  272. rs_ctx->SUB = NULL; \
  273. } \
  274. \
  275. if (rs_ctx != NULL) \
  276. rs_ctx->depth--; \
  277. } while (0)
  278. #else /* MBEDTLS_ECP_RESTARTABLE */
  279. #define ECP_RS_ENTER(sub) (void) rs_ctx;
  280. #define ECP_RS_LEAVE(sub) (void) rs_ctx;
  281. #endif /* MBEDTLS_ECP_RESTARTABLE */
  282. static void mpi_init_many(mbedtls_mpi *arr, size_t size)
  283. {
  284. while (size--) {
  285. mbedtls_mpi_init(arr++);
  286. }
  287. }
  288. static void mpi_free_many(mbedtls_mpi *arr, size_t size)
  289. {
  290. while (size--) {
  291. mbedtls_mpi_free(arr++);
  292. }
  293. }
  294. /*
  295. * List of supported curves:
  296. * - internal ID
  297. * - TLS NamedCurve ID (RFC 4492 sec. 5.1.1, RFC 7071 sec. 2, RFC 8446 sec. 4.2.7)
  298. * - size in bits
  299. * - readable name
  300. *
  301. * Curves are listed in order: largest curves first, and for a given size,
  302. * fastest curves first.
  303. *
  304. * Reminder: update profiles in x509_crt.c and ssl_tls.c when adding a new curve!
  305. */
  306. static const mbedtls_ecp_curve_info ecp_supported_curves[] =
  307. {
  308. #if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)
  309. { MBEDTLS_ECP_DP_SECP521R1, 25, 521, "secp521r1" },
  310. #endif
  311. #if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED)
  312. { MBEDTLS_ECP_DP_BP512R1, 28, 512, "brainpoolP512r1" },
  313. #endif
  314. #if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
  315. { MBEDTLS_ECP_DP_SECP384R1, 24, 384, "secp384r1" },
  316. #endif
  317. #if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED)
  318. { MBEDTLS_ECP_DP_BP384R1, 27, 384, "brainpoolP384r1" },
  319. #endif
  320. #if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
  321. { MBEDTLS_ECP_DP_SECP256R1, 23, 256, "secp256r1" },
  322. #endif
  323. #if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)
  324. { MBEDTLS_ECP_DP_SECP256K1, 22, 256, "secp256k1" },
  325. #endif
  326. #if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED)
  327. { MBEDTLS_ECP_DP_BP256R1, 26, 256, "brainpoolP256r1" },
  328. #endif
  329. #if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED)
  330. { MBEDTLS_ECP_DP_SECP224R1, 21, 224, "secp224r1" },
  331. #endif
  332. #if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED)
  333. { MBEDTLS_ECP_DP_SECP224K1, 20, 224, "secp224k1" },
  334. #endif
  335. #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)
  336. { MBEDTLS_ECP_DP_SECP192R1, 19, 192, "secp192r1" },
  337. #endif
  338. #if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED)
  339. { MBEDTLS_ECP_DP_SECP192K1, 18, 192, "secp192k1" },
  340. #endif
  341. #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
  342. { MBEDTLS_ECP_DP_CURVE25519, 29, 256, "x25519" },
  343. #endif
  344. #if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)
  345. { MBEDTLS_ECP_DP_CURVE448, 30, 448, "x448" },
  346. #endif
  347. { MBEDTLS_ECP_DP_NONE, 0, 0, NULL },
  348. };
  349. #define ECP_NB_CURVES sizeof(ecp_supported_curves) / \
  350. sizeof(ecp_supported_curves[0])
  351. static mbedtls_ecp_group_id ecp_supported_grp_id[ECP_NB_CURVES];
  352. /*
  353. * List of supported curves and associated info
  354. */
  355. const mbedtls_ecp_curve_info *mbedtls_ecp_curve_list(void)
  356. {
  357. return ecp_supported_curves;
  358. }
  359. /*
  360. * List of supported curves, group ID only
  361. */
  362. const mbedtls_ecp_group_id *mbedtls_ecp_grp_id_list(void)
  363. {
  364. static int init_done = 0;
  365. if (!init_done) {
  366. size_t i = 0;
  367. const mbedtls_ecp_curve_info *curve_info;
  368. for (curve_info = mbedtls_ecp_curve_list();
  369. curve_info->grp_id != MBEDTLS_ECP_DP_NONE;
  370. curve_info++) {
  371. ecp_supported_grp_id[i++] = curve_info->grp_id;
  372. }
  373. ecp_supported_grp_id[i] = MBEDTLS_ECP_DP_NONE;
  374. init_done = 1;
  375. }
  376. return ecp_supported_grp_id;
  377. }
  378. /*
  379. * Get the curve info for the internal identifier
  380. */
  381. const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_grp_id(mbedtls_ecp_group_id grp_id)
  382. {
  383. const mbedtls_ecp_curve_info *curve_info;
  384. for (curve_info = mbedtls_ecp_curve_list();
  385. curve_info->grp_id != MBEDTLS_ECP_DP_NONE;
  386. curve_info++) {
  387. if (curve_info->grp_id == grp_id) {
  388. return curve_info;
  389. }
  390. }
  391. return NULL;
  392. }
  393. /*
  394. * Get the curve info from the TLS identifier
  395. */
  396. const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_tls_id(uint16_t tls_id)
  397. {
  398. const mbedtls_ecp_curve_info *curve_info;
  399. for (curve_info = mbedtls_ecp_curve_list();
  400. curve_info->grp_id != MBEDTLS_ECP_DP_NONE;
  401. curve_info++) {
  402. if (curve_info->tls_id == tls_id) {
  403. return curve_info;
  404. }
  405. }
  406. return NULL;
  407. }
  408. /*
  409. * Get the curve info from the name
  410. */
  411. const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_name(const char *name)
  412. {
  413. const mbedtls_ecp_curve_info *curve_info;
  414. if (name == NULL) {
  415. return NULL;
  416. }
  417. for (curve_info = mbedtls_ecp_curve_list();
  418. curve_info->grp_id != MBEDTLS_ECP_DP_NONE;
  419. curve_info++) {
  420. if (strcmp(curve_info->name, name) == 0) {
  421. return curve_info;
  422. }
  423. }
  424. return NULL;
  425. }
  426. /*
  427. * Get the type of a curve
  428. */
  429. mbedtls_ecp_curve_type mbedtls_ecp_get_type(const mbedtls_ecp_group *grp)
  430. {
  431. if (grp->G.X.p == NULL) {
  432. return MBEDTLS_ECP_TYPE_NONE;
  433. }
  434. if (grp->G.Y.p == NULL) {
  435. return MBEDTLS_ECP_TYPE_MONTGOMERY;
  436. } else {
  437. return MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS;
  438. }
  439. }
  440. /*
  441. * Initialize (the components of) a point
  442. */
  443. void mbedtls_ecp_point_init(mbedtls_ecp_point *pt)
  444. {
  445. mbedtls_mpi_init(&pt->X);
  446. mbedtls_mpi_init(&pt->Y);
  447. mbedtls_mpi_init(&pt->Z);
  448. }
  449. /*
  450. * Initialize (the components of) a group
  451. */
  452. void mbedtls_ecp_group_init(mbedtls_ecp_group *grp)
  453. {
  454. grp->id = MBEDTLS_ECP_DP_NONE;
  455. mbedtls_mpi_init(&grp->P);
  456. mbedtls_mpi_init(&grp->A);
  457. mbedtls_mpi_init(&grp->B);
  458. mbedtls_ecp_point_init(&grp->G);
  459. mbedtls_mpi_init(&grp->N);
  460. grp->pbits = 0;
  461. grp->nbits = 0;
  462. grp->h = 0;
  463. grp->modp = NULL;
  464. grp->t_pre = NULL;
  465. grp->t_post = NULL;
  466. grp->t_data = NULL;
  467. grp->T = NULL;
  468. grp->T_size = 0;
  469. }
  470. /*
  471. * Initialize (the components of) a key pair
  472. */
  473. void mbedtls_ecp_keypair_init(mbedtls_ecp_keypair *key)
  474. {
  475. mbedtls_ecp_group_init(&key->grp);
  476. mbedtls_mpi_init(&key->d);
  477. mbedtls_ecp_point_init(&key->Q);
  478. }
  479. /*
  480. * Unallocate (the components of) a point
  481. */
  482. void mbedtls_ecp_point_free(mbedtls_ecp_point *pt)
  483. {
  484. if (pt == NULL) {
  485. return;
  486. }
  487. mbedtls_mpi_free(&(pt->X));
  488. mbedtls_mpi_free(&(pt->Y));
  489. mbedtls_mpi_free(&(pt->Z));
  490. }
  491. /*
  492. * Check that the comb table (grp->T) is static initialized.
  493. */
  494. static int ecp_group_is_static_comb_table(const mbedtls_ecp_group *grp)
  495. {
  496. #if MBEDTLS_ECP_FIXED_POINT_OPTIM == 1
  497. return grp->T != NULL && grp->T_size == 0;
  498. #else
  499. (void) grp;
  500. return 0;
  501. #endif
  502. }
  503. /*
  504. * Unallocate (the components of) a group
  505. */
  506. void mbedtls_ecp_group_free(mbedtls_ecp_group *grp)
  507. {
  508. size_t i;
  509. if (grp == NULL) {
  510. return;
  511. }
  512. if (grp->h != 1) {
  513. mbedtls_mpi_free(&grp->A);
  514. mbedtls_mpi_free(&grp->B);
  515. mbedtls_ecp_point_free(&grp->G);
  516. }
  517. if (!ecp_group_is_static_comb_table(grp) && grp->T != NULL) {
  518. for (i = 0; i < grp->T_size; i++) {
  519. mbedtls_ecp_point_free(&grp->T[i]);
  520. }
  521. mbedtls_free(grp->T);
  522. }
  523. mbedtls_platform_zeroize(grp, sizeof(mbedtls_ecp_group));
  524. }
  525. /*
  526. * Unallocate (the components of) a key pair
  527. */
  528. void mbedtls_ecp_keypair_free(mbedtls_ecp_keypair *key)
  529. {
  530. if (key == NULL) {
  531. return;
  532. }
  533. mbedtls_ecp_group_free(&key->grp);
  534. mbedtls_mpi_free(&key->d);
  535. mbedtls_ecp_point_free(&key->Q);
  536. }
  537. /*
  538. * Copy the contents of a point
  539. */
  540. int mbedtls_ecp_copy(mbedtls_ecp_point *P, const mbedtls_ecp_point *Q)
  541. {
  542. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  543. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&P->X, &Q->X));
  544. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&P->Y, &Q->Y));
  545. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&P->Z, &Q->Z));
  546. cleanup:
  547. return ret;
  548. }
  549. /*
  550. * Copy the contents of a group object
  551. */
  552. int mbedtls_ecp_group_copy(mbedtls_ecp_group *dst, const mbedtls_ecp_group *src)
  553. {
  554. return mbedtls_ecp_group_load(dst, src->id);
  555. }
  556. /*
  557. * Set point to zero
  558. */
  559. int mbedtls_ecp_set_zero(mbedtls_ecp_point *pt)
  560. {
  561. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  562. MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&pt->X, 1));
  563. MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&pt->Y, 1));
  564. MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&pt->Z, 0));
  565. cleanup:
  566. return ret;
  567. }
  568. /*
  569. * Tell if a point is zero
  570. */
  571. int mbedtls_ecp_is_zero(mbedtls_ecp_point *pt)
  572. {
  573. return mbedtls_mpi_cmp_int(&pt->Z, 0) == 0;
  574. }
  575. /*
  576. * Compare two points lazily
  577. */
  578. int mbedtls_ecp_point_cmp(const mbedtls_ecp_point *P,
  579. const mbedtls_ecp_point *Q)
  580. {
  581. if (mbedtls_mpi_cmp_mpi(&P->X, &Q->X) == 0 &&
  582. mbedtls_mpi_cmp_mpi(&P->Y, &Q->Y) == 0 &&
  583. mbedtls_mpi_cmp_mpi(&P->Z, &Q->Z) == 0) {
  584. return 0;
  585. }
  586. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  587. }
  588. /*
  589. * Import a non-zero point from ASCII strings
  590. */
  591. int mbedtls_ecp_point_read_string(mbedtls_ecp_point *P, int radix,
  592. const char *x, const char *y)
  593. {
  594. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  595. MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&P->X, radix, x));
  596. MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&P->Y, radix, y));
  597. MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&P->Z, 1));
  598. cleanup:
  599. return ret;
  600. }
  601. /*
  602. * Export a point into unsigned binary data (SEC1 2.3.3 and RFC7748)
  603. */
  604. int mbedtls_ecp_point_write_binary(const mbedtls_ecp_group *grp,
  605. const mbedtls_ecp_point *P,
  606. int format, size_t *olen,
  607. unsigned char *buf, size_t buflen)
  608. {
  609. int ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
  610. size_t plen;
  611. if (format != MBEDTLS_ECP_PF_UNCOMPRESSED &&
  612. format != MBEDTLS_ECP_PF_COMPRESSED) {
  613. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  614. }
  615. plen = mbedtls_mpi_size(&grp->P);
  616. #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
  617. (void) format; /* Montgomery curves always use the same point format */
  618. if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
  619. *olen = plen;
  620. if (buflen < *olen) {
  621. return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
  622. }
  623. MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary_le(&P->X, buf, plen));
  624. }
  625. #endif
  626. #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
  627. if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
  628. /*
  629. * Common case: P == 0
  630. */
  631. if (mbedtls_mpi_cmp_int(&P->Z, 0) == 0) {
  632. if (buflen < 1) {
  633. return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
  634. }
  635. buf[0] = 0x00;
  636. *olen = 1;
  637. return 0;
  638. }
  639. if (format == MBEDTLS_ECP_PF_UNCOMPRESSED) {
  640. *olen = 2 * plen + 1;
  641. if (buflen < *olen) {
  642. return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
  643. }
  644. buf[0] = 0x04;
  645. MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&P->X, buf + 1, plen));
  646. MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&P->Y, buf + 1 + plen, plen));
  647. } else if (format == MBEDTLS_ECP_PF_COMPRESSED) {
  648. *olen = plen + 1;
  649. if (buflen < *olen) {
  650. return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
  651. }
  652. buf[0] = 0x02 + mbedtls_mpi_get_bit(&P->Y, 0);
  653. MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&P->X, buf + 1, plen));
  654. }
  655. }
  656. #endif
  657. cleanup:
  658. return ret;
  659. }
  660. #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
  661. static int mbedtls_ecp_sw_derive_y(const mbedtls_ecp_group *grp,
  662. const mbedtls_mpi *X,
  663. mbedtls_mpi *Y,
  664. int parity_bit);
  665. #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
  666. /*
  667. * Import a point from unsigned binary data (SEC1 2.3.4 and RFC7748)
  668. */
  669. int mbedtls_ecp_point_read_binary(const mbedtls_ecp_group *grp,
  670. mbedtls_ecp_point *pt,
  671. const unsigned char *buf, size_t ilen)
  672. {
  673. int ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
  674. size_t plen;
  675. if (ilen < 1) {
  676. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  677. }
  678. plen = mbedtls_mpi_size(&grp->P);
  679. #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
  680. if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
  681. if (plen != ilen) {
  682. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  683. }
  684. MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary_le(&pt->X, buf, plen));
  685. mbedtls_mpi_free(&pt->Y);
  686. if (grp->id == MBEDTLS_ECP_DP_CURVE25519) {
  687. /* Set most significant bit to 0 as prescribed in RFC7748 §5 */
  688. MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(&pt->X, plen * 8 - 1, 0));
  689. }
  690. MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&pt->Z, 1));
  691. }
  692. #endif
  693. #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
  694. if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
  695. if (buf[0] == 0x00) {
  696. if (ilen == 1) {
  697. return mbedtls_ecp_set_zero(pt);
  698. } else {
  699. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  700. }
  701. }
  702. if (ilen < 1 + plen) {
  703. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  704. }
  705. MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&pt->X, buf + 1, plen));
  706. MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&pt->Z, 1));
  707. if (buf[0] == 0x04) {
  708. /* format == MBEDTLS_ECP_PF_UNCOMPRESSED */
  709. if (ilen != 1 + plen * 2) {
  710. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  711. }
  712. return mbedtls_mpi_read_binary(&pt->Y, buf + 1 + plen, plen);
  713. } else if (buf[0] == 0x02 || buf[0] == 0x03) {
  714. /* format == MBEDTLS_ECP_PF_COMPRESSED */
  715. if (ilen != 1 + plen) {
  716. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  717. }
  718. return mbedtls_ecp_sw_derive_y(grp, &pt->X, &pt->Y,
  719. (buf[0] & 1));
  720. } else {
  721. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  722. }
  723. }
  724. #endif
  725. cleanup:
  726. return ret;
  727. }
  728. /*
  729. * Import a point from a TLS ECPoint record (RFC 4492)
  730. * struct {
  731. * opaque point <1..2^8-1>;
  732. * } ECPoint;
  733. */
  734. int mbedtls_ecp_tls_read_point(const mbedtls_ecp_group *grp,
  735. mbedtls_ecp_point *pt,
  736. const unsigned char **buf, size_t buf_len)
  737. {
  738. unsigned char data_len;
  739. const unsigned char *buf_start;
  740. /*
  741. * We must have at least two bytes (1 for length, at least one for data)
  742. */
  743. if (buf_len < 2) {
  744. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  745. }
  746. data_len = *(*buf)++;
  747. if (data_len < 1 || data_len > buf_len - 1) {
  748. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  749. }
  750. /*
  751. * Save buffer start for read_binary and update buf
  752. */
  753. buf_start = *buf;
  754. *buf += data_len;
  755. return mbedtls_ecp_point_read_binary(grp, pt, buf_start, data_len);
  756. }
  757. /*
  758. * Export a point as a TLS ECPoint record (RFC 4492)
  759. * struct {
  760. * opaque point <1..2^8-1>;
  761. * } ECPoint;
  762. */
  763. int mbedtls_ecp_tls_write_point(const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt,
  764. int format, size_t *olen,
  765. unsigned char *buf, size_t blen)
  766. {
  767. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  768. if (format != MBEDTLS_ECP_PF_UNCOMPRESSED &&
  769. format != MBEDTLS_ECP_PF_COMPRESSED) {
  770. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  771. }
  772. /*
  773. * buffer length must be at least one, for our length byte
  774. */
  775. if (blen < 1) {
  776. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  777. }
  778. if ((ret = mbedtls_ecp_point_write_binary(grp, pt, format,
  779. olen, buf + 1, blen - 1)) != 0) {
  780. return ret;
  781. }
  782. /*
  783. * write length to the first byte and update total length
  784. */
  785. buf[0] = (unsigned char) *olen;
  786. ++*olen;
  787. return 0;
  788. }
  789. /*
  790. * Set a group from an ECParameters record (RFC 4492)
  791. */
  792. int mbedtls_ecp_tls_read_group(mbedtls_ecp_group *grp,
  793. const unsigned char **buf, size_t len)
  794. {
  795. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  796. mbedtls_ecp_group_id grp_id;
  797. if ((ret = mbedtls_ecp_tls_read_group_id(&grp_id, buf, len)) != 0) {
  798. return ret;
  799. }
  800. return mbedtls_ecp_group_load(grp, grp_id);
  801. }
  802. /*
  803. * Read a group id from an ECParameters record (RFC 4492) and convert it to
  804. * mbedtls_ecp_group_id.
  805. */
  806. int mbedtls_ecp_tls_read_group_id(mbedtls_ecp_group_id *grp,
  807. const unsigned char **buf, size_t len)
  808. {
  809. uint16_t tls_id;
  810. const mbedtls_ecp_curve_info *curve_info;
  811. /*
  812. * We expect at least three bytes (see below)
  813. */
  814. if (len < 3) {
  815. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  816. }
  817. /*
  818. * First byte is curve_type; only named_curve is handled
  819. */
  820. if (*(*buf)++ != MBEDTLS_ECP_TLS_NAMED_CURVE) {
  821. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  822. }
  823. /*
  824. * Next two bytes are the namedcurve value
  825. */
  826. tls_id = *(*buf)++;
  827. tls_id <<= 8;
  828. tls_id |= *(*buf)++;
  829. if ((curve_info = mbedtls_ecp_curve_info_from_tls_id(tls_id)) == NULL) {
  830. return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
  831. }
  832. *grp = curve_info->grp_id;
  833. return 0;
  834. }
  835. /*
  836. * Write the ECParameters record corresponding to a group (RFC 4492)
  837. */
  838. int mbedtls_ecp_tls_write_group(const mbedtls_ecp_group *grp, size_t *olen,
  839. unsigned char *buf, size_t blen)
  840. {
  841. const mbedtls_ecp_curve_info *curve_info;
  842. if ((curve_info = mbedtls_ecp_curve_info_from_grp_id(grp->id)) == NULL) {
  843. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  844. }
  845. /*
  846. * We are going to write 3 bytes (see below)
  847. */
  848. *olen = 3;
  849. if (blen < *olen) {
  850. return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
  851. }
  852. /*
  853. * First byte is curve_type, always named_curve
  854. */
  855. *buf++ = MBEDTLS_ECP_TLS_NAMED_CURVE;
  856. /*
  857. * Next two bytes are the namedcurve value
  858. */
  859. MBEDTLS_PUT_UINT16_BE(curve_info->tls_id, buf, 0);
  860. return 0;
  861. }
  862. /*
  863. * Wrapper around fast quasi-modp functions, with fall-back to mbedtls_mpi_mod_mpi.
  864. * See the documentation of struct mbedtls_ecp_group.
  865. *
  866. * This function is in the critial loop for mbedtls_ecp_mul, so pay attention to perf.
  867. */
  868. static int ecp_modp(mbedtls_mpi *N, const mbedtls_ecp_group *grp)
  869. {
  870. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  871. if (grp->modp == NULL) {
  872. return mbedtls_mpi_mod_mpi(N, N, &grp->P);
  873. }
  874. /* N->s < 0 is a much faster test, which fails only if N is 0 */
  875. if ((N->s < 0 && mbedtls_mpi_cmp_int(N, 0) != 0) ||
  876. mbedtls_mpi_bitlen(N) > 2 * grp->pbits) {
  877. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  878. }
  879. MBEDTLS_MPI_CHK(grp->modp(N));
  880. /* N->s < 0 is a much faster test, which fails only if N is 0 */
  881. while (N->s < 0 && mbedtls_mpi_cmp_int(N, 0) != 0) {
  882. MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(N, N, &grp->P));
  883. }
  884. while (mbedtls_mpi_cmp_mpi(N, &grp->P) >= 0) {
  885. /* we known P, N and the result are positive */
  886. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_abs(N, N, &grp->P));
  887. }
  888. cleanup:
  889. return ret;
  890. }
  891. /*
  892. * Fast mod-p functions expect their argument to be in the 0..p^2 range.
  893. *
  894. * In order to guarantee that, we need to ensure that operands of
  895. * mbedtls_mpi_mul_mpi are in the 0..p range. So, after each operation we will
  896. * bring the result back to this range.
  897. *
  898. * The following macros are shortcuts for doing that.
  899. */
  900. /*
  901. * Reduce a mbedtls_mpi mod p in-place, general case, to use after mbedtls_mpi_mul_mpi
  902. */
  903. #if defined(MBEDTLS_SELF_TEST)
  904. #define INC_MUL_COUNT mul_count++;
  905. #else
  906. #define INC_MUL_COUNT
  907. #endif
  908. #define MOD_MUL(N) \
  909. do \
  910. { \
  911. MBEDTLS_MPI_CHK(ecp_modp(&(N), grp)); \
  912. INC_MUL_COUNT \
  913. } while (0)
  914. static inline int mbedtls_mpi_mul_mod(const mbedtls_ecp_group *grp,
  915. mbedtls_mpi *X,
  916. const mbedtls_mpi *A,
  917. const mbedtls_mpi *B)
  918. {
  919. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  920. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(X, A, B));
  921. MOD_MUL(*X);
  922. cleanup:
  923. return ret;
  924. }
  925. /*
  926. * Reduce a mbedtls_mpi mod p in-place, to use after mbedtls_mpi_sub_mpi
  927. * N->s < 0 is a very fast test, which fails only if N is 0
  928. */
  929. #define MOD_SUB(N) \
  930. do { \
  931. while ((N)->s < 0 && mbedtls_mpi_cmp_int((N), 0) != 0) \
  932. MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi((N), (N), &grp->P)); \
  933. } while (0)
  934. #if (defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) && \
  935. !(defined(MBEDTLS_ECP_NO_FALLBACK) && \
  936. defined(MBEDTLS_ECP_DOUBLE_JAC_ALT) && \
  937. defined(MBEDTLS_ECP_ADD_MIXED_ALT))) || \
  938. (defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) && \
  939. !(defined(MBEDTLS_ECP_NO_FALLBACK) && \
  940. defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT)))
  941. static inline int mbedtls_mpi_sub_mod(const mbedtls_ecp_group *grp,
  942. mbedtls_mpi *X,
  943. const mbedtls_mpi *A,
  944. const mbedtls_mpi *B)
  945. {
  946. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  947. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(X, A, B));
  948. MOD_SUB(X);
  949. cleanup:
  950. return ret;
  951. }
  952. #endif /* All functions referencing mbedtls_mpi_sub_mod() are alt-implemented without fallback */
  953. /*
  954. * Reduce a mbedtls_mpi mod p in-place, to use after mbedtls_mpi_add_mpi and mbedtls_mpi_mul_int.
  955. * We known P, N and the result are positive, so sub_abs is correct, and
  956. * a bit faster.
  957. */
  958. #define MOD_ADD(N) \
  959. while (mbedtls_mpi_cmp_mpi((N), &grp->P) >= 0) \
  960. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_abs((N), (N), &grp->P))
  961. static inline int mbedtls_mpi_add_mod(const mbedtls_ecp_group *grp,
  962. mbedtls_mpi *X,
  963. const mbedtls_mpi *A,
  964. const mbedtls_mpi *B)
  965. {
  966. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  967. MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(X, A, B));
  968. MOD_ADD(X);
  969. cleanup:
  970. return ret;
  971. }
  972. static inline int mbedtls_mpi_mul_int_mod(const mbedtls_ecp_group *grp,
  973. mbedtls_mpi *X,
  974. const mbedtls_mpi *A,
  975. mbedtls_mpi_uint c)
  976. {
  977. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  978. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_int(X, A, c));
  979. MOD_ADD(X);
  980. cleanup:
  981. return ret;
  982. }
  983. static inline int mbedtls_mpi_sub_int_mod(const mbedtls_ecp_group *grp,
  984. mbedtls_mpi *X,
  985. const mbedtls_mpi *A,
  986. mbedtls_mpi_uint c)
  987. {
  988. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  989. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(X, A, c));
  990. MOD_SUB(X);
  991. cleanup:
  992. return ret;
  993. }
  994. #define MPI_ECP_SUB_INT(X, A, c) \
  995. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int_mod(grp, X, A, c))
  996. #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) && \
  997. !(defined(MBEDTLS_ECP_NO_FALLBACK) && \
  998. defined(MBEDTLS_ECP_DOUBLE_JAC_ALT) && \
  999. defined(MBEDTLS_ECP_ADD_MIXED_ALT))
  1000. static inline int mbedtls_mpi_shift_l_mod(const mbedtls_ecp_group *grp,
  1001. mbedtls_mpi *X,
  1002. size_t count)
  1003. {
  1004. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1005. MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l(X, count));
  1006. MOD_ADD(X);
  1007. cleanup:
  1008. return ret;
  1009. }
  1010. #endif \
  1011. /* All functions referencing mbedtls_mpi_shift_l_mod() are alt-implemented without fallback */
  1012. /*
  1013. * Macro wrappers around ECP modular arithmetic
  1014. *
  1015. * Currently, these wrappers are defined via the bignum module.
  1016. */
  1017. #define MPI_ECP_ADD(X, A, B) \
  1018. MBEDTLS_MPI_CHK(mbedtls_mpi_add_mod(grp, X, A, B))
  1019. #define MPI_ECP_SUB(X, A, B) \
  1020. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mod(grp, X, A, B))
  1021. #define MPI_ECP_MUL(X, A, B) \
  1022. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, X, A, B))
  1023. #define MPI_ECP_SQR(X, A) \
  1024. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, X, A, A))
  1025. #define MPI_ECP_MUL_INT(X, A, c) \
  1026. MBEDTLS_MPI_CHK(mbedtls_mpi_mul_int_mod(grp, X, A, c))
  1027. #define MPI_ECP_INV(dst, src) \
  1028. MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod((dst), (src), &grp->P))
  1029. #define MPI_ECP_MOV(X, A) \
  1030. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(X, A))
  1031. #define MPI_ECP_SHIFT_L(X, count) \
  1032. MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l_mod(grp, X, count))
  1033. #define MPI_ECP_LSET(X, c) \
  1034. MBEDTLS_MPI_CHK(mbedtls_mpi_lset(X, c))
  1035. #define MPI_ECP_CMP_INT(X, c) \
  1036. mbedtls_mpi_cmp_int(X, c)
  1037. #define MPI_ECP_CMP(X, Y) \
  1038. mbedtls_mpi_cmp_mpi(X, Y)
  1039. /* Needs f_rng, p_rng to be defined. */
  1040. #define MPI_ECP_RAND(X) \
  1041. MBEDTLS_MPI_CHK(mbedtls_mpi_random((X), 2, &grp->P, f_rng, p_rng))
  1042. /* Conditional negation
  1043. * Needs grp and a temporary MPI tmp to be defined. */
  1044. #define MPI_ECP_COND_NEG(X, cond) \
  1045. do \
  1046. { \
  1047. unsigned char nonzero = mbedtls_mpi_cmp_int((X), 0) != 0; \
  1048. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&tmp, &grp->P, (X))); \
  1049. MBEDTLS_MPI_CHK(mbedtls_mpi_safe_cond_assign((X), &tmp, \
  1050. nonzero & cond)); \
  1051. } while (0)
  1052. #define MPI_ECP_NEG(X) MPI_ECP_COND_NEG((X), 1)
  1053. #define MPI_ECP_VALID(X) \
  1054. ((X)->p != NULL)
  1055. #define MPI_ECP_COND_ASSIGN(X, Y, cond) \
  1056. MBEDTLS_MPI_CHK(mbedtls_mpi_safe_cond_assign((X), (Y), (cond)))
  1057. #define MPI_ECP_COND_SWAP(X, Y, cond) \
  1058. MBEDTLS_MPI_CHK(mbedtls_mpi_safe_cond_swap((X), (Y), (cond)))
  1059. #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
  1060. /*
  1061. * Computes the right-hand side of the Short Weierstrass equation
  1062. * RHS = X^3 + A X + B
  1063. */
  1064. static int ecp_sw_rhs(const mbedtls_ecp_group *grp,
  1065. mbedtls_mpi *rhs,
  1066. const mbedtls_mpi *X)
  1067. {
  1068. int ret;
  1069. /* Compute X^3 + A X + B as X (X^2 + A) + B */
  1070. MPI_ECP_SQR(rhs, X);
  1071. /* Special case for A = -3 */
  1072. if (grp->A.p == NULL) {
  1073. MPI_ECP_SUB_INT(rhs, rhs, 3);
  1074. } else {
  1075. MPI_ECP_ADD(rhs, rhs, &grp->A);
  1076. }
  1077. MPI_ECP_MUL(rhs, rhs, X);
  1078. MPI_ECP_ADD(rhs, rhs, &grp->B);
  1079. cleanup:
  1080. return ret;
  1081. }
  1082. /*
  1083. * Derive Y from X and a parity bit
  1084. */
  1085. static int mbedtls_ecp_sw_derive_y(const mbedtls_ecp_group *grp,
  1086. const mbedtls_mpi *X,
  1087. mbedtls_mpi *Y,
  1088. int parity_bit)
  1089. {
  1090. /* w = y^2 = x^3 + ax + b
  1091. * y = sqrt(w) = w^((p+1)/4) mod p (for prime p where p = 3 mod 4)
  1092. *
  1093. * Note: this method for extracting square root does not validate that w
  1094. * was indeed a square so this function will return garbage in Y if X
  1095. * does not correspond to a point on the curve.
  1096. */
  1097. /* Check prerequisite p = 3 mod 4 */
  1098. if (mbedtls_mpi_get_bit(&grp->P, 0) != 1 ||
  1099. mbedtls_mpi_get_bit(&grp->P, 1) != 1) {
  1100. return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
  1101. }
  1102. int ret;
  1103. mbedtls_mpi exp;
  1104. mbedtls_mpi_init(&exp);
  1105. /* use Y to store intermediate result, actually w above */
  1106. MBEDTLS_MPI_CHK(ecp_sw_rhs(grp, Y, X));
  1107. /* w = y^2 */ /* Y contains y^2 intermediate result */
  1108. /* exp = ((p+1)/4) */
  1109. MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(&exp, &grp->P, 1));
  1110. MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&exp, 2));
  1111. /* sqrt(w) = w^((p+1)/4) mod p (for prime p where p = 3 mod 4) */
  1112. MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(Y, Y /*y^2*/, &exp, &grp->P, NULL));
  1113. /* check parity bit match or else invert Y */
  1114. /* This quick inversion implementation is valid because Y != 0 for all
  1115. * Short Weierstrass curves supported by mbedtls, as each supported curve
  1116. * has an order that is a large prime, so each supported curve does not
  1117. * have any point of order 2, and a point with Y == 0 would be of order 2 */
  1118. if (mbedtls_mpi_get_bit(Y, 0) != parity_bit) {
  1119. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(Y, &grp->P, Y));
  1120. }
  1121. cleanup:
  1122. mbedtls_mpi_free(&exp);
  1123. return ret;
  1124. }
  1125. /*
  1126. * For curves in short Weierstrass form, we do all the internal operations in
  1127. * Jacobian coordinates.
  1128. *
  1129. * For multiplication, we'll use a comb method with countermeasures against
  1130. * SPA, hence timing attacks.
  1131. */
  1132. /*
  1133. * Normalize jacobian coordinates so that Z == 0 || Z == 1 (GECC 3.2.1)
  1134. * Cost: 1N := 1I + 3M + 1S
  1135. */
  1136. static int ecp_normalize_jac(const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt)
  1137. {
  1138. if (MPI_ECP_CMP_INT(&pt->Z, 0) == 0) {
  1139. return 0;
  1140. }
  1141. #if defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT)
  1142. if (mbedtls_internal_ecp_grp_capable(grp)) {
  1143. return mbedtls_internal_ecp_normalize_jac(grp, pt);
  1144. }
  1145. #endif /* MBEDTLS_ECP_NORMALIZE_JAC_ALT */
  1146. #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT)
  1147. return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
  1148. #else
  1149. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1150. mbedtls_mpi T;
  1151. mbedtls_mpi_init(&T);
  1152. MPI_ECP_INV(&T, &pt->Z); /* T <- 1 / Z */
  1153. MPI_ECP_MUL(&pt->Y, &pt->Y, &T); /* Y' <- Y*T = Y / Z */
  1154. MPI_ECP_SQR(&T, &T); /* T <- T^2 = 1 / Z^2 */
  1155. MPI_ECP_MUL(&pt->X, &pt->X, &T); /* X <- X * T = X / Z^2 */
  1156. MPI_ECP_MUL(&pt->Y, &pt->Y, &T); /* Y'' <- Y' * T = Y / Z^3 */
  1157. MPI_ECP_LSET(&pt->Z, 1);
  1158. cleanup:
  1159. mbedtls_mpi_free(&T);
  1160. return ret;
  1161. #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT) */
  1162. }
  1163. /*
  1164. * Normalize jacobian coordinates of an array of (pointers to) points,
  1165. * using Montgomery's trick to perform only one inversion mod P.
  1166. * (See for example Cohen's "A Course in Computational Algebraic Number
  1167. * Theory", Algorithm 10.3.4.)
  1168. *
  1169. * Warning: fails (returning an error) if one of the points is zero!
  1170. * This should never happen, see choice of w in ecp_mul_comb().
  1171. *
  1172. * Cost: 1N(t) := 1I + (6t - 3)M + 1S
  1173. */
  1174. static int ecp_normalize_jac_many(const mbedtls_ecp_group *grp,
  1175. mbedtls_ecp_point *T[], size_t T_size)
  1176. {
  1177. if (T_size < 2) {
  1178. return ecp_normalize_jac(grp, *T);
  1179. }
  1180. #if defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT)
  1181. if (mbedtls_internal_ecp_grp_capable(grp)) {
  1182. return mbedtls_internal_ecp_normalize_jac_many(grp, T, T_size);
  1183. }
  1184. #endif
  1185. #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT)
  1186. return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
  1187. #else
  1188. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1189. size_t i;
  1190. mbedtls_mpi *c, t;
  1191. if ((c = mbedtls_calloc(T_size, sizeof(mbedtls_mpi))) == NULL) {
  1192. return MBEDTLS_ERR_ECP_ALLOC_FAILED;
  1193. }
  1194. mbedtls_mpi_init(&t);
  1195. mpi_init_many(c, T_size);
  1196. /*
  1197. * c[i] = Z_0 * ... * Z_i, i = 0,..,n := T_size-1
  1198. */
  1199. MPI_ECP_MOV(&c[0], &T[0]->Z);
  1200. for (i = 1; i < T_size; i++) {
  1201. MPI_ECP_MUL(&c[i], &c[i-1], &T[i]->Z);
  1202. }
  1203. /*
  1204. * c[n] = 1 / (Z_0 * ... * Z_n) mod P
  1205. */
  1206. MPI_ECP_INV(&c[T_size-1], &c[T_size-1]);
  1207. for (i = T_size - 1;; i--) {
  1208. /* At the start of iteration i (note that i decrements), we have
  1209. * - c[j] = Z_0 * .... * Z_j for j < i,
  1210. * - c[j] = 1 / (Z_0 * .... * Z_j) for j == i,
  1211. *
  1212. * This is maintained via
  1213. * - c[i-1] <- c[i] * Z_i
  1214. *
  1215. * We also derive 1/Z_i = c[i] * c[i-1] for i>0 and use that
  1216. * to do the actual normalization. For i==0, we already have
  1217. * c[0] = 1 / Z_0.
  1218. */
  1219. if (i > 0) {
  1220. /* Compute 1/Z_i and establish invariant for the next iteration. */
  1221. MPI_ECP_MUL(&t, &c[i], &c[i-1]);
  1222. MPI_ECP_MUL(&c[i-1], &c[i], &T[i]->Z);
  1223. } else {
  1224. MPI_ECP_MOV(&t, &c[0]);
  1225. }
  1226. /* Now t holds 1 / Z_i; normalize as in ecp_normalize_jac() */
  1227. MPI_ECP_MUL(&T[i]->Y, &T[i]->Y, &t);
  1228. MPI_ECP_SQR(&t, &t);
  1229. MPI_ECP_MUL(&T[i]->X, &T[i]->X, &t);
  1230. MPI_ECP_MUL(&T[i]->Y, &T[i]->Y, &t);
  1231. /*
  1232. * Post-precessing: reclaim some memory by shrinking coordinates
  1233. * - not storing Z (always 1)
  1234. * - shrinking other coordinates, but still keeping the same number of
  1235. * limbs as P, as otherwise it will too likely be regrown too fast.
  1236. */
  1237. MBEDTLS_MPI_CHK(mbedtls_mpi_shrink(&T[i]->X, grp->P.n));
  1238. MBEDTLS_MPI_CHK(mbedtls_mpi_shrink(&T[i]->Y, grp->P.n));
  1239. MPI_ECP_LSET(&T[i]->Z, 1);
  1240. if (i == 0) {
  1241. break;
  1242. }
  1243. }
  1244. cleanup:
  1245. mbedtls_mpi_free(&t);
  1246. mpi_free_many(c, T_size);
  1247. mbedtls_free(c);
  1248. return ret;
  1249. #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT) */
  1250. }
  1251. /*
  1252. * Conditional point inversion: Q -> -Q = (Q.X, -Q.Y, Q.Z) without leak.
  1253. * "inv" must be 0 (don't invert) or 1 (invert) or the result will be invalid
  1254. */
  1255. static int ecp_safe_invert_jac(const mbedtls_ecp_group *grp,
  1256. mbedtls_ecp_point *Q,
  1257. unsigned char inv)
  1258. {
  1259. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1260. mbedtls_mpi tmp;
  1261. mbedtls_mpi_init(&tmp);
  1262. MPI_ECP_COND_NEG(&Q->Y, inv);
  1263. cleanup:
  1264. mbedtls_mpi_free(&tmp);
  1265. return ret;
  1266. }
  1267. /*
  1268. * Point doubling R = 2 P, Jacobian coordinates
  1269. *
  1270. * Based on http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#doubling-dbl-1998-cmo-2 .
  1271. *
  1272. * We follow the variable naming fairly closely. The formula variations that trade a MUL for a SQR
  1273. * (plus a few ADDs) aren't useful as our bignum implementation doesn't distinguish squaring.
  1274. *
  1275. * Standard optimizations are applied when curve parameter A is one of { 0, -3 }.
  1276. *
  1277. * Cost: 1D := 3M + 4S (A == 0)
  1278. * 4M + 4S (A == -3)
  1279. * 3M + 6S + 1a otherwise
  1280. */
  1281. static int ecp_double_jac(const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
  1282. const mbedtls_ecp_point *P,
  1283. mbedtls_mpi tmp[4])
  1284. {
  1285. #if defined(MBEDTLS_SELF_TEST)
  1286. dbl_count++;
  1287. #endif
  1288. #if defined(MBEDTLS_ECP_DOUBLE_JAC_ALT)
  1289. if (mbedtls_internal_ecp_grp_capable(grp)) {
  1290. return mbedtls_internal_ecp_double_jac(grp, R, P);
  1291. }
  1292. #endif /* MBEDTLS_ECP_DOUBLE_JAC_ALT */
  1293. #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_DOUBLE_JAC_ALT)
  1294. return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
  1295. #else
  1296. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1297. /* Special case for A = -3 */
  1298. if (grp->A.p == NULL) {
  1299. /* tmp[0] <- M = 3(X + Z^2)(X - Z^2) */
  1300. MPI_ECP_SQR(&tmp[1], &P->Z);
  1301. MPI_ECP_ADD(&tmp[2], &P->X, &tmp[1]);
  1302. MPI_ECP_SUB(&tmp[3], &P->X, &tmp[1]);
  1303. MPI_ECP_MUL(&tmp[1], &tmp[2], &tmp[3]);
  1304. MPI_ECP_MUL_INT(&tmp[0], &tmp[1], 3);
  1305. } else {
  1306. /* tmp[0] <- M = 3.X^2 + A.Z^4 */
  1307. MPI_ECP_SQR(&tmp[1], &P->X);
  1308. MPI_ECP_MUL_INT(&tmp[0], &tmp[1], 3);
  1309. /* Optimize away for "koblitz" curves with A = 0 */
  1310. if (MPI_ECP_CMP_INT(&grp->A, 0) != 0) {
  1311. /* M += A.Z^4 */
  1312. MPI_ECP_SQR(&tmp[1], &P->Z);
  1313. MPI_ECP_SQR(&tmp[2], &tmp[1]);
  1314. MPI_ECP_MUL(&tmp[1], &tmp[2], &grp->A);
  1315. MPI_ECP_ADD(&tmp[0], &tmp[0], &tmp[1]);
  1316. }
  1317. }
  1318. /* tmp[1] <- S = 4.X.Y^2 */
  1319. MPI_ECP_SQR(&tmp[2], &P->Y);
  1320. MPI_ECP_SHIFT_L(&tmp[2], 1);
  1321. MPI_ECP_MUL(&tmp[1], &P->X, &tmp[2]);
  1322. MPI_ECP_SHIFT_L(&tmp[1], 1);
  1323. /* tmp[3] <- U = 8.Y^4 */
  1324. MPI_ECP_SQR(&tmp[3], &tmp[2]);
  1325. MPI_ECP_SHIFT_L(&tmp[3], 1);
  1326. /* tmp[2] <- T = M^2 - 2.S */
  1327. MPI_ECP_SQR(&tmp[2], &tmp[0]);
  1328. MPI_ECP_SUB(&tmp[2], &tmp[2], &tmp[1]);
  1329. MPI_ECP_SUB(&tmp[2], &tmp[2], &tmp[1]);
  1330. /* tmp[1] <- S = M(S - T) - U */
  1331. MPI_ECP_SUB(&tmp[1], &tmp[1], &tmp[2]);
  1332. MPI_ECP_MUL(&tmp[1], &tmp[1], &tmp[0]);
  1333. MPI_ECP_SUB(&tmp[1], &tmp[1], &tmp[3]);
  1334. /* tmp[3] <- U = 2.Y.Z */
  1335. MPI_ECP_MUL(&tmp[3], &P->Y, &P->Z);
  1336. MPI_ECP_SHIFT_L(&tmp[3], 1);
  1337. /* Store results */
  1338. MPI_ECP_MOV(&R->X, &tmp[2]);
  1339. MPI_ECP_MOV(&R->Y, &tmp[1]);
  1340. MPI_ECP_MOV(&R->Z, &tmp[3]);
  1341. cleanup:
  1342. return ret;
  1343. #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_DOUBLE_JAC_ALT) */
  1344. }
  1345. /*
  1346. * Addition: R = P + Q, mixed affine-Jacobian coordinates (GECC 3.22)
  1347. *
  1348. * The coordinates of Q must be normalized (= affine),
  1349. * but those of P don't need to. R is not normalized.
  1350. *
  1351. * P,Q,R may alias, but only at the level of EC points: they must be either
  1352. * equal as pointers, or disjoint (including the coordinate data buffers).
  1353. * Fine-grained aliasing at the level of coordinates is not supported.
  1354. *
  1355. * Special cases: (1) P or Q is zero, (2) R is zero, (3) P == Q.
  1356. * None of these cases can happen as intermediate step in ecp_mul_comb():
  1357. * - at each step, P, Q and R are multiples of the base point, the factor
  1358. * being less than its order, so none of them is zero;
  1359. * - Q is an odd multiple of the base point, P an even multiple,
  1360. * due to the choice of precomputed points in the modified comb method.
  1361. * So branches for these cases do not leak secret information.
  1362. *
  1363. * Cost: 1A := 8M + 3S
  1364. */
  1365. static int ecp_add_mixed(const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
  1366. const mbedtls_ecp_point *P, const mbedtls_ecp_point *Q,
  1367. mbedtls_mpi tmp[4])
  1368. {
  1369. #if defined(MBEDTLS_SELF_TEST)
  1370. add_count++;
  1371. #endif
  1372. #if defined(MBEDTLS_ECP_ADD_MIXED_ALT)
  1373. if (mbedtls_internal_ecp_grp_capable(grp)) {
  1374. return mbedtls_internal_ecp_add_mixed(grp, R, P, Q);
  1375. }
  1376. #endif /* MBEDTLS_ECP_ADD_MIXED_ALT */
  1377. #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_ADD_MIXED_ALT)
  1378. return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
  1379. #else
  1380. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1381. /* NOTE: Aliasing between input and output is allowed, so one has to make
  1382. * sure that at the point X,Y,Z are written, {P,Q}->{X,Y,Z} are no
  1383. * longer read from. */
  1384. mbedtls_mpi * const X = &R->X;
  1385. mbedtls_mpi * const Y = &R->Y;
  1386. mbedtls_mpi * const Z = &R->Z;
  1387. if (!MPI_ECP_VALID(&Q->Z)) {
  1388. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  1389. }
  1390. /*
  1391. * Trivial cases: P == 0 or Q == 0 (case 1)
  1392. */
  1393. if (MPI_ECP_CMP_INT(&P->Z, 0) == 0) {
  1394. return mbedtls_ecp_copy(R, Q);
  1395. }
  1396. if (MPI_ECP_CMP_INT(&Q->Z, 0) == 0) {
  1397. return mbedtls_ecp_copy(R, P);
  1398. }
  1399. /*
  1400. * Make sure Q coordinates are normalized
  1401. */
  1402. if (MPI_ECP_CMP_INT(&Q->Z, 1) != 0) {
  1403. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  1404. }
  1405. MPI_ECP_SQR(&tmp[0], &P->Z);
  1406. MPI_ECP_MUL(&tmp[1], &tmp[0], &P->Z);
  1407. MPI_ECP_MUL(&tmp[0], &tmp[0], &Q->X);
  1408. MPI_ECP_MUL(&tmp[1], &tmp[1], &Q->Y);
  1409. MPI_ECP_SUB(&tmp[0], &tmp[0], &P->X);
  1410. MPI_ECP_SUB(&tmp[1], &tmp[1], &P->Y);
  1411. /* Special cases (2) and (3) */
  1412. if (MPI_ECP_CMP_INT(&tmp[0], 0) == 0) {
  1413. if (MPI_ECP_CMP_INT(&tmp[1], 0) == 0) {
  1414. ret = ecp_double_jac(grp, R, P, tmp);
  1415. goto cleanup;
  1416. } else {
  1417. ret = mbedtls_ecp_set_zero(R);
  1418. goto cleanup;
  1419. }
  1420. }
  1421. /* {P,Q}->Z no longer used, so OK to write to Z even if there's aliasing. */
  1422. MPI_ECP_MUL(Z, &P->Z, &tmp[0]);
  1423. MPI_ECP_SQR(&tmp[2], &tmp[0]);
  1424. MPI_ECP_MUL(&tmp[3], &tmp[2], &tmp[0]);
  1425. MPI_ECP_MUL(&tmp[2], &tmp[2], &P->X);
  1426. MPI_ECP_MOV(&tmp[0], &tmp[2]);
  1427. MPI_ECP_SHIFT_L(&tmp[0], 1);
  1428. /* {P,Q}->X no longer used, so OK to write to X even if there's aliasing. */
  1429. MPI_ECP_SQR(X, &tmp[1]);
  1430. MPI_ECP_SUB(X, X, &tmp[0]);
  1431. MPI_ECP_SUB(X, X, &tmp[3]);
  1432. MPI_ECP_SUB(&tmp[2], &tmp[2], X);
  1433. MPI_ECP_MUL(&tmp[2], &tmp[2], &tmp[1]);
  1434. MPI_ECP_MUL(&tmp[3], &tmp[3], &P->Y);
  1435. /* {P,Q}->Y no longer used, so OK to write to Y even if there's aliasing. */
  1436. MPI_ECP_SUB(Y, &tmp[2], &tmp[3]);
  1437. cleanup:
  1438. return ret;
  1439. #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_ADD_MIXED_ALT) */
  1440. }
  1441. /*
  1442. * Randomize jacobian coordinates:
  1443. * (X, Y, Z) -> (l^2 X, l^3 Y, l Z) for random l
  1444. * This is sort of the reverse operation of ecp_normalize_jac().
  1445. *
  1446. * This countermeasure was first suggested in [2].
  1447. */
  1448. static int ecp_randomize_jac(const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt,
  1449. int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
  1450. {
  1451. #if defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT)
  1452. if (mbedtls_internal_ecp_grp_capable(grp)) {
  1453. return mbedtls_internal_ecp_randomize_jac(grp, pt, f_rng, p_rng);
  1454. }
  1455. #endif /* MBEDTLS_ECP_RANDOMIZE_JAC_ALT */
  1456. #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT)
  1457. return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
  1458. #else
  1459. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1460. mbedtls_mpi l;
  1461. mbedtls_mpi_init(&l);
  1462. /* Generate l such that 1 < l < p */
  1463. MPI_ECP_RAND(&l);
  1464. /* Z' = l * Z */
  1465. MPI_ECP_MUL(&pt->Z, &pt->Z, &l);
  1466. /* Y' = l * Y */
  1467. MPI_ECP_MUL(&pt->Y, &pt->Y, &l);
  1468. /* X' = l^2 * X */
  1469. MPI_ECP_SQR(&l, &l);
  1470. MPI_ECP_MUL(&pt->X, &pt->X, &l);
  1471. /* Y'' = l^2 * Y' = l^3 * Y */
  1472. MPI_ECP_MUL(&pt->Y, &pt->Y, &l);
  1473. cleanup:
  1474. mbedtls_mpi_free(&l);
  1475. if (ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) {
  1476. ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
  1477. }
  1478. return ret;
  1479. #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT) */
  1480. }
  1481. /*
  1482. * Check and define parameters used by the comb method (see below for details)
  1483. */
  1484. #if MBEDTLS_ECP_WINDOW_SIZE < 2 || MBEDTLS_ECP_WINDOW_SIZE > 7
  1485. #error "MBEDTLS_ECP_WINDOW_SIZE out of bounds"
  1486. #endif
  1487. /* d = ceil( n / w ) */
  1488. #define COMB_MAX_D (MBEDTLS_ECP_MAX_BITS + 1) / 2
  1489. /* number of precomputed points */
  1490. #define COMB_MAX_PRE (1 << (MBEDTLS_ECP_WINDOW_SIZE - 1))
  1491. /*
  1492. * Compute the representation of m that will be used with our comb method.
  1493. *
  1494. * The basic comb method is described in GECC 3.44 for example. We use a
  1495. * modified version that provides resistance to SPA by avoiding zero
  1496. * digits in the representation as in [3]. We modify the method further by
  1497. * requiring that all K_i be odd, which has the small cost that our
  1498. * representation uses one more K_i, due to carries, but saves on the size of
  1499. * the precomputed table.
  1500. *
  1501. * Summary of the comb method and its modifications:
  1502. *
  1503. * - The goal is to compute m*P for some w*d-bit integer m.
  1504. *
  1505. * - The basic comb method splits m into the w-bit integers
  1506. * x[0] .. x[d-1] where x[i] consists of the bits in m whose
  1507. * index has residue i modulo d, and computes m * P as
  1508. * S[x[0]] + 2 * S[x[1]] + .. + 2^(d-1) S[x[d-1]], where
  1509. * S[i_{w-1} .. i_0] := i_{w-1} 2^{(w-1)d} P + ... + i_1 2^d P + i_0 P.
  1510. *
  1511. * - If it happens that, say, x[i+1]=0 (=> S[x[i+1]]=0), one can replace the sum by
  1512. * .. + 2^{i-1} S[x[i-1]] - 2^i S[x[i]] + 2^{i+1} S[x[i]] + 2^{i+2} S[x[i+2]] ..,
  1513. * thereby successively converting it into a form where all summands
  1514. * are nonzero, at the cost of negative summands. This is the basic idea of [3].
  1515. *
  1516. * - More generally, even if x[i+1] != 0, we can first transform the sum as
  1517. * .. - 2^i S[x[i]] + 2^{i+1} ( S[x[i]] + S[x[i+1]] ) + 2^{i+2} S[x[i+2]] ..,
  1518. * and then replace S[x[i]] + S[x[i+1]] = S[x[i] ^ x[i+1]] + 2 S[x[i] & x[i+1]].
  1519. * Performing and iterating this procedure for those x[i] that are even
  1520. * (keeping track of carry), we can transform the original sum into one of the form
  1521. * S[x'[0]] +- 2 S[x'[1]] +- .. +- 2^{d-1} S[x'[d-1]] + 2^d S[x'[d]]
  1522. * with all x'[i] odd. It is therefore only necessary to know S at odd indices,
  1523. * which is why we are only computing half of it in the first place in
  1524. * ecp_precompute_comb and accessing it with index abs(i) / 2 in ecp_select_comb.
  1525. *
  1526. * - For the sake of compactness, only the seven low-order bits of x[i]
  1527. * are used to represent its absolute value (K_i in the paper), and the msb
  1528. * of x[i] encodes the sign (s_i in the paper): it is set if and only if
  1529. * if s_i == -1;
  1530. *
  1531. * Calling conventions:
  1532. * - x is an array of size d + 1
  1533. * - w is the size, ie number of teeth, of the comb, and must be between
  1534. * 2 and 7 (in practice, between 2 and MBEDTLS_ECP_WINDOW_SIZE)
  1535. * - m is the MPI, expected to be odd and such that bitlength(m) <= w * d
  1536. * (the result will be incorrect if these assumptions are not satisfied)
  1537. */
  1538. static void ecp_comb_recode_core(unsigned char x[], size_t d,
  1539. unsigned char w, const mbedtls_mpi *m)
  1540. {
  1541. size_t i, j;
  1542. unsigned char c, cc, adjust;
  1543. memset(x, 0, d+1);
  1544. /* First get the classical comb values (except for x_d = 0) */
  1545. for (i = 0; i < d; i++) {
  1546. for (j = 0; j < w; j++) {
  1547. x[i] |= mbedtls_mpi_get_bit(m, i + d * j) << j;
  1548. }
  1549. }
  1550. /* Now make sure x_1 .. x_d are odd */
  1551. c = 0;
  1552. for (i = 1; i <= d; i++) {
  1553. /* Add carry and update it */
  1554. cc = x[i] & c;
  1555. x[i] = x[i] ^ c;
  1556. c = cc;
  1557. /* Adjust if needed, avoiding branches */
  1558. adjust = 1 - (x[i] & 0x01);
  1559. c |= x[i] & (x[i-1] * adjust);
  1560. x[i] = x[i] ^ (x[i-1] * adjust);
  1561. x[i-1] |= adjust << 7;
  1562. }
  1563. }
  1564. /*
  1565. * Precompute points for the adapted comb method
  1566. *
  1567. * Assumption: T must be able to hold 2^{w - 1} elements.
  1568. *
  1569. * Operation: If i = i_{w-1} ... i_1 is the binary representation of i,
  1570. * sets T[i] = i_{w-1} 2^{(w-1)d} P + ... + i_1 2^d P + P.
  1571. *
  1572. * Cost: d(w-1) D + (2^{w-1} - 1) A + 1 N(w-1) + 1 N(2^{w-1} - 1)
  1573. *
  1574. * Note: Even comb values (those where P would be omitted from the
  1575. * sum defining T[i] above) are not needed in our adaption
  1576. * the comb method. See ecp_comb_recode_core().
  1577. *
  1578. * This function currently works in four steps:
  1579. * (1) [dbl] Computation of intermediate T[i] for 2-power values of i
  1580. * (2) [norm_dbl] Normalization of coordinates of these T[i]
  1581. * (3) [add] Computation of all T[i]
  1582. * (4) [norm_add] Normalization of all T[i]
  1583. *
  1584. * Step 1 can be interrupted but not the others; together with the final
  1585. * coordinate normalization they are the largest steps done at once, depending
  1586. * on the window size. Here are operation counts for P-256:
  1587. *
  1588. * step (2) (3) (4)
  1589. * w = 5 142 165 208
  1590. * w = 4 136 77 160
  1591. * w = 3 130 33 136
  1592. * w = 2 124 11 124
  1593. *
  1594. * So if ECC operations are blocking for too long even with a low max_ops
  1595. * value, it's useful to set MBEDTLS_ECP_WINDOW_SIZE to a lower value in order
  1596. * to minimize maximum blocking time.
  1597. */
  1598. static int ecp_precompute_comb(const mbedtls_ecp_group *grp,
  1599. mbedtls_ecp_point T[], const mbedtls_ecp_point *P,
  1600. unsigned char w, size_t d,
  1601. mbedtls_ecp_restart_ctx *rs_ctx)
  1602. {
  1603. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1604. unsigned char i;
  1605. size_t j = 0;
  1606. const unsigned char T_size = 1U << (w - 1);
  1607. mbedtls_ecp_point *cur, *TT[COMB_MAX_PRE - 1] = { NULL };
  1608. mbedtls_mpi tmp[4];
  1609. mpi_init_many(tmp, sizeof(tmp) / sizeof(mbedtls_mpi));
  1610. #if defined(MBEDTLS_ECP_RESTARTABLE)
  1611. if (rs_ctx != NULL && rs_ctx->rsm != NULL) {
  1612. if (rs_ctx->rsm->state == ecp_rsm_pre_dbl) {
  1613. goto dbl;
  1614. }
  1615. if (rs_ctx->rsm->state == ecp_rsm_pre_norm_dbl) {
  1616. goto norm_dbl;
  1617. }
  1618. if (rs_ctx->rsm->state == ecp_rsm_pre_add) {
  1619. goto add;
  1620. }
  1621. if (rs_ctx->rsm->state == ecp_rsm_pre_norm_add) {
  1622. goto norm_add;
  1623. }
  1624. }
  1625. #else
  1626. (void) rs_ctx;
  1627. #endif
  1628. #if defined(MBEDTLS_ECP_RESTARTABLE)
  1629. if (rs_ctx != NULL && rs_ctx->rsm != NULL) {
  1630. rs_ctx->rsm->state = ecp_rsm_pre_dbl;
  1631. /* initial state for the loop */
  1632. rs_ctx->rsm->i = 0;
  1633. }
  1634. dbl:
  1635. #endif
  1636. /*
  1637. * Set T[0] = P and
  1638. * T[2^{l-1}] = 2^{dl} P for l = 1 .. w-1 (this is not the final value)
  1639. */
  1640. MBEDTLS_MPI_CHK(mbedtls_ecp_copy(&T[0], P));
  1641. #if defined(MBEDTLS_ECP_RESTARTABLE)
  1642. if (rs_ctx != NULL && rs_ctx->rsm != NULL && rs_ctx->rsm->i != 0) {
  1643. j = rs_ctx->rsm->i;
  1644. } else
  1645. #endif
  1646. j = 0;
  1647. for (; j < d * (w - 1); j++) {
  1648. MBEDTLS_ECP_BUDGET(MBEDTLS_ECP_OPS_DBL);
  1649. i = 1U << (j / d);
  1650. cur = T + i;
  1651. if (j % d == 0) {
  1652. MBEDTLS_MPI_CHK(mbedtls_ecp_copy(cur, T + (i >> 1)));
  1653. }
  1654. MBEDTLS_MPI_CHK(ecp_double_jac(grp, cur, cur, tmp));
  1655. }
  1656. #if defined(MBEDTLS_ECP_RESTARTABLE)
  1657. if (rs_ctx != NULL && rs_ctx->rsm != NULL) {
  1658. rs_ctx->rsm->state = ecp_rsm_pre_norm_dbl;
  1659. }
  1660. norm_dbl:
  1661. #endif
  1662. /*
  1663. * Normalize current elements in T to allow them to be used in
  1664. * ecp_add_mixed() below, which requires one normalized input.
  1665. *
  1666. * As T has holes, use an auxiliary array of pointers to elements in T.
  1667. *
  1668. */
  1669. j = 0;
  1670. for (i = 1; i < T_size; i <<= 1) {
  1671. TT[j++] = T + i;
  1672. }
  1673. MBEDTLS_ECP_BUDGET(MBEDTLS_ECP_OPS_INV + 6 * j - 2);
  1674. MBEDTLS_MPI_CHK(ecp_normalize_jac_many(grp, TT, j));
  1675. #if defined(MBEDTLS_ECP_RESTARTABLE)
  1676. if (rs_ctx != NULL && rs_ctx->rsm != NULL) {
  1677. rs_ctx->rsm->state = ecp_rsm_pre_add;
  1678. }
  1679. add:
  1680. #endif
  1681. /*
  1682. * Compute the remaining ones using the minimal number of additions
  1683. * Be careful to update T[2^l] only after using it!
  1684. */
  1685. MBEDTLS_ECP_BUDGET((T_size - 1) * MBEDTLS_ECP_OPS_ADD);
  1686. for (i = 1; i < T_size; i <<= 1) {
  1687. j = i;
  1688. while (j--) {
  1689. MBEDTLS_MPI_CHK(ecp_add_mixed(grp, &T[i + j], &T[j], &T[i], tmp));
  1690. }
  1691. }
  1692. #if defined(MBEDTLS_ECP_RESTARTABLE)
  1693. if (rs_ctx != NULL && rs_ctx->rsm != NULL) {
  1694. rs_ctx->rsm->state = ecp_rsm_pre_norm_add;
  1695. }
  1696. norm_add:
  1697. #endif
  1698. /*
  1699. * Normalize final elements in T. Even though there are no holes now, we
  1700. * still need the auxiliary array for homogeneity with the previous
  1701. * call. Also, skip T[0] which is already normalised, being a copy of P.
  1702. */
  1703. for (j = 0; j + 1 < T_size; j++) {
  1704. TT[j] = T + j + 1;
  1705. }
  1706. MBEDTLS_ECP_BUDGET(MBEDTLS_ECP_OPS_INV + 6 * j - 2);
  1707. MBEDTLS_MPI_CHK(ecp_normalize_jac_many(grp, TT, j));
  1708. /* Free Z coordinate (=1 after normalization) to save RAM.
  1709. * This makes T[i] invalid as mbedtls_ecp_points, but this is OK
  1710. * since from this point onwards, they are only accessed indirectly
  1711. * via the getter function ecp_select_comb() which does set the
  1712. * target's Z coordinate to 1. */
  1713. for (i = 0; i < T_size; i++) {
  1714. mbedtls_mpi_free(&T[i].Z);
  1715. }
  1716. cleanup:
  1717. mpi_free_many(tmp, sizeof(tmp) / sizeof(mbedtls_mpi));
  1718. #if defined(MBEDTLS_ECP_RESTARTABLE)
  1719. if (rs_ctx != NULL && rs_ctx->rsm != NULL &&
  1720. ret == MBEDTLS_ERR_ECP_IN_PROGRESS) {
  1721. if (rs_ctx->rsm->state == ecp_rsm_pre_dbl) {
  1722. rs_ctx->rsm->i = j;
  1723. }
  1724. }
  1725. #endif
  1726. return ret;
  1727. }
  1728. /*
  1729. * Select precomputed point: R = sign(i) * T[ abs(i) / 2 ]
  1730. *
  1731. * See ecp_comb_recode_core() for background
  1732. */
  1733. static int ecp_select_comb(const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
  1734. const mbedtls_ecp_point T[], unsigned char T_size,
  1735. unsigned char i)
  1736. {
  1737. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1738. unsigned char ii, j;
  1739. /* Ignore the "sign" bit and scale down */
  1740. ii = (i & 0x7Fu) >> 1;
  1741. /* Read the whole table to thwart cache-based timing attacks */
  1742. for (j = 0; j < T_size; j++) {
  1743. MPI_ECP_COND_ASSIGN(&R->X, &T[j].X, j == ii);
  1744. MPI_ECP_COND_ASSIGN(&R->Y, &T[j].Y, j == ii);
  1745. }
  1746. /* Safely invert result if i is "negative" */
  1747. MBEDTLS_MPI_CHK(ecp_safe_invert_jac(grp, R, i >> 7));
  1748. MPI_ECP_LSET(&R->Z, 1);
  1749. cleanup:
  1750. return ret;
  1751. }
  1752. /*
  1753. * Core multiplication algorithm for the (modified) comb method.
  1754. * This part is actually common with the basic comb method (GECC 3.44)
  1755. *
  1756. * Cost: d A + d D + 1 R
  1757. */
  1758. static int ecp_mul_comb_core(const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
  1759. const mbedtls_ecp_point T[], unsigned char T_size,
  1760. const unsigned char x[], size_t d,
  1761. int (*f_rng)(void *, unsigned char *, size_t),
  1762. void *p_rng,
  1763. mbedtls_ecp_restart_ctx *rs_ctx)
  1764. {
  1765. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1766. mbedtls_ecp_point Txi;
  1767. mbedtls_mpi tmp[4];
  1768. size_t i;
  1769. mbedtls_ecp_point_init(&Txi);
  1770. mpi_init_many(tmp, sizeof(tmp) / sizeof(mbedtls_mpi));
  1771. #if !defined(MBEDTLS_ECP_RESTARTABLE)
  1772. (void) rs_ctx;
  1773. #endif
  1774. #if defined(MBEDTLS_ECP_RESTARTABLE)
  1775. if (rs_ctx != NULL && rs_ctx->rsm != NULL &&
  1776. rs_ctx->rsm->state != ecp_rsm_comb_core) {
  1777. rs_ctx->rsm->i = 0;
  1778. rs_ctx->rsm->state = ecp_rsm_comb_core;
  1779. }
  1780. /* new 'if' instead of nested for the sake of the 'else' branch */
  1781. if (rs_ctx != NULL && rs_ctx->rsm != NULL && rs_ctx->rsm->i != 0) {
  1782. /* restore current index (R already pointing to rs_ctx->rsm->R) */
  1783. i = rs_ctx->rsm->i;
  1784. } else
  1785. #endif
  1786. {
  1787. /* Start with a non-zero point and randomize its coordinates */
  1788. i = d;
  1789. MBEDTLS_MPI_CHK(ecp_select_comb(grp, R, T, T_size, x[i]));
  1790. if (f_rng != 0) {
  1791. MBEDTLS_MPI_CHK(ecp_randomize_jac(grp, R, f_rng, p_rng));
  1792. }
  1793. }
  1794. while (i != 0) {
  1795. MBEDTLS_ECP_BUDGET(MBEDTLS_ECP_OPS_DBL + MBEDTLS_ECP_OPS_ADD);
  1796. --i;
  1797. MBEDTLS_MPI_CHK(ecp_double_jac(grp, R, R, tmp));
  1798. MBEDTLS_MPI_CHK(ecp_select_comb(grp, &Txi, T, T_size, x[i]));
  1799. MBEDTLS_MPI_CHK(ecp_add_mixed(grp, R, R, &Txi, tmp));
  1800. }
  1801. cleanup:
  1802. mbedtls_ecp_point_free(&Txi);
  1803. mpi_free_many(tmp, sizeof(tmp) / sizeof(mbedtls_mpi));
  1804. #if defined(MBEDTLS_ECP_RESTARTABLE)
  1805. if (rs_ctx != NULL && rs_ctx->rsm != NULL &&
  1806. ret == MBEDTLS_ERR_ECP_IN_PROGRESS) {
  1807. rs_ctx->rsm->i = i;
  1808. /* no need to save R, already pointing to rs_ctx->rsm->R */
  1809. }
  1810. #endif
  1811. return ret;
  1812. }
  1813. /*
  1814. * Recode the scalar to get constant-time comb multiplication
  1815. *
  1816. * As the actual scalar recoding needs an odd scalar as a starting point,
  1817. * this wrapper ensures that by replacing m by N - m if necessary, and
  1818. * informs the caller that the result of multiplication will be negated.
  1819. *
  1820. * This works because we only support large prime order for Short Weierstrass
  1821. * curves, so N is always odd hence either m or N - m is.
  1822. *
  1823. * See ecp_comb_recode_core() for background.
  1824. */
  1825. static int ecp_comb_recode_scalar(const mbedtls_ecp_group *grp,
  1826. const mbedtls_mpi *m,
  1827. unsigned char k[COMB_MAX_D + 1],
  1828. size_t d,
  1829. unsigned char w,
  1830. unsigned char *parity_trick)
  1831. {
  1832. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1833. mbedtls_mpi M, mm;
  1834. mbedtls_mpi_init(&M);
  1835. mbedtls_mpi_init(&mm);
  1836. /* N is always odd (see above), just make extra sure */
  1837. if (mbedtls_mpi_get_bit(&grp->N, 0) != 1) {
  1838. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  1839. }
  1840. /* do we need the parity trick? */
  1841. *parity_trick = (mbedtls_mpi_get_bit(m, 0) == 0);
  1842. /* execute parity fix in constant time */
  1843. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&M, m));
  1844. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&mm, &grp->N, m));
  1845. MBEDTLS_MPI_CHK(mbedtls_mpi_safe_cond_assign(&M, &mm, *parity_trick));
  1846. /* actual scalar recoding */
  1847. ecp_comb_recode_core(k, d, w, &M);
  1848. cleanup:
  1849. mbedtls_mpi_free(&mm);
  1850. mbedtls_mpi_free(&M);
  1851. return ret;
  1852. }
  1853. /*
  1854. * Perform comb multiplication (for short Weierstrass curves)
  1855. * once the auxiliary table has been pre-computed.
  1856. *
  1857. * Scalar recoding may use a parity trick that makes us compute -m * P,
  1858. * if that is the case we'll need to recover m * P at the end.
  1859. */
  1860. static int ecp_mul_comb_after_precomp(const mbedtls_ecp_group *grp,
  1861. mbedtls_ecp_point *R,
  1862. const mbedtls_mpi *m,
  1863. const mbedtls_ecp_point *T,
  1864. unsigned char T_size,
  1865. unsigned char w,
  1866. size_t d,
  1867. int (*f_rng)(void *, unsigned char *, size_t),
  1868. void *p_rng,
  1869. mbedtls_ecp_restart_ctx *rs_ctx)
  1870. {
  1871. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1872. unsigned char parity_trick;
  1873. unsigned char k[COMB_MAX_D + 1];
  1874. mbedtls_ecp_point *RR = R;
  1875. #if defined(MBEDTLS_ECP_RESTARTABLE)
  1876. if (rs_ctx != NULL && rs_ctx->rsm != NULL) {
  1877. RR = &rs_ctx->rsm->R;
  1878. if (rs_ctx->rsm->state == ecp_rsm_final_norm) {
  1879. goto final_norm;
  1880. }
  1881. }
  1882. #endif
  1883. MBEDTLS_MPI_CHK(ecp_comb_recode_scalar(grp, m, k, d, w,
  1884. &parity_trick));
  1885. MBEDTLS_MPI_CHK(ecp_mul_comb_core(grp, RR, T, T_size, k, d,
  1886. f_rng, p_rng, rs_ctx));
  1887. MBEDTLS_MPI_CHK(ecp_safe_invert_jac(grp, RR, parity_trick));
  1888. #if defined(MBEDTLS_ECP_RESTARTABLE)
  1889. if (rs_ctx != NULL && rs_ctx->rsm != NULL) {
  1890. rs_ctx->rsm->state = ecp_rsm_final_norm;
  1891. }
  1892. final_norm:
  1893. MBEDTLS_ECP_BUDGET(MBEDTLS_ECP_OPS_INV);
  1894. #endif
  1895. /*
  1896. * Knowledge of the jacobian coordinates may leak the last few bits of the
  1897. * scalar [1], and since our MPI implementation isn't constant-flow,
  1898. * inversion (used for coordinate normalization) may leak the full value
  1899. * of its input via side-channels [2].
  1900. *
  1901. * [1] https://eprint.iacr.org/2003/191
  1902. * [2] https://eprint.iacr.org/2020/055
  1903. *
  1904. * Avoid the leak by randomizing coordinates before we normalize them.
  1905. */
  1906. if (f_rng != 0) {
  1907. MBEDTLS_MPI_CHK(ecp_randomize_jac(grp, RR, f_rng, p_rng));
  1908. }
  1909. MBEDTLS_MPI_CHK(ecp_normalize_jac(grp, RR));
  1910. #if defined(MBEDTLS_ECP_RESTARTABLE)
  1911. if (rs_ctx != NULL && rs_ctx->rsm != NULL) {
  1912. MBEDTLS_MPI_CHK(mbedtls_ecp_copy(R, RR));
  1913. }
  1914. #endif
  1915. cleanup:
  1916. return ret;
  1917. }
  1918. /*
  1919. * Pick window size based on curve size and whether we optimize for base point
  1920. */
  1921. static unsigned char ecp_pick_window_size(const mbedtls_ecp_group *grp,
  1922. unsigned char p_eq_g)
  1923. {
  1924. unsigned char w;
  1925. /*
  1926. * Minimize the number of multiplications, that is minimize
  1927. * 10 * d * w + 18 * 2^(w-1) + 11 * d + 7 * w, with d = ceil( nbits / w )
  1928. * (see costs of the various parts, with 1S = 1M)
  1929. */
  1930. w = grp->nbits >= 384 ? 5 : 4;
  1931. /*
  1932. * If P == G, pre-compute a bit more, since this may be re-used later.
  1933. * Just adding one avoids upping the cost of the first mul too much,
  1934. * and the memory cost too.
  1935. */
  1936. if (p_eq_g) {
  1937. w++;
  1938. }
  1939. /*
  1940. * If static comb table may not be used (!p_eq_g) or static comb table does
  1941. * not exists, make sure w is within bounds.
  1942. * (The last test is useful only for very small curves in the test suite.)
  1943. *
  1944. * The user reduces MBEDTLS_ECP_WINDOW_SIZE does not changes the size of
  1945. * static comb table, because the size of static comb table is fixed when
  1946. * it is generated.
  1947. */
  1948. #if (MBEDTLS_ECP_WINDOW_SIZE < 6)
  1949. if ((!p_eq_g || !ecp_group_is_static_comb_table(grp)) && w > MBEDTLS_ECP_WINDOW_SIZE) {
  1950. w = MBEDTLS_ECP_WINDOW_SIZE;
  1951. }
  1952. #endif
  1953. if (w >= grp->nbits) {
  1954. w = 2;
  1955. }
  1956. return w;
  1957. }
  1958. /*
  1959. * Multiplication using the comb method - for curves in short Weierstrass form
  1960. *
  1961. * This function is mainly responsible for administrative work:
  1962. * - managing the restart context if enabled
  1963. * - managing the table of precomputed points (passed between the below two
  1964. * functions): allocation, computation, ownership transfer, freeing.
  1965. *
  1966. * It delegates the actual arithmetic work to:
  1967. * ecp_precompute_comb() and ecp_mul_comb_with_precomp()
  1968. *
  1969. * See comments on ecp_comb_recode_core() regarding the computation strategy.
  1970. */
  1971. static int ecp_mul_comb(mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
  1972. const mbedtls_mpi *m, const mbedtls_ecp_point *P,
  1973. int (*f_rng)(void *, unsigned char *, size_t),
  1974. void *p_rng,
  1975. mbedtls_ecp_restart_ctx *rs_ctx)
  1976. {
  1977. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  1978. unsigned char w, p_eq_g, i;
  1979. size_t d;
  1980. unsigned char T_size = 0, T_ok = 0;
  1981. mbedtls_ecp_point *T = NULL;
  1982. ECP_RS_ENTER(rsm);
  1983. /* Is P the base point ? */
  1984. #if MBEDTLS_ECP_FIXED_POINT_OPTIM == 1
  1985. p_eq_g = (MPI_ECP_CMP(&P->Y, &grp->G.Y) == 0 &&
  1986. MPI_ECP_CMP(&P->X, &grp->G.X) == 0);
  1987. #else
  1988. p_eq_g = 0;
  1989. #endif
  1990. /* Pick window size and deduce related sizes */
  1991. w = ecp_pick_window_size(grp, p_eq_g);
  1992. T_size = 1U << (w - 1);
  1993. d = (grp->nbits + w - 1) / w;
  1994. /* Pre-computed table: do we have it already for the base point? */
  1995. if (p_eq_g && grp->T != NULL) {
  1996. /* second pointer to the same table, will be deleted on exit */
  1997. T = grp->T;
  1998. T_ok = 1;
  1999. } else
  2000. #if defined(MBEDTLS_ECP_RESTARTABLE)
  2001. /* Pre-computed table: do we have one in progress? complete? */
  2002. if (rs_ctx != NULL && rs_ctx->rsm != NULL && rs_ctx->rsm->T != NULL) {
  2003. /* transfer ownership of T from rsm to local function */
  2004. T = rs_ctx->rsm->T;
  2005. rs_ctx->rsm->T = NULL;
  2006. rs_ctx->rsm->T_size = 0;
  2007. /* This effectively jumps to the call to mul_comb_after_precomp() */
  2008. T_ok = rs_ctx->rsm->state >= ecp_rsm_comb_core;
  2009. } else
  2010. #endif
  2011. /* Allocate table if we didn't have any */
  2012. {
  2013. T = mbedtls_calloc(T_size, sizeof(mbedtls_ecp_point));
  2014. if (T == NULL) {
  2015. ret = MBEDTLS_ERR_ECP_ALLOC_FAILED;
  2016. goto cleanup;
  2017. }
  2018. for (i = 0; i < T_size; i++) {
  2019. mbedtls_ecp_point_init(&T[i]);
  2020. }
  2021. T_ok = 0;
  2022. }
  2023. /* Compute table (or finish computing it) if not done already */
  2024. if (!T_ok) {
  2025. MBEDTLS_MPI_CHK(ecp_precompute_comb(grp, T, P, w, d, rs_ctx));
  2026. if (p_eq_g) {
  2027. /* almost transfer ownership of T to the group, but keep a copy of
  2028. * the pointer to use for calling the next function more easily */
  2029. grp->T = T;
  2030. grp->T_size = T_size;
  2031. }
  2032. }
  2033. /* Actual comb multiplication using precomputed points */
  2034. MBEDTLS_MPI_CHK(ecp_mul_comb_after_precomp(grp, R, m,
  2035. T, T_size, w, d,
  2036. f_rng, p_rng, rs_ctx));
  2037. cleanup:
  2038. /* does T belong to the group? */
  2039. if (T == grp->T) {
  2040. T = NULL;
  2041. }
  2042. /* does T belong to the restart context? */
  2043. #if defined(MBEDTLS_ECP_RESTARTABLE)
  2044. if (rs_ctx != NULL && rs_ctx->rsm != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS && T != NULL) {
  2045. /* transfer ownership of T from local function to rsm */
  2046. rs_ctx->rsm->T_size = T_size;
  2047. rs_ctx->rsm->T = T;
  2048. T = NULL;
  2049. }
  2050. #endif
  2051. /* did T belong to us? then let's destroy it! */
  2052. if (T != NULL) {
  2053. for (i = 0; i < T_size; i++) {
  2054. mbedtls_ecp_point_free(&T[i]);
  2055. }
  2056. mbedtls_free(T);
  2057. }
  2058. /* prevent caller from using invalid value */
  2059. int should_free_R = (ret != 0);
  2060. #if defined(MBEDTLS_ECP_RESTARTABLE)
  2061. /* don't free R while in progress in case R == P */
  2062. if (ret == MBEDTLS_ERR_ECP_IN_PROGRESS) {
  2063. should_free_R = 0;
  2064. }
  2065. #endif
  2066. if (should_free_R) {
  2067. mbedtls_ecp_point_free(R);
  2068. }
  2069. ECP_RS_LEAVE(rsm);
  2070. return ret;
  2071. }
  2072. #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
  2073. #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
  2074. /*
  2075. * For Montgomery curves, we do all the internal arithmetic in projective
  2076. * coordinates. Import/export of points uses only the x coordinates, which is
  2077. * internally represented as X / Z.
  2078. *
  2079. * For scalar multiplication, we'll use a Montgomery ladder.
  2080. */
  2081. /*
  2082. * Normalize Montgomery x/z coordinates: X = X/Z, Z = 1
  2083. * Cost: 1M + 1I
  2084. */
  2085. static int ecp_normalize_mxz(const mbedtls_ecp_group *grp, mbedtls_ecp_point *P)
  2086. {
  2087. #if defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT)
  2088. if (mbedtls_internal_ecp_grp_capable(grp)) {
  2089. return mbedtls_internal_ecp_normalize_mxz(grp, P);
  2090. }
  2091. #endif /* MBEDTLS_ECP_NORMALIZE_MXZ_ALT */
  2092. #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT)
  2093. return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
  2094. #else
  2095. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2096. MPI_ECP_INV(&P->Z, &P->Z);
  2097. MPI_ECP_MUL(&P->X, &P->X, &P->Z);
  2098. MPI_ECP_LSET(&P->Z, 1);
  2099. cleanup:
  2100. return ret;
  2101. #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT) */
  2102. }
  2103. /*
  2104. * Randomize projective x/z coordinates:
  2105. * (X, Z) -> (l X, l Z) for random l
  2106. * This is sort of the reverse operation of ecp_normalize_mxz().
  2107. *
  2108. * This countermeasure was first suggested in [2].
  2109. * Cost: 2M
  2110. */
  2111. static int ecp_randomize_mxz(const mbedtls_ecp_group *grp, mbedtls_ecp_point *P,
  2112. int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
  2113. {
  2114. #if defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT)
  2115. if (mbedtls_internal_ecp_grp_capable(grp)) {
  2116. return mbedtls_internal_ecp_randomize_mxz(grp, P, f_rng, p_rng);
  2117. }
  2118. #endif /* MBEDTLS_ECP_RANDOMIZE_MXZ_ALT */
  2119. #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT)
  2120. return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
  2121. #else
  2122. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2123. mbedtls_mpi l;
  2124. mbedtls_mpi_init(&l);
  2125. /* Generate l such that 1 < l < p */
  2126. MPI_ECP_RAND(&l);
  2127. MPI_ECP_MUL(&P->X, &P->X, &l);
  2128. MPI_ECP_MUL(&P->Z, &P->Z, &l);
  2129. cleanup:
  2130. mbedtls_mpi_free(&l);
  2131. if (ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) {
  2132. ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
  2133. }
  2134. return ret;
  2135. #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT) */
  2136. }
  2137. /*
  2138. * Double-and-add: R = 2P, S = P + Q, with d = X(P - Q),
  2139. * for Montgomery curves in x/z coordinates.
  2140. *
  2141. * http://www.hyperelliptic.org/EFD/g1p/auto-code/montgom/xz/ladder/mladd-1987-m.op3
  2142. * with
  2143. * d = X1
  2144. * P = (X2, Z2)
  2145. * Q = (X3, Z3)
  2146. * R = (X4, Z4)
  2147. * S = (X5, Z5)
  2148. * and eliminating temporary variables tO, ..., t4.
  2149. *
  2150. * Cost: 5M + 4S
  2151. */
  2152. static int ecp_double_add_mxz(const mbedtls_ecp_group *grp,
  2153. mbedtls_ecp_point *R, mbedtls_ecp_point *S,
  2154. const mbedtls_ecp_point *P, const mbedtls_ecp_point *Q,
  2155. const mbedtls_mpi *d,
  2156. mbedtls_mpi T[4])
  2157. {
  2158. #if defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT)
  2159. if (mbedtls_internal_ecp_grp_capable(grp)) {
  2160. return mbedtls_internal_ecp_double_add_mxz(grp, R, S, P, Q, d);
  2161. }
  2162. #endif /* MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT */
  2163. #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT)
  2164. return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
  2165. #else
  2166. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2167. MPI_ECP_ADD(&T[0], &P->X, &P->Z); /* Pp := PX + PZ */
  2168. MPI_ECP_SUB(&T[1], &P->X, &P->Z); /* Pm := PX - PZ */
  2169. MPI_ECP_ADD(&T[2], &Q->X, &Q->Z); /* Qp := QX + XZ */
  2170. MPI_ECP_SUB(&T[3], &Q->X, &Q->Z); /* Qm := QX - QZ */
  2171. MPI_ECP_MUL(&T[3], &T[3], &T[0]); /* Qm * Pp */
  2172. MPI_ECP_MUL(&T[2], &T[2], &T[1]); /* Qp * Pm */
  2173. MPI_ECP_SQR(&T[0], &T[0]); /* Pp^2 */
  2174. MPI_ECP_SQR(&T[1], &T[1]); /* Pm^2 */
  2175. MPI_ECP_MUL(&R->X, &T[0], &T[1]); /* Pp^2 * Pm^2 */
  2176. MPI_ECP_SUB(&T[0], &T[0], &T[1]); /* Pp^2 - Pm^2 */
  2177. MPI_ECP_MUL(&R->Z, &grp->A, &T[0]); /* A * (Pp^2 - Pm^2) */
  2178. MPI_ECP_ADD(&R->Z, &T[1], &R->Z); /* [ A * (Pp^2-Pm^2) ] + Pm^2 */
  2179. MPI_ECP_ADD(&S->X, &T[3], &T[2]); /* Qm*Pp + Qp*Pm */
  2180. MPI_ECP_SQR(&S->X, &S->X); /* (Qm*Pp + Qp*Pm)^2 */
  2181. MPI_ECP_SUB(&S->Z, &T[3], &T[2]); /* Qm*Pp - Qp*Pm */
  2182. MPI_ECP_SQR(&S->Z, &S->Z); /* (Qm*Pp - Qp*Pm)^2 */
  2183. MPI_ECP_MUL(&S->Z, d, &S->Z); /* d * ( Qm*Pp - Qp*Pm )^2 */
  2184. MPI_ECP_MUL(&R->Z, &T[0], &R->Z); /* [A*(Pp^2-Pm^2)+Pm^2]*(Pp^2-Pm^2) */
  2185. cleanup:
  2186. return ret;
  2187. #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT) */
  2188. }
  2189. /*
  2190. * Multiplication with Montgomery ladder in x/z coordinates,
  2191. * for curves in Montgomery form
  2192. */
  2193. static int ecp_mul_mxz(mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
  2194. const mbedtls_mpi *m, const mbedtls_ecp_point *P,
  2195. int (*f_rng)(void *, unsigned char *, size_t),
  2196. void *p_rng)
  2197. {
  2198. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2199. size_t i;
  2200. unsigned char b;
  2201. mbedtls_ecp_point RP;
  2202. mbedtls_mpi PX;
  2203. mbedtls_mpi tmp[4];
  2204. mbedtls_ecp_point_init(&RP); mbedtls_mpi_init(&PX);
  2205. mpi_init_many(tmp, sizeof(tmp) / sizeof(mbedtls_mpi));
  2206. if (f_rng == NULL) {
  2207. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  2208. }
  2209. /* Save PX and read from P before writing to R, in case P == R */
  2210. MPI_ECP_MOV(&PX, &P->X);
  2211. MBEDTLS_MPI_CHK(mbedtls_ecp_copy(&RP, P));
  2212. /* Set R to zero in modified x/z coordinates */
  2213. MPI_ECP_LSET(&R->X, 1);
  2214. MPI_ECP_LSET(&R->Z, 0);
  2215. mbedtls_mpi_free(&R->Y);
  2216. /* RP.X might be slightly larger than P, so reduce it */
  2217. MOD_ADD(&RP.X);
  2218. /* Randomize coordinates of the starting point */
  2219. MBEDTLS_MPI_CHK(ecp_randomize_mxz(grp, &RP, f_rng, p_rng));
  2220. /* Loop invariant: R = result so far, RP = R + P */
  2221. i = grp->nbits + 1; /* one past the (zero-based) required msb for private keys */
  2222. while (i-- > 0) {
  2223. b = mbedtls_mpi_get_bit(m, i);
  2224. /*
  2225. * if (b) R = 2R + P else R = 2R,
  2226. * which is:
  2227. * if (b) double_add( RP, R, RP, R )
  2228. * else double_add( R, RP, R, RP )
  2229. * but using safe conditional swaps to avoid leaks
  2230. */
  2231. MPI_ECP_COND_SWAP(&R->X, &RP.X, b);
  2232. MPI_ECP_COND_SWAP(&R->Z, &RP.Z, b);
  2233. MBEDTLS_MPI_CHK(ecp_double_add_mxz(grp, R, &RP, R, &RP, &PX, tmp));
  2234. MPI_ECP_COND_SWAP(&R->X, &RP.X, b);
  2235. MPI_ECP_COND_SWAP(&R->Z, &RP.Z, b);
  2236. }
  2237. /*
  2238. * Knowledge of the projective coordinates may leak the last few bits of the
  2239. * scalar [1], and since our MPI implementation isn't constant-flow,
  2240. * inversion (used for coordinate normalization) may leak the full value
  2241. * of its input via side-channels [2].
  2242. *
  2243. * [1] https://eprint.iacr.org/2003/191
  2244. * [2] https://eprint.iacr.org/2020/055
  2245. *
  2246. * Avoid the leak by randomizing coordinates before we normalize them.
  2247. */
  2248. MBEDTLS_MPI_CHK(ecp_randomize_mxz(grp, R, f_rng, p_rng));
  2249. MBEDTLS_MPI_CHK(ecp_normalize_mxz(grp, R));
  2250. cleanup:
  2251. mbedtls_ecp_point_free(&RP); mbedtls_mpi_free(&PX);
  2252. mpi_free_many(tmp, sizeof(tmp) / sizeof(mbedtls_mpi));
  2253. return ret;
  2254. }
  2255. #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
  2256. /*
  2257. * Restartable multiplication R = m * P
  2258. *
  2259. * This internal function can be called without an RNG in case where we know
  2260. * the inputs are not sensitive.
  2261. */
  2262. static int ecp_mul_restartable_internal(mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
  2263. const mbedtls_mpi *m, const mbedtls_ecp_point *P,
  2264. int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
  2265. mbedtls_ecp_restart_ctx *rs_ctx)
  2266. {
  2267. int ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  2268. #if defined(MBEDTLS_ECP_INTERNAL_ALT)
  2269. char is_grp_capable = 0;
  2270. #endif
  2271. #if defined(MBEDTLS_ECP_RESTARTABLE)
  2272. /* reset ops count for this call if top-level */
  2273. if (rs_ctx != NULL && rs_ctx->depth++ == 0) {
  2274. rs_ctx->ops_done = 0;
  2275. }
  2276. #else
  2277. (void) rs_ctx;
  2278. #endif
  2279. #if defined(MBEDTLS_ECP_INTERNAL_ALT)
  2280. if ((is_grp_capable = mbedtls_internal_ecp_grp_capable(grp))) {
  2281. MBEDTLS_MPI_CHK(mbedtls_internal_ecp_init(grp));
  2282. }
  2283. #endif /* MBEDTLS_ECP_INTERNAL_ALT */
  2284. int restarting = 0;
  2285. #if defined(MBEDTLS_ECP_RESTARTABLE)
  2286. restarting = (rs_ctx != NULL && rs_ctx->rsm != NULL);
  2287. #endif
  2288. /* skip argument check when restarting */
  2289. if (!restarting) {
  2290. /* check_privkey is free */
  2291. MBEDTLS_ECP_BUDGET(MBEDTLS_ECP_OPS_CHK);
  2292. /* Common sanity checks */
  2293. MBEDTLS_MPI_CHK(mbedtls_ecp_check_privkey(grp, m));
  2294. MBEDTLS_MPI_CHK(mbedtls_ecp_check_pubkey(grp, P));
  2295. }
  2296. ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  2297. #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
  2298. if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
  2299. MBEDTLS_MPI_CHK(ecp_mul_mxz(grp, R, m, P, f_rng, p_rng));
  2300. }
  2301. #endif
  2302. #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
  2303. if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
  2304. MBEDTLS_MPI_CHK(ecp_mul_comb(grp, R, m, P, f_rng, p_rng, rs_ctx));
  2305. }
  2306. #endif
  2307. cleanup:
  2308. #if defined(MBEDTLS_ECP_INTERNAL_ALT)
  2309. if (is_grp_capable) {
  2310. mbedtls_internal_ecp_free(grp);
  2311. }
  2312. #endif /* MBEDTLS_ECP_INTERNAL_ALT */
  2313. #if defined(MBEDTLS_ECP_RESTARTABLE)
  2314. if (rs_ctx != NULL) {
  2315. rs_ctx->depth--;
  2316. }
  2317. #endif
  2318. return ret;
  2319. }
  2320. /*
  2321. * Restartable multiplication R = m * P
  2322. */
  2323. int mbedtls_ecp_mul_restartable(mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
  2324. const mbedtls_mpi *m, const mbedtls_ecp_point *P,
  2325. int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
  2326. mbedtls_ecp_restart_ctx *rs_ctx)
  2327. {
  2328. if (f_rng == NULL) {
  2329. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  2330. }
  2331. return ecp_mul_restartable_internal(grp, R, m, P, f_rng, p_rng, rs_ctx);
  2332. }
  2333. /*
  2334. * Multiplication R = m * P
  2335. */
  2336. int mbedtls_ecp_mul(mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
  2337. const mbedtls_mpi *m, const mbedtls_ecp_point *P,
  2338. int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
  2339. {
  2340. return mbedtls_ecp_mul_restartable(grp, R, m, P, f_rng, p_rng, NULL);
  2341. }
  2342. #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
  2343. /*
  2344. * Check that an affine point is valid as a public key,
  2345. * short weierstrass curves (SEC1 3.2.3.1)
  2346. */
  2347. static int ecp_check_pubkey_sw(const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt)
  2348. {
  2349. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2350. mbedtls_mpi YY, RHS;
  2351. /* pt coordinates must be normalized for our checks */
  2352. if (mbedtls_mpi_cmp_int(&pt->X, 0) < 0 ||
  2353. mbedtls_mpi_cmp_int(&pt->Y, 0) < 0 ||
  2354. mbedtls_mpi_cmp_mpi(&pt->X, &grp->P) >= 0 ||
  2355. mbedtls_mpi_cmp_mpi(&pt->Y, &grp->P) >= 0) {
  2356. return MBEDTLS_ERR_ECP_INVALID_KEY;
  2357. }
  2358. mbedtls_mpi_init(&YY); mbedtls_mpi_init(&RHS);
  2359. /*
  2360. * YY = Y^2
  2361. * RHS = X^3 + A X + B
  2362. */
  2363. MPI_ECP_SQR(&YY, &pt->Y);
  2364. MBEDTLS_MPI_CHK(ecp_sw_rhs(grp, &RHS, &pt->X));
  2365. if (MPI_ECP_CMP(&YY, &RHS) != 0) {
  2366. ret = MBEDTLS_ERR_ECP_INVALID_KEY;
  2367. }
  2368. cleanup:
  2369. mbedtls_mpi_free(&YY); mbedtls_mpi_free(&RHS);
  2370. return ret;
  2371. }
  2372. #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
  2373. #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
  2374. /*
  2375. * R = m * P with shortcuts for m == 0, m == 1 and m == -1
  2376. * NOT constant-time - ONLY for short Weierstrass!
  2377. */
  2378. static int mbedtls_ecp_mul_shortcuts(mbedtls_ecp_group *grp,
  2379. mbedtls_ecp_point *R,
  2380. const mbedtls_mpi *m,
  2381. const mbedtls_ecp_point *P,
  2382. mbedtls_ecp_restart_ctx *rs_ctx)
  2383. {
  2384. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2385. mbedtls_mpi tmp;
  2386. mbedtls_mpi_init(&tmp);
  2387. if (mbedtls_mpi_cmp_int(m, 0) == 0) {
  2388. MBEDTLS_MPI_CHK(mbedtls_ecp_check_pubkey(grp, P));
  2389. MBEDTLS_MPI_CHK(mbedtls_ecp_set_zero(R));
  2390. } else if (mbedtls_mpi_cmp_int(m, 1) == 0) {
  2391. MBEDTLS_MPI_CHK(mbedtls_ecp_check_pubkey(grp, P));
  2392. MBEDTLS_MPI_CHK(mbedtls_ecp_copy(R, P));
  2393. } else if (mbedtls_mpi_cmp_int(m, -1) == 0) {
  2394. MBEDTLS_MPI_CHK(mbedtls_ecp_check_pubkey(grp, P));
  2395. MBEDTLS_MPI_CHK(mbedtls_ecp_copy(R, P));
  2396. MPI_ECP_NEG(&R->Y);
  2397. } else {
  2398. MBEDTLS_MPI_CHK(ecp_mul_restartable_internal(grp, R, m, P,
  2399. NULL, NULL, rs_ctx));
  2400. }
  2401. cleanup:
  2402. mbedtls_mpi_free(&tmp);
  2403. return ret;
  2404. }
  2405. /*
  2406. * Restartable linear combination
  2407. * NOT constant-time
  2408. */
  2409. int mbedtls_ecp_muladd_restartable(
  2410. mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
  2411. const mbedtls_mpi *m, const mbedtls_ecp_point *P,
  2412. const mbedtls_mpi *n, const mbedtls_ecp_point *Q,
  2413. mbedtls_ecp_restart_ctx *rs_ctx)
  2414. {
  2415. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2416. mbedtls_ecp_point mP;
  2417. mbedtls_ecp_point *pmP = &mP;
  2418. mbedtls_ecp_point *pR = R;
  2419. mbedtls_mpi tmp[4];
  2420. #if defined(MBEDTLS_ECP_INTERNAL_ALT)
  2421. char is_grp_capable = 0;
  2422. #endif
  2423. if (mbedtls_ecp_get_type(grp) != MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
  2424. return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
  2425. }
  2426. mbedtls_ecp_point_init(&mP);
  2427. mpi_init_many(tmp, sizeof(tmp) / sizeof(mbedtls_mpi));
  2428. ECP_RS_ENTER(ma);
  2429. #if defined(MBEDTLS_ECP_RESTARTABLE)
  2430. if (rs_ctx != NULL && rs_ctx->ma != NULL) {
  2431. /* redirect intermediate results to restart context */
  2432. pmP = &rs_ctx->ma->mP;
  2433. pR = &rs_ctx->ma->R;
  2434. /* jump to next operation */
  2435. if (rs_ctx->ma->state == ecp_rsma_mul2) {
  2436. goto mul2;
  2437. }
  2438. if (rs_ctx->ma->state == ecp_rsma_add) {
  2439. goto add;
  2440. }
  2441. if (rs_ctx->ma->state == ecp_rsma_norm) {
  2442. goto norm;
  2443. }
  2444. }
  2445. #endif /* MBEDTLS_ECP_RESTARTABLE */
  2446. MBEDTLS_MPI_CHK(mbedtls_ecp_mul_shortcuts(grp, pmP, m, P, rs_ctx));
  2447. #if defined(MBEDTLS_ECP_RESTARTABLE)
  2448. if (rs_ctx != NULL && rs_ctx->ma != NULL) {
  2449. rs_ctx->ma->state = ecp_rsma_mul2;
  2450. }
  2451. mul2:
  2452. #endif
  2453. MBEDTLS_MPI_CHK(mbedtls_ecp_mul_shortcuts(grp, pR, n, Q, rs_ctx));
  2454. #if defined(MBEDTLS_ECP_INTERNAL_ALT)
  2455. if ((is_grp_capable = mbedtls_internal_ecp_grp_capable(grp))) {
  2456. MBEDTLS_MPI_CHK(mbedtls_internal_ecp_init(grp));
  2457. }
  2458. #endif /* MBEDTLS_ECP_INTERNAL_ALT */
  2459. #if defined(MBEDTLS_ECP_RESTARTABLE)
  2460. if (rs_ctx != NULL && rs_ctx->ma != NULL) {
  2461. rs_ctx->ma->state = ecp_rsma_add;
  2462. }
  2463. add:
  2464. #endif
  2465. MBEDTLS_ECP_BUDGET(MBEDTLS_ECP_OPS_ADD);
  2466. MBEDTLS_MPI_CHK(ecp_add_mixed(grp, pR, pmP, pR, tmp));
  2467. #if defined(MBEDTLS_ECP_RESTARTABLE)
  2468. if (rs_ctx != NULL && rs_ctx->ma != NULL) {
  2469. rs_ctx->ma->state = ecp_rsma_norm;
  2470. }
  2471. norm:
  2472. #endif
  2473. MBEDTLS_ECP_BUDGET(MBEDTLS_ECP_OPS_INV);
  2474. MBEDTLS_MPI_CHK(ecp_normalize_jac(grp, pR));
  2475. #if defined(MBEDTLS_ECP_RESTARTABLE)
  2476. if (rs_ctx != NULL && rs_ctx->ma != NULL) {
  2477. MBEDTLS_MPI_CHK(mbedtls_ecp_copy(R, pR));
  2478. }
  2479. #endif
  2480. cleanup:
  2481. mpi_free_many(tmp, sizeof(tmp) / sizeof(mbedtls_mpi));
  2482. #if defined(MBEDTLS_ECP_INTERNAL_ALT)
  2483. if (is_grp_capable) {
  2484. mbedtls_internal_ecp_free(grp);
  2485. }
  2486. #endif /* MBEDTLS_ECP_INTERNAL_ALT */
  2487. mbedtls_ecp_point_free(&mP);
  2488. ECP_RS_LEAVE(ma);
  2489. return ret;
  2490. }
  2491. /*
  2492. * Linear combination
  2493. * NOT constant-time
  2494. */
  2495. int mbedtls_ecp_muladd(mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
  2496. const mbedtls_mpi *m, const mbedtls_ecp_point *P,
  2497. const mbedtls_mpi *n, const mbedtls_ecp_point *Q)
  2498. {
  2499. return mbedtls_ecp_muladd_restartable(grp, R, m, P, n, Q, NULL);
  2500. }
  2501. #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
  2502. #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
  2503. #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
  2504. #define ECP_MPI_INIT(s, n, p) { s, (n), (mbedtls_mpi_uint *) (p) }
  2505. #define ECP_MPI_INIT_ARRAY(x) \
  2506. ECP_MPI_INIT(1, sizeof(x) / sizeof(mbedtls_mpi_uint), x)
  2507. /*
  2508. * Constants for the two points other than 0, 1, -1 (mod p) in
  2509. * https://cr.yp.to/ecdh.html#validate
  2510. * See ecp_check_pubkey_x25519().
  2511. */
  2512. static const mbedtls_mpi_uint x25519_bad_point_1[] = {
  2513. MBEDTLS_BYTES_TO_T_UINT_8(0xe0, 0xeb, 0x7a, 0x7c, 0x3b, 0x41, 0xb8, 0xae),
  2514. MBEDTLS_BYTES_TO_T_UINT_8(0x16, 0x56, 0xe3, 0xfa, 0xf1, 0x9f, 0xc4, 0x6a),
  2515. MBEDTLS_BYTES_TO_T_UINT_8(0xda, 0x09, 0x8d, 0xeb, 0x9c, 0x32, 0xb1, 0xfd),
  2516. MBEDTLS_BYTES_TO_T_UINT_8(0x86, 0x62, 0x05, 0x16, 0x5f, 0x49, 0xb8, 0x00),
  2517. };
  2518. static const mbedtls_mpi_uint x25519_bad_point_2[] = {
  2519. MBEDTLS_BYTES_TO_T_UINT_8(0x5f, 0x9c, 0x95, 0xbc, 0xa3, 0x50, 0x8c, 0x24),
  2520. MBEDTLS_BYTES_TO_T_UINT_8(0xb1, 0xd0, 0xb1, 0x55, 0x9c, 0x83, 0xef, 0x5b),
  2521. MBEDTLS_BYTES_TO_T_UINT_8(0x04, 0x44, 0x5c, 0xc4, 0x58, 0x1c, 0x8e, 0x86),
  2522. MBEDTLS_BYTES_TO_T_UINT_8(0xd8, 0x22, 0x4e, 0xdd, 0xd0, 0x9f, 0x11, 0x57),
  2523. };
  2524. static const mbedtls_mpi ecp_x25519_bad_point_1 = ECP_MPI_INIT_ARRAY(
  2525. x25519_bad_point_1);
  2526. static const mbedtls_mpi ecp_x25519_bad_point_2 = ECP_MPI_INIT_ARRAY(
  2527. x25519_bad_point_2);
  2528. #endif /* MBEDTLS_ECP_DP_CURVE25519_ENABLED */
  2529. /*
  2530. * Check that the input point is not one of the low-order points.
  2531. * This is recommended by the "May the Fourth" paper:
  2532. * https://eprint.iacr.org/2017/806.pdf
  2533. * Those points are never sent by an honest peer.
  2534. */
  2535. static int ecp_check_bad_points_mx(const mbedtls_mpi *X, const mbedtls_mpi *P,
  2536. const mbedtls_ecp_group_id grp_id)
  2537. {
  2538. int ret;
  2539. mbedtls_mpi XmP;
  2540. mbedtls_mpi_init(&XmP);
  2541. /* Reduce X mod P so that we only need to check values less than P.
  2542. * We know X < 2^256 so we can proceed by subtraction. */
  2543. MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&XmP, X));
  2544. while (mbedtls_mpi_cmp_mpi(&XmP, P) >= 0) {
  2545. MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&XmP, &XmP, P));
  2546. }
  2547. /* Check against the known bad values that are less than P. For Curve448
  2548. * these are 0, 1 and -1. For Curve25519 we check the values less than P
  2549. * from the following list: https://cr.yp.to/ecdh.html#validate */
  2550. if (mbedtls_mpi_cmp_int(&XmP, 1) <= 0) { /* takes care of 0 and 1 */
  2551. ret = MBEDTLS_ERR_ECP_INVALID_KEY;
  2552. goto cleanup;
  2553. }
  2554. #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
  2555. if (grp_id == MBEDTLS_ECP_DP_CURVE25519) {
  2556. if (mbedtls_mpi_cmp_mpi(&XmP, &ecp_x25519_bad_point_1) == 0) {
  2557. ret = MBEDTLS_ERR_ECP_INVALID_KEY;
  2558. goto cleanup;
  2559. }
  2560. if (mbedtls_mpi_cmp_mpi(&XmP, &ecp_x25519_bad_point_2) == 0) {
  2561. ret = MBEDTLS_ERR_ECP_INVALID_KEY;
  2562. goto cleanup;
  2563. }
  2564. }
  2565. #else
  2566. (void) grp_id;
  2567. #endif
  2568. /* Final check: check if XmP + 1 is P (final because it changes XmP!) */
  2569. MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(&XmP, &XmP, 1));
  2570. if (mbedtls_mpi_cmp_mpi(&XmP, P) == 0) {
  2571. ret = MBEDTLS_ERR_ECP_INVALID_KEY;
  2572. goto cleanup;
  2573. }
  2574. ret = 0;
  2575. cleanup:
  2576. mbedtls_mpi_free(&XmP);
  2577. return ret;
  2578. }
  2579. /*
  2580. * Check validity of a public key for Montgomery curves with x-only schemes
  2581. */
  2582. static int ecp_check_pubkey_mx(const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt)
  2583. {
  2584. /* [Curve25519 p. 5] Just check X is the correct number of bytes */
  2585. /* Allow any public value, if it's too big then we'll just reduce it mod p
  2586. * (RFC 7748 sec. 5 para. 3). */
  2587. if (mbedtls_mpi_size(&pt->X) > (grp->nbits + 7) / 8) {
  2588. return MBEDTLS_ERR_ECP_INVALID_KEY;
  2589. }
  2590. /* Implicit in all standards (as they don't consider negative numbers):
  2591. * X must be non-negative. This is normally ensured by the way it's
  2592. * encoded for transmission, but let's be extra sure. */
  2593. if (mbedtls_mpi_cmp_int(&pt->X, 0) < 0) {
  2594. return MBEDTLS_ERR_ECP_INVALID_KEY;
  2595. }
  2596. return ecp_check_bad_points_mx(&pt->X, &grp->P, grp->id);
  2597. }
  2598. #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
  2599. /*
  2600. * Check that a point is valid as a public key
  2601. */
  2602. int mbedtls_ecp_check_pubkey(const mbedtls_ecp_group *grp,
  2603. const mbedtls_ecp_point *pt)
  2604. {
  2605. /* Must use affine coordinates */
  2606. if (mbedtls_mpi_cmp_int(&pt->Z, 1) != 0) {
  2607. return MBEDTLS_ERR_ECP_INVALID_KEY;
  2608. }
  2609. #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
  2610. if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
  2611. return ecp_check_pubkey_mx(grp, pt);
  2612. }
  2613. #endif
  2614. #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
  2615. if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
  2616. return ecp_check_pubkey_sw(grp, pt);
  2617. }
  2618. #endif
  2619. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  2620. }
  2621. /*
  2622. * Check that an mbedtls_mpi is valid as a private key
  2623. */
  2624. int mbedtls_ecp_check_privkey(const mbedtls_ecp_group *grp,
  2625. const mbedtls_mpi *d)
  2626. {
  2627. #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
  2628. if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
  2629. /* see RFC 7748 sec. 5 para. 5 */
  2630. if (mbedtls_mpi_get_bit(d, 0) != 0 ||
  2631. mbedtls_mpi_get_bit(d, 1) != 0 ||
  2632. mbedtls_mpi_bitlen(d) - 1 != grp->nbits) { /* mbedtls_mpi_bitlen is one-based! */
  2633. return MBEDTLS_ERR_ECP_INVALID_KEY;
  2634. }
  2635. /* see [Curve25519] page 5 */
  2636. if (grp->nbits == 254 && mbedtls_mpi_get_bit(d, 2) != 0) {
  2637. return MBEDTLS_ERR_ECP_INVALID_KEY;
  2638. }
  2639. return 0;
  2640. }
  2641. #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
  2642. #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
  2643. if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
  2644. /* see SEC1 3.2 */
  2645. if (mbedtls_mpi_cmp_int(d, 1) < 0 ||
  2646. mbedtls_mpi_cmp_mpi(d, &grp->N) >= 0) {
  2647. return MBEDTLS_ERR_ECP_INVALID_KEY;
  2648. } else {
  2649. return 0;
  2650. }
  2651. }
  2652. #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
  2653. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  2654. }
  2655. #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
  2656. MBEDTLS_STATIC_TESTABLE
  2657. int mbedtls_ecp_gen_privkey_mx(size_t high_bit,
  2658. mbedtls_mpi *d,
  2659. int (*f_rng)(void *, unsigned char *, size_t),
  2660. void *p_rng)
  2661. {
  2662. int ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  2663. size_t n_random_bytes = high_bit / 8 + 1;
  2664. /* [Curve25519] page 5 */
  2665. /* Generate a (high_bit+1)-bit random number by generating just enough
  2666. * random bytes, then shifting out extra bits from the top (necessary
  2667. * when (high_bit+1) is not a multiple of 8). */
  2668. MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(d, n_random_bytes,
  2669. f_rng, p_rng));
  2670. MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(d, 8 * n_random_bytes - high_bit - 1));
  2671. MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(d, high_bit, 1));
  2672. /* Make sure the last two bits are unset for Curve448, three bits for
  2673. Curve25519 */
  2674. MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(d, 0, 0));
  2675. MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(d, 1, 0));
  2676. if (high_bit == 254) {
  2677. MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(d, 2, 0));
  2678. }
  2679. cleanup:
  2680. return ret;
  2681. }
  2682. #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
  2683. #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
  2684. static int mbedtls_ecp_gen_privkey_sw(
  2685. const mbedtls_mpi *N, mbedtls_mpi *d,
  2686. int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
  2687. {
  2688. int ret = mbedtls_mpi_random(d, 1, N, f_rng, p_rng);
  2689. switch (ret) {
  2690. case MBEDTLS_ERR_MPI_NOT_ACCEPTABLE:
  2691. return MBEDTLS_ERR_ECP_RANDOM_FAILED;
  2692. default:
  2693. return ret;
  2694. }
  2695. }
  2696. #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
  2697. /*
  2698. * Generate a private key
  2699. */
  2700. int mbedtls_ecp_gen_privkey(const mbedtls_ecp_group *grp,
  2701. mbedtls_mpi *d,
  2702. int (*f_rng)(void *, unsigned char *, size_t),
  2703. void *p_rng)
  2704. {
  2705. #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
  2706. if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
  2707. return mbedtls_ecp_gen_privkey_mx(grp->nbits, d, f_rng, p_rng);
  2708. }
  2709. #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
  2710. #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
  2711. if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
  2712. return mbedtls_ecp_gen_privkey_sw(&grp->N, d, f_rng, p_rng);
  2713. }
  2714. #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
  2715. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  2716. }
  2717. /*
  2718. * Generate a keypair with configurable base point
  2719. */
  2720. int mbedtls_ecp_gen_keypair_base(mbedtls_ecp_group *grp,
  2721. const mbedtls_ecp_point *G,
  2722. mbedtls_mpi *d, mbedtls_ecp_point *Q,
  2723. int (*f_rng)(void *, unsigned char *, size_t),
  2724. void *p_rng)
  2725. {
  2726. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2727. MBEDTLS_MPI_CHK(mbedtls_ecp_gen_privkey(grp, d, f_rng, p_rng));
  2728. MBEDTLS_MPI_CHK(mbedtls_ecp_mul(grp, Q, d, G, f_rng, p_rng));
  2729. cleanup:
  2730. return ret;
  2731. }
  2732. /*
  2733. * Generate key pair, wrapper for conventional base point
  2734. */
  2735. int mbedtls_ecp_gen_keypair(mbedtls_ecp_group *grp,
  2736. mbedtls_mpi *d, mbedtls_ecp_point *Q,
  2737. int (*f_rng)(void *, unsigned char *, size_t),
  2738. void *p_rng)
  2739. {
  2740. return mbedtls_ecp_gen_keypair_base(grp, &grp->G, d, Q, f_rng, p_rng);
  2741. }
  2742. /*
  2743. * Generate a keypair, prettier wrapper
  2744. */
  2745. int mbedtls_ecp_gen_key(mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key,
  2746. int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
  2747. {
  2748. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2749. if ((ret = mbedtls_ecp_group_load(&key->grp, grp_id)) != 0) {
  2750. return ret;
  2751. }
  2752. return mbedtls_ecp_gen_keypair(&key->grp, &key->d, &key->Q, f_rng, p_rng);
  2753. }
  2754. #define ECP_CURVE25519_KEY_SIZE 32
  2755. #define ECP_CURVE448_KEY_SIZE 56
  2756. /*
  2757. * Read a private key.
  2758. */
  2759. int mbedtls_ecp_read_key(mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key,
  2760. const unsigned char *buf, size_t buflen)
  2761. {
  2762. int ret = 0;
  2763. if ((ret = mbedtls_ecp_group_load(&key->grp, grp_id)) != 0) {
  2764. return ret;
  2765. }
  2766. ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
  2767. #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
  2768. if (mbedtls_ecp_get_type(&key->grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
  2769. /*
  2770. * Mask the key as mandated by RFC7748 for Curve25519 and Curve448.
  2771. */
  2772. if (grp_id == MBEDTLS_ECP_DP_CURVE25519) {
  2773. if (buflen != ECP_CURVE25519_KEY_SIZE) {
  2774. return MBEDTLS_ERR_ECP_INVALID_KEY;
  2775. }
  2776. MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary_le(&key->d, buf, buflen));
  2777. /* Set the three least significant bits to 0 */
  2778. MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(&key->d, 0, 0));
  2779. MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(&key->d, 1, 0));
  2780. MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(&key->d, 2, 0));
  2781. /* Set the most significant bit to 0 */
  2782. MBEDTLS_MPI_CHK(
  2783. mbedtls_mpi_set_bit(&key->d,
  2784. ECP_CURVE25519_KEY_SIZE * 8 - 1, 0)
  2785. );
  2786. /* Set the second most significant bit to 1 */
  2787. MBEDTLS_MPI_CHK(
  2788. mbedtls_mpi_set_bit(&key->d,
  2789. ECP_CURVE25519_KEY_SIZE * 8 - 2, 1)
  2790. );
  2791. } else if (grp_id == MBEDTLS_ECP_DP_CURVE448) {
  2792. if (buflen != ECP_CURVE448_KEY_SIZE) {
  2793. return MBEDTLS_ERR_ECP_INVALID_KEY;
  2794. }
  2795. MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary_le(&key->d, buf, buflen));
  2796. /* Set the two least significant bits to 0 */
  2797. MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(&key->d, 0, 0));
  2798. MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(&key->d, 1, 0));
  2799. /* Set the most significant bit to 1 */
  2800. MBEDTLS_MPI_CHK(
  2801. mbedtls_mpi_set_bit(&key->d,
  2802. ECP_CURVE448_KEY_SIZE * 8 - 1, 1)
  2803. );
  2804. }
  2805. }
  2806. #endif
  2807. #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
  2808. if (mbedtls_ecp_get_type(&key->grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
  2809. MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&key->d, buf, buflen));
  2810. MBEDTLS_MPI_CHK(mbedtls_ecp_check_privkey(&key->grp, &key->d));
  2811. }
  2812. #endif
  2813. cleanup:
  2814. if (ret != 0) {
  2815. mbedtls_mpi_free(&key->d);
  2816. }
  2817. return ret;
  2818. }
  2819. /*
  2820. * Write a private key.
  2821. */
  2822. int mbedtls_ecp_write_key(mbedtls_ecp_keypair *key,
  2823. unsigned char *buf, size_t buflen)
  2824. {
  2825. int ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
  2826. #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
  2827. if (mbedtls_ecp_get_type(&key->grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
  2828. if (key->grp.id == MBEDTLS_ECP_DP_CURVE25519) {
  2829. if (buflen < ECP_CURVE25519_KEY_SIZE) {
  2830. return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
  2831. }
  2832. } else if (key->grp.id == MBEDTLS_ECP_DP_CURVE448) {
  2833. if (buflen < ECP_CURVE448_KEY_SIZE) {
  2834. return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
  2835. }
  2836. }
  2837. MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary_le(&key->d, buf, buflen));
  2838. }
  2839. #endif
  2840. #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
  2841. if (mbedtls_ecp_get_type(&key->grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
  2842. MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&key->d, buf, buflen));
  2843. }
  2844. #endif
  2845. cleanup:
  2846. return ret;
  2847. }
  2848. /*
  2849. * Check a public-private key pair
  2850. */
  2851. int mbedtls_ecp_check_pub_priv(
  2852. const mbedtls_ecp_keypair *pub, const mbedtls_ecp_keypair *prv,
  2853. int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
  2854. {
  2855. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2856. mbedtls_ecp_point Q;
  2857. mbedtls_ecp_group grp;
  2858. if (pub->grp.id == MBEDTLS_ECP_DP_NONE ||
  2859. pub->grp.id != prv->grp.id ||
  2860. mbedtls_mpi_cmp_mpi(&pub->Q.X, &prv->Q.X) ||
  2861. mbedtls_mpi_cmp_mpi(&pub->Q.Y, &prv->Q.Y) ||
  2862. mbedtls_mpi_cmp_mpi(&pub->Q.Z, &prv->Q.Z)) {
  2863. return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  2864. }
  2865. mbedtls_ecp_point_init(&Q);
  2866. mbedtls_ecp_group_init(&grp);
  2867. /* mbedtls_ecp_mul() needs a non-const group... */
  2868. mbedtls_ecp_group_copy(&grp, &prv->grp);
  2869. /* Also checks d is valid */
  2870. MBEDTLS_MPI_CHK(mbedtls_ecp_mul(&grp, &Q, &prv->d, &prv->grp.G, f_rng, p_rng));
  2871. if (mbedtls_mpi_cmp_mpi(&Q.X, &prv->Q.X) ||
  2872. mbedtls_mpi_cmp_mpi(&Q.Y, &prv->Q.Y) ||
  2873. mbedtls_mpi_cmp_mpi(&Q.Z, &prv->Q.Z)) {
  2874. ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
  2875. goto cleanup;
  2876. }
  2877. cleanup:
  2878. mbedtls_ecp_point_free(&Q);
  2879. mbedtls_ecp_group_free(&grp);
  2880. return ret;
  2881. }
  2882. /*
  2883. * Export generic key-pair parameters.
  2884. */
  2885. int mbedtls_ecp_export(const mbedtls_ecp_keypair *key, mbedtls_ecp_group *grp,
  2886. mbedtls_mpi *d, mbedtls_ecp_point *Q)
  2887. {
  2888. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  2889. if ((ret = mbedtls_ecp_group_copy(grp, &key->grp)) != 0) {
  2890. return ret;
  2891. }
  2892. if ((ret = mbedtls_mpi_copy(d, &key->d)) != 0) {
  2893. return ret;
  2894. }
  2895. if ((ret = mbedtls_ecp_copy(Q, &key->Q)) != 0) {
  2896. return ret;
  2897. }
  2898. return 0;
  2899. }
  2900. #if defined(MBEDTLS_SELF_TEST)
  2901. /*
  2902. * PRNG for test - !!!INSECURE NEVER USE IN PRODUCTION!!!
  2903. *
  2904. * This is the linear congruential generator from numerical recipes,
  2905. * except we only use the low byte as the output. See
  2906. * https://en.wikipedia.org/wiki/Linear_congruential_generator#Parameters_in_common_use
  2907. */
  2908. static int self_test_rng(void *ctx, unsigned char *out, size_t len)
  2909. {
  2910. static uint32_t state = 42;
  2911. (void) ctx;
  2912. for (size_t i = 0; i < len; i++) {
  2913. state = state * 1664525u + 1013904223u;
  2914. out[i] = (unsigned char) state;
  2915. }
  2916. return 0;
  2917. }
  2918. /* Adjust the exponent to be a valid private point for the specified curve.
  2919. * This is sometimes necessary because we use a single set of exponents
  2920. * for all curves but the validity of values depends on the curve. */
  2921. static int self_test_adjust_exponent(const mbedtls_ecp_group *grp,
  2922. mbedtls_mpi *m)
  2923. {
  2924. int ret = 0;
  2925. switch (grp->id) {
  2926. /* If Curve25519 is available, then that's what we use for the
  2927. * Montgomery test, so we don't need the adjustment code. */
  2928. #if !defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
  2929. #if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)
  2930. case MBEDTLS_ECP_DP_CURVE448:
  2931. /* Move highest bit from 254 to N-1. Setting bit N-1 is
  2932. * necessary to enforce the highest-bit-set constraint. */
  2933. MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(m, 254, 0));
  2934. MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(m, grp->nbits, 1));
  2935. /* Copy second-highest bit from 253 to N-2. This is not
  2936. * necessary but improves the test variety a bit. */
  2937. MBEDTLS_MPI_CHK(
  2938. mbedtls_mpi_set_bit(m, grp->nbits - 1,
  2939. mbedtls_mpi_get_bit(m, 253)));
  2940. break;
  2941. #endif
  2942. #endif /* ! defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) */
  2943. default:
  2944. /* Non-Montgomery curves and Curve25519 need no adjustment. */
  2945. (void) grp;
  2946. (void) m;
  2947. goto cleanup;
  2948. }
  2949. cleanup:
  2950. return ret;
  2951. }
  2952. /* Calculate R = m.P for each m in exponents. Check that the number of
  2953. * basic operations doesn't depend on the value of m. */
  2954. static int self_test_point(int verbose,
  2955. mbedtls_ecp_group *grp,
  2956. mbedtls_ecp_point *R,
  2957. mbedtls_mpi *m,
  2958. const mbedtls_ecp_point *P,
  2959. const char *const *exponents,
  2960. size_t n_exponents)
  2961. {
  2962. int ret = 0;
  2963. size_t i = 0;
  2964. unsigned long add_c_prev, dbl_c_prev, mul_c_prev;
  2965. add_count = 0;
  2966. dbl_count = 0;
  2967. mul_count = 0;
  2968. MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(m, 16, exponents[0]));
  2969. MBEDTLS_MPI_CHK(self_test_adjust_exponent(grp, m));
  2970. MBEDTLS_MPI_CHK(mbedtls_ecp_mul(grp, R, m, P, self_test_rng, NULL));
  2971. for (i = 1; i < n_exponents; i++) {
  2972. add_c_prev = add_count;
  2973. dbl_c_prev = dbl_count;
  2974. mul_c_prev = mul_count;
  2975. add_count = 0;
  2976. dbl_count = 0;
  2977. mul_count = 0;
  2978. MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(m, 16, exponents[i]));
  2979. MBEDTLS_MPI_CHK(self_test_adjust_exponent(grp, m));
  2980. MBEDTLS_MPI_CHK(mbedtls_ecp_mul(grp, R, m, P, self_test_rng, NULL));
  2981. if (add_count != add_c_prev ||
  2982. dbl_count != dbl_c_prev ||
  2983. mul_count != mul_c_prev) {
  2984. ret = 1;
  2985. break;
  2986. }
  2987. }
  2988. cleanup:
  2989. if (verbose != 0) {
  2990. if (ret != 0) {
  2991. mbedtls_printf("failed (%u)\n", (unsigned int) i);
  2992. } else {
  2993. mbedtls_printf("passed\n");
  2994. }
  2995. }
  2996. return ret;
  2997. }
  2998. /*
  2999. * Checkup routine
  3000. */
  3001. int mbedtls_ecp_self_test(int verbose)
  3002. {
  3003. int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
  3004. mbedtls_ecp_group grp;
  3005. mbedtls_ecp_point R, P;
  3006. mbedtls_mpi m;
  3007. #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
  3008. /* Exponents especially adapted for secp192k1, which has the lowest
  3009. * order n of all supported curves (secp192r1 is in a slightly larger
  3010. * field but the order of its base point is slightly smaller). */
  3011. const char *sw_exponents[] =
  3012. {
  3013. "000000000000000000000000000000000000000000000001", /* one */
  3014. "FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8C", /* n - 1 */
  3015. "5EA6F389A38B8BC81E767753B15AA5569E1782E30ABE7D25", /* random */
  3016. "400000000000000000000000000000000000000000000000", /* one and zeros */
  3017. "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", /* all ones */
  3018. "555555555555555555555555555555555555555555555555", /* 101010... */
  3019. };
  3020. #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
  3021. #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
  3022. const char *m_exponents[] =
  3023. {
  3024. /* Valid private values for Curve25519. In a build with Curve448
  3025. * but not Curve25519, they will be adjusted in
  3026. * self_test_adjust_exponent(). */
  3027. "4000000000000000000000000000000000000000000000000000000000000000",
  3028. "5C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C30",
  3029. "5715ECCE24583F7A7023C24164390586842E816D7280A49EF6DF4EAE6B280BF8",
  3030. "41A2B017516F6D254E1F002BCCBADD54BE30F8CEC737A0E912B4963B6BA74460",
  3031. "5555555555555555555555555555555555555555555555555555555555555550",
  3032. "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8",
  3033. };
  3034. #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
  3035. mbedtls_ecp_group_init(&grp);
  3036. mbedtls_ecp_point_init(&R);
  3037. mbedtls_ecp_point_init(&P);
  3038. mbedtls_mpi_init(&m);
  3039. #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
  3040. /* Use secp192r1 if available, or any available curve */
  3041. #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)
  3042. MBEDTLS_MPI_CHK(mbedtls_ecp_group_load(&grp, MBEDTLS_ECP_DP_SECP192R1));
  3043. #else
  3044. MBEDTLS_MPI_CHK(mbedtls_ecp_group_load(&grp, mbedtls_ecp_curve_list()->grp_id));
  3045. #endif
  3046. if (verbose != 0) {
  3047. mbedtls_printf(" ECP SW test #1 (constant op_count, base point G): ");
  3048. }
  3049. /* Do a dummy multiplication first to trigger precomputation */
  3050. MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&m, 2));
  3051. MBEDTLS_MPI_CHK(mbedtls_ecp_mul(&grp, &P, &m, &grp.G, self_test_rng, NULL));
  3052. ret = self_test_point(verbose,
  3053. &grp, &R, &m, &grp.G,
  3054. sw_exponents,
  3055. sizeof(sw_exponents) / sizeof(sw_exponents[0]));
  3056. if (ret != 0) {
  3057. goto cleanup;
  3058. }
  3059. if (verbose != 0) {
  3060. mbedtls_printf(" ECP SW test #2 (constant op_count, other point): ");
  3061. }
  3062. /* We computed P = 2G last time, use it */
  3063. ret = self_test_point(verbose,
  3064. &grp, &R, &m, &P,
  3065. sw_exponents,
  3066. sizeof(sw_exponents) / sizeof(sw_exponents[0]));
  3067. if (ret != 0) {
  3068. goto cleanup;
  3069. }
  3070. mbedtls_ecp_group_free(&grp);
  3071. mbedtls_ecp_point_free(&R);
  3072. #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
  3073. #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
  3074. if (verbose != 0) {
  3075. mbedtls_printf(" ECP Montgomery test (constant op_count): ");
  3076. }
  3077. #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
  3078. MBEDTLS_MPI_CHK(mbedtls_ecp_group_load(&grp, MBEDTLS_ECP_DP_CURVE25519));
  3079. #elif defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)
  3080. MBEDTLS_MPI_CHK(mbedtls_ecp_group_load(&grp, MBEDTLS_ECP_DP_CURVE448));
  3081. #else
  3082. #error "MBEDTLS_ECP_MONTGOMERY_ENABLED is defined, but no curve is supported for self-test"
  3083. #endif
  3084. ret = self_test_point(verbose,
  3085. &grp, &R, &m, &grp.G,
  3086. m_exponents,
  3087. sizeof(m_exponents) / sizeof(m_exponents[0]));
  3088. if (ret != 0) {
  3089. goto cleanup;
  3090. }
  3091. #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
  3092. cleanup:
  3093. if (ret < 0 && verbose != 0) {
  3094. mbedtls_printf("Unexpected error, return code = %08X\n", (unsigned int) ret);
  3095. }
  3096. mbedtls_ecp_group_free(&grp);
  3097. mbedtls_ecp_point_free(&R);
  3098. mbedtls_ecp_point_free(&P);
  3099. mbedtls_mpi_free(&m);
  3100. if (verbose != 0) {
  3101. mbedtls_printf("\n");
  3102. }
  3103. return ret;
  3104. }
  3105. #endif /* MBEDTLS_SELF_TEST */
  3106. #endif /* !MBEDTLS_ECP_ALT */
  3107. #endif /* MBEDTLS_ECP_C */