hs_descriptor.c 78 KB

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