hs_descriptor.c 78 KB

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