hs_descriptor.c 83 KB

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