hs_descriptor.c 62 KB

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