hs_descriptor.c 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909
  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 AES128. It can't fail. */
  481. cipher = crypto_cipher_new_with_iv((const char *) key, (const char *) iv);
  482. /* This can't fail. */
  483. encrypted_len = build_plaintext_padding(plaintext, plaintext_len,
  484. &padded_plaintext);
  485. /* Extra precautions that we have a valie padding length. */
  486. tor_assert(encrypted_len <= HS_DESC_PADDED_PLAINTEXT_MAX_LEN);
  487. tor_assert(!(encrypted_len % HS_DESC_PLAINTEXT_PADDING_MULTIPLE));
  488. /* We use a stream cipher so the encrypted length will be the same as the
  489. * plaintext padded length. */
  490. encrypted = tor_malloc_zero(encrypted_len);
  491. /* This can't fail. */
  492. crypto_cipher_encrypt(cipher, (char *) encrypted,
  493. (const char *) padded_plaintext, encrypted_len);
  494. *encrypted_out = encrypted;
  495. /* Cleanup. */
  496. crypto_cipher_free(cipher);
  497. tor_free(padded_plaintext);
  498. return encrypted_len;
  499. }
  500. /* Encrypt the given plaintext buffer and using the descriptor to get the
  501. * keys. Set encrypted_out with the encrypted data and return the length of
  502. * it. */
  503. static size_t
  504. encrypt_descriptor_data(const hs_descriptor_t *desc, const char *plaintext,
  505. char **encrypted_out)
  506. {
  507. char *final_blob;
  508. size_t encrypted_len, final_blob_len, offset = 0;
  509. uint8_t *encrypted;
  510. uint8_t salt[HS_DESC_ENCRYPTED_SALT_LEN];
  511. uint8_t secret_key[CIPHER_KEY_LEN], secret_iv[CIPHER_IV_LEN];
  512. uint8_t mac_key[DIGEST256_LEN], mac[DIGEST256_LEN];
  513. tor_assert(desc);
  514. tor_assert(plaintext);
  515. tor_assert(encrypted_out);
  516. /* Get our salt. The returned bytes are already hashed. */
  517. crypto_strongest_rand(salt, sizeof(salt));
  518. /* KDF construction resulting in a key from which the secret key, IV and MAC
  519. * key are extracted which is what we need for the encryption. */
  520. build_secret_key_iv_mac(desc, salt, sizeof(salt),
  521. secret_key, sizeof(secret_key),
  522. secret_iv, sizeof(secret_iv),
  523. mac_key, sizeof(mac_key));
  524. /* Build the encrypted part that is do the actual encryption. */
  525. encrypted_len = build_encrypted(secret_key, secret_iv, plaintext,
  526. strlen(plaintext), &encrypted);
  527. memwipe(secret_key, 0, sizeof(secret_key));
  528. memwipe(secret_iv, 0, sizeof(secret_iv));
  529. /* This construction is specified in section 2.5 of proposal 224. */
  530. final_blob_len = sizeof(salt) + encrypted_len + DIGEST256_LEN;
  531. final_blob = tor_malloc_zero(final_blob_len);
  532. /* Build the MAC. */
  533. build_mac(mac_key, sizeof(mac_key), salt, sizeof(salt),
  534. encrypted, encrypted_len, mac, sizeof(mac));
  535. memwipe(mac_key, 0, sizeof(mac_key));
  536. /* The salt is the first value. */
  537. memcpy(final_blob, salt, sizeof(salt));
  538. offset = sizeof(salt);
  539. /* Second value is the encrypted data. */
  540. memcpy(final_blob + offset, encrypted, encrypted_len);
  541. offset += encrypted_len;
  542. /* Third value is the MAC. */
  543. memcpy(final_blob + offset, mac, sizeof(mac));
  544. offset += sizeof(mac);
  545. /* Cleanup the buffers. */
  546. memwipe(salt, 0, sizeof(salt));
  547. memwipe(encrypted, 0, encrypted_len);
  548. tor_free(encrypted);
  549. /* Extra precaution. */
  550. tor_assert(offset == final_blob_len);
  551. *encrypted_out = final_blob;
  552. return final_blob_len;
  553. }
  554. /* Take care of encoding the encrypted data section and then encrypting it
  555. * with the descriptor's key. A newly allocated NUL terminated string pointer
  556. * containing the encrypted encoded blob is put in encrypted_blob_out. Return
  557. * 0 on success else a negative value. */
  558. static int
  559. encode_encrypted_data(const hs_descriptor_t *desc,
  560. char **encrypted_blob_out)
  561. {
  562. int ret = -1;
  563. char *encoded_str, *encrypted_blob;
  564. smartlist_t *lines = smartlist_new();
  565. tor_assert(desc);
  566. tor_assert(encrypted_blob_out);
  567. /* Build the start of the section prior to the introduction points. */
  568. {
  569. if (!desc->encrypted_data.create2_ntor) {
  570. log_err(LD_BUG, "HS desc doesn't have recognized handshake type.");
  571. goto err;
  572. }
  573. smartlist_add_asprintf(lines, "%s %d\n", str_create2_formats,
  574. ONION_HANDSHAKE_TYPE_NTOR);
  575. if (desc->encrypted_data.auth_types &&
  576. smartlist_len(desc->encrypted_data.auth_types)) {
  577. /* Put the authentication-required line. */
  578. char *buf = smartlist_join_strings(desc->encrypted_data.auth_types, " ",
  579. 0, NULL);
  580. smartlist_add_asprintf(lines, "%s %s\n", str_auth_required, buf);
  581. tor_free(buf);
  582. }
  583. if (desc->encrypted_data.single_onion_service) {
  584. smartlist_add_asprintf(lines, "%s\n", str_single_onion);
  585. }
  586. }
  587. /* Build the introduction point(s) section. */
  588. SMARTLIST_FOREACH_BEGIN(desc->encrypted_data.intro_points,
  589. const hs_desc_intro_point_t *, ip) {
  590. char *encoded_ip = encode_intro_point(&desc->plaintext_data.signing_pubkey,
  591. ip);
  592. if (encoded_ip == NULL) {
  593. log_err(LD_BUG, "HS desc intro point is malformed.");
  594. goto err;
  595. }
  596. smartlist_add(lines, encoded_ip);
  597. } SMARTLIST_FOREACH_END(ip);
  598. /* Build the entire encrypted data section into one encoded plaintext and
  599. * then encrypt it. */
  600. encoded_str = smartlist_join_strings(lines, "", 0, NULL);
  601. /* Encrypt the section into an encrypted blob that we'll base64 encode
  602. * before returning it. */
  603. {
  604. char *enc_b64;
  605. ssize_t enc_b64_len, ret_len, enc_len;
  606. enc_len = encrypt_descriptor_data(desc, encoded_str, &encrypted_blob);
  607. tor_free(encoded_str);
  608. /* Get the encoded size plus a NUL terminating byte. */
  609. enc_b64_len = base64_encode_size(enc_len, BASE64_ENCODE_MULTILINE) + 1;
  610. enc_b64 = tor_malloc_zero(enc_b64_len);
  611. /* Base64 the encrypted blob before returning it. */
  612. ret_len = base64_encode(enc_b64, enc_b64_len, encrypted_blob, enc_len,
  613. BASE64_ENCODE_MULTILINE);
  614. /* Return length doesn't count the NUL byte. */
  615. tor_assert(ret_len == (enc_b64_len - 1));
  616. tor_free(encrypted_blob);
  617. *encrypted_blob_out = enc_b64;
  618. }
  619. /* Success! */
  620. ret = 0;
  621. err:
  622. SMARTLIST_FOREACH(lines, char *, l, tor_free(l));
  623. smartlist_free(lines);
  624. return ret;
  625. }
  626. /* Encode a v3 HS descriptor. Return 0 on success and set encoded_out to the
  627. * newly allocated string of the encoded descriptor. On error, -1 is returned
  628. * and encoded_out is untouched. */
  629. static int
  630. desc_encode_v3(const hs_descriptor_t *desc,
  631. const ed25519_keypair_t *signing_kp, char **encoded_out)
  632. {
  633. int ret = -1;
  634. char *encoded_str = NULL;
  635. size_t encoded_len;
  636. smartlist_t *lines = smartlist_new();
  637. tor_assert(desc);
  638. tor_assert(signing_kp);
  639. tor_assert(encoded_out);
  640. tor_assert(desc->plaintext_data.version == 3);
  641. /* Build the non-encrypted values. */
  642. {
  643. char *encoded_cert;
  644. /* Encode certificate then create the first line of the descriptor. */
  645. if (desc->plaintext_data.signing_key_cert->cert_type
  646. != CERT_TYPE_SIGNING_HS_DESC) {
  647. log_err(LD_BUG, "HS descriptor signing key has an unexpected cert type "
  648. "(%d)", (int) desc->plaintext_data.signing_key_cert->cert_type);
  649. goto err;
  650. }
  651. if (tor_cert_encode_ed22519(desc->plaintext_data.signing_key_cert,
  652. &encoded_cert) < 0) {
  653. /* The function will print error logs. */
  654. goto err;
  655. }
  656. /* Create the hs descriptor line. */
  657. smartlist_add_asprintf(lines, "%s %" PRIu32, str_hs_desc,
  658. desc->plaintext_data.version);
  659. /* Add the descriptor lifetime line (in minutes). */
  660. smartlist_add_asprintf(lines, "%s %" PRIu32, str_lifetime,
  661. desc->plaintext_data.lifetime_sec / 60);
  662. /* Create the descriptor certificate line. */
  663. smartlist_add_asprintf(lines, "%s\n%s", str_desc_cert, encoded_cert);
  664. tor_free(encoded_cert);
  665. /* Create the revision counter line. */
  666. smartlist_add_asprintf(lines, "%s %" PRIu64, str_rev_counter,
  667. desc->plaintext_data.revision_counter);
  668. }
  669. /* Build the superencrypted data section. */
  670. {
  671. char *enc_b64_blob=NULL;
  672. if (encode_encrypted_data(desc, &enc_b64_blob) < 0) {
  673. goto err;
  674. }
  675. smartlist_add_asprintf(lines,
  676. "%s\n"
  677. "-----BEGIN MESSAGE-----\n"
  678. "%s"
  679. "-----END MESSAGE-----",
  680. str_superencrypted, enc_b64_blob);
  681. tor_free(enc_b64_blob);
  682. }
  683. /* Join all lines in one string so we can generate a signature and append
  684. * it to the descriptor. */
  685. encoded_str = smartlist_join_strings(lines, "\n", 1, &encoded_len);
  686. /* Sign all fields of the descriptor with our short term signing key. */
  687. {
  688. ed25519_signature_t sig;
  689. char ed_sig_b64[ED25519_SIG_BASE64_LEN + 1];
  690. if (ed25519_sign_prefixed(&sig,
  691. (const uint8_t *) encoded_str, encoded_len,
  692. str_desc_sig_prefix, signing_kp) < 0) {
  693. log_warn(LD_BUG, "Can't sign encoded HS descriptor!");
  694. tor_free(encoded_str);
  695. goto err;
  696. }
  697. if (ed25519_signature_to_base64(ed_sig_b64, &sig) < 0) {
  698. log_warn(LD_BUG, "Can't base64 encode descriptor signature!");
  699. tor_free(encoded_str);
  700. goto err;
  701. }
  702. /* Create the signature line. */
  703. smartlist_add_asprintf(lines, "%s %s", str_signature, ed_sig_b64);
  704. }
  705. /* Free previous string that we used so compute the signature. */
  706. tor_free(encoded_str);
  707. encoded_str = smartlist_join_strings(lines, "\n", 1, NULL);
  708. *encoded_out = encoded_str;
  709. /* XXX: Trigger a control port event. */
  710. /* Success! */
  711. ret = 0;
  712. err:
  713. SMARTLIST_FOREACH(lines, char *, l, tor_free(l));
  714. smartlist_free(lines);
  715. return ret;
  716. }
  717. /* === DECODING === */
  718. /* Given an encoded string of the link specifiers, return a newly allocated
  719. * list of decoded link specifiers. Return NULL on error. */
  720. STATIC smartlist_t *
  721. decode_link_specifiers(const char *encoded)
  722. {
  723. int decoded_len;
  724. size_t encoded_len, i;
  725. uint8_t *decoded;
  726. smartlist_t *results = NULL;
  727. link_specifier_list_t *specs = NULL;
  728. tor_assert(encoded);
  729. encoded_len = strlen(encoded);
  730. decoded = tor_malloc(encoded_len);
  731. decoded_len = base64_decode((char *) decoded, encoded_len, encoded,
  732. encoded_len);
  733. if (decoded_len < 0) {
  734. goto err;
  735. }
  736. if (link_specifier_list_parse(&specs, decoded,
  737. (size_t) decoded_len) < decoded_len) {
  738. goto err;
  739. }
  740. tor_assert(specs);
  741. results = smartlist_new();
  742. for (i = 0; i < link_specifier_list_getlen_spec(specs); i++) {
  743. hs_desc_link_specifier_t *hs_spec;
  744. link_specifier_t *ls = link_specifier_list_get_spec(specs, i);
  745. tor_assert(ls);
  746. hs_spec = tor_malloc_zero(sizeof(*hs_spec));
  747. hs_spec->type = link_specifier_get_ls_type(ls);
  748. switch (hs_spec->type) {
  749. case LS_IPV4:
  750. tor_addr_from_ipv4h(&hs_spec->u.ap.addr,
  751. link_specifier_get_un_ipv4_addr(ls));
  752. hs_spec->u.ap.port = link_specifier_get_un_ipv4_port(ls);
  753. break;
  754. case LS_IPV6:
  755. tor_addr_from_ipv6_bytes(&hs_spec->u.ap.addr, (const char *)
  756. link_specifier_getarray_un_ipv6_addr(ls));
  757. hs_spec->u.ap.port = link_specifier_get_un_ipv6_port(ls);
  758. break;
  759. case LS_LEGACY_ID:
  760. /* Both are known at compile time so let's make sure they are the same
  761. * else we can copy memory out of bound. */
  762. tor_assert(link_specifier_getlen_un_legacy_id(ls) ==
  763. sizeof(hs_spec->u.legacy_id));
  764. memcpy(hs_spec->u.legacy_id, link_specifier_getarray_un_legacy_id(ls),
  765. sizeof(hs_spec->u.legacy_id));
  766. break;
  767. default:
  768. goto err;
  769. }
  770. smartlist_add(results, hs_spec);
  771. }
  772. goto done;
  773. err:
  774. if (results) {
  775. SMARTLIST_FOREACH(results, hs_desc_link_specifier_t *, s, tor_free(s));
  776. smartlist_free(results);
  777. results = NULL;
  778. }
  779. done:
  780. link_specifier_list_free(specs);
  781. tor_free(decoded);
  782. return results;
  783. }
  784. /* Given a list of authentication types, decode it and put it in the encrypted
  785. * data section. Return 1 if we at least know one of the type or 0 if we know
  786. * none of them. */
  787. static int
  788. decode_auth_type(hs_desc_encrypted_data_t *desc, const char *list)
  789. {
  790. int match = 0;
  791. tor_assert(desc);
  792. tor_assert(list);
  793. desc->auth_types = smartlist_new();
  794. smartlist_split_string(desc->auth_types, list, " ", 0, 0);
  795. /* Validate the types that we at least know about one. */
  796. SMARTLIST_FOREACH_BEGIN(desc->auth_types, const char *, auth) {
  797. for (int idx = 0; auth_types[idx].identifier; idx++) {
  798. if (!strncmp(auth, auth_types[idx].identifier,
  799. strlen(auth_types[idx].identifier))) {
  800. match = 1;
  801. break;
  802. }
  803. }
  804. } SMARTLIST_FOREACH_END(auth);
  805. return match;
  806. }
  807. /* Parse a space-delimited list of integers representing CREATE2 formats into
  808. * the bitfield in hs_desc_encrypted_data_t. Ignore unrecognized values. */
  809. static void
  810. decode_create2_list(hs_desc_encrypted_data_t *desc, const char *list)
  811. {
  812. smartlist_t *tokens;
  813. tor_assert(desc);
  814. tor_assert(list);
  815. tokens = smartlist_new();
  816. smartlist_split_string(tokens, list, " ", 0, 0);
  817. SMARTLIST_FOREACH_BEGIN(tokens, char *, s) {
  818. int ok;
  819. unsigned long type = tor_parse_ulong(s, 10, 1, UINT16_MAX, &ok, NULL);
  820. if (!ok) {
  821. log_warn(LD_REND, "Unparseable value %s in create2 list", escaped(s));
  822. continue;
  823. }
  824. switch (type) {
  825. case ONION_HANDSHAKE_TYPE_NTOR:
  826. desc->create2_ntor = 1;
  827. break;
  828. default:
  829. /* We deliberately ignore unsupported handshake types */
  830. continue;
  831. }
  832. } SMARTLIST_FOREACH_END(s);
  833. SMARTLIST_FOREACH(tokens, char *, s, tor_free(s));
  834. smartlist_free(tokens);
  835. }
  836. /* Given a certificate, validate the certificate for certain conditions which
  837. * are if the given type matches the cert's one, if the signing key is
  838. * included and if the that key was actually used to sign the certificate.
  839. *
  840. * Return 1 iff if all conditions pass or 0 if one of them fails. */
  841. STATIC int
  842. cert_is_valid(tor_cert_t *cert, uint8_t type, const char *log_obj_type)
  843. {
  844. tor_assert(log_obj_type);
  845. if (cert == NULL) {
  846. log_warn(LD_REND, "Certificate for %s couldn't be parsed.", log_obj_type);
  847. goto err;
  848. }
  849. if (cert->cert_type != type) {
  850. log_warn(LD_REND, "Invalid cert type %02x for %s.", cert->cert_type,
  851. log_obj_type);
  852. goto err;
  853. }
  854. /* All certificate must have its signing key included. */
  855. if (!cert->signing_key_included) {
  856. log_warn(LD_REND, "Signing key is NOT included for %s.", log_obj_type);
  857. goto err;
  858. }
  859. /* The following will not only check if the signature matches but also the
  860. * expiration date and overall validity. */
  861. if (tor_cert_checksig(cert, &cert->signing_key, time(NULL)) < 0) {
  862. log_warn(LD_REND, "Invalid signature for %s.", log_obj_type);
  863. goto err;
  864. }
  865. return 1;
  866. err:
  867. return 0;
  868. }
  869. /* Given some binary data, try to parse it to get a certificate object. If we
  870. * have a valid cert, validate it using the given wanted type. On error, print
  871. * a log using the err_msg has the certificate identifier adding semantic to
  872. * the log and cert_out is set to NULL. On success, 0 is returned and cert_out
  873. * points to a newly allocated certificate object. */
  874. static int
  875. cert_parse_and_validate(tor_cert_t **cert_out, const char *data,
  876. size_t data_len, unsigned int cert_type_wanted,
  877. const char *err_msg)
  878. {
  879. tor_cert_t *cert;
  880. tor_assert(cert_out);
  881. tor_assert(data);
  882. tor_assert(err_msg);
  883. /* Parse certificate. */
  884. cert = tor_cert_parse((const uint8_t *) data, data_len);
  885. if (!cert) {
  886. log_warn(LD_REND, "Certificate for %s couldn't be parsed.", err_msg);
  887. goto err;
  888. }
  889. /* Validate certificate. */
  890. if (!cert_is_valid(cert, cert_type_wanted, err_msg)) {
  891. goto err;
  892. }
  893. *cert_out = cert;
  894. return 0;
  895. err:
  896. tor_cert_free(cert);
  897. *cert_out = NULL;
  898. return -1;
  899. }
  900. /* Return true iff the given length of the encrypted data of a descriptor
  901. * passes validation. */
  902. STATIC int
  903. encrypted_data_length_is_valid(size_t len)
  904. {
  905. /* Check for the minimum length possible. */
  906. if (len < HS_DESC_ENCRYPTED_MIN_LEN) {
  907. log_warn(LD_REND, "Length of descriptor's encrypted data is too small. "
  908. "Got %lu but minimum value is %d",
  909. (unsigned long)len, HS_DESC_ENCRYPTED_MIN_LEN);
  910. goto err;
  911. }
  912. /* Encrypted data has the salt and MAC concatenated to it so remove those
  913. * from the validation calculation. */
  914. len -= HS_DESC_ENCRYPTED_SALT_LEN + DIGEST256_LEN;
  915. /* Check that it's aligned on the block size of the crypto algorithm. */
  916. if (len % HS_DESC_PLAINTEXT_PADDING_MULTIPLE) {
  917. log_warn(LD_REND, "Length of descriptor's encrypted data is invalid. "
  918. "Got %lu which is not a multiple of %d.",
  919. (unsigned long) len, HS_DESC_PLAINTEXT_PADDING_MULTIPLE);
  920. goto err;
  921. }
  922. /* XXX: Check maximum size. Will strongly depends on the maximum intro point
  923. * allowed we decide on and probably if they will all have to use the legacy
  924. * key which is bigger than the ed25519 key. */
  925. return 1;
  926. err:
  927. return 0;
  928. }
  929. /* Decrypt the encrypted section of the descriptor using the given descriptor
  930. * object desc. A newly allocated NUL terminated string is put in
  931. * decrypted_out. Return the length of decrypted_out on success else 0 is
  932. * returned and decrypted_out is set to NULL. */
  933. static size_t
  934. desc_decrypt_data_v3(const hs_descriptor_t *desc, char **decrypted_out)
  935. {
  936. uint8_t *decrypted = NULL;
  937. uint8_t secret_key[CIPHER_KEY_LEN], secret_iv[CIPHER_IV_LEN];
  938. uint8_t mac_key[DIGEST256_LEN], our_mac[DIGEST256_LEN];
  939. const uint8_t *salt, *encrypted, *desc_mac;
  940. size_t encrypted_len, result_len = 0;
  941. tor_assert(decrypted_out);
  942. tor_assert(desc);
  943. tor_assert(desc->plaintext_data.encrypted_blob);
  944. /* Construction is as follow: SALT | ENCRYPTED_DATA | MAC */
  945. if (!encrypted_data_length_is_valid(
  946. desc->plaintext_data.encrypted_blob_size)) {
  947. goto err;
  948. }
  949. /* Start of the blob thus the salt. */
  950. salt = desc->plaintext_data.encrypted_blob;
  951. /* Next is the encrypted data. */
  952. encrypted = desc->plaintext_data.encrypted_blob +
  953. HS_DESC_ENCRYPTED_SALT_LEN;
  954. encrypted_len = desc->plaintext_data.encrypted_blob_size -
  955. (HS_DESC_ENCRYPTED_SALT_LEN + DIGEST256_LEN);
  956. /* At the very end is the MAC. Make sure it's of the right size. */
  957. {
  958. desc_mac = encrypted + encrypted_len;
  959. size_t desc_mac_size = desc->plaintext_data.encrypted_blob_size -
  960. (desc_mac - desc->plaintext_data.encrypted_blob);
  961. if (desc_mac_size != DIGEST256_LEN) {
  962. log_warn(LD_REND, "Service descriptor MAC length of encrypted data "
  963. "is invalid (%lu, expected %u)",
  964. (unsigned long) desc_mac_size, DIGEST256_LEN);
  965. goto err;
  966. }
  967. }
  968. /* KDF construction resulting in a key from which the secret key, IV and MAC
  969. * key are extracted which is what we need for the decryption. */
  970. build_secret_key_iv_mac(desc, salt, HS_DESC_ENCRYPTED_SALT_LEN,
  971. secret_key, sizeof(secret_key),
  972. secret_iv, sizeof(secret_iv),
  973. mac_key, sizeof(mac_key));
  974. /* Build MAC. */
  975. build_mac(mac_key, sizeof(mac_key), salt, HS_DESC_ENCRYPTED_SALT_LEN,
  976. encrypted, encrypted_len, our_mac, sizeof(our_mac));
  977. memwipe(mac_key, 0, sizeof(mac_key));
  978. /* Verify MAC; MAC is H(mac_key || salt || encrypted)
  979. *
  980. * This is a critical check that is making sure the computed MAC matches the
  981. * one in the descriptor. */
  982. if (!tor_memeq(our_mac, desc_mac, sizeof(our_mac))) {
  983. log_warn(LD_REND, "Encrypted service descriptor MAC check failed");
  984. goto err;
  985. }
  986. {
  987. /* Decrypt. Here we are assured that the encrypted length is valid for
  988. * decryption. */
  989. crypto_cipher_t *cipher;
  990. cipher = crypto_cipher_new_with_iv((const char *) secret_key,
  991. (const char *) secret_iv);
  992. /* Extra byte for the NUL terminated byte. */
  993. decrypted = tor_malloc_zero(encrypted_len + 1);
  994. crypto_cipher_decrypt(cipher, (char *) decrypted,
  995. (const char *) encrypted, encrypted_len);
  996. crypto_cipher_free(cipher);
  997. }
  998. {
  999. /* Adjust length to remove NULL padding bytes */
  1000. uint8_t *end = memchr(decrypted, 0, encrypted_len);
  1001. result_len = encrypted_len;
  1002. if (end) {
  1003. result_len = end - decrypted;
  1004. }
  1005. }
  1006. /* Make sure to NUL terminate the string. */
  1007. decrypted[encrypted_len] = '\0';
  1008. *decrypted_out = (char *) decrypted;
  1009. goto done;
  1010. err:
  1011. if (decrypted) {
  1012. tor_free(decrypted);
  1013. }
  1014. *decrypted_out = NULL;
  1015. result_len = 0;
  1016. done:
  1017. memwipe(secret_key, 0, sizeof(secret_key));
  1018. memwipe(secret_iv, 0, sizeof(secret_iv));
  1019. return result_len;
  1020. }
  1021. /* Given the start of a section and the end of it, decode a single
  1022. * introduction point from that section. Return a newly allocated introduction
  1023. * point object containing the decoded data. Return NULL if the section can't
  1024. * be decoded. */
  1025. STATIC hs_desc_intro_point_t *
  1026. decode_introduction_point(const hs_descriptor_t *desc, const char *start)
  1027. {
  1028. hs_desc_intro_point_t *ip = NULL;
  1029. memarea_t *area = NULL;
  1030. smartlist_t *tokens = NULL;
  1031. tor_cert_t *cross_cert = NULL;
  1032. const directory_token_t *tok;
  1033. tor_assert(desc);
  1034. tor_assert(start);
  1035. area = memarea_new();
  1036. tokens = smartlist_new();
  1037. if (tokenize_string(area, start, start + strlen(start),
  1038. tokens, hs_desc_intro_point_v3_token_table, 0) < 0) {
  1039. log_warn(LD_REND, "Introduction point is not parseable");
  1040. goto err;
  1041. }
  1042. /* Ok we seem to have a well formed section containing enough tokens to
  1043. * parse. Allocate our IP object and try to populate it. */
  1044. ip = tor_malloc_zero(sizeof(hs_desc_intro_point_t));
  1045. /* "introduction-point" SP link-specifiers NL */
  1046. tok = find_by_keyword(tokens, R3_INTRODUCTION_POINT);
  1047. tor_assert(tok->n_args == 1);
  1048. ip->link_specifiers = decode_link_specifiers(tok->args[0]);
  1049. if (!ip->link_specifiers) {
  1050. log_warn(LD_REND, "Introduction point has invalid link specifiers");
  1051. goto err;
  1052. }
  1053. /* "auth-key" NL certificate NL */
  1054. tok = find_by_keyword(tokens, R3_INTRO_AUTH_KEY);
  1055. tor_assert(tok->object_body);
  1056. if (strcmp(tok->object_type, "ED25519 CERT")) {
  1057. log_warn(LD_REND, "Unexpected object type for introduction auth key");
  1058. goto err;
  1059. }
  1060. /* Parse cert and do some validation. */
  1061. if (cert_parse_and_validate(&ip->auth_key_cert, tok->object_body,
  1062. tok->object_size, CERT_TYPE_AUTH_HS_IP_KEY,
  1063. "introduction point auth-key") < 0) {
  1064. goto err;
  1065. }
  1066. /* Exactly one "enc-key" ... */
  1067. tok = find_by_keyword(tokens, R3_INTRO_ENC_KEY);
  1068. if (!strcmp(tok->args[0], "ntor")) {
  1069. /* "enc-key" SP "ntor" SP key NL */
  1070. if (tok->n_args != 2 || tok->object_body) {
  1071. log_warn(LD_REND, "Introduction point ntor encryption key is invalid");
  1072. goto err;
  1073. }
  1074. if (curve25519_public_from_base64(&ip->enc_key.curve25519.pubkey,
  1075. tok->args[1]) < 0) {
  1076. log_warn(LD_REND, "Introduction point ntor encryption key is invalid");
  1077. goto err;
  1078. }
  1079. ip->enc_key_type = HS_DESC_KEY_TYPE_CURVE25519;
  1080. } else if (!strcmp(tok->args[0], "legacy")) {
  1081. /* "enc-key" SP "legacy" NL key NL */
  1082. if (!tok->key) {
  1083. log_warn(LD_REND, "Introduction point legacy encryption key is "
  1084. "invalid");
  1085. goto err;
  1086. }
  1087. ip->enc_key.legacy = crypto_pk_dup_key(tok->key);
  1088. ip->enc_key_type = HS_DESC_KEY_TYPE_LEGACY;
  1089. } else {
  1090. /* Unknown key type so we can't use that introduction point. */
  1091. log_warn(LD_REND, "Introduction point encryption key is unrecognized.");
  1092. goto err;
  1093. }
  1094. /* "enc-key-certification" NL certificate NL */
  1095. tok = find_by_keyword(tokens, R3_INTRO_ENC_KEY_CERTIFICATION);
  1096. tor_assert(tok->object_body);
  1097. /* Do the cross certification. */
  1098. switch (ip->enc_key_type) {
  1099. case HS_DESC_KEY_TYPE_CURVE25519:
  1100. {
  1101. if (strcmp(tok->object_type, "ED25519 CERT")) {
  1102. log_warn(LD_REND, "Introduction point ntor encryption key "
  1103. "cross-certification has an unknown format.");
  1104. goto err;
  1105. }
  1106. if (cert_parse_and_validate(&cross_cert, tok->object_body,
  1107. tok->object_size, CERT_TYPE_CROSS_HS_IP_KEYS,
  1108. "introduction point enc-key-certification") < 0) {
  1109. goto err;
  1110. }
  1111. break;
  1112. }
  1113. case HS_DESC_KEY_TYPE_LEGACY:
  1114. if (strcmp(tok->object_type, "CROSSCERT")) {
  1115. log_warn(LD_REND, "Introduction point legacy encryption key "
  1116. "cross-certification has an unknown format.");
  1117. goto err;
  1118. }
  1119. if (rsa_ed25519_crosscert_check((const uint8_t *) tok->object_body,
  1120. tok->object_size, ip->enc_key.legacy,
  1121. &desc->plaintext_data.signing_key_cert->signed_key,
  1122. approx_time()-86400)) {
  1123. log_warn(LD_REND, "Unable to check cross-certification on the "
  1124. "introduction point legacy encryption key.");
  1125. goto err;
  1126. }
  1127. break;
  1128. default:
  1129. tor_assert(0);
  1130. break;
  1131. }
  1132. /* It is successfully cross certified. Flag the object. */
  1133. ip->cross_certified = 1;
  1134. goto done;
  1135. err:
  1136. desc_intro_point_free(ip);
  1137. ip = NULL;
  1138. done:
  1139. tor_cert_free(cross_cert);
  1140. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1141. smartlist_free(tokens);
  1142. memarea_drop_all(area);
  1143. return ip;
  1144. }
  1145. /* Given a descriptor string at <b>data</b>, decode all possible introduction
  1146. * points that we can find. Add the introduction point object to desc_enc as we
  1147. * find them. Return 0 on success.
  1148. *
  1149. * On error, a negative value is returned. It is possible that some intro
  1150. * point object have been added to the desc_enc, they should be considered
  1151. * invalid. One single bad encoded introduction point will make this function
  1152. * return an error. */
  1153. STATIC int
  1154. decode_intro_points(const hs_descriptor_t *desc,
  1155. hs_desc_encrypted_data_t *desc_enc,
  1156. const char *data)
  1157. {
  1158. int retval = -1;
  1159. smartlist_t *chunked_desc = smartlist_new();
  1160. smartlist_t *intro_points = smartlist_new();
  1161. tor_assert(desc);
  1162. tor_assert(desc_enc);
  1163. tor_assert(data);
  1164. tor_assert(desc_enc->intro_points);
  1165. /* Take the desc string, and extract the intro point substrings out of it */
  1166. {
  1167. /* Split the descriptor string using the intro point header as delimiter */
  1168. smartlist_split_string(chunked_desc, data, str_intro_point_start, 0, 0);
  1169. /* Check if there are actually any intro points included. The first chunk
  1170. * should be other descriptor fields (e.g. create2-formats), so it's not an
  1171. * intro point. */
  1172. if (smartlist_len(chunked_desc) < 2) {
  1173. goto done;
  1174. }
  1175. }
  1176. /* Take the intro point substrings, and prepare them for parsing */
  1177. {
  1178. int i = 0;
  1179. /* Prepend the introduction-point header to all the chunks, since
  1180. smartlist_split_string() devoured it. */
  1181. SMARTLIST_FOREACH_BEGIN(chunked_desc, char *, chunk) {
  1182. /* Ignore first chunk. It's other descriptor fields. */
  1183. if (i++ == 0) {
  1184. continue;
  1185. }
  1186. smartlist_add_asprintf(intro_points, "%s %s", str_intro_point, chunk);
  1187. } SMARTLIST_FOREACH_END(chunk);
  1188. }
  1189. /* Parse the intro points! */
  1190. SMARTLIST_FOREACH_BEGIN(intro_points, const char *, intro_point) {
  1191. hs_desc_intro_point_t *ip = decode_introduction_point(desc, intro_point);
  1192. if (!ip) {
  1193. /* Malformed introduction point section. Stop right away, this
  1194. * descriptor shouldn't be used. */
  1195. goto err;
  1196. }
  1197. smartlist_add(desc_enc->intro_points, ip);
  1198. } SMARTLIST_FOREACH_END(intro_point);
  1199. done:
  1200. retval = 0;
  1201. err:
  1202. SMARTLIST_FOREACH(chunked_desc, char *, a, tor_free(a));
  1203. smartlist_free(chunked_desc);
  1204. SMARTLIST_FOREACH(intro_points, char *, a, tor_free(a));
  1205. smartlist_free(intro_points);
  1206. return retval;
  1207. }
  1208. /* Return 1 iff the given base64 encoded signature in b64_sig from the encoded
  1209. * descriptor in encoded_desc validates the descriptor content. */
  1210. STATIC int
  1211. desc_sig_is_valid(const char *b64_sig,
  1212. const ed25519_public_key_t *signing_pubkey,
  1213. const char *encoded_desc, size_t encoded_len)
  1214. {
  1215. int ret = 0;
  1216. ed25519_signature_t sig;
  1217. const char *sig_start;
  1218. tor_assert(b64_sig);
  1219. tor_assert(signing_pubkey);
  1220. tor_assert(encoded_desc);
  1221. /* Verifying nothing won't end well :). */
  1222. tor_assert(encoded_len > 0);
  1223. /* Signature length check. */
  1224. if (strlen(b64_sig) != ED25519_SIG_BASE64_LEN) {
  1225. log_warn(LD_REND, "Service descriptor has an invalid signature length."
  1226. "Exptected %d but got %lu",
  1227. ED25519_SIG_BASE64_LEN, (unsigned long) strlen(b64_sig));
  1228. goto err;
  1229. }
  1230. /* First, convert base64 blob to an ed25519 signature. */
  1231. if (ed25519_signature_from_base64(&sig, b64_sig) != 0) {
  1232. log_warn(LD_REND, "Service descriptor does not contain a valid "
  1233. "signature");
  1234. goto err;
  1235. }
  1236. /* Find the start of signature. */
  1237. sig_start = tor_memstr(encoded_desc, encoded_len, "\n" str_signature);
  1238. /* Getting here means the token parsing worked for the signature so if we
  1239. * can't find the start of the signature, we have a code flow issue. */
  1240. if (BUG(!sig_start)) {
  1241. goto err;
  1242. }
  1243. /* Skip newline, it has to go in the signature check. */
  1244. sig_start++;
  1245. /* Validate signature with the full body of the descriptor. */
  1246. if (ed25519_checksig_prefixed(&sig,
  1247. (const uint8_t *) encoded_desc,
  1248. sig_start - encoded_desc,
  1249. str_desc_sig_prefix,
  1250. signing_pubkey) != 0) {
  1251. log_warn(LD_REND, "Invalid signature on service descriptor");
  1252. goto err;
  1253. }
  1254. /* Valid signature! All is good. */
  1255. ret = 1;
  1256. err:
  1257. return ret;
  1258. }
  1259. /* Decode descriptor plaintext data for version 3. Given a list of tokens, an
  1260. * allocated plaintext object that will be populated and the encoded
  1261. * descriptor with its length. The last one is needed for signature
  1262. * verification. Unknown tokens are simply ignored so this won't error on
  1263. * unknowns but requires that all v3 token be present and valid.
  1264. *
  1265. * Return 0 on success else a negative value. */
  1266. static int
  1267. desc_decode_plaintext_v3(smartlist_t *tokens,
  1268. hs_desc_plaintext_data_t *desc,
  1269. const char *encoded_desc, size_t encoded_len)
  1270. {
  1271. int ok;
  1272. directory_token_t *tok;
  1273. tor_assert(tokens);
  1274. tor_assert(desc);
  1275. /* Version higher could still use this function to decode most of the
  1276. * descriptor and then they decode the extra part. */
  1277. tor_assert(desc->version >= 3);
  1278. /* Descriptor lifetime parsing. */
  1279. tok = find_by_keyword(tokens, R3_DESC_LIFETIME);
  1280. tor_assert(tok->n_args == 1);
  1281. desc->lifetime_sec = (uint32_t) tor_parse_ulong(tok->args[0], 10, 0,
  1282. UINT32_MAX, &ok, NULL);
  1283. if (!ok) {
  1284. log_warn(LD_REND, "Service descriptor lifetime value is invalid");
  1285. goto err;
  1286. }
  1287. /* Put it from minute to second. */
  1288. desc->lifetime_sec *= 60;
  1289. if (desc->lifetime_sec > HS_DESC_MAX_LIFETIME) {
  1290. log_warn(LD_REND, "Service descriptor lifetime is too big. "
  1291. "Got %" PRIu32 " but max is %d",
  1292. desc->lifetime_sec, HS_DESC_MAX_LIFETIME);
  1293. goto err;
  1294. }
  1295. /* Descriptor signing certificate. */
  1296. tok = find_by_keyword(tokens, R3_DESC_SIGNING_CERT);
  1297. tor_assert(tok->object_body);
  1298. /* Expecting a prop220 cert with the signing key extension, which contains
  1299. * the blinded public key. */
  1300. if (strcmp(tok->object_type, "ED25519 CERT") != 0) {
  1301. log_warn(LD_REND, "Service descriptor signing cert wrong type (%s)",
  1302. escaped(tok->object_type));
  1303. goto err;
  1304. }
  1305. if (cert_parse_and_validate(&desc->signing_key_cert, tok->object_body,
  1306. tok->object_size, CERT_TYPE_SIGNING_HS_DESC,
  1307. "service descriptor signing key") < 0) {
  1308. goto err;
  1309. }
  1310. /* Copy the public keys into signing_pubkey and blinded_pubkey */
  1311. memcpy(&desc->signing_pubkey, &desc->signing_key_cert->signed_key,
  1312. sizeof(ed25519_public_key_t));
  1313. memcpy(&desc->blinded_pubkey, &desc->signing_key_cert->signing_key,
  1314. sizeof(ed25519_public_key_t));
  1315. /* Extract revision counter value. */
  1316. tok = find_by_keyword(tokens, R3_REVISION_COUNTER);
  1317. tor_assert(tok->n_args == 1);
  1318. desc->revision_counter = tor_parse_uint64(tok->args[0], 10, 0,
  1319. UINT64_MAX, &ok, NULL);
  1320. if (!ok) {
  1321. log_warn(LD_REND, "Service descriptor revision-counter is invalid");
  1322. goto err;
  1323. }
  1324. /* Extract the encrypted data section. */
  1325. tok = find_by_keyword(tokens, R3_SUPERENCRYPTED);
  1326. tor_assert(tok->object_body);
  1327. if (strcmp(tok->object_type, "MESSAGE") != 0) {
  1328. log_warn(LD_REND, "Service descriptor encrypted data section is invalid");
  1329. goto err;
  1330. }
  1331. /* Make sure the length of the encrypted blob is valid. */
  1332. if (!encrypted_data_length_is_valid(tok->object_size)) {
  1333. goto err;
  1334. }
  1335. /* Copy the encrypted blob to the descriptor object so we can handle it
  1336. * latter if needed. */
  1337. desc->encrypted_blob = tor_memdup(tok->object_body, tok->object_size);
  1338. desc->encrypted_blob_size = tok->object_size;
  1339. /* Extract signature and verify it. */
  1340. tok = find_by_keyword(tokens, R3_SIGNATURE);
  1341. tor_assert(tok->n_args == 1);
  1342. /* First arg here is the actual encoded signature. */
  1343. if (!desc_sig_is_valid(tok->args[0], &desc->signing_pubkey,
  1344. encoded_desc, encoded_len)) {
  1345. goto err;
  1346. }
  1347. return 0;
  1348. err:
  1349. return -1;
  1350. }
  1351. /* Decode the version 3 encrypted section of the given descriptor desc. The
  1352. * desc_encrypted_out will be populated with the decoded data. Return 0 on
  1353. * success else -1. */
  1354. static int
  1355. desc_decode_encrypted_v3(const hs_descriptor_t *desc,
  1356. hs_desc_encrypted_data_t *desc_encrypted_out)
  1357. {
  1358. int result = -1;
  1359. char *message = NULL;
  1360. size_t message_len;
  1361. memarea_t *area = NULL;
  1362. directory_token_t *tok;
  1363. smartlist_t *tokens = NULL;
  1364. tor_assert(desc);
  1365. tor_assert(desc_encrypted_out);
  1366. /* Decrypt the encrypted data that is located in the plaintext section in
  1367. * the descriptor as a blob of bytes. The following functions will use the
  1368. * keys found in the same section. */
  1369. message_len = desc_decrypt_data_v3(desc, &message);
  1370. if (!message_len) {
  1371. log_warn(LD_REND, "Service descriptor decryption failed.");
  1372. goto err;
  1373. }
  1374. tor_assert(message);
  1375. area = memarea_new();
  1376. tokens = smartlist_new();
  1377. if (tokenize_string(area, message, message + message_len,
  1378. tokens, hs_desc_encrypted_v3_token_table, 0) < 0) {
  1379. log_warn(LD_REND, "Encrypted service descriptor is not parseable.");
  1380. goto err;
  1381. }
  1382. /* CREATE2 supported cell format. It's mandatory. */
  1383. tok = find_by_keyword(tokens, R3_CREATE2_FORMATS);
  1384. tor_assert(tok);
  1385. decode_create2_list(desc_encrypted_out, tok->args[0]);
  1386. /* Must support ntor according to the specification */
  1387. if (!desc_encrypted_out->create2_ntor) {
  1388. log_warn(LD_REND, "Service create2-formats does not include ntor.");
  1389. goto err;
  1390. }
  1391. /* Authentication type. It's optional but only once. */
  1392. tok = find_opt_by_keyword(tokens, R3_AUTHENTICATION_REQUIRED);
  1393. if (tok) {
  1394. if (!decode_auth_type(desc_encrypted_out, tok->args[0])) {
  1395. log_warn(LD_REND, "Service descriptor authentication type has "
  1396. "invalid entry(ies).");
  1397. goto err;
  1398. }
  1399. }
  1400. /* Is this service a single onion service? */
  1401. tok = find_opt_by_keyword(tokens, R3_SINGLE_ONION_SERVICE);
  1402. if (tok) {
  1403. desc_encrypted_out->single_onion_service = 1;
  1404. }
  1405. /* Initialize the descriptor's introduction point list before we start
  1406. * decoding. Having 0 intro point is valid. Then decode them all. */
  1407. desc_encrypted_out->intro_points = smartlist_new();
  1408. if (decode_intro_points(desc, desc_encrypted_out, message) < 0) {
  1409. goto err;
  1410. }
  1411. /* Validation of maximum introduction points allowed. */
  1412. if (smartlist_len(desc_encrypted_out->intro_points) > MAX_INTRO_POINTS) {
  1413. log_warn(LD_REND, "Service descriptor contains too many introduction "
  1414. "points. Maximum allowed is %d but we have %d",
  1415. MAX_INTRO_POINTS,
  1416. smartlist_len(desc_encrypted_out->intro_points));
  1417. goto err;
  1418. }
  1419. /* NOTE: Unknown fields are allowed because this function could be used to
  1420. * decode other descriptor version. */
  1421. result = 0;
  1422. goto done;
  1423. err:
  1424. tor_assert(result < 0);
  1425. desc_encrypted_data_free_contents(desc_encrypted_out);
  1426. done:
  1427. if (tokens) {
  1428. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1429. smartlist_free(tokens);
  1430. }
  1431. if (area) {
  1432. memarea_drop_all(area);
  1433. }
  1434. if (message) {
  1435. tor_free(message);
  1436. }
  1437. return result;
  1438. }
  1439. /* Table of encrypted decode function version specific. The function are
  1440. * indexed by the version number so v3 callback is at index 3 in the array. */
  1441. static int
  1442. (*decode_encrypted_handlers[])(
  1443. const hs_descriptor_t *desc,
  1444. hs_desc_encrypted_data_t *desc_encrypted) =
  1445. {
  1446. /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
  1447. desc_decode_encrypted_v3,
  1448. };
  1449. /* Decode the encrypted data section of the given descriptor and store the
  1450. * data in the given encrypted data object. Return 0 on success else a
  1451. * negative value on error. */
  1452. int
  1453. hs_desc_decode_encrypted(const hs_descriptor_t *desc,
  1454. hs_desc_encrypted_data_t *desc_encrypted)
  1455. {
  1456. int ret;
  1457. uint32_t version;
  1458. tor_assert(desc);
  1459. /* Ease our life a bit. */
  1460. version = desc->plaintext_data.version;
  1461. tor_assert(desc_encrypted);
  1462. /* Calling this function without an encrypted blob to parse is a code flow
  1463. * error. The plaintext parsing should never succeed in the first place
  1464. * without an encrypted section. */
  1465. tor_assert(desc->plaintext_data.encrypted_blob);
  1466. /* Let's make sure we have a supported version as well. By correctly parsing
  1467. * the plaintext, this should not fail. */
  1468. if (BUG(!hs_desc_is_supported_version(version))) {
  1469. ret = -1;
  1470. goto err;
  1471. }
  1472. /* Extra precaution. Having no handler for the supported version should
  1473. * never happened else we forgot to add it but we bumped the version. */
  1474. tor_assert(ARRAY_LENGTH(decode_encrypted_handlers) >= version);
  1475. tor_assert(decode_encrypted_handlers[version]);
  1476. /* Run the version specific plaintext decoder. */
  1477. ret = decode_encrypted_handlers[version](desc, desc_encrypted);
  1478. if (ret < 0) {
  1479. goto err;
  1480. }
  1481. err:
  1482. return ret;
  1483. }
  1484. /* Table of plaintext decode function version specific. The function are
  1485. * indexed by the version number so v3 callback is at index 3 in the array. */
  1486. static int
  1487. (*decode_plaintext_handlers[])(
  1488. smartlist_t *tokens,
  1489. hs_desc_plaintext_data_t *desc,
  1490. const char *encoded_desc,
  1491. size_t encoded_len) =
  1492. {
  1493. /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
  1494. desc_decode_plaintext_v3,
  1495. };
  1496. /* Fully decode the given descriptor plaintext and store the data in the
  1497. * plaintext data object. Returns 0 on success else a negative value. */
  1498. int
  1499. hs_desc_decode_plaintext(const char *encoded,
  1500. hs_desc_plaintext_data_t *plaintext)
  1501. {
  1502. int ok = 0, ret = -1;
  1503. memarea_t *area = NULL;
  1504. smartlist_t *tokens = NULL;
  1505. size_t encoded_len;
  1506. directory_token_t *tok;
  1507. tor_assert(encoded);
  1508. tor_assert(plaintext);
  1509. /* Check that descriptor is within size limits. */
  1510. encoded_len = strlen(encoded);
  1511. if (encoded_len >= hs_cache_get_max_descriptor_size()) {
  1512. log_warn(LD_REND, "Service descriptor is too big (%lu bytes)",
  1513. (unsigned long) encoded_len);
  1514. goto err;
  1515. }
  1516. area = memarea_new();
  1517. tokens = smartlist_new();
  1518. /* Tokenize the descriptor so we can start to parse it. */
  1519. if (tokenize_string(area, encoded, encoded + encoded_len, tokens,
  1520. hs_desc_v3_token_table, 0) < 0) {
  1521. log_warn(LD_REND, "Service descriptor is not parseable");
  1522. goto err;
  1523. }
  1524. /* Get the version of the descriptor which is the first mandatory field of
  1525. * the descriptor. From there, we'll decode the right descriptor version. */
  1526. tok = find_by_keyword(tokens, R_HS_DESCRIPTOR);
  1527. tor_assert(tok->n_args == 1);
  1528. plaintext->version = (uint32_t) tor_parse_ulong(tok->args[0], 10, 0,
  1529. UINT32_MAX, &ok, NULL);
  1530. if (!ok) {
  1531. log_warn(LD_REND, "Service descriptor has unparseable version %s",
  1532. escaped(tok->args[0]));
  1533. goto err;
  1534. }
  1535. if (!hs_desc_is_supported_version(plaintext->version)) {
  1536. log_warn(LD_REND, "Service descriptor has unsupported version %" PRIu32,
  1537. plaintext->version);
  1538. goto err;
  1539. }
  1540. /* Extra precaution. Having no handler for the supported version should
  1541. * never happened else we forgot to add it but we bumped the version. */
  1542. tor_assert(ARRAY_LENGTH(decode_plaintext_handlers) >= plaintext->version);
  1543. tor_assert(decode_plaintext_handlers[plaintext->version]);
  1544. /* Run the version specific plaintext decoder. */
  1545. ret = decode_plaintext_handlers[plaintext->version](tokens, plaintext,
  1546. encoded, encoded_len);
  1547. if (ret < 0) {
  1548. goto err;
  1549. }
  1550. /* Success. Descriptor has been populated with the data. */
  1551. ret = 0;
  1552. err:
  1553. if (tokens) {
  1554. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1555. smartlist_free(tokens);
  1556. }
  1557. if (area) {
  1558. memarea_drop_all(area);
  1559. }
  1560. return ret;
  1561. }
  1562. /* Fully decode an encoded descriptor and set a newly allocated descriptor
  1563. * object in desc_out. Subcredentials are used if not NULL else it's ignored.
  1564. *
  1565. * Return 0 on success. A negative value is returned on error and desc_out is
  1566. * set to NULL. */
  1567. int
  1568. hs_desc_decode_descriptor(const char *encoded,
  1569. const uint8_t *subcredential,
  1570. hs_descriptor_t **desc_out)
  1571. {
  1572. int ret;
  1573. hs_descriptor_t *desc;
  1574. tor_assert(encoded);
  1575. desc = tor_malloc_zero(sizeof(hs_descriptor_t));
  1576. /* Subcredentials are optional. */
  1577. if (subcredential) {
  1578. memcpy(desc->subcredential, subcredential, sizeof(desc->subcredential));
  1579. }
  1580. ret = hs_desc_decode_plaintext(encoded, &desc->plaintext_data);
  1581. if (ret < 0) {
  1582. goto err;
  1583. }
  1584. ret = hs_desc_decode_encrypted(desc, &desc->encrypted_data);
  1585. if (ret < 0) {
  1586. goto err;
  1587. }
  1588. if (desc_out) {
  1589. *desc_out = desc;
  1590. } else {
  1591. hs_descriptor_free(desc);
  1592. }
  1593. return ret;
  1594. err:
  1595. hs_descriptor_free(desc);
  1596. if (desc_out) {
  1597. *desc_out = NULL;
  1598. }
  1599. tor_assert(ret < 0);
  1600. return ret;
  1601. }
  1602. /* Table of encode function version specific. The functions are indexed by the
  1603. * version number so v3 callback is at index 3 in the array. */
  1604. static int
  1605. (*encode_handlers[])(
  1606. const hs_descriptor_t *desc,
  1607. const ed25519_keypair_t *signing_kp,
  1608. char **encoded_out) =
  1609. {
  1610. /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
  1611. desc_encode_v3,
  1612. };
  1613. /* Encode the given descriptor desc including signing with the given key pair
  1614. * signing_kp. On success, encoded_out points to a newly allocated NUL
  1615. * terminated string that contains the encoded descriptor as a string.
  1616. *
  1617. * Return 0 on success and encoded_out is a valid pointer. On error, -1 is
  1618. * returned and encoded_out is set to NULL. */
  1619. int
  1620. hs_desc_encode_descriptor(const hs_descriptor_t *desc,
  1621. const ed25519_keypair_t *signing_kp,
  1622. char **encoded_out)
  1623. {
  1624. int ret = -1;
  1625. uint32_t version;
  1626. tor_assert(desc);
  1627. tor_assert(encoded_out);
  1628. /* Make sure we support the version of the descriptor format. */
  1629. version = desc->plaintext_data.version;
  1630. if (!hs_desc_is_supported_version(version)) {
  1631. goto err;
  1632. }
  1633. /* Extra precaution. Having no handler for the supported version should
  1634. * never happened else we forgot to add it but we bumped the version. */
  1635. tor_assert(ARRAY_LENGTH(encode_handlers) >= version);
  1636. tor_assert(encode_handlers[version]);
  1637. ret = encode_handlers[version](desc, signing_kp, encoded_out);
  1638. if (ret < 0) {
  1639. goto err;
  1640. }
  1641. /* Try to decode what we just encoded. Symmetry is nice! */
  1642. ret = hs_desc_decode_descriptor(*encoded_out, desc->subcredential, NULL);
  1643. if (BUG(ret < 0)) {
  1644. goto err;
  1645. }
  1646. return 0;
  1647. err:
  1648. *encoded_out = NULL;
  1649. return ret;
  1650. }
  1651. /* Free the descriptor plaintext data object. */
  1652. void
  1653. hs_desc_plaintext_data_free(hs_desc_plaintext_data_t *desc)
  1654. {
  1655. desc_plaintext_data_free_contents(desc);
  1656. tor_free(desc);
  1657. }
  1658. /* Free the descriptor encrypted data object. */
  1659. void
  1660. hs_desc_encrypted_data_free(hs_desc_encrypted_data_t *desc)
  1661. {
  1662. desc_encrypted_data_free_contents(desc);
  1663. tor_free(desc);
  1664. }
  1665. /* Free the given descriptor object. */
  1666. void
  1667. hs_descriptor_free(hs_descriptor_t *desc)
  1668. {
  1669. if (!desc) {
  1670. return;
  1671. }
  1672. desc_plaintext_data_free_contents(&desc->plaintext_data);
  1673. desc_encrypted_data_free_contents(&desc->encrypted_data);
  1674. tor_free(desc);
  1675. }
  1676. /* Return the size in bytes of the given plaintext data object. A sizeof() is
  1677. * not enough because the object contains pointers and the encrypted blob.
  1678. * This is particularly useful for our OOM subsystem that tracks the HSDir
  1679. * cache size for instance. */
  1680. size_t
  1681. hs_desc_plaintext_obj_size(const hs_desc_plaintext_data_t *data)
  1682. {
  1683. tor_assert(data);
  1684. return (sizeof(*data) + sizeof(*data->signing_key_cert) +
  1685. data->encrypted_blob_size);
  1686. }