ecp.c 111 KB

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