rendcommon.c 37 KB

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