dos.c 24 KB

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