rendcommon.c 38 KB

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