hs_descriptor.c 62 KB

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