rendcommon.c 37 KB

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