hs_descriptor.c 86 KB

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