hs_descriptor.c 63 KB

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