ecp.c 111 KB

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