hs_descriptor.c 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907
  1. /* Copyright (c) 2016, 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. /* For unit tests.*/
  8. #define HS_DESCRIPTOR_PRIVATE
  9. #include "hs_descriptor.h"
  10. #include "or.h"
  11. #include "ed25519_cert.h" /* Trunnel interface. */
  12. #include "parsecommon.h"
  13. #include "rendcache.h"
  14. #include "torcert.h" /* tor_cert_encode_ed22519() */
  15. /* Constant string value used for the descriptor format. */
  16. #define str_hs_desc "hs-descriptor"
  17. #define str_desc_cert "descriptor-signing-key-cert"
  18. #define str_rev_counter "revision-counter"
  19. #define str_encrypted "encrypted"
  20. #define str_signature "signature"
  21. #define str_lifetime "descriptor-lifetime"
  22. /* Constant string value for the encrypted part of the descriptor. */
  23. #define str_create2_formats "create2-formats"
  24. #define str_auth_required "authentication-required"
  25. #define str_single_onion "single-onion-service"
  26. #define str_intro_point "introduction-point"
  27. #define str_ip_auth_key "auth-key"
  28. #define str_ip_enc_key "enc-key"
  29. #define str_ip_enc_key_cert "enc-key-certification"
  30. #define str_intro_point_start "\n" str_intro_point " "
  31. /* Constant string value for the construction to encrypt the encrypted data
  32. * section. */
  33. #define str_enc_hsdir_data "hsdir-encrypted-data"
  34. /* Prefix required to compute/verify HS desc signatures */
  35. #define str_desc_sig_prefix "Tor onion service descriptor sig v3"
  36. /* Authentication supported types. */
  37. static const struct {
  38. hs_desc_auth_type_t type;
  39. const char *identifier;
  40. } auth_types[] = {
  41. { HS_DESC_AUTH_PASSWORD, "password" },
  42. { HS_DESC_AUTH_ED25519, "ed25519" },
  43. /* Indicate end of array. */
  44. { 0, NULL }
  45. };
  46. /* Descriptor ruleset. */
  47. static token_rule_t hs_desc_v3_token_table[] = {
  48. T1_START(str_hs_desc, R_HS_DESCRIPTOR, EQ(1), NO_OBJ),
  49. T1(str_lifetime, R3_DESC_LIFETIME, EQ(1), NO_OBJ),
  50. T1(str_desc_cert, R3_DESC_SIGNING_CERT, NO_ARGS, NEED_OBJ),
  51. T1(str_rev_counter, R3_REVISION_COUNTER, EQ(1), NO_OBJ),
  52. T1(str_encrypted, R3_ENCRYPTED, NO_ARGS, NEED_OBJ),
  53. T1_END(str_signature, R3_SIGNATURE, EQ(1), NO_OBJ),
  54. END_OF_TABLE
  55. };
  56. /* Descriptor ruleset for the encrypted section. */
  57. static token_rule_t hs_desc_encrypted_v3_token_table[] = {
  58. T1_START(str_create2_formats, R3_CREATE2_FORMATS, CONCAT_ARGS, NO_OBJ),
  59. T01(str_auth_required, R3_AUTHENTICATION_REQUIRED, ARGS, NO_OBJ),
  60. T01(str_single_onion, R3_SINGLE_ONION_SERVICE, ARGS, NO_OBJ),
  61. END_OF_TABLE
  62. };
  63. /* Descriptor ruleset for the introduction points section. */
  64. static token_rule_t hs_desc_intro_point_v3_token_table[] = {
  65. T1_START(str_intro_point, R3_INTRODUCTION_POINT, EQ(1), NO_OBJ),
  66. T1(str_ip_auth_key, R3_INTRO_AUTH_KEY, NO_ARGS, NEED_OBJ),
  67. T1(str_ip_enc_key, R3_INTRO_ENC_KEY, ARGS, OBJ_OK),
  68. T1_END(str_ip_enc_key_cert, R3_INTRO_ENC_KEY_CERTIFICATION,
  69. NO_ARGS, NEED_OBJ),
  70. END_OF_TABLE
  71. };
  72. /* Free a descriptor intro point object. */
  73. STATIC void
  74. desc_intro_point_free(hs_desc_intro_point_t *ip)
  75. {
  76. if (!ip) {
  77. return;
  78. }
  79. if (ip->link_specifiers) {
  80. SMARTLIST_FOREACH(ip->link_specifiers, hs_desc_link_specifier_t *,
  81. ls, tor_free(ls));
  82. smartlist_free(ip->link_specifiers);
  83. }
  84. tor_cert_free(ip->auth_key_cert);
  85. if (ip->enc_key_type == HS_DESC_KEY_TYPE_LEGACY) {
  86. crypto_pk_free(ip->enc_key.legacy);
  87. }
  88. tor_free(ip);
  89. }
  90. /* Free the content of the plaintext section of a descriptor. */
  91. static void
  92. desc_plaintext_data_free_contents(hs_desc_plaintext_data_t *desc)
  93. {
  94. if (!desc) {
  95. return;
  96. }
  97. if (desc->encrypted_blob) {
  98. tor_free(desc->encrypted_blob);
  99. }
  100. tor_cert_free(desc->signing_key_cert);
  101. memwipe(desc, 0, sizeof(*desc));
  102. }
  103. /* Free the content of the encrypted section of a descriptor. */
  104. static void
  105. desc_encrypted_data_free_contents(hs_desc_encrypted_data_t *desc)
  106. {
  107. if (!desc) {
  108. return;
  109. }
  110. if (desc->auth_types) {
  111. SMARTLIST_FOREACH(desc->auth_types, char *, a, tor_free(a));
  112. smartlist_free(desc->auth_types);
  113. }
  114. if (desc->intro_points) {
  115. SMARTLIST_FOREACH(desc->intro_points, hs_desc_intro_point_t *, ip,
  116. desc_intro_point_free(ip));
  117. smartlist_free(desc->intro_points);
  118. }
  119. memwipe(desc, 0, sizeof(*desc));
  120. }
  121. /* === ENCODING === */
  122. /* Encode the given link specifier objects into a newly allocated string.
  123. * This can't fail so caller can always assume a valid string being
  124. * returned. */
  125. STATIC char *
  126. encode_link_specifiers(const smartlist_t *specs)
  127. {
  128. char *encoded_b64 = NULL;
  129. link_specifier_list_t *lslist = link_specifier_list_new();
  130. tor_assert(specs);
  131. /* No link specifiers is a code flow error, can't happen. */
  132. tor_assert(smartlist_len(specs) > 0);
  133. tor_assert(smartlist_len(specs) <= UINT8_MAX);
  134. link_specifier_list_set_n_spec(lslist, smartlist_len(specs));
  135. SMARTLIST_FOREACH_BEGIN(specs, const hs_desc_link_specifier_t *,
  136. spec) {
  137. link_specifier_t *ls = link_specifier_new();
  138. link_specifier_set_ls_type(ls, spec->type);
  139. switch (spec->type) {
  140. case LS_IPV4:
  141. link_specifier_set_un_ipv4_addr(ls,
  142. tor_addr_to_ipv4h(&spec->u.ap.addr));
  143. link_specifier_set_un_ipv4_port(ls, spec->u.ap.port);
  144. /* Four bytes IPv4 and two bytes port. */
  145. link_specifier_set_ls_len(ls, sizeof(spec->u.ap.addr.addr.in_addr) +
  146. sizeof(spec->u.ap.port));
  147. break;
  148. case LS_IPV6:
  149. {
  150. size_t addr_len = link_specifier_getlen_un_ipv6_addr(ls);
  151. const uint8_t *in6_addr = tor_addr_to_in6_addr8(&spec->u.ap.addr);
  152. uint8_t *ipv6_array = link_specifier_getarray_un_ipv6_addr(ls);
  153. memcpy(ipv6_array, in6_addr, addr_len);
  154. link_specifier_set_un_ipv6_port(ls, spec->u.ap.port);
  155. /* Sixteen bytes IPv6 and two bytes port. */
  156. link_specifier_set_ls_len(ls, addr_len + sizeof(spec->u.ap.port));
  157. break;
  158. }
  159. case LS_LEGACY_ID:
  160. {
  161. size_t legacy_id_len = link_specifier_getlen_un_legacy_id(ls);
  162. uint8_t *legacy_id_array = link_specifier_getarray_un_legacy_id(ls);
  163. memcpy(legacy_id_array, spec->u.legacy_id, legacy_id_len);
  164. link_specifier_set_ls_len(ls, legacy_id_len);
  165. break;
  166. }
  167. default:
  168. tor_assert(0);
  169. }
  170. link_specifier_list_add_spec(lslist, ls);
  171. } SMARTLIST_FOREACH_END(spec);
  172. {
  173. uint8_t *encoded;
  174. ssize_t encoded_len, encoded_b64_len, ret;
  175. encoded_len = link_specifier_list_encoded_len(lslist);
  176. tor_assert(encoded_len > 0);
  177. encoded = tor_malloc_zero(encoded_len);
  178. ret = link_specifier_list_encode(encoded, encoded_len, lslist);
  179. tor_assert(ret == encoded_len);
  180. /* Base64 encode our binary format. Add extra NUL byte for the base64
  181. * encoded value. */
  182. encoded_b64_len = base64_encode_size(encoded_len, 0) + 1;
  183. encoded_b64 = tor_malloc_zero(encoded_b64_len);
  184. ret = base64_encode(encoded_b64, encoded_b64_len, (const char *) encoded,
  185. encoded_len, 0);
  186. tor_assert(ret == (encoded_b64_len - 1));
  187. tor_free(encoded);
  188. }
  189. link_specifier_list_free(lslist);
  190. return encoded_b64;
  191. }
  192. /* Encode an introduction point encryption key and return a newly allocated
  193. * string with it. On failure, return NULL. */
  194. static char *
  195. encode_enc_key(const ed25519_public_key_t *sig_key,
  196. const hs_desc_intro_point_t *ip)
  197. {
  198. char *encoded = NULL;
  199. time_t now = time(NULL);
  200. tor_assert(sig_key);
  201. tor_assert(ip);
  202. switch (ip->enc_key_type) {
  203. case HS_DESC_KEY_TYPE_LEGACY:
  204. {
  205. char *key_str, b64_cert[256];
  206. ssize_t cert_len;
  207. size_t key_str_len;
  208. uint8_t *cert_data = NULL;
  209. /* Create cross certification cert. */
  210. cert_len = tor_make_rsa_ed25519_crosscert(sig_key, ip->enc_key.legacy,
  211. now + HS_DESC_CERT_LIFETIME,
  212. &cert_data);
  213. if (cert_len < 0) {
  214. log_warn(LD_REND, "Unable to create legacy crosscert.");
  215. goto err;
  216. }
  217. /* Encode cross cert. */
  218. if (base64_encode(b64_cert, sizeof(b64_cert), (const char *) cert_data,
  219. cert_len, BASE64_ENCODE_MULTILINE) < 0) {
  220. tor_free(cert_data);
  221. log_warn(LD_REND, "Unable to encode legacy crosscert.");
  222. goto err;
  223. }
  224. tor_free(cert_data);
  225. /* Convert the encryption key to a string. */
  226. if (crypto_pk_write_public_key_to_string(ip->enc_key.legacy, &key_str,
  227. &key_str_len) < 0) {
  228. log_warn(LD_REND, "Unable to encode legacy encryption key.");
  229. goto err;
  230. }
  231. tor_asprintf(&encoded,
  232. "%s legacy\n%s" /* Newline is added by the call above. */
  233. "%s\n"
  234. "-----BEGIN CROSSCERT-----\n"
  235. "%s"
  236. "-----END CROSSCERT-----",
  237. str_ip_enc_key, key_str,
  238. str_ip_enc_key_cert, b64_cert);
  239. tor_free(key_str);
  240. break;
  241. }
  242. case HS_DESC_KEY_TYPE_CURVE25519:
  243. {
  244. int signbit, ret;
  245. char *encoded_cert, key_fp_b64[CURVE25519_BASE64_PADDED_LEN + 1];
  246. ed25519_keypair_t curve_kp;
  247. if (ed25519_keypair_from_curve25519_keypair(&curve_kp, &signbit,
  248. &ip->enc_key.curve25519)) {
  249. goto err;
  250. }
  251. tor_cert_t *cross_cert = tor_cert_create(&curve_kp,
  252. CERT_TYPE_CROSS_HS_IP_KEYS,
  253. sig_key, now,
  254. HS_DESC_CERT_LIFETIME,
  255. CERT_FLAG_INCLUDE_SIGNING_KEY);
  256. memwipe(&curve_kp, 0, sizeof(curve_kp));
  257. if (!cross_cert) {
  258. goto err;
  259. }
  260. ret = tor_cert_encode_ed22519(cross_cert, &encoded_cert);
  261. tor_cert_free(cross_cert);
  262. if (ret) {
  263. goto err;
  264. }
  265. if (curve25519_public_to_base64(key_fp_b64,
  266. &ip->enc_key.curve25519.pubkey) < 0) {
  267. tor_free(encoded_cert);
  268. goto err;
  269. }
  270. tor_asprintf(&encoded,
  271. "%s ntor %s\n"
  272. "%s\n%s",
  273. str_ip_enc_key, key_fp_b64,
  274. str_ip_enc_key_cert, encoded_cert);
  275. tor_free(encoded_cert);
  276. break;
  277. }
  278. default:
  279. tor_assert(0);
  280. }
  281. err:
  282. return encoded;
  283. }
  284. /* Encode an introduction point object and return a newly allocated string
  285. * with it. On failure, return NULL. */
  286. static char *
  287. encode_intro_point(const ed25519_public_key_t *sig_key,
  288. const hs_desc_intro_point_t *ip)
  289. {
  290. char *encoded_ip = NULL;
  291. smartlist_t *lines = smartlist_new();
  292. tor_assert(ip);
  293. tor_assert(sig_key);
  294. /* Encode link specifier. */
  295. {
  296. char *ls_str = encode_link_specifiers(ip->link_specifiers);
  297. smartlist_add_asprintf(lines, "%s %s", str_intro_point, ls_str);
  298. tor_free(ls_str);
  299. }
  300. /* Authentication key encoding. */
  301. {
  302. char *encoded_cert;
  303. if (tor_cert_encode_ed22519(ip->auth_key_cert, &encoded_cert) < 0) {
  304. goto err;
  305. }
  306. smartlist_add_asprintf(lines, "%s\n%s", str_ip_auth_key, encoded_cert);
  307. tor_free(encoded_cert);
  308. }
  309. /* Encryption key encoding. */
  310. {
  311. char *encoded_enc_key = encode_enc_key(sig_key, ip);
  312. if (encoded_enc_key == NULL) {
  313. goto err;
  314. }
  315. smartlist_add_asprintf(lines, "%s", encoded_enc_key);
  316. tor_free(encoded_enc_key);
  317. }
  318. /* Join them all in one blob of text. */
  319. encoded_ip = smartlist_join_strings(lines, "\n", 1, NULL);
  320. err:
  321. SMARTLIST_FOREACH(lines, char *, l, tor_free(l));
  322. smartlist_free(lines);
  323. return encoded_ip;
  324. }
  325. /* Using a given decriptor object, build the secret input needed for the
  326. * KDF and put it in the dst pointer which is an already allocated buffer
  327. * of size dstlen. */
  328. static void
  329. build_secret_input(const hs_descriptor_t *desc, uint8_t *dst, size_t dstlen)
  330. {
  331. size_t offset = 0;
  332. tor_assert(desc);
  333. tor_assert(dst);
  334. tor_assert(HS_DESC_ENCRYPTED_SECRET_INPUT_LEN <= dstlen);
  335. /* XXX use the destination length as the memcpy length */
  336. /* Copy blinded public key. */
  337. memcpy(dst, desc->plaintext_data.blinded_pubkey.pubkey,
  338. sizeof(desc->plaintext_data.blinded_pubkey.pubkey));
  339. offset += sizeof(desc->plaintext_data.blinded_pubkey.pubkey);
  340. /* Copy subcredential. */
  341. memcpy(dst + offset, desc->subcredential, sizeof(desc->subcredential));
  342. offset += sizeof(desc->subcredential);
  343. /* Copy revision counter value. */
  344. set_uint64(dst + offset, tor_ntohll(desc->plaintext_data.revision_counter));
  345. offset += sizeof(uint64_t);
  346. tor_assert(HS_DESC_ENCRYPTED_SECRET_INPUT_LEN == offset);
  347. }
  348. /* Do the KDF construction and put the resulting data in key_out which is of
  349. * key_out_len length. It uses SHAKE-256 as specified in the spec. */
  350. static void
  351. build_kdf_key(const hs_descriptor_t *desc,
  352. const uint8_t *salt, size_t salt_len,
  353. uint8_t *key_out, size_t key_out_len)
  354. {
  355. uint8_t secret_input[HS_DESC_ENCRYPTED_SECRET_INPUT_LEN];
  356. crypto_xof_t *xof;
  357. tor_assert(desc);
  358. tor_assert(salt);
  359. tor_assert(key_out);
  360. /* Build the secret input for the KDF computation. */
  361. build_secret_input(desc, secret_input, sizeof(secret_input));
  362. xof = crypto_xof_new();
  363. /* Feed our KDF. [SHAKE it like a polaroid picture --Yawning]. */
  364. crypto_xof_add_bytes(xof, secret_input, sizeof(secret_input));
  365. crypto_xof_add_bytes(xof, salt, salt_len);
  366. crypto_xof_add_bytes(xof, (const uint8_t *) str_enc_hsdir_data,
  367. strlen(str_enc_hsdir_data));
  368. /* Eat from our KDF. */
  369. crypto_xof_squeeze_bytes(xof, key_out, key_out_len);
  370. crypto_xof_free(xof);
  371. memwipe(secret_input, 0, sizeof(secret_input));
  372. }
  373. /* Using the given descriptor and salt, run it through our KDF function and
  374. * then extract a secret key in key_out, the IV in iv_out and MAC in mac_out.
  375. * This function can't fail. */
  376. static void
  377. build_secret_key_iv_mac(const hs_descriptor_t *desc,
  378. const uint8_t *salt, size_t salt_len,
  379. uint8_t *key_out, size_t key_len,
  380. uint8_t *iv_out, size_t iv_len,
  381. uint8_t *mac_out, size_t mac_len)
  382. {
  383. size_t offset = 0;
  384. uint8_t kdf_key[HS_DESC_ENCRYPTED_KDF_OUTPUT_LEN];
  385. tor_assert(desc);
  386. tor_assert(salt);
  387. tor_assert(key_out);
  388. tor_assert(iv_out);
  389. tor_assert(mac_out);
  390. build_kdf_key(desc, salt, salt_len, kdf_key, sizeof(kdf_key));
  391. /* Copy the bytes we need for both the secret key and IV. */
  392. memcpy(key_out, kdf_key, key_len);
  393. offset += key_len;
  394. memcpy(iv_out, kdf_key + offset, iv_len);
  395. offset += iv_len;
  396. memcpy(mac_out, kdf_key + offset, mac_len);
  397. /* Extra precaution to make sure we are not out of bound. */
  398. tor_assert((offset + mac_len) == sizeof(kdf_key));
  399. memwipe(kdf_key, 0, sizeof(kdf_key));
  400. }
  401. /* Using a key, salt and encrypted payload, build a MAC and put it in mac_out.
  402. * We use SHA3-256 for the MAC computation.
  403. * This function can't fail. */
  404. static void
  405. build_mac(const uint8_t *mac_key, size_t mac_key_len,
  406. const uint8_t *salt, size_t salt_len,
  407. const uint8_t *encrypted, size_t encrypted_len,
  408. uint8_t *mac_out, size_t mac_len)
  409. {
  410. crypto_digest_t *digest;
  411. const uint64_t mac_len_netorder = tor_htonll(mac_key_len);
  412. const uint64_t salt_len_netorder = tor_htonll(salt_len);
  413. tor_assert(mac_key);
  414. tor_assert(salt);
  415. tor_assert(encrypted);
  416. tor_assert(mac_out);
  417. digest = crypto_digest256_new(DIGEST_SHA3_256);
  418. /* As specified in section 2.5 of proposal 224, first add the mac key
  419. * then add the salt first and then the encrypted section. */
  420. crypto_digest_add_bytes(digest, (const char *) &mac_len_netorder, 8);
  421. crypto_digest_add_bytes(digest, (const char *) mac_key, mac_key_len);
  422. crypto_digest_add_bytes(digest, (const char *) &salt_len_netorder, 8);
  423. crypto_digest_add_bytes(digest, (const char *) salt, salt_len);
  424. crypto_digest_add_bytes(digest, (const char *) encrypted, encrypted_len);
  425. crypto_digest_get_digest(digest, (char *) mac_out, mac_len);
  426. crypto_digest_free(digest);
  427. }
  428. /* Given a source length, return the new size including padding for the
  429. * plaintext encryption. */
  430. static size_t
  431. compute_padded_plaintext_length(size_t plaintext_len)
  432. {
  433. size_t plaintext_padded_len;
  434. /* Make sure we won't overflow. */
  435. tor_assert(plaintext_len <=
  436. (SIZE_T_CEILING - HS_DESC_PLAINTEXT_PADDING_MULTIPLE));
  437. /* Get the extra length we need to add. For example, if srclen is 234 bytes,
  438. * this will expand to (2 * 128) == 256 thus an extra 22 bytes. */
  439. plaintext_padded_len = CEIL_DIV(plaintext_len,
  440. HS_DESC_PLAINTEXT_PADDING_MULTIPLE) *
  441. HS_DESC_PLAINTEXT_PADDING_MULTIPLE;
  442. /* Can never be extra careful. Make sure we are _really_ padded. */
  443. tor_assert(!(plaintext_padded_len % HS_DESC_PLAINTEXT_PADDING_MULTIPLE));
  444. return plaintext_padded_len;
  445. }
  446. /* Given a buffer, pad it up to the encrypted section padding requirement. Set
  447. * the newly allocated string in padded_out and return the length of the
  448. * padded buffer. */
  449. STATIC size_t
  450. build_plaintext_padding(const char *plaintext, size_t plaintext_len,
  451. uint8_t **padded_out)
  452. {
  453. size_t padded_len;
  454. uint8_t *padded;
  455. tor_assert(plaintext);
  456. tor_assert(padded_out);
  457. /* Allocate the final length including padding. */
  458. padded_len = compute_padded_plaintext_length(plaintext_len);
  459. tor_assert(padded_len >= plaintext_len);
  460. padded = tor_malloc_zero(padded_len);
  461. memcpy(padded, plaintext, plaintext_len);
  462. *padded_out = padded;
  463. return padded_len;
  464. }
  465. /* Using a key, IV and plaintext data of length plaintext_len, create the
  466. * encrypted section by encrypting it and setting encrypted_out with the
  467. * data. Return size of the encrypted data buffer. */
  468. static size_t
  469. build_encrypted(const uint8_t *key, const uint8_t *iv, const char *plaintext,
  470. size_t plaintext_len, uint8_t **encrypted_out)
  471. {
  472. size_t encrypted_len;
  473. uint8_t *padded_plaintext, *encrypted;
  474. crypto_cipher_t *cipher;
  475. tor_assert(key);
  476. tor_assert(iv);
  477. tor_assert(plaintext);
  478. tor_assert(encrypted_out);
  479. /* This creates a cipher for AES128. It can't fail. */
  480. cipher = crypto_cipher_new_with_iv((const char *) key, (const char *) iv);
  481. /* This can't fail. */
  482. encrypted_len = build_plaintext_padding(plaintext, plaintext_len,
  483. &padded_plaintext);
  484. /* Extra precautions that we have a valie padding length. */
  485. tor_assert(encrypted_len <= HS_DESC_PADDED_PLAINTEXT_MAX_LEN);
  486. tor_assert(!(encrypted_len % HS_DESC_PLAINTEXT_PADDING_MULTIPLE));
  487. /* We use a stream cipher so the encrypted length will be the same as the
  488. * plaintext padded length. */
  489. encrypted = tor_malloc_zero(encrypted_len);
  490. /* This can't fail. */
  491. crypto_cipher_encrypt(cipher, (char *) encrypted,
  492. (const char *) padded_plaintext, encrypted_len);
  493. *encrypted_out = encrypted;
  494. /* Cleanup. */
  495. crypto_cipher_free(cipher);
  496. tor_free(padded_plaintext);
  497. return encrypted_len;
  498. }
  499. /* Encrypt the given plaintext buffer and using the descriptor to get the
  500. * keys. Set encrypted_out with the encrypted data and return the length of
  501. * it. */
  502. static size_t
  503. encrypt_descriptor_data(const hs_descriptor_t *desc, const char *plaintext,
  504. char **encrypted_out)
  505. {
  506. char *final_blob;
  507. size_t encrypted_len, final_blob_len, offset = 0;
  508. uint8_t *encrypted;
  509. uint8_t salt[HS_DESC_ENCRYPTED_SALT_LEN];
  510. uint8_t secret_key[CIPHER_KEY_LEN], secret_iv[CIPHER_IV_LEN];
  511. uint8_t mac_key[DIGEST256_LEN], mac[DIGEST256_LEN];
  512. tor_assert(desc);
  513. tor_assert(plaintext);
  514. tor_assert(encrypted_out);
  515. /* Get our salt. The returned bytes are already hashed. */
  516. crypto_strongest_rand(salt, sizeof(salt));
  517. /* KDF construction resulting in a key from which the secret key, IV and MAC
  518. * key are extracted which is what we need for the encryption. */
  519. build_secret_key_iv_mac(desc, salt, sizeof(salt),
  520. secret_key, sizeof(secret_key),
  521. secret_iv, sizeof(secret_iv),
  522. mac_key, sizeof(mac_key));
  523. /* Build the encrypted part that is do the actual encryption. */
  524. encrypted_len = build_encrypted(secret_key, secret_iv, plaintext,
  525. strlen(plaintext), &encrypted);
  526. memwipe(secret_key, 0, sizeof(secret_key));
  527. memwipe(secret_iv, 0, sizeof(secret_iv));
  528. /* This construction is specified in section 2.5 of proposal 224. */
  529. final_blob_len = sizeof(salt) + encrypted_len + DIGEST256_LEN;
  530. final_blob = tor_malloc_zero(final_blob_len);
  531. /* Build the MAC. */
  532. build_mac(mac_key, sizeof(mac_key), salt, sizeof(salt),
  533. encrypted, encrypted_len, mac, sizeof(mac));
  534. memwipe(mac_key, 0, sizeof(mac_key));
  535. /* The salt is the first value. */
  536. memcpy(final_blob, salt, sizeof(salt));
  537. offset = sizeof(salt);
  538. /* Second value is the encrypted data. */
  539. memcpy(final_blob + offset, encrypted, encrypted_len);
  540. offset += encrypted_len;
  541. /* Third value is the MAC. */
  542. memcpy(final_blob + offset, mac, sizeof(mac));
  543. offset += sizeof(mac);
  544. /* Cleanup the buffers. */
  545. memwipe(salt, 0, sizeof(salt));
  546. memwipe(encrypted, 0, encrypted_len);
  547. tor_free(encrypted);
  548. /* Extra precaution. */
  549. tor_assert(offset == final_blob_len);
  550. *encrypted_out = final_blob;
  551. return final_blob_len;
  552. }
  553. /* Take care of encoding the encrypted data section and then encrypting it
  554. * with the descriptor's key. A newly allocated NUL terminated string pointer
  555. * containing the encrypted encoded blob is put in encrypted_blob_out. Return
  556. * 0 on success else a negative value. */
  557. static int
  558. encode_encrypted_data(const hs_descriptor_t *desc,
  559. char **encrypted_blob_out)
  560. {
  561. int ret = -1;
  562. char *encoded_str, *encrypted_blob;
  563. smartlist_t *lines = smartlist_new();
  564. tor_assert(desc);
  565. tor_assert(encrypted_blob_out);
  566. /* Build the start of the section prior to the introduction points. */
  567. {
  568. if (!desc->encrypted_data.create2_ntor) {
  569. log_err(LD_BUG, "HS desc doesn't have recognized handshake type.");
  570. goto err;
  571. }
  572. smartlist_add_asprintf(lines, "%s %d\n", str_create2_formats,
  573. ONION_HANDSHAKE_TYPE_NTOR);
  574. if (desc->encrypted_data.auth_types &&
  575. smartlist_len(desc->encrypted_data.auth_types)) {
  576. /* Put the authentication-required line. */
  577. char *buf = smartlist_join_strings(desc->encrypted_data.auth_types, " ",
  578. 0, NULL);
  579. smartlist_add_asprintf(lines, "%s %s\n", str_auth_required, buf);
  580. tor_free(buf);
  581. }
  582. if (desc->encrypted_data.single_onion_service) {
  583. smartlist_add_asprintf(lines, "%s\n", str_single_onion);
  584. }
  585. }
  586. /* Build the introduction point(s) section. */
  587. SMARTLIST_FOREACH_BEGIN(desc->encrypted_data.intro_points,
  588. const hs_desc_intro_point_t *, ip) {
  589. char *encoded_ip = encode_intro_point(&desc->plaintext_data.signing_pubkey,
  590. ip);
  591. if (encoded_ip == NULL) {
  592. log_err(LD_BUG, "HS desc intro point is malformed.");
  593. goto err;
  594. }
  595. smartlist_add(lines, encoded_ip);
  596. } SMARTLIST_FOREACH_END(ip);
  597. /* Build the entire encrypted data section into one encoded plaintext and
  598. * then encrypt it. */
  599. encoded_str = smartlist_join_strings(lines, "", 0, NULL);
  600. /* Encrypt the section into an encrypted blob that we'll base64 encode
  601. * before returning it. */
  602. {
  603. char *enc_b64;
  604. ssize_t enc_b64_len, ret_len, enc_len;
  605. enc_len = encrypt_descriptor_data(desc, encoded_str, &encrypted_blob);
  606. tor_free(encoded_str);
  607. /* Get the encoded size plus a NUL terminating byte. */
  608. enc_b64_len = base64_encode_size(enc_len, BASE64_ENCODE_MULTILINE) + 1;
  609. enc_b64 = tor_malloc_zero(enc_b64_len);
  610. /* Base64 the encrypted blob before returning it. */
  611. ret_len = base64_encode(enc_b64, enc_b64_len, encrypted_blob, enc_len,
  612. BASE64_ENCODE_MULTILINE);
  613. /* Return length doesn't count the NUL byte. */
  614. tor_assert(ret_len == (enc_b64_len - 1));
  615. tor_free(encrypted_blob);
  616. *encrypted_blob_out = enc_b64;
  617. }
  618. /* Success! */
  619. ret = 0;
  620. err:
  621. SMARTLIST_FOREACH(lines, char *, l, tor_free(l));
  622. smartlist_free(lines);
  623. return ret;
  624. }
  625. /* Encode a v3 HS descriptor. Return 0 on success and set encoded_out to the
  626. * newly allocated string of the encoded descriptor. On error, -1 is returned
  627. * and encoded_out is untouched. */
  628. static int
  629. desc_encode_v3(const hs_descriptor_t *desc,
  630. const ed25519_keypair_t *signing_kp, char **encoded_out)
  631. {
  632. int ret = -1;
  633. char *encoded_str = NULL;
  634. size_t encoded_len;
  635. smartlist_t *lines = smartlist_new();
  636. tor_assert(desc);
  637. tor_assert(signing_kp);
  638. tor_assert(encoded_out);
  639. tor_assert(desc->plaintext_data.version == 3);
  640. /* Build the non-encrypted values. */
  641. {
  642. char *encoded_cert;
  643. /* Encode certificate then create the first line of the descriptor. */
  644. if (desc->plaintext_data.signing_key_cert->cert_type
  645. != CERT_TYPE_SIGNING_HS_DESC) {
  646. log_err(LD_BUG, "HS descriptor signing key has an unexpected cert type "
  647. "(%d)", (int) desc->plaintext_data.signing_key_cert->cert_type);
  648. goto err;
  649. }
  650. if (tor_cert_encode_ed22519(desc->plaintext_data.signing_key_cert,
  651. &encoded_cert) < 0) {
  652. /* The function will print error logs. */
  653. goto err;
  654. }
  655. /* Create the hs descriptor line. */
  656. smartlist_add_asprintf(lines, "%s %" PRIu32, str_hs_desc,
  657. desc->plaintext_data.version);
  658. /* Add the descriptor lifetime line (in minutes). */
  659. smartlist_add_asprintf(lines, "%s %" PRIu32, str_lifetime,
  660. desc->plaintext_data.lifetime_sec / 60);
  661. /* Create the descriptor certificate line. */
  662. smartlist_add_asprintf(lines, "%s\n%s", str_desc_cert, encoded_cert);
  663. tor_free(encoded_cert);
  664. /* Create the revision counter line. */
  665. smartlist_add_asprintf(lines, "%s %" PRIu64, str_rev_counter,
  666. desc->plaintext_data.revision_counter);
  667. }
  668. /* Build the encrypted data section. */
  669. {
  670. char *enc_b64_blob=NULL;
  671. if (encode_encrypted_data(desc, &enc_b64_blob) < 0) {
  672. goto err;
  673. }
  674. smartlist_add_asprintf(lines,
  675. "%s\n"
  676. "-----BEGIN MESSAGE-----\n"
  677. "%s"
  678. "-----END MESSAGE-----",
  679. str_encrypted, enc_b64_blob);
  680. tor_free(enc_b64_blob);
  681. }
  682. /* Join all lines in one string so we can generate a signature and append
  683. * it to the descriptor. */
  684. encoded_str = smartlist_join_strings(lines, "\n", 1, &encoded_len);
  685. /* Sign all fields of the descriptor with our short term signing key. */
  686. {
  687. ed25519_signature_t sig;
  688. char ed_sig_b64[ED25519_SIG_BASE64_LEN + 1];
  689. if (ed25519_sign_prefixed(&sig,
  690. (const uint8_t *) encoded_str, encoded_len,
  691. str_desc_sig_prefix, signing_kp) < 0) {
  692. log_warn(LD_BUG, "Can't sign encoded HS descriptor!");
  693. tor_free(encoded_str);
  694. goto err;
  695. }
  696. if (ed25519_signature_to_base64(ed_sig_b64, &sig) < 0) {
  697. log_warn(LD_BUG, "Can't base64 encode descriptor signature!");
  698. tor_free(encoded_str);
  699. goto err;
  700. }
  701. /* Create the signature line. */
  702. smartlist_add_asprintf(lines, "%s %s", str_signature, ed_sig_b64);
  703. }
  704. /* Free previous string that we used so compute the signature. */
  705. tor_free(encoded_str);
  706. encoded_str = smartlist_join_strings(lines, "\n", 1, NULL);
  707. *encoded_out = encoded_str;
  708. /* XXX: Trigger a control port event. */
  709. /* Success! */
  710. ret = 0;
  711. err:
  712. SMARTLIST_FOREACH(lines, char *, l, tor_free(l));
  713. smartlist_free(lines);
  714. return ret;
  715. }
  716. /* === DECODING === */
  717. /* Given an encoded string of the link specifiers, return a newly allocated
  718. * list of decoded link specifiers. Return NULL on error. */
  719. STATIC smartlist_t *
  720. decode_link_specifiers(const char *encoded)
  721. {
  722. int decoded_len;
  723. size_t encoded_len, i;
  724. uint8_t *decoded;
  725. smartlist_t *results = NULL;
  726. link_specifier_list_t *specs = NULL;
  727. tor_assert(encoded);
  728. encoded_len = strlen(encoded);
  729. decoded = tor_malloc(encoded_len);
  730. decoded_len = base64_decode((char *) decoded, encoded_len, encoded,
  731. encoded_len);
  732. if (decoded_len < 0) {
  733. goto err;
  734. }
  735. if (link_specifier_list_parse(&specs, decoded,
  736. (size_t) decoded_len) < decoded_len) {
  737. goto err;
  738. }
  739. tor_assert(specs);
  740. results = smartlist_new();
  741. for (i = 0; i < link_specifier_list_getlen_spec(specs); i++) {
  742. hs_desc_link_specifier_t *hs_spec;
  743. link_specifier_t *ls = link_specifier_list_get_spec(specs, i);
  744. tor_assert(ls);
  745. hs_spec = tor_malloc_zero(sizeof(*hs_spec));
  746. hs_spec->type = link_specifier_get_ls_type(ls);
  747. switch (hs_spec->type) {
  748. case LS_IPV4:
  749. tor_addr_from_ipv4h(&hs_spec->u.ap.addr,
  750. link_specifier_get_un_ipv4_addr(ls));
  751. hs_spec->u.ap.port = link_specifier_get_un_ipv4_port(ls);
  752. break;
  753. case LS_IPV6:
  754. tor_addr_from_ipv6_bytes(&hs_spec->u.ap.addr, (const char *)
  755. link_specifier_getarray_un_ipv6_addr(ls));
  756. hs_spec->u.ap.port = link_specifier_get_un_ipv6_port(ls);
  757. break;
  758. case LS_LEGACY_ID:
  759. /* Both are known at compile time so let's make sure they are the same
  760. * else we can copy memory out of bound. */
  761. tor_assert(link_specifier_getlen_un_legacy_id(ls) ==
  762. sizeof(hs_spec->u.legacy_id));
  763. memcpy(hs_spec->u.legacy_id, link_specifier_getarray_un_legacy_id(ls),
  764. sizeof(hs_spec->u.legacy_id));
  765. break;
  766. default:
  767. goto err;
  768. }
  769. smartlist_add(results, hs_spec);
  770. }
  771. goto done;
  772. err:
  773. if (results) {
  774. SMARTLIST_FOREACH(results, hs_desc_link_specifier_t *, s, tor_free(s));
  775. smartlist_free(results);
  776. results = NULL;
  777. }
  778. done:
  779. link_specifier_list_free(specs);
  780. tor_free(decoded);
  781. return results;
  782. }
  783. /* Given a list of authentication types, decode it and put it in the encrypted
  784. * data section. Return 1 if we at least know one of the type or 0 if we know
  785. * none of them. */
  786. static int
  787. decode_auth_type(hs_desc_encrypted_data_t *desc, const char *list)
  788. {
  789. int match = 0;
  790. tor_assert(desc);
  791. tor_assert(list);
  792. desc->auth_types = smartlist_new();
  793. smartlist_split_string(desc->auth_types, list, " ", 0, 0);
  794. /* Validate the types that we at least know about one. */
  795. SMARTLIST_FOREACH_BEGIN(desc->auth_types, const char *, auth) {
  796. for (int idx = 0; auth_types[idx].identifier; idx++) {
  797. if (!strncmp(auth, auth_types[idx].identifier,
  798. strlen(auth_types[idx].identifier))) {
  799. match = 1;
  800. break;
  801. }
  802. }
  803. } SMARTLIST_FOREACH_END(auth);
  804. return match;
  805. }
  806. /* Parse a space-delimited list of integers representing CREATE2 formats into
  807. * the bitfield in hs_desc_encrypted_data_t. Ignore unrecognized values. */
  808. static void
  809. decode_create2_list(hs_desc_encrypted_data_t *desc, const char *list)
  810. {
  811. smartlist_t *tokens;
  812. tor_assert(desc);
  813. tor_assert(list);
  814. tokens = smartlist_new();
  815. smartlist_split_string(tokens, list, " ", 0, 0);
  816. SMARTLIST_FOREACH_BEGIN(tokens, char *, s) {
  817. int ok;
  818. unsigned long type = tor_parse_ulong(s, 10, 1, UINT16_MAX, &ok, NULL);
  819. if (!ok) {
  820. log_warn(LD_REND, "Unparseable value %s in create2 list", escaped(s));
  821. continue;
  822. }
  823. switch (type) {
  824. case ONION_HANDSHAKE_TYPE_NTOR:
  825. desc->create2_ntor = 1;
  826. break;
  827. default:
  828. /* We deliberately ignore unsupported handshake types */
  829. continue;
  830. }
  831. } SMARTLIST_FOREACH_END(s);
  832. SMARTLIST_FOREACH(tokens, char *, s, tor_free(s));
  833. smartlist_free(tokens);
  834. }
  835. /* Given a certificate, validate the certificate for certain conditions which
  836. * are if the given type matches the cert's one, if the signing key is
  837. * included and if the that key was actually used to sign the certificate.
  838. *
  839. * Return 1 iff if all conditions pass or 0 if one of them fails. */
  840. STATIC int
  841. cert_is_valid(tor_cert_t *cert, uint8_t type, const char *log_obj_type)
  842. {
  843. tor_assert(log_obj_type);
  844. if (cert == NULL) {
  845. log_warn(LD_REND, "Certificate for %s couldn't be parsed.", log_obj_type);
  846. goto err;
  847. }
  848. if (cert->cert_type != type) {
  849. log_warn(LD_REND, "Invalid cert type %02x for %s.", cert->cert_type,
  850. log_obj_type);
  851. goto err;
  852. }
  853. /* All certificate must have its signing key included. */
  854. if (!cert->signing_key_included) {
  855. log_warn(LD_REND, "Signing key is NOT included for %s.", log_obj_type);
  856. goto err;
  857. }
  858. /* The following will not only check if the signature matches but also the
  859. * expiration date and overall validity. */
  860. if (tor_cert_checksig(cert, &cert->signing_key, time(NULL)) < 0) {
  861. log_warn(LD_REND, "Invalid signature for %s.", log_obj_type);
  862. goto err;
  863. }
  864. return 1;
  865. err:
  866. return 0;
  867. }
  868. /* Given some binary data, try to parse it to get a certificate object. If we
  869. * have a valid cert, validate it using the given wanted type. On error, print
  870. * a log using the err_msg has the certificate identifier adding semantic to
  871. * the log and cert_out is set to NULL. On success, 0 is returned and cert_out
  872. * points to a newly allocated certificate object. */
  873. static int
  874. cert_parse_and_validate(tor_cert_t **cert_out, const char *data,
  875. size_t data_len, unsigned int cert_type_wanted,
  876. const char *err_msg)
  877. {
  878. tor_cert_t *cert;
  879. tor_assert(cert_out);
  880. tor_assert(data);
  881. tor_assert(err_msg);
  882. /* Parse certificate. */
  883. cert = tor_cert_parse((const uint8_t *) data, data_len);
  884. if (!cert) {
  885. log_warn(LD_REND, "Certificate for %s couldn't be parsed.", err_msg);
  886. goto err;
  887. }
  888. /* Validate certificate. */
  889. if (!cert_is_valid(cert, cert_type_wanted, err_msg)) {
  890. goto err;
  891. }
  892. *cert_out = cert;
  893. return 0;
  894. err:
  895. tor_cert_free(cert);
  896. *cert_out = NULL;
  897. return -1;
  898. }
  899. /* Return true iff the given length of the encrypted data of a descriptor
  900. * passes validation. */
  901. STATIC int
  902. encrypted_data_length_is_valid(size_t len)
  903. {
  904. /* Check for the minimum length possible. */
  905. if (len < HS_DESC_ENCRYPTED_MIN_LEN) {
  906. log_warn(LD_REND, "Length of descriptor's encrypted data is too small. "
  907. "Got %lu but minimum value is %d",
  908. (unsigned long)len, HS_DESC_ENCRYPTED_MIN_LEN);
  909. goto err;
  910. }
  911. /* Encrypted data has the salt and MAC concatenated to it so remove those
  912. * from the validation calculation. */
  913. len -= HS_DESC_ENCRYPTED_SALT_LEN + DIGEST256_LEN;
  914. /* Check that it's aligned on the block size of the crypto algorithm. */
  915. if (len % HS_DESC_PLAINTEXT_PADDING_MULTIPLE) {
  916. log_warn(LD_REND, "Length of descriptor's encrypted data is invalid. "
  917. "Got %lu which is not a multiple of %d.",
  918. (unsigned long) len, HS_DESC_PLAINTEXT_PADDING_MULTIPLE);
  919. goto err;
  920. }
  921. /* XXX: Check maximum size. Will strongly depends on the maximum intro point
  922. * allowed we decide on and probably if they will all have to use the legacy
  923. * key which is bigger than the ed25519 key. */
  924. return 1;
  925. err:
  926. return 0;
  927. }
  928. /* Decrypt the encrypted section of the descriptor using the given descriptor
  929. * object desc. A newly allocated NUL terminated string is put in
  930. * decrypted_out. Return the length of decrypted_out on success else 0 is
  931. * returned and decrypted_out is set to NULL. */
  932. static size_t
  933. desc_decrypt_data_v3(const hs_descriptor_t *desc, char **decrypted_out)
  934. {
  935. uint8_t *decrypted = NULL;
  936. uint8_t secret_key[CIPHER_KEY_LEN], secret_iv[CIPHER_IV_LEN];
  937. uint8_t mac_key[DIGEST256_LEN], our_mac[DIGEST256_LEN];
  938. const uint8_t *salt, *encrypted, *desc_mac;
  939. size_t encrypted_len, result_len = 0;
  940. tor_assert(decrypted_out);
  941. tor_assert(desc);
  942. tor_assert(desc->plaintext_data.encrypted_blob);
  943. /* Construction is as follow: SALT | ENCRYPTED_DATA | MAC */
  944. if (!encrypted_data_length_is_valid(
  945. desc->plaintext_data.encrypted_blob_size)) {
  946. goto err;
  947. }
  948. /* Start of the blob thus the salt. */
  949. salt = desc->plaintext_data.encrypted_blob;
  950. /* Next is the encrypted data. */
  951. encrypted = desc->plaintext_data.encrypted_blob +
  952. HS_DESC_ENCRYPTED_SALT_LEN;
  953. encrypted_len = desc->plaintext_data.encrypted_blob_size -
  954. (HS_DESC_ENCRYPTED_SALT_LEN + DIGEST256_LEN);
  955. /* At the very end is the MAC. Make sure it's of the right size. */
  956. {
  957. desc_mac = encrypted + encrypted_len;
  958. size_t desc_mac_size = desc->plaintext_data.encrypted_blob_size -
  959. (desc_mac - desc->plaintext_data.encrypted_blob);
  960. if (desc_mac_size != DIGEST256_LEN) {
  961. log_warn(LD_REND, "Service descriptor MAC length of encrypted data "
  962. "is invalid (%lu, expected %u)",
  963. (unsigned long) desc_mac_size, DIGEST256_LEN);
  964. goto err;
  965. }
  966. }
  967. /* KDF construction resulting in a key from which the secret key, IV and MAC
  968. * key are extracted which is what we need for the decryption. */
  969. build_secret_key_iv_mac(desc, salt, HS_DESC_ENCRYPTED_SALT_LEN,
  970. secret_key, sizeof(secret_key),
  971. secret_iv, sizeof(secret_iv),
  972. mac_key, sizeof(mac_key));
  973. /* Build MAC. */
  974. build_mac(mac_key, sizeof(mac_key), salt, HS_DESC_ENCRYPTED_SALT_LEN,
  975. encrypted, encrypted_len, our_mac, sizeof(our_mac));
  976. memwipe(mac_key, 0, sizeof(mac_key));
  977. /* Verify MAC; MAC is H(mac_key || salt || encrypted)
  978. *
  979. * This is a critical check that is making sure the computed MAC matches the
  980. * one in the descriptor. */
  981. if (!tor_memeq(our_mac, desc_mac, sizeof(our_mac))) {
  982. log_warn(LD_REND, "Encrypted service descriptor MAC check failed");
  983. goto err;
  984. }
  985. {
  986. /* Decrypt. Here we are assured that the encrypted length is valid for
  987. * decryption. */
  988. crypto_cipher_t *cipher;
  989. cipher = crypto_cipher_new_with_iv((const char *) secret_key,
  990. (const char *) secret_iv);
  991. /* Extra byte for the NUL terminated byte. */
  992. decrypted = tor_malloc_zero(encrypted_len + 1);
  993. crypto_cipher_decrypt(cipher, (char *) decrypted,
  994. (const char *) encrypted, encrypted_len);
  995. crypto_cipher_free(cipher);
  996. }
  997. {
  998. /* Adjust length to remove NULL padding bytes */
  999. uint8_t *end = memchr(decrypted, 0, encrypted_len);
  1000. result_len = encrypted_len;
  1001. if (end) {
  1002. result_len = end - decrypted;
  1003. }
  1004. }
  1005. /* Make sure to NUL terminate the string. */
  1006. decrypted[encrypted_len] = '\0';
  1007. *decrypted_out = (char *) decrypted;
  1008. goto done;
  1009. err:
  1010. if (decrypted) {
  1011. tor_free(decrypted);
  1012. }
  1013. *decrypted_out = NULL;
  1014. result_len = 0;
  1015. done:
  1016. memwipe(secret_key, 0, sizeof(secret_key));
  1017. memwipe(secret_iv, 0, sizeof(secret_iv));
  1018. return result_len;
  1019. }
  1020. /* Given the start of a section and the end of it, decode a single
  1021. * introduction point from that section. Return a newly allocated introduction
  1022. * point object containing the decoded data. Return NULL if the section can't
  1023. * be decoded. */
  1024. STATIC hs_desc_intro_point_t *
  1025. decode_introduction_point(const hs_descriptor_t *desc, const char *start)
  1026. {
  1027. hs_desc_intro_point_t *ip = NULL;
  1028. memarea_t *area = NULL;
  1029. smartlist_t *tokens = NULL;
  1030. tor_cert_t *cross_cert = NULL;
  1031. const directory_token_t *tok;
  1032. tor_assert(desc);
  1033. tor_assert(start);
  1034. area = memarea_new();
  1035. tokens = smartlist_new();
  1036. if (tokenize_string(area, start, start + strlen(start),
  1037. tokens, hs_desc_intro_point_v3_token_table, 0) < 0) {
  1038. log_warn(LD_REND, "Introduction point is not parseable");
  1039. goto err;
  1040. }
  1041. /* Ok we seem to have a well formed section containing enough tokens to
  1042. * parse. Allocate our IP object and try to populate it. */
  1043. ip = tor_malloc_zero(sizeof(hs_desc_intro_point_t));
  1044. /* "introduction-point" SP link-specifiers NL */
  1045. tok = find_by_keyword(tokens, R3_INTRODUCTION_POINT);
  1046. tor_assert(tok->n_args == 1);
  1047. ip->link_specifiers = decode_link_specifiers(tok->args[0]);
  1048. if (!ip->link_specifiers) {
  1049. log_warn(LD_REND, "Introduction point has invalid link specifiers");
  1050. goto err;
  1051. }
  1052. /* "auth-key" NL certificate NL */
  1053. tok = find_by_keyword(tokens, R3_INTRO_AUTH_KEY);
  1054. tor_assert(tok->object_body);
  1055. if (strcmp(tok->object_type, "ED25519 CERT")) {
  1056. log_warn(LD_REND, "Unexpected object type for introduction auth key");
  1057. goto err;
  1058. }
  1059. /* Parse cert and do some validation. */
  1060. if (cert_parse_and_validate(&ip->auth_key_cert, tok->object_body,
  1061. tok->object_size, CERT_TYPE_AUTH_HS_IP_KEY,
  1062. "introduction point auth-key") < 0) {
  1063. goto err;
  1064. }
  1065. /* Exactly one "enc-key" ... */
  1066. tok = find_by_keyword(tokens, R3_INTRO_ENC_KEY);
  1067. if (!strcmp(tok->args[0], "ntor")) {
  1068. /* "enc-key" SP "ntor" SP key NL */
  1069. if (tok->n_args != 2 || tok->object_body) {
  1070. log_warn(LD_REND, "Introduction point ntor encryption key is invalid");
  1071. goto err;
  1072. }
  1073. if (curve25519_public_from_base64(&ip->enc_key.curve25519.pubkey,
  1074. tok->args[1]) < 0) {
  1075. log_warn(LD_REND, "Introduction point ntor encryption key is invalid");
  1076. goto err;
  1077. }
  1078. ip->enc_key_type = HS_DESC_KEY_TYPE_CURVE25519;
  1079. } else if (!strcmp(tok->args[0], "legacy")) {
  1080. /* "enc-key" SP "legacy" NL key NL */
  1081. if (!tok->key) {
  1082. log_warn(LD_REND, "Introduction point legacy encryption key is "
  1083. "invalid");
  1084. goto err;
  1085. }
  1086. ip->enc_key.legacy = crypto_pk_dup_key(tok->key);
  1087. ip->enc_key_type = HS_DESC_KEY_TYPE_LEGACY;
  1088. } else {
  1089. /* Unknown key type so we can't use that introduction point. */
  1090. log_warn(LD_REND, "Introduction point encryption key is unrecognized.");
  1091. goto err;
  1092. }
  1093. /* "enc-key-certification" NL certificate NL */
  1094. tok = find_by_keyword(tokens, R3_INTRO_ENC_KEY_CERTIFICATION);
  1095. tor_assert(tok->object_body);
  1096. /* Do the cross certification. */
  1097. switch (ip->enc_key_type) {
  1098. case HS_DESC_KEY_TYPE_CURVE25519:
  1099. {
  1100. if (strcmp(tok->object_type, "ED25519 CERT")) {
  1101. log_warn(LD_REND, "Introduction point ntor encryption key "
  1102. "cross-certification has an unknown format.");
  1103. goto err;
  1104. }
  1105. if (cert_parse_and_validate(&cross_cert, tok->object_body,
  1106. tok->object_size, CERT_TYPE_CROSS_HS_IP_KEYS,
  1107. "introduction point enc-key-certification") < 0) {
  1108. goto err;
  1109. }
  1110. break;
  1111. }
  1112. case HS_DESC_KEY_TYPE_LEGACY:
  1113. if (strcmp(tok->object_type, "CROSSCERT")) {
  1114. log_warn(LD_REND, "Introduction point legacy encryption key "
  1115. "cross-certification has an unknown format.");
  1116. goto err;
  1117. }
  1118. if (rsa_ed25519_crosscert_check((const uint8_t *) tok->object_body,
  1119. tok->object_size, ip->enc_key.legacy,
  1120. &desc->plaintext_data.signing_key_cert->signed_key,
  1121. approx_time()-86400)) {
  1122. log_warn(LD_REND, "Unable to check cross-certification on the "
  1123. "introduction point legacy encryption key.");
  1124. goto err;
  1125. }
  1126. break;
  1127. default:
  1128. tor_assert(0);
  1129. break;
  1130. }
  1131. /* It is successfully cross certified. Flag the object. */
  1132. ip->cross_certified = 1;
  1133. goto done;
  1134. err:
  1135. desc_intro_point_free(ip);
  1136. ip = NULL;
  1137. done:
  1138. tor_cert_free(cross_cert);
  1139. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1140. smartlist_free(tokens);
  1141. memarea_drop_all(area);
  1142. return ip;
  1143. }
  1144. /* Given a descriptor string at <b>data</b>, decode all possible introduction
  1145. * points that we can find. Add the introduction point object to desc_enc as we
  1146. * find them. Return 0 on success.
  1147. *
  1148. * On error, a negative value is returned. It is possible that some intro
  1149. * point object have been added to the desc_enc, they should be considered
  1150. * invalid. One single bad encoded introduction point will make this function
  1151. * return an error. */
  1152. STATIC int
  1153. decode_intro_points(const hs_descriptor_t *desc,
  1154. hs_desc_encrypted_data_t *desc_enc,
  1155. const char *data)
  1156. {
  1157. int retval = -1;
  1158. smartlist_t *chunked_desc = smartlist_new();
  1159. smartlist_t *intro_points = smartlist_new();
  1160. tor_assert(desc);
  1161. tor_assert(desc_enc);
  1162. tor_assert(data);
  1163. tor_assert(desc_enc->intro_points);
  1164. /* Take the desc string, and extract the intro point substrings out of it */
  1165. {
  1166. /* Split the descriptor string using the intro point header as delimiter */
  1167. smartlist_split_string(chunked_desc, data, str_intro_point_start, 0, 0);
  1168. /* Check if there are actually any intro points included. The first chunk
  1169. * should be other descriptor fields (e.g. create2-formats), so it's not an
  1170. * intro point. */
  1171. if (smartlist_len(chunked_desc) < 2) {
  1172. goto done;
  1173. }
  1174. }
  1175. /* Take the intro point substrings, and prepare them for parsing */
  1176. {
  1177. int i = 0;
  1178. /* Prepend the introduction-point header to all the chunks, since
  1179. smartlist_split_string() devoured it. */
  1180. SMARTLIST_FOREACH_BEGIN(chunked_desc, char *, chunk) {
  1181. /* Ignore first chunk. It's other descriptor fields. */
  1182. if (i++ == 0) {
  1183. continue;
  1184. }
  1185. smartlist_add_asprintf(intro_points, "%s %s", str_intro_point, chunk);
  1186. } SMARTLIST_FOREACH_END(chunk);
  1187. }
  1188. /* Parse the intro points! */
  1189. SMARTLIST_FOREACH_BEGIN(intro_points, const char *, intro_point) {
  1190. hs_desc_intro_point_t *ip = decode_introduction_point(desc, intro_point);
  1191. if (!ip) {
  1192. /* Malformed introduction point section. Stop right away, this
  1193. * descriptor shouldn't be used. */
  1194. goto err;
  1195. }
  1196. smartlist_add(desc_enc->intro_points, ip);
  1197. } SMARTLIST_FOREACH_END(intro_point);
  1198. done:
  1199. retval = 0;
  1200. err:
  1201. SMARTLIST_FOREACH(chunked_desc, char *, a, tor_free(a));
  1202. smartlist_free(chunked_desc);
  1203. SMARTLIST_FOREACH(intro_points, char *, a, tor_free(a));
  1204. smartlist_free(intro_points);
  1205. return retval;
  1206. }
  1207. /* Return 1 iff the given base64 encoded signature in b64_sig from the encoded
  1208. * descriptor in encoded_desc validates the descriptor content. */
  1209. STATIC int
  1210. desc_sig_is_valid(const char *b64_sig,
  1211. const ed25519_public_key_t *signing_pubkey,
  1212. const char *encoded_desc, size_t encoded_len)
  1213. {
  1214. int ret = 0;
  1215. ed25519_signature_t sig;
  1216. const char *sig_start;
  1217. tor_assert(b64_sig);
  1218. tor_assert(signing_pubkey);
  1219. tor_assert(encoded_desc);
  1220. /* Verifying nothing won't end well :). */
  1221. tor_assert(encoded_len > 0);
  1222. /* Signature length check. */
  1223. if (strlen(b64_sig) != ED25519_SIG_BASE64_LEN) {
  1224. log_warn(LD_REND, "Service descriptor has an invalid signature length."
  1225. "Exptected %d but got %lu",
  1226. ED25519_SIG_BASE64_LEN, (unsigned long) strlen(b64_sig));
  1227. goto err;
  1228. }
  1229. /* First, convert base64 blob to an ed25519 signature. */
  1230. if (ed25519_signature_from_base64(&sig, b64_sig) != 0) {
  1231. log_warn(LD_REND, "Service descriptor does not contain a valid "
  1232. "signature");
  1233. goto err;
  1234. }
  1235. /* Find the start of signature. */
  1236. sig_start = tor_memstr(encoded_desc, encoded_len, "\n" str_signature);
  1237. /* Getting here means the token parsing worked for the signature so if we
  1238. * can't find the start of the signature, we have a code flow issue. */
  1239. if (BUG(!sig_start)) {
  1240. goto err;
  1241. }
  1242. /* Skip newline, it has to go in the signature check. */
  1243. sig_start++;
  1244. /* Validate signature with the full body of the descriptor. */
  1245. if (ed25519_checksig_prefixed(&sig,
  1246. (const uint8_t *) encoded_desc,
  1247. sig_start - encoded_desc,
  1248. str_desc_sig_prefix,
  1249. signing_pubkey) != 0) {
  1250. log_warn(LD_REND, "Invalid signature on service descriptor");
  1251. goto err;
  1252. }
  1253. /* Valid signature! All is good. */
  1254. ret = 1;
  1255. err:
  1256. return ret;
  1257. }
  1258. /* Decode descriptor plaintext data for version 3. Given a list of tokens, an
  1259. * allocated plaintext object that will be populated and the encoded
  1260. * descriptor with its length. The last one is needed for signature
  1261. * verification. Unknown tokens are simply ignored so this won't error on
  1262. * unknowns but requires that all v3 token be present and valid.
  1263. *
  1264. * Return 0 on success else a negative value. */
  1265. static int
  1266. desc_decode_plaintext_v3(smartlist_t *tokens,
  1267. hs_desc_plaintext_data_t *desc,
  1268. const char *encoded_desc, size_t encoded_len)
  1269. {
  1270. int ok;
  1271. directory_token_t *tok;
  1272. tor_assert(tokens);
  1273. tor_assert(desc);
  1274. /* Version higher could still use this function to decode most of the
  1275. * descriptor and then they decode the extra part. */
  1276. tor_assert(desc->version >= 3);
  1277. /* Descriptor lifetime parsing. */
  1278. tok = find_by_keyword(tokens, R3_DESC_LIFETIME);
  1279. tor_assert(tok->n_args == 1);
  1280. desc->lifetime_sec = (uint32_t) tor_parse_ulong(tok->args[0], 10, 0,
  1281. UINT32_MAX, &ok, NULL);
  1282. if (!ok) {
  1283. log_warn(LD_REND, "Service descriptor lifetime value is invalid");
  1284. goto err;
  1285. }
  1286. /* Put it from minute to second. */
  1287. desc->lifetime_sec *= 60;
  1288. if (desc->lifetime_sec > HS_DESC_MAX_LIFETIME) {
  1289. log_warn(LD_REND, "Service descriptor lifetime is too big. "
  1290. "Got %" PRIu32 " but max is %d",
  1291. desc->lifetime_sec, HS_DESC_MAX_LIFETIME);
  1292. goto err;
  1293. }
  1294. /* Descriptor signing certificate. */
  1295. tok = find_by_keyword(tokens, R3_DESC_SIGNING_CERT);
  1296. tor_assert(tok->object_body);
  1297. /* Expecting a prop220 cert with the signing key extension, which contains
  1298. * the blinded public key. */
  1299. if (strcmp(tok->object_type, "ED25519 CERT") != 0) {
  1300. log_warn(LD_REND, "Service descriptor signing cert wrong type (%s)",
  1301. escaped(tok->object_type));
  1302. goto err;
  1303. }
  1304. if (cert_parse_and_validate(&desc->signing_key_cert, tok->object_body,
  1305. tok->object_size, CERT_TYPE_SIGNING_HS_DESC,
  1306. "service descriptor signing key") < 0) {
  1307. goto err;
  1308. }
  1309. /* Copy the public keys into signing_pubkey and blinded_pubkey */
  1310. memcpy(&desc->signing_pubkey, &desc->signing_key_cert->signed_key,
  1311. sizeof(ed25519_public_key_t));
  1312. memcpy(&desc->blinded_pubkey, &desc->signing_key_cert->signing_key,
  1313. sizeof(ed25519_public_key_t));
  1314. /* Extract revision counter value. */
  1315. tok = find_by_keyword(tokens, R3_REVISION_COUNTER);
  1316. tor_assert(tok->n_args == 1);
  1317. desc->revision_counter = tor_parse_uint64(tok->args[0], 10, 0,
  1318. UINT64_MAX, &ok, NULL);
  1319. if (!ok) {
  1320. log_warn(LD_REND, "Service descriptor revision-counter is invalid");
  1321. goto err;
  1322. }
  1323. /* Extract the encrypted data section. */
  1324. tok = find_by_keyword(tokens, R3_ENCRYPTED);
  1325. tor_assert(tok->object_body);
  1326. if (strcmp(tok->object_type, "MESSAGE") != 0) {
  1327. log_warn(LD_REND, "Service descriptor encrypted data section is invalid");
  1328. goto err;
  1329. }
  1330. /* Make sure the length of the encrypted blob is valid. */
  1331. if (!encrypted_data_length_is_valid(tok->object_size)) {
  1332. goto err;
  1333. }
  1334. /* Copy the encrypted blob to the descriptor object so we can handle it
  1335. * latter if needed. */
  1336. desc->encrypted_blob = tor_memdup(tok->object_body, tok->object_size);
  1337. desc->encrypted_blob_size = tok->object_size;
  1338. /* Extract signature and verify it. */
  1339. tok = find_by_keyword(tokens, R3_SIGNATURE);
  1340. tor_assert(tok->n_args == 1);
  1341. /* First arg here is the actual encoded signature. */
  1342. if (!desc_sig_is_valid(tok->args[0], &desc->signing_pubkey,
  1343. encoded_desc, encoded_len)) {
  1344. goto err;
  1345. }
  1346. return 0;
  1347. err:
  1348. return -1;
  1349. }
  1350. /* Decode the version 3 encrypted section of the given descriptor desc. The
  1351. * desc_encrypted_out will be populated with the decoded data. Return 0 on
  1352. * success else -1. */
  1353. static int
  1354. desc_decode_encrypted_v3(const hs_descriptor_t *desc,
  1355. hs_desc_encrypted_data_t *desc_encrypted_out)
  1356. {
  1357. int result = -1;
  1358. char *message = NULL;
  1359. size_t message_len;
  1360. memarea_t *area = NULL;
  1361. directory_token_t *tok;
  1362. smartlist_t *tokens = NULL;
  1363. tor_assert(desc);
  1364. tor_assert(desc_encrypted_out);
  1365. /* Decrypt the encrypted data that is located in the plaintext section in
  1366. * the descriptor as a blob of bytes. The following functions will use the
  1367. * keys found in the same section. */
  1368. message_len = desc_decrypt_data_v3(desc, &message);
  1369. if (!message_len) {
  1370. log_warn(LD_REND, "Service descriptor decryption failed.");
  1371. goto err;
  1372. }
  1373. tor_assert(message);
  1374. area = memarea_new();
  1375. tokens = smartlist_new();
  1376. if (tokenize_string(area, message, message + message_len,
  1377. tokens, hs_desc_encrypted_v3_token_table, 0) < 0) {
  1378. log_warn(LD_REND, "Encrypted service descriptor is not parseable.");
  1379. goto err;
  1380. }
  1381. /* CREATE2 supported cell format. It's mandatory. */
  1382. tok = find_by_keyword(tokens, R3_CREATE2_FORMATS);
  1383. tor_assert(tok);
  1384. decode_create2_list(desc_encrypted_out, tok->args[0]);
  1385. /* Must support ntor according to the specification */
  1386. if (!desc_encrypted_out->create2_ntor) {
  1387. log_warn(LD_REND, "Service create2-formats does not include ntor.");
  1388. goto err;
  1389. }
  1390. /* Authentication type. It's optional but only once. */
  1391. tok = find_opt_by_keyword(tokens, R3_AUTHENTICATION_REQUIRED);
  1392. if (tok) {
  1393. if (!decode_auth_type(desc_encrypted_out, tok->args[0])) {
  1394. log_warn(LD_REND, "Service descriptor authentication type has "
  1395. "invalid entry(ies).");
  1396. goto err;
  1397. }
  1398. }
  1399. /* Is this service a single onion service? */
  1400. tok = find_opt_by_keyword(tokens, R3_SINGLE_ONION_SERVICE);
  1401. if (tok) {
  1402. desc_encrypted_out->single_onion_service = 1;
  1403. }
  1404. /* Initialize the descriptor's introduction point list before we start
  1405. * decoding. Having 0 intro point is valid. Then decode them all. */
  1406. desc_encrypted_out->intro_points = smartlist_new();
  1407. if (decode_intro_points(desc, desc_encrypted_out, message) < 0) {
  1408. goto err;
  1409. }
  1410. /* Validation of maximum introduction points allowed. */
  1411. if (smartlist_len(desc_encrypted_out->intro_points) > MAX_INTRO_POINTS) {
  1412. log_warn(LD_REND, "Service descriptor contains too many introduction "
  1413. "points. Maximum allowed is %d but we have %d",
  1414. MAX_INTRO_POINTS,
  1415. smartlist_len(desc_encrypted_out->intro_points));
  1416. goto err;
  1417. }
  1418. /* NOTE: Unknown fields are allowed because this function could be used to
  1419. * decode other descriptor version. */
  1420. result = 0;
  1421. goto done;
  1422. err:
  1423. tor_assert(result < 0);
  1424. desc_encrypted_data_free_contents(desc_encrypted_out);
  1425. done:
  1426. if (tokens) {
  1427. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1428. smartlist_free(tokens);
  1429. }
  1430. if (area) {
  1431. memarea_drop_all(area);
  1432. }
  1433. if (message) {
  1434. tor_free(message);
  1435. }
  1436. return result;
  1437. }
  1438. /* Table of encrypted decode function version specific. The function are
  1439. * indexed by the version number so v3 callback is at index 3 in the array. */
  1440. static int
  1441. (*decode_encrypted_handlers[])(
  1442. const hs_descriptor_t *desc,
  1443. hs_desc_encrypted_data_t *desc_encrypted) =
  1444. {
  1445. /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
  1446. desc_decode_encrypted_v3,
  1447. };
  1448. /* Decode the encrypted data section of the given descriptor and store the
  1449. * data in the given encrypted data object. Return 0 on success else a
  1450. * negative value on error. */
  1451. int
  1452. hs_desc_decode_encrypted(const hs_descriptor_t *desc,
  1453. hs_desc_encrypted_data_t *desc_encrypted)
  1454. {
  1455. int ret;
  1456. uint32_t version;
  1457. tor_assert(desc);
  1458. /* Ease our life a bit. */
  1459. version = desc->plaintext_data.version;
  1460. tor_assert(desc_encrypted);
  1461. /* Calling this function without an encrypted blob to parse is a code flow
  1462. * error. The plaintext parsing should never succeed in the first place
  1463. * without an encrypted section. */
  1464. tor_assert(desc->plaintext_data.encrypted_blob);
  1465. /* Let's make sure we have a supported version as well. By correctly parsing
  1466. * the plaintext, this should not fail. */
  1467. if (BUG(!hs_desc_is_supported_version(version))) {
  1468. ret = -1;
  1469. goto err;
  1470. }
  1471. /* Extra precaution. Having no handler for the supported version should
  1472. * never happened else we forgot to add it but we bumped the version. */
  1473. tor_assert(ARRAY_LENGTH(decode_encrypted_handlers) >= version);
  1474. tor_assert(decode_encrypted_handlers[version]);
  1475. /* Run the version specific plaintext decoder. */
  1476. ret = decode_encrypted_handlers[version](desc, desc_encrypted);
  1477. if (ret < 0) {
  1478. goto err;
  1479. }
  1480. err:
  1481. return ret;
  1482. }
  1483. /* Table of plaintext decode function version specific. The function are
  1484. * indexed by the version number so v3 callback is at index 3 in the array. */
  1485. static int
  1486. (*decode_plaintext_handlers[])(
  1487. smartlist_t *tokens,
  1488. hs_desc_plaintext_data_t *desc,
  1489. const char *encoded_desc,
  1490. size_t encoded_len) =
  1491. {
  1492. /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
  1493. desc_decode_plaintext_v3,
  1494. };
  1495. /* Fully decode the given descriptor plaintext and store the data in the
  1496. * plaintext data object. Returns 0 on success else a negative value. */
  1497. int
  1498. hs_desc_decode_plaintext(const char *encoded,
  1499. hs_desc_plaintext_data_t *plaintext)
  1500. {
  1501. int ok = 0, ret = -1;
  1502. memarea_t *area = NULL;
  1503. smartlist_t *tokens = NULL;
  1504. size_t encoded_len;
  1505. directory_token_t *tok;
  1506. tor_assert(encoded);
  1507. tor_assert(plaintext);
  1508. encoded_len = strlen(encoded);
  1509. if (encoded_len >= HS_DESC_MAX_LEN) {
  1510. log_warn(LD_REND, "Service descriptor is too big (%lu bytes)",
  1511. (unsigned long) encoded_len);
  1512. goto err;
  1513. }
  1514. area = memarea_new();
  1515. tokens = smartlist_new();
  1516. /* Tokenize the descriptor so we can start to parse it. */
  1517. if (tokenize_string(area, encoded, encoded + encoded_len, tokens,
  1518. hs_desc_v3_token_table, 0) < 0) {
  1519. log_warn(LD_REND, "Service descriptor is not parseable");
  1520. goto err;
  1521. }
  1522. /* Get the version of the descriptor which is the first mandatory field of
  1523. * the descriptor. From there, we'll decode the right descriptor version. */
  1524. tok = find_by_keyword(tokens, R_HS_DESCRIPTOR);
  1525. tor_assert(tok->n_args == 1);
  1526. plaintext->version = (uint32_t) tor_parse_ulong(tok->args[0], 10, 0,
  1527. UINT32_MAX, &ok, NULL);
  1528. if (!ok) {
  1529. log_warn(LD_REND, "Service descriptor has unparseable version %s",
  1530. escaped(tok->args[0]));
  1531. goto err;
  1532. }
  1533. if (!hs_desc_is_supported_version(plaintext->version)) {
  1534. log_warn(LD_REND, "Service descriptor has unsupported version %" PRIu32,
  1535. plaintext->version);
  1536. goto err;
  1537. }
  1538. /* Extra precaution. Having no handler for the supported version should
  1539. * never happened else we forgot to add it but we bumped the version. */
  1540. tor_assert(ARRAY_LENGTH(decode_plaintext_handlers) >= plaintext->version);
  1541. tor_assert(decode_plaintext_handlers[plaintext->version]);
  1542. /* Run the version specific plaintext decoder. */
  1543. ret = decode_plaintext_handlers[plaintext->version](tokens, plaintext,
  1544. encoded, encoded_len);
  1545. if (ret < 0) {
  1546. goto err;
  1547. }
  1548. /* Success. Descriptor has been populated with the data. */
  1549. ret = 0;
  1550. err:
  1551. if (tokens) {
  1552. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
  1553. smartlist_free(tokens);
  1554. }
  1555. if (area) {
  1556. memarea_drop_all(area);
  1557. }
  1558. return ret;
  1559. }
  1560. /* Fully decode an encoded descriptor and set a newly allocated descriptor
  1561. * object in desc_out. Subcredentials are used if not NULL else it's ignored.
  1562. *
  1563. * Return 0 on success. A negative value is returned on error and desc_out is
  1564. * set to NULL. */
  1565. int
  1566. hs_desc_decode_descriptor(const char *encoded,
  1567. const uint8_t *subcredential,
  1568. hs_descriptor_t **desc_out)
  1569. {
  1570. int ret;
  1571. hs_descriptor_t *desc;
  1572. tor_assert(encoded);
  1573. desc = tor_malloc_zero(sizeof(hs_descriptor_t));
  1574. /* Subcredentials are optional. */
  1575. if (subcredential) {
  1576. memcpy(desc->subcredential, subcredential, sizeof(desc->subcredential));
  1577. }
  1578. ret = hs_desc_decode_plaintext(encoded, &desc->plaintext_data);
  1579. if (ret < 0) {
  1580. goto err;
  1581. }
  1582. ret = hs_desc_decode_encrypted(desc, &desc->encrypted_data);
  1583. if (ret < 0) {
  1584. goto err;
  1585. }
  1586. if (desc_out) {
  1587. *desc_out = desc;
  1588. } else {
  1589. hs_descriptor_free(desc);
  1590. }
  1591. return ret;
  1592. err:
  1593. hs_descriptor_free(desc);
  1594. if (desc_out) {
  1595. *desc_out = NULL;
  1596. }
  1597. tor_assert(ret < 0);
  1598. return ret;
  1599. }
  1600. /* Table of encode function version specific. The functions are indexed by the
  1601. * version number so v3 callback is at index 3 in the array. */
  1602. static int
  1603. (*encode_handlers[])(
  1604. const hs_descriptor_t *desc,
  1605. const ed25519_keypair_t *signing_kp,
  1606. char **encoded_out) =
  1607. {
  1608. /* v0 */ NULL, /* v1 */ NULL, /* v2 */ NULL,
  1609. desc_encode_v3,
  1610. };
  1611. /* Encode the given descriptor desc including signing with the given key pair
  1612. * signing_kp. On success, encoded_out points to a newly allocated NUL
  1613. * terminated string that contains the encoded descriptor as a string.
  1614. *
  1615. * Return 0 on success and encoded_out is a valid pointer. On error, -1 is
  1616. * returned and encoded_out is set to NULL. */
  1617. int
  1618. hs_desc_encode_descriptor(const hs_descriptor_t *desc,
  1619. const ed25519_keypair_t *signing_kp,
  1620. char **encoded_out)
  1621. {
  1622. int ret = -1;
  1623. uint32_t version;
  1624. tor_assert(desc);
  1625. tor_assert(encoded_out);
  1626. /* Make sure we support the version of the descriptor format. */
  1627. version = desc->plaintext_data.version;
  1628. if (!hs_desc_is_supported_version(version)) {
  1629. goto err;
  1630. }
  1631. /* Extra precaution. Having no handler for the supported version should
  1632. * never happened else we forgot to add it but we bumped the version. */
  1633. tor_assert(ARRAY_LENGTH(encode_handlers) >= version);
  1634. tor_assert(encode_handlers[version]);
  1635. ret = encode_handlers[version](desc, signing_kp, encoded_out);
  1636. if (ret < 0) {
  1637. goto err;
  1638. }
  1639. /* Try to decode what we just encoded. Symmetry is nice! */
  1640. ret = hs_desc_decode_descriptor(*encoded_out, desc->subcredential, NULL);
  1641. if (BUG(ret < 0)) {
  1642. goto err;
  1643. }
  1644. return 0;
  1645. err:
  1646. *encoded_out = NULL;
  1647. return ret;
  1648. }
  1649. /* Free the descriptor plaintext data object. */
  1650. void
  1651. hs_desc_plaintext_data_free(hs_desc_plaintext_data_t *desc)
  1652. {
  1653. desc_plaintext_data_free_contents(desc);
  1654. tor_free(desc);
  1655. }
  1656. /* Free the descriptor encrypted data object. */
  1657. void
  1658. hs_desc_encrypted_data_free(hs_desc_encrypted_data_t *desc)
  1659. {
  1660. desc_encrypted_data_free_contents(desc);
  1661. tor_free(desc);
  1662. }
  1663. /* Free the given descriptor object. */
  1664. void
  1665. hs_descriptor_free(hs_descriptor_t *desc)
  1666. {
  1667. if (!desc) {
  1668. return;
  1669. }
  1670. desc_plaintext_data_free_contents(&desc->plaintext_data);
  1671. desc_encrypted_data_free_contents(&desc->encrypted_data);
  1672. tor_free(desc);
  1673. }
  1674. /* Return the size in bytes of the given plaintext data object. A sizeof() is
  1675. * not enough because the object contains pointers and the encrypted blob.
  1676. * This is particularly useful for our OOM subsystem that tracks the HSDir
  1677. * cache size for instance. */
  1678. size_t
  1679. hs_desc_plaintext_obj_size(const hs_desc_plaintext_data_t *data)
  1680. {
  1681. tor_assert(data);
  1682. return (sizeof(*data) + sizeof(*data->signing_key_cert) +
  1683. data->encrypted_blob_size);
  1684. }