ecp.c 114 KB

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