hs_descriptor.c 62 KB

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