ecp.c 119 KB

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