rendcommon.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2017, The Tor Project, Inc. */
  3. /* See LICENSE for licensing information */
  4. /**
  5. * \file rendcommon.c
  6. * \brief Rendezvous implementation: shared code between
  7. * introducers, services, clients, and rendezvous points.
  8. **/
  9. #define RENDCOMMON_PRIVATE
  10. #include "or.h"
  11. #include "circuitbuild.h"
  12. #include "circuitlist.h"
  13. #include "circuituse.h"
  14. #include "config.h"
  15. #include "control.h"
  16. #include "crypto_rand.h"
  17. #include "crypto_util.h"
  18. #include "hs_client.h"
  19. #include "hs_common.h"
  20. #include "hs_intropoint.h"
  21. #include "networkstatus.h"
  22. #include "rendclient.h"
  23. #include "rendcommon.h"
  24. #include "rendmid.h"
  25. #include "rendservice.h"
  26. #include "rephist.h"
  27. #include "router.h"
  28. #include "routerlist.h"
  29. #include "routerparse.h"
  30. #include "cpath_build_state_st.h"
  31. #include "crypt_path_st.h"
  32. #include "origin_circuit_st.h"
  33. /** Return 0 if one and two are the same service ids, else -1 or 1 */
  34. int
  35. rend_cmp_service_ids(const char *one, const char *two)
  36. {
  37. return strcasecmp(one,two);
  38. }
  39. /** Free the storage held by the service descriptor <b>desc</b>.
  40. */
  41. void
  42. rend_service_descriptor_free_(rend_service_descriptor_t *desc)
  43. {
  44. if (!desc)
  45. return;
  46. if (desc->pk)
  47. crypto_pk_free(desc->pk);
  48. if (desc->intro_nodes) {
  49. SMARTLIST_FOREACH(desc->intro_nodes, rend_intro_point_t *, intro,
  50. rend_intro_point_free(intro););
  51. smartlist_free(desc->intro_nodes);
  52. }
  53. if (desc->successful_uploads) {
  54. SMARTLIST_FOREACH(desc->successful_uploads, char *, c, tor_free(c););
  55. smartlist_free(desc->successful_uploads);
  56. }
  57. tor_free(desc);
  58. }
  59. /** Length of the descriptor cookie that is used for versioned hidden
  60. * service descriptors. */
  61. #define REND_DESC_COOKIE_LEN 16
  62. /** Length of the replica number that is used to determine the secret ID
  63. * part of versioned hidden service descriptors. */
  64. #define REND_REPLICA_LEN 1
  65. /** Compute the descriptor ID for <b>service_id</b> of length
  66. * <b>REND_SERVICE_ID_LEN</b> and <b>secret_id_part</b> of length
  67. * <b>DIGEST_LEN</b>, and write it to <b>descriptor_id_out</b> of length
  68. * <b>DIGEST_LEN</b>. */
  69. void
  70. rend_get_descriptor_id_bytes(char *descriptor_id_out,
  71. const char *service_id,
  72. const char *secret_id_part)
  73. {
  74. crypto_digest_t *digest = crypto_digest_new();
  75. crypto_digest_add_bytes(digest, service_id, REND_SERVICE_ID_LEN);
  76. crypto_digest_add_bytes(digest, secret_id_part, DIGEST_LEN);
  77. crypto_digest_get_digest(digest, descriptor_id_out, DIGEST_LEN);
  78. crypto_digest_free(digest);
  79. }
  80. /** Compute the secret ID part for time_period,
  81. * a <b>descriptor_cookie</b> of length
  82. * <b>REND_DESC_COOKIE_LEN</b> which may also be <b>NULL</b> if no
  83. * descriptor_cookie shall be used, and <b>replica</b>, and write it to
  84. * <b>secret_id_part</b> of length DIGEST_LEN. */
  85. static void
  86. get_secret_id_part_bytes(char *secret_id_part, uint32_t time_period,
  87. const char *descriptor_cookie, uint8_t replica)
  88. {
  89. crypto_digest_t *digest = crypto_digest_new();
  90. time_period = htonl(time_period);
  91. crypto_digest_add_bytes(digest, (char*)&time_period, sizeof(uint32_t));
  92. if (descriptor_cookie) {
  93. crypto_digest_add_bytes(digest, descriptor_cookie,
  94. REND_DESC_COOKIE_LEN);
  95. }
  96. crypto_digest_add_bytes(digest, (const char *)&replica, REND_REPLICA_LEN);
  97. crypto_digest_get_digest(digest, secret_id_part, DIGEST_LEN);
  98. crypto_digest_free(digest);
  99. }
  100. /** Return the time period for time <b>now</b> plus a potentially
  101. * intended <b>deviation</b> of one or more periods, based on the first byte
  102. * of <b>service_id</b>. */
  103. static uint32_t
  104. get_time_period(time_t now, uint8_t deviation, const char *service_id)
  105. {
  106. /* The time period is the number of REND_TIME_PERIOD_V2_DESC_VALIDITY
  107. * intervals that have passed since the epoch, offset slightly so that
  108. * each service's time periods start and end at a fraction of that
  109. * period based on their first byte. */
  110. return (uint32_t)
  111. (now + ((uint8_t) *service_id) * REND_TIME_PERIOD_V2_DESC_VALIDITY / 256)
  112. / REND_TIME_PERIOD_V2_DESC_VALIDITY + deviation;
  113. }
  114. /** Compute the time in seconds that a descriptor that is generated
  115. * <b>now</b> for <b>service_id</b> will be valid. */
  116. static uint32_t
  117. get_seconds_valid(time_t now, const char *service_id)
  118. {
  119. uint32_t result = REND_TIME_PERIOD_V2_DESC_VALIDITY -
  120. ((uint32_t)
  121. (now + ((uint8_t) *service_id) * REND_TIME_PERIOD_V2_DESC_VALIDITY / 256)
  122. % REND_TIME_PERIOD_V2_DESC_VALIDITY);
  123. return result;
  124. }
  125. /** Compute the binary <b>desc_id_out</b> (DIGEST_LEN bytes long) for a given
  126. * base32-encoded <b>service_id</b> and optional unencoded
  127. * <b>descriptor_cookie</b> of length REND_DESC_COOKIE_LEN,
  128. * at time <b>now</b> for replica number
  129. * <b>replica</b>. <b>desc_id</b> needs to have <b>DIGEST_LEN</b> bytes
  130. * free. Return 0 for success, -1 otherwise. */
  131. int
  132. rend_compute_v2_desc_id(char *desc_id_out, const char *service_id,
  133. const char *descriptor_cookie, time_t now,
  134. uint8_t replica)
  135. {
  136. char service_id_binary[REND_SERVICE_ID_LEN];
  137. char secret_id_part[DIGEST_LEN];
  138. uint32_t time_period;
  139. if (!service_id ||
  140. strlen(service_id) != REND_SERVICE_ID_LEN_BASE32) {
  141. log_warn(LD_REND, "Could not compute v2 descriptor ID: "
  142. "Illegal service ID: %s",
  143. safe_str(service_id));
  144. return -1;
  145. }
  146. if (replica >= REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS) {
  147. log_warn(LD_REND, "Could not compute v2 descriptor ID: "
  148. "Replica number out of range: %d", replica);
  149. return -1;
  150. }
  151. /* Convert service ID to binary. */
  152. if (base32_decode(service_id_binary, REND_SERVICE_ID_LEN,
  153. service_id, REND_SERVICE_ID_LEN_BASE32) < 0) {
  154. log_warn(LD_REND, "Could not compute v2 descriptor ID: "
  155. "Illegal characters in service ID: %s",
  156. safe_str_client(service_id));
  157. return -1;
  158. }
  159. /* Calculate current time-period. */
  160. time_period = get_time_period(now, 0, service_id_binary);
  161. /* Calculate secret-id-part = h(time-period | desc-cookie | replica). */
  162. get_secret_id_part_bytes(secret_id_part, time_period, descriptor_cookie,
  163. replica);
  164. /* Calculate descriptor ID: H(permanent-id | secret-id-part) */
  165. rend_get_descriptor_id_bytes(desc_id_out, service_id_binary, secret_id_part);
  166. return 0;
  167. }
  168. /** Encode the introduction points in <b>desc</b> and write the result to a
  169. * newly allocated string pointed to by <b>encoded</b>. Return 0 for
  170. * success, -1 otherwise. */
  171. static int
  172. rend_encode_v2_intro_points(char **encoded, rend_service_descriptor_t *desc)
  173. {
  174. size_t unenc_len;
  175. char *unenc = NULL;
  176. size_t unenc_written = 0;
  177. int i;
  178. int r = -1;
  179. /* Assemble unencrypted list of introduction points. */
  180. unenc_len = smartlist_len(desc->intro_nodes) * 1000; /* too long, but ok. */
  181. unenc = tor_malloc_zero(unenc_len);
  182. for (i = 0; i < smartlist_len(desc->intro_nodes); i++) {
  183. char id_base32[REND_INTRO_POINT_ID_LEN_BASE32 + 1];
  184. char *onion_key = NULL;
  185. size_t onion_key_len;
  186. crypto_pk_t *intro_key;
  187. char *service_key = NULL;
  188. char *address = NULL;
  189. size_t service_key_len;
  190. int res;
  191. rend_intro_point_t *intro = smartlist_get(desc->intro_nodes, i);
  192. /* Obtain extend info with introduction point details. */
  193. extend_info_t *info = intro->extend_info;
  194. /* Encode introduction point ID. */
  195. base32_encode(id_base32, sizeof(id_base32),
  196. info->identity_digest, DIGEST_LEN);
  197. /* Encode onion key. */
  198. if (crypto_pk_write_public_key_to_string(info->onion_key, &onion_key,
  199. &onion_key_len) < 0) {
  200. log_warn(LD_REND, "Could not write onion key.");
  201. goto done;
  202. }
  203. /* Encode intro key. */
  204. intro_key = intro->intro_key;
  205. if (!intro_key ||
  206. crypto_pk_write_public_key_to_string(intro_key, &service_key,
  207. &service_key_len) < 0) {
  208. log_warn(LD_REND, "Could not write intro key.");
  209. tor_free(onion_key);
  210. goto done;
  211. }
  212. /* Assemble everything for this introduction point. */
  213. address = tor_addr_to_str_dup(&info->addr);
  214. res = tor_snprintf(unenc + unenc_written, unenc_len - unenc_written,
  215. "introduction-point %s\n"
  216. "ip-address %s\n"
  217. "onion-port %d\n"
  218. "onion-key\n%s"
  219. "service-key\n%s",
  220. id_base32,
  221. address,
  222. info->port,
  223. onion_key,
  224. service_key);
  225. tor_free(address);
  226. tor_free(onion_key);
  227. tor_free(service_key);
  228. if (res < 0) {
  229. log_warn(LD_REND, "Not enough space for writing introduction point "
  230. "string.");
  231. goto done;
  232. }
  233. /* Update total number of written bytes for unencrypted intro points. */
  234. unenc_written += res;
  235. }
  236. /* Finalize unencrypted introduction points. */
  237. if (unenc_len < unenc_written + 2) {
  238. log_warn(LD_REND, "Not enough space for finalizing introduction point "
  239. "string.");
  240. goto done;
  241. }
  242. unenc[unenc_written++] = '\n';
  243. unenc[unenc_written++] = 0;
  244. *encoded = unenc;
  245. r = 0;
  246. done:
  247. if (r<0)
  248. tor_free(unenc);
  249. return r;
  250. }
  251. /** Encrypt the encoded introduction points in <b>encoded</b> using
  252. * authorization type 'basic' with <b>client_cookies</b> and write the
  253. * result to a newly allocated string pointed to by <b>encrypted_out</b> of
  254. * length <b>encrypted_len_out</b>. Return 0 for success, -1 otherwise. */
  255. static int
  256. rend_encrypt_v2_intro_points_basic(char **encrypted_out,
  257. size_t *encrypted_len_out,
  258. const char *encoded,
  259. smartlist_t *client_cookies)
  260. {
  261. int r = -1, i, pos, enclen, client_blocks;
  262. size_t len, client_entries_len;
  263. char *enc = NULL, iv[CIPHER_IV_LEN], *client_part = NULL,
  264. session_key[CIPHER_KEY_LEN];
  265. smartlist_t *encrypted_session_keys = NULL;
  266. crypto_digest_t *digest;
  267. crypto_cipher_t *cipher;
  268. tor_assert(encoded);
  269. tor_assert(client_cookies && smartlist_len(client_cookies) > 0);
  270. /* Generate session key. */
  271. crypto_rand(session_key, CIPHER_KEY_LEN);
  272. /* Determine length of encrypted introduction points including session
  273. * keys. */
  274. client_blocks = 1 + ((smartlist_len(client_cookies) - 1) /
  275. REND_BASIC_AUTH_CLIENT_MULTIPLE);
  276. client_entries_len = client_blocks * REND_BASIC_AUTH_CLIENT_MULTIPLE *
  277. REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
  278. len = 2 + client_entries_len + CIPHER_IV_LEN + strlen(encoded);
  279. if (client_blocks >= 256) {
  280. log_warn(LD_REND, "Too many clients in introduction point string.");
  281. goto done;
  282. }
  283. enc = tor_malloc_zero(len);
  284. enc[0] = 0x01; /* type of authorization. */
  285. enc[1] = (uint8_t)client_blocks;
  286. /* Encrypt with random session key. */
  287. enclen = crypto_cipher_encrypt_with_iv(session_key,
  288. enc + 2 + client_entries_len,
  289. CIPHER_IV_LEN + strlen(encoded), encoded, strlen(encoded));
  290. if (enclen < 0) {
  291. log_warn(LD_REND, "Could not encrypt introduction point string.");
  292. goto done;
  293. }
  294. memcpy(iv, enc + 2 + client_entries_len, CIPHER_IV_LEN);
  295. /* Encrypt session key for cookies, determine client IDs, and put both
  296. * in a smartlist. */
  297. encrypted_session_keys = smartlist_new();
  298. SMARTLIST_FOREACH_BEGIN(client_cookies, const char *, cookie) {
  299. client_part = tor_malloc_zero(REND_BASIC_AUTH_CLIENT_ENTRY_LEN);
  300. /* Encrypt session key. */
  301. cipher = crypto_cipher_new(cookie);
  302. if (crypto_cipher_encrypt(cipher, client_part +
  303. REND_BASIC_AUTH_CLIENT_ID_LEN,
  304. session_key, CIPHER_KEY_LEN) < 0) {
  305. log_warn(LD_REND, "Could not encrypt session key for client.");
  306. crypto_cipher_free(cipher);
  307. tor_free(client_part);
  308. goto done;
  309. }
  310. crypto_cipher_free(cipher);
  311. /* Determine client ID. */
  312. digest = crypto_digest_new();
  313. crypto_digest_add_bytes(digest, cookie, REND_DESC_COOKIE_LEN);
  314. crypto_digest_add_bytes(digest, iv, CIPHER_IV_LEN);
  315. crypto_digest_get_digest(digest, client_part,
  316. REND_BASIC_AUTH_CLIENT_ID_LEN);
  317. crypto_digest_free(digest);
  318. /* Put both together. */
  319. smartlist_add(encrypted_session_keys, client_part);
  320. } SMARTLIST_FOREACH_END(cookie);
  321. /* Add some fake client IDs and encrypted session keys. */
  322. for (i = (smartlist_len(client_cookies) - 1) %
  323. REND_BASIC_AUTH_CLIENT_MULTIPLE;
  324. i < REND_BASIC_AUTH_CLIENT_MULTIPLE - 1; i++) {
  325. client_part = tor_malloc_zero(REND_BASIC_AUTH_CLIENT_ENTRY_LEN);
  326. crypto_rand(client_part, REND_BASIC_AUTH_CLIENT_ENTRY_LEN);
  327. smartlist_add(encrypted_session_keys, client_part);
  328. }
  329. /* Sort smartlist and put elements in result in order. */
  330. smartlist_sort_digests(encrypted_session_keys);
  331. pos = 2;
  332. SMARTLIST_FOREACH(encrypted_session_keys, const char *, entry, {
  333. memcpy(enc + pos, entry, REND_BASIC_AUTH_CLIENT_ENTRY_LEN);
  334. pos += REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
  335. });
  336. *encrypted_out = enc;
  337. *encrypted_len_out = len;
  338. enc = NULL; /* prevent free. */
  339. r = 0;
  340. done:
  341. tor_free(enc);
  342. if (encrypted_session_keys) {
  343. SMARTLIST_FOREACH(encrypted_session_keys, char *, d, tor_free(d););
  344. smartlist_free(encrypted_session_keys);
  345. }
  346. return r;
  347. }
  348. /** Encrypt the encoded introduction points in <b>encoded</b> using
  349. * authorization type 'stealth' with <b>descriptor_cookie</b> of length
  350. * REND_DESC_COOKIE_LEN and write the result to a newly allocated string
  351. * pointed to by <b>encrypted_out</b> of length <b>encrypted_len_out</b>.
  352. * Return 0 for success, -1 otherwise. */
  353. static int
  354. rend_encrypt_v2_intro_points_stealth(char **encrypted_out,
  355. size_t *encrypted_len_out,
  356. const char *encoded,
  357. const char *descriptor_cookie)
  358. {
  359. int r = -1, enclen;
  360. char *enc;
  361. tor_assert(encoded);
  362. tor_assert(descriptor_cookie);
  363. enc = tor_malloc_zero(1 + CIPHER_IV_LEN + strlen(encoded));
  364. enc[0] = 0x02; /* Auth type */
  365. enclen = crypto_cipher_encrypt_with_iv(descriptor_cookie,
  366. enc + 1,
  367. CIPHER_IV_LEN+strlen(encoded),
  368. encoded, strlen(encoded));
  369. if (enclen < 0) {
  370. log_warn(LD_REND, "Could not encrypt introduction point string.");
  371. goto done;
  372. }
  373. *encrypted_out = enc;
  374. *encrypted_len_out = enclen;
  375. enc = NULL; /* prevent free */
  376. r = 0;
  377. done:
  378. tor_free(enc);
  379. return r;
  380. }
  381. /** Attempt to parse the given <b>desc_str</b> and return true if this
  382. * succeeds, false otherwise. */
  383. STATIC int
  384. rend_desc_v2_is_parsable(rend_encoded_v2_service_descriptor_t *desc)
  385. {
  386. rend_service_descriptor_t *test_parsed = NULL;
  387. char test_desc_id[DIGEST_LEN];
  388. char *test_intro_content = NULL;
  389. size_t test_intro_size;
  390. size_t test_encoded_size;
  391. const char *test_next;
  392. int res = rend_parse_v2_service_descriptor(&test_parsed, test_desc_id,
  393. &test_intro_content,
  394. &test_intro_size,
  395. &test_encoded_size,
  396. &test_next, desc->desc_str, 1);
  397. rend_service_descriptor_free(test_parsed);
  398. tor_free(test_intro_content);
  399. return (res >= 0);
  400. }
  401. /** Free the storage held by an encoded v2 service descriptor. */
  402. void
  403. rend_encoded_v2_service_descriptor_free_(
  404. rend_encoded_v2_service_descriptor_t *desc)
  405. {
  406. if (!desc)
  407. return;
  408. tor_free(desc->desc_str);
  409. tor_free(desc);
  410. }
  411. /** Free the storage held by an introduction point info. */
  412. void
  413. rend_intro_point_free_(rend_intro_point_t *intro)
  414. {
  415. if (!intro)
  416. return;
  417. extend_info_free(intro->extend_info);
  418. crypto_pk_free(intro->intro_key);
  419. if (intro->accepted_intro_rsa_parts != NULL) {
  420. replaycache_free(intro->accepted_intro_rsa_parts);
  421. }
  422. tor_free(intro);
  423. }
  424. /** Encode a set of rend_encoded_v2_service_descriptor_t's for <b>desc</b>
  425. * at time <b>now</b> using <b>service_key</b>, depending on
  426. * <b>auth_type</b> a <b>descriptor_cookie</b> and a list of
  427. * <b>client_cookies</b> (which are both <b>NULL</b> if no client
  428. * authorization is performed), and <b>period</b> (e.g. 0 for the current
  429. * period, 1 for the next period, etc.) and add them to the existing list
  430. * <b>descs_out</b>; return the number of seconds that the descriptors will
  431. * be found by clients, or -1 if the encoding was not successful. */
  432. int
  433. rend_encode_v2_descriptors(smartlist_t *descs_out,
  434. rend_service_descriptor_t *desc, time_t now,
  435. uint8_t period, rend_auth_type_t auth_type,
  436. crypto_pk_t *client_key,
  437. smartlist_t *client_cookies)
  438. {
  439. char service_id[DIGEST_LEN];
  440. char service_id_base32[REND_SERVICE_ID_LEN_BASE32+1];
  441. uint32_t time_period;
  442. char *ipos_base64 = NULL, *ipos = NULL, *ipos_encrypted = NULL,
  443. *descriptor_cookie = NULL;
  444. size_t ipos_len = 0, ipos_encrypted_len = 0;
  445. int k;
  446. uint32_t seconds_valid;
  447. crypto_pk_t *service_key;
  448. if (!desc) {
  449. log_warn(LD_BUG, "Could not encode v2 descriptor: No desc given.");
  450. return -1;
  451. }
  452. service_key = (auth_type == REND_STEALTH_AUTH) ? client_key : desc->pk;
  453. tor_assert(service_key);
  454. if (auth_type == REND_STEALTH_AUTH) {
  455. descriptor_cookie = smartlist_get(client_cookies, 0);
  456. tor_assert(descriptor_cookie);
  457. }
  458. /* Obtain service_id from public key. */
  459. if (crypto_pk_get_digest(service_key, service_id) < 0) {
  460. log_warn(LD_BUG, "Couldn't compute service key digest.");
  461. return -1;
  462. }
  463. /* Calculate current time-period. */
  464. time_period = get_time_period(now, period, service_id);
  465. /* Determine how many seconds the descriptor will be valid. */
  466. seconds_valid = period * REND_TIME_PERIOD_V2_DESC_VALIDITY +
  467. get_seconds_valid(now, service_id);
  468. /* Assemble, possibly encrypt, and encode introduction points. */
  469. if (smartlist_len(desc->intro_nodes) > 0) {
  470. if (rend_encode_v2_intro_points(&ipos, desc) < 0) {
  471. log_warn(LD_REND, "Encoding of introduction points did not succeed.");
  472. return -1;
  473. }
  474. switch (auth_type) {
  475. case REND_NO_AUTH:
  476. ipos_len = strlen(ipos);
  477. break;
  478. case REND_BASIC_AUTH:
  479. if (rend_encrypt_v2_intro_points_basic(&ipos_encrypted,
  480. &ipos_encrypted_len, ipos,
  481. client_cookies) < 0) {
  482. log_warn(LD_REND, "Encrypting of introduction points did not "
  483. "succeed.");
  484. tor_free(ipos);
  485. return -1;
  486. }
  487. tor_free(ipos);
  488. ipos = ipos_encrypted;
  489. ipos_len = ipos_encrypted_len;
  490. break;
  491. case REND_STEALTH_AUTH:
  492. if (rend_encrypt_v2_intro_points_stealth(&ipos_encrypted,
  493. &ipos_encrypted_len, ipos,
  494. descriptor_cookie) < 0) {
  495. log_warn(LD_REND, "Encrypting of introduction points did not "
  496. "succeed.");
  497. tor_free(ipos);
  498. return -1;
  499. }
  500. tor_free(ipos);
  501. ipos = ipos_encrypted;
  502. ipos_len = ipos_encrypted_len;
  503. break;
  504. default:
  505. log_warn(LD_REND|LD_BUG, "Unrecognized authorization type %d",
  506. (int)auth_type);
  507. tor_free(ipos);
  508. return -1;
  509. }
  510. /* Base64-encode introduction points. */
  511. ipos_base64 = tor_calloc(ipos_len, 2);
  512. if (base64_encode(ipos_base64, ipos_len * 2, ipos, ipos_len,
  513. BASE64_ENCODE_MULTILINE)<0) {
  514. log_warn(LD_REND, "Could not encode introduction point string to "
  515. "base64. length=%d", (int)ipos_len);
  516. tor_free(ipos_base64);
  517. tor_free(ipos);
  518. return -1;
  519. }
  520. tor_free(ipos);
  521. }
  522. /* Encode REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS descriptors. */
  523. for (k = 0; k < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; k++) {
  524. char secret_id_part[DIGEST_LEN];
  525. char secret_id_part_base32[REND_SECRET_ID_PART_LEN_BASE32 + 1];
  526. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  527. char *permanent_key = NULL;
  528. size_t permanent_key_len;
  529. char published[ISO_TIME_LEN+1];
  530. int i;
  531. char protocol_versions_string[16]; /* max len: "0,1,2,3,4,5,6,7\0" */
  532. size_t protocol_versions_written;
  533. size_t desc_len;
  534. char *desc_str = NULL;
  535. int result = 0;
  536. size_t written = 0;
  537. char desc_digest[DIGEST_LEN];
  538. rend_encoded_v2_service_descriptor_t *enc =
  539. tor_malloc_zero(sizeof(rend_encoded_v2_service_descriptor_t));
  540. /* Calculate secret-id-part = h(time-period | cookie | replica). */
  541. get_secret_id_part_bytes(secret_id_part, time_period, descriptor_cookie,
  542. k);
  543. base32_encode(secret_id_part_base32, sizeof(secret_id_part_base32),
  544. secret_id_part, DIGEST_LEN);
  545. /* Calculate descriptor ID. */
  546. rend_get_descriptor_id_bytes(enc->desc_id, service_id, secret_id_part);
  547. base32_encode(desc_id_base32, sizeof(desc_id_base32),
  548. enc->desc_id, DIGEST_LEN);
  549. /* PEM-encode the public key */
  550. if (crypto_pk_write_public_key_to_string(service_key, &permanent_key,
  551. &permanent_key_len) < 0) {
  552. log_warn(LD_BUG, "Could not write public key to string.");
  553. rend_encoded_v2_service_descriptor_free(enc);
  554. goto err;
  555. }
  556. /* Encode timestamp. */
  557. format_iso_time(published, desc->timestamp);
  558. /* Write protocol-versions bitmask to comma-separated value string. */
  559. protocol_versions_written = 0;
  560. for (i = 0; i < 8; i++) {
  561. if (desc->protocols & 1 << i) {
  562. tor_snprintf(protocol_versions_string + protocol_versions_written,
  563. 16 - protocol_versions_written, "%d,", i);
  564. protocol_versions_written += 2;
  565. }
  566. }
  567. if (protocol_versions_written)
  568. protocol_versions_string[protocol_versions_written - 1] = '\0';
  569. else
  570. protocol_versions_string[0]= '\0';
  571. /* Assemble complete descriptor. */
  572. desc_len = 2000 + smartlist_len(desc->intro_nodes) * 1000; /* far too long,
  573. but okay.*/
  574. enc->desc_str = desc_str = tor_malloc_zero(desc_len);
  575. result = tor_snprintf(desc_str, desc_len,
  576. "rendezvous-service-descriptor %s\n"
  577. "version 2\n"
  578. "permanent-key\n%s"
  579. "secret-id-part %s\n"
  580. "publication-time %s\n"
  581. "protocol-versions %s\n",
  582. desc_id_base32,
  583. permanent_key,
  584. secret_id_part_base32,
  585. published,
  586. protocol_versions_string);
  587. tor_free(permanent_key);
  588. if (result < 0) {
  589. log_warn(LD_BUG, "Descriptor ran out of room.");
  590. rend_encoded_v2_service_descriptor_free(enc);
  591. goto err;
  592. }
  593. written = result;
  594. /* Add introduction points. */
  595. if (ipos_base64) {
  596. result = tor_snprintf(desc_str + written, desc_len - written,
  597. "introduction-points\n"
  598. "-----BEGIN MESSAGE-----\n%s"
  599. "-----END MESSAGE-----\n",
  600. ipos_base64);
  601. if (result < 0) {
  602. log_warn(LD_BUG, "could not write introduction points.");
  603. rend_encoded_v2_service_descriptor_free(enc);
  604. goto err;
  605. }
  606. written += result;
  607. }
  608. /* Add signature. */
  609. strlcpy(desc_str + written, "signature\n", desc_len - written);
  610. written += strlen(desc_str + written);
  611. if (crypto_digest(desc_digest, desc_str, written) < 0) {
  612. log_warn(LD_BUG, "could not create digest.");
  613. rend_encoded_v2_service_descriptor_free(enc);
  614. goto err;
  615. }
  616. if (router_append_dirobj_signature(desc_str + written,
  617. desc_len - written,
  618. desc_digest, DIGEST_LEN,
  619. service_key) < 0) {
  620. log_warn(LD_BUG, "Couldn't sign desc.");
  621. rend_encoded_v2_service_descriptor_free(enc);
  622. goto err;
  623. }
  624. written += strlen(desc_str+written);
  625. if (written+2 > desc_len) {
  626. log_warn(LD_BUG, "Could not finish desc.");
  627. rend_encoded_v2_service_descriptor_free(enc);
  628. goto err;
  629. }
  630. desc_str[written++] = 0;
  631. /* Check if we can parse our own descriptor. */
  632. if (!rend_desc_v2_is_parsable(enc)) {
  633. log_warn(LD_BUG, "Could not parse my own descriptor: %s", desc_str);
  634. rend_encoded_v2_service_descriptor_free(enc);
  635. goto err;
  636. }
  637. smartlist_add(descs_out, enc);
  638. /* Add the uploaded descriptor to the local service's descriptor cache */
  639. rend_cache_store_v2_desc_as_service(enc->desc_str);
  640. base32_encode(service_id_base32, sizeof(service_id_base32),
  641. service_id, REND_SERVICE_ID_LEN);
  642. control_event_hs_descriptor_created(service_id_base32, desc_id_base32, k);
  643. }
  644. log_info(LD_REND, "Successfully encoded a v2 descriptor and "
  645. "confirmed that it is parsable.");
  646. goto done;
  647. err:
  648. SMARTLIST_FOREACH(descs_out, rend_encoded_v2_service_descriptor_t *, d,
  649. rend_encoded_v2_service_descriptor_free(d););
  650. smartlist_clear(descs_out);
  651. seconds_valid = -1;
  652. done:
  653. tor_free(ipos_base64);
  654. return seconds_valid;
  655. }
  656. /** Sets <b>out</b> to the first 10 bytes of the digest of <b>pk</b>,
  657. * base32 encoded. NUL-terminates out. (We use this string to
  658. * identify services in directory requests and .onion URLs.)
  659. */
  660. int
  661. rend_get_service_id(crypto_pk_t *pk, char *out)
  662. {
  663. char buf[DIGEST_LEN];
  664. tor_assert(pk);
  665. if (crypto_pk_get_digest(pk, buf) < 0)
  666. return -1;
  667. base32_encode(out, REND_SERVICE_ID_LEN_BASE32+1, buf, REND_SERVICE_ID_LEN);
  668. return 0;
  669. }
  670. /** Return true iff <b>query</b> is a syntactically valid service ID (as
  671. * generated by rend_get_service_id). */
  672. int
  673. rend_valid_v2_service_id(const char *query)
  674. {
  675. if (strlen(query) != REND_SERVICE_ID_LEN_BASE32)
  676. return 0;
  677. if (strspn(query, BASE32_CHARS) != REND_SERVICE_ID_LEN_BASE32)
  678. return 0;
  679. return 1;
  680. }
  681. /** Return true iff <b>query</b> is a syntactically valid descriptor ID.
  682. * (as generated by rend_get_descriptor_id_bytes). */
  683. int
  684. rend_valid_descriptor_id(const char *query)
  685. {
  686. if (strlen(query) != REND_DESC_ID_V2_LEN_BASE32) {
  687. goto invalid;
  688. }
  689. if (strspn(query, BASE32_CHARS) != REND_DESC_ID_V2_LEN_BASE32) {
  690. goto invalid;
  691. }
  692. return 1;
  693. invalid:
  694. return 0;
  695. }
  696. /** Return true iff <b>client_name</b> is a syntactically valid name
  697. * for rendezvous client authentication. */
  698. int
  699. rend_valid_client_name(const char *client_name)
  700. {
  701. size_t len = strlen(client_name);
  702. if (len < 1 || len > REND_CLIENTNAME_MAX_LEN) {
  703. return 0;
  704. }
  705. if (strspn(client_name, REND_LEGAL_CLIENTNAME_CHARACTERS) != len) {
  706. return 0;
  707. }
  708. return 1;
  709. }
  710. /** Called when we get a rendezvous-related relay cell on circuit
  711. * <b>circ</b>. Dispatch on rendezvous relay command. */
  712. void
  713. rend_process_relay_cell(circuit_t *circ, const crypt_path_t *layer_hint,
  714. int command, size_t length,
  715. const uint8_t *payload)
  716. {
  717. or_circuit_t *or_circ = NULL;
  718. origin_circuit_t *origin_circ = NULL;
  719. int r = -2;
  720. if (CIRCUIT_IS_ORIGIN(circ)) {
  721. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  722. if (!layer_hint || layer_hint != origin_circ->cpath->prev) {
  723. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  724. "Relay cell (rend purpose %d) from wrong hop on origin circ",
  725. command);
  726. origin_circ = NULL;
  727. }
  728. } else {
  729. or_circ = TO_OR_CIRCUIT(circ);
  730. }
  731. switch (command) {
  732. case RELAY_COMMAND_ESTABLISH_INTRO:
  733. if (or_circ)
  734. r = hs_intro_received_establish_intro(or_circ,payload,length);
  735. break;
  736. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
  737. if (or_circ)
  738. r = rend_mid_establish_rendezvous(or_circ,payload,length);
  739. break;
  740. case RELAY_COMMAND_INTRODUCE1:
  741. if (or_circ)
  742. r = hs_intro_received_introduce1(or_circ,payload,length);
  743. break;
  744. case RELAY_COMMAND_INTRODUCE2:
  745. if (origin_circ)
  746. r = hs_service_receive_introduce2(origin_circ,payload,length);
  747. break;
  748. case RELAY_COMMAND_INTRODUCE_ACK:
  749. if (origin_circ)
  750. r = hs_client_receive_introduce_ack(origin_circ,payload,length);
  751. break;
  752. case RELAY_COMMAND_RENDEZVOUS1:
  753. if (or_circ)
  754. r = rend_mid_rendezvous(or_circ,payload,length);
  755. break;
  756. case RELAY_COMMAND_RENDEZVOUS2:
  757. if (origin_circ)
  758. r = hs_client_receive_rendezvous2(origin_circ,payload,length);
  759. break;
  760. case RELAY_COMMAND_INTRO_ESTABLISHED:
  761. if (origin_circ)
  762. r = hs_service_receive_intro_established(origin_circ,payload,length);
  763. break;
  764. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  765. if (origin_circ)
  766. r = hs_client_receive_rendezvous_acked(origin_circ,payload,length);
  767. break;
  768. default:
  769. tor_fragile_assert();
  770. }
  771. if (r == 0 && origin_circ) {
  772. /* This was a valid cell. Count it as delivered + overhead. */
  773. circuit_read_valid_data(origin_circ, length);
  774. }
  775. if (r == -2)
  776. log_info(LD_PROTOCOL, "Dropping cell (type %d) for wrong circuit type.",
  777. command);
  778. }
  779. /** Determine the routers that are responsible for <b>id</b> (binary) and
  780. * add pointers to those routers' routerstatus_t to <b>responsible_dirs</b>.
  781. * Return -1 if we're returning an empty smartlist, else return 0.
  782. */
  783. int
  784. hid_serv_get_responsible_directories(smartlist_t *responsible_dirs,
  785. const char *id)
  786. {
  787. int start, found, n_added = 0, i;
  788. networkstatus_t *c = networkstatus_get_latest_consensus();
  789. if (!c || !smartlist_len(c->routerstatus_list)) {
  790. log_warn(LD_REND, "We don't have a consensus, so we can't perform v2 "
  791. "rendezvous operations.");
  792. return -1;
  793. }
  794. tor_assert(id);
  795. start = networkstatus_vote_find_entry_idx(c, id, &found);
  796. if (start == smartlist_len(c->routerstatus_list)) start = 0;
  797. i = start;
  798. do {
  799. routerstatus_t *r = smartlist_get(c->routerstatus_list, i);
  800. if (r->is_hs_dir) {
  801. smartlist_add(responsible_dirs, r);
  802. if (++n_added == REND_NUMBER_OF_CONSECUTIVE_REPLICAS)
  803. return 0;
  804. }
  805. if (++i == smartlist_len(c->routerstatus_list))
  806. i = 0;
  807. } while (i != start);
  808. /* Even though we don't have the desired number of hidden service
  809. * directories, be happy if we got any. */
  810. return smartlist_len(responsible_dirs) ? 0 : -1;
  811. }
  812. /* Length of the 'extended' auth cookie used to encode auth type before
  813. * base64 encoding. */
  814. #define REND_DESC_COOKIE_LEN_EXT (REND_DESC_COOKIE_LEN + 1)
  815. /* Length of the zero-padded auth cookie when base64 encoded. These two
  816. * padding bytes always (A=) are stripped off of the returned cookie. */
  817. #define REND_DESC_COOKIE_LEN_EXT_BASE64 (REND_DESC_COOKIE_LEN_BASE64 + 2)
  818. /** Encode a client authorization descriptor cookie.
  819. * The result of this function is suitable for use in the HidServAuth
  820. * option. The trailing padding characters are removed, and the
  821. * auth type is encoded into the cookie.
  822. *
  823. * Returns a new base64-encoded cookie. This function cannot fail.
  824. * The caller is responsible for freeing the returned value.
  825. */
  826. char *
  827. rend_auth_encode_cookie(const uint8_t *cookie_in, rend_auth_type_t auth_type)
  828. {
  829. uint8_t extended_cookie[REND_DESC_COOKIE_LEN_EXT];
  830. char *cookie_out = tor_malloc_zero(REND_DESC_COOKIE_LEN_EXT_BASE64 + 1);
  831. int re;
  832. tor_assert(cookie_in);
  833. memcpy(extended_cookie, cookie_in, REND_DESC_COOKIE_LEN);
  834. extended_cookie[REND_DESC_COOKIE_LEN] = ((int)auth_type - 1) << 4;
  835. re = base64_encode(cookie_out, REND_DESC_COOKIE_LEN_EXT_BASE64 + 1,
  836. (const char *) extended_cookie, REND_DESC_COOKIE_LEN_EXT,
  837. 0);
  838. tor_assert(re == REND_DESC_COOKIE_LEN_EXT_BASE64);
  839. /* Remove the trailing 'A='. Auth type is encoded in the high bits
  840. * of the last byte, so the last base64 character will always be zero
  841. * (A). This is subtly different behavior from base64_encode_nopad. */
  842. cookie_out[REND_DESC_COOKIE_LEN_BASE64] = '\0';
  843. memwipe(extended_cookie, 0, sizeof(extended_cookie));
  844. return cookie_out;
  845. }
  846. /** Decode a base64-encoded client authorization descriptor cookie.
  847. * The descriptor_cookie can be truncated to REND_DESC_COOKIE_LEN_BASE64
  848. * characters (as given to clients), or may include the two padding
  849. * characters (as stored by the service).
  850. *
  851. * The result is stored in REND_DESC_COOKIE_LEN bytes of cookie_out.
  852. * The rend_auth_type_t decoded from the cookie is stored in the
  853. * optional auth_type_out parameter.
  854. *
  855. * Return 0 on success, or -1 on error. The caller is responsible for
  856. * freeing the returned err_msg.
  857. */
  858. int
  859. rend_auth_decode_cookie(const char *cookie_in, uint8_t *cookie_out,
  860. rend_auth_type_t *auth_type_out, char **err_msg_out)
  861. {
  862. uint8_t descriptor_cookie_decoded[REND_DESC_COOKIE_LEN_EXT + 1] = { 0 };
  863. char descriptor_cookie_base64ext[REND_DESC_COOKIE_LEN_EXT_BASE64 + 1];
  864. const char *descriptor_cookie = cookie_in;
  865. char *err_msg = NULL;
  866. int auth_type_val = 0;
  867. int res = -1;
  868. int decoded_len;
  869. size_t len = strlen(descriptor_cookie);
  870. if (len == REND_DESC_COOKIE_LEN_BASE64) {
  871. /* Add a trailing zero byte to make base64-decoding happy. */
  872. tor_snprintf(descriptor_cookie_base64ext,
  873. sizeof(descriptor_cookie_base64ext),
  874. "%sA=", descriptor_cookie);
  875. descriptor_cookie = descriptor_cookie_base64ext;
  876. } else if (len != REND_DESC_COOKIE_LEN_EXT_BASE64) {
  877. tor_asprintf(&err_msg, "Authorization cookie has wrong length: %s",
  878. escaped(cookie_in));
  879. goto err;
  880. }
  881. decoded_len = base64_decode((char *) descriptor_cookie_decoded,
  882. sizeof(descriptor_cookie_decoded),
  883. descriptor_cookie,
  884. REND_DESC_COOKIE_LEN_EXT_BASE64);
  885. if (decoded_len != REND_DESC_COOKIE_LEN &&
  886. decoded_len != REND_DESC_COOKIE_LEN_EXT) {
  887. tor_asprintf(&err_msg, "Authorization cookie has invalid characters: %s",
  888. escaped(cookie_in));
  889. goto err;
  890. }
  891. if (auth_type_out) {
  892. auth_type_val = (descriptor_cookie_decoded[REND_DESC_COOKIE_LEN] >> 4) + 1;
  893. if (auth_type_val < 1 || auth_type_val > 2) {
  894. tor_asprintf(&err_msg, "Authorization cookie type is unknown: %s",
  895. escaped(cookie_in));
  896. goto err;
  897. }
  898. *auth_type_out = auth_type_val == 1 ? REND_BASIC_AUTH : REND_STEALTH_AUTH;
  899. }
  900. memcpy(cookie_out, descriptor_cookie_decoded, REND_DESC_COOKIE_LEN);
  901. res = 0;
  902. err:
  903. if (err_msg_out) {
  904. *err_msg_out = err_msg;
  905. } else {
  906. tor_free(err_msg);
  907. }
  908. memwipe(descriptor_cookie_decoded, 0, sizeof(descriptor_cookie_decoded));
  909. memwipe(descriptor_cookie_base64ext, 0, sizeof(descriptor_cookie_base64ext));
  910. return res;
  911. }
  912. /* Is this a rend client or server that allows direct (non-anonymous)
  913. * connections?
  914. * Clients must be specifically compiled and configured in this mode.
  915. * Onion services can be configured to start in this mode.
  916. * Prefer rend_client_allow_non_anonymous_connection() or
  917. * rend_service_allow_non_anonymous_connection() whenever possible, so that
  918. * checks are specific to Single Onion Services or Tor2web. */
  919. int
  920. rend_allow_non_anonymous_connection(const or_options_t* options)
  921. {
  922. return (rend_client_allow_non_anonymous_connection(options)
  923. || rend_service_allow_non_anonymous_connection(options));
  924. }
  925. /* Is this a rend client or server in non-anonymous mode?
  926. * Clients must be specifically compiled in this mode.
  927. * Onion services can be configured to start in this mode.
  928. * Prefer rend_client_non_anonymous_mode_enabled() or
  929. * rend_service_non_anonymous_mode_enabled() whenever possible, so that checks
  930. * are specific to Single Onion Services or Tor2web. */
  931. int
  932. rend_non_anonymous_mode_enabled(const or_options_t *options)
  933. {
  934. return (rend_client_non_anonymous_mode_enabled(options)
  935. || rend_service_non_anonymous_mode_enabled(options));
  936. }
  937. /* Make sure that tor only builds one-hop circuits when they would not
  938. * compromise user anonymity.
  939. *
  940. * One-hop circuits are permitted in Tor2web or Single Onion modes.
  941. *
  942. * Tor2web or Single Onion modes are also allowed to make multi-hop circuits.
  943. * For example, single onion HSDir circuits are 3-hop to prevent denial of
  944. * service.
  945. */
  946. void
  947. assert_circ_anonymity_ok(const origin_circuit_t *circ,
  948. const or_options_t *options)
  949. {
  950. tor_assert(options);
  951. tor_assert(circ);
  952. tor_assert(circ->build_state);
  953. if (circ->build_state->onehop_tunnel) {
  954. tor_assert(rend_allow_non_anonymous_connection(options));
  955. }
  956. }
  957. /* Return 1 iff the given <b>digest</b> of a permenanent hidden service key is
  958. * equal to the digest in the origin circuit <b>ocirc</b> of its rend data .
  959. * If the rend data doesn't exist, 0 is returned. This function is agnostic to
  960. * the rend data version. */
  961. int
  962. rend_circuit_pk_digest_eq(const origin_circuit_t *ocirc,
  963. const uint8_t *digest)
  964. {
  965. size_t rend_pk_digest_len;
  966. const uint8_t *rend_pk_digest;
  967. tor_assert(ocirc);
  968. tor_assert(digest);
  969. if (ocirc->rend_data == NULL) {
  970. goto no_match;
  971. }
  972. rend_pk_digest = rend_data_get_pk_digest(ocirc->rend_data,
  973. &rend_pk_digest_len);
  974. if (tor_memeq(rend_pk_digest, digest, rend_pk_digest_len)) {
  975. goto match;
  976. }
  977. no_match:
  978. return 0;
  979. match:
  980. return 1;
  981. }