ecp.c 115 KB

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