ecp.c 107 KB

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