hs_descriptor.c 100 KB

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