hs_descriptor.c 105 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108
  1. /* Copyright (c) 2016-2019, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file hs_descriptor.c
  5. * \brief Handle hidden service descriptor encoding/decoding.
  6. *
  7. * \details
  8. * Here is a graphical depiction of an HS descriptor and its layers:
  9. *
  10. * +------------------------------------------------------+
  11. * |DESCRIPTOR HEADER: |
  12. * | hs-descriptor 3 |
  13. * | descriptor-lifetime 180 |
  14. * | ... |
  15. * | superencrypted |
  16. * |+---------------------------------------------------+ |
  17. * ||SUPERENCRYPTED LAYER (aka OUTER ENCRYPTED LAYER): | |
  18. * || desc-auth-type x25519 | |
  19. * || desc-auth-ephemeral-key | |
  20. * || auth-client | |
  21. * || auth-client | |
  22. * || ... | |
  23. * || encrypted | |
  24. * ||+-------------------------------------------------+| |
  25. * |||ENCRYPTED LAYER (aka INNER ENCRYPTED LAYER): || |
  26. * ||| create2-formats || |
  27. * ||| intro-auth-required || |
  28. * ||| introduction-point || |
  29. * ||| introduction-point || |
  30. * ||| ... || |
  31. * ||+-------------------------------------------------+| |
  32. * |+---------------------------------------------------+ |
  33. * +------------------------------------------------------+
  34. *
  35. * The DESCRIPTOR HEADER section is completely unencrypted and contains generic
  36. * descriptor metadata.
  37. *
  38. * The SUPERENCRYPTED LAYER section is the first layer of encryption, and it's
  39. * encrypted using the blinded public key of the hidden service to protect
  40. * against entities who don't know its onion address. The clients of the hidden
  41. * service know its onion address and blinded public key, whereas third-parties
  42. * (like HSDirs) don't know it (except if it's a public hidden service).
  43. *
  44. * The ENCRYPTED LAYER section is the second layer of encryption, and it's
  45. * encrypted using the client authorization key material (if those exist). When
  46. * client authorization is enabled, this second layer of encryption protects
  47. * the descriptor content from unauthorized entities. If client authorization
  48. * is disabled, this second layer of encryption does not provide any extra
  49. * security but is still present. The plaintext of this layer contains all the
  50. * information required to connect to the hidden service like its list of
  51. * introduction points.
  52. **/
  53. /* For unit tests.*/
  54. #define HS_DESCRIPTOR_PRIVATE
  55. #include "core/or/or.h"
  56. #include "trunnel/ed25519_cert.h" /* Trunnel interface. */
  57. #include "feature/hs/hs_descriptor.h"
  58. #include "core/or/circuitbuild.h"
  59. #include "lib/crypt_ops/crypto_rand.h"
  60. #include "lib/crypt_ops/crypto_util.h"
  61. #include "feature/dirparse/parsecommon.h"
  62. #include "feature/rend/rendcache.h"
  63. #include "feature/hs/hs_cache.h"
  64. #include "feature/hs/hs_config.h"
  65. #include "feature/nodelist/torcert.h" /* tor_cert_encode_ed22519() */
  66. #include "lib/memarea/memarea.h"
  67. #include "lib/crypt_ops/crypto_format.h"
  68. #include "core/or/extend_info_st.h"
  69. /* Constant string value used for the descriptor format. */
  70. #define str_hs_desc "hs-descriptor"
  71. #define str_desc_cert "descriptor-signing-key-cert"
  72. #define str_rev_counter "revision-counter"
  73. #define str_superencrypted "superencrypted"
  74. #define str_encrypted "encrypted"
  75. #define str_signature "signature"
  76. #define str_lifetime "descriptor-lifetime"
  77. /* Constant string value for the encrypted part of the descriptor. */
  78. #define str_create2_formats "create2-formats"
  79. #define str_intro_auth_required "intro-auth-required"
  80. #define str_single_onion "single-onion-service"
  81. #define str_intro_point "introduction-point"
  82. #define str_ip_onion_key "onion-key"
  83. #define str_ip_auth_key "auth-key"
  84. #define str_ip_enc_key "enc-key"
  85. #define str_ip_enc_key_cert "enc-key-cert"
  86. #define str_ip_legacy_key "legacy-key"
  87. #define str_ip_legacy_key_cert "legacy-key-cert"
  88. #define str_intro_point_start "\n" str_intro_point " "
  89. /* Constant string value for the construction to encrypt the encrypted data
  90. * section. */
  91. #define str_enc_const_superencryption "hsdir-superencrypted-data"
  92. #define str_enc_const_encryption "hsdir-encrypted-data"
  93. /* Prefix required to compute/verify HS desc signatures */
  94. #define str_desc_sig_prefix "Tor onion service descriptor sig v3"
  95. #define str_desc_auth_type "desc-auth-type"
  96. #define str_desc_auth_key "desc-auth-ephemeral-key"
  97. #define str_desc_auth_client "auth-client"
  98. #define str_encrypted "encrypted"
  99. /* Authentication supported types. */
  100. static const struct {
  101. hs_desc_auth_type_t type;
  102. const char *identifier;
  103. } intro_auth_types[] = {
  104. { HS_DESC_AUTH_ED25519, "ed25519" },
  105. /* Indicate end of array. */
  106. { 0, NULL }
  107. };
  108. /* Descriptor ruleset. */
  109. static token_rule_t hs_desc_v3_token_table[] = {
  110. T1_START(str_hs_desc, R_HS_DESCRIPTOR, EQ(1), NO_OBJ),
  111. T1(str_lifetime, R3_DESC_LIFETIME, EQ(1), NO_OBJ),
  112. T1(str_desc_cert, R3_DESC_SIGNING_CERT, NO_ARGS, NEED_OBJ),
  113. T1(str_rev_counter, R3_REVISION_COUNTER, EQ(1), NO_OBJ),
  114. T1(str_superencrypted, R3_SUPERENCRYPTED, NO_ARGS, NEED_OBJ),
  115. T1_END(str_signature, R3_SIGNATURE, EQ(1), NO_OBJ),
  116. END_OF_TABLE
  117. };
  118. /* Descriptor ruleset for the superencrypted section. */
  119. static token_rule_t hs_desc_superencrypted_v3_token_table[] = {
  120. T1_START(str_desc_auth_type, R3_DESC_AUTH_TYPE, GE(1), NO_OBJ),
  121. T1(str_desc_auth_key, R3_DESC_AUTH_KEY, GE(1), NO_OBJ),
  122. T1N(str_desc_auth_client, R3_DESC_AUTH_CLIENT, GE(3), NO_OBJ),
  123. T1(str_encrypted, R3_ENCRYPTED, NO_ARGS, NEED_OBJ),
  124. END_OF_TABLE
  125. };
  126. /* Descriptor ruleset for the encrypted section. */
  127. static token_rule_t hs_desc_encrypted_v3_token_table[] = {
  128. T1_START(str_create2_formats, R3_CREATE2_FORMATS, CONCAT_ARGS, NO_OBJ),
  129. T01(str_intro_auth_required, R3_INTRO_AUTH_REQUIRED, ARGS, NO_OBJ),
  130. T01(str_single_onion, R3_SINGLE_ONION_SERVICE, ARGS, NO_OBJ),
  131. END_OF_TABLE
  132. };
  133. /* Descriptor ruleset for the introduction points section. */
  134. static token_rule_t hs_desc_intro_point_v3_token_table[] = {
  135. T1_START(str_intro_point, R3_INTRODUCTION_POINT, EQ(1), NO_OBJ),
  136. T1N(str_ip_onion_key, R3_INTRO_ONION_KEY, GE(2), OBJ_OK),
  137. T1(str_ip_auth_key, R3_INTRO_AUTH_KEY, NO_ARGS, NEED_OBJ),
  138. T1(str_ip_enc_key, R3_INTRO_ENC_KEY, GE(2), OBJ_OK),
  139. T1(str_ip_enc_key_cert, R3_INTRO_ENC_KEY_CERT, ARGS, OBJ_OK),
  140. T01(str_ip_legacy_key, R3_INTRO_LEGACY_KEY, ARGS, NEED_KEY_1024),
  141. T01(str_ip_legacy_key_cert, R3_INTRO_LEGACY_KEY_CERT, ARGS, OBJ_OK),
  142. END_OF_TABLE
  143. };
  144. /* Using a key, salt and encrypted payload, build a MAC and put it in mac_out.
  145. * We use SHA3-256 for the MAC computation.
  146. * This function can't fail. */
  147. static void
  148. build_mac(const uint8_t *mac_key, size_t mac_key_len,
  149. const uint8_t *salt, size_t salt_len,
  150. const uint8_t *encrypted, size_t encrypted_len,
  151. uint8_t *mac_out, size_t mac_len)
  152. {
  153. crypto_digest_t *digest;
  154. const uint64_t mac_len_netorder = tor_htonll(mac_key_len);
  155. const uint64_t salt_len_netorder = tor_htonll(salt_len);
  156. tor_assert(mac_key);
  157. tor_assert(salt);
  158. tor_assert(encrypted);
  159. tor_assert(mac_out);
  160. digest = crypto_digest256_new(DIGEST_SHA3_256);
  161. /* As specified in section 2.5 of proposal 224, first add the mac key
  162. * then add the salt first and then the encrypted section. */
  163. crypto_digest_add_bytes(digest, (const char *) &mac_len_netorder, 8);
  164. crypto_digest_add_bytes(digest, (const char *) mac_key, mac_key_len);
  165. crypto_digest_add_bytes(digest, (const char *) &salt_len_netorder, 8);
  166. crypto_digest_add_bytes(digest, (const char *) salt, salt_len);
  167. crypto_digest_add_bytes(digest, (const char *) encrypted, encrypted_len);
  168. crypto_digest_get_digest(digest, (char *) mac_out, mac_len);
  169. crypto_digest_free(digest);
  170. }
  171. /* Using a secret data and a given decriptor object, build the secret
  172. * input needed for the KDF.
  173. *
  174. * secret_input = SECRET_DATA | subcredential | INT_8(revision_counter)
  175. *
  176. * Then, set the newly allocated buffer in secret_input_out and return the
  177. * length of the buffer. */
  178. static size_t
  179. build_secret_input(const hs_descriptor_t *desc,
  180. const uint8_t *secret_data,
  181. size_t secret_data_len,
  182. uint8_t **secret_input_out)
  183. {
  184. size_t offset = 0;
  185. size_t secret_input_len = secret_data_len + DIGEST256_LEN + sizeof(uint64_t);
  186. uint8_t *secret_input = NULL;
  187. tor_assert(desc);
  188. tor_assert(secret_data);
  189. tor_assert(secret_input_out);
  190. secret_input = tor_malloc_zero(secret_input_len);
  191. /* Copy the secret data. */
  192. memcpy(secret_input, secret_data, secret_data_len);
  193. offset += secret_data_len;
  194. /* Copy subcredential. */
  195. memcpy(secret_input + offset, desc->subcredential, DIGEST256_LEN);
  196. offset += DIGEST256_LEN;
  197. /* Copy revision counter value. */
  198. set_uint64(secret_input + offset,
  199. tor_htonll(desc->plaintext_data.revision_counter));
  200. offset += sizeof(uint64_t);
  201. tor_assert(secret_input_len == offset);
  202. *secret_input_out = secret_input;
  203. return secret_input_len;
  204. }
  205. /* Do the KDF construction and put the resulting data in key_out which is of
  206. * key_out_len length. It uses SHAKE-256 as specified in the spec. */
  207. static void
  208. build_kdf_key(const hs_descriptor_t *desc,
  209. const uint8_t *secret_data,
  210. size_t secret_data_len,
  211. const uint8_t *salt, size_t salt_len,
  212. uint8_t *key_out, size_t key_out_len,
  213. int is_superencrypted_layer)
  214. {
  215. uint8_t *secret_input = NULL;
  216. size_t secret_input_len;
  217. crypto_xof_t *xof;
  218. tor_assert(desc);
  219. tor_assert(secret_data);
  220. tor_assert(salt);
  221. tor_assert(key_out);
  222. /* Build the secret input for the KDF computation. */
  223. secret_input_len = build_secret_input(desc, secret_data,
  224. secret_data_len, &secret_input);
  225. xof = crypto_xof_new();
  226. /* Feed our KDF. [SHAKE it like a polaroid picture --Yawning]. */
  227. crypto_xof_add_bytes(xof, secret_input, secret_input_len);
  228. crypto_xof_add_bytes(xof, salt, salt_len);
  229. /* Feed in the right string constant based on the desc layer */
  230. if (is_superencrypted_layer) {
  231. crypto_xof_add_bytes(xof, (const uint8_t *) str_enc_const_superencryption,
  232. strlen(str_enc_const_superencryption));
  233. } else {
  234. crypto_xof_add_bytes(xof, (const uint8_t *) str_enc_const_encryption,
  235. strlen(str_enc_const_encryption));
  236. }
  237. /* Eat from our KDF. */
  238. crypto_xof_squeeze_bytes(xof, key_out, key_out_len);
  239. crypto_xof_free(xof);
  240. memwipe(secret_input, 0, secret_input_len);
  241. tor_free(secret_input);
  242. }
  243. /* Using the given descriptor, secret data, and salt, run it through our
  244. * KDF function and then extract a secret key in key_out, the IV in iv_out
  245. * and MAC in mac_out. This function can't fail. */
  246. static void
  247. build_secret_key_iv_mac(const hs_descriptor_t *desc,
  248. const uint8_t *secret_data,
  249. size_t secret_data_len,
  250. const uint8_t *salt, size_t salt_len,
  251. uint8_t *key_out, size_t key_len,
  252. uint8_t *iv_out, size_t iv_len,
  253. uint8_t *mac_out, size_t mac_len,
  254. int is_superencrypted_layer)
  255. {
  256. size_t offset = 0;
  257. uint8_t kdf_key[HS_DESC_ENCRYPTED_KDF_OUTPUT_LEN];
  258. tor_assert(desc);
  259. tor_assert(secret_data);
  260. tor_assert(salt);
  261. tor_assert(key_out);
  262. tor_assert(iv_out);
  263. tor_assert(mac_out);
  264. build_kdf_key(desc, secret_data, secret_data_len,
  265. salt, salt_len, kdf_key, sizeof(kdf_key),
  266. is_superencrypted_layer);
  267. /* Copy the bytes we need for both the secret key and IV. */
  268. memcpy(key_out, kdf_key, key_len);
  269. offset += key_len;
  270. memcpy(iv_out, kdf_key + offset, iv_len);
  271. offset += iv_len;
  272. memcpy(mac_out, kdf_key + offset, mac_len);
  273. /* Extra precaution to make sure we are not out of bound. */
  274. tor_assert((offset + mac_len) == sizeof(kdf_key));
  275. memwipe(kdf_key, 0, sizeof(kdf_key));
  276. }
  277. /* === ENCODING === */
  278. /* Encode the given link specifier objects into a newly allocated string.
  279. * This can't fail so caller can always assume a valid string being
  280. * returned. */
  281. STATIC char *
  282. encode_link_specifiers(const smartlist_t *specs)
  283. {
  284. char *encoded_b64 = NULL;
  285. link_specifier_list_t *lslist = link_specifier_list_new();
  286. tor_assert(specs);
  287. /* No link specifiers is a code flow error, can't happen. */
  288. tor_assert(smartlist_len(specs) > 0);
  289. tor_assert(smartlist_len(specs) <= UINT8_MAX);
  290. link_specifier_list_set_n_spec(lslist, smartlist_len(specs));
  291. SMARTLIST_FOREACH_BEGIN(specs, const hs_desc_link_specifier_t *,
  292. spec) {
  293. link_specifier_t *ls = hs_desc_lspec_to_trunnel(spec);
  294. if (ls) {
  295. link_specifier_list_add_spec(lslist, ls);
  296. }
  297. } SMARTLIST_FOREACH_END(spec);
  298. {
  299. uint8_t *encoded;
  300. ssize_t encoded_len, encoded_b64_len, ret;
  301. encoded_len = link_specifier_list_encoded_len(lslist);
  302. tor_assert(encoded_len > 0);
  303. encoded = tor_malloc_zero(encoded_len);
  304. ret = link_specifier_list_encode(encoded, encoded_len, lslist);
  305. tor_assert(ret == encoded_len);
  306. /* Base64 encode our binary format. Add extra NUL byte for the base64
  307. * encoded value. */
  308. encoded_b64_len = base64_encode_size(encoded_len, 0) + 1;
  309. encoded_b64 = tor_malloc_zero(encoded_b64_len);
  310. ret = base64_encode(encoded_b64, encoded_b64_len, (const char *) encoded,
  311. encoded_len, 0);
  312. tor_assert(ret == (encoded_b64_len - 1));
  313. tor_free(encoded);
  314. }
  315. link_specifier_list_free(lslist);
  316. return encoded_b64;
  317. }
  318. /* Encode an introduction point legacy key and certificate. Return a newly
  319. * allocated string with it. On failure, return NULL. */
  320. static char *
  321. encode_legacy_key(const hs_desc_intro_point_t *ip)
  322. {
  323. char *key_str, b64_cert[256], *encoded = NULL;
  324. size_t key_str_len;
  325. tor_assert(ip);
  326. /* Encode cross cert. */
  327. if (base64_encode(b64_cert, sizeof(b64_cert),
  328. (const char *) ip->legacy.cert.encoded,
  329. ip->legacy.cert.len, BASE64_ENCODE_MULTILINE) < 0) {
  330. log_warn(LD_REND, "Unable to encode legacy crosscert.");
  331. goto done;
  332. }
  333. /* Convert the encryption key to PEM format NUL terminated. */
  334. if (crypto_pk_write_public_key_to_string(ip->legacy.key, &key_str,
  335. &key_str_len) < 0) {
  336. log_warn(LD_REND, "Unable to encode legacy encryption key.");
  337. goto done;
  338. }
  339. tor_asprintf(&encoded,
  340. "%s \n%s" /* Newline is added by the call above. */
  341. "%s\n"
  342. "-----BEGIN CROSSCERT-----\n"
  343. "%s"
  344. "-----END CROSSCERT-----",
  345. str_ip_legacy_key, key_str,
  346. str_ip_legacy_key_cert, b64_cert);
  347. tor_free(key_str);
  348. done:
  349. return encoded;
  350. }
  351. /* Encode an introduction point encryption key and certificate. Return a newly
  352. * allocated string with it. On failure, return NULL. */
  353. static char *
  354. encode_enc_key(const hs_desc_intro_point_t *ip)
  355. {
  356. char *encoded = NULL, *encoded_cert;
  357. char key_b64[CURVE25519_BASE64_PADDED_LEN + 1];
  358. tor_assert(ip);
  359. /* Base64 encode the encryption key for the "enc-key" field. */
  360. if (curve25519_public_to_base64(key_b64, &ip->enc_key) < 0) {
  361. goto done;
  362. }
  363. if (tor_cert_encode_ed22519(ip->enc_key_cert, &encoded_cert) < 0) {
  364. goto done;
  365. }
  366. tor_asprintf(&encoded,
  367. "%s ntor %s\n"
  368. "%s\n%s",
  369. str_ip_enc_key, key_b64,
  370. str_ip_enc_key_cert, encoded_cert);
  371. tor_free(encoded_cert);
  372. done:
  373. return encoded;
  374. }
  375. /* Encode an introduction point onion key. Return a newly allocated string
  376. * with it. On failure, return NULL. */
  377. static char *
  378. encode_onion_key(const hs_desc_intro_point_t *ip)
  379. {
  380. char *encoded = NULL;
  381. char key_b64[CURVE25519_BASE64_PADDED_LEN + 1];
  382. tor_assert(ip);
  383. /* Base64 encode the encryption key for the "onion-key" field. */
  384. if (curve25519_public_to_base64(key_b64, &ip->onion_key) < 0) {
  385. goto done;
  386. }
  387. tor_asprintf(&encoded, "%s ntor %s", str_ip_onion_key, key_b64);
  388. done:
  389. return encoded;
  390. }
  391. /* Encode an introduction point object and return a newly allocated string
  392. * with it. On failure, return NULL. */
  393. static char *
  394. encode_intro_point(const ed25519_public_key_t *sig_key,
  395. const hs_desc_intro_point_t *ip)
  396. {
  397. char *encoded_ip = NULL;
  398. smartlist_t *lines = smartlist_new();
  399. tor_assert(ip);
  400. tor_assert(sig_key);
  401. /* Encode link specifier. */
  402. {
  403. char *ls_str = encode_link_specifiers(ip->link_specifiers);
  404. smartlist_add_asprintf(lines, "%s %s", str_intro_point, ls_str);
  405. tor_free(ls_str);
  406. }
  407. /* Onion key encoding. */
  408. {
  409. char *encoded_onion_key = encode_onion_key(ip);
  410. if (encoded_onion_key == NULL) {
  411. goto err;
  412. }
  413. smartlist_add_asprintf(lines, "%s", encoded_onion_key);
  414. tor_free(encoded_onion_key);
  415. }
  416. /* Authentication key encoding. */
  417. {
  418. char *encoded_cert;
  419. if (tor_cert_encode_ed22519(ip->auth_key_cert, &encoded_cert) < 0) {
  420. goto err;
  421. }
  422. smartlist_add_asprintf(lines, "%s\n%s", str_ip_auth_key, encoded_cert);
  423. tor_free(encoded_cert);
  424. }
  425. /* Encryption key encoding. */
  426. {
  427. char *encoded_enc_key = encode_enc_key(ip);
  428. if (encoded_enc_key == NULL) {
  429. goto err;
  430. }
  431. smartlist_add_asprintf(lines, "%s", encoded_enc_key);
  432. tor_free(encoded_enc_key);
  433. }
  434. /* Legacy key if any. */
  435. if (ip->legacy.key != NULL) {
  436. /* Strong requirement else the IP creation was badly done. */
  437. tor_assert(ip->legacy.cert.encoded);
  438. char *encoded_legacy_key = encode_legacy_key(ip);
  439. if (encoded_legacy_key == NULL) {
  440. goto err;
  441. }
  442. smartlist_add_asprintf(lines, "%s", encoded_legacy_key);
  443. tor_free(encoded_legacy_key);
  444. }
  445. /* Join them all in one blob of text. */
  446. encoded_ip = smartlist_join_strings(lines, "\n", 1, NULL);
  447. err:
  448. SMARTLIST_FOREACH(lines, char *, l, tor_free(l));
  449. smartlist_free(lines);
  450. return encoded_ip;
  451. }
  452. /* Given a source length, return the new size including padding for the
  453. * plaintext encryption. */
  454. static size_t
  455. compute_padded_plaintext_length(size_t plaintext_len)
  456. {
  457. size_t plaintext_padded_len;
  458. const int padding_block_length = HS_DESC_SUPERENC_PLAINTEXT_PAD_MULTIPLE;
  459. /* Make sure we won't overflow. */
  460. tor_assert(plaintext_len <= (SIZE_T_CEILING - padding_block_length));
  461. /* Get the extra length we need to add. For example, if srclen is 10200
  462. * bytes, this will expand to (2 * 10k) == 20k thus an extra 9800 bytes. */
  463. plaintext_padded_len = CEIL_DIV(plaintext_len, padding_block_length) *
  464. padding_block_length;
  465. /* Can never be extra careful. Make sure we are _really_ padded. */
  466. tor_assert(!(plaintext_padded_len % padding_block_length));
  467. return plaintext_padded_len;
  468. }
  469. /* Given a buffer, pad it up to the encrypted section padding requirement. Set
  470. * the newly allocated string in padded_out and return the length of the
  471. * padded buffer. */
  472. STATIC size_t
  473. build_plaintext_padding(const char *plaintext, size_t plaintext_len,
  474. uint8_t **padded_out)
  475. {
  476. size_t padded_len;
  477. uint8_t *padded;
  478. tor_assert(plaintext);
  479. tor_assert(padded_out);
  480. /* Allocate the final length including padding. */
  481. padded_len = compute_padded_plaintext_length(plaintext_len);
  482. tor_assert(padded_len >= plaintext_len);
  483. padded = tor_malloc_zero(padded_len);
  484. memcpy(padded, plaintext, plaintext_len);
  485. *padded_out = padded;
  486. return padded_len;
  487. }
  488. /* Using a key, IV and plaintext data of length plaintext_len, create the
  489. * encrypted section by encrypting it and setting encrypted_out with the
  490. * data. Return size of the encrypted data buffer. */
  491. static size_t
  492. build_encrypted(const uint8_t *key, const uint8_t *iv, const char *plaintext,
  493. size_t plaintext_len, uint8_t **encrypted_out,
  494. int is_superencrypted_layer)
  495. {
  496. size_t encrypted_len;
  497. uint8_t *padded_plaintext, *encrypted;
  498. crypto_cipher_t *cipher;
  499. tor_assert(key);
  500. tor_assert(iv);
  501. tor_assert(plaintext);
  502. tor_assert(encrypted_out);
  503. /* If we are encrypting the middle layer of the descriptor, we need to first
  504. pad the plaintext */
  505. if (is_superencrypted_layer) {
  506. encrypted_len = build_plaintext_padding(plaintext, plaintext_len,
  507. &padded_plaintext);
  508. /* Extra precautions that we have a valid padding length. */
  509. tor_assert(!(encrypted_len % HS_DESC_SUPERENC_PLAINTEXT_PAD_MULTIPLE));
  510. } else { /* No padding required for inner layers */
  511. padded_plaintext = tor_memdup(plaintext, plaintext_len);
  512. encrypted_len = plaintext_len;
  513. }
  514. /* This creates a cipher for AES. It can't fail. */
  515. cipher = crypto_cipher_new_with_iv_and_bits(key, iv,
  516. HS_DESC_ENCRYPTED_BIT_SIZE);
  517. /* We use a stream cipher so the encrypted length will be the same as the
  518. * plaintext padded length. */
  519. encrypted = tor_malloc_zero(encrypted_len);
  520. /* This can't fail. */
  521. crypto_cipher_encrypt(cipher, (char *) encrypted,
  522. (const char *) padded_plaintext, encrypted_len);
  523. *encrypted_out = encrypted;
  524. /* Cleanup. */
  525. crypto_cipher_free(cipher);
  526. tor_free(padded_plaintext);
  527. return encrypted_len;
  528. }
  529. /* Encrypt the given <b>plaintext</b> buffer using <b>desc</b> and
  530. * <b>secret_data</b> to get the keys. Set encrypted_out with the encrypted
  531. * data and return the length of it. <b>is_superencrypted_layer</b> is set
  532. * if this is the outer encrypted layer of the descriptor. */
  533. static size_t
  534. encrypt_descriptor_data(const hs_descriptor_t *desc,
  535. const uint8_t *secret_data,
  536. size_t secret_data_len,
  537. const char *plaintext,
  538. char **encrypted_out, int is_superencrypted_layer)
  539. {
  540. char *final_blob;
  541. size_t encrypted_len, final_blob_len, offset = 0;
  542. uint8_t *encrypted;
  543. uint8_t salt[HS_DESC_ENCRYPTED_SALT_LEN];
  544. uint8_t secret_key[HS_DESC_ENCRYPTED_KEY_LEN], secret_iv[CIPHER_IV_LEN];
  545. uint8_t mac_key[DIGEST256_LEN], mac[DIGEST256_LEN];
  546. tor_assert(desc);
  547. tor_assert(secret_data);
  548. tor_assert(plaintext);
  549. tor_assert(encrypted_out);
  550. /* Get our salt. The returned bytes are already hashed. */
  551. crypto_strongest_rand(salt, sizeof(salt));
  552. /* KDF construction resulting in a key from which the secret key, IV and MAC
  553. * key are extracted which is what we need for the encryption. */
  554. build_secret_key_iv_mac(desc, secret_data, secret_data_len,
  555. salt, sizeof(salt),
  556. secret_key, sizeof(secret_key),
  557. secret_iv, sizeof(secret_iv),
  558. mac_key, sizeof(mac_key),
  559. is_superencrypted_layer);
  560. /* Build the encrypted part that is do the actual encryption. */
  561. encrypted_len = build_encrypted(secret_key, secret_iv, plaintext,
  562. strlen(plaintext), &encrypted,
  563. is_superencrypted_layer);
  564. memwipe(secret_key, 0, sizeof(secret_key));
  565. memwipe(secret_iv, 0, sizeof(secret_iv));
  566. /* This construction is specified in section 2.5 of proposal 224. */
  567. final_blob_len = sizeof(salt) + encrypted_len + DIGEST256_LEN;
  568. final_blob = tor_malloc_zero(final_blob_len);
  569. /* Build the MAC. */
  570. build_mac(mac_key, sizeof(mac_key), salt, sizeof(salt),
  571. encrypted, encrypted_len, mac, sizeof(mac));
  572. memwipe(mac_key, 0, sizeof(mac_key));
  573. /* The salt is the first value. */
  574. memcpy(final_blob, salt, sizeof(salt));
  575. offset = sizeof(salt);
  576. /* Second value is the encrypted data. */
  577. memcpy(final_blob + offset, encrypted, encrypted_len);
  578. offset += encrypted_len;
  579. /* Third value is the MAC. */
  580. memcpy(final_blob + offset, mac, sizeof(mac));
  581. offset += sizeof(mac);
  582. /* Cleanup the buffers. */
  583. memwipe(salt, 0, sizeof(salt));
  584. memwipe(encrypted, 0, encrypted_len);
  585. tor_free(encrypted);
  586. /* Extra precaution. */
  587. tor_assert(offset == final_blob_len);
  588. *encrypted_out = final_blob;
  589. return final_blob_len;
  590. }
  591. /* Create and return a string containing a client-auth entry. It's the
  592. * responsibility of the caller to free the returned string. This function
  593. * will never fail. */
  594. static char *
  595. get_auth_client_str(const hs_desc_authorized_client_t *client)
  596. {
  597. int ret;
  598. char *auth_client_str = NULL;
  599. /* We are gonna fill these arrays with base64 data. They are all double
  600. * the size of their binary representation to fit the base64 overhead. */
  601. char client_id_b64[HS_DESC_CLIENT_ID_LEN * 2];
  602. char iv_b64[CIPHER_IV_LEN * 2];
  603. char encrypted_cookie_b64[HS_DESC_ENCRYPED_COOKIE_LEN * 2];
  604. #define ASSERT_AND_BASE64(field) STMT_BEGIN \
  605. tor_assert(!tor_mem_is_zero((char *) client->field, \
  606. sizeof(client->field))); \
  607. ret = base64_encode_nopad(field##_b64, sizeof(field##_b64), \
  608. client->field, sizeof(client->field)); \
  609. tor_assert(ret > 0); \
  610. STMT_END
  611. ASSERT_AND_BASE64(client_id);
  612. ASSERT_AND_BASE64(iv);
  613. ASSERT_AND_BASE64(encrypted_cookie);
  614. /* Build the final string */
  615. tor_asprintf(&auth_client_str, "%s %s %s %s", str_desc_auth_client,
  616. client_id_b64, iv_b64, encrypted_cookie_b64);
  617. #undef ASSERT_AND_BASE64
  618. return auth_client_str;
  619. }
  620. /** Create the "client-auth" part of the descriptor and return a
  621. * newly-allocated string with it. It's the responsibility of the caller to
  622. * free the returned string. */
  623. static char *
  624. get_all_auth_client_lines(const hs_descriptor_t *desc)
  625. {
  626. smartlist_t *auth_client_lines = smartlist_new();
  627. char *auth_client_lines_str = NULL;
  628. tor_assert(desc);
  629. tor_assert(desc->superencrypted_data.clients);
  630. tor_assert(smartlist_len(desc->superencrypted_data.clients) != 0);
  631. tor_assert(smartlist_len(desc->superencrypted_data.clients)
  632. % HS_DESC_AUTH_CLIENT_MULTIPLE == 0);
  633. /* Make a line for each client */
  634. SMARTLIST_FOREACH_BEGIN(desc->superencrypted_data.clients,
  635. const hs_desc_authorized_client_t *, client) {
  636. char *auth_client_str = NULL;
  637. auth_client_str = get_auth_client_str(client);
  638. smartlist_add(auth_client_lines, auth_client_str);
  639. } SMARTLIST_FOREACH_END(client);
  640. /* Join all lines together to form final string */
  641. auth_client_lines_str = smartlist_join_strings(auth_client_lines,
  642. "\n", 1, NULL);
  643. /* Cleanup the mess */
  644. SMARTLIST_FOREACH(auth_client_lines, char *, a, tor_free(a));
  645. smartlist_free(auth_client_lines);
  646. return auth_client_lines_str;
  647. }
  648. /* Create the inner layer of the descriptor (which includes the intro points,
  649. * etc.). Return a newly-allocated string with the layer plaintext, or NULL if
  650. * an error occurred. It's the responsibility of the caller to free the
  651. * returned string. */
  652. static char *
  653. get_inner_encrypted_layer_plaintext(const hs_descriptor_t *desc)
  654. {
  655. char *encoded_str = NULL;
  656. smartlist_t *lines = smartlist_new();
  657. /* Build the start of the section prior to the introduction points. */
  658. {
  659. if (!desc->encrypted_data.create2_ntor) {
  660. log_err(LD_BUG, "HS desc doesn't have recognized handshake type.");
  661. goto err;
  662. }
  663. smartlist_add_asprintf(lines, "%s %d\n", str_create2_formats,
  664. ONION_HANDSHAKE_TYPE_NTOR);
  665. if (desc->encrypted_data.intro_auth_types &&
  666. smartlist_len(desc->encrypted_data.intro_auth_types)) {
  667. /* Put the authentication-required line. */
  668. char *buf = smartlist_join_strings(desc->encrypted_data.intro_auth_types,
  669. " ", 0, NULL);
  670. smartlist_add_asprintf(lines, "%s %s\n", str_intro_auth_required, buf);
  671. tor_free(buf);
  672. }
  673. if (desc->encrypted_data.single_onion_service) {
  674. smartlist_add_asprintf(lines, "%s\n", str_single_onion);
  675. }
  676. }
  677. /* Build the introduction point(s) section. */
  678. SMARTLIST_FOREACH_BEGIN(desc->encrypted_data.intro_points,
  679. const hs_desc_intro_point_t *, ip) {
  680. char *encoded_ip = encode_intro_point(&desc->plaintext_data.signing_pubkey,
  681. ip);
  682. if (encoded_ip == NULL) {
  683. log_err(LD_BUG, "HS desc intro point is malformed.");
  684. goto err;
  685. }
  686. smartlist_add(lines, encoded_ip);
  687. } SMARTLIST_FOREACH_END(ip);
  688. /* Build the entire encrypted data section into one encoded plaintext and
  689. * then encrypt it. */
  690. encoded_str = smartlist_join_strings(lines, "", 0, NULL);
  691. err:
  692. SMARTLIST_FOREACH(lines, char *, l, tor_free(l));
  693. smartlist_free(lines);
  694. return encoded_str;
  695. }
  696. /* Create the middle layer of the descriptor, which includes the client auth
  697. * data and the encrypted inner layer (provided as a base64 string at
  698. * <b>layer2_b64_ciphertext</b>). Return a newly-allocated string with the
  699. * layer plaintext, or NULL if an error occurred. It's the responsibility of
  700. * the caller to free the returned string. */
  701. static char *
  702. get_outer_encrypted_layer_plaintext(const hs_descriptor_t *desc,
  703. const char *layer2_b64_ciphertext)
  704. {
  705. char *layer1_str = NULL;
  706. smartlist_t *lines = smartlist_new();
  707. /* Specify auth type */
  708. smartlist_add_asprintf(lines, "%s %s\n", str_desc_auth_type, "x25519");
  709. { /* Print ephemeral x25519 key */
  710. char ephemeral_key_base64[CURVE25519_BASE64_PADDED_LEN + 1];
  711. const curve25519_public_key_t *ephemeral_pubkey;
  712. ephemeral_pubkey = &desc->superencrypted_data.auth_ephemeral_pubkey;
  713. tor_assert(!tor_mem_is_zero((char *) ephemeral_pubkey->public_key,
  714. CURVE25519_PUBKEY_LEN));
  715. if (curve25519_public_to_base64(ephemeral_key_base64,
  716. ephemeral_pubkey) < 0) {
  717. goto done;
  718. }
  719. smartlist_add_asprintf(lines, "%s %s\n",
  720. str_desc_auth_key, ephemeral_key_base64);
  721. memwipe(ephemeral_key_base64, 0, sizeof(ephemeral_key_base64));
  722. }
  723. { /* Create auth-client lines. */
  724. char *auth_client_lines = get_all_auth_client_lines(desc);
  725. tor_assert(auth_client_lines);
  726. smartlist_add(lines, auth_client_lines);
  727. }
  728. /* create encrypted section */
  729. {
  730. smartlist_add_asprintf(lines,
  731. "%s\n"
  732. "-----BEGIN MESSAGE-----\n"
  733. "%s"
  734. "-----END MESSAGE-----",
  735. str_encrypted, layer2_b64_ciphertext);
  736. }
  737. layer1_str = smartlist_join_strings(lines, "", 0, NULL);
  738. done:
  739. /* We need to memwipe all lines because it contains the ephemeral key */
  740. SMARTLIST_FOREACH(lines, char *, a, memwipe(a, 0, strlen(a)));
  741. SMARTLIST_FOREACH(lines, char *, a, tor_free(a));
  742. smartlist_free(lines);
  743. return layer1_str;
  744. }
  745. /* Encrypt <b>encoded_str</b> into an encrypted blob and then base64 it before
  746. * returning it. <b>desc</b> is provided to derive the encryption
  747. * keys. <b>secret_data</b> is also proved to derive the encryption keys.
  748. * <b>is_superencrypted_layer</b> is set if <b>encoded_str</b> is the
  749. * middle (superencrypted) layer of the descriptor. It's the responsibility of
  750. * the caller to free the returned string. */
  751. static char *
  752. encrypt_desc_data_and_base64(const hs_descriptor_t *desc,
  753. const uint8_t *secret_data,
  754. size_t secret_data_len,
  755. const char *encoded_str,
  756. int is_superencrypted_layer)
  757. {
  758. char *enc_b64;
  759. ssize_t enc_b64_len, ret_len, enc_len;
  760. char *encrypted_blob = NULL;
  761. enc_len = encrypt_descriptor_data(desc, secret_data, secret_data_len,
  762. encoded_str, &encrypted_blob,
  763. is_superencrypted_layer);
  764. /* Get the encoded size plus a NUL terminating byte. */
  765. enc_b64_len = base64_encode_size(enc_len, BASE64_ENCODE_MULTILINE) + 1;
  766. enc_b64 = tor_malloc_zero(enc_b64_len);
  767. /* Base64 the encrypted blob before returning it. */
  768. ret_len = base64_encode(enc_b64, enc_b64_len, encrypted_blob, enc_len,
  769. BASE64_ENCODE_MULTILINE);
  770. /* Return length doesn't count the NUL byte. */
  771. tor_assert(ret_len == (enc_b64_len - 1));
  772. tor_free(encrypted_blob);
  773. return enc_b64;
  774. }
  775. /* Generate the secret data which is used to encrypt/decrypt the descriptor.
  776. *
  777. * SECRET_DATA = blinded-public-key
  778. * SECRET_DATA = blinded-public-key | descriptor_cookie
  779. *
  780. * The descriptor_cookie is optional but if it exists, it must be at least
  781. * HS_DESC_DESCRIPTOR_COOKIE_LEN bytes long.
  782. *
  783. * A newly allocated secret data is put in secret_data_out. Return the
  784. * length of the secret data. This function cannot fail. */
  785. static size_t
  786. build_secret_data(const ed25519_public_key_t *blinded_pubkey,
  787. const uint8_t *descriptor_cookie,
  788. uint8_t **secret_data_out)
  789. {
  790. size_t secret_data_len;
  791. uint8_t *secret_data;
  792. tor_assert(blinded_pubkey);
  793. tor_assert(secret_data_out);
  794. if (descriptor_cookie) {
  795. /* If the descriptor cookie is present, we need both the blinded
  796. * pubkey and the descriptor cookie as a secret data. */
  797. secret_data_len = ED25519_PUBKEY_LEN + HS_DESC_DESCRIPTOR_COOKIE_LEN;
  798. secret_data = tor_malloc(secret_data_len);
  799. memcpy(secret_data,
  800. blinded_pubkey->pubkey,
  801. ED25519_PUBKEY_LEN);
  802. memcpy(secret_data + ED25519_PUBKEY_LEN,
  803. descriptor_cookie,
  804. HS_DESC_DESCRIPTOR_COOKIE_LEN);
  805. } else {
  806. /* If the descriptor cookie is not present, we need only the blinded
  807. * pubkey as a secret data. */
  808. secret_data_len = ED25519_PUBKEY_LEN;
  809. secret_data = tor_malloc(secret_data_len);
  810. memcpy(secret_data,
  811. blinded_pubkey->pubkey,
  812. ED25519_PUBKEY_LEN);
  813. }
  814. *secret_data_out = secret_data;
  815. return secret_data_len;
  816. }
  817. /* Generate and encode the superencrypted portion of <b>desc</b>. This also
  818. * involves generating the encrypted portion of the descriptor, and performing
  819. * the superencryption. A newly allocated NUL-terminated string pointer
  820. * containing the encrypted encoded blob is put in encrypted_blob_out. Return 0
  821. * on success else a negative value. */
  822. static int
  823. encode_superencrypted_data(const hs_descriptor_t *desc,
  824. const uint8_t *descriptor_cookie,
  825. char **encrypted_blob_out)
  826. {
  827. int ret = -1;
  828. uint8_t *secret_data = NULL;
  829. size_t secret_data_len = 0;
  830. char *layer2_str = NULL;
  831. char *layer2_b64_ciphertext = NULL;
  832. char *layer1_str = NULL;
  833. char *layer1_b64_ciphertext = NULL;
  834. tor_assert(desc);
  835. tor_assert(encrypted_blob_out);
  836. /* Func logic: We first create the inner layer of the descriptor (layer2).
  837. * We then encrypt it and use it to create the middle layer of the descriptor
  838. * (layer1). Finally we superencrypt the middle layer and return it to our
  839. * caller. */
  840. /* Create inner descriptor layer */
  841. layer2_str = get_inner_encrypted_layer_plaintext(desc);
  842. if (!layer2_str) {
  843. goto err;
  844. }
  845. secret_data_len = build_secret_data(&desc->plaintext_data.blinded_pubkey,
  846. descriptor_cookie,
  847. &secret_data);
  848. /* Encrypt and b64 the inner layer */
  849. layer2_b64_ciphertext =
  850. encrypt_desc_data_and_base64(desc, secret_data, secret_data_len,
  851. layer2_str, 0);
  852. if (!layer2_b64_ciphertext) {
  853. goto err;
  854. }
  855. /* Now create middle descriptor layer given the inner layer */
  856. layer1_str = get_outer_encrypted_layer_plaintext(desc,layer2_b64_ciphertext);
  857. if (!layer1_str) {
  858. goto err;
  859. }
  860. /* Encrypt and base64 the middle layer */
  861. layer1_b64_ciphertext =
  862. encrypt_desc_data_and_base64(desc,
  863. desc->plaintext_data.blinded_pubkey.pubkey,
  864. ED25519_PUBKEY_LEN,
  865. layer1_str, 1);
  866. if (!layer1_b64_ciphertext) {
  867. goto err;
  868. }
  869. /* Success! */
  870. ret = 0;
  871. err:
  872. memwipe(secret_data, 0, secret_data_len);
  873. tor_free(secret_data);
  874. tor_free(layer1_str);
  875. tor_free(layer2_str);
  876. tor_free(layer2_b64_ciphertext);
  877. *encrypted_blob_out = layer1_b64_ciphertext;
  878. return ret;
  879. }
  880. /* Encode a v3 HS descriptor. Return 0 on success and set encoded_out to the
  881. * newly allocated string of the encoded descriptor. On error, -1 is returned
  882. * and encoded_out is untouched. */
  883. static int
  884. desc_encode_v3(const hs_descriptor_t *desc,
  885. const ed25519_keypair_t *signing_kp,
  886. const uint8_t *descriptor_cookie,
  887. char **encoded_out)
  888. {
  889. int ret = -1;
  890. char *encoded_str = NULL;
  891. size_t encoded_len;
  892. smartlist_t *lines = smartlist_new();
  893. tor_assert(desc);
  894. tor_assert(signing_kp);
  895. tor_assert(encoded_out);
  896. tor_assert(desc->plaintext_data.version == 3);
  897. if (BUG(desc->subcredential == NULL)) {
  898. goto err;
  899. }
  900. /* Build the non-encrypted values. */
  901. {
  902. char *encoded_cert;
  903. /* Encode certificate then create the first line of the descriptor. */
  904. if (desc->plaintext_data.signing_key_cert->cert_type
  905. != CERT_TYPE_SIGNING_HS_DESC) {
  906. log_err(LD_BUG, "HS descriptor signing key has an unexpected cert type "
  907. "(%d)", (int) desc->plaintext_data.signing_key_cert->cert_type);
  908. goto err;
  909. }
  910. if (tor_cert_encode_ed22519(desc->plaintext_data.signing_key_cert,
  911. &encoded_cert) < 0) {
  912. /* The function will print error logs. */
  913. goto err;
  914. }
  915. /* Create the hs descriptor line. */
  916. smartlist_add_asprintf(lines, "%s %" PRIu32, str_hs_desc,
  917. desc->plaintext_data.version);
  918. /* Add the descriptor lifetime line (in minutes). */
  919. smartlist_add_asprintf(lines, "%s %" PRIu32, str_lifetime,
  920. desc->plaintext_data.lifetime_sec / 60);
  921. /* Create the descriptor certificate line. */
  922. smartlist_add_asprintf(lines, "%s\n%s", str_desc_cert, encoded_cert);
  923. tor_free(encoded_cert);
  924. /* Create the revision counter line. */
  925. smartlist_add_asprintf(lines, "%s %" PRIu64, str_rev_counter,
  926. desc->plaintext_data.revision_counter);
  927. }
  928. /* Build the superencrypted data section. */
  929. {
  930. char *enc_b64_blob=NULL;
  931. if (encode_superencrypted_data(desc, descriptor_cookie,
  932. &enc_b64_blob) < 0) {
  933. goto err;
  934. }
  935. smartlist_add_asprintf(lines,
  936. "%s\n"
  937. "-----BEGIN MESSAGE-----\n"
  938. "%s"
  939. "-----END MESSAGE-----",
  940. str_superencrypted, enc_b64_blob);
  941. tor_free(enc_b64_blob);
  942. }
  943. /* Join all lines in one string so we can generate a signature and append
  944. * it to the descriptor. */
  945. encoded_str = smartlist_join_strings(lines, "\n", 1, &encoded_len);
  946. /* Sign all fields of the descriptor with our short term signing key. */
  947. {
  948. ed25519_signature_t sig;
  949. char ed_sig_b64[ED25519_SIG_BASE64_LEN + 1];
  950. if (ed25519_sign_prefixed(&sig,
  951. (const uint8_t *) encoded_str, encoded_len,
  952. str_desc_sig_prefix, signing_kp) < 0) {
  953. log_warn(LD_BUG, "Can't sign encoded HS descriptor!");
  954. tor_free(encoded_str);
  955. goto err;
  956. }
  957. if (ed25519_signature_to_base64(ed_sig_b64, &sig) < 0) {
  958. log_warn(LD_BUG, "Can't base64 encode descriptor signature!");
  959. tor_free(encoded_str);
  960. goto err;
  961. }
  962. /* Create the signature line. */
  963. smartlist_add_asprintf(lines, "%s %s", str_signature, ed_sig_b64);
  964. }
  965. /* Free previous string that we used so compute the signature. */
  966. tor_free(encoded_str);
  967. encoded_str = smartlist_join_strings(lines, "\n", 1, NULL);
  968. *encoded_out = encoded_str;
  969. if (strlen(encoded_str) >= hs_cache_get_max_descriptor_size()) {
  970. log_warn(LD_GENERAL, "We just made an HS descriptor that's too big (%d)."
  971. "Failing.", (int)strlen(encoded_str));
  972. tor_free(encoded_str);
  973. goto err;
  974. }
  975. /* XXX: Trigger a control port event. */
  976. /* Success! */
  977. ret = 0;
  978. err:
  979. SMARTLIST_FOREACH(lines, char *, l, tor_free(l));
  980. smartlist_free(lines);
  981. return ret;
  982. }
  983. /* === DECODING === */
  984. /* Given the token tok for an auth client, decode it as
  985. * hs_desc_authorized_client_t. tok->args MUST contain at least 3 elements
  986. * Return 0 on success else -1 on failure. */
  987. static int
  988. decode_auth_client(const directory_token_t *tok,
  989. hs_desc_authorized_client_t *client)
  990. {
  991. int ret = -1;
  992. tor_assert(tok);
  993. tor_assert(tok->n_args >= 3);
  994. tor_assert(client);
  995. if (base64_decode((char *) client->client_id, sizeof(client->client_id),
  996. tok->args[0], strlen(tok->args[0])) !=
  997. sizeof(client->client_id)) {
  998. goto done;
  999. }
  1000. if (base64_decode((char *) client->iv, sizeof(client->iv),
  1001. tok->args[1], strlen(tok->args[1])) !=
  1002. sizeof(client->iv)) {
  1003. goto done;
  1004. }
  1005. if (base64_decode((char *) client->encrypted_cookie,
  1006. sizeof(client->encrypted_cookie),
  1007. tok->args[2], strlen(tok->args[2])) !=
  1008. sizeof(client->encrypted_cookie)) {
  1009. goto done;
  1010. }
  1011. /* Success. */
  1012. ret = 0;
  1013. done:
  1014. return ret;
  1015. }
  1016. /* Given an encoded string of the link specifiers, return a newly allocated
  1017. * list of decoded link specifiers. Return NULL on error. */
  1018. STATIC smartlist_t *
  1019. decode_link_specifiers(const char *encoded)
  1020. {
  1021. int decoded_len;
  1022. size_t encoded_len, i;
  1023. uint8_t *decoded;
  1024. smartlist_t *results = NULL;
  1025. link_specifier_list_t *specs = NULL;
  1026. tor_assert(encoded);
  1027. encoded_len = strlen(encoded);
  1028. decoded = tor_malloc(encoded_len);
  1029. decoded_len = base64_decode((char *) decoded, encoded_len, encoded,
  1030. encoded_len);
  1031. if (decoded_len < 0) {
  1032. goto err;
  1033. }
  1034. if (link_specifier_list_parse(&specs, decoded,
  1035. (size_t) decoded_len) < decoded_len) {
  1036. goto err;
  1037. }
  1038. tor_assert(specs);
  1039. results = smartlist_new();
  1040. for (i = 0; i < link_specifier_list_getlen_spec(specs); i++) {
  1041. hs_desc_link_specifier_t *hs_spec;
  1042. link_specifier_t *ls = link_specifier_list_get_spec(specs, i);
  1043. tor_assert(ls);
  1044. hs_spec = tor_malloc_zero(sizeof(*hs_spec));
  1045. hs_spec->type = link_specifier_get_ls_type(ls);
  1046. switch (hs_spec->type) {
  1047. case LS_IPV4:
  1048. tor_addr_from_ipv4h(&hs_spec->u.ap.addr,
  1049. link_specifier_get_un_ipv4_addr(ls));
  1050. hs_spec->u.ap.port = link_specifier_get_un_ipv4_port(ls);
  1051. break;
  1052. case LS_IPV6:
  1053. tor_addr_from_ipv6_bytes(&hs_spec->u.ap.addr, (const char *)
  1054. link_specifier_getarray_un_ipv6_addr(ls));
  1055. hs_spec->u.ap.port = link_specifier_get_un_ipv6_port(ls);
  1056. break;
  1057. case LS_LEGACY_ID:
  1058. /* Both are known at compile time so let's make sure they are the same
  1059. * else we can copy memory out of bound. */
  1060. tor_assert(link_specifier_getlen_un_legacy_id(ls) ==
  1061. sizeof(hs_spec->u.legacy_id));
  1062. memcpy(hs_spec->u.legacy_id, link_specifier_getarray_un_legacy_id(ls),
  1063. sizeof(hs_spec->u.legacy_id));
  1064. break;
  1065. case LS_ED25519_ID:
  1066. /* Both are known at compile time so let's make sure they are the same
  1067. * else we can copy memory out of bound. */
  1068. tor_assert(link_specifier_getlen_un_ed25519_id(ls) ==
  1069. sizeof(hs_spec->u.ed25519_id));
  1070. memcpy(hs_spec->u.ed25519_id,
  1071. link_specifier_getconstarray_un_ed25519_id(ls),
  1072. sizeof(hs_spec->u.ed25519_id));
  1073. break;
  1074. default:
  1075. tor_free(hs_spec);
  1076. goto err;
  1077. }
  1078. smartlist_add(results, hs_spec);
  1079. }
  1080. goto done;
  1081. err:
  1082. if (results) {
  1083. SMARTLIST_FOREACH(results, hs_desc_link_specifier_t *, s, tor_free(s));
  1084. smartlist_free(results);
  1085. results = NULL;
  1086. }
  1087. done:
  1088. link_specifier_list_free(specs);
  1089. tor_free(decoded);
  1090. return results;
  1091. }
  1092. /* Given a list of authentication types, decode it and put it in the encrypted
  1093. * data section. Return 1 if we at least know one of the type or 0 if we know
  1094. * none of them. */
  1095. static int
  1096. decode_auth_type(hs_desc_encrypted_data_t *desc, const char *list)
  1097. {
  1098. int match = 0;
  1099. tor_assert(desc);
  1100. tor_assert(list);
  1101. desc->intro_auth_types = smartlist_new();
  1102. smartlist_split_string(desc->intro_auth_types, list, " ", 0, 0);
  1103. /* Validate the types that we at least know about one. */
  1104. SMARTLIST_FOREACH_BEGIN(desc->intro_auth_types, const char *, auth) {
  1105. for (int idx = 0; intro_auth_types[idx].identifier; idx++) {
  1106. if (!strncmp(auth, intro_auth_types[idx].identifier,
  1107. strlen(intro_auth_types[idx].identifier))) {
  1108. match = 1;
  1109. break;
  1110. }
  1111. }
  1112. } SMARTLIST_FOREACH_END(auth);
  1113. return match;
  1114. }
  1115. /* Parse a space-delimited list of integers representing CREATE2 formats into
  1116. * the bitfield in hs_desc_encrypted_data_t. Ignore unrecognized values. */
  1117. static void
  1118. decode_create2_list(hs_desc_encrypted_data_t *desc, const char *list)
  1119. {
  1120. smartlist_t *tokens;
  1121. tor_assert(desc);
  1122. tor_assert(list);
  1123. tokens = smartlist_new();
  1124. smartlist_split_string(tokens, list, " ", 0, 0);
  1125. SMARTLIST_FOREACH_BEGIN(tokens, char *, s) {
  1126. int ok;
  1127. unsigned long type = tor_parse_ulong(s, 10, 1, UINT16_MAX, &ok, NULL);
  1128. if (!ok) {
  1129. log_warn(LD_REND, "Unparseable value %s in create2 list", escaped(s));
  1130. continue;
  1131. }
  1132. switch (type) {
  1133. case ONION_HANDSHAKE_TYPE_NTOR:
  1134. desc->create2_ntor = 1;
  1135. break;
  1136. default:
  1137. /* We deliberately ignore unsupported handshake types */
  1138. continue;
  1139. }
  1140. } SMARTLIST_FOREACH_END(s);
  1141. SMARTLIST_FOREACH(tokens, char *, s, tor_free(s));
  1142. smartlist_free(tokens);
  1143. }
  1144. /* Given a certificate, validate the certificate for certain conditions which
  1145. * are if the given type matches the cert's one, if the signing key is
  1146. * included and if the that key was actually used to sign the certificate.
  1147. *
  1148. * Return 1 iff if all conditions pass or 0 if one of them fails. */
  1149. STATIC int
  1150. cert_is_valid(tor_cert_t *cert, uint8_t type, const char *log_obj_type)
  1151. {
  1152. tor_assert(log_obj_type);
  1153. if (cert == NULL) {
  1154. log_warn(LD_REND, "Certificate for %s couldn't be parsed.", log_obj_type);
  1155. goto err;
  1156. }
  1157. if (cert->cert_type != type) {
  1158. log_warn(LD_REND, "Invalid cert type %02x for %s.", cert->cert_type,
  1159. log_obj_type);
  1160. goto err;
  1161. }
  1162. /* All certificate must have its signing key included. */
  1163. if (!cert->signing_key_included) {
  1164. log_warn(LD_REND, "Signing key is NOT included for %s.", log_obj_type);
  1165. goto err;
  1166. }
  1167. /* The following will not only check if the signature matches but also the
  1168. * expiration date and overall validity. */
  1169. if (tor_cert_checksig(cert, &cert->signing_key, approx_time()) < 0) {
  1170. log_warn(LD_REND, "Invalid signature for %s: %s", log_obj_type,
  1171. tor_cert_describe_signature_status(cert));
  1172. goto err;
  1173. }
  1174. return 1;
  1175. err:
  1176. return 0;
  1177. }
  1178. /* Given some binary data, try to parse it to get a certificate object. If we
  1179. * have a valid cert, validate it using the given wanted type. On error, print
  1180. * a log using the err_msg has the certificate identifier adding semantic to
  1181. * the log and cert_out is set to NULL. On success, 0 is returned and cert_out
  1182. * points to a newly allocated certificate object. */
  1183. static int
  1184. cert_parse_and_validate(tor_cert_t **cert_out, const char *data,
  1185. size_t data_len, unsigned int cert_type_wanted,
  1186. const char *err_msg)
  1187. {
  1188. tor_cert_t *cert;
  1189. tor_assert(cert_out);
  1190. tor_assert(data);
  1191. tor_assert(err_msg);
  1192. /* Parse certificate. */
  1193. cert = tor_cert_parse((const uint8_t *) data, data_len);
  1194. if (!cert) {
  1195. log_warn(LD_REND, "Certificate for %s couldn't be parsed.", err_msg);
  1196. goto err;
  1197. }
  1198. /* Validate certificate. */
  1199. if (!cert_is_valid(cert, cert_type_wanted, err_msg)) {
  1200. goto err;
  1201. }
  1202. *cert_out = cert;
  1203. return 0;
  1204. err:
  1205. tor_cert_free(cert);
  1206. *cert_out = NULL;
  1207. return -1;
  1208. }
  1209. /* Return true iff the given length of the encrypted data of a descriptor
  1210. * passes validation. */
  1211. STATIC int
  1212. encrypted_data_length_is_valid(size_t len)
  1213. {
  1214. /* Make sure there is enough data for the salt and the mac. The equality is
  1215. there to ensure that there is at least one byte of encrypted data. */
  1216. if (len <= HS_DESC_ENCRYPTED_SALT_LEN + DIGEST256_LEN) {
  1217. log_warn(LD_REND, "Length of descriptor's encrypted data is too small. "
  1218. "Got %lu but minimum value is %d",
  1219. (unsigned long)len, HS_DESC_ENCRYPTED_SALT_LEN + DIGEST256_LEN);
  1220. goto err;
  1221. }
  1222. return 1;
  1223. err:
  1224. return 0;
  1225. }
  1226. /* Build the KEYS component for the authorized client computation. The format
  1227. * of the construction is:
  1228. *
  1229. * SECRET_SEED = x25519(sk, pk)
  1230. * KEYS = KDF(subcredential | SECRET_SEED, 40)
  1231. *
  1232. * Set the <b>keys_out</b> argument to point to the buffer containing the KEYS,
  1233. * and return the buffer's length. The caller should wipe and free its content
  1234. * once done with it. This function can't fail. */
  1235. static size_t
  1236. build_descriptor_cookie_keys(const uint8_t *subcredential,
  1237. size_t subcredential_len,
  1238. const curve25519_secret_key_t *sk,
  1239. const curve25519_public_key_t *pk,
  1240. uint8_t **keys_out)
  1241. {
  1242. uint8_t secret_seed[CURVE25519_OUTPUT_LEN];
  1243. uint8_t *keystream;
  1244. size_t keystream_len = HS_DESC_CLIENT_ID_LEN + HS_DESC_COOKIE_KEY_LEN;
  1245. crypto_xof_t *xof;
  1246. tor_assert(subcredential);
  1247. tor_assert(sk);
  1248. tor_assert(pk);
  1249. tor_assert(keys_out);
  1250. keystream = tor_malloc_zero(keystream_len);
  1251. /* Calculate x25519(sk, pk) to get the secret seed. */
  1252. curve25519_handshake(secret_seed, sk, pk);
  1253. /* Calculate KEYS = KDF(subcredential | SECRET_SEED, 40) */
  1254. xof = crypto_xof_new();
  1255. crypto_xof_add_bytes(xof, subcredential, subcredential_len);
  1256. crypto_xof_add_bytes(xof, secret_seed, sizeof(secret_seed));
  1257. crypto_xof_squeeze_bytes(xof, keystream, keystream_len);
  1258. crypto_xof_free(xof);
  1259. memwipe(secret_seed, 0, sizeof(secret_seed));
  1260. *keys_out = keystream;
  1261. return keystream_len;
  1262. }
  1263. /* Decrypt the descriptor cookie given the descriptor, the auth client,
  1264. * and the client secret key. On sucess, return 0 and a newly allocated
  1265. * descriptor cookie descriptor_cookie_out. On error or if the client id
  1266. * is invalid, return -1 and descriptor_cookie_out is set to
  1267. * NULL. */
  1268. static int
  1269. decrypt_descriptor_cookie(const hs_descriptor_t *desc,
  1270. const hs_desc_authorized_client_t *client,
  1271. const curve25519_secret_key_t *client_auth_sk,
  1272. uint8_t **descriptor_cookie_out)
  1273. {
  1274. int ret = -1;
  1275. uint8_t *keystream = NULL;
  1276. size_t keystream_length = 0;
  1277. uint8_t *descriptor_cookie = NULL;
  1278. const uint8_t *cookie_key = NULL;
  1279. crypto_cipher_t *cipher = NULL;
  1280. tor_assert(desc);
  1281. tor_assert(client);
  1282. tor_assert(client_auth_sk);
  1283. tor_assert(!tor_mem_is_zero(
  1284. (char *) &desc->superencrypted_data.auth_ephemeral_pubkey,
  1285. sizeof(desc->superencrypted_data.auth_ephemeral_pubkey)));
  1286. tor_assert(!tor_mem_is_zero((char *) client_auth_sk,
  1287. sizeof(*client_auth_sk)));
  1288. tor_assert(!tor_mem_is_zero((char *) desc->subcredential, DIGEST256_LEN));
  1289. /* Get the KEYS component to derive the CLIENT-ID and COOKIE-KEY. */
  1290. keystream_length =
  1291. build_descriptor_cookie_keys(desc->subcredential, DIGEST256_LEN,
  1292. client_auth_sk,
  1293. &desc->superencrypted_data.auth_ephemeral_pubkey,
  1294. &keystream);
  1295. tor_assert(keystream_length > 0);
  1296. /* If the client id of auth client is not the same as the calculcated
  1297. * client id, it means that this auth client is invaild according to the
  1298. * client secret key client_auth_sk. */
  1299. if (tor_memneq(client->client_id, keystream, HS_DESC_CLIENT_ID_LEN)) {
  1300. goto done;
  1301. }
  1302. cookie_key = keystream + HS_DESC_CLIENT_ID_LEN;
  1303. /* This creates a cipher for AES. It can't fail. */
  1304. cipher = crypto_cipher_new_with_iv_and_bits(cookie_key, client->iv,
  1305. HS_DESC_COOKIE_KEY_BIT_SIZE);
  1306. descriptor_cookie = tor_malloc_zero(HS_DESC_DESCRIPTOR_COOKIE_LEN);
  1307. /* This can't fail. */
  1308. crypto_cipher_decrypt(cipher, (char *) descriptor_cookie,
  1309. (const char *) client->encrypted_cookie,
  1310. sizeof(client->encrypted_cookie));
  1311. /* Success. */
  1312. ret = 0;
  1313. done:
  1314. *descriptor_cookie_out = descriptor_cookie;
  1315. if (cipher) {
  1316. crypto_cipher_free(cipher);
  1317. }
  1318. memwipe(keystream, 0, keystream_length);
  1319. tor_free(keystream);
  1320. return ret;
  1321. }
  1322. /** Decrypt an encrypted descriptor layer at <b>encrypted_blob</b> of size
  1323. * <b>encrypted_blob_size</b>. The descriptor cookie is optional. Use
  1324. * the descriptor object <b>desc</b> and <b>descriptor_cookie</b>
  1325. * to generate the right decryption keys; set <b>decrypted_out</b> to
  1326. * the plaintext. If <b>is_superencrypted_layer</b> is set, this is
  1327. * the outter encrypted layer of the descriptor.
  1328. *
  1329. * On any error case, including an empty output, return 0 and set
  1330. * *<b>decrypted_out</b> to NULL.
  1331. */
  1332. MOCK_IMPL(STATIC size_t,
  1333. decrypt_desc_layer,(const hs_descriptor_t *desc,
  1334. const uint8_t *encrypted_blob,
  1335. size_t encrypted_blob_size,
  1336. const uint8_t *descriptor_cookie,
  1337. int is_superencrypted_layer,
  1338. char **decrypted_out))
  1339. {
  1340. uint8_t *decrypted = NULL;
  1341. uint8_t secret_key[HS_DESC_ENCRYPTED_KEY_LEN], secret_iv[CIPHER_IV_LEN];
  1342. uint8_t *secret_data = NULL;
  1343. size_t secret_data_len = 0;
  1344. uint8_t mac_key[DIGEST256_LEN], our_mac[DIGEST256_LEN];
  1345. const uint8_t *salt, *encrypted, *desc_mac;
  1346. size_t encrypted_len, result_len = 0;
  1347. tor_assert(decrypted_out);
  1348. tor_assert(desc);
  1349. tor_assert(encrypted_blob);
  1350. /* Construction is as follow: SALT | ENCRYPTED_DATA | MAC .
  1351. * Make sure we have enough space for all these things. */
  1352. if (!encrypted_data_length_is_valid(encrypted_blob_size)) {
  1353. goto err;
  1354. }
  1355. /* Start of the blob thus the salt. */
  1356. salt = encrypted_blob;
  1357. /* Next is the encrypted data. */
  1358. encrypted = encrypted_blob + HS_DESC_ENCRYPTED_SALT_LEN;
  1359. encrypted_len = encrypted_blob_size -
  1360. (HS_DESC_ENCRYPTED_SALT_LEN + DIGEST256_LEN);
  1361. tor_assert(encrypted_len > 0); /* guaranteed by the check above */
  1362. /* And last comes the MAC. */
  1363. desc_mac = encrypted_blob + encrypted_blob_size - DIGEST256_LEN;
  1364. /* Build secret data to be used in the decryption. */
  1365. secret_data_len = build_secret_data(&desc->plaintext_data.blinded_pubkey,
  1366. descriptor_cookie,
  1367. &secret_data);
  1368. /* KDF construction resulting in a key from which the secret key, IV and MAC
  1369. * key are extracted which is what we need for the decryption. */
  1370. build_secret_key_iv_mac(desc, secret_data, secret_data_len,
  1371. salt, HS_DESC_ENCRYPTED_SALT_LEN,
  1372. secret_key, sizeof(secret_key),
  1373. secret_iv, sizeof(secret_iv),
  1374. mac_key, sizeof(mac_key),
  1375. is_superencrypted_layer);
  1376. /* Build MAC. */
  1377. build_mac(mac_key, sizeof(mac_key), salt, HS_DESC_ENCRYPTED_SALT_LEN,
  1378. encrypted, encrypted_len, our_mac, sizeof(our_mac));
  1379. memwipe(mac_key, 0, sizeof(mac_key));
  1380. /* Verify MAC; MAC is H(mac_key || salt || encrypted)
  1381. *
  1382. * This is a critical check that is making sure the computed MAC matches the
  1383. * one in the descriptor. */
  1384. if (!tor_memeq(our_mac, desc_mac, sizeof(our_mac))) {
  1385. log_info(LD_REND, "Encrypted service descriptor MAC check failed");
  1386. goto err;
  1387. }
  1388. {
  1389. /* Decrypt. Here we are assured that the encrypted length is valid for
  1390. * decryption. */
  1391. crypto_cipher_t *cipher;
  1392. cipher = crypto_cipher_new_with_iv_and_bits(secret_key, secret_iv,
  1393. HS_DESC_ENCRYPTED_BIT_SIZE);
  1394. /* Extra byte for the NUL terminated byte. */
  1395. decrypted = tor_malloc_zero(encrypted_len + 1);
  1396. crypto_cipher_decrypt(cipher, (char *) decrypted,
  1397. (const char *) encrypted, encrypted_len);
  1398. crypto_cipher_free(cipher);
  1399. }
  1400. {
  1401. /* Adjust length to remove NUL padding bytes */
  1402. uint8_t *end = memchr(decrypted, 0, encrypted_len);
  1403. result_len = encrypted_len;
  1404. if (end) {
  1405. result_len = end - decrypted;
  1406. }
  1407. }
  1408. if (result_len == 0) {
  1409. /* Treat this as an error, so that somebody will free the output. */
  1410. goto err;
  1411. }
  1412. /* Make sure to NUL terminate the string. */
  1413. decrypted[encrypted_len] = '\0';
  1414. *decrypted_out = (char *) decrypted;
  1415. goto done;
  1416. err:
  1417. if (decrypted) {
  1418. tor_free(decrypted);
  1419. }
  1420. *decrypted_out = NULL;
  1421. result_len = 0;
  1422. done:
  1423. memwipe(secret_data, 0, secret_data_len);
  1424. memwipe(secret_key, 0, sizeof(secret_key));
  1425. memwipe(secret_iv, 0, sizeof(secret_iv));
  1426. tor_free(secret_data);
  1427. return result_len;
  1428. }
  1429. /* Decrypt the superencrypted section of the descriptor using the given
  1430. * descriptor object <b>desc</b>. A newly allocated NUL terminated string is
  1431. * put in decrypted_out which contains the superencrypted layer of the
  1432. * descriptor. Return the length of decrypted_out on success else 0 is
  1433. * returned and decrypted_out is set to NULL. */
  1434. static size_t
  1435. desc_decrypt_superencrypted(const hs_descriptor_t *desc, char **decrypted_out)
  1436. {
  1437. size_t superencrypted_len = 0;
  1438. char *superencrypted_plaintext = NULL;
  1439. tor_assert(desc);
  1440. tor_assert(decrypted_out);
  1441. superencrypted_len = decrypt_desc_layer(desc,
  1442. desc->plaintext_data.superencrypted_blob,
  1443. desc->plaintext_data.superencrypted_blob_size,
  1444. NULL, 1, &superencrypted_plaintext);
  1445. if (!superencrypted_len) {
  1446. log_warn(LD_REND, "Decrypting superencrypted desc failed.");
  1447. goto done;
  1448. }
  1449. tor_assert(superencrypted_plaintext);
  1450. done:
  1451. /* In case of error, superencrypted_plaintext is already NULL, so the
  1452. * following line makes sense. */
  1453. *decrypted_out = superencrypted_plaintext;
  1454. /* This makes sense too, because, in case of error, this is zero. */
  1455. return superencrypted_len;
  1456. }
  1457. /* Decrypt the encrypted section of the descriptor using the given descriptor
  1458. * object <b>desc</b>. A newly allocated NUL terminated string is put in
  1459. * decrypted_out which contains the encrypted layer of the descriptor.
  1460. * Return the length of decrypted_out on success else 0 is returned and
  1461. * decrypted_out is set to NULL. */
  1462. static size_t
  1463. desc_decrypt_encrypted(const hs_descriptor_t *desc,
  1464. const curve25519_secret_key_t *client_auth_sk,
  1465. char **decrypted_out)
  1466. {
  1467. size_t encrypted_len = 0;
  1468. char *encrypted_plaintext = NULL;
  1469. uint8_t *descriptor_cookie = NULL;
  1470. tor_assert(desc);
  1471. tor_assert(desc->superencrypted_data.clients);
  1472. tor_assert(decrypted_out);
  1473. /* If the client secret key is provided, try to find a valid descriptor
  1474. * cookie. Otherwise, leave it NULL. */
  1475. if (client_auth_sk) {
  1476. SMARTLIST_FOREACH_BEGIN(desc->superencrypted_data.clients,
  1477. hs_desc_authorized_client_t *, client) {
  1478. /* If we can decrypt the descriptor cookie successfully, we will use that
  1479. * descriptor cookie and break from the loop. */
  1480. if (!decrypt_descriptor_cookie(desc, client, client_auth_sk,
  1481. &descriptor_cookie)) {
  1482. break;
  1483. }
  1484. } SMARTLIST_FOREACH_END(client);
  1485. }
  1486. encrypted_len = decrypt_desc_layer(desc,
  1487. desc->superencrypted_data.encrypted_blob,
  1488. desc->superencrypted_data.encrypted_blob_size,
  1489. descriptor_cookie, 0, &encrypted_plaintext);
  1490. if (!encrypted_len) {
  1491. goto err;
  1492. }
  1493. tor_assert(encrypted_plaintext);
  1494. err:
  1495. /* In case of error, encrypted_plaintext is already NULL, so the
  1496. * following line makes sense. */
  1497. *decrypted_out = encrypted_plaintext;
  1498. if (descriptor_cookie) {
  1499. memwipe(descriptor_cookie, 0, HS_DESC_DESCRIPTOR_COOKIE_LEN);
  1500. }
  1501. tor_free(descriptor_cookie);
  1502. /* This makes sense too, because, in case of error, this is zero. */
  1503. return encrypted_len;
  1504. }
  1505. /* Given the token tok for an intro point legacy key, the list of tokens, the
  1506. * introduction point ip being decoded and the descriptor desc from which it
  1507. * comes from, decode the legacy key and set the intro point object. Return 0
  1508. * on success else -1 on failure. */
  1509. static int
  1510. decode_intro_legacy_key(const directory_token_t *tok,
  1511. smartlist_t *tokens,
  1512. hs_desc_intro_point_t *ip,
  1513. const hs_descriptor_t *desc)
  1514. {
  1515. tor_assert(tok);
  1516. tor_assert(tokens);
  1517. tor_assert(ip);
  1518. tor_assert(desc);
  1519. if (!crypto_pk_public_exponent_ok(tok->key)) {
  1520. log_warn(LD_REND, "Introduction point legacy key is invalid");
  1521. goto err;
  1522. }
  1523. ip->legacy.key = crypto_pk_dup_key(tok->key);
  1524. /* Extract the legacy cross certification cert which MUST be present if we
  1525. * have a legacy key. */
  1526. tok = find_opt_by_keyword(tokens, R3_INTRO_LEGACY_KEY_CERT);
  1527. if (!tok) {
  1528. log_warn(LD_REND, "Introduction point legacy key cert is missing");
  1529. goto err;
  1530. }
  1531. tor_assert(tok->object_body);
  1532. if (strcmp(tok->object_type, "CROSSCERT")) {
  1533. /* Info level because this might be an unknown field that we should
  1534. * ignore. */
  1535. log_info(LD_REND, "Introduction point legacy encryption key "
  1536. "cross-certification has an unknown format.");
  1537. goto err;
  1538. }
  1539. /* Keep a copy of the certificate. */
  1540. ip->legacy.cert.encoded = tor_memdup(tok->object_body, tok->object_size);
  1541. ip->legacy.cert.len = tok->object_size;
  1542. /* The check on the expiration date is for the entire lifetime of a
  1543. * certificate which is 24 hours. However, a descriptor has a maximum
  1544. * lifetime of 12 hours meaning we have a 12h difference between the two
  1545. * which ultimately accommodate the clock skewed client. */
  1546. if (rsa_ed25519_crosscert_check(ip->legacy.cert.encoded,
  1547. ip->legacy.cert.len, ip->legacy.key,
  1548. &desc->plaintext_data.signing_pubkey,
  1549. approx_time() - HS_DESC_CERT_LIFETIME)) {
  1550. log_warn(LD_REND, "Unable to check cross-certification on the "
  1551. "introduction point legacy encryption key.");
  1552. ip->cross_certified = 0;
  1553. goto err;
  1554. }
  1555. /* Success. */
  1556. return 0;
  1557. err:
  1558. return -1;
  1559. }
  1560. /* Dig into the descriptor <b>tokens</b> to find the onion key we should use
  1561. * for this intro point, and set it into <b>onion_key_out</b>. Return 0 if it
  1562. * was found and well-formed, otherwise return -1 in case of errors. */
  1563. static int
  1564. set_intro_point_onion_key(curve25519_public_key_t *onion_key_out,
  1565. const smartlist_t *tokens)
  1566. {
  1567. int retval = -1;
  1568. smartlist_t *onion_keys = NULL;
  1569. tor_assert(onion_key_out);
  1570. onion_keys = find_all_by_keyword(tokens, R3_INTRO_ONION_KEY);
  1571. if (!onion_keys) {
  1572. log_warn(LD_REND, "Descriptor did not contain intro onion keys");
  1573. goto err;
  1574. }
  1575. SMARTLIST_FOREACH_BEGIN(onion_keys, directory_token_t *, tok) {
  1576. /* This field is using GE(2) so for possible forward compatibility, we
  1577. * accept more fields but must be at least 2. */
  1578. tor_assert(tok->n_args >= 2);
  1579. /* Try to find an ntor key, it's the only recognized type right now */
  1580. if (!strcmp(tok->args[0], "ntor")) {
  1581. if (curve25519_public_from_base64(onion_key_out, tok->args[1]) < 0) {
  1582. log_warn(LD_REND, "Introduction point ntor onion-key is invalid");
  1583. goto err;
  1584. }
  1585. /* Got the onion key! Set the appropriate retval */
  1586. retval = 0;
  1587. }
  1588. } SMARTLIST_FOREACH_END(tok);
  1589. /* Log an error if we didn't find it :( */
  1590. if (retval < 0) {
  1591. log_warn(LD_REND, "Descriptor did not contain ntor onion keys");
  1592. }
  1593. err:
  1594. smartlist_free(onion_keys);
  1595. return retval;
  1596. }
  1597. /* Given the start of a section and the end of it, decode a single
  1598. * introduction point from that section. Return a newly allocated introduction
  1599. * point object containing the decoded data. Return NULL if the section can't
  1600. * be decoded. */
  1601. STATIC hs_desc_intro_point_t *
  1602. decode_introduction_point(const hs_descriptor_t *desc, const char *start)
  1603. {
  1604. hs_desc_intro_point_t *ip = NULL;
  1605. memarea_t *area = NULL;
  1606. smartlist_t *tokens = NULL;
  1607. const directory_token_t *tok;
  1608. tor_assert(desc);
  1609. tor_assert(start);
  1610. area = memarea_new();
  1611. tokens = smartlist_new();
  1612. if (tokenize_string(area, start, start + strlen(start),
  1613. tokens, hs_desc_intro_point_v3_token_table, 0) < 0) {
  1614. log_warn(LD_REND, "Introduction point is not parseable");
  1615. goto err;
  1616. }
  1617. /* Ok we seem to have a well formed section containing enough tokens to
  1618. * parse. Allocate our IP object and try to populate it. */
  1619. ip = hs_desc_intro_point_new();
  1620. /* "introduction-point" SP link-specifiers NL */
  1621. tok = find_by_keyword(tokens, R3_INTRODUCTION_POINT);
  1622. tor_assert(tok->n_args == 1);
  1623. /* Our constructor creates this list by default so free it. */
  1624. smartlist_free(ip->link_specifiers);
  1625. ip->link_specifiers = decode_link_specifiers(tok->args[0]);
  1626. if (!ip->link_specifiers) {
  1627. log_warn(LD_REND, "Introduction point has invalid link specifiers");
  1628. goto err;
  1629. }
  1630. /* "onion-key" SP ntor SP key NL */
  1631. if (set_intro_point_onion_key(&ip->onion_key, tokens) < 0) {
  1632. goto err;
  1633. }
  1634. /* "auth-key" NL certificate NL */
  1635. tok = find_by_keyword(tokens, R3_INTRO_AUTH_KEY);
  1636. tor_assert(tok->object_body);
  1637. if (strcmp(tok->object_type, "ED25519 CERT")) {
  1638. log_warn(LD_REND, "Unexpected object type for introduction auth key");
  1639. goto err;
  1640. }
  1641. /* Parse cert and do some validation. */
  1642. if (cert_parse_and_validate(&ip->auth_key_cert, tok->object_body,
  1643. tok->object_size, CERT_TYPE_AUTH_HS_IP_KEY,
  1644. "introduction point auth-key") < 0) {
  1645. goto err;
  1646. }
  1647. /* Validate authentication certificate with descriptor signing key. */
  1648. if (tor_cert_checksig(ip->auth_key_cert,
  1649. &desc->plaintext_data.signing_pubkey, 0) < 0) {
  1650. log_warn(LD_REND, "Invalid authentication key signature: %s",
  1651. tor_cert_describe_signature_status(ip->auth_key_cert));
  1652. goto err;
  1653. }
  1654. /* Exactly one "enc-key" SP "ntor" SP key NL */
  1655. tok = find_by_keyword(tokens, R3_INTRO_ENC_KEY);
  1656. if (!strcmp(tok->args[0], "ntor")) {
  1657. /* This field is using GE(2) so for possible forward compatibility, we
  1658. * accept more fields but must be at least 2. */
  1659. tor_assert(tok->n_args >= 2);
  1660. if (curve25519_public_from_base64(&ip->enc_key, tok->args[1]) < 0) {
  1661. log_warn(LD_REND, "Introduction point ntor enc-key is invalid");
  1662. goto err;
  1663. }
  1664. } else {
  1665. /* Unknown key type so we can't use that introduction point. */
  1666. log_warn(LD_REND, "Introduction point encryption key is unrecognized.");
  1667. goto err;
  1668. }
  1669. /* Exactly once "enc-key-cert" NL certificate NL */
  1670. tok = find_by_keyword(tokens, R3_INTRO_ENC_KEY_CERT);
  1671. tor_assert(tok->object_body);
  1672. /* Do the cross certification. */
  1673. if (strcmp(tok->object_type, "ED25519 CERT")) {
  1674. log_warn(LD_REND, "Introduction point ntor encryption key "
  1675. "cross-certification has an unknown format.");
  1676. goto err;
  1677. }
  1678. if (cert_parse_and_validate(&ip->enc_key_cert, tok->object_body,
  1679. tok->object_size, CERT_TYPE_CROSS_HS_IP_KEYS,
  1680. "introduction point enc-key-cert") < 0) {
  1681. goto err;
  1682. }
  1683. if (tor_cert_checksig(ip->enc_key_cert,
  1684. &desc->plaintext_data.signing_pubkey, 0) < 0) {
  1685. log_warn(LD_REND, "Invalid encryption key signature: %s",
  1686. tor_cert_describe_signature_status(ip->enc_key_cert));
  1687. goto err;
  1688. }
  1689. /* It is successfully cross certified. Flag the object. */
  1690. ip->cross_certified = 1;
  1691. /* Do we have a "legacy-key" SP key NL ?*/
  1692. tok = find_opt_by_keyword(tokens, R3_INTRO_LEGACY_KEY);
  1693. if (tok) {
  1694. if (decode_intro_legacy_key(tok, tokens, ip, desc) < 0) {
  1695. goto err;
  1696. }
  1697. }
  1698. /* Introduction point has been parsed successfully. */
  1699. goto done;
  1700. err:
  1701. hs_desc_intro_point_free(ip);
  1702. ip = NULL;
  1703. done:
  1704. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1705. smartlist_free(tokens);
  1706. if (area) {
  1707. memarea_drop_all(area);
  1708. }
  1709. return ip;
  1710. }
  1711. /* Given a descriptor string at <b>data</b>, decode all possible introduction
  1712. * points that we can find. Add the introduction point object to desc_enc as we
  1713. * find them. This function can't fail and it is possible that zero
  1714. * introduction points can be decoded. */
  1715. static void
  1716. decode_intro_points(const hs_descriptor_t *desc,
  1717. hs_desc_encrypted_data_t *desc_enc,
  1718. const char *data)
  1719. {
  1720. smartlist_t *chunked_desc = smartlist_new();
  1721. smartlist_t *intro_points = smartlist_new();
  1722. tor_assert(desc);
  1723. tor_assert(desc_enc);
  1724. tor_assert(data);
  1725. tor_assert(desc_enc->intro_points);
  1726. /* Take the desc string, and extract the intro point substrings out of it */
  1727. {
  1728. /* Split the descriptor string using the intro point header as delimiter */
  1729. smartlist_split_string(chunked_desc, data, str_intro_point_start, 0, 0);
  1730. /* Check if there are actually any intro points included. The first chunk
  1731. * should be other descriptor fields (e.g. create2-formats), so it's not an
  1732. * intro point. */
  1733. if (smartlist_len(chunked_desc) < 2) {
  1734. goto done;
  1735. }
  1736. }
  1737. /* Take the intro point substrings, and prepare them for parsing */
  1738. {
  1739. int i = 0;
  1740. /* Prepend the introduction-point header to all the chunks, since
  1741. smartlist_split_string() devoured it. */
  1742. SMARTLIST_FOREACH_BEGIN(chunked_desc, char *, chunk) {
  1743. /* Ignore first chunk. It's other descriptor fields. */
  1744. if (i++ == 0) {
  1745. continue;
  1746. }
  1747. smartlist_add_asprintf(intro_points, "%s %s", str_intro_point, chunk);
  1748. } SMARTLIST_FOREACH_END(chunk);
  1749. }
  1750. /* Parse the intro points! */
  1751. SMARTLIST_FOREACH_BEGIN(intro_points, const char *, intro_point) {
  1752. hs_desc_intro_point_t *ip = decode_introduction_point(desc, intro_point);
  1753. if (!ip) {
  1754. /* Malformed introduction point section. We'll ignore this introduction
  1755. * point and continue parsing. New or unknown fields are possible for
  1756. * forward compatibility. */
  1757. continue;
  1758. }
  1759. smartlist_add(desc_enc->intro_points, ip);
  1760. } SMARTLIST_FOREACH_END(intro_point);
  1761. done:
  1762. SMARTLIST_FOREACH(chunked_desc, char *, a, tor_free(a));
  1763. smartlist_free(chunked_desc);
  1764. SMARTLIST_FOREACH(intro_points, char *, a, tor_free(a));
  1765. smartlist_free(intro_points);
  1766. }
  1767. /* Return 1 iff the given base64 encoded signature in b64_sig from the encoded
  1768. * descriptor in encoded_desc validates the descriptor content. */
  1769. STATIC int
  1770. desc_sig_is_valid(const char *b64_sig,
  1771. const ed25519_public_key_t *signing_pubkey,
  1772. const char *encoded_desc, size_t encoded_len)
  1773. {
  1774. int ret = 0;
  1775. ed25519_signature_t sig;
  1776. const char *sig_start;
  1777. tor_assert(b64_sig);
  1778. tor_assert(signing_pubkey);
  1779. tor_assert(encoded_desc);
  1780. /* Verifying nothing won't end well :). */
  1781. tor_assert(encoded_len > 0);
  1782. /* Signature length check. */
  1783. if (strlen(b64_sig) != ED25519_SIG_BASE64_LEN) {
  1784. log_warn(LD_REND, "Service descriptor has an invalid signature length."
  1785. "Exptected %d but got %lu",
  1786. ED25519_SIG_BASE64_LEN, (unsigned long) strlen(b64_sig));
  1787. goto err;
  1788. }
  1789. /* First, convert base64 blob to an ed25519 signature. */
  1790. if (ed25519_signature_from_base64(&sig, b64_sig) != 0) {
  1791. log_warn(LD_REND, "Service descriptor does not contain a valid "
  1792. "signature");
  1793. goto err;
  1794. }
  1795. /* Find the start of signature. */
  1796. sig_start = tor_memstr(encoded_desc, encoded_len, "\n" str_signature " ");
  1797. /* Getting here means the token parsing worked for the signature so if we
  1798. * can't find the start of the signature, we have a code flow issue. */
  1799. if (!sig_start) {
  1800. log_warn(LD_GENERAL, "Malformed signature line. Rejecting.");
  1801. goto err;
  1802. }
  1803. /* Skip newline, it has to go in the signature check. */
  1804. sig_start++;
  1805. /* Validate signature with the full body of the descriptor. */
  1806. if (ed25519_checksig_prefixed(&sig,
  1807. (const uint8_t *) encoded_desc,
  1808. sig_start - encoded_desc,
  1809. str_desc_sig_prefix,
  1810. signing_pubkey) != 0) {
  1811. log_warn(LD_REND, "Invalid signature on service descriptor");
  1812. goto err;
  1813. }
  1814. /* Valid signature! All is good. */
  1815. ret = 1;
  1816. err:
  1817. return ret;
  1818. }
  1819. /* Decode descriptor plaintext data for version 3. Given a list of tokens, an
  1820. * allocated plaintext object that will be populated and the encoded
  1821. * descriptor with its length. The last one is needed for signature
  1822. * verification. Unknown tokens are simply ignored so this won't error on
  1823. * unknowns but requires that all v3 token be present and valid.
  1824. *
  1825. * Return 0 on success else a negative value. */
  1826. static int
  1827. desc_decode_plaintext_v3(smartlist_t *tokens,
  1828. hs_desc_plaintext_data_t *desc,
  1829. const char *encoded_desc, size_t encoded_len)
  1830. {
  1831. int ok;
  1832. directory_token_t *tok;
  1833. tor_assert(tokens);
  1834. tor_assert(desc);
  1835. /* Version higher could still use this function to decode most of the
  1836. * descriptor and then they decode the extra part. */
  1837. tor_assert(desc->version >= 3);
  1838. /* Descriptor lifetime parsing. */
  1839. tok = find_by_keyword(tokens, R3_DESC_LIFETIME);
  1840. tor_assert(tok->n_args == 1);
  1841. desc->lifetime_sec = (uint32_t) tor_parse_ulong(tok->args[0], 10, 0,
  1842. UINT32_MAX, &ok, NULL);
  1843. if (!ok) {
  1844. log_warn(LD_REND, "Service descriptor lifetime value is invalid");
  1845. goto err;
  1846. }
  1847. /* Put it from minute to second. */
  1848. desc->lifetime_sec *= 60;
  1849. if (desc->lifetime_sec > HS_DESC_MAX_LIFETIME) {
  1850. log_warn(LD_REND, "Service descriptor lifetime is too big. "
  1851. "Got %" PRIu32 " but max is %d",
  1852. desc->lifetime_sec, HS_DESC_MAX_LIFETIME);
  1853. goto err;
  1854. }
  1855. /* Descriptor signing certificate. */
  1856. tok = find_by_keyword(tokens, R3_DESC_SIGNING_CERT);
  1857. tor_assert(tok->object_body);
  1858. /* Expecting a prop220 cert with the signing key extension, which contains
  1859. * the blinded public key. */
  1860. if (strcmp(tok->object_type, "ED25519 CERT") != 0) {
  1861. log_warn(LD_REND, "Service descriptor signing cert wrong type (%s)",
  1862. escaped(tok->object_type));
  1863. goto err;
  1864. }
  1865. if (cert_parse_and_validate(&desc->signing_key_cert, tok->object_body,
  1866. tok->object_size, CERT_TYPE_SIGNING_HS_DESC,
  1867. "service descriptor signing key") < 0) {
  1868. goto err;
  1869. }
  1870. /* Copy the public keys into signing_pubkey and blinded_pubkey */
  1871. memcpy(&desc->signing_pubkey, &desc->signing_key_cert->signed_key,
  1872. sizeof(ed25519_public_key_t));
  1873. memcpy(&desc->blinded_pubkey, &desc->signing_key_cert->signing_key,
  1874. sizeof(ed25519_public_key_t));
  1875. /* Extract revision counter value. */
  1876. tok = find_by_keyword(tokens, R3_REVISION_COUNTER);
  1877. tor_assert(tok->n_args == 1);
  1878. desc->revision_counter = tor_parse_uint64(tok->args[0], 10, 0,
  1879. UINT64_MAX, &ok, NULL);
  1880. if (!ok) {
  1881. log_warn(LD_REND, "Service descriptor revision-counter is invalid");
  1882. goto err;
  1883. }
  1884. /* Extract the superencrypted data section. */
  1885. tok = find_by_keyword(tokens, R3_SUPERENCRYPTED);
  1886. tor_assert(tok->object_body);
  1887. if (strcmp(tok->object_type, "MESSAGE") != 0) {
  1888. log_warn(LD_REND, "Desc superencrypted data section is invalid");
  1889. goto err;
  1890. }
  1891. /* Make sure the length of the superencrypted blob is valid. */
  1892. if (!encrypted_data_length_is_valid(tok->object_size)) {
  1893. goto err;
  1894. }
  1895. /* Copy the superencrypted blob to the descriptor object so we can handle it
  1896. * latter if needed. */
  1897. desc->superencrypted_blob = tor_memdup(tok->object_body, tok->object_size);
  1898. desc->superencrypted_blob_size = tok->object_size;
  1899. /* Extract signature and verify it. */
  1900. tok = find_by_keyword(tokens, R3_SIGNATURE);
  1901. tor_assert(tok->n_args == 1);
  1902. /* First arg here is the actual encoded signature. */
  1903. if (!desc_sig_is_valid(tok->args[0], &desc->signing_pubkey,
  1904. encoded_desc, encoded_len)) {
  1905. goto err;
  1906. }
  1907. return 0;
  1908. err:
  1909. return -1;
  1910. }
  1911. /* Decode the version 3 superencrypted section of the given descriptor desc.
  1912. * The desc_superencrypted_out will be populated with the decoded data.
  1913. * Return 0 on success else -1. */
  1914. static int
  1915. desc_decode_superencrypted_v3(const hs_descriptor_t *desc,
  1916. hs_desc_superencrypted_data_t *
  1917. desc_superencrypted_out)
  1918. {
  1919. int ret = -1;
  1920. char *message = NULL;
  1921. size_t message_len;
  1922. memarea_t *area = NULL;
  1923. directory_token_t *tok;
  1924. smartlist_t *tokens = NULL;
  1925. /* Rename the parameter because it is too long. */
  1926. hs_desc_superencrypted_data_t *superencrypted = desc_superencrypted_out;
  1927. tor_assert(desc);
  1928. tor_assert(desc_superencrypted_out);
  1929. /* Decrypt the superencrypted data that is located in the plaintext section
  1930. * in the descriptor as a blob of bytes. */
  1931. message_len = desc_decrypt_superencrypted(desc, &message);
  1932. if (!message_len) {
  1933. log_warn(LD_REND, "Service descriptor decryption failed.");
  1934. goto err;
  1935. }
  1936. tor_assert(message);
  1937. area = memarea_new();
  1938. tokens = smartlist_new();
  1939. if (tokenize_string(area, message, message + message_len,
  1940. tokens, hs_desc_superencrypted_v3_token_table, 0) < 0) {
  1941. log_warn(LD_REND, "Superencrypted service descriptor is not parseable.");
  1942. goto err;
  1943. }
  1944. /* Verify desc auth type */
  1945. tok = find_by_keyword(tokens, R3_DESC_AUTH_TYPE);
  1946. tor_assert(tok->n_args >= 1);
  1947. if (strcmp(tok->args[0], "x25519")) {
  1948. log_warn(LD_DIR, "Unrecognized desc auth type");
  1949. goto err;
  1950. }
  1951. /* Extract desc auth ephemeral key */
  1952. tok = find_by_keyword(tokens, R3_DESC_AUTH_KEY);
  1953. tor_assert(tok->n_args >= 1);
  1954. if (curve25519_public_from_base64(&superencrypted->auth_ephemeral_pubkey,
  1955. tok->args[0]) < 0) {
  1956. log_warn(LD_DIR, "Bogus desc auth ephemeral key in HS desc");
  1957. goto err;
  1958. }
  1959. /* Extract desc auth client items */
  1960. if (!superencrypted->clients) {
  1961. superencrypted->clients = smartlist_new();
  1962. }
  1963. SMARTLIST_FOREACH_BEGIN(tokens, const directory_token_t *, token) {
  1964. if (token->tp == R3_DESC_AUTH_CLIENT) {
  1965. tor_assert(token->n_args >= 3);
  1966. hs_desc_authorized_client_t *client =
  1967. tor_malloc_zero(sizeof(hs_desc_authorized_client_t));
  1968. if (decode_auth_client(token, client) < 0) {
  1969. log_warn(LD_REND, "Descriptor client authorization section can't "
  1970. "be decoded.");
  1971. tor_free(client);
  1972. goto err;
  1973. }
  1974. smartlist_add(superencrypted->clients, client);
  1975. }
  1976. } SMARTLIST_FOREACH_END(token);
  1977. /* Extract the encrypted data section. */
  1978. tok = find_by_keyword(tokens, R3_ENCRYPTED);
  1979. tor_assert(tok->object_body);
  1980. if (strcmp(tok->object_type, "MESSAGE") != 0) {
  1981. log_warn(LD_REND, "Desc encrypted data section is invalid");
  1982. goto err;
  1983. }
  1984. /* Make sure the length of the encrypted blob is valid. */
  1985. if (!encrypted_data_length_is_valid(tok->object_size)) {
  1986. goto err;
  1987. }
  1988. /* Copy the encrypted blob to the descriptor object so we can handle it
  1989. * latter if needed. */
  1990. tor_assert(tok->object_size <= INT_MAX);
  1991. superencrypted->encrypted_blob = tor_memdup(tok->object_body,
  1992. tok->object_size);
  1993. superencrypted->encrypted_blob_size = tok->object_size;
  1994. ret = 0;
  1995. goto done;
  1996. err:
  1997. tor_assert(ret < 0);
  1998. hs_desc_superencrypted_data_free_contents(desc_superencrypted_out);
  1999. done:
  2000. if (tokens) {
  2001. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2002. smartlist_free(tokens);
  2003. }
  2004. if (area) {
  2005. memarea_drop_all(area);
  2006. }
  2007. if (message) {
  2008. tor_free(message);
  2009. }
  2010. return ret;
  2011. }
  2012. /* Decode the version 3 encrypted section of the given descriptor desc. The
  2013. * desc_encrypted_out will be populated with the decoded data. Return 0 on
  2014. * success else -1. */
  2015. static int
  2016. desc_decode_encrypted_v3(const hs_descriptor_t *desc,
  2017. const curve25519_secret_key_t *client_auth_sk,
  2018. hs_desc_encrypted_data_t *desc_encrypted_out)
  2019. {
  2020. int ret = -1;
  2021. char *message = NULL;
  2022. size_t message_len;
  2023. memarea_t *area = NULL;
  2024. directory_token_t *tok;
  2025. smartlist_t *tokens = NULL;
  2026. tor_assert(desc);
  2027. tor_assert(desc_encrypted_out);
  2028. /* Decrypt the encrypted data that is located in the superencrypted section
  2029. * in the descriptor as a blob of bytes. */
  2030. message_len = desc_decrypt_encrypted(desc, client_auth_sk, &message);
  2031. if (!message_len) {
  2032. /* Two possible situation here. Either we have a client authorization
  2033. * configured that didn't work or we do not have any configured for this
  2034. * onion address so likely the descriptor is for authorized client only,
  2035. * we are not. */
  2036. if (client_auth_sk) {
  2037. /* At warning level so the client can notice that its client
  2038. * authorization is failing. */
  2039. log_warn(LD_REND, "Client authorization for requested onion address "
  2040. "is invalid. Can't decrypt the descriptor.");
  2041. } else {
  2042. /* Inform at notice level that the onion address requested can't be
  2043. * reached without client authorization most likely. */
  2044. log_notice(LD_REND, "Fail to decrypt descriptor for requested onion "
  2045. "address. It is likely requiring client "
  2046. "authorization.");
  2047. }
  2048. goto err;
  2049. }
  2050. tor_assert(message);
  2051. area = memarea_new();
  2052. tokens = smartlist_new();
  2053. if (tokenize_string(area, message, message + message_len,
  2054. tokens, hs_desc_encrypted_v3_token_table, 0) < 0) {
  2055. log_warn(LD_REND, "Encrypted service descriptor is not parseable.");
  2056. goto err;
  2057. }
  2058. /* CREATE2 supported cell format. It's mandatory. */
  2059. tok = find_by_keyword(tokens, R3_CREATE2_FORMATS);
  2060. tor_assert(tok);
  2061. decode_create2_list(desc_encrypted_out, tok->args[0]);
  2062. /* Must support ntor according to the specification */
  2063. if (!desc_encrypted_out->create2_ntor) {
  2064. log_warn(LD_REND, "Service create2-formats does not include ntor.");
  2065. goto err;
  2066. }
  2067. /* Authentication type. It's optional but only once. */
  2068. tok = find_opt_by_keyword(tokens, R3_INTRO_AUTH_REQUIRED);
  2069. if (tok) {
  2070. if (!decode_auth_type(desc_encrypted_out, tok->args[0])) {
  2071. log_warn(LD_REND, "Service descriptor authentication type has "
  2072. "invalid entry(ies).");
  2073. goto err;
  2074. }
  2075. }
  2076. /* Is this service a single onion service? */
  2077. tok = find_opt_by_keyword(tokens, R3_SINGLE_ONION_SERVICE);
  2078. if (tok) {
  2079. desc_encrypted_out->single_onion_service = 1;
  2080. }
  2081. /* Initialize the descriptor's introduction point list before we start
  2082. * decoding. Having 0 intro point is valid. Then decode them all. */
  2083. desc_encrypted_out->intro_points = smartlist_new();
  2084. decode_intro_points(desc, desc_encrypted_out, message);
  2085. /* Validation of maximum introduction points allowed. */
  2086. if (smartlist_len(desc_encrypted_out->intro_points) >
  2087. HS_CONFIG_V3_MAX_INTRO_POINTS) {
  2088. log_warn(LD_REND, "Service descriptor contains too many introduction "
  2089. "points. Maximum allowed is %d but we have %d",
  2090. HS_CONFIG_V3_MAX_INTRO_POINTS,
  2091. smartlist_len(desc_encrypted_out->intro_points));
  2092. goto err;
  2093. }
  2094. /* NOTE: Unknown fields are allowed because this function could be used to
  2095. * decode other descriptor version. */
  2096. ret = 0;
  2097. goto done;
  2098. err:
  2099. tor_assert(ret < 0);
  2100. hs_desc_encrypted_data_free_contents(desc_encrypted_out);
  2101. done:
  2102. if (tokens) {
  2103. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2104. smartlist_free(tokens);
  2105. }
  2106. if (area) {
  2107. memarea_drop_all(area);
  2108. }
  2109. if (message) {
  2110. tor_free(message);
  2111. }
  2112. return ret;
  2113. }
  2114. /* Table of encrypted decode function version specific. The function are
  2115. * indexed by the version number so v3 callback is at index 3 in the array. */
  2116. static int
  2117. (*decode_encrypted_handlers[])(
  2118. const hs_descriptor_t *desc,
  2119. const curve25519_secret_key_t *client_auth_sk,
  2120. hs_desc_encrypted_data_t *desc_encrypted) =
  2121. {
  2122. /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
  2123. desc_decode_encrypted_v3,
  2124. };
  2125. /* Decode the encrypted data section of the given descriptor and store the
  2126. * data in the given encrypted data object. Return 0 on success else a
  2127. * negative value on error. */
  2128. int
  2129. hs_desc_decode_encrypted(const hs_descriptor_t *desc,
  2130. const curve25519_secret_key_t *client_auth_sk,
  2131. hs_desc_encrypted_data_t *desc_encrypted)
  2132. {
  2133. int ret;
  2134. uint32_t version;
  2135. tor_assert(desc);
  2136. /* Ease our life a bit. */
  2137. version = desc->plaintext_data.version;
  2138. tor_assert(desc_encrypted);
  2139. /* Calling this function without an encrypted blob to parse is a code flow
  2140. * error. The superencrypted parsing should never succeed in the first place
  2141. * without an encrypted section. */
  2142. tor_assert(desc->superencrypted_data.encrypted_blob);
  2143. /* Let's make sure we have a supported version as well. By correctly parsing
  2144. * the plaintext, this should not fail. */
  2145. if (BUG(!hs_desc_is_supported_version(version))) {
  2146. ret = -1;
  2147. goto err;
  2148. }
  2149. /* Extra precaution. Having no handler for the supported version should
  2150. * never happened else we forgot to add it but we bumped the version. */
  2151. tor_assert(ARRAY_LENGTH(decode_encrypted_handlers) >= version);
  2152. tor_assert(decode_encrypted_handlers[version]);
  2153. /* Run the version specific plaintext decoder. */
  2154. ret = decode_encrypted_handlers[version](desc, client_auth_sk,
  2155. desc_encrypted);
  2156. if (ret < 0) {
  2157. goto err;
  2158. }
  2159. err:
  2160. return ret;
  2161. }
  2162. /* Table of superencrypted decode function version specific. The function are
  2163. * indexed by the version number so v3 callback is at index 3 in the array. */
  2164. static int
  2165. (*decode_superencrypted_handlers[])(
  2166. const hs_descriptor_t *desc,
  2167. hs_desc_superencrypted_data_t *desc_superencrypted) =
  2168. {
  2169. /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
  2170. desc_decode_superencrypted_v3,
  2171. };
  2172. /* Decode the superencrypted data section of the given descriptor and store the
  2173. * data in the given superencrypted data object. Return 0 on success else a
  2174. * negative value on error. */
  2175. int
  2176. hs_desc_decode_superencrypted(const hs_descriptor_t *desc,
  2177. hs_desc_superencrypted_data_t *
  2178. desc_superencrypted)
  2179. {
  2180. int ret;
  2181. uint32_t version;
  2182. tor_assert(desc);
  2183. /* Ease our life a bit. */
  2184. version = desc->plaintext_data.version;
  2185. tor_assert(desc_superencrypted);
  2186. /* Calling this function without an superencrypted blob to parse is
  2187. * a code flow error. The plaintext parsing should never succeed in
  2188. * the first place without an superencrypted section. */
  2189. tor_assert(desc->plaintext_data.superencrypted_blob);
  2190. /* Let's make sure we have a supported version as well. By correctly parsing
  2191. * the plaintext, this should not fail. */
  2192. if (BUG(!hs_desc_is_supported_version(version))) {
  2193. ret = -1;
  2194. goto err;
  2195. }
  2196. /* Extra precaution. Having no handler for the supported version should
  2197. * never happened else we forgot to add it but we bumped the version. */
  2198. tor_assert(ARRAY_LENGTH(decode_superencrypted_handlers) >= version);
  2199. tor_assert(decode_superencrypted_handlers[version]);
  2200. /* Run the version specific plaintext decoder. */
  2201. ret = decode_superencrypted_handlers[version](desc, desc_superencrypted);
  2202. if (ret < 0) {
  2203. goto err;
  2204. }
  2205. err:
  2206. return ret;
  2207. }
  2208. /* Table of plaintext decode function version specific. The function are
  2209. * indexed by the version number so v3 callback is at index 3 in the array. */
  2210. static int
  2211. (*decode_plaintext_handlers[])(
  2212. smartlist_t *tokens,
  2213. hs_desc_plaintext_data_t *desc,
  2214. const char *encoded_desc,
  2215. size_t encoded_len) =
  2216. {
  2217. /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
  2218. desc_decode_plaintext_v3,
  2219. };
  2220. /* Fully decode the given descriptor plaintext and store the data in the
  2221. * plaintext data object. Returns 0 on success else a negative value. */
  2222. int
  2223. hs_desc_decode_plaintext(const char *encoded,
  2224. hs_desc_plaintext_data_t *plaintext)
  2225. {
  2226. int ok = 0, ret = -1;
  2227. memarea_t *area = NULL;
  2228. smartlist_t *tokens = NULL;
  2229. size_t encoded_len;
  2230. directory_token_t *tok;
  2231. tor_assert(encoded);
  2232. tor_assert(plaintext);
  2233. /* Check that descriptor is within size limits. */
  2234. encoded_len = strlen(encoded);
  2235. if (encoded_len >= hs_cache_get_max_descriptor_size()) {
  2236. log_warn(LD_REND, "Service descriptor is too big (%lu bytes)",
  2237. (unsigned long) encoded_len);
  2238. goto err;
  2239. }
  2240. area = memarea_new();
  2241. tokens = smartlist_new();
  2242. /* Tokenize the descriptor so we can start to parse it. */
  2243. if (tokenize_string(area, encoded, encoded + encoded_len, tokens,
  2244. hs_desc_v3_token_table, 0) < 0) {
  2245. log_warn(LD_REND, "Service descriptor is not parseable");
  2246. goto err;
  2247. }
  2248. /* Get the version of the descriptor which is the first mandatory field of
  2249. * the descriptor. From there, we'll decode the right descriptor version. */
  2250. tok = find_by_keyword(tokens, R_HS_DESCRIPTOR);
  2251. tor_assert(tok->n_args == 1);
  2252. plaintext->version = (uint32_t) tor_parse_ulong(tok->args[0], 10, 0,
  2253. UINT32_MAX, &ok, NULL);
  2254. if (!ok) {
  2255. log_warn(LD_REND, "Service descriptor has unparseable version %s",
  2256. escaped(tok->args[0]));
  2257. goto err;
  2258. }
  2259. if (!hs_desc_is_supported_version(plaintext->version)) {
  2260. log_warn(LD_REND, "Service descriptor has unsupported version %" PRIu32,
  2261. plaintext->version);
  2262. goto err;
  2263. }
  2264. /* Extra precaution. Having no handler for the supported version should
  2265. * never happened else we forgot to add it but we bumped the version. */
  2266. tor_assert(ARRAY_LENGTH(decode_plaintext_handlers) >= plaintext->version);
  2267. tor_assert(decode_plaintext_handlers[plaintext->version]);
  2268. /* Run the version specific plaintext decoder. */
  2269. ret = decode_plaintext_handlers[plaintext->version](tokens, plaintext,
  2270. encoded, encoded_len);
  2271. if (ret < 0) {
  2272. goto err;
  2273. }
  2274. /* Success. Descriptor has been populated with the data. */
  2275. ret = 0;
  2276. err:
  2277. if (tokens) {
  2278. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2279. smartlist_free(tokens);
  2280. }
  2281. if (area) {
  2282. memarea_drop_all(area);
  2283. }
  2284. return ret;
  2285. }
  2286. /* Fully decode an encoded descriptor and set a newly allocated descriptor
  2287. * object in desc_out. Client secret key is used to decrypt the "encrypted"
  2288. * section if not NULL else it's ignored.
  2289. *
  2290. * Return 0 on success. A negative value is returned on error and desc_out is
  2291. * set to NULL. */
  2292. int
  2293. hs_desc_decode_descriptor(const char *encoded,
  2294. const uint8_t *subcredential,
  2295. const curve25519_secret_key_t *client_auth_sk,
  2296. hs_descriptor_t **desc_out)
  2297. {
  2298. int ret = -1;
  2299. hs_descriptor_t *desc;
  2300. tor_assert(encoded);
  2301. desc = tor_malloc_zero(sizeof(hs_descriptor_t));
  2302. /* Subcredentials are not optional. */
  2303. if (BUG(!subcredential ||
  2304. tor_mem_is_zero((char*)subcredential, DIGEST256_LEN))) {
  2305. log_warn(LD_GENERAL, "Tried to decrypt without subcred. Impossible!");
  2306. goto err;
  2307. }
  2308. memcpy(desc->subcredential, subcredential, sizeof(desc->subcredential));
  2309. ret = hs_desc_decode_plaintext(encoded, &desc->plaintext_data);
  2310. if (ret < 0) {
  2311. goto err;
  2312. }
  2313. ret = hs_desc_decode_superencrypted(desc, &desc->superencrypted_data);
  2314. if (ret < 0) {
  2315. goto err;
  2316. }
  2317. ret = hs_desc_decode_encrypted(desc, client_auth_sk, &desc->encrypted_data);
  2318. if (ret < 0) {
  2319. goto err;
  2320. }
  2321. if (desc_out) {
  2322. *desc_out = desc;
  2323. } else {
  2324. hs_descriptor_free(desc);
  2325. }
  2326. return ret;
  2327. err:
  2328. hs_descriptor_free(desc);
  2329. if (desc_out) {
  2330. *desc_out = NULL;
  2331. }
  2332. tor_assert(ret < 0);
  2333. return ret;
  2334. }
  2335. /* Table of encode function version specific. The functions are indexed by the
  2336. * version number so v3 callback is at index 3 in the array. */
  2337. static int
  2338. (*encode_handlers[])(
  2339. const hs_descriptor_t *desc,
  2340. const ed25519_keypair_t *signing_kp,
  2341. const uint8_t *descriptor_cookie,
  2342. char **encoded_out) =
  2343. {
  2344. /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
  2345. desc_encode_v3,
  2346. };
  2347. /* Encode the given descriptor desc including signing with the given key pair
  2348. * signing_kp and encrypting with the given descriptor cookie.
  2349. *
  2350. * If the client authorization is enabled, descriptor_cookie must be the same
  2351. * as the one used to build hs_desc_authorized_client_t in the descriptor.
  2352. * Otherwise, it must be NULL. On success, encoded_out points to a newly
  2353. * allocated NUL terminated string that contains the encoded descriptor as
  2354. * a string.
  2355. *
  2356. * Return 0 on success and encoded_out is a valid pointer. On error, -1 is
  2357. * returned and encoded_out is set to NULL. */
  2358. MOCK_IMPL(int,
  2359. hs_desc_encode_descriptor,(const hs_descriptor_t *desc,
  2360. const ed25519_keypair_t *signing_kp,
  2361. const uint8_t *descriptor_cookie,
  2362. char **encoded_out))
  2363. {
  2364. int ret = -1;
  2365. uint32_t version;
  2366. tor_assert(desc);
  2367. tor_assert(encoded_out);
  2368. /* Make sure we support the version of the descriptor format. */
  2369. version = desc->plaintext_data.version;
  2370. if (!hs_desc_is_supported_version(version)) {
  2371. goto err;
  2372. }
  2373. /* Extra precaution. Having no handler for the supported version should
  2374. * never happened else we forgot to add it but we bumped the version. */
  2375. tor_assert(ARRAY_LENGTH(encode_handlers) >= version);
  2376. tor_assert(encode_handlers[version]);
  2377. ret = encode_handlers[version](desc, signing_kp,
  2378. descriptor_cookie, encoded_out);
  2379. if (ret < 0) {
  2380. goto err;
  2381. }
  2382. /* Try to decode what we just encoded. Symmetry is nice!, but it is
  2383. * symmetric only if the client auth is disabled. That is, the descriptor
  2384. * cookie will be NULL. */
  2385. if (!descriptor_cookie) {
  2386. ret = hs_desc_decode_descriptor(*encoded_out, desc->subcredential,
  2387. NULL, NULL);
  2388. if (BUG(ret < 0)) {
  2389. goto err;
  2390. }
  2391. }
  2392. return 0;
  2393. err:
  2394. *encoded_out = NULL;
  2395. return ret;
  2396. }
  2397. /* Free the content of the plaintext section of a descriptor. */
  2398. void
  2399. hs_desc_plaintext_data_free_contents(hs_desc_plaintext_data_t *desc)
  2400. {
  2401. if (!desc) {
  2402. return;
  2403. }
  2404. if (desc->superencrypted_blob) {
  2405. tor_free(desc->superencrypted_blob);
  2406. }
  2407. tor_cert_free(desc->signing_key_cert);
  2408. memwipe(desc, 0, sizeof(*desc));
  2409. }
  2410. /* Free the content of the superencrypted section of a descriptor. */
  2411. void
  2412. hs_desc_superencrypted_data_free_contents(hs_desc_superencrypted_data_t *desc)
  2413. {
  2414. if (!desc) {
  2415. return;
  2416. }
  2417. if (desc->encrypted_blob) {
  2418. tor_free(desc->encrypted_blob);
  2419. }
  2420. if (desc->clients) {
  2421. SMARTLIST_FOREACH(desc->clients, hs_desc_authorized_client_t *, client,
  2422. hs_desc_authorized_client_free(client));
  2423. smartlist_free(desc->clients);
  2424. }
  2425. memwipe(desc, 0, sizeof(*desc));
  2426. }
  2427. /* Free the content of the encrypted section of a descriptor. */
  2428. void
  2429. hs_desc_encrypted_data_free_contents(hs_desc_encrypted_data_t *desc)
  2430. {
  2431. if (!desc) {
  2432. return;
  2433. }
  2434. if (desc->intro_auth_types) {
  2435. SMARTLIST_FOREACH(desc->intro_auth_types, char *, a, tor_free(a));
  2436. smartlist_free(desc->intro_auth_types);
  2437. }
  2438. if (desc->intro_points) {
  2439. SMARTLIST_FOREACH(desc->intro_points, hs_desc_intro_point_t *, ip,
  2440. hs_desc_intro_point_free(ip));
  2441. smartlist_free(desc->intro_points);
  2442. }
  2443. memwipe(desc, 0, sizeof(*desc));
  2444. }
  2445. /* Free the descriptor plaintext data object. */
  2446. void
  2447. hs_desc_plaintext_data_free_(hs_desc_plaintext_data_t *desc)
  2448. {
  2449. hs_desc_plaintext_data_free_contents(desc);
  2450. tor_free(desc);
  2451. }
  2452. /* Free the descriptor plaintext data object. */
  2453. void
  2454. hs_desc_superencrypted_data_free_(hs_desc_superencrypted_data_t *desc)
  2455. {
  2456. hs_desc_superencrypted_data_free_contents(desc);
  2457. tor_free(desc);
  2458. }
  2459. /* Free the descriptor encrypted data object. */
  2460. void
  2461. hs_desc_encrypted_data_free_(hs_desc_encrypted_data_t *desc)
  2462. {
  2463. hs_desc_encrypted_data_free_contents(desc);
  2464. tor_free(desc);
  2465. }
  2466. /* Free the given descriptor object. */
  2467. void
  2468. hs_descriptor_free_(hs_descriptor_t *desc)
  2469. {
  2470. if (!desc) {
  2471. return;
  2472. }
  2473. hs_desc_plaintext_data_free_contents(&desc->plaintext_data);
  2474. hs_desc_superencrypted_data_free_contents(&desc->superencrypted_data);
  2475. hs_desc_encrypted_data_free_contents(&desc->encrypted_data);
  2476. tor_free(desc);
  2477. }
  2478. /* Return the size in bytes of the given plaintext data object. A sizeof() is
  2479. * not enough because the object contains pointers and the encrypted blob.
  2480. * This is particularly useful for our OOM subsystem that tracks the HSDir
  2481. * cache size for instance. */
  2482. size_t
  2483. hs_desc_plaintext_obj_size(const hs_desc_plaintext_data_t *data)
  2484. {
  2485. tor_assert(data);
  2486. return (sizeof(*data) + sizeof(*data->signing_key_cert) +
  2487. data->superencrypted_blob_size);
  2488. }
  2489. /* Return the size in bytes of the given encrypted data object. Used by OOM
  2490. * subsystem. */
  2491. static size_t
  2492. hs_desc_encrypted_obj_size(const hs_desc_encrypted_data_t *data)
  2493. {
  2494. tor_assert(data);
  2495. size_t intro_size = 0;
  2496. if (data->intro_auth_types) {
  2497. intro_size +=
  2498. smartlist_len(data->intro_auth_types) * sizeof(intro_auth_types);
  2499. }
  2500. if (data->intro_points) {
  2501. /* XXX could follow pointers here and get more accurate size */
  2502. intro_size +=
  2503. smartlist_len(data->intro_points) * sizeof(hs_desc_intro_point_t);
  2504. }
  2505. return sizeof(*data) + intro_size;
  2506. }
  2507. /* Return the size in bytes of the given descriptor object. Used by OOM
  2508. * subsystem. */
  2509. size_t
  2510. hs_desc_obj_size(const hs_descriptor_t *data)
  2511. {
  2512. tor_assert(data);
  2513. return (hs_desc_plaintext_obj_size(&data->plaintext_data) +
  2514. hs_desc_encrypted_obj_size(&data->encrypted_data) +
  2515. sizeof(data->subcredential));
  2516. }
  2517. /* Return a newly allocated descriptor intro point. */
  2518. hs_desc_intro_point_t *
  2519. hs_desc_intro_point_new(void)
  2520. {
  2521. hs_desc_intro_point_t *ip = tor_malloc_zero(sizeof(*ip));
  2522. ip->link_specifiers = smartlist_new();
  2523. return ip;
  2524. }
  2525. /* Free a descriptor intro point object. */
  2526. void
  2527. hs_desc_intro_point_free_(hs_desc_intro_point_t *ip)
  2528. {
  2529. if (ip == NULL) {
  2530. return;
  2531. }
  2532. if (ip->link_specifiers) {
  2533. SMARTLIST_FOREACH(ip->link_specifiers, hs_desc_link_specifier_t *,
  2534. ls, hs_desc_link_specifier_free(ls));
  2535. smartlist_free(ip->link_specifiers);
  2536. }
  2537. tor_cert_free(ip->auth_key_cert);
  2538. tor_cert_free(ip->enc_key_cert);
  2539. crypto_pk_free(ip->legacy.key);
  2540. tor_free(ip->legacy.cert.encoded);
  2541. tor_free(ip);
  2542. }
  2543. /* Allocate and build a new fake client info for the descriptor. Return a
  2544. * newly allocated object. This can't fail. */
  2545. hs_desc_authorized_client_t *
  2546. hs_desc_build_fake_authorized_client(void)
  2547. {
  2548. hs_desc_authorized_client_t *client_auth =
  2549. tor_malloc_zero(sizeof(*client_auth));
  2550. crypto_rand((char *) client_auth->client_id,
  2551. sizeof(client_auth->client_id));
  2552. crypto_rand((char *) client_auth->iv,
  2553. sizeof(client_auth->iv));
  2554. crypto_rand((char *) client_auth->encrypted_cookie,
  2555. sizeof(client_auth->encrypted_cookie));
  2556. return client_auth;
  2557. }
  2558. /* Using the service's subcredential, client public key, auth ephemeral secret
  2559. * key, and descriptor cookie, build the auth client so we can then encode the
  2560. * descriptor for publication. client_out must be already allocated. */
  2561. void
  2562. hs_desc_build_authorized_client(const uint8_t *subcredential,
  2563. const curve25519_public_key_t *client_auth_pk,
  2564. const curve25519_secret_key_t *
  2565. auth_ephemeral_sk,
  2566. const uint8_t *descriptor_cookie,
  2567. hs_desc_authorized_client_t *client_out)
  2568. {
  2569. uint8_t *keystream = NULL;
  2570. size_t keystream_length = 0;
  2571. const uint8_t *cookie_key;
  2572. crypto_cipher_t *cipher;
  2573. tor_assert(client_auth_pk);
  2574. tor_assert(auth_ephemeral_sk);
  2575. tor_assert(descriptor_cookie);
  2576. tor_assert(client_out);
  2577. tor_assert(subcredential);
  2578. tor_assert(!tor_mem_is_zero((char *) auth_ephemeral_sk,
  2579. sizeof(*auth_ephemeral_sk)));
  2580. tor_assert(!tor_mem_is_zero((char *) client_auth_pk,
  2581. sizeof(*client_auth_pk)));
  2582. tor_assert(!tor_mem_is_zero((char *) descriptor_cookie,
  2583. HS_DESC_DESCRIPTOR_COOKIE_LEN));
  2584. tor_assert(!tor_mem_is_zero((char *) subcredential,
  2585. DIGEST256_LEN));
  2586. /* Get the KEYS part so we can derive the CLIENT-ID and COOKIE-KEY. */
  2587. keystream_length =
  2588. build_descriptor_cookie_keys(subcredential, DIGEST256_LEN,
  2589. auth_ephemeral_sk, client_auth_pk,
  2590. &keystream);
  2591. tor_assert(keystream_length > 0);
  2592. /* Extract the CLIENT-ID and COOKIE-KEY from the KEYS. */
  2593. memcpy(client_out->client_id, keystream, HS_DESC_CLIENT_ID_LEN);
  2594. cookie_key = keystream + HS_DESC_CLIENT_ID_LEN;
  2595. /* Random IV */
  2596. crypto_strongest_rand(client_out->iv, sizeof(client_out->iv));
  2597. /* This creates a cipher for AES. It can't fail. */
  2598. cipher = crypto_cipher_new_with_iv_and_bits(cookie_key, client_out->iv,
  2599. HS_DESC_COOKIE_KEY_BIT_SIZE);
  2600. /* This can't fail. */
  2601. crypto_cipher_encrypt(cipher, (char *) client_out->encrypted_cookie,
  2602. (const char *) descriptor_cookie,
  2603. HS_DESC_DESCRIPTOR_COOKIE_LEN);
  2604. memwipe(keystream, 0, keystream_length);
  2605. tor_free(keystream);
  2606. crypto_cipher_free(cipher);
  2607. }
  2608. /* Free an authoriezd client object. */
  2609. void
  2610. hs_desc_authorized_client_free_(hs_desc_authorized_client_t *client)
  2611. {
  2612. tor_free(client);
  2613. }
  2614. /* Free the given descriptor link specifier. */
  2615. void
  2616. hs_desc_link_specifier_free_(hs_desc_link_specifier_t *ls)
  2617. {
  2618. if (ls == NULL) {
  2619. return;
  2620. }
  2621. tor_free(ls);
  2622. }
  2623. /* Return a newly allocated descriptor link specifier using the given extend
  2624. * info and requested type. Return NULL on error. */
  2625. hs_desc_link_specifier_t *
  2626. hs_desc_link_specifier_new(const extend_info_t *info, uint8_t type)
  2627. {
  2628. hs_desc_link_specifier_t *ls = NULL;
  2629. tor_assert(info);
  2630. ls = tor_malloc_zero(sizeof(*ls));
  2631. ls->type = type;
  2632. switch (ls->type) {
  2633. case LS_IPV4:
  2634. if (info->addr.family != AF_INET) {
  2635. goto err;
  2636. }
  2637. tor_addr_copy(&ls->u.ap.addr, &info->addr);
  2638. ls->u.ap.port = info->port;
  2639. break;
  2640. case LS_IPV6:
  2641. if (info->addr.family != AF_INET6) {
  2642. goto err;
  2643. }
  2644. tor_addr_copy(&ls->u.ap.addr, &info->addr);
  2645. ls->u.ap.port = info->port;
  2646. break;
  2647. case LS_LEGACY_ID:
  2648. /* Bug out if the identity digest is not set */
  2649. if (BUG(tor_mem_is_zero(info->identity_digest,
  2650. sizeof(info->identity_digest)))) {
  2651. goto err;
  2652. }
  2653. memcpy(ls->u.legacy_id, info->identity_digest, sizeof(ls->u.legacy_id));
  2654. break;
  2655. case LS_ED25519_ID:
  2656. /* ed25519 keys are optional for intro points */
  2657. if (ed25519_public_key_is_zero(&info->ed_identity)) {
  2658. goto err;
  2659. }
  2660. memcpy(ls->u.ed25519_id, info->ed_identity.pubkey,
  2661. sizeof(ls->u.ed25519_id));
  2662. break;
  2663. default:
  2664. /* Unknown type is code flow error. */
  2665. tor_assert(0);
  2666. }
  2667. return ls;
  2668. err:
  2669. tor_free(ls);
  2670. return NULL;
  2671. }
  2672. /* From the given descriptor, remove and free every introduction point. */
  2673. void
  2674. hs_descriptor_clear_intro_points(hs_descriptor_t *desc)
  2675. {
  2676. smartlist_t *ips;
  2677. tor_assert(desc);
  2678. ips = desc->encrypted_data.intro_points;
  2679. if (ips) {
  2680. SMARTLIST_FOREACH(ips, hs_desc_intro_point_t *,
  2681. ip, hs_desc_intro_point_free(ip));
  2682. smartlist_clear(ips);
  2683. }
  2684. }
  2685. /* From a descriptor link specifier object spec, returned a newly allocated
  2686. * link specifier object that is the encoded representation of spec. Return
  2687. * NULL on error. */
  2688. link_specifier_t *
  2689. hs_desc_lspec_to_trunnel(const hs_desc_link_specifier_t *spec)
  2690. {
  2691. tor_assert(spec);
  2692. link_specifier_t *ls = link_specifier_new();
  2693. link_specifier_set_ls_type(ls, spec->type);
  2694. switch (spec->type) {
  2695. case LS_IPV4:
  2696. link_specifier_set_un_ipv4_addr(ls,
  2697. tor_addr_to_ipv4h(&spec->u.ap.addr));
  2698. link_specifier_set_un_ipv4_port(ls, spec->u.ap.port);
  2699. /* Four bytes IPv4 and two bytes port. */
  2700. link_specifier_set_ls_len(ls, sizeof(spec->u.ap.addr.addr.in_addr) +
  2701. sizeof(spec->u.ap.port));
  2702. break;
  2703. case LS_IPV6:
  2704. {
  2705. size_t addr_len = link_specifier_getlen_un_ipv6_addr(ls);
  2706. const uint8_t *in6_addr = tor_addr_to_in6_addr8(&spec->u.ap.addr);
  2707. uint8_t *ipv6_array = link_specifier_getarray_un_ipv6_addr(ls);
  2708. memcpy(ipv6_array, in6_addr, addr_len);
  2709. link_specifier_set_un_ipv6_port(ls, spec->u.ap.port);
  2710. /* Sixteen bytes IPv6 and two bytes port. */
  2711. link_specifier_set_ls_len(ls, addr_len + sizeof(spec->u.ap.port));
  2712. break;
  2713. }
  2714. case LS_LEGACY_ID:
  2715. {
  2716. size_t legacy_id_len = link_specifier_getlen_un_legacy_id(ls);
  2717. uint8_t *legacy_id_array = link_specifier_getarray_un_legacy_id(ls);
  2718. memcpy(legacy_id_array, spec->u.legacy_id, legacy_id_len);
  2719. link_specifier_set_ls_len(ls, legacy_id_len);
  2720. break;
  2721. }
  2722. case LS_ED25519_ID:
  2723. {
  2724. size_t ed25519_id_len = link_specifier_getlen_un_ed25519_id(ls);
  2725. uint8_t *ed25519_id_array = link_specifier_getarray_un_ed25519_id(ls);
  2726. memcpy(ed25519_id_array, spec->u.ed25519_id, ed25519_id_len);
  2727. link_specifier_set_ls_len(ls, ed25519_id_len);
  2728. break;
  2729. }
  2730. default:
  2731. tor_assert_nonfatal_unreached();
  2732. link_specifier_free(ls);
  2733. ls = NULL;
  2734. }
  2735. return ls;
  2736. }