hs_descriptor.c 63 KB

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