hs_descriptor.c 93 KB

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