hs_descriptor.c 90 KB

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