hs_descriptor.c 78 KB

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