ecp.c 116 KB

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