hs_descriptor.c 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903
  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_keypair_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->pubkey,
  212. ip->enc_key.legacy,
  213. now + HS_DESC_CERT_LIFETIME,
  214. &cert_data);
  215. if (cert_len < 0) {
  216. log_warn(LD_REND, "Unable to create legacy crosscert.");
  217. goto err;
  218. }
  219. /* Encode cross cert. */
  220. if (base64_encode(b64_cert, sizeof(b64_cert), (const char *) cert_data,
  221. cert_len, BASE64_ENCODE_MULTILINE) < 0) {
  222. tor_free(cert_data);
  223. log_warn(LD_REND, "Unable to encode legacy crosscert.");
  224. goto err;
  225. }
  226. tor_free(cert_data);
  227. /* Convert the encryption key to a string. */
  228. if (crypto_pk_write_public_key_to_string(ip->enc_key.legacy, &key_str,
  229. &key_str_len) < 0) {
  230. log_warn(LD_REND, "Unable to encode legacy encryption key.");
  231. goto err;
  232. }
  233. tor_asprintf(&encoded,
  234. "%s legacy\n%s" /* Newline is added by the call above. */
  235. "%s\n"
  236. "-----BEGIN CROSSCERT-----\n"
  237. "%s"
  238. "-----END CROSSCERT-----",
  239. str_ip_enc_key, key_str,
  240. str_ip_enc_key_cert, b64_cert);
  241. tor_free(key_str);
  242. break;
  243. }
  244. case HS_DESC_KEY_TYPE_CURVE25519:
  245. {
  246. int signbit, ret;
  247. char *encoded_cert, key_fp_b64[CURVE25519_BASE64_PADDED_LEN + 1];
  248. ed25519_keypair_t curve_kp;
  249. if (ed25519_keypair_from_curve25519_keypair(&curve_kp, &signbit,
  250. &ip->enc_key.curve25519)) {
  251. goto err;
  252. }
  253. tor_cert_t *cross_cert = tor_cert_create(&curve_kp,
  254. CERT_TYPE_CROSS_HS_IP_KEYS,
  255. &sig_key->pubkey, now,
  256. HS_DESC_CERT_LIFETIME,
  257. CERT_FLAG_INCLUDE_SIGNING_KEY);
  258. memwipe(&curve_kp, 0, sizeof(curve_kp));
  259. if (!cross_cert) {
  260. goto err;
  261. }
  262. ret = tor_cert_encode_ed22519(cross_cert, &encoded_cert);
  263. tor_cert_free(cross_cert);
  264. if (ret) {
  265. goto err;
  266. }
  267. if (curve25519_public_to_base64(key_fp_b64,
  268. &ip->enc_key.curve25519.pubkey) < 0) {
  269. tor_free(encoded_cert);
  270. goto err;
  271. }
  272. tor_asprintf(&encoded,
  273. "%s ntor %s\n"
  274. "%s\n%s",
  275. str_ip_enc_key, key_fp_b64,
  276. str_ip_enc_key_cert, encoded_cert);
  277. tor_free(encoded_cert);
  278. break;
  279. }
  280. default:
  281. tor_assert(0);
  282. }
  283. err:
  284. return encoded;
  285. }
  286. /* Encode an introduction point object and return a newly allocated string
  287. * with it. On failure, return NULL. */
  288. static char *
  289. encode_intro_point(const ed25519_keypair_t *sig_key,
  290. const hs_desc_intro_point_t *ip)
  291. {
  292. char *encoded_ip = NULL;
  293. smartlist_t *lines = smartlist_new();
  294. tor_assert(ip);
  295. tor_assert(sig_key);
  296. /* Encode link specifier. */
  297. {
  298. char *ls_str = encode_link_specifiers(ip->link_specifiers);
  299. smartlist_add_asprintf(lines, "%s %s", str_intro_point, ls_str);
  300. tor_free(ls_str);
  301. }
  302. /* Authentication key encoding. */
  303. {
  304. char *encoded_cert;
  305. if (tor_cert_encode_ed22519(ip->auth_key_cert, &encoded_cert) < 0) {
  306. goto err;
  307. }
  308. smartlist_add_asprintf(lines, "%s\n%s", str_ip_auth_key, encoded_cert);
  309. tor_free(encoded_cert);
  310. }
  311. /* Encryption key encoding. */
  312. {
  313. char *encoded_enc_key = encode_enc_key(sig_key, ip);
  314. if (encoded_enc_key == NULL) {
  315. goto err;
  316. }
  317. smartlist_add_asprintf(lines, "%s", encoded_enc_key);
  318. tor_free(encoded_enc_key);
  319. }
  320. /* Join them all in one blob of text. */
  321. encoded_ip = smartlist_join_strings(lines, "\n", 1, NULL);
  322. err:
  323. SMARTLIST_FOREACH(lines, char *, l, tor_free(l));
  324. smartlist_free(lines);
  325. return encoded_ip;
  326. }
  327. /* Using a given decriptor object, build the secret input needed for the
  328. * KDF and put it in the dst pointer which is an already allocated buffer
  329. * of size dstlen. */
  330. static void
  331. build_secret_input(const hs_descriptor_t *desc, uint8_t *dst, size_t dstlen)
  332. {
  333. size_t offset = 0;
  334. tor_assert(desc);
  335. tor_assert(dst);
  336. tor_assert(HS_DESC_ENCRYPTED_SECRET_INPUT_LEN <= dstlen);
  337. /* XXX use the destination length as the memcpy length */
  338. /* Copy blinded public key. */
  339. memcpy(dst, desc->plaintext_data.blinded_kp.pubkey.pubkey,
  340. sizeof(desc->plaintext_data.blinded_kp.pubkey.pubkey));
  341. offset += sizeof(desc->plaintext_data.blinded_kp.pubkey.pubkey);
  342. /* Copy subcredential. */
  343. memcpy(dst + offset, desc->subcredential, sizeof(desc->subcredential));
  344. offset += sizeof(desc->subcredential);
  345. /* Copy revision counter value. */
  346. set_uint64(dst + offset, tor_ntohll(desc->plaintext_data.revision_counter));
  347. offset += sizeof(uint64_t);
  348. tor_assert(HS_DESC_ENCRYPTED_SECRET_INPUT_LEN == offset);
  349. }
  350. /* Do the KDF construction and put the resulting data in key_out which is of
  351. * key_out_len length. It uses SHAKE-256 as specified in the spec. */
  352. static void
  353. build_kdf_key(const hs_descriptor_t *desc,
  354. const uint8_t *salt, size_t salt_len,
  355. uint8_t *key_out, size_t key_out_len)
  356. {
  357. uint8_t secret_input[HS_DESC_ENCRYPTED_SECRET_INPUT_LEN];
  358. crypto_xof_t *xof;
  359. tor_assert(desc);
  360. tor_assert(salt);
  361. tor_assert(key_out);
  362. /* Build the secret input for the KDF computation. */
  363. build_secret_input(desc, secret_input, sizeof(secret_input));
  364. xof = crypto_xof_new();
  365. /* Feed our KDF. [SHAKE it like a polaroid picture --Yawning]. */
  366. crypto_xof_add_bytes(xof, secret_input, sizeof(secret_input));
  367. crypto_xof_add_bytes(xof, salt, salt_len);
  368. crypto_xof_add_bytes(xof, (const uint8_t *) str_enc_hsdir_data,
  369. strlen(str_enc_hsdir_data));
  370. /* Eat from our KDF. */
  371. crypto_xof_squeeze_bytes(xof, key_out, key_out_len);
  372. crypto_xof_free(xof);
  373. memwipe(secret_input, 0, sizeof(secret_input));
  374. }
  375. /* Using the given descriptor and salt, run it through our KDF function and
  376. * then extract a secret key in key_out, the IV in iv_out and MAC in mac_out.
  377. * This function can't fail. */
  378. static void
  379. build_secret_key_iv_mac(const hs_descriptor_t *desc,
  380. const uint8_t *salt, size_t salt_len,
  381. uint8_t *key_out, size_t key_len,
  382. uint8_t *iv_out, size_t iv_len,
  383. uint8_t *mac_out, size_t mac_len)
  384. {
  385. size_t offset = 0;
  386. uint8_t kdf_key[HS_DESC_ENCRYPTED_KDF_OUTPUT_LEN];
  387. tor_assert(desc);
  388. tor_assert(salt);
  389. tor_assert(key_out);
  390. tor_assert(iv_out);
  391. tor_assert(mac_out);
  392. build_kdf_key(desc, salt, salt_len, kdf_key, sizeof(kdf_key));
  393. /* Copy the bytes we need for both the secret key and IV. */
  394. memcpy(key_out, kdf_key, key_len);
  395. offset += key_len;
  396. memcpy(iv_out, kdf_key + offset, iv_len);
  397. offset += iv_len;
  398. memcpy(mac_out, kdf_key + offset, mac_len);
  399. /* Extra precaution to make sure we are not out of bound. */
  400. tor_assert((offset + mac_len) == sizeof(kdf_key));
  401. memwipe(kdf_key, 0, sizeof(kdf_key));
  402. }
  403. /* Using a key, salt and encrypted payload, build a MAC and put it in mac_out.
  404. * We use SHA3-256 for the MAC computation.
  405. * This function can't fail. */
  406. static void
  407. build_mac(const uint8_t *mac_key, size_t mac_key_len,
  408. const uint8_t *salt, size_t salt_len,
  409. const uint8_t *encrypted, size_t encrypted_len,
  410. uint8_t *mac_out, size_t mac_len)
  411. {
  412. crypto_digest_t *digest;
  413. const uint64_t mac_len_netorder = tor_htonll(mac_key_len);
  414. const uint64_t salt_len_netorder = tor_htonll(salt_len);
  415. tor_assert(mac_key);
  416. tor_assert(salt);
  417. tor_assert(encrypted);
  418. tor_assert(mac_out);
  419. digest = crypto_digest256_new(DIGEST_SHA3_256);
  420. /* As specified in section 2.5 of proposal 224, first add the mac key
  421. * then add the salt first and then the encrypted section. */
  422. crypto_digest_add_bytes(digest, (const char *) &mac_len_netorder, 8);
  423. crypto_digest_add_bytes(digest, (const char *) mac_key, mac_key_len);
  424. crypto_digest_add_bytes(digest, (const char *) &salt_len_netorder, 8);
  425. crypto_digest_add_bytes(digest, (const char *) salt, salt_len);
  426. crypto_digest_add_bytes(digest, (const char *) encrypted, encrypted_len);
  427. crypto_digest_get_digest(digest, (char *) mac_out, mac_len);
  428. crypto_digest_free(digest);
  429. }
  430. /* Given a source length, return the new size including padding for the
  431. * plaintext encryption. */
  432. static size_t
  433. compute_padded_plaintext_length(size_t plaintext_len)
  434. {
  435. size_t plaintext_padded_len;
  436. /* Make sure we won't overflow. */
  437. tor_assert(plaintext_len <=
  438. (SIZE_T_CEILING - HS_DESC_PLAINTEXT_PADDING_MULTIPLE));
  439. /* Get the extra length we need to add. For example, if srclen is 234 bytes,
  440. * this will expand to (2 * 128) == 256 thus an extra 22 bytes. */
  441. plaintext_padded_len = CEIL_DIV(plaintext_len,
  442. HS_DESC_PLAINTEXT_PADDING_MULTIPLE) *
  443. HS_DESC_PLAINTEXT_PADDING_MULTIPLE;
  444. /* Can never be extra careful. Make sure we are _really_ padded. */
  445. tor_assert(!(plaintext_padded_len % HS_DESC_PLAINTEXT_PADDING_MULTIPLE));
  446. return plaintext_padded_len;
  447. }
  448. /* Given a buffer, pad it up to the encrypted section padding requirement. Set
  449. * the newly allocated string in padded_out and return the length of the
  450. * padded buffer. */
  451. STATIC size_t
  452. build_plaintext_padding(const char *plaintext, size_t plaintext_len,
  453. uint8_t **padded_out)
  454. {
  455. size_t padded_len;
  456. uint8_t *padded;
  457. tor_assert(plaintext);
  458. tor_assert(padded_out);
  459. /* Allocate the final length including padding. */
  460. padded_len = compute_padded_plaintext_length(plaintext_len);
  461. tor_assert(padded_len >= plaintext_len);
  462. padded = tor_malloc_zero(padded_len);
  463. memcpy(padded, plaintext, plaintext_len);
  464. *padded_out = padded;
  465. return padded_len;
  466. }
  467. /* Using a key, IV and plaintext data of length plaintext_len, create the
  468. * encrypted section by encrypting it and setting encrypted_out with the
  469. * data. Return size of the encrypted data buffer. */
  470. static size_t
  471. build_encrypted(const uint8_t *key, const uint8_t *iv, const char *plaintext,
  472. size_t plaintext_len, uint8_t **encrypted_out)
  473. {
  474. size_t encrypted_len;
  475. uint8_t *padded_plaintext, *encrypted;
  476. crypto_cipher_t *cipher;
  477. tor_assert(key);
  478. tor_assert(iv);
  479. tor_assert(plaintext);
  480. tor_assert(encrypted_out);
  481. /* This creates a cipher for AES128. It can't fail. */
  482. cipher = crypto_cipher_new_with_iv((const char *) key, (const char *) iv);
  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[CIPHER_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_kp,
  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, 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(encoded_out);
  639. tor_assert(desc->plaintext_data.version == 3);
  640. /* Build the non-encrypted values. */
  641. {
  642. char *encoded_cert;
  643. /* Encode certificate then create the first line of the descriptor. */
  644. if (desc->plaintext_data.signing_key_cert->cert_type
  645. != CERT_TYPE_SIGNING_HS_DESC) {
  646. log_err(LD_BUG, "HS descriptor signing key has an unexpected cert type "
  647. "(%d)", (int) desc->plaintext_data.signing_key_cert->cert_type);
  648. goto err;
  649. }
  650. if (tor_cert_encode_ed22519(desc->plaintext_data.signing_key_cert,
  651. &encoded_cert) < 0) {
  652. /* The function will print error logs. */
  653. goto err;
  654. }
  655. /* Create the hs descriptor line. */
  656. smartlist_add_asprintf(lines, "%s %" PRIu32, str_hs_desc,
  657. desc->plaintext_data.version);
  658. /* Add the descriptor lifetime line (in minutes). */
  659. smartlist_add_asprintf(lines, "%s %" PRIu32, str_lifetime,
  660. desc->plaintext_data.lifetime_sec / 60);
  661. /* Create the descriptor certificate line. */
  662. smartlist_add_asprintf(lines, "%s\n%s", str_desc_cert, encoded_cert);
  663. tor_free(encoded_cert);
  664. /* Create the revision counter line. */
  665. smartlist_add_asprintf(lines, "%s %" PRIu64, str_rev_counter,
  666. desc->plaintext_data.revision_counter);
  667. }
  668. /* Build the superencrypted data section. */
  669. {
  670. char *enc_b64_blob=NULL;
  671. if (encode_encrypted_data(desc, &enc_b64_blob) < 0) {
  672. goto err;
  673. }
  674. smartlist_add_asprintf(lines,
  675. "%s\n"
  676. "-----BEGIN MESSAGE-----\n"
  677. "%s"
  678. "-----END MESSAGE-----",
  679. str_superencrypted, enc_b64_blob);
  680. tor_free(enc_b64_blob);
  681. }
  682. /* Join all lines in one string so we can generate a signature and append
  683. * it to the descriptor. */
  684. encoded_str = smartlist_join_strings(lines, "\n", 1, &encoded_len);
  685. /* Sign all fields of the descriptor with our short term signing key. */
  686. {
  687. ed25519_signature_t sig;
  688. char ed_sig_b64[ED25519_SIG_BASE64_LEN + 1];
  689. if (ed25519_sign_prefixed(&sig,
  690. (const uint8_t *) encoded_str, encoded_len,
  691. str_desc_sig_prefix,
  692. &desc->plaintext_data.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, const ed25519_keypair_t *signing_kp,
  1212. const char *encoded_desc, size_t encoded_len)
  1213. {
  1214. int ret = 0;
  1215. ed25519_signature_t sig;
  1216. const char *sig_start;
  1217. tor_assert(b64_sig);
  1218. tor_assert(signing_kp);
  1219. tor_assert(encoded_desc);
  1220. /* Verifying nothing won't end well :). */
  1221. tor_assert(encoded_len > 0);
  1222. /* Signature length check. */
  1223. if (strlen(b64_sig) != ED25519_SIG_BASE64_LEN) {
  1224. log_warn(LD_REND, "Service descriptor has an invalid signature length."
  1225. "Exptected %d but got %lu",
  1226. ED25519_SIG_BASE64_LEN, (unsigned long) strlen(b64_sig));
  1227. goto err;
  1228. }
  1229. /* First, convert base64 blob to an ed25519 signature. */
  1230. if (ed25519_signature_from_base64(&sig, b64_sig) != 0) {
  1231. log_warn(LD_REND, "Service descriptor does not contain a valid "
  1232. "signature");
  1233. goto err;
  1234. }
  1235. /* Find the start of signature. */
  1236. sig_start = tor_memstr(encoded_desc, encoded_len, "\n" str_signature);
  1237. /* Getting here means the token parsing worked for the signature so if we
  1238. * can't find the start of the signature, we have a code flow issue. */
  1239. if (BUG(!sig_start)) {
  1240. goto err;
  1241. }
  1242. /* Skip newline, it has to go in the signature check. */
  1243. sig_start++;
  1244. /* Validate signature with the full body of the descriptor. */
  1245. if (ed25519_checksig_prefixed(&sig,
  1246. (const uint8_t *) encoded_desc,
  1247. sig_start - encoded_desc,
  1248. str_desc_sig_prefix,
  1249. &signing_kp->pubkey) != 0) {
  1250. log_warn(LD_REND, "Invalid signature on service descriptor");
  1251. goto err;
  1252. }
  1253. /* Valid signature! All is good. */
  1254. ret = 1;
  1255. err:
  1256. return ret;
  1257. }
  1258. /* Decode descriptor plaintext data for version 3. Given a list of tokens, an
  1259. * allocated plaintext object that will be populated and the encoded
  1260. * descriptor with its length. The last one is needed for signature
  1261. * verification. Unknown tokens are simply ignored so this won't error on
  1262. * unknowns but requires that all v3 token be present and valid.
  1263. *
  1264. * Return 0 on success else a negative value. */
  1265. static int
  1266. desc_decode_plaintext_v3(smartlist_t *tokens,
  1267. hs_desc_plaintext_data_t *desc,
  1268. const char *encoded_desc, size_t encoded_len)
  1269. {
  1270. int ok;
  1271. directory_token_t *tok;
  1272. tor_assert(tokens);
  1273. tor_assert(desc);
  1274. /* Version higher could still use this function to decode most of the
  1275. * descriptor and then they decode the extra part. */
  1276. tor_assert(desc->version >= 3);
  1277. /* Descriptor lifetime parsing. */
  1278. tok = find_by_keyword(tokens, R3_DESC_LIFETIME);
  1279. tor_assert(tok->n_args == 1);
  1280. desc->lifetime_sec = (uint32_t) tor_parse_ulong(tok->args[0], 10, 0,
  1281. UINT32_MAX, &ok, NULL);
  1282. if (!ok) {
  1283. log_warn(LD_REND, "Service descriptor lifetime value is invalid");
  1284. goto err;
  1285. }
  1286. /* Put it from minute to second. */
  1287. desc->lifetime_sec *= 60;
  1288. if (desc->lifetime_sec > HS_DESC_MAX_LIFETIME) {
  1289. log_warn(LD_REND, "Service descriptor lifetime is too big. "
  1290. "Got %" PRIu32 " but max is %d",
  1291. desc->lifetime_sec, HS_DESC_MAX_LIFETIME);
  1292. goto err;
  1293. }
  1294. /* Descriptor signing certificate. */
  1295. tok = find_by_keyword(tokens, R3_DESC_SIGNING_CERT);
  1296. tor_assert(tok->object_body);
  1297. /* Expecting a prop220 cert with the signing key extension, which contains
  1298. * the blinded public key. */
  1299. if (strcmp(tok->object_type, "ED25519 CERT") != 0) {
  1300. log_warn(LD_REND, "Service descriptor signing cert wrong type (%s)",
  1301. escaped(tok->object_type));
  1302. goto err;
  1303. }
  1304. if (cert_parse_and_validate(&desc->signing_key_cert, tok->object_body,
  1305. tok->object_size, CERT_TYPE_SIGNING_HS_DESC,
  1306. "service descriptor signing key") < 0) {
  1307. goto err;
  1308. }
  1309. /* Copy the public keys into signing_kp and blinded_kp */
  1310. memcpy(&desc->signing_kp.pubkey, &desc->signing_key_cert->signed_key,
  1311. sizeof(ed25519_public_key_t));
  1312. memcpy(&desc->blinded_kp.pubkey, &desc->signing_key_cert->signing_key,
  1313. sizeof(ed25519_public_key_t));
  1314. /* Extract revision counter value. */
  1315. tok = find_by_keyword(tokens, R3_REVISION_COUNTER);
  1316. tor_assert(tok->n_args == 1);
  1317. desc->revision_counter = tor_parse_uint64(tok->args[0], 10, 0,
  1318. UINT64_MAX, &ok, NULL);
  1319. if (!ok) {
  1320. log_warn(LD_REND, "Service descriptor revision-counter is invalid");
  1321. goto err;
  1322. }
  1323. /* Extract the encrypted data section. */
  1324. tok = find_by_keyword(tokens, R3_SUPERENCRYPTED);
  1325. tor_assert(tok->object_body);
  1326. if (strcmp(tok->object_type, "MESSAGE") != 0) {
  1327. log_warn(LD_REND, "Service descriptor encrypted data section is invalid");
  1328. goto err;
  1329. }
  1330. /* Make sure the length of the encrypted blob is valid. */
  1331. if (!encrypted_data_length_is_valid(tok->object_size)) {
  1332. goto err;
  1333. }
  1334. /* Copy the encrypted blob to the descriptor object so we can handle it
  1335. * latter if needed. */
  1336. desc->encrypted_blob = tor_memdup(tok->object_body, tok->object_size);
  1337. desc->encrypted_blob_size = tok->object_size;
  1338. /* Extract signature and verify it. */
  1339. tok = find_by_keyword(tokens, R3_SIGNATURE);
  1340. tor_assert(tok->n_args == 1);
  1341. /* First arg here is the actual encoded signature. */
  1342. if (!desc_sig_is_valid(tok->args[0], &desc->signing_kp,
  1343. encoded_desc, encoded_len)) {
  1344. goto err;
  1345. }
  1346. return 0;
  1347. err:
  1348. return -1;
  1349. }
  1350. /* Decode the version 3 encrypted section of the given descriptor desc. The
  1351. * desc_encrypted_out will be populated with the decoded data. Return 0 on
  1352. * success else -1. */
  1353. static int
  1354. desc_decode_encrypted_v3(const hs_descriptor_t *desc,
  1355. hs_desc_encrypted_data_t *desc_encrypted_out)
  1356. {
  1357. int result = -1;
  1358. char *message = NULL;
  1359. size_t message_len;
  1360. memarea_t *area = NULL;
  1361. directory_token_t *tok;
  1362. smartlist_t *tokens = NULL;
  1363. tor_assert(desc);
  1364. tor_assert(desc_encrypted_out);
  1365. /* Decrypt the encrypted data that is located in the plaintext section in
  1366. * the descriptor as a blob of bytes. The following functions will use the
  1367. * keys found in the same section. */
  1368. message_len = desc_decrypt_data_v3(desc, &message);
  1369. if (!message_len) {
  1370. log_warn(LD_REND, "Service descriptor decryption failed.");
  1371. goto err;
  1372. }
  1373. tor_assert(message);
  1374. area = memarea_new();
  1375. tokens = smartlist_new();
  1376. if (tokenize_string(area, message, message + message_len,
  1377. tokens, hs_desc_encrypted_v3_token_table, 0) < 0) {
  1378. log_warn(LD_REND, "Encrypted service descriptor is not parseable.");
  1379. goto err;
  1380. }
  1381. /* CREATE2 supported cell format. It's mandatory. */
  1382. tok = find_by_keyword(tokens, R3_CREATE2_FORMATS);
  1383. tor_assert(tok);
  1384. decode_create2_list(desc_encrypted_out, tok->args[0]);
  1385. /* Must support ntor according to the specification */
  1386. if (!desc_encrypted_out->create2_ntor) {
  1387. log_warn(LD_REND, "Service create2-formats does not include ntor.");
  1388. goto err;
  1389. }
  1390. /* Authentication type. It's optional but only once. */
  1391. tok = find_opt_by_keyword(tokens, R3_AUTHENTICATION_REQUIRED);
  1392. if (tok) {
  1393. if (!decode_auth_type(desc_encrypted_out, tok->args[0])) {
  1394. log_warn(LD_REND, "Service descriptor authentication type has "
  1395. "invalid entry(ies).");
  1396. goto err;
  1397. }
  1398. }
  1399. /* Is this service a single onion service? */
  1400. tok = find_opt_by_keyword(tokens, R3_SINGLE_ONION_SERVICE);
  1401. if (tok) {
  1402. desc_encrypted_out->single_onion_service = 1;
  1403. }
  1404. /* Initialize the descriptor's introduction point list before we start
  1405. * decoding. Having 0 intro point is valid. Then decode them all. */
  1406. desc_encrypted_out->intro_points = smartlist_new();
  1407. if (decode_intro_points(desc, desc_encrypted_out, message) < 0) {
  1408. goto err;
  1409. }
  1410. /* Validation of maximum introduction points allowed. */
  1411. if (smartlist_len(desc_encrypted_out->intro_points) > MAX_INTRO_POINTS) {
  1412. log_warn(LD_REND, "Service descriptor contains too many introduction "
  1413. "points. Maximum allowed is %d but we have %d",
  1414. MAX_INTRO_POINTS,
  1415. smartlist_len(desc_encrypted_out->intro_points));
  1416. goto err;
  1417. }
  1418. /* NOTE: Unknown fields are allowed because this function could be used to
  1419. * decode other descriptor version. */
  1420. result = 0;
  1421. goto done;
  1422. err:
  1423. tor_assert(result < 0);
  1424. desc_encrypted_data_free_contents(desc_encrypted_out);
  1425. done:
  1426. if (tokens) {
  1427. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1428. smartlist_free(tokens);
  1429. }
  1430. if (area) {
  1431. memarea_drop_all(area);
  1432. }
  1433. if (message) {
  1434. tor_free(message);
  1435. }
  1436. return result;
  1437. }
  1438. /* Table of encrypted decode function version specific. The function are
  1439. * indexed by the version number so v3 callback is at index 3 in the array. */
  1440. static int
  1441. (*decode_encrypted_handlers[])(
  1442. const hs_descriptor_t *desc,
  1443. hs_desc_encrypted_data_t *desc_encrypted) =
  1444. {
  1445. /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
  1446. desc_decode_encrypted_v3,
  1447. };
  1448. /* Decode the encrypted data section of the given descriptor and store the
  1449. * data in the given encrypted data object. Return 0 on success else a
  1450. * negative value on error. */
  1451. int
  1452. hs_desc_decode_encrypted(const hs_descriptor_t *desc,
  1453. hs_desc_encrypted_data_t *desc_encrypted)
  1454. {
  1455. int ret;
  1456. uint32_t version;
  1457. tor_assert(desc);
  1458. /* Ease our life a bit. */
  1459. version = desc->plaintext_data.version;
  1460. tor_assert(desc_encrypted);
  1461. /* Calling this function without an encrypted blob to parse is a code flow
  1462. * error. The plaintext parsing should never succeed in the first place
  1463. * without an encrypted section. */
  1464. tor_assert(desc->plaintext_data.encrypted_blob);
  1465. /* Let's make sure we have a supported version as well. By correctly parsing
  1466. * the plaintext, this should not fail. */
  1467. if (BUG(!hs_desc_is_supported_version(version))) {
  1468. ret = -1;
  1469. goto err;
  1470. }
  1471. /* Extra precaution. Having no handler for the supported version should
  1472. * never happened else we forgot to add it but we bumped the version. */
  1473. tor_assert(ARRAY_LENGTH(decode_encrypted_handlers) >= version);
  1474. tor_assert(decode_encrypted_handlers[version]);
  1475. /* Run the version specific plaintext decoder. */
  1476. ret = decode_encrypted_handlers[version](desc, desc_encrypted);
  1477. if (ret < 0) {
  1478. goto err;
  1479. }
  1480. err:
  1481. return ret;
  1482. }
  1483. /* Table of plaintext decode function version specific. The function are
  1484. * indexed by the version number so v3 callback is at index 3 in the array. */
  1485. static int
  1486. (*decode_plaintext_handlers[])(
  1487. smartlist_t *tokens,
  1488. hs_desc_plaintext_data_t *desc,
  1489. const char *encoded_desc,
  1490. size_t encoded_len) =
  1491. {
  1492. /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
  1493. desc_decode_plaintext_v3,
  1494. };
  1495. /* Fully decode the given descriptor plaintext and store the data in the
  1496. * plaintext data object. Returns 0 on success else a negative value. */
  1497. int
  1498. hs_desc_decode_plaintext(const char *encoded,
  1499. hs_desc_plaintext_data_t *plaintext)
  1500. {
  1501. int ok = 0, ret = -1;
  1502. memarea_t *area = NULL;
  1503. smartlist_t *tokens = NULL;
  1504. size_t encoded_len;
  1505. directory_token_t *tok;
  1506. tor_assert(encoded);
  1507. tor_assert(plaintext);
  1508. /* Check that descriptor is within size limits. */
  1509. encoded_len = strlen(encoded);
  1510. if (encoded_len >= hs_cache_get_max_descriptor_size()) {
  1511. log_warn(LD_REND, "Service descriptor is too big (%lu bytes)",
  1512. (unsigned long) encoded_len);
  1513. goto err;
  1514. }
  1515. area = memarea_new();
  1516. tokens = smartlist_new();
  1517. /* Tokenize the descriptor so we can start to parse it. */
  1518. if (tokenize_string(area, encoded, encoded + encoded_len, tokens,
  1519. hs_desc_v3_token_table, 0) < 0) {
  1520. log_warn(LD_REND, "Service descriptor is not parseable");
  1521. goto err;
  1522. }
  1523. /* Get the version of the descriptor which is the first mandatory field of
  1524. * the descriptor. From there, we'll decode the right descriptor version. */
  1525. tok = find_by_keyword(tokens, R_HS_DESCRIPTOR);
  1526. tor_assert(tok->n_args == 1);
  1527. plaintext->version = (uint32_t) tor_parse_ulong(tok->args[0], 10, 0,
  1528. UINT32_MAX, &ok, NULL);
  1529. if (!ok) {
  1530. log_warn(LD_REND, "Service descriptor has unparseable version %s",
  1531. escaped(tok->args[0]));
  1532. goto err;
  1533. }
  1534. if (!hs_desc_is_supported_version(plaintext->version)) {
  1535. log_warn(LD_REND, "Service descriptor has unsupported version %" PRIu32,
  1536. plaintext->version);
  1537. goto err;
  1538. }
  1539. /* Extra precaution. Having no handler for the supported version should
  1540. * never happened else we forgot to add it but we bumped the version. */
  1541. tor_assert(ARRAY_LENGTH(decode_plaintext_handlers) >= plaintext->version);
  1542. tor_assert(decode_plaintext_handlers[plaintext->version]);
  1543. /* Run the version specific plaintext decoder. */
  1544. ret = decode_plaintext_handlers[plaintext->version](tokens, plaintext,
  1545. encoded, encoded_len);
  1546. if (ret < 0) {
  1547. goto err;
  1548. }
  1549. /* Success. Descriptor has been populated with the data. */
  1550. ret = 0;
  1551. err:
  1552. if (tokens) {
  1553. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1554. smartlist_free(tokens);
  1555. }
  1556. if (area) {
  1557. memarea_drop_all(area);
  1558. }
  1559. return ret;
  1560. }
  1561. /* Fully decode an encoded descriptor and set a newly allocated descriptor
  1562. * object in desc_out. Subcredentials are used if not NULL else it's ignored.
  1563. *
  1564. * Return 0 on success. A negative value is returned on error and desc_out is
  1565. * set to NULL. */
  1566. int
  1567. hs_desc_decode_descriptor(const char *encoded,
  1568. const uint8_t *subcredential,
  1569. hs_descriptor_t **desc_out)
  1570. {
  1571. int ret;
  1572. hs_descriptor_t *desc;
  1573. tor_assert(encoded);
  1574. desc = tor_malloc_zero(sizeof(hs_descriptor_t));
  1575. /* Subcredentials are optional. */
  1576. if (subcredential) {
  1577. memcpy(desc->subcredential, subcredential, sizeof(desc->subcredential));
  1578. }
  1579. ret = hs_desc_decode_plaintext(encoded, &desc->plaintext_data);
  1580. if (ret < 0) {
  1581. goto err;
  1582. }
  1583. ret = hs_desc_decode_encrypted(desc, &desc->encrypted_data);
  1584. if (ret < 0) {
  1585. goto err;
  1586. }
  1587. if (desc_out) {
  1588. *desc_out = desc;
  1589. } else {
  1590. hs_descriptor_free(desc);
  1591. }
  1592. return ret;
  1593. err:
  1594. hs_descriptor_free(desc);
  1595. if (desc_out) {
  1596. *desc_out = NULL;
  1597. }
  1598. tor_assert(ret < 0);
  1599. return ret;
  1600. }
  1601. /* Table of encode function version specific. The function are indexed by the
  1602. * version number so v3 callback is at index 3 in the array. */
  1603. static int
  1604. (*encode_handlers[])(
  1605. const hs_descriptor_t *desc,
  1606. char **encoded_out) =
  1607. {
  1608. /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
  1609. desc_encode_v3,
  1610. };
  1611. /* Encode the given descriptor desc. On success, encoded_out points to a newly
  1612. * allocated NUL terminated string that contains the encoded descriptor as a
  1613. * string.
  1614. *
  1615. * Return 0 on success and encoded_out is a valid pointer. On error, -1 is
  1616. * returned and encoded_out is set to NULL. */
  1617. int
  1618. hs_desc_encode_descriptor(const hs_descriptor_t *desc, char **encoded_out)
  1619. {
  1620. int ret = -1;
  1621. tor_assert(desc);
  1622. tor_assert(encoded_out);
  1623. /* Make sure we support the version of the descriptor format. */
  1624. if (!hs_desc_is_supported_version(desc->plaintext_data.version)) {
  1625. goto err;
  1626. }
  1627. /* Extra precaution. Having no handler for the supported version should
  1628. * never happened else we forgot to add it but we bumped the version. */
  1629. tor_assert(ARRAY_LENGTH(encode_handlers) >= desc->plaintext_data.version);
  1630. tor_assert(encode_handlers[desc->plaintext_data.version]);
  1631. ret = encode_handlers[desc->plaintext_data.version](desc, encoded_out);
  1632. if (ret < 0) {
  1633. goto err;
  1634. }
  1635. /* Try to decode what we just encoded. Symmetry is nice! */
  1636. ret = hs_desc_decode_descriptor(*encoded_out, desc->subcredential, NULL);
  1637. if (BUG(ret < 0)) {
  1638. goto err;
  1639. }
  1640. return 0;
  1641. err:
  1642. *encoded_out = NULL;
  1643. return ret;
  1644. }
  1645. /* Free the descriptor plaintext data object. */
  1646. void
  1647. hs_desc_plaintext_data_free(hs_desc_plaintext_data_t *desc)
  1648. {
  1649. desc_plaintext_data_free_contents(desc);
  1650. tor_free(desc);
  1651. }
  1652. /* Free the descriptor encrypted data object. */
  1653. void
  1654. hs_desc_encrypted_data_free(hs_desc_encrypted_data_t *desc)
  1655. {
  1656. desc_encrypted_data_free_contents(desc);
  1657. tor_free(desc);
  1658. }
  1659. /* Free the given descriptor object. */
  1660. void
  1661. hs_descriptor_free(hs_descriptor_t *desc)
  1662. {
  1663. if (!desc) {
  1664. return;
  1665. }
  1666. desc_plaintext_data_free_contents(&desc->plaintext_data);
  1667. desc_encrypted_data_free_contents(&desc->encrypted_data);
  1668. tor_free(desc);
  1669. }
  1670. /* Return the size in bytes of the given plaintext data object. A sizeof() is
  1671. * not enough because the object contains pointers and the encrypted blob.
  1672. * This is particularly useful for our OOM subsystem that tracks the HSDir
  1673. * cache size for instance. */
  1674. size_t
  1675. hs_desc_plaintext_obj_size(const hs_desc_plaintext_data_t *data)
  1676. {
  1677. tor_assert(data);
  1678. return (sizeof(*data) + sizeof(*data->signing_key_cert) +
  1679. data->encrypted_blob_size);
  1680. }