dos.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  1. /* Copyright (c) 2018, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /*
  4. * \file dos.c
  5. * \brief Implement Denial of Service mitigation subsystem.
  6. */
  7. #define DOS_PRIVATE
  8. #include "or.h"
  9. #include "channel.h"
  10. #include "config.h"
  11. #include "crypto_rand.h"
  12. #include "geoip.h"
  13. #include "main.h"
  14. #include "networkstatus.h"
  15. #include "nodelist.h"
  16. #include "router.h"
  17. #include "dos.h"
  18. /*
  19. * Circuit creation denial of service mitigation.
  20. *
  21. * Namespace used for this mitigation framework is "dos_cc_" where "cc" is for
  22. * Circuit Creation.
  23. */
  24. /* Is the circuit creation DoS mitigation enabled? */
  25. static unsigned int dos_cc_enabled = 0;
  26. /* Consensus parameters. They can be changed when a new consensus arrives.
  27. * They are initialized with the hardcoded default values. */
  28. static uint32_t dos_cc_min_concurrent_conn;
  29. static uint32_t dos_cc_circuit_rate;
  30. static uint32_t dos_cc_circuit_burst;
  31. static dos_cc_defense_type_t dos_cc_defense_type;
  32. static int32_t dos_cc_defense_time_period;
  33. /* Keep some stats for the heartbeat so we can report out. */
  34. static uint64_t cc_num_rejected_cells;
  35. static uint32_t cc_num_marked_addrs;
  36. /*
  37. * Concurrent connection denial of service mitigation.
  38. *
  39. * Namespace used for this mitigation framework is "dos_conn_".
  40. */
  41. /* Is the connection DoS mitigation enabled? */
  42. static unsigned int dos_conn_enabled = 0;
  43. /* Consensus parameters. They can be changed when a new consensus arrives.
  44. * They are initialized with the hardcoded default values. */
  45. static uint32_t dos_conn_max_concurrent_count;
  46. static dos_conn_defense_type_t dos_conn_defense_type;
  47. /* Keep some stats for the heartbeat so we can report out. */
  48. static uint64_t conn_num_addr_rejected;
  49. /*
  50. * General interface of the denial of service mitigation subsystem.
  51. */
  52. /* Keep stats for the heartbeat. */
  53. static uint64_t num_single_hop_client_refused;
  54. /* Return true iff the circuit creation mitigation is enabled. We look at the
  55. * consensus for this else a default value is returned. */
  56. MOCK_IMPL(STATIC unsigned int,
  57. get_param_cc_enabled, (const networkstatus_t *ns))
  58. {
  59. if (get_options()->DoSCircuitCreationEnabled != -1) {
  60. return get_options()->DoSCircuitCreationEnabled;
  61. }
  62. return !!networkstatus_get_param(ns, "DoSCircuitCreationEnabled",
  63. DOS_CC_ENABLED_DEFAULT, 0, 1);
  64. }
  65. /* Return the parameter for the minimum concurrent connection at which we'll
  66. * start counting circuit for a specific client address. */
  67. STATIC uint32_t
  68. get_param_cc_min_concurrent_connection(const networkstatus_t *ns)
  69. {
  70. if (get_options()->DoSCircuitCreationMinConnections) {
  71. return get_options()->DoSCircuitCreationMinConnections;
  72. }
  73. return networkstatus_get_param(ns, "DoSCircuitCreationMinConnections",
  74. DOS_CC_MIN_CONCURRENT_CONN_DEFAULT,
  75. 1, INT32_MAX);
  76. }
  77. /* Return the parameter for the time rate that is how many circuits over this
  78. * time span. */
  79. static uint32_t
  80. get_param_cc_circuit_rate(const networkstatus_t *ns)
  81. {
  82. /* This is in seconds. */
  83. if (get_options()->DoSCircuitCreationRate) {
  84. return get_options()->DoSCircuitCreationRate;
  85. }
  86. return networkstatus_get_param(ns, "DoSCircuitCreationRate",
  87. DOS_CC_CIRCUIT_RATE_DEFAULT,
  88. 1, INT32_MAX);
  89. }
  90. /* Return the parameter for the maximum circuit count for the circuit time
  91. * rate. */
  92. STATIC uint32_t
  93. get_param_cc_circuit_burst(const networkstatus_t *ns)
  94. {
  95. if (get_options()->DoSCircuitCreationBurst) {
  96. return get_options()->DoSCircuitCreationBurst;
  97. }
  98. return networkstatus_get_param(ns, "DoSCircuitCreationBurst",
  99. DOS_CC_CIRCUIT_BURST_DEFAULT,
  100. 1, INT32_MAX);
  101. }
  102. /* Return the consensus parameter of the circuit creation defense type. */
  103. static uint32_t
  104. get_param_cc_defense_type(const networkstatus_t *ns)
  105. {
  106. if (get_options()->DoSCircuitCreationDefenseType) {
  107. return get_options()->DoSCircuitCreationDefenseType;
  108. }
  109. return networkstatus_get_param(ns, "DoSCircuitCreationDefenseType",
  110. DOS_CC_DEFENSE_TYPE_DEFAULT,
  111. DOS_CC_DEFENSE_NONE, DOS_CC_DEFENSE_MAX);
  112. }
  113. /* Return the consensus parameter of the defense time period which is how much
  114. * time should we defend against a malicious client address. */
  115. static int32_t
  116. get_param_cc_defense_time_period(const networkstatus_t *ns)
  117. {
  118. /* Time in seconds. */
  119. if (get_options()->DoSCircuitCreationDefenseTimePeriod) {
  120. return get_options()->DoSCircuitCreationDefenseTimePeriod;
  121. }
  122. return networkstatus_get_param(ns, "DoSCircuitCreationDefenseTimePeriod",
  123. DOS_CC_DEFENSE_TIME_PERIOD_DEFAULT,
  124. 0, INT32_MAX);
  125. }
  126. /* Return true iff connection mitigation is enabled. We look at the consensus
  127. * for this else a default value is returned. */
  128. MOCK_IMPL(STATIC unsigned int,
  129. get_param_conn_enabled, (const networkstatus_t *ns))
  130. {
  131. if (get_options()->DoSConnectionEnabled != -1) {
  132. return get_options()->DoSConnectionEnabled;
  133. }
  134. return !!networkstatus_get_param(ns, "DoSConnectionEnabled",
  135. DOS_CONN_ENABLED_DEFAULT, 0, 1);
  136. }
  137. /* Return the consensus parameter for the maximum concurrent connection
  138. * allowed. */
  139. STATIC uint32_t
  140. get_param_conn_max_concurrent_count(const networkstatus_t *ns)
  141. {
  142. if (get_options()->DoSConnectionMaxConcurrentCount) {
  143. return get_options()->DoSConnectionMaxConcurrentCount;
  144. }
  145. return networkstatus_get_param(ns, "DoSConnectionMaxConcurrentCount",
  146. DOS_CONN_MAX_CONCURRENT_COUNT_DEFAULT,
  147. 1, INT32_MAX);
  148. }
  149. /* Return the consensus parameter of the connection defense type. */
  150. static uint32_t
  151. get_param_conn_defense_type(const networkstatus_t *ns)
  152. {
  153. if (get_options()->DoSConnectionDefenseType) {
  154. return get_options()->DoSConnectionDefenseType;
  155. }
  156. return networkstatus_get_param(ns, "DoSConnectionDefenseType",
  157. DOS_CONN_DEFENSE_TYPE_DEFAULT,
  158. DOS_CONN_DEFENSE_NONE, DOS_CONN_DEFENSE_MAX);
  159. }
  160. /* Set circuit creation parameters located in the consensus or their default
  161. * if none are present. Called at initialization or when the consensus
  162. * changes. */
  163. static void
  164. set_dos_parameters(const networkstatus_t *ns)
  165. {
  166. /* Get the default consensus param values. */
  167. dos_cc_enabled = get_param_cc_enabled(ns);
  168. dos_cc_min_concurrent_conn = get_param_cc_min_concurrent_connection(ns);
  169. dos_cc_circuit_rate = get_param_cc_circuit_rate(ns);
  170. dos_cc_circuit_burst = get_param_cc_circuit_burst(ns);
  171. dos_cc_defense_time_period = get_param_cc_defense_time_period(ns);
  172. dos_cc_defense_type = get_param_cc_defense_type(ns);
  173. /* Connection detection. */
  174. dos_conn_enabled = get_param_conn_enabled(ns);
  175. dos_conn_max_concurrent_count = get_param_conn_max_concurrent_count(ns);
  176. dos_conn_defense_type = get_param_conn_defense_type(ns);
  177. }
  178. /* Free everything for the circuit creation DoS mitigation subsystem. */
  179. static void
  180. cc_free_all(void)
  181. {
  182. /* If everything is freed, the circuit creation subsystem is not enabled. */
  183. dos_cc_enabled = 0;
  184. }
  185. /* Called when the consensus has changed. Do appropriate actions for the
  186. * circuit creation subsystem. */
  187. static void
  188. cc_consensus_has_changed(const networkstatus_t *ns)
  189. {
  190. /* Looking at the consensus, is the circuit creation subsystem enabled? If
  191. * not and it was enabled before, clean it up. */
  192. if (dos_cc_enabled && !get_param_cc_enabled(ns)) {
  193. cc_free_all();
  194. }
  195. }
  196. /** Return the number of circuits we allow per second under the current
  197. * configuration. */
  198. STATIC uint64_t
  199. get_circuit_rate_per_second(void)
  200. {
  201. return dos_cc_circuit_rate;
  202. }
  203. /* Given the circuit creation client statistics object, refill the circuit
  204. * bucket if needed. This also works if the bucket was never filled in the
  205. * first place. The addr is only used for logging purposes. */
  206. STATIC void
  207. cc_stats_refill_bucket(cc_client_stats_t *stats, const tor_addr_t *addr)
  208. {
  209. uint32_t new_circuit_bucket_count;
  210. uint64_t num_token, elapsed_time_last_refill = 0, circuit_rate = 0;
  211. time_t now;
  212. int64_t last_refill_ts;
  213. tor_assert(stats);
  214. tor_assert(addr);
  215. now = approx_time();
  216. last_refill_ts = (int64_t)stats->last_circ_bucket_refill_ts;
  217. /* If less than a second has elapsed, don't add any tokens.
  218. * Note: If a relay's clock is ever 0, any new clients won't get a refill
  219. * until the next second. But a relay that thinks it is 1970 will never
  220. * validate the public consensus. */
  221. if ((int64_t)now == last_refill_ts) {
  222. goto done;
  223. }
  224. /* At this point, we know we might need to add token to the bucket. We'll
  225. * first get the circuit rate that is how many circuit are we allowed to do
  226. * per second. */
  227. circuit_rate = get_circuit_rate_per_second();
  228. /* We've never filled the bucket so fill it with the maximum being the burst
  229. * and we are done.
  230. * Note: If a relay's clock is ever 0, all clients that were last refilled
  231. * in that zero second will get a full refill here. */
  232. if (last_refill_ts == 0) {
  233. num_token = dos_cc_circuit_burst;
  234. goto end;
  235. }
  236. /* Our clock jumped backward so fill it up to the maximum. Not filling it
  237. * could trigger a detection for a valid client. Also, if the clock jumped
  238. * negative but we didn't notice until the elapsed time became positive
  239. * again, then we potentially spent many seconds not refilling the bucket
  240. * when we should have been refilling it. But the fact that we didn't notice
  241. * until now means that no circuit creation requests came in during that
  242. * time, so the client doesn't end up punished that much from this hopefully
  243. * rare situation.*/
  244. if ((int64_t)now < last_refill_ts) {
  245. /* Use the maximum allowed value of token. */
  246. num_token = dos_cc_circuit_burst;
  247. goto end;
  248. }
  249. /* How many seconds have elapsed between now and the last refill?
  250. * This subtraction can't underflow, because now >= last_refill_ts.
  251. * And it can't overflow, because INT64_MAX - (-INT64_MIN) == UINT64_MAX. */
  252. elapsed_time_last_refill = (uint64_t)now - last_refill_ts;
  253. /* If the elapsed time is very large, it means our clock jumped forward.
  254. * If the multiplication would overflow, use the maximum allowed value. */
  255. if (elapsed_time_last_refill > UINT32_MAX) {
  256. num_token = dos_cc_circuit_burst;
  257. goto end;
  258. }
  259. /* Compute how many circuits we are allowed in that time frame which we'll
  260. * add to the bucket. This can't overflow, because both multiplicands
  261. * are less than or equal to UINT32_MAX, and num_token is uint64_t. */
  262. num_token = elapsed_time_last_refill * circuit_rate;
  263. end:
  264. /* If the sum would overflow, use the maximum allowed value. */
  265. if (num_token > UINT32_MAX - stats->circuit_bucket) {
  266. new_circuit_bucket_count = dos_cc_circuit_burst;
  267. } else {
  268. /* We cap the bucket to the burst value else this could overflow uint32_t
  269. * over time. */
  270. new_circuit_bucket_count = MIN(stats->circuit_bucket + (uint32_t)num_token,
  271. dos_cc_circuit_burst);
  272. }
  273. /* This function is not allowed to make the bucket count larger than the
  274. * burst value */
  275. tor_assert_nonfatal(new_circuit_bucket_count <= dos_cc_circuit_burst);
  276. /* This function is not allowed to make the bucket count smaller, unless it
  277. * is decreasing it to a newly configured, lower burst value. We allow the
  278. * bucket to stay the same size, in case the circuit rate is zero. */
  279. tor_assert_nonfatal(new_circuit_bucket_count >= stats->circuit_bucket ||
  280. new_circuit_bucket_count == dos_cc_circuit_burst);
  281. log_debug(LD_DOS, "DoS address %s has its circuit bucket value: %" PRIu32
  282. ". Filling it to %" PRIu32 ". Circuit rate is %" PRIu64
  283. ". Elapsed time is %" PRIi64,
  284. fmt_addr(addr), stats->circuit_bucket, new_circuit_bucket_count,
  285. circuit_rate, (int64_t)elapsed_time_last_refill);
  286. stats->circuit_bucket = new_circuit_bucket_count;
  287. stats->last_circ_bucket_refill_ts = now;
  288. done:
  289. return;
  290. }
  291. /* Return true iff the circuit bucket is down to 0 and the number of
  292. * concurrent connections is greater or equal the minimum threshold set the
  293. * consensus parameter. */
  294. static int
  295. cc_has_exhausted_circuits(const dos_client_stats_t *stats)
  296. {
  297. tor_assert(stats);
  298. return stats->cc_stats.circuit_bucket == 0 &&
  299. stats->concurrent_count >= dos_cc_min_concurrent_conn;
  300. }
  301. /* Mark client address by setting a timestamp in the stats object which tells
  302. * us until when it is marked as positively detected. */
  303. static void
  304. cc_mark_client(cc_client_stats_t *stats)
  305. {
  306. tor_assert(stats);
  307. /* We add a random offset of a maximum of half the defense time so it is
  308. * less predictable. */
  309. stats->marked_until_ts =
  310. approx_time() + dos_cc_defense_time_period +
  311. crypto_rand_int_range(1, dos_cc_defense_time_period / 2);
  312. }
  313. /* Return true iff the given channel address is marked as malicious. This is
  314. * called a lot and part of the fast path of handling cells. It has to remain
  315. * as fast as we can. */
  316. static int
  317. cc_channel_addr_is_marked(channel_t *chan)
  318. {
  319. time_t now;
  320. tor_addr_t addr;
  321. clientmap_entry_t *entry;
  322. cc_client_stats_t *stats = NULL;
  323. if (chan == NULL) {
  324. goto end;
  325. }
  326. /* Must be a client connection else we ignore. */
  327. if (!channel_is_client(chan)) {
  328. goto end;
  329. }
  330. /* Without an IP address, nothing can work. */
  331. if (!channel_get_addr_if_possible(chan, &addr)) {
  332. goto end;
  333. }
  334. /* We are only interested in client connection from the geoip cache. */
  335. entry = geoip_lookup_client(&addr, NULL, GEOIP_CLIENT_CONNECT);
  336. if (entry == NULL) {
  337. /* We can have a connection creating circuits but not tracked by the geoip
  338. * cache. Once this DoS subsystem is enabled, we can end up here with no
  339. * entry for the channel. */
  340. goto end;
  341. }
  342. now = approx_time();
  343. stats = &entry->dos_stats.cc_stats;
  344. end:
  345. return stats && stats->marked_until_ts >= now;
  346. }
  347. /* Concurrent connection private API. */
  348. /* Free everything for the connection DoS mitigation subsystem. */
  349. static void
  350. conn_free_all(void)
  351. {
  352. dos_conn_enabled = 0;
  353. }
  354. /* Called when the consensus has changed. Do appropriate actions for the
  355. * connection mitigation subsystem. */
  356. static void
  357. conn_consensus_has_changed(const networkstatus_t *ns)
  358. {
  359. /* Looking at the consensus, is the connection mitigation subsystem enabled?
  360. * If not and it was enabled before, clean it up. */
  361. if (dos_conn_enabled && !get_param_conn_enabled(ns)) {
  362. conn_free_all();
  363. }
  364. }
  365. /* General private API */
  366. /* Return true iff we have at least one DoS detection enabled. This is used to
  367. * decide if we need to allocate any kind of high level DoS object. */
  368. static inline int
  369. dos_is_enabled(void)
  370. {
  371. return (dos_cc_enabled || dos_conn_enabled);
  372. }
  373. /* Circuit creation public API. */
  374. /* Called when a CREATE cell is received from the given channel. */
  375. void
  376. dos_cc_new_create_cell(channel_t *chan)
  377. {
  378. tor_addr_t addr;
  379. clientmap_entry_t *entry;
  380. tor_assert(chan);
  381. /* Skip everything if not enabled. */
  382. if (!dos_cc_enabled) {
  383. goto end;
  384. }
  385. /* Must be a client connection else we ignore. */
  386. if (!channel_is_client(chan)) {
  387. goto end;
  388. }
  389. /* Without an IP address, nothing can work. */
  390. if (!channel_get_addr_if_possible(chan, &addr)) {
  391. goto end;
  392. }
  393. /* We are only interested in client connection from the geoip cache. */
  394. entry = geoip_lookup_client(&addr, NULL, GEOIP_CLIENT_CONNECT);
  395. if (entry == NULL) {
  396. /* We can have a connection creating circuits but not tracked by the geoip
  397. * cache. Once this DoS subsystem is enabled, we can end up here with no
  398. * entry for the channel. */
  399. goto end;
  400. }
  401. /* General comment. Even though the client can already be marked as
  402. * malicious, we continue to track statistics. If it keeps going above
  403. * threshold while marked, the defense period time will grow longer. There
  404. * is really no point at unmarking a client that keeps DoSing us. */
  405. /* First of all, we'll try to refill the circuit bucket opportunistically
  406. * before we assess. */
  407. cc_stats_refill_bucket(&entry->dos_stats.cc_stats, &addr);
  408. /* Take a token out of the circuit bucket if we are above 0 so we don't
  409. * underflow the bucket. */
  410. if (entry->dos_stats.cc_stats.circuit_bucket > 0) {
  411. entry->dos_stats.cc_stats.circuit_bucket--;
  412. }
  413. /* This is the detection. Assess at every CREATE cell if the client should
  414. * get marked as malicious. This should be kept as fast as possible. */
  415. if (cc_has_exhausted_circuits(&entry->dos_stats)) {
  416. /* If this is the first time we mark this entry, log it a info level.
  417. * Under heavy DDoS, logging each time we mark would results in lots and
  418. * lots of logs. */
  419. if (entry->dos_stats.cc_stats.marked_until_ts == 0) {
  420. log_debug(LD_DOS, "Detected circuit creation DoS by address: %s",
  421. fmt_addr(&addr));
  422. cc_num_marked_addrs++;
  423. }
  424. cc_mark_client(&entry->dos_stats.cc_stats);
  425. }
  426. end:
  427. return;
  428. }
  429. /* Return the defense type that should be used for this circuit.
  430. *
  431. * This is part of the fast path and called a lot. */
  432. dos_cc_defense_type_t
  433. dos_cc_get_defense_type(channel_t *chan)
  434. {
  435. tor_assert(chan);
  436. /* Skip everything if not enabled. */
  437. if (!dos_cc_enabled) {
  438. goto end;
  439. }
  440. /* On an OR circuit, we'll check if the previous channel is a marked client
  441. * connection detected by our DoS circuit creation mitigation subsystem. */
  442. if (cc_channel_addr_is_marked(chan)) {
  443. /* We've just assess that this circuit should trigger a defense for the
  444. * cell it just seen. Note it down. */
  445. cc_num_rejected_cells++;
  446. return dos_cc_defense_type;
  447. }
  448. end:
  449. return DOS_CC_DEFENSE_NONE;
  450. }
  451. /* Concurrent connection detection public API. */
  452. /* Return true iff the given address is permitted to open another connection.
  453. * A defense value is returned for the caller to take appropriate actions. */
  454. dos_conn_defense_type_t
  455. dos_conn_addr_get_defense_type(const tor_addr_t *addr)
  456. {
  457. clientmap_entry_t *entry;
  458. tor_assert(addr);
  459. /* Skip everything if not enabled. */
  460. if (!dos_conn_enabled) {
  461. goto end;
  462. }
  463. /* We are only interested in client connection from the geoip cache. */
  464. entry = geoip_lookup_client(addr, NULL, GEOIP_CLIENT_CONNECT);
  465. if (entry == NULL) {
  466. goto end;
  467. }
  468. /* Need to be above the maximum concurrent connection count to trigger a
  469. * defense. */
  470. if (entry->dos_stats.concurrent_count > dos_conn_max_concurrent_count) {
  471. conn_num_addr_rejected++;
  472. return dos_conn_defense_type;
  473. }
  474. end:
  475. return DOS_CONN_DEFENSE_NONE;
  476. }
  477. /* General API */
  478. /* Take any appropriate actions for the given geoip entry that is about to get
  479. * freed. This is called for every entry that is being freed.
  480. *
  481. * This function will clear out the connection tracked flag if the concurrent
  482. * count of the entry is above 0 so if those connections end up being seen by
  483. * this subsystem, we won't try to decrement the counter for a new geoip entry
  484. * that might have been added after this call for the same address. */
  485. void
  486. dos_geoip_entry_about_to_free(const clientmap_entry_t *geoip_ent)
  487. {
  488. tor_assert(geoip_ent);
  489. /* The count is down to 0 meaning no connections right now, we can safely
  490. * clear the geoip entry from the cache. */
  491. if (geoip_ent->dos_stats.concurrent_count == 0) {
  492. goto end;
  493. }
  494. /* For each connection matching the geoip entry address, we'll clear the
  495. * tracked flag because the entry is about to get removed from the geoip
  496. * cache. We do not try to decrement if the flag is not set. */
  497. SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
  498. if (conn->type == CONN_TYPE_OR) {
  499. or_connection_t *or_conn = TO_OR_CONN(conn);
  500. if (!tor_addr_compare(&geoip_ent->addr, &or_conn->real_addr,
  501. CMP_EXACT)) {
  502. or_conn->tracked_for_dos_mitigation = 0;
  503. }
  504. }
  505. } SMARTLIST_FOREACH_END(conn);
  506. end:
  507. return;
  508. }
  509. /* Note down that we've just refused a single hop client. This increments a
  510. * counter later used for the heartbeat. */
  511. void
  512. dos_note_refuse_single_hop_client(void)
  513. {
  514. num_single_hop_client_refused++;
  515. }
  516. /* Return true iff single hop client connection (ESTABLISH_RENDEZVOUS) should
  517. * be refused. */
  518. int
  519. dos_should_refuse_single_hop_client(void)
  520. {
  521. /* If we aren't a public relay, this shouldn't apply to anything. */
  522. if (!public_server_mode(get_options())) {
  523. return 0;
  524. }
  525. if (get_options()->DoSRefuseSingleHopClientRendezvous != -1) {
  526. return get_options()->DoSRefuseSingleHopClientRendezvous;
  527. }
  528. return (int) networkstatus_get_param(NULL,
  529. "DoSRefuseSingleHopClientRendezvous",
  530. 0 /* default */, 0, 1);
  531. }
  532. /* Log a heartbeat message with some statistics. */
  533. void
  534. dos_log_heartbeat(void)
  535. {
  536. char *conn_msg = NULL;
  537. char *cc_msg = NULL;
  538. char *single_hop_client_msg = NULL;
  539. if (!dos_is_enabled()) {
  540. goto end;
  541. }
  542. if (dos_cc_enabled) {
  543. tor_asprintf(&cc_msg,
  544. " %" PRIu64 " circuits rejected,"
  545. " %" PRIu32 " marked addresses.",
  546. cc_num_rejected_cells, cc_num_marked_addrs);
  547. }
  548. if (dos_conn_enabled) {
  549. tor_asprintf(&conn_msg,
  550. " %" PRIu64 " connections closed.",
  551. conn_num_addr_rejected);
  552. }
  553. if (dos_should_refuse_single_hop_client()) {
  554. tor_asprintf(&single_hop_client_msg,
  555. " %" PRIu64 " single hop clients refused.",
  556. num_single_hop_client_refused);
  557. }
  558. log_notice(LD_HEARTBEAT,
  559. "DoS mitigation since startup:%s%s%s",
  560. (cc_msg != NULL) ? cc_msg : " [cc not enabled]",
  561. (conn_msg != NULL) ? conn_msg : " [conn not enabled]",
  562. (single_hop_client_msg != NULL) ? single_hop_client_msg : "");
  563. tor_free(conn_msg);
  564. tor_free(cc_msg);
  565. tor_free(single_hop_client_msg);
  566. end:
  567. return;
  568. }
  569. /* Called when a new client connection has been established on the given
  570. * address. */
  571. void
  572. dos_new_client_conn(or_connection_t *or_conn)
  573. {
  574. clientmap_entry_t *entry;
  575. tor_assert(or_conn);
  576. /* Past that point, we know we have at least one DoS detection subsystem
  577. * enabled so we'll start allocating stuff. */
  578. if (!dos_is_enabled()) {
  579. goto end;
  580. }
  581. /* We ignore any known address meaning an address of a known relay. The
  582. * reason to do so is because network reentry is possible where a client
  583. * connection comes from an Exit node. Even when we'll fix reentry, this is
  584. * a robust defense to keep in place. */
  585. if (nodelist_probably_contains_address(&or_conn->real_addr)) {
  586. goto end;
  587. }
  588. /* We are only interested in client connection from the geoip cache. */
  589. entry = geoip_lookup_client(&or_conn->real_addr, NULL,
  590. GEOIP_CLIENT_CONNECT);
  591. if (BUG(entry == NULL)) {
  592. /* Should never happen because we note down the address in the geoip
  593. * cache before this is called. */
  594. goto end;
  595. }
  596. entry->dos_stats.concurrent_count++;
  597. or_conn->tracked_for_dos_mitigation = 1;
  598. log_debug(LD_DOS, "Client address %s has now %u concurrent connections.",
  599. fmt_addr(&or_conn->real_addr),
  600. entry->dos_stats.concurrent_count);
  601. end:
  602. return;
  603. }
  604. /* Called when a client connection for the given IP address has been closed. */
  605. void
  606. dos_close_client_conn(const or_connection_t *or_conn)
  607. {
  608. clientmap_entry_t *entry;
  609. tor_assert(or_conn);
  610. /* We have to decrement the count on tracked connection only even if the
  611. * subsystem has been disabled at runtime because it might be re-enabled
  612. * after and we need to keep a synchronized counter at all time. */
  613. if (!or_conn->tracked_for_dos_mitigation) {
  614. goto end;
  615. }
  616. /* We are only interested in client connection from the geoip cache. */
  617. entry = geoip_lookup_client(&or_conn->real_addr, NULL,
  618. GEOIP_CLIENT_CONNECT);
  619. if (entry == NULL) {
  620. /* This can happen because we can close a connection before the channel
  621. * got to be noted down in the geoip cache. */
  622. goto end;
  623. }
  624. /* Extra super duper safety. Going below 0 means an underflow which could
  625. * lead to most likely a false positive. In theory, this should never happen
  626. * but lets be extra safe. */
  627. if (BUG(entry->dos_stats.concurrent_count == 0)) {
  628. goto end;
  629. }
  630. entry->dos_stats.concurrent_count--;
  631. log_debug(LD_DOS, "Client address %s has lost a connection. Concurrent "
  632. "connections are now at %u",
  633. fmt_addr(&or_conn->real_addr),
  634. entry->dos_stats.concurrent_count);
  635. end:
  636. return;
  637. }
  638. /* Called when the consensus has changed. We might have new consensus
  639. * parameters to look at. */
  640. void
  641. dos_consensus_has_changed(const networkstatus_t *ns)
  642. {
  643. /* There are two ways to configure this subsystem, one at startup through
  644. * dos_init() which is called when the options are parsed. And this one
  645. * through the consensus. We don't want to enable any DoS mitigation if we
  646. * aren't a public relay. */
  647. if (!public_server_mode(get_options())) {
  648. return;
  649. }
  650. cc_consensus_has_changed(ns);
  651. conn_consensus_has_changed(ns);
  652. /* We were already enabled or we just became enabled but either way, set the
  653. * consensus parameters for all subsystems. */
  654. set_dos_parameters(ns);
  655. }
  656. /* Return true iff the DoS mitigation subsystem is enabled. */
  657. int
  658. dos_enabled(void)
  659. {
  660. return dos_is_enabled();
  661. }
  662. /* Free everything from the Denial of Service subsystem. */
  663. void
  664. dos_free_all(void)
  665. {
  666. /* Free the circuit creation mitigation subsystem. It is safe to do this
  667. * even if it wasn't initialized. */
  668. cc_free_all();
  669. /* Free the connection mitigation subsystem. It is safe to do this even if
  670. * it wasn't initialized. */
  671. conn_free_all();
  672. }
  673. /* Initialize the Denial of Service subsystem. */
  674. void
  675. dos_init(void)
  676. {
  677. /* To initialize, we only need to get the parameters. */
  678. set_dos_parameters(NULL);
  679. }