hs_descriptor.c 86 KB

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