ecp.c 112 KB

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