hs_descriptor.c 63 KB

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