hs_descriptor.c 79 KB

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