hs_descriptor.c 73 KB

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