hs_descriptor.c 79 KB

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