dos.c 26 KB

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