hs_descriptor.c 86 KB

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