hs_descriptor.c 63 KB

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