hs_descriptor.c 86 KB

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