hs_descriptor.c 84 KB

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