hs_descriptor.c 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046
  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 the secret data which is used to encrypt/decrypt the descriptor.
  824. *
  825. * SECRET_DATA = blinded-public-key
  826. * SECRET_DATA = blinded-public-key | descriptor_cookie
  827. *
  828. * The descriptor_cookie is optional but if it exists, it must be at least
  829. * HS_DESC_DESCRIPTOR_COOKIE_LEN bytes long.
  830. *
  831. * A newly allocated secret data is put in secret_data_out. Return the
  832. * length of the secret data. This function cannot fail. */
  833. static size_t
  834. build_secret_data(const ed25519_public_key_t *blinded_pubkey,
  835. const uint8_t *descriptor_cookie,
  836. uint8_t **secret_data_out)
  837. {
  838. size_t secret_data_len;
  839. uint8_t *secret_data;
  840. tor_assert(blinded_pubkey);
  841. tor_assert(secret_data_out);
  842. if (descriptor_cookie) {
  843. /* If the descriptor cookie is present, we need both the blinded
  844. * pubkey and the descriptor cookie as a secret data. */
  845. secret_data_len = ED25519_PUBKEY_LEN + HS_DESC_DESCRIPTOR_COOKIE_LEN;
  846. secret_data = tor_malloc(secret_data_len);
  847. memcpy(secret_data,
  848. blinded_pubkey->pubkey,
  849. ED25519_PUBKEY_LEN);
  850. memcpy(secret_data + ED25519_PUBKEY_LEN,
  851. descriptor_cookie,
  852. HS_DESC_DESCRIPTOR_COOKIE_LEN);
  853. } else {
  854. /* If the descriptor cookie is not present, we need only the blinded
  855. * pubkey as a secret data. */
  856. secret_data_len = ED25519_PUBKEY_LEN;
  857. secret_data = tor_malloc(secret_data_len);
  858. memcpy(secret_data,
  859. blinded_pubkey->pubkey,
  860. ED25519_PUBKEY_LEN);
  861. }
  862. *secret_data_out = secret_data;
  863. return secret_data_len;
  864. }
  865. /* Generate and encode the superencrypted portion of <b>desc</b>. This also
  866. * involves generating the encrypted portion of the descriptor, and performing
  867. * the superencryption. A newly allocated NUL-terminated string pointer
  868. * containing the encrypted encoded blob is put in encrypted_blob_out. Return 0
  869. * on success else a negative value. */
  870. static int
  871. encode_superencrypted_data(const hs_descriptor_t *desc,
  872. const uint8_t *descriptor_cookie,
  873. char **encrypted_blob_out)
  874. {
  875. int ret = -1;
  876. uint8_t *secret_data = NULL;
  877. size_t secret_data_len = 0;
  878. char *layer2_str = NULL;
  879. char *layer2_b64_ciphertext = NULL;
  880. char *layer1_str = NULL;
  881. char *layer1_b64_ciphertext = NULL;
  882. tor_assert(desc);
  883. tor_assert(encrypted_blob_out);
  884. /* Func logic: We first create the inner layer of the descriptor (layer2).
  885. * We then encrypt it and use it to create the middle layer of the descriptor
  886. * (layer1). Finally we superencrypt the middle layer and return it to our
  887. * caller. */
  888. /* Create inner descriptor layer */
  889. layer2_str = get_inner_encrypted_layer_plaintext(desc);
  890. if (!layer2_str) {
  891. goto err;
  892. }
  893. secret_data_len = build_secret_data(&desc->plaintext_data.blinded_pubkey,
  894. descriptor_cookie,
  895. &secret_data);
  896. /* Encrypt and b64 the inner layer */
  897. layer2_b64_ciphertext =
  898. encrypt_desc_data_and_base64(desc, secret_data, secret_data_len,
  899. layer2_str, 0);
  900. if (!layer2_b64_ciphertext) {
  901. goto err;
  902. }
  903. /* Now create middle descriptor layer given the inner layer */
  904. layer1_str = get_outer_encrypted_layer_plaintext(desc,layer2_b64_ciphertext);
  905. if (!layer1_str) {
  906. goto err;
  907. }
  908. /* Encrypt and base64 the middle layer */
  909. layer1_b64_ciphertext =
  910. encrypt_desc_data_and_base64(desc,
  911. desc->plaintext_data.blinded_pubkey.pubkey,
  912. ED25519_PUBKEY_LEN,
  913. layer1_str, 1);
  914. if (!layer1_b64_ciphertext) {
  915. goto err;
  916. }
  917. /* Success! */
  918. ret = 0;
  919. err:
  920. memwipe(secret_data, 0, secret_data_len);
  921. tor_free(secret_data);
  922. tor_free(layer1_str);
  923. tor_free(layer2_str);
  924. tor_free(layer2_b64_ciphertext);
  925. *encrypted_blob_out = layer1_b64_ciphertext;
  926. return ret;
  927. }
  928. /* Encode a v3 HS descriptor. Return 0 on success and set encoded_out to the
  929. * newly allocated string of the encoded descriptor. On error, -1 is returned
  930. * and encoded_out is untouched. */
  931. static int
  932. desc_encode_v3(const hs_descriptor_t *desc,
  933. const ed25519_keypair_t *signing_kp,
  934. const uint8_t *descriptor_cookie,
  935. char **encoded_out)
  936. {
  937. int ret = -1;
  938. char *encoded_str = NULL;
  939. size_t encoded_len;
  940. smartlist_t *lines = smartlist_new();
  941. tor_assert(desc);
  942. tor_assert(signing_kp);
  943. tor_assert(encoded_out);
  944. tor_assert(desc->plaintext_data.version == 3);
  945. if (BUG(desc->subcredential == NULL)) {
  946. goto err;
  947. }
  948. /* Build the non-encrypted values. */
  949. {
  950. char *encoded_cert;
  951. /* Encode certificate then create the first line of the descriptor. */
  952. if (desc->plaintext_data.signing_key_cert->cert_type
  953. != CERT_TYPE_SIGNING_HS_DESC) {
  954. log_err(LD_BUG, "HS descriptor signing key has an unexpected cert type "
  955. "(%d)", (int) desc->plaintext_data.signing_key_cert->cert_type);
  956. goto err;
  957. }
  958. if (tor_cert_encode_ed22519(desc->plaintext_data.signing_key_cert,
  959. &encoded_cert) < 0) {
  960. /* The function will print error logs. */
  961. goto err;
  962. }
  963. /* Create the hs descriptor line. */
  964. smartlist_add_asprintf(lines, "%s %" PRIu32, str_hs_desc,
  965. desc->plaintext_data.version);
  966. /* Add the descriptor lifetime line (in minutes). */
  967. smartlist_add_asprintf(lines, "%s %" PRIu32, str_lifetime,
  968. desc->plaintext_data.lifetime_sec / 60);
  969. /* Create the descriptor certificate line. */
  970. smartlist_add_asprintf(lines, "%s\n%s", str_desc_cert, encoded_cert);
  971. tor_free(encoded_cert);
  972. /* Create the revision counter line. */
  973. smartlist_add_asprintf(lines, "%s %" PRIu64, str_rev_counter,
  974. desc->plaintext_data.revision_counter);
  975. }
  976. /* Build the superencrypted data section. */
  977. {
  978. char *enc_b64_blob=NULL;
  979. if (encode_superencrypted_data(desc, descriptor_cookie,
  980. &enc_b64_blob) < 0) {
  981. goto err;
  982. }
  983. smartlist_add_asprintf(lines,
  984. "%s\n"
  985. "-----BEGIN MESSAGE-----\n"
  986. "%s"
  987. "-----END MESSAGE-----",
  988. str_superencrypted, enc_b64_blob);
  989. tor_free(enc_b64_blob);
  990. }
  991. /* Join all lines in one string so we can generate a signature and append
  992. * it to the descriptor. */
  993. encoded_str = smartlist_join_strings(lines, "\n", 1, &encoded_len);
  994. /* Sign all fields of the descriptor with our short term signing key. */
  995. {
  996. ed25519_signature_t sig;
  997. char ed_sig_b64[ED25519_SIG_BASE64_LEN + 1];
  998. if (ed25519_sign_prefixed(&sig,
  999. (const uint8_t *) encoded_str, encoded_len,
  1000. str_desc_sig_prefix, signing_kp) < 0) {
  1001. log_warn(LD_BUG, "Can't sign encoded HS descriptor!");
  1002. tor_free(encoded_str);
  1003. goto err;
  1004. }
  1005. if (ed25519_signature_to_base64(ed_sig_b64, &sig) < 0) {
  1006. log_warn(LD_BUG, "Can't base64 encode descriptor signature!");
  1007. tor_free(encoded_str);
  1008. goto err;
  1009. }
  1010. /* Create the signature line. */
  1011. smartlist_add_asprintf(lines, "%s %s", str_signature, ed_sig_b64);
  1012. }
  1013. /* Free previous string that we used so compute the signature. */
  1014. tor_free(encoded_str);
  1015. encoded_str = smartlist_join_strings(lines, "\n", 1, NULL);
  1016. *encoded_out = encoded_str;
  1017. if (strlen(encoded_str) >= hs_cache_get_max_descriptor_size()) {
  1018. log_warn(LD_GENERAL, "We just made an HS descriptor that's too big (%d)."
  1019. "Failing.", (int)strlen(encoded_str));
  1020. tor_free(encoded_str);
  1021. goto err;
  1022. }
  1023. /* XXX: Trigger a control port event. */
  1024. /* Success! */
  1025. ret = 0;
  1026. err:
  1027. SMARTLIST_FOREACH(lines, char *, l, tor_free(l));
  1028. smartlist_free(lines);
  1029. return ret;
  1030. }
  1031. /* === DECODING === */
  1032. /* Given the token tok for an auth client, decode it as
  1033. * hs_desc_authorized_client_t. tok->args MUST contain at least 3 elements
  1034. * Return 0 on success else -1 on failure. */
  1035. static int
  1036. decode_auth_client(const directory_token_t *tok,
  1037. hs_desc_authorized_client_t *client)
  1038. {
  1039. int ret = -1;
  1040. tor_assert(tok);
  1041. tor_assert(tok->n_args >= 3);
  1042. tor_assert(client);
  1043. if (base64_decode((char *) client->client_id, sizeof(client->client_id),
  1044. tok->args[0], strlen(tok->args[0])) !=
  1045. sizeof(client->client_id)) {
  1046. goto done;
  1047. }
  1048. if (base64_decode((char *) client->iv, sizeof(client->iv),
  1049. tok->args[1], strlen(tok->args[1])) !=
  1050. sizeof(client->iv)) {
  1051. goto done;
  1052. }
  1053. if (base64_decode((char *) client->encrypted_cookie,
  1054. sizeof(client->encrypted_cookie),
  1055. tok->args[2], strlen(tok->args[2])) !=
  1056. sizeof(client->encrypted_cookie)) {
  1057. goto done;
  1058. }
  1059. /* Success. */
  1060. ret = 0;
  1061. done:
  1062. return ret;
  1063. }
  1064. /* Given an encoded string of the link specifiers, return a newly allocated
  1065. * list of decoded link specifiers. Return NULL on error. */
  1066. STATIC smartlist_t *
  1067. decode_link_specifiers(const char *encoded)
  1068. {
  1069. int decoded_len;
  1070. size_t encoded_len, i;
  1071. uint8_t *decoded;
  1072. smartlist_t *results = NULL;
  1073. link_specifier_list_t *specs = NULL;
  1074. tor_assert(encoded);
  1075. encoded_len = strlen(encoded);
  1076. decoded = tor_malloc(encoded_len);
  1077. decoded_len = base64_decode((char *) decoded, encoded_len, encoded,
  1078. encoded_len);
  1079. if (decoded_len < 0) {
  1080. goto err;
  1081. }
  1082. if (link_specifier_list_parse(&specs, decoded,
  1083. (size_t) decoded_len) < decoded_len) {
  1084. goto err;
  1085. }
  1086. tor_assert(specs);
  1087. results = smartlist_new();
  1088. for (i = 0; i < link_specifier_list_getlen_spec(specs); i++) {
  1089. hs_desc_link_specifier_t *hs_spec;
  1090. link_specifier_t *ls = link_specifier_list_get_spec(specs, i);
  1091. tor_assert(ls);
  1092. hs_spec = tor_malloc_zero(sizeof(*hs_spec));
  1093. hs_spec->type = link_specifier_get_ls_type(ls);
  1094. switch (hs_spec->type) {
  1095. case LS_IPV4:
  1096. tor_addr_from_ipv4h(&hs_spec->u.ap.addr,
  1097. link_specifier_get_un_ipv4_addr(ls));
  1098. hs_spec->u.ap.port = link_specifier_get_un_ipv4_port(ls);
  1099. break;
  1100. case LS_IPV6:
  1101. tor_addr_from_ipv6_bytes(&hs_spec->u.ap.addr, (const char *)
  1102. link_specifier_getarray_un_ipv6_addr(ls));
  1103. hs_spec->u.ap.port = link_specifier_get_un_ipv6_port(ls);
  1104. break;
  1105. case LS_LEGACY_ID:
  1106. /* Both are known at compile time so let's make sure they are the same
  1107. * else we can copy memory out of bound. */
  1108. tor_assert(link_specifier_getlen_un_legacy_id(ls) ==
  1109. sizeof(hs_spec->u.legacy_id));
  1110. memcpy(hs_spec->u.legacy_id, link_specifier_getarray_un_legacy_id(ls),
  1111. sizeof(hs_spec->u.legacy_id));
  1112. break;
  1113. case LS_ED25519_ID:
  1114. /* Both are known at compile time so let's make sure they are the same
  1115. * else we can copy memory out of bound. */
  1116. tor_assert(link_specifier_getlen_un_ed25519_id(ls) ==
  1117. sizeof(hs_spec->u.ed25519_id));
  1118. memcpy(hs_spec->u.ed25519_id,
  1119. link_specifier_getconstarray_un_ed25519_id(ls),
  1120. sizeof(hs_spec->u.ed25519_id));
  1121. break;
  1122. default:
  1123. tor_free(hs_spec);
  1124. goto err;
  1125. }
  1126. smartlist_add(results, hs_spec);
  1127. }
  1128. goto done;
  1129. err:
  1130. if (results) {
  1131. SMARTLIST_FOREACH(results, hs_desc_link_specifier_t *, s, tor_free(s));
  1132. smartlist_free(results);
  1133. results = NULL;
  1134. }
  1135. done:
  1136. link_specifier_list_free(specs);
  1137. tor_free(decoded);
  1138. return results;
  1139. }
  1140. /* Given a list of authentication types, decode it and put it in the encrypted
  1141. * data section. Return 1 if we at least know one of the type or 0 if we know
  1142. * none of them. */
  1143. static int
  1144. decode_auth_type(hs_desc_encrypted_data_t *desc, const char *list)
  1145. {
  1146. int match = 0;
  1147. tor_assert(desc);
  1148. tor_assert(list);
  1149. desc->intro_auth_types = smartlist_new();
  1150. smartlist_split_string(desc->intro_auth_types, list, " ", 0, 0);
  1151. /* Validate the types that we at least know about one. */
  1152. SMARTLIST_FOREACH_BEGIN(desc->intro_auth_types, const char *, auth) {
  1153. for (int idx = 0; intro_auth_types[idx].identifier; idx++) {
  1154. if (!strncmp(auth, intro_auth_types[idx].identifier,
  1155. strlen(intro_auth_types[idx].identifier))) {
  1156. match = 1;
  1157. break;
  1158. }
  1159. }
  1160. } SMARTLIST_FOREACH_END(auth);
  1161. return match;
  1162. }
  1163. /* Parse a space-delimited list of integers representing CREATE2 formats into
  1164. * the bitfield in hs_desc_encrypted_data_t. Ignore unrecognized values. */
  1165. static void
  1166. decode_create2_list(hs_desc_encrypted_data_t *desc, const char *list)
  1167. {
  1168. smartlist_t *tokens;
  1169. tor_assert(desc);
  1170. tor_assert(list);
  1171. tokens = smartlist_new();
  1172. smartlist_split_string(tokens, list, " ", 0, 0);
  1173. SMARTLIST_FOREACH_BEGIN(tokens, char *, s) {
  1174. int ok;
  1175. unsigned long type = tor_parse_ulong(s, 10, 1, UINT16_MAX, &ok, NULL);
  1176. if (!ok) {
  1177. log_warn(LD_REND, "Unparseable value %s in create2 list", escaped(s));
  1178. continue;
  1179. }
  1180. switch (type) {
  1181. case ONION_HANDSHAKE_TYPE_NTOR:
  1182. desc->create2_ntor = 1;
  1183. break;
  1184. default:
  1185. /* We deliberately ignore unsupported handshake types */
  1186. continue;
  1187. }
  1188. } SMARTLIST_FOREACH_END(s);
  1189. SMARTLIST_FOREACH(tokens, char *, s, tor_free(s));
  1190. smartlist_free(tokens);
  1191. }
  1192. /* Given a certificate, validate the certificate for certain conditions which
  1193. * are if the given type matches the cert's one, if the signing key is
  1194. * included and if the that key was actually used to sign the certificate.
  1195. *
  1196. * Return 1 iff if all conditions pass or 0 if one of them fails. */
  1197. STATIC int
  1198. cert_is_valid(tor_cert_t *cert, uint8_t type, const char *log_obj_type)
  1199. {
  1200. tor_assert(log_obj_type);
  1201. if (cert == NULL) {
  1202. log_warn(LD_REND, "Certificate for %s couldn't be parsed.", log_obj_type);
  1203. goto err;
  1204. }
  1205. if (cert->cert_type != type) {
  1206. log_warn(LD_REND, "Invalid cert type %02x for %s.", cert->cert_type,
  1207. log_obj_type);
  1208. goto err;
  1209. }
  1210. /* All certificate must have its signing key included. */
  1211. if (!cert->signing_key_included) {
  1212. log_warn(LD_REND, "Signing key is NOT included for %s.", log_obj_type);
  1213. goto err;
  1214. }
  1215. /* The following will not only check if the signature matches but also the
  1216. * expiration date and overall validity. */
  1217. if (tor_cert_checksig(cert, &cert->signing_key, approx_time()) < 0) {
  1218. log_warn(LD_REND, "Invalid signature for %s: %s", log_obj_type,
  1219. tor_cert_describe_signature_status(cert));
  1220. goto err;
  1221. }
  1222. return 1;
  1223. err:
  1224. return 0;
  1225. }
  1226. /* Given some binary data, try to parse it to get a certificate object. If we
  1227. * have a valid cert, validate it using the given wanted type. On error, print
  1228. * a log using the err_msg has the certificate identifier adding semantic to
  1229. * the log and cert_out is set to NULL. On success, 0 is returned and cert_out
  1230. * points to a newly allocated certificate object. */
  1231. static int
  1232. cert_parse_and_validate(tor_cert_t **cert_out, const char *data,
  1233. size_t data_len, unsigned int cert_type_wanted,
  1234. const char *err_msg)
  1235. {
  1236. tor_cert_t *cert;
  1237. tor_assert(cert_out);
  1238. tor_assert(data);
  1239. tor_assert(err_msg);
  1240. /* Parse certificate. */
  1241. cert = tor_cert_parse((const uint8_t *) data, data_len);
  1242. if (!cert) {
  1243. log_warn(LD_REND, "Certificate for %s couldn't be parsed.", err_msg);
  1244. goto err;
  1245. }
  1246. /* Validate certificate. */
  1247. if (!cert_is_valid(cert, cert_type_wanted, err_msg)) {
  1248. goto err;
  1249. }
  1250. *cert_out = cert;
  1251. return 0;
  1252. err:
  1253. tor_cert_free(cert);
  1254. *cert_out = NULL;
  1255. return -1;
  1256. }
  1257. /* Return true iff the given length of the encrypted data of a descriptor
  1258. * passes validation. */
  1259. STATIC int
  1260. encrypted_data_length_is_valid(size_t len)
  1261. {
  1262. /* Make sure there is enough data for the salt and the mac. The equality is
  1263. there to ensure that there is at least one byte of encrypted data. */
  1264. if (len <= HS_DESC_ENCRYPTED_SALT_LEN + DIGEST256_LEN) {
  1265. log_warn(LD_REND, "Length of descriptor's encrypted data is too small. "
  1266. "Got %lu but minimum value is %d",
  1267. (unsigned long)len, HS_DESC_ENCRYPTED_SALT_LEN + DIGEST256_LEN);
  1268. goto err;
  1269. }
  1270. return 1;
  1271. err:
  1272. return 0;
  1273. }
  1274. /* Decrypt the descriptor cookie given the descriptor, the auth client,
  1275. * and the client secret key. On sucess, return 0 and a newly allocated
  1276. * descriptor cookie descriptor_cookie_out. On error or if the client id
  1277. * is invalid, return -1 and descriptor_cookie_out is set to
  1278. * NULL. */
  1279. static int
  1280. decrypt_descriptor_cookie(const hs_descriptor_t *desc,
  1281. const hs_desc_authorized_client_t *client,
  1282. const curve25519_secret_key_t *client_sk,
  1283. uint8_t **descriptor_cookie_out)
  1284. {
  1285. int ret = -1;
  1286. uint8_t secret_seed[CURVE25519_OUTPUT_LEN];
  1287. uint8_t keystream[HS_DESC_CLIENT_ID_LEN + HS_DESC_COOKIE_KEY_LEN];
  1288. uint8_t *cookie_key = NULL;
  1289. uint8_t *descriptor_cookie = NULL;
  1290. crypto_cipher_t *cipher = NULL;
  1291. crypto_xof_t *xof = NULL;
  1292. tor_assert(desc);
  1293. tor_assert(client);
  1294. tor_assert(client_sk);
  1295. tor_assert(!tor_mem_is_zero(
  1296. (char *) &desc->superencrypted_data.auth_ephemeral_pubkey,
  1297. sizeof(desc->superencrypted_data.auth_ephemeral_pubkey)));
  1298. tor_assert(!tor_mem_is_zero((char *) client_sk,
  1299. sizeof(*client_sk)));
  1300. /* Calculate x25519(client_x, hs_Y) */
  1301. curve25519_handshake(secret_seed, client_sk,
  1302. &desc->superencrypted_data.auth_ephemeral_pubkey);
  1303. /* Calculate KEYS = KDF(SECRET_SEED, 40) */
  1304. xof = crypto_xof_new();
  1305. crypto_xof_add_bytes(xof, secret_seed, sizeof(secret_seed));
  1306. crypto_xof_squeeze_bytes(xof, keystream, sizeof(keystream));
  1307. crypto_xof_free(xof);
  1308. /* If the client id of auth client is not the same as the calculcated
  1309. * client id, it means that this auth client is invaild according to the
  1310. * client secret key client_sk. */
  1311. if (tor_memneq(client->client_id, keystream, HS_DESC_CLIENT_ID_LEN)) {
  1312. goto done;
  1313. }
  1314. cookie_key = keystream + HS_DESC_CLIENT_ID_LEN;
  1315. /* This creates a cipher for AES. It can't fail. */
  1316. cipher = crypto_cipher_new_with_iv_and_bits(cookie_key, client->iv,
  1317. HS_DESC_COOKIE_KEY_BIT_SIZE);
  1318. descriptor_cookie = tor_malloc_zero(HS_DESC_DESCRIPTOR_COOKIE_LEN);
  1319. /* This can't fail. */
  1320. crypto_cipher_decrypt(cipher, (char *) descriptor_cookie,
  1321. (const char *) client->encrypted_cookie,
  1322. sizeof(client->encrypted_cookie));
  1323. /* Success. */
  1324. ret = 0;
  1325. done:
  1326. *descriptor_cookie_out = descriptor_cookie;
  1327. if (cipher) {
  1328. crypto_cipher_free(cipher);
  1329. }
  1330. memwipe(secret_seed, 0, sizeof(secret_seed));
  1331. memwipe(keystream, 0, sizeof(keystream));
  1332. return ret;
  1333. }
  1334. /** Decrypt an encrypted descriptor layer at <b>encrypted_blob</b> of size
  1335. * <b>encrypted_blob_size</b>. The descriptor cookie is optional. Use
  1336. * the descriptor object <b>desc</b> and <b>descriptor_cookie</b>
  1337. * to generate the right decryption keys; set <b>decrypted_out</b> to
  1338. * the plaintext. If <b>is_superencrypted_layer</b> is set, this is
  1339. * the outter encrypted layer of the descriptor.
  1340. *
  1341. * On any error case, including an empty output, return 0 and set
  1342. * *<b>decrypted_out</b> to NULL.
  1343. */
  1344. MOCK_IMPL(STATIC size_t,
  1345. decrypt_desc_layer,(const hs_descriptor_t *desc,
  1346. const uint8_t *encrypted_blob,
  1347. size_t encrypted_blob_size,
  1348. const uint8_t *descriptor_cookie,
  1349. int is_superencrypted_layer,
  1350. char **decrypted_out))
  1351. {
  1352. uint8_t *decrypted = NULL;
  1353. uint8_t secret_key[HS_DESC_ENCRYPTED_KEY_LEN], secret_iv[CIPHER_IV_LEN];
  1354. uint8_t *secret_data = NULL;
  1355. size_t secret_data_len = 0;
  1356. uint8_t mac_key[DIGEST256_LEN], our_mac[DIGEST256_LEN];
  1357. const uint8_t *salt, *encrypted, *desc_mac;
  1358. size_t encrypted_len, result_len = 0;
  1359. tor_assert(decrypted_out);
  1360. tor_assert(desc);
  1361. tor_assert(encrypted_blob);
  1362. /* Construction is as follow: SALT | ENCRYPTED_DATA | MAC .
  1363. * Make sure we have enough space for all these things. */
  1364. if (!encrypted_data_length_is_valid(encrypted_blob_size)) {
  1365. goto err;
  1366. }
  1367. /* Start of the blob thus the salt. */
  1368. salt = encrypted_blob;
  1369. /* Next is the encrypted data. */
  1370. encrypted = encrypted_blob + HS_DESC_ENCRYPTED_SALT_LEN;
  1371. encrypted_len = encrypted_blob_size -
  1372. (HS_DESC_ENCRYPTED_SALT_LEN + DIGEST256_LEN);
  1373. tor_assert(encrypted_len > 0); /* guaranteed by the check above */
  1374. /* And last comes the MAC. */
  1375. desc_mac = encrypted_blob + encrypted_blob_size - DIGEST256_LEN;
  1376. /* Build secret data to be used in the decryption. */
  1377. secret_data_len = build_secret_data(&desc->plaintext_data.blinded_pubkey,
  1378. descriptor_cookie,
  1379. &secret_data);
  1380. /* KDF construction resulting in a key from which the secret key, IV and MAC
  1381. * key are extracted which is what we need for the decryption. */
  1382. build_secret_key_iv_mac(desc, secret_data, secret_data_len,
  1383. salt, HS_DESC_ENCRYPTED_SALT_LEN,
  1384. secret_key, sizeof(secret_key),
  1385. secret_iv, sizeof(secret_iv),
  1386. mac_key, sizeof(mac_key),
  1387. is_superencrypted_layer);
  1388. /* Build MAC. */
  1389. build_mac(mac_key, sizeof(mac_key), salt, HS_DESC_ENCRYPTED_SALT_LEN,
  1390. encrypted, encrypted_len, our_mac, sizeof(our_mac));
  1391. memwipe(mac_key, 0, sizeof(mac_key));
  1392. /* Verify MAC; MAC is H(mac_key || salt || encrypted)
  1393. *
  1394. * This is a critical check that is making sure the computed MAC matches the
  1395. * one in the descriptor. */
  1396. if (!tor_memeq(our_mac, desc_mac, sizeof(our_mac))) {
  1397. log_warn(LD_REND, "Encrypted service descriptor MAC check failed");
  1398. goto err;
  1399. }
  1400. {
  1401. /* Decrypt. Here we are assured that the encrypted length is valid for
  1402. * decryption. */
  1403. crypto_cipher_t *cipher;
  1404. cipher = crypto_cipher_new_with_iv_and_bits(secret_key, secret_iv,
  1405. HS_DESC_ENCRYPTED_BIT_SIZE);
  1406. /* Extra byte for the NUL terminated byte. */
  1407. decrypted = tor_malloc_zero(encrypted_len + 1);
  1408. crypto_cipher_decrypt(cipher, (char *) decrypted,
  1409. (const char *) encrypted, encrypted_len);
  1410. crypto_cipher_free(cipher);
  1411. }
  1412. {
  1413. /* Adjust length to remove NUL padding bytes */
  1414. uint8_t *end = memchr(decrypted, 0, encrypted_len);
  1415. result_len = encrypted_len;
  1416. if (end) {
  1417. result_len = end - decrypted;
  1418. }
  1419. }
  1420. if (result_len == 0) {
  1421. /* Treat this as an error, so that somebody will free the output. */
  1422. goto err;
  1423. }
  1424. /* Make sure to NUL terminate the string. */
  1425. decrypted[encrypted_len] = '\0';
  1426. *decrypted_out = (char *) decrypted;
  1427. goto done;
  1428. err:
  1429. if (decrypted) {
  1430. tor_free(decrypted);
  1431. }
  1432. *decrypted_out = NULL;
  1433. result_len = 0;
  1434. done:
  1435. memwipe(secret_data, 0, secret_data_len);
  1436. memwipe(secret_key, 0, sizeof(secret_key));
  1437. memwipe(secret_iv, 0, sizeof(secret_iv));
  1438. tor_free(secret_data);
  1439. return result_len;
  1440. }
  1441. /* Decrypt the superencrypted section of the descriptor using the given
  1442. * descriptor object <b>desc</b>. A newly allocated NUL terminated string is
  1443. * put in decrypted_out which contains the superencrypted layer of the
  1444. * descriptor. Return the length of decrypted_out on success else 0 is
  1445. * returned and decrypted_out is set to NULL. */
  1446. static size_t
  1447. desc_decrypt_superencrypted(const hs_descriptor_t *desc, char **decrypted_out)
  1448. {
  1449. size_t superencrypted_len = 0;
  1450. char *superencrypted_plaintext = NULL;
  1451. tor_assert(desc);
  1452. tor_assert(decrypted_out);
  1453. superencrypted_len = decrypt_desc_layer(desc,
  1454. desc->plaintext_data.superencrypted_blob,
  1455. desc->plaintext_data.superencrypted_blob_size,
  1456. NULL, 1, &superencrypted_plaintext);
  1457. if (!superencrypted_len) {
  1458. log_warn(LD_REND, "Decrypting superencrypted desc failed.");
  1459. goto done;
  1460. }
  1461. tor_assert(superencrypted_plaintext);
  1462. done:
  1463. /* In case of error, superencrypted_plaintext is already NULL, so the
  1464. * following line makes sense. */
  1465. *decrypted_out = superencrypted_plaintext;
  1466. /* This makes sense too, because, in case of error, this is zero. */
  1467. return superencrypted_len;
  1468. }
  1469. /* Decrypt the encrypted section of the descriptor using the given descriptor
  1470. * object <b>desc</b>. A newly allocated NUL terminated string is put in
  1471. * decrypted_out which contains the encrypted layer of the descriptor.
  1472. * Return the length of decrypted_out on success else 0 is returned and
  1473. * decrypted_out is set to NULL. */
  1474. static size_t
  1475. desc_decrypt_encrypted(const hs_descriptor_t *desc,
  1476. const curve25519_secret_key_t *client_sk,
  1477. char **decrypted_out)
  1478. {
  1479. size_t encrypted_len = 0;
  1480. char *encrypted_plaintext = NULL;
  1481. uint8_t *descriptor_cookie = NULL;
  1482. tor_assert(desc);
  1483. tor_assert(desc->superencrypted_data.clients);
  1484. tor_assert(decrypted_out);
  1485. /* If the client secret key is provided, try to find a valid descriptor
  1486. * cookie. Otherwise, leave it NULL. */
  1487. if (client_sk) {
  1488. SMARTLIST_FOREACH_BEGIN(desc->superencrypted_data.clients,
  1489. hs_desc_authorized_client_t *, client) {
  1490. /* If we can decrypt the descriptor cookie successfully, we will use that
  1491. * descriptor cookie and break from the loop. */
  1492. if (!decrypt_descriptor_cookie(desc, client, client_sk,
  1493. &descriptor_cookie)) {
  1494. break;
  1495. }
  1496. } SMARTLIST_FOREACH_END(client);
  1497. }
  1498. encrypted_len = decrypt_desc_layer(desc,
  1499. desc->superencrypted_data.encrypted_blob,
  1500. desc->superencrypted_data.encrypted_blob_size,
  1501. descriptor_cookie, 0, &encrypted_plaintext);
  1502. if (!encrypted_len) {
  1503. log_warn(LD_REND, "Decrypting encrypted desc failed.");
  1504. goto err;
  1505. }
  1506. tor_assert(encrypted_plaintext);
  1507. err:
  1508. /* In case of error, encrypted_plaintext is already NULL, so the
  1509. * following line makes sense. */
  1510. *decrypted_out = encrypted_plaintext;
  1511. if (descriptor_cookie) {
  1512. memwipe(descriptor_cookie, 0, HS_DESC_DESCRIPTOR_COOKIE_LEN);
  1513. }
  1514. tor_free(descriptor_cookie);
  1515. /* This makes sense too, because, in case of error, this is zero. */
  1516. return encrypted_len;
  1517. }
  1518. /* Given the token tok for an intro point legacy key, the list of tokens, the
  1519. * introduction point ip being decoded and the descriptor desc from which it
  1520. * comes from, decode the legacy key and set the intro point object. Return 0
  1521. * on success else -1 on failure. */
  1522. static int
  1523. decode_intro_legacy_key(const directory_token_t *tok,
  1524. smartlist_t *tokens,
  1525. hs_desc_intro_point_t *ip,
  1526. const hs_descriptor_t *desc)
  1527. {
  1528. tor_assert(tok);
  1529. tor_assert(tokens);
  1530. tor_assert(ip);
  1531. tor_assert(desc);
  1532. if (!crypto_pk_public_exponent_ok(tok->key)) {
  1533. log_warn(LD_REND, "Introduction point legacy key is invalid");
  1534. goto err;
  1535. }
  1536. ip->legacy.key = crypto_pk_dup_key(tok->key);
  1537. /* Extract the legacy cross certification cert which MUST be present if we
  1538. * have a legacy key. */
  1539. tok = find_opt_by_keyword(tokens, R3_INTRO_LEGACY_KEY_CERT);
  1540. if (!tok) {
  1541. log_warn(LD_REND, "Introduction point legacy key cert is missing");
  1542. goto err;
  1543. }
  1544. tor_assert(tok->object_body);
  1545. if (strcmp(tok->object_type, "CROSSCERT")) {
  1546. /* Info level because this might be an unknown field that we should
  1547. * ignore. */
  1548. log_info(LD_REND, "Introduction point legacy encryption key "
  1549. "cross-certification has an unknown format.");
  1550. goto err;
  1551. }
  1552. /* Keep a copy of the certificate. */
  1553. ip->legacy.cert.encoded = tor_memdup(tok->object_body, tok->object_size);
  1554. ip->legacy.cert.len = tok->object_size;
  1555. /* The check on the expiration date is for the entire lifetime of a
  1556. * certificate which is 24 hours. However, a descriptor has a maximum
  1557. * lifetime of 12 hours meaning we have a 12h difference between the two
  1558. * which ultimately accommodate the clock skewed client. */
  1559. if (rsa_ed25519_crosscert_check(ip->legacy.cert.encoded,
  1560. ip->legacy.cert.len, ip->legacy.key,
  1561. &desc->plaintext_data.signing_pubkey,
  1562. approx_time() - HS_DESC_CERT_LIFETIME)) {
  1563. log_warn(LD_REND, "Unable to check cross-certification on the "
  1564. "introduction point legacy encryption key.");
  1565. ip->cross_certified = 0;
  1566. goto err;
  1567. }
  1568. /* Success. */
  1569. return 0;
  1570. err:
  1571. return -1;
  1572. }
  1573. /* Dig into the descriptor <b>tokens</b> to find the onion key we should use
  1574. * for this intro point, and set it into <b>onion_key_out</b>. Return 0 if it
  1575. * was found and well-formed, otherwise return -1 in case of errors. */
  1576. static int
  1577. set_intro_point_onion_key(curve25519_public_key_t *onion_key_out,
  1578. const smartlist_t *tokens)
  1579. {
  1580. int retval = -1;
  1581. smartlist_t *onion_keys = NULL;
  1582. tor_assert(onion_key_out);
  1583. onion_keys = find_all_by_keyword(tokens, R3_INTRO_ONION_KEY);
  1584. if (!onion_keys) {
  1585. log_warn(LD_REND, "Descriptor did not contain intro onion keys");
  1586. goto err;
  1587. }
  1588. SMARTLIST_FOREACH_BEGIN(onion_keys, directory_token_t *, tok) {
  1589. /* This field is using GE(2) so for possible forward compatibility, we
  1590. * accept more fields but must be at least 2. */
  1591. tor_assert(tok->n_args >= 2);
  1592. /* Try to find an ntor key, it's the only recognized type right now */
  1593. if (!strcmp(tok->args[0], "ntor")) {
  1594. if (curve25519_public_from_base64(onion_key_out, tok->args[1]) < 0) {
  1595. log_warn(LD_REND, "Introduction point ntor onion-key is invalid");
  1596. goto err;
  1597. }
  1598. /* Got the onion key! Set the appropriate retval */
  1599. retval = 0;
  1600. }
  1601. } SMARTLIST_FOREACH_END(tok);
  1602. /* Log an error if we didn't find it :( */
  1603. if (retval < 0) {
  1604. log_warn(LD_REND, "Descriptor did not contain ntor onion keys");
  1605. }
  1606. err:
  1607. smartlist_free(onion_keys);
  1608. return retval;
  1609. }
  1610. /* Given the start of a section and the end of it, decode a single
  1611. * introduction point from that section. Return a newly allocated introduction
  1612. * point object containing the decoded data. Return NULL if the section can't
  1613. * be decoded. */
  1614. STATIC hs_desc_intro_point_t *
  1615. decode_introduction_point(const hs_descriptor_t *desc, const char *start)
  1616. {
  1617. hs_desc_intro_point_t *ip = NULL;
  1618. memarea_t *area = NULL;
  1619. smartlist_t *tokens = NULL;
  1620. const directory_token_t *tok;
  1621. tor_assert(desc);
  1622. tor_assert(start);
  1623. area = memarea_new();
  1624. tokens = smartlist_new();
  1625. if (tokenize_string(area, start, start + strlen(start),
  1626. tokens, hs_desc_intro_point_v3_token_table, 0) < 0) {
  1627. log_warn(LD_REND, "Introduction point is not parseable");
  1628. goto err;
  1629. }
  1630. /* Ok we seem to have a well formed section containing enough tokens to
  1631. * parse. Allocate our IP object and try to populate it. */
  1632. ip = hs_desc_intro_point_new();
  1633. /* "introduction-point" SP link-specifiers NL */
  1634. tok = find_by_keyword(tokens, R3_INTRODUCTION_POINT);
  1635. tor_assert(tok->n_args == 1);
  1636. /* Our constructor creates this list by default so free it. */
  1637. smartlist_free(ip->link_specifiers);
  1638. ip->link_specifiers = decode_link_specifiers(tok->args[0]);
  1639. if (!ip->link_specifiers) {
  1640. log_warn(LD_REND, "Introduction point has invalid link specifiers");
  1641. goto err;
  1642. }
  1643. /* "onion-key" SP ntor SP key NL */
  1644. if (set_intro_point_onion_key(&ip->onion_key, tokens) < 0) {
  1645. goto err;
  1646. }
  1647. /* "auth-key" NL certificate NL */
  1648. tok = find_by_keyword(tokens, R3_INTRO_AUTH_KEY);
  1649. tor_assert(tok->object_body);
  1650. if (strcmp(tok->object_type, "ED25519 CERT")) {
  1651. log_warn(LD_REND, "Unexpected object type for introduction auth key");
  1652. goto err;
  1653. }
  1654. /* Parse cert and do some validation. */
  1655. if (cert_parse_and_validate(&ip->auth_key_cert, tok->object_body,
  1656. tok->object_size, CERT_TYPE_AUTH_HS_IP_KEY,
  1657. "introduction point auth-key") < 0) {
  1658. goto err;
  1659. }
  1660. /* Validate authentication certificate with descriptor signing key. */
  1661. if (tor_cert_checksig(ip->auth_key_cert,
  1662. &desc->plaintext_data.signing_pubkey, 0) < 0) {
  1663. log_warn(LD_REND, "Invalid authentication key signature: %s",
  1664. tor_cert_describe_signature_status(ip->auth_key_cert));
  1665. goto err;
  1666. }
  1667. /* Exactly one "enc-key" SP "ntor" SP key NL */
  1668. tok = find_by_keyword(tokens, R3_INTRO_ENC_KEY);
  1669. if (!strcmp(tok->args[0], "ntor")) {
  1670. /* This field is using GE(2) so for possible forward compatibility, we
  1671. * accept more fields but must be at least 2. */
  1672. tor_assert(tok->n_args >= 2);
  1673. if (curve25519_public_from_base64(&ip->enc_key, tok->args[1]) < 0) {
  1674. log_warn(LD_REND, "Introduction point ntor enc-key is invalid");
  1675. goto err;
  1676. }
  1677. } else {
  1678. /* Unknown key type so we can't use that introduction point. */
  1679. log_warn(LD_REND, "Introduction point encryption key is unrecognized.");
  1680. goto err;
  1681. }
  1682. /* Exactly once "enc-key-cert" NL certificate NL */
  1683. tok = find_by_keyword(tokens, R3_INTRO_ENC_KEY_CERT);
  1684. tor_assert(tok->object_body);
  1685. /* Do the cross certification. */
  1686. if (strcmp(tok->object_type, "ED25519 CERT")) {
  1687. log_warn(LD_REND, "Introduction point ntor encryption key "
  1688. "cross-certification has an unknown format.");
  1689. goto err;
  1690. }
  1691. if (cert_parse_and_validate(&ip->enc_key_cert, tok->object_body,
  1692. tok->object_size, CERT_TYPE_CROSS_HS_IP_KEYS,
  1693. "introduction point enc-key-cert") < 0) {
  1694. goto err;
  1695. }
  1696. if (tor_cert_checksig(ip->enc_key_cert,
  1697. &desc->plaintext_data.signing_pubkey, 0) < 0) {
  1698. log_warn(LD_REND, "Invalid encryption key signature: %s",
  1699. tor_cert_describe_signature_status(ip->enc_key_cert));
  1700. goto err;
  1701. }
  1702. /* It is successfully cross certified. Flag the object. */
  1703. ip->cross_certified = 1;
  1704. /* Do we have a "legacy-key" SP key NL ?*/
  1705. tok = find_opt_by_keyword(tokens, R3_INTRO_LEGACY_KEY);
  1706. if (tok) {
  1707. if (decode_intro_legacy_key(tok, tokens, ip, desc) < 0) {
  1708. goto err;
  1709. }
  1710. }
  1711. /* Introduction point has been parsed successfully. */
  1712. goto done;
  1713. err:
  1714. hs_desc_intro_point_free(ip);
  1715. ip = NULL;
  1716. done:
  1717. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1718. smartlist_free(tokens);
  1719. if (area) {
  1720. memarea_drop_all(area);
  1721. }
  1722. return ip;
  1723. }
  1724. /* Given a descriptor string at <b>data</b>, decode all possible introduction
  1725. * points that we can find. Add the introduction point object to desc_enc as we
  1726. * find them. This function can't fail and it is possible that zero
  1727. * introduction points can be decoded. */
  1728. static void
  1729. decode_intro_points(const hs_descriptor_t *desc,
  1730. hs_desc_encrypted_data_t *desc_enc,
  1731. const char *data)
  1732. {
  1733. smartlist_t *chunked_desc = smartlist_new();
  1734. smartlist_t *intro_points = smartlist_new();
  1735. tor_assert(desc);
  1736. tor_assert(desc_enc);
  1737. tor_assert(data);
  1738. tor_assert(desc_enc->intro_points);
  1739. /* Take the desc string, and extract the intro point substrings out of it */
  1740. {
  1741. /* Split the descriptor string using the intro point header as delimiter */
  1742. smartlist_split_string(chunked_desc, data, str_intro_point_start, 0, 0);
  1743. /* Check if there are actually any intro points included. The first chunk
  1744. * should be other descriptor fields (e.g. create2-formats), so it's not an
  1745. * intro point. */
  1746. if (smartlist_len(chunked_desc) < 2) {
  1747. goto done;
  1748. }
  1749. }
  1750. /* Take the intro point substrings, and prepare them for parsing */
  1751. {
  1752. int i = 0;
  1753. /* Prepend the introduction-point header to all the chunks, since
  1754. smartlist_split_string() devoured it. */
  1755. SMARTLIST_FOREACH_BEGIN(chunked_desc, char *, chunk) {
  1756. /* Ignore first chunk. It's other descriptor fields. */
  1757. if (i++ == 0) {
  1758. continue;
  1759. }
  1760. smartlist_add_asprintf(intro_points, "%s %s", str_intro_point, chunk);
  1761. } SMARTLIST_FOREACH_END(chunk);
  1762. }
  1763. /* Parse the intro points! */
  1764. SMARTLIST_FOREACH_BEGIN(intro_points, const char *, intro_point) {
  1765. hs_desc_intro_point_t *ip = decode_introduction_point(desc, intro_point);
  1766. if (!ip) {
  1767. /* Malformed introduction point section. We'll ignore this introduction
  1768. * point and continue parsing. New or unknown fields are possible for
  1769. * forward compatibility. */
  1770. continue;
  1771. }
  1772. smartlist_add(desc_enc->intro_points, ip);
  1773. } SMARTLIST_FOREACH_END(intro_point);
  1774. done:
  1775. SMARTLIST_FOREACH(chunked_desc, char *, a, tor_free(a));
  1776. smartlist_free(chunked_desc);
  1777. SMARTLIST_FOREACH(intro_points, char *, a, tor_free(a));
  1778. smartlist_free(intro_points);
  1779. }
  1780. /* Return 1 iff the given base64 encoded signature in b64_sig from the encoded
  1781. * descriptor in encoded_desc validates the descriptor content. */
  1782. STATIC int
  1783. desc_sig_is_valid(const char *b64_sig,
  1784. const ed25519_public_key_t *signing_pubkey,
  1785. const char *encoded_desc, size_t encoded_len)
  1786. {
  1787. int ret = 0;
  1788. ed25519_signature_t sig;
  1789. const char *sig_start;
  1790. tor_assert(b64_sig);
  1791. tor_assert(signing_pubkey);
  1792. tor_assert(encoded_desc);
  1793. /* Verifying nothing won't end well :). */
  1794. tor_assert(encoded_len > 0);
  1795. /* Signature length check. */
  1796. if (strlen(b64_sig) != ED25519_SIG_BASE64_LEN) {
  1797. log_warn(LD_REND, "Service descriptor has an invalid signature length."
  1798. "Exptected %d but got %lu",
  1799. ED25519_SIG_BASE64_LEN, (unsigned long) strlen(b64_sig));
  1800. goto err;
  1801. }
  1802. /* First, convert base64 blob to an ed25519 signature. */
  1803. if (ed25519_signature_from_base64(&sig, b64_sig) != 0) {
  1804. log_warn(LD_REND, "Service descriptor does not contain a valid "
  1805. "signature");
  1806. goto err;
  1807. }
  1808. /* Find the start of signature. */
  1809. sig_start = tor_memstr(encoded_desc, encoded_len, "\n" str_signature " ");
  1810. /* Getting here means the token parsing worked for the signature so if we
  1811. * can't find the start of the signature, we have a code flow issue. */
  1812. if (!sig_start) {
  1813. log_warn(LD_GENERAL, "Malformed signature line. Rejecting.");
  1814. goto err;
  1815. }
  1816. /* Skip newline, it has to go in the signature check. */
  1817. sig_start++;
  1818. /* Validate signature with the full body of the descriptor. */
  1819. if (ed25519_checksig_prefixed(&sig,
  1820. (const uint8_t *) encoded_desc,
  1821. sig_start - encoded_desc,
  1822. str_desc_sig_prefix,
  1823. signing_pubkey) != 0) {
  1824. log_warn(LD_REND, "Invalid signature on service descriptor");
  1825. goto err;
  1826. }
  1827. /* Valid signature! All is good. */
  1828. ret = 1;
  1829. err:
  1830. return ret;
  1831. }
  1832. /* Decode descriptor plaintext data for version 3. Given a list of tokens, an
  1833. * allocated plaintext object that will be populated and the encoded
  1834. * descriptor with its length. The last one is needed for signature
  1835. * verification. Unknown tokens are simply ignored so this won't error on
  1836. * unknowns but requires that all v3 token be present and valid.
  1837. *
  1838. * Return 0 on success else a negative value. */
  1839. static int
  1840. desc_decode_plaintext_v3(smartlist_t *tokens,
  1841. hs_desc_plaintext_data_t *desc,
  1842. const char *encoded_desc, size_t encoded_len)
  1843. {
  1844. int ok;
  1845. directory_token_t *tok;
  1846. tor_assert(tokens);
  1847. tor_assert(desc);
  1848. /* Version higher could still use this function to decode most of the
  1849. * descriptor and then they decode the extra part. */
  1850. tor_assert(desc->version >= 3);
  1851. /* Descriptor lifetime parsing. */
  1852. tok = find_by_keyword(tokens, R3_DESC_LIFETIME);
  1853. tor_assert(tok->n_args == 1);
  1854. desc->lifetime_sec = (uint32_t) tor_parse_ulong(tok->args[0], 10, 0,
  1855. UINT32_MAX, &ok, NULL);
  1856. if (!ok) {
  1857. log_warn(LD_REND, "Service descriptor lifetime value is invalid");
  1858. goto err;
  1859. }
  1860. /* Put it from minute to second. */
  1861. desc->lifetime_sec *= 60;
  1862. if (desc->lifetime_sec > HS_DESC_MAX_LIFETIME) {
  1863. log_warn(LD_REND, "Service descriptor lifetime is too big. "
  1864. "Got %" PRIu32 " but max is %d",
  1865. desc->lifetime_sec, HS_DESC_MAX_LIFETIME);
  1866. goto err;
  1867. }
  1868. /* Descriptor signing certificate. */
  1869. tok = find_by_keyword(tokens, R3_DESC_SIGNING_CERT);
  1870. tor_assert(tok->object_body);
  1871. /* Expecting a prop220 cert with the signing key extension, which contains
  1872. * the blinded public key. */
  1873. if (strcmp(tok->object_type, "ED25519 CERT") != 0) {
  1874. log_warn(LD_REND, "Service descriptor signing cert wrong type (%s)",
  1875. escaped(tok->object_type));
  1876. goto err;
  1877. }
  1878. if (cert_parse_and_validate(&desc->signing_key_cert, tok->object_body,
  1879. tok->object_size, CERT_TYPE_SIGNING_HS_DESC,
  1880. "service descriptor signing key") < 0) {
  1881. goto err;
  1882. }
  1883. /* Copy the public keys into signing_pubkey and blinded_pubkey */
  1884. memcpy(&desc->signing_pubkey, &desc->signing_key_cert->signed_key,
  1885. sizeof(ed25519_public_key_t));
  1886. memcpy(&desc->blinded_pubkey, &desc->signing_key_cert->signing_key,
  1887. sizeof(ed25519_public_key_t));
  1888. /* Extract revision counter value. */
  1889. tok = find_by_keyword(tokens, R3_REVISION_COUNTER);
  1890. tor_assert(tok->n_args == 1);
  1891. desc->revision_counter = tor_parse_uint64(tok->args[0], 10, 0,
  1892. UINT64_MAX, &ok, NULL);
  1893. if (!ok) {
  1894. log_warn(LD_REND, "Service descriptor revision-counter is invalid");
  1895. goto err;
  1896. }
  1897. /* Extract the superencrypted data section. */
  1898. tok = find_by_keyword(tokens, R3_SUPERENCRYPTED);
  1899. tor_assert(tok->object_body);
  1900. if (strcmp(tok->object_type, "MESSAGE") != 0) {
  1901. log_warn(LD_REND, "Desc superencrypted data section is invalid");
  1902. goto err;
  1903. }
  1904. /* Make sure the length of the superencrypted blob is valid. */
  1905. if (!encrypted_data_length_is_valid(tok->object_size)) {
  1906. goto err;
  1907. }
  1908. /* Copy the superencrypted blob to the descriptor object so we can handle it
  1909. * latter if needed. */
  1910. desc->superencrypted_blob = tor_memdup(tok->object_body, tok->object_size);
  1911. desc->superencrypted_blob_size = tok->object_size;
  1912. /* Extract signature and verify it. */
  1913. tok = find_by_keyword(tokens, R3_SIGNATURE);
  1914. tor_assert(tok->n_args == 1);
  1915. /* First arg here is the actual encoded signature. */
  1916. if (!desc_sig_is_valid(tok->args[0], &desc->signing_pubkey,
  1917. encoded_desc, encoded_len)) {
  1918. goto err;
  1919. }
  1920. return 0;
  1921. err:
  1922. return -1;
  1923. }
  1924. /* Decode the version 3 superencrypted section of the given descriptor desc.
  1925. * The desc_superencrypted_out will be populated with the decoded data.
  1926. * Return 0 on success else -1. */
  1927. static int
  1928. desc_decode_superencrypted_v3(const hs_descriptor_t *desc,
  1929. hs_desc_superencrypted_data_t *
  1930. desc_superencrypted_out)
  1931. {
  1932. int ret = -1;
  1933. char *message = NULL;
  1934. size_t message_len;
  1935. memarea_t *area = NULL;
  1936. directory_token_t *tok;
  1937. smartlist_t *tokens = NULL;
  1938. /* Rename the parameter because it is too long. */
  1939. hs_desc_superencrypted_data_t *superencrypted = desc_superencrypted_out;
  1940. tor_assert(desc);
  1941. tor_assert(desc_superencrypted_out);
  1942. /* Decrypt the superencrypted data that is located in the plaintext section
  1943. * in the descriptor as a blob of bytes. */
  1944. message_len = desc_decrypt_superencrypted(desc, &message);
  1945. if (!message_len) {
  1946. log_warn(LD_REND, "Service descriptor decryption failed.");
  1947. goto err;
  1948. }
  1949. tor_assert(message);
  1950. area = memarea_new();
  1951. tokens = smartlist_new();
  1952. if (tokenize_string(area, message, message + message_len,
  1953. tokens, hs_desc_superencrypted_v3_token_table, 0) < 0) {
  1954. log_warn(LD_REND, "Superencrypted service descriptor is not parseable.");
  1955. goto err;
  1956. }
  1957. /* Verify desc auth type */
  1958. tok = find_by_keyword(tokens, R3_DESC_AUTH_TYPE);
  1959. tor_assert(tok->n_args >= 1);
  1960. if (strcmp(tok->args[0], "x25519")) {
  1961. log_warn(LD_DIR, "Unrecognized desc auth type");
  1962. goto err;
  1963. }
  1964. /* Extract desc auth ephemeral key */
  1965. tok = find_by_keyword(tokens, R3_DESC_AUTH_KEY);
  1966. tor_assert(tok->n_args >= 1);
  1967. if (curve25519_public_from_base64(&superencrypted->auth_ephemeral_pubkey,
  1968. tok->args[0]) < 0) {
  1969. log_warn(LD_DIR, "Bogus desc auth ephemeral key in HS desc");
  1970. goto err;
  1971. }
  1972. /* Extract desc auth client items */
  1973. if (!superencrypted->clients) {
  1974. superencrypted->clients = smartlist_new();
  1975. }
  1976. SMARTLIST_FOREACH_BEGIN(tokens, const directory_token_t *, token) {
  1977. if (token->tp == R3_DESC_AUTH_CLIENT) {
  1978. tor_assert(token->n_args >= 3);
  1979. hs_desc_authorized_client_t *client =
  1980. tor_malloc_zero(sizeof(hs_desc_authorized_client_t));
  1981. if (decode_auth_client(token, client) < 0) {
  1982. log_warn(LD_REND, "Descriptor client authorization section can't "
  1983. "be decoded.");
  1984. tor_free(client);
  1985. goto err;
  1986. }
  1987. smartlist_add(superencrypted->clients, client);
  1988. }
  1989. } SMARTLIST_FOREACH_END(token);
  1990. /* Extract the encrypted data section. */
  1991. tok = find_by_keyword(tokens, R3_ENCRYPTED);
  1992. tor_assert(tok->object_body);
  1993. if (strcmp(tok->object_type, "MESSAGE") != 0) {
  1994. log_warn(LD_REND, "Desc encrypted data section is invalid");
  1995. goto err;
  1996. }
  1997. /* Make sure the length of the encrypted blob is valid. */
  1998. if (!encrypted_data_length_is_valid(tok->object_size)) {
  1999. goto err;
  2000. }
  2001. /* Copy the encrypted blob to the descriptor object so we can handle it
  2002. * latter if needed. */
  2003. tor_assert(tok->object_size <= INT_MAX);
  2004. superencrypted->encrypted_blob = tor_memdup(tok->object_body,
  2005. tok->object_size);
  2006. superencrypted->encrypted_blob_size = tok->object_size;
  2007. ret = 0;
  2008. goto done;
  2009. err:
  2010. tor_assert(ret < 0);
  2011. desc_superencrypted_data_free_contents(desc_superencrypted_out);
  2012. done:
  2013. if (tokens) {
  2014. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2015. smartlist_free(tokens);
  2016. }
  2017. if (area) {
  2018. memarea_drop_all(area);
  2019. }
  2020. if (message) {
  2021. tor_free(message);
  2022. }
  2023. return ret;
  2024. }
  2025. /* Decode the version 3 encrypted section of the given descriptor desc. The
  2026. * desc_encrypted_out will be populated with the decoded data. Return 0 on
  2027. * success else -1. */
  2028. static int
  2029. desc_decode_encrypted_v3(const hs_descriptor_t *desc,
  2030. const curve25519_secret_key_t *client_sk,
  2031. hs_desc_encrypted_data_t *desc_encrypted_out)
  2032. {
  2033. int ret = -1;
  2034. char *message = NULL;
  2035. size_t message_len;
  2036. memarea_t *area = NULL;
  2037. directory_token_t *tok;
  2038. smartlist_t *tokens = NULL;
  2039. tor_assert(desc);
  2040. tor_assert(desc_encrypted_out);
  2041. /* Decrypt the encrypted data that is located in the superencrypted section
  2042. * in the descriptor as a blob of bytes. */
  2043. message_len = desc_decrypt_encrypted(desc, client_sk, &message);
  2044. if (!message_len) {
  2045. log_warn(LD_REND, "Service descriptor decryption failed.");
  2046. goto err;
  2047. }
  2048. tor_assert(message);
  2049. area = memarea_new();
  2050. tokens = smartlist_new();
  2051. if (tokenize_string(area, message, message + message_len,
  2052. tokens, hs_desc_encrypted_v3_token_table, 0) < 0) {
  2053. log_warn(LD_REND, "Encrypted service descriptor is not parseable.");
  2054. goto err;
  2055. }
  2056. /* CREATE2 supported cell format. It's mandatory. */
  2057. tok = find_by_keyword(tokens, R3_CREATE2_FORMATS);
  2058. tor_assert(tok);
  2059. decode_create2_list(desc_encrypted_out, tok->args[0]);
  2060. /* Must support ntor according to the specification */
  2061. if (!desc_encrypted_out->create2_ntor) {
  2062. log_warn(LD_REND, "Service create2-formats does not include ntor.");
  2063. goto err;
  2064. }
  2065. /* Authentication type. It's optional but only once. */
  2066. tok = find_opt_by_keyword(tokens, R3_INTRO_AUTH_REQUIRED);
  2067. if (tok) {
  2068. if (!decode_auth_type(desc_encrypted_out, tok->args[0])) {
  2069. log_warn(LD_REND, "Service descriptor authentication type has "
  2070. "invalid entry(ies).");
  2071. goto err;
  2072. }
  2073. }
  2074. /* Is this service a single onion service? */
  2075. tok = find_opt_by_keyword(tokens, R3_SINGLE_ONION_SERVICE);
  2076. if (tok) {
  2077. desc_encrypted_out->single_onion_service = 1;
  2078. }
  2079. /* Initialize the descriptor's introduction point list before we start
  2080. * decoding. Having 0 intro point is valid. Then decode them all. */
  2081. desc_encrypted_out->intro_points = smartlist_new();
  2082. decode_intro_points(desc, desc_encrypted_out, message);
  2083. /* Validation of maximum introduction points allowed. */
  2084. if (smartlist_len(desc_encrypted_out->intro_points) >
  2085. HS_CONFIG_V3_MAX_INTRO_POINTS) {
  2086. log_warn(LD_REND, "Service descriptor contains too many introduction "
  2087. "points. Maximum allowed is %d but we have %d",
  2088. HS_CONFIG_V3_MAX_INTRO_POINTS,
  2089. smartlist_len(desc_encrypted_out->intro_points));
  2090. goto err;
  2091. }
  2092. /* NOTE: Unknown fields are allowed because this function could be used to
  2093. * decode other descriptor version. */
  2094. ret = 0;
  2095. goto done;
  2096. err:
  2097. tor_assert(ret < 0);
  2098. desc_encrypted_data_free_contents(desc_encrypted_out);
  2099. done:
  2100. if (tokens) {
  2101. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2102. smartlist_free(tokens);
  2103. }
  2104. if (area) {
  2105. memarea_drop_all(area);
  2106. }
  2107. if (message) {
  2108. tor_free(message);
  2109. }
  2110. return ret;
  2111. }
  2112. /* Table of encrypted decode function version specific. The function are
  2113. * indexed by the version number so v3 callback is at index 3 in the array. */
  2114. static int
  2115. (*decode_encrypted_handlers[])(
  2116. const hs_descriptor_t *desc,
  2117. const curve25519_secret_key_t *client_sk,
  2118. hs_desc_encrypted_data_t *desc_encrypted) =
  2119. {
  2120. /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
  2121. desc_decode_encrypted_v3,
  2122. };
  2123. /* Decode the encrypted data section of the given descriptor and store the
  2124. * data in the given encrypted data object. Return 0 on success else a
  2125. * negative value on error. */
  2126. int
  2127. hs_desc_decode_encrypted(const hs_descriptor_t *desc,
  2128. const curve25519_secret_key_t *client_sk,
  2129. hs_desc_encrypted_data_t *desc_encrypted)
  2130. {
  2131. int ret;
  2132. uint32_t version;
  2133. tor_assert(desc);
  2134. /* Ease our life a bit. */
  2135. version = desc->plaintext_data.version;
  2136. tor_assert(desc_encrypted);
  2137. /* Calling this function without an encrypted blob to parse is a code flow
  2138. * error. The superencrypted parsing should never succeed in the first place
  2139. * without an encrypted section. */
  2140. tor_assert(desc->superencrypted_data.encrypted_blob);
  2141. /* Let's make sure we have a supported version as well. By correctly parsing
  2142. * the plaintext, this should not fail. */
  2143. if (BUG(!hs_desc_is_supported_version(version))) {
  2144. ret = -1;
  2145. goto err;
  2146. }
  2147. /* Extra precaution. Having no handler for the supported version should
  2148. * never happened else we forgot to add it but we bumped the version. */
  2149. tor_assert(ARRAY_LENGTH(decode_encrypted_handlers) >= version);
  2150. tor_assert(decode_encrypted_handlers[version]);
  2151. /* Run the version specific plaintext decoder. */
  2152. ret = decode_encrypted_handlers[version](desc, client_sk, desc_encrypted);
  2153. if (ret < 0) {
  2154. goto err;
  2155. }
  2156. err:
  2157. return ret;
  2158. }
  2159. /* Table of superencrypted decode function version specific. The function are
  2160. * indexed by the version number so v3 callback is at index 3 in the array. */
  2161. static int
  2162. (*decode_superencrypted_handlers[])(
  2163. const hs_descriptor_t *desc,
  2164. hs_desc_superencrypted_data_t *desc_superencrypted) =
  2165. {
  2166. /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
  2167. desc_decode_superencrypted_v3,
  2168. };
  2169. /* Decode the superencrypted data section of the given descriptor and store the
  2170. * data in the given superencrypted data object. Return 0 on success else a
  2171. * negative value on error. */
  2172. int
  2173. hs_desc_decode_superencrypted(const hs_descriptor_t *desc,
  2174. hs_desc_superencrypted_data_t *
  2175. desc_superencrypted)
  2176. {
  2177. int ret;
  2178. uint32_t version;
  2179. tor_assert(desc);
  2180. /* Ease our life a bit. */
  2181. version = desc->plaintext_data.version;
  2182. tor_assert(desc_superencrypted);
  2183. /* Calling this function without an superencrypted blob to parse is
  2184. * a code flow error. The plaintext parsing should never succeed in
  2185. * the first place without an superencrypted section. */
  2186. tor_assert(desc->plaintext_data.superencrypted_blob);
  2187. /* Let's make sure we have a supported version as well. By correctly parsing
  2188. * the plaintext, this should not fail. */
  2189. if (BUG(!hs_desc_is_supported_version(version))) {
  2190. ret = -1;
  2191. goto err;
  2192. }
  2193. /* Extra precaution. Having no handler for the supported version should
  2194. * never happened else we forgot to add it but we bumped the version. */
  2195. tor_assert(ARRAY_LENGTH(decode_superencrypted_handlers) >= version);
  2196. tor_assert(decode_superencrypted_handlers[version]);
  2197. /* Run the version specific plaintext decoder. */
  2198. ret = decode_superencrypted_handlers[version](desc, desc_superencrypted);
  2199. if (ret < 0) {
  2200. goto err;
  2201. }
  2202. err:
  2203. return ret;
  2204. }
  2205. /* Table of plaintext decode function version specific. The function are
  2206. * indexed by the version number so v3 callback is at index 3 in the array. */
  2207. static int
  2208. (*decode_plaintext_handlers[])(
  2209. smartlist_t *tokens,
  2210. hs_desc_plaintext_data_t *desc,
  2211. const char *encoded_desc,
  2212. size_t encoded_len) =
  2213. {
  2214. /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
  2215. desc_decode_plaintext_v3,
  2216. };
  2217. /* Fully decode the given descriptor plaintext and store the data in the
  2218. * plaintext data object. Returns 0 on success else a negative value. */
  2219. int
  2220. hs_desc_decode_plaintext(const char *encoded,
  2221. hs_desc_plaintext_data_t *plaintext)
  2222. {
  2223. int ok = 0, ret = -1;
  2224. memarea_t *area = NULL;
  2225. smartlist_t *tokens = NULL;
  2226. size_t encoded_len;
  2227. directory_token_t *tok;
  2228. tor_assert(encoded);
  2229. tor_assert(plaintext);
  2230. /* Check that descriptor is within size limits. */
  2231. encoded_len = strlen(encoded);
  2232. if (encoded_len >= hs_cache_get_max_descriptor_size()) {
  2233. log_warn(LD_REND, "Service descriptor is too big (%lu bytes)",
  2234. (unsigned long) encoded_len);
  2235. goto err;
  2236. }
  2237. area = memarea_new();
  2238. tokens = smartlist_new();
  2239. /* Tokenize the descriptor so we can start to parse it. */
  2240. if (tokenize_string(area, encoded, encoded + encoded_len, tokens,
  2241. hs_desc_v3_token_table, 0) < 0) {
  2242. log_warn(LD_REND, "Service descriptor is not parseable");
  2243. goto err;
  2244. }
  2245. /* Get the version of the descriptor which is the first mandatory field of
  2246. * the descriptor. From there, we'll decode the right descriptor version. */
  2247. tok = find_by_keyword(tokens, R_HS_DESCRIPTOR);
  2248. tor_assert(tok->n_args == 1);
  2249. plaintext->version = (uint32_t) tor_parse_ulong(tok->args[0], 10, 0,
  2250. UINT32_MAX, &ok, NULL);
  2251. if (!ok) {
  2252. log_warn(LD_REND, "Service descriptor has unparseable version %s",
  2253. escaped(tok->args[0]));
  2254. goto err;
  2255. }
  2256. if (!hs_desc_is_supported_version(plaintext->version)) {
  2257. log_warn(LD_REND, "Service descriptor has unsupported version %" PRIu32,
  2258. plaintext->version);
  2259. goto err;
  2260. }
  2261. /* Extra precaution. Having no handler for the supported version should
  2262. * never happened else we forgot to add it but we bumped the version. */
  2263. tor_assert(ARRAY_LENGTH(decode_plaintext_handlers) >= plaintext->version);
  2264. tor_assert(decode_plaintext_handlers[plaintext->version]);
  2265. /* Run the version specific plaintext decoder. */
  2266. ret = decode_plaintext_handlers[plaintext->version](tokens, plaintext,
  2267. encoded, encoded_len);
  2268. if (ret < 0) {
  2269. goto err;
  2270. }
  2271. /* Success. Descriptor has been populated with the data. */
  2272. ret = 0;
  2273. err:
  2274. if (tokens) {
  2275. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  2276. smartlist_free(tokens);
  2277. }
  2278. if (area) {
  2279. memarea_drop_all(area);
  2280. }
  2281. return ret;
  2282. }
  2283. /* Fully decode an encoded descriptor and set a newly allocated descriptor
  2284. * object in desc_out. Subcredentials are used if not NULL else it's ignored.
  2285. * Client secret key is used to decrypt the "encrypted" section if not NULL
  2286. * else it's ignored.
  2287. *
  2288. * Return 0 on success. A negative value is returned on error and desc_out is
  2289. * set to NULL. */
  2290. int
  2291. hs_desc_decode_descriptor(const char *encoded,
  2292. const uint8_t *subcredential,
  2293. const curve25519_secret_key_t *client_sk,
  2294. hs_descriptor_t **desc_out)
  2295. {
  2296. int ret = -1;
  2297. hs_descriptor_t *desc;
  2298. tor_assert(encoded);
  2299. desc = tor_malloc_zero(sizeof(hs_descriptor_t));
  2300. /* Subcredentials are optional. */
  2301. if (BUG(!subcredential)) {
  2302. log_warn(LD_GENERAL, "Tried to decrypt without subcred. Impossible!");
  2303. goto err;
  2304. }
  2305. memcpy(desc->subcredential, subcredential, sizeof(desc->subcredential));
  2306. ret = hs_desc_decode_plaintext(encoded, &desc->plaintext_data);
  2307. if (ret < 0) {
  2308. goto err;
  2309. }
  2310. ret = hs_desc_decode_superencrypted(desc, &desc->superencrypted_data);
  2311. if (ret < 0) {
  2312. goto err;
  2313. }
  2314. ret = hs_desc_decode_encrypted(desc, client_sk, &desc->encrypted_data);
  2315. if (ret < 0) {
  2316. goto err;
  2317. }
  2318. if (desc_out) {
  2319. *desc_out = desc;
  2320. } else {
  2321. hs_descriptor_free(desc);
  2322. }
  2323. return ret;
  2324. err:
  2325. hs_descriptor_free(desc);
  2326. if (desc_out) {
  2327. *desc_out = NULL;
  2328. }
  2329. tor_assert(ret < 0);
  2330. return ret;
  2331. }
  2332. /* Table of encode function version specific. The functions are indexed by the
  2333. * version number so v3 callback is at index 3 in the array. */
  2334. static int
  2335. (*encode_handlers[])(
  2336. const hs_descriptor_t *desc,
  2337. const ed25519_keypair_t *signing_kp,
  2338. const uint8_t *descriptor_cookie,
  2339. char **encoded_out) =
  2340. {
  2341. /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
  2342. desc_encode_v3,
  2343. };
  2344. /* Encode the given descriptor desc including signing with the given key pair
  2345. * signing_kp and encrypting with the given descriptor cookie.
  2346. *
  2347. * If the client authorization is enabled, descriptor_cookie must be the same
  2348. * as the one used to build hs_desc_authorized_client_t in the descriptor.
  2349. * Otherwise, it must be NULL. On success, encoded_out points to a newly
  2350. * allocated NUL terminated string that contains the encoded descriptor as
  2351. * a string.
  2352. *
  2353. * Return 0 on success and encoded_out is a valid pointer. On error, -1 is
  2354. * returned and encoded_out is set to NULL. */
  2355. MOCK_IMPL(int,
  2356. hs_desc_encode_descriptor,(const hs_descriptor_t *desc,
  2357. const ed25519_keypair_t *signing_kp,
  2358. const uint8_t *descriptor_cookie,
  2359. char **encoded_out))
  2360. {
  2361. int ret = -1;
  2362. uint32_t version;
  2363. tor_assert(desc);
  2364. tor_assert(encoded_out);
  2365. /* Make sure we support the version of the descriptor format. */
  2366. version = desc->plaintext_data.version;
  2367. if (!hs_desc_is_supported_version(version)) {
  2368. goto err;
  2369. }
  2370. /* Extra precaution. Having no handler for the supported version should
  2371. * never happened else we forgot to add it but we bumped the version. */
  2372. tor_assert(ARRAY_LENGTH(encode_handlers) >= version);
  2373. tor_assert(encode_handlers[version]);
  2374. ret = encode_handlers[version](desc, signing_kp,
  2375. descriptor_cookie, encoded_out);
  2376. if (ret < 0) {
  2377. goto err;
  2378. }
  2379. /* Try to decode what we just encoded. Symmetry is nice!, but it is
  2380. * symmetric only if the client auth is disabled. That is, the descriptor
  2381. * cookie will be NULL. */
  2382. if (!descriptor_cookie) {
  2383. ret = hs_desc_decode_descriptor(*encoded_out, desc->subcredential,
  2384. NULL, NULL);
  2385. if (BUG(ret < 0)) {
  2386. goto err;
  2387. }
  2388. }
  2389. return 0;
  2390. err:
  2391. *encoded_out = NULL;
  2392. return ret;
  2393. }
  2394. /* Free the descriptor plaintext data object. */
  2395. void
  2396. hs_desc_plaintext_data_free_(hs_desc_plaintext_data_t *desc)
  2397. {
  2398. desc_plaintext_data_free_contents(desc);
  2399. tor_free(desc);
  2400. }
  2401. /* Free the descriptor plaintext data object. */
  2402. void
  2403. hs_desc_superencrypted_data_free_(hs_desc_superencrypted_data_t *desc)
  2404. {
  2405. desc_superencrypted_data_free_contents(desc);
  2406. tor_free(desc);
  2407. }
  2408. /* Free the descriptor encrypted data object. */
  2409. void
  2410. hs_desc_encrypted_data_free_(hs_desc_encrypted_data_t *desc)
  2411. {
  2412. desc_encrypted_data_free_contents(desc);
  2413. tor_free(desc);
  2414. }
  2415. /* Free the given descriptor object. */
  2416. void
  2417. hs_descriptor_free_(hs_descriptor_t *desc)
  2418. {
  2419. if (!desc) {
  2420. return;
  2421. }
  2422. desc_plaintext_data_free_contents(&desc->plaintext_data);
  2423. desc_superencrypted_data_free_contents(&desc->superencrypted_data);
  2424. desc_encrypted_data_free_contents(&desc->encrypted_data);
  2425. tor_free(desc);
  2426. }
  2427. /* Return the size in bytes of the given plaintext data object. A sizeof() is
  2428. * not enough because the object contains pointers and the encrypted blob.
  2429. * This is particularly useful for our OOM subsystem that tracks the HSDir
  2430. * cache size for instance. */
  2431. size_t
  2432. hs_desc_plaintext_obj_size(const hs_desc_plaintext_data_t *data)
  2433. {
  2434. tor_assert(data);
  2435. return (sizeof(*data) + sizeof(*data->signing_key_cert) +
  2436. data->superencrypted_blob_size);
  2437. }
  2438. /* Return the size in bytes of the given encrypted data object. Used by OOM
  2439. * subsystem. */
  2440. static size_t
  2441. hs_desc_encrypted_obj_size(const hs_desc_encrypted_data_t *data)
  2442. {
  2443. tor_assert(data);
  2444. size_t intro_size = 0;
  2445. if (data->intro_auth_types) {
  2446. intro_size +=
  2447. smartlist_len(data->intro_auth_types) * sizeof(intro_auth_types);
  2448. }
  2449. if (data->intro_points) {
  2450. /* XXX could follow pointers here and get more accurate size */
  2451. intro_size +=
  2452. smartlist_len(data->intro_points) * sizeof(hs_desc_intro_point_t);
  2453. }
  2454. return sizeof(*data) + intro_size;
  2455. }
  2456. /* Return the size in bytes of the given descriptor object. Used by OOM
  2457. * subsystem. */
  2458. size_t
  2459. hs_desc_obj_size(const hs_descriptor_t *data)
  2460. {
  2461. tor_assert(data);
  2462. return (hs_desc_plaintext_obj_size(&data->plaintext_data) +
  2463. hs_desc_encrypted_obj_size(&data->encrypted_data) +
  2464. sizeof(data->subcredential));
  2465. }
  2466. /* Return a newly allocated descriptor intro point. */
  2467. hs_desc_intro_point_t *
  2468. hs_desc_intro_point_new(void)
  2469. {
  2470. hs_desc_intro_point_t *ip = tor_malloc_zero(sizeof(*ip));
  2471. ip->link_specifiers = smartlist_new();
  2472. return ip;
  2473. }
  2474. /* Free a descriptor intro point object. */
  2475. void
  2476. hs_desc_intro_point_free_(hs_desc_intro_point_t *ip)
  2477. {
  2478. if (ip == NULL) {
  2479. return;
  2480. }
  2481. if (ip->link_specifiers) {
  2482. SMARTLIST_FOREACH(ip->link_specifiers, hs_desc_link_specifier_t *,
  2483. ls, hs_desc_link_specifier_free(ls));
  2484. smartlist_free(ip->link_specifiers);
  2485. }
  2486. tor_cert_free(ip->auth_key_cert);
  2487. tor_cert_free(ip->enc_key_cert);
  2488. crypto_pk_free(ip->legacy.key);
  2489. tor_free(ip->legacy.cert.encoded);
  2490. tor_free(ip);
  2491. }
  2492. /* Build a fake client info for the descriptor */
  2493. void
  2494. hs_desc_build_fake_authorized_client(hs_desc_authorized_client_t *client_out)
  2495. {
  2496. tor_assert(client_out);
  2497. crypto_rand((char *) client_out->client_id,
  2498. sizeof(client_out->client_id));
  2499. crypto_rand((char *) client_out->iv,
  2500. sizeof(client_out->iv));
  2501. crypto_rand((char *) client_out->encrypted_cookie,
  2502. sizeof(client_out->encrypted_cookie));
  2503. }
  2504. /* Using the client public key, auth ephemeral secret key, and descriptor
  2505. * cookie, build the auth client so we can then encode the descriptor for
  2506. * publication. client_out must be already allocated. */
  2507. void
  2508. hs_desc_build_authorized_client(const curve25519_public_key_t *client_pk,
  2509. const curve25519_secret_key_t *
  2510. auth_ephemeral_sk,
  2511. const uint8_t *descriptor_cookie,
  2512. hs_desc_authorized_client_t *client_out)
  2513. {
  2514. uint8_t secret_seed[CURVE25519_OUTPUT_LEN];
  2515. uint8_t keystream[HS_DESC_CLIENT_ID_LEN + HS_DESC_COOKIE_KEY_LEN];
  2516. uint8_t *cookie_key;
  2517. crypto_cipher_t *cipher;
  2518. crypto_xof_t *xof;
  2519. tor_assert(client_pk);
  2520. tor_assert(auth_ephemeral_sk);
  2521. tor_assert(descriptor_cookie);
  2522. tor_assert(client_out);
  2523. tor_assert(!tor_mem_is_zero((char *) auth_ephemeral_sk,
  2524. sizeof(*auth_ephemeral_sk)));
  2525. tor_assert(!tor_mem_is_zero((char *) client_pk, sizeof(*client_pk)));
  2526. tor_assert(!tor_mem_is_zero((char *) descriptor_cookie,
  2527. HS_DESC_DESCRIPTOR_COOKIE_LEN));
  2528. /* Calculate x25519(hs_y, client_X) */
  2529. curve25519_handshake(secret_seed,
  2530. auth_ephemeral_sk,
  2531. client_pk);
  2532. /* Calculate KEYS = KDF(SECRET_SEED, 40) */
  2533. xof = crypto_xof_new();
  2534. crypto_xof_add_bytes(xof, secret_seed, sizeof(secret_seed));
  2535. crypto_xof_squeeze_bytes(xof, keystream, sizeof(keystream));
  2536. crypto_xof_free(xof);
  2537. memcpy(client_out->client_id, keystream, HS_DESC_CLIENT_ID_LEN);
  2538. cookie_key = keystream + HS_DESC_CLIENT_ID_LEN;
  2539. /* Random IV */
  2540. crypto_strongest_rand(client_out->iv, sizeof(client_out->iv));
  2541. /* This creates a cipher for AES. It can't fail. */
  2542. cipher = crypto_cipher_new_with_iv_and_bits(cookie_key, client_out->iv,
  2543. HS_DESC_COOKIE_KEY_BIT_SIZE);
  2544. /* This can't fail. */
  2545. crypto_cipher_encrypt(cipher, (char *) client_out->encrypted_cookie,
  2546. (const char *) descriptor_cookie,
  2547. HS_DESC_DESCRIPTOR_COOKIE_LEN);
  2548. memwipe(secret_seed, 0, sizeof(secret_seed));
  2549. memwipe(keystream, 0, sizeof(keystream));
  2550. crypto_cipher_free(cipher);
  2551. }
  2552. /* Free an authoriezd client object. */
  2553. void
  2554. hs_desc_authorized_client_free_(hs_desc_authorized_client_t *client)
  2555. {
  2556. tor_free(client);
  2557. }
  2558. /* Free the given descriptor link specifier. */
  2559. void
  2560. hs_desc_link_specifier_free_(hs_desc_link_specifier_t *ls)
  2561. {
  2562. if (ls == NULL) {
  2563. return;
  2564. }
  2565. tor_free(ls);
  2566. }
  2567. /* Return a newly allocated descriptor link specifier using the given extend
  2568. * info and requested type. Return NULL on error. */
  2569. hs_desc_link_specifier_t *
  2570. hs_desc_link_specifier_new(const extend_info_t *info, uint8_t type)
  2571. {
  2572. hs_desc_link_specifier_t *ls = NULL;
  2573. tor_assert(info);
  2574. ls = tor_malloc_zero(sizeof(*ls));
  2575. ls->type = type;
  2576. switch (ls->type) {
  2577. case LS_IPV4:
  2578. if (info->addr.family != AF_INET) {
  2579. goto err;
  2580. }
  2581. tor_addr_copy(&ls->u.ap.addr, &info->addr);
  2582. ls->u.ap.port = info->port;
  2583. break;
  2584. case LS_IPV6:
  2585. if (info->addr.family != AF_INET6) {
  2586. goto err;
  2587. }
  2588. tor_addr_copy(&ls->u.ap.addr, &info->addr);
  2589. ls->u.ap.port = info->port;
  2590. break;
  2591. case LS_LEGACY_ID:
  2592. /* Bug out if the identity digest is not set */
  2593. if (BUG(tor_mem_is_zero(info->identity_digest,
  2594. sizeof(info->identity_digest)))) {
  2595. goto err;
  2596. }
  2597. memcpy(ls->u.legacy_id, info->identity_digest, sizeof(ls->u.legacy_id));
  2598. break;
  2599. case LS_ED25519_ID:
  2600. /* ed25519 keys are optional for intro points */
  2601. if (ed25519_public_key_is_zero(&info->ed_identity)) {
  2602. goto err;
  2603. }
  2604. memcpy(ls->u.ed25519_id, info->ed_identity.pubkey,
  2605. sizeof(ls->u.ed25519_id));
  2606. break;
  2607. default:
  2608. /* Unknown type is code flow error. */
  2609. tor_assert(0);
  2610. }
  2611. return ls;
  2612. err:
  2613. tor_free(ls);
  2614. return NULL;
  2615. }
  2616. /* From the given descriptor, remove and free every introduction point. */
  2617. void
  2618. hs_descriptor_clear_intro_points(hs_descriptor_t *desc)
  2619. {
  2620. smartlist_t *ips;
  2621. tor_assert(desc);
  2622. ips = desc->encrypted_data.intro_points;
  2623. if (ips) {
  2624. SMARTLIST_FOREACH(ips, hs_desc_intro_point_t *,
  2625. ip, hs_desc_intro_point_free(ip));
  2626. smartlist_clear(ips);
  2627. }
  2628. }
  2629. /* From a descriptor link specifier object spec, returned a newly allocated
  2630. * link specifier object that is the encoded representation of spec. Return
  2631. * NULL on error. */
  2632. link_specifier_t *
  2633. hs_desc_lspec_to_trunnel(const hs_desc_link_specifier_t *spec)
  2634. {
  2635. tor_assert(spec);
  2636. link_specifier_t *ls = link_specifier_new();
  2637. link_specifier_set_ls_type(ls, spec->type);
  2638. switch (spec->type) {
  2639. case LS_IPV4:
  2640. link_specifier_set_un_ipv4_addr(ls,
  2641. tor_addr_to_ipv4h(&spec->u.ap.addr));
  2642. link_specifier_set_un_ipv4_port(ls, spec->u.ap.port);
  2643. /* Four bytes IPv4 and two bytes port. */
  2644. link_specifier_set_ls_len(ls, sizeof(spec->u.ap.addr.addr.in_addr) +
  2645. sizeof(spec->u.ap.port));
  2646. break;
  2647. case LS_IPV6:
  2648. {
  2649. size_t addr_len = link_specifier_getlen_un_ipv6_addr(ls);
  2650. const uint8_t *in6_addr = tor_addr_to_in6_addr8(&spec->u.ap.addr);
  2651. uint8_t *ipv6_array = link_specifier_getarray_un_ipv6_addr(ls);
  2652. memcpy(ipv6_array, in6_addr, addr_len);
  2653. link_specifier_set_un_ipv6_port(ls, spec->u.ap.port);
  2654. /* Sixteen bytes IPv6 and two bytes port. */
  2655. link_specifier_set_ls_len(ls, addr_len + sizeof(spec->u.ap.port));
  2656. break;
  2657. }
  2658. case LS_LEGACY_ID:
  2659. {
  2660. size_t legacy_id_len = link_specifier_getlen_un_legacy_id(ls);
  2661. uint8_t *legacy_id_array = link_specifier_getarray_un_legacy_id(ls);
  2662. memcpy(legacy_id_array, spec->u.legacy_id, legacy_id_len);
  2663. link_specifier_set_ls_len(ls, legacy_id_len);
  2664. break;
  2665. }
  2666. case LS_ED25519_ID:
  2667. {
  2668. size_t ed25519_id_len = link_specifier_getlen_un_ed25519_id(ls);
  2669. uint8_t *ed25519_id_array = link_specifier_getarray_un_ed25519_id(ls);
  2670. memcpy(ed25519_id_array, spec->u.ed25519_id, ed25519_id_len);
  2671. link_specifier_set_ls_len(ls, ed25519_id_len);
  2672. break;
  2673. }
  2674. default:
  2675. tor_assert_nonfatal_unreached();
  2676. link_specifier_free(ls);
  2677. ls = NULL;
  2678. }
  2679. return ls;
  2680. }