policies.c 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2008, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file policies.c
  7. * \brief Code to parse and use address policies and exit policies.
  8. **/
  9. #include "or.h"
  10. #include "ht.h"
  11. /** Policy that addresses for incoming SOCKS connections must match. */
  12. static smartlist_t *socks_policy = NULL;
  13. /** Policy that addresses for incoming directory connections must match. */
  14. static smartlist_t *dir_policy = NULL;
  15. /** Policy that addresses for incoming router descriptors must match in order
  16. * to be published by us. */
  17. static smartlist_t *authdir_reject_policy = NULL;
  18. /** Policy that addresses for incoming router descriptors must match in order
  19. * to be marked as valid in our networkstatus. */
  20. static smartlist_t *authdir_invalid_policy = NULL;
  21. /** Policy that addresses for incoming router descriptors must <b>not</b>
  22. * match in order to not be marked as BadDirectory. */
  23. static smartlist_t *authdir_baddir_policy = NULL;
  24. /** Policy that addresses for incoming router descriptors must <b>not</b>
  25. * match in order to not be marked as BadExit. */
  26. static smartlist_t *authdir_badexit_policy = NULL;
  27. /** Parsed addr_policy_t describing which addresses we believe we can start
  28. * circuits at. */
  29. static smartlist_t *reachable_or_addr_policy = NULL;
  30. /** Parsed addr_policy_t describing which addresses we believe we can connect
  31. * to directories at. */
  32. static smartlist_t *reachable_dir_addr_policy = NULL;
  33. /** Element of an exit policy summary */
  34. typedef struct policy_summary_item_t {
  35. uint16_t prt_min; /**< Lowest port number to accept/reject. */
  36. uint16_t prt_max; /**< Highest port number to accept/reject. */
  37. uint64_t reject_count; /**< Number of IP-Addresses that are rejected to
  38. this portrange. */
  39. int accepted:1; /** Has this port already been accepted */
  40. } policy_summary_item_t;
  41. /** Private networks. This list is used in two places, once to expand the
  42. * "private" keyword when parsing our own exit policy, secondly to ignore
  43. * just such networks when building exit policy summaries. It is important
  44. * that all authorities agree on that list when creating summaries, so don't
  45. * just change this without a proper migration plan and a proposal and stuff.
  46. */
  47. static const char *private_nets[] = {
  48. "0.0.0.0/8", "169.254.0.0/16",
  49. "127.0.0.0/8", "192.168.0.0/16", "10.0.0.0/8", "172.16.0.0/12",
  50. // "fc00::/7", "fe80::/10", "fec0::/10", "::/127",
  51. NULL };
  52. /** Replace all "private" entries in *<b>policy</b> with their expanded
  53. * equivalents. */
  54. void
  55. policy_expand_private(smartlist_t **policy)
  56. {
  57. uint16_t port_min, port_max;
  58. int i;
  59. smartlist_t *tmp;
  60. if (!*policy) /*XXXX disallow NULL policies? */
  61. return;
  62. tmp = smartlist_create();
  63. SMARTLIST_FOREACH(*policy, addr_policy_t *, p,
  64. {
  65. if (! p->is_private) {
  66. smartlist_add(tmp, p);
  67. continue;
  68. }
  69. for (i = 0; private_nets[i]; ++i) {
  70. addr_policy_t policy;
  71. memcpy(&policy, p, sizeof(addr_policy_t));
  72. policy.is_private = 0;
  73. policy.is_canonical = 0;
  74. if (tor_addr_parse_mask_ports(private_nets[i], &policy.addr,
  75. &policy.maskbits, &port_min, &port_max)<0) {
  76. tor_assert(0);
  77. }
  78. smartlist_add(tmp, addr_policy_get_canonical_entry(&policy));
  79. }
  80. addr_policy_free(p);
  81. });
  82. smartlist_free(*policy);
  83. *policy = tmp;
  84. }
  85. /**
  86. * Given a linked list of config lines containing "allow" and "deny"
  87. * tokens, parse them and append the result to <b>dest</b>. Return -1
  88. * if any tokens are malformed (and don't append any), else return 0.
  89. *
  90. * If <b>assume_action</b> is nonnegative, then insert its action
  91. * (ADDR_POLICY_ACCEPT or ADDR_POLICY_REJECT) for items that specify no
  92. * action.
  93. */
  94. static int
  95. parse_addr_policy(config_line_t *cfg, smartlist_t **dest,
  96. int assume_action)
  97. {
  98. smartlist_t *result;
  99. smartlist_t *entries;
  100. addr_policy_t *item;
  101. int r = 0;
  102. if (!cfg)
  103. return 0;
  104. result = smartlist_create();
  105. entries = smartlist_create();
  106. for (; cfg; cfg = cfg->next) {
  107. smartlist_split_string(entries, cfg->value, ",",
  108. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  109. SMARTLIST_FOREACH(entries, const char *, ent,
  110. {
  111. log_debug(LD_CONFIG,"Adding new entry '%s'",ent);
  112. item = router_parse_addr_policy_item_from_string(ent, assume_action);
  113. if (item) {
  114. smartlist_add(result, item);
  115. } else {
  116. log_warn(LD_CONFIG,"Malformed policy '%s'.", ent);
  117. r = -1;
  118. }
  119. });
  120. SMARTLIST_FOREACH(entries, char *, ent, tor_free(ent));
  121. smartlist_clear(entries);
  122. }
  123. smartlist_free(entries);
  124. if (r == -1) {
  125. addr_policy_list_free(result);
  126. } else {
  127. policy_expand_private(&result);
  128. if (*dest) {
  129. smartlist_add_all(*dest, result);
  130. smartlist_free(result);
  131. } else {
  132. *dest = result;
  133. }
  134. }
  135. return r;
  136. }
  137. /** Helper: parse the Reachable(Dir|OR)?Addresses fields into
  138. * reachable_(or|dir)_addr_policy. The options should already have
  139. * been validated by validate_addr_policies.
  140. */
  141. static int
  142. parse_reachable_addresses(void)
  143. {
  144. or_options_t *options = get_options();
  145. int ret = 0;
  146. if (options->ReachableDirAddresses &&
  147. options->ReachableORAddresses &&
  148. options->ReachableAddresses) {
  149. log_warn(LD_CONFIG,
  150. "Both ReachableDirAddresses and ReachableORAddresses are set. "
  151. "ReachableAddresses setting will be ignored.");
  152. }
  153. addr_policy_list_free(reachable_or_addr_policy);
  154. reachable_or_addr_policy = NULL;
  155. if (!options->ReachableORAddresses && options->ReachableAddresses)
  156. log_info(LD_CONFIG,
  157. "Using ReachableAddresses as ReachableORAddresses.");
  158. if (parse_addr_policy(options->ReachableORAddresses ?
  159. options->ReachableORAddresses :
  160. options->ReachableAddresses,
  161. &reachable_or_addr_policy, ADDR_POLICY_ACCEPT)) {
  162. log_warn(LD_CONFIG,
  163. "Error parsing Reachable%sAddresses entry; ignoring.",
  164. options->ReachableORAddresses ? "OR" : "");
  165. ret = -1;
  166. }
  167. addr_policy_list_free(reachable_dir_addr_policy);
  168. reachable_dir_addr_policy = NULL;
  169. if (!options->ReachableDirAddresses && options->ReachableAddresses)
  170. log_info(LD_CONFIG,
  171. "Using ReachableAddresses as ReachableDirAddresses");
  172. if (parse_addr_policy(options->ReachableDirAddresses ?
  173. options->ReachableDirAddresses :
  174. options->ReachableAddresses,
  175. &reachable_dir_addr_policy, ADDR_POLICY_ACCEPT)) {
  176. if (options->ReachableDirAddresses)
  177. log_warn(LD_CONFIG,
  178. "Error parsing ReachableDirAddresses entry; ignoring.");
  179. ret = -1;
  180. }
  181. return ret;
  182. }
  183. /** Return true iff the firewall options might block any address:port
  184. * combination.
  185. */
  186. int
  187. firewall_is_fascist_or(void)
  188. {
  189. return reachable_or_addr_policy != NULL;
  190. }
  191. /** Return true iff <b>policy</b> (possibly NULL) will allow a
  192. * connection to <b>addr</b>:<b>port</b>.
  193. */
  194. static int
  195. addr_policy_permits_tor_addr(const tor_addr_t *addr, uint16_t port,
  196. smartlist_t *policy)
  197. {
  198. addr_policy_result_t p;
  199. p = compare_tor_addr_to_addr_policy(addr, port, policy);
  200. switch (p) {
  201. case ADDR_POLICY_PROBABLY_ACCEPTED:
  202. case ADDR_POLICY_ACCEPTED:
  203. return 1;
  204. case ADDR_POLICY_PROBABLY_REJECTED:
  205. case ADDR_POLICY_REJECTED:
  206. return 0;
  207. default:
  208. log_warn(LD_BUG, "Unexpected result: %d", (int)p);
  209. return 0;
  210. }
  211. }
  212. /** Return true iff <b> policy</b> (possibly NULL) will allow a connection to
  213. * <b>addr</b>:<b>port</b>. <b>addr</b> is an IPv4 address given in host
  214. * order. */
  215. /* XXXX deprecate when possible. */
  216. static int
  217. addr_policy_permits_address(uint32_t addr, uint16_t port,
  218. smartlist_t *policy)
  219. {
  220. tor_addr_t a;
  221. tor_addr_from_ipv4h(&a, addr);
  222. return addr_policy_permits_tor_addr(&a, port, policy);
  223. }
  224. /** Return true iff we think our firewall will let us make an OR connection to
  225. * addr:port. */
  226. int
  227. fascist_firewall_allows_address_or(const tor_addr_t *addr, uint16_t port)
  228. {
  229. return addr_policy_permits_tor_addr(addr, port,
  230. reachable_or_addr_policy);
  231. }
  232. /** Return true iff we think our firewall will let us make an OR connection to
  233. * <b>ri</b>. */
  234. int
  235. fascist_firewall_allows_or(routerinfo_t *ri)
  236. {
  237. /* XXXX proposal 118 */
  238. tor_addr_t addr;
  239. tor_addr_from_ipv4h(&addr, ri->addr);
  240. return fascist_firewall_allows_address_or(&addr, ri->or_port);
  241. }
  242. /** Return true iff we think our firewall will let us make a directory
  243. * connection to addr:port. */
  244. int
  245. fascist_firewall_allows_address_dir(const tor_addr_t *addr, uint16_t port)
  246. {
  247. return addr_policy_permits_tor_addr(addr, port,
  248. reachable_dir_addr_policy);
  249. }
  250. /** Return 1 if <b>addr</b> is permitted to connect to our dir port,
  251. * based on <b>dir_policy</b>. Else return 0.
  252. */
  253. int
  254. dir_policy_permits_address(const tor_addr_t *addr)
  255. {
  256. return addr_policy_permits_tor_addr(addr, 1, dir_policy);
  257. }
  258. /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
  259. * based on <b>socks_policy</b>. Else return 0.
  260. */
  261. int
  262. socks_policy_permits_address(const tor_addr_t *addr)
  263. {
  264. return addr_policy_permits_tor_addr(addr, 1, socks_policy);
  265. }
  266. /** Return 1 if <b>addr</b>:<b>port</b> is permitted to publish to our
  267. * directory, based on <b>authdir_reject_policy</b>. Else return 0.
  268. */
  269. int
  270. authdir_policy_permits_address(uint32_t addr, uint16_t port)
  271. {
  272. return addr_policy_permits_address(addr, port, authdir_reject_policy);
  273. }
  274. /** Return 1 if <b>addr</b>:<b>port</b> is considered valid in our
  275. * directory, based on <b>authdir_invalid_policy</b>. Else return 0.
  276. */
  277. int
  278. authdir_policy_valid_address(uint32_t addr, uint16_t port)
  279. {
  280. return addr_policy_permits_address(addr, port, authdir_invalid_policy);
  281. }
  282. /** Return 1 if <b>addr</b>:<b>port</b> should be marked as a bad dir,
  283. * based on <b>authdir_baddir_policy</b>. Else return 0.
  284. */
  285. int
  286. authdir_policy_baddir_address(uint32_t addr, uint16_t port)
  287. {
  288. return ! addr_policy_permits_address(addr, port, authdir_baddir_policy);
  289. }
  290. /** Return 1 if <b>addr</b>:<b>port</b> should be marked as a bad exit,
  291. * based on <b>authdir_badexit_policy</b>. Else return 0.
  292. */
  293. int
  294. authdir_policy_badexit_address(uint32_t addr, uint16_t port)
  295. {
  296. return ! addr_policy_permits_address(addr, port, authdir_badexit_policy);
  297. }
  298. #define REJECT(arg) \
  299. STMT_BEGIN *msg = tor_strdup(arg); goto err; STMT_END
  300. /** Config helper: If there's any problem with the policy configuration
  301. * options in <b>options</b>, return -1 and set <b>msg</b> to a newly
  302. * allocated description of the error. Else return 0. */
  303. int
  304. validate_addr_policies(or_options_t *options, char **msg)
  305. {
  306. /* XXXX Maybe merge this into parse_policies_from_options, to make sure
  307. * that the two can't go out of sync. */
  308. smartlist_t *addr_policy=NULL;
  309. *msg = NULL;
  310. if (policies_parse_exit_policy(options->ExitPolicy, &addr_policy,
  311. options->ExitPolicyRejectPrivate, NULL))
  312. REJECT("Error in ExitPolicy entry.");
  313. /* The rest of these calls *append* to addr_policy. So don't actually
  314. * use the results for anything other than checking if they parse! */
  315. if (parse_addr_policy(options->DirPolicy, &addr_policy, -1))
  316. REJECT("Error in DirPolicy entry.");
  317. if (parse_addr_policy(options->SocksPolicy, &addr_policy, -1))
  318. REJECT("Error in SocksPolicy entry.");
  319. if (parse_addr_policy(options->AuthDirReject, &addr_policy,
  320. ADDR_POLICY_REJECT))
  321. REJECT("Error in AuthDirReject entry.");
  322. if (parse_addr_policy(options->AuthDirInvalid, &addr_policy,
  323. ADDR_POLICY_REJECT))
  324. REJECT("Error in AuthDirInvalid entry.");
  325. if (parse_addr_policy(options->AuthDirBadDir, &addr_policy,
  326. ADDR_POLICY_REJECT))
  327. REJECT("Error in AuthDirBadDir entry.");
  328. if (parse_addr_policy(options->AuthDirBadExit, &addr_policy,
  329. ADDR_POLICY_REJECT))
  330. REJECT("Error in AuthDirBadExit entry.");
  331. if (parse_addr_policy(options->ReachableAddresses, &addr_policy,
  332. ADDR_POLICY_ACCEPT))
  333. REJECT("Error in ReachableAddresses entry.");
  334. if (parse_addr_policy(options->ReachableORAddresses, &addr_policy,
  335. ADDR_POLICY_ACCEPT))
  336. REJECT("Error in ReachableORAddresses entry.");
  337. if (parse_addr_policy(options->ReachableDirAddresses, &addr_policy,
  338. ADDR_POLICY_ACCEPT))
  339. REJECT("Error in ReachableDirAddresses entry.");
  340. if (parse_addr_policy(options->AuthDirReject, &addr_policy,
  341. ADDR_POLICY_REJECT))
  342. REJECT("Error in AuthDirReject entry.");
  343. if (parse_addr_policy(options->AuthDirInvalid, &addr_policy,
  344. ADDR_POLICY_REJECT))
  345. REJECT("Error in AuthDirInvalid entry.");
  346. err:
  347. addr_policy_list_free(addr_policy);
  348. return *msg ? -1 : 0;
  349. #undef REJECT
  350. }
  351. /** Parse <b>string</b> in the same way that the exit policy
  352. * is parsed, and put the processed version in *<b>policy</b>.
  353. * Ignore port specifiers.
  354. */
  355. static int
  356. load_policy_from_option(config_line_t *config, smartlist_t **policy,
  357. int assume_action)
  358. {
  359. int r;
  360. addr_policy_list_free(*policy);
  361. *policy = NULL;
  362. r = parse_addr_policy(config, policy, assume_action);
  363. if (r < 0) {
  364. return -1;
  365. }
  366. if (*policy) {
  367. SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, n) {
  368. /* ports aren't used in these. */
  369. if (n->prt_min > 1 || n->prt_max != 65535) {
  370. addr_policy_t newp, *c;
  371. memcpy(&newp, n, sizeof(newp));
  372. newp.prt_min = 1;
  373. newp.prt_max = 65535;
  374. c = addr_policy_get_canonical_entry(&newp);
  375. SMARTLIST_REPLACE_CURRENT(*policy, n, c);
  376. addr_policy_free(n);
  377. }
  378. } SMARTLIST_FOREACH_END(n);
  379. }
  380. return 0;
  381. }
  382. /** Set all policies based on <b>options</b>, which should have been validated
  383. * first by validate_addr_policies. */
  384. int
  385. policies_parse_from_options(or_options_t *options)
  386. {
  387. int ret = 0;
  388. if (load_policy_from_option(options->SocksPolicy, &socks_policy, -1) < 0)
  389. ret = -1;
  390. if (load_policy_from_option(options->DirPolicy, &dir_policy, -1) < 0)
  391. ret = -1;
  392. if (load_policy_from_option(options->AuthDirReject,
  393. &authdir_reject_policy, ADDR_POLICY_REJECT) < 0)
  394. ret = -1;
  395. if (load_policy_from_option(options->AuthDirInvalid,
  396. &authdir_invalid_policy, ADDR_POLICY_REJECT) < 0)
  397. ret = -1;
  398. if (load_policy_from_option(options->AuthDirBadDir,
  399. &authdir_baddir_policy, ADDR_POLICY_REJECT) < 0)
  400. ret = -1;
  401. if (load_policy_from_option(options->AuthDirBadExit,
  402. &authdir_badexit_policy, ADDR_POLICY_REJECT) < 0)
  403. ret = -1;
  404. if (parse_reachable_addresses() < 0)
  405. ret = -1;
  406. return ret;
  407. }
  408. /** Compare two provided address policy items, and return -1, 0, or 1
  409. * if the first is less than, equal to, or greater than the second. */
  410. static int
  411. cmp_single_addr_policy(addr_policy_t *a, addr_policy_t *b)
  412. {
  413. int r;
  414. if ((r=((int)a->policy_type - (int)b->policy_type)))
  415. return r;
  416. if ((r=((int)a->is_private - (int)b->is_private)))
  417. return r;
  418. if ((r=tor_addr_compare(&a->addr, &b->addr, CMP_EXACT)))
  419. return r;
  420. if ((r=((int)a->maskbits - (int)b->maskbits)))
  421. return r;
  422. if ((r=((int)a->prt_min - (int)b->prt_min)))
  423. return r;
  424. if ((r=((int)a->prt_max - (int)b->prt_max)))
  425. return r;
  426. return 0;
  427. }
  428. /** Like cmp_single_addr_policy() above, but looks at the
  429. * whole set of policies in each case. */
  430. int
  431. cmp_addr_policies(smartlist_t *a, smartlist_t *b)
  432. {
  433. int r, i;
  434. int len_a = a ? smartlist_len(a) : 0;
  435. int len_b = b ? smartlist_len(b) : 0;
  436. for (i = 0; i < len_a && i < len_b; ++i) {
  437. if ((r = cmp_single_addr_policy(smartlist_get(a, i), smartlist_get(b, i))))
  438. return r;
  439. }
  440. if (i == len_a && i == len_b)
  441. return 0;
  442. if (i < len_a)
  443. return -1;
  444. else
  445. return 1;
  446. }
  447. /** Node in hashtable used to store address policy entries. */
  448. typedef struct policy_map_ent_t {
  449. HT_ENTRY(policy_map_ent_t) node;
  450. addr_policy_t *policy;
  451. } policy_map_ent_t;
  452. static HT_HEAD(policy_map, policy_map_ent_t) policy_root = HT_INITIALIZER();
  453. /** Return true iff a and b are equal. */
  454. static INLINE int
  455. policy_eq(policy_map_ent_t *a, policy_map_ent_t *b)
  456. {
  457. return cmp_single_addr_policy(a->policy, b->policy) == 0;
  458. }
  459. /** Return a hashcode for <b>ent</b> */
  460. static unsigned int
  461. policy_hash(policy_map_ent_t *ent)
  462. {
  463. addr_policy_t *a = ent->policy;
  464. unsigned int r;
  465. if (a->is_private)
  466. r = 0x1234abcd;
  467. else
  468. r = tor_addr_hash(&a->addr);
  469. r += a->prt_min << 8;
  470. r += a->prt_max << 16;
  471. r += a->maskbits;
  472. if (a->policy_type == ADDR_POLICY_REJECT)
  473. r ^= 0xffffffff;
  474. return r;
  475. }
  476. HT_PROTOTYPE(policy_map, policy_map_ent_t, node, policy_hash,
  477. policy_eq)
  478. HT_GENERATE(policy_map, policy_map_ent_t, node, policy_hash,
  479. policy_eq, 0.6, malloc, realloc, free)
  480. /** Given a pointer to an addr_policy_t, return a copy of the pointer to the
  481. * "canonical" copy of that addr_policy_t; the canonical copy is a single
  482. * reference-counted object. */
  483. addr_policy_t *
  484. addr_policy_get_canonical_entry(addr_policy_t *e)
  485. {
  486. policy_map_ent_t search, *found;
  487. if (e->is_canonical)
  488. return e;
  489. search.policy = e;
  490. found = HT_FIND(policy_map, &policy_root, &search);
  491. if (!found) {
  492. found = tor_malloc_zero(sizeof(policy_map_ent_t));
  493. found->policy = tor_memdup(e, sizeof(addr_policy_t));
  494. found->policy->is_canonical = 1;
  495. found->policy->refcnt = 0;
  496. HT_INSERT(policy_map, &policy_root, found);
  497. }
  498. tor_assert(!cmp_single_addr_policy(found->policy, e));
  499. ++found->policy->refcnt;
  500. return found->policy;
  501. }
  502. /** As compare_tor_addr_to_addr_policy, but instead of a tor_addr_t, takes
  503. * in host order. */
  504. addr_policy_result_t
  505. compare_addr_to_addr_policy(uint32_t addr, uint16_t port,
  506. const smartlist_t *policy)
  507. {
  508. /*XXXX deprecate this function when possible. */
  509. tor_addr_t a;
  510. tor_addr_from_ipv4h(&a, addr);
  511. return compare_tor_addr_to_addr_policy(&a, port, policy);
  512. }
  513. /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
  514. * addr and port are both known. */
  515. static addr_policy_result_t
  516. compare_known_tor_addr_to_addr_policy(const tor_addr_t *addr, uint16_t port,
  517. const smartlist_t *policy)
  518. {
  519. /* We know the address and port, and we know the policy, so we can just
  520. * compute an exact match. */
  521. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
  522. /* Address is known */
  523. if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
  524. CMP_EXACT)) {
  525. if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
  526. /* Exact match for the policy */
  527. return tmpe->policy_type == ADDR_POLICY_ACCEPT ?
  528. ADDR_POLICY_ACCEPTED : ADDR_POLICY_REJECTED;
  529. }
  530. }
  531. } SMARTLIST_FOREACH_END(tmpe);
  532. /* accept all by default. */
  533. return ADDR_POLICY_ACCEPTED;
  534. }
  535. /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
  536. * addr is known but port is not. */
  537. static addr_policy_result_t
  538. compare_known_tor_addr_to_addr_policy_noport(const tor_addr_t *addr,
  539. const smartlist_t *policy)
  540. {
  541. /* We look to see if there's a definite match. If so, we return that
  542. match's value, unless there's an intervening possible match that says
  543. something different. */
  544. int maybe_accept = 0, maybe_reject = 0;
  545. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
  546. if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
  547. CMP_EXACT)) {
  548. if (tmpe->prt_min <= 1 && tmpe->prt_max >= 65535) {
  549. /* Definitely matches, since it covers all ports. */
  550. if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
  551. /* If we already hit a clause that might trigger a 'reject', than we
  552. * can't be sure of this certain 'accept'.*/
  553. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
  554. ADDR_POLICY_ACCEPTED;
  555. } else {
  556. return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
  557. ADDR_POLICY_REJECTED;
  558. }
  559. } else {
  560. /* Might match. */
  561. if (tmpe->policy_type == ADDR_POLICY_REJECT)
  562. maybe_reject = 1;
  563. else
  564. maybe_accept = 1;
  565. }
  566. }
  567. } SMARTLIST_FOREACH_END(tmpe);
  568. /* accept all by default. */
  569. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  570. }
  571. /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
  572. * port is known but address is not. */
  573. static addr_policy_result_t
  574. compare_unknown_tor_addr_to_addr_policy(uint16_t port,
  575. const smartlist_t *policy)
  576. {
  577. /* We look to see if there's a definite match. If so, we return that
  578. match's value, unless there's an intervening possible match that says
  579. something different. */
  580. int maybe_accept = 0, maybe_reject = 0;
  581. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
  582. if (tmpe->prt_min <= port && port <= tmpe->prt_max) {
  583. if (tmpe->maskbits == 0) {
  584. /* Definitely matches, since it covers all addresses. */
  585. if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
  586. /* If we already hit a clause that might trigger a 'reject', than we
  587. * can't be sure of this certain 'accept'.*/
  588. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
  589. ADDR_POLICY_ACCEPTED;
  590. } else {
  591. return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
  592. ADDR_POLICY_REJECTED;
  593. }
  594. } else {
  595. /* Might match. */
  596. if (tmpe->policy_type == ADDR_POLICY_REJECT)
  597. maybe_reject = 1;
  598. else
  599. maybe_accept = 1;
  600. }
  601. }
  602. } SMARTLIST_FOREACH_END(tmpe);
  603. /* accept all by default. */
  604. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  605. }
  606. /** Decide whether a given addr:port is definitely accepted,
  607. * definitely rejected, probably accepted, or probably rejected by a
  608. * given policy. If <b>addr</b> is 0, we don't know the IP of the
  609. * target address. If <b>port</b> is 0, we don't know the port of the
  610. * target address. (At least one of <b>addr</b> and <b>port</b> must be
  611. * provided. If you want to know whether a policy would definitely reject
  612. * an unknown address:port, use policy_is_reject_star().)
  613. *
  614. * We could do better by assuming that some ranges never match typical
  615. * addresses (127.0.0.1, and so on). But we'll try this for now.
  616. */
  617. addr_policy_result_t
  618. compare_tor_addr_to_addr_policy(const tor_addr_t *addr, uint16_t port,
  619. const smartlist_t *policy)
  620. {
  621. if (!policy) {
  622. /* no policy? accept all. */
  623. return ADDR_POLICY_ACCEPTED;
  624. } else if (tor_addr_is_null(addr)) {
  625. tor_assert(port != 0);
  626. return compare_unknown_tor_addr_to_addr_policy(port, policy);
  627. } else if (port == 0) {
  628. return compare_known_tor_addr_to_addr_policy_noport(addr, policy);
  629. } else {
  630. return compare_known_tor_addr_to_addr_policy(addr, port, policy);
  631. }
  632. }
  633. /** Return true iff the address policy <b>a</b> covers every case that
  634. * would be covered by <b>b</b>, so that a,b is redundant. */
  635. static int
  636. addr_policy_covers(addr_policy_t *a, addr_policy_t *b)
  637. {
  638. /* We can ignore accept/reject, since "accept *:80, reject *:80" reduces
  639. * to "accept *:80". */
  640. if (a->maskbits > b->maskbits) {
  641. /* a has more fixed bits than b; it can't possibly cover b. */
  642. return 0;
  643. }
  644. if (tor_addr_compare_masked(&a->addr, &b->addr, a->maskbits, CMP_EXACT)) {
  645. /* There's a fixed bit in a that's set differently in b. */
  646. return 0;
  647. }
  648. return (a->prt_min <= b->prt_min && a->prt_max >= b->prt_max);
  649. }
  650. /** Return true iff the address policies <b>a</b> and <b>b</b> intersect,
  651. * that is, there exists an address/port that is covered by <b>a</b> that
  652. * is also covered by <b>b</b>.
  653. */
  654. static int
  655. addr_policy_intersects(addr_policy_t *a, addr_policy_t *b)
  656. {
  657. maskbits_t minbits;
  658. /* All the bits we care about are those that are set in both
  659. * netmasks. If they are equal in a and b's networkaddresses
  660. * then the networks intersect. If there is a difference,
  661. * then they do not. */
  662. if (a->maskbits < b->maskbits)
  663. minbits = a->maskbits;
  664. else
  665. minbits = b->maskbits;
  666. if (tor_addr_compare_masked(&a->addr, &b->addr, minbits, CMP_EXACT))
  667. return 0;
  668. if (a->prt_max < b->prt_min || b->prt_max < a->prt_min)
  669. return 0;
  670. return 1;
  671. }
  672. /** Add the exit policy described by <b>more</b> to <b>policy</b>.
  673. */
  674. static void
  675. append_exit_policy_string(smartlist_t **policy, const char *more)
  676. {
  677. config_line_t tmp;
  678. tmp.key = NULL;
  679. tmp.value = (char*) more;
  680. tmp.next = NULL;
  681. if (parse_addr_policy(&tmp, policy, -1)<0) {
  682. log_warn(LD_BUG, "Unable to parse internally generated policy %s",more);
  683. }
  684. }
  685. /** Detect and excise "dead code" from the policy *<b>dest</b>. */
  686. static void
  687. exit_policy_remove_redundancies(smartlist_t *dest)
  688. {
  689. addr_policy_t *ap, *tmp, *victim;
  690. int i, j;
  691. /* Step one: find a *:* entry and cut off everything after it. */
  692. for (i = 0; i < smartlist_len(dest); ++i) {
  693. ap = smartlist_get(dest, i);
  694. if (ap->maskbits == 0 && ap->prt_min <= 1 && ap->prt_max >= 65535) {
  695. /* This is a catch-all line -- later lines are unreachable. */
  696. while (i+1 < smartlist_len(dest)) {
  697. victim = smartlist_get(dest, i+1);
  698. smartlist_del(dest, i+1);
  699. addr_policy_free(victim);
  700. }
  701. break;
  702. }
  703. }
  704. /* Step two: for every entry, see if there's a redundant entry
  705. * later on, and remove it. */
  706. for (i = 0; i < smartlist_len(dest)-1; ++i) {
  707. ap = smartlist_get(dest, i);
  708. for (j = i+1; j < smartlist_len(dest); ++j) {
  709. tmp = smartlist_get(dest, j);
  710. tor_assert(j > i);
  711. if (addr_policy_covers(ap, tmp)) {
  712. char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
  713. policy_write_item(p1, sizeof(p1), tmp, 0);
  714. policy_write_item(p2, sizeof(p2), ap, 0);
  715. log(LOG_DEBUG, LD_CONFIG, "Removing exit policy %s (%d). It is made "
  716. "redundant by %s (%d).", p1, j, p2, i);
  717. smartlist_del_keeporder(dest, j--);
  718. addr_policy_free(tmp);
  719. }
  720. }
  721. }
  722. /* Step three: for every entry A, see if there's an entry B making this one
  723. * redundant later on. This is the case if A and B are of the same type
  724. * (accept/reject), A is a subset of B, and there is no other entry of
  725. * different type in between those two that intersects with A.
  726. *
  727. * Anybody want to doublecheck the logic here? XXX
  728. */
  729. for (i = 0; i < smartlist_len(dest)-1; ++i) {
  730. ap = smartlist_get(dest, i);
  731. for (j = i+1; j < smartlist_len(dest); ++j) {
  732. // tor_assert(j > i); // j starts out at i+1; j only increases; i only
  733. // // decreases.
  734. tmp = smartlist_get(dest, j);
  735. if (ap->policy_type != tmp->policy_type) {
  736. if (addr_policy_intersects(ap, tmp))
  737. break;
  738. } else { /* policy_types are equal. */
  739. if (addr_policy_covers(tmp, ap)) {
  740. char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
  741. policy_write_item(p1, sizeof(p1), ap, 0);
  742. policy_write_item(p2, sizeof(p2), tmp, 0);
  743. log(LOG_DEBUG, LD_CONFIG, "Removing exit policy %s. It is already "
  744. "covered by %s.", p1, p2);
  745. smartlist_del_keeporder(dest, i--);
  746. addr_policy_free(ap);
  747. break;
  748. }
  749. }
  750. }
  751. }
  752. }
  753. #define DEFAULT_EXIT_POLICY \
  754. "reject *:25,reject *:119,reject *:135-139,reject *:445," \
  755. "reject *:563,reject *:1214,reject *:4661-4666," \
  756. "reject *:6346-6429,reject *:6699,reject *:6881-6999,accept *:*"
  757. /** Parse the exit policy <b>cfg</b> into the linked list *<b>dest</b>. If
  758. * cfg doesn't end in an absolute accept or reject, add the default exit
  759. * policy afterwards. If <b>rejectprivate</b> is true, prepend
  760. * "reject private:*" to the policy. Return -1 if we can't parse cfg,
  761. * else return 0.
  762. */
  763. int
  764. policies_parse_exit_policy(config_line_t *cfg, smartlist_t **dest,
  765. int rejectprivate, const char *local_address)
  766. {
  767. if (rejectprivate) {
  768. append_exit_policy_string(dest, "reject private:*");
  769. if (local_address) {
  770. char buf[POLICY_BUF_LEN];
  771. tor_snprintf(buf, sizeof(buf), "reject %s:*", local_address);
  772. append_exit_policy_string(dest, buf);
  773. }
  774. }
  775. if (parse_addr_policy(cfg, dest, -1))
  776. return -1;
  777. append_exit_policy_string(dest, DEFAULT_EXIT_POLICY);
  778. exit_policy_remove_redundancies(*dest);
  779. return 0;
  780. }
  781. /** Replace the exit policy of <b>r</b> with reject *:*. */
  782. void
  783. policies_set_router_exitpolicy_to_reject_all(routerinfo_t *r)
  784. {
  785. addr_policy_t *item;
  786. addr_policy_list_free(r->exit_policy);
  787. r->exit_policy = smartlist_create();
  788. item = router_parse_addr_policy_item_from_string("reject *:*", -1);
  789. smartlist_add(r->exit_policy, item);
  790. }
  791. /** Return true iff <b>ri</b> is "useful as an exit node", meaning
  792. * it allows exit to at least one /8 address space for at least
  793. * two of ports 80, 443, and 6667. */
  794. int
  795. exit_policy_is_general_exit(smartlist_t *policy)
  796. {
  797. static const int ports[] = { 80, 443, 6667 };
  798. int n_allowed = 0;
  799. int i;
  800. if (!policy) /*XXXX disallow NULL policies? */
  801. return 0;
  802. for (i = 0; i < 3; ++i) {
  803. SMARTLIST_FOREACH(policy, addr_policy_t *, p, {
  804. if (p->prt_min > ports[i] || p->prt_max < ports[i])
  805. continue; /* Doesn't cover our port. */
  806. if (p->maskbits > 8)
  807. continue; /* Narrower than a /8. */
  808. if (tor_addr_is_loopback(&p->addr))
  809. continue; /* 127.x or ::1. */
  810. /* We have a match that is at least a /8. */
  811. if (p->policy_type == ADDR_POLICY_ACCEPT) {
  812. ++n_allowed;
  813. break; /* stop considering this port */
  814. }
  815. });
  816. }
  817. return n_allowed >= 2;
  818. }
  819. /** Return false if <b>policy</b> might permit access to some addr:port;
  820. * otherwise if we are certain it rejects everything, return true. */
  821. int
  822. policy_is_reject_star(const smartlist_t *policy)
  823. {
  824. if (!policy) /*XXXX disallow NULL policies? */
  825. return 1;
  826. SMARTLIST_FOREACH(policy, addr_policy_t *, p, {
  827. if (p->policy_type == ADDR_POLICY_ACCEPT)
  828. return 0;
  829. else if (p->policy_type == ADDR_POLICY_REJECT &&
  830. p->prt_min <= 1 && p->prt_max == 65535 &&
  831. p->maskbits == 0)
  832. return 1;
  833. });
  834. return 1;
  835. }
  836. /** Write a single address policy to the buf_len byte buffer at buf. Return
  837. * the number of characters written, or -1 on failure. */
  838. int
  839. policy_write_item(char *buf, size_t buflen, addr_policy_t *policy,
  840. int format_for_desc)
  841. {
  842. size_t written = 0;
  843. char addrbuf[TOR_ADDR_BUF_LEN];
  844. const char *addrpart;
  845. int result;
  846. const int is_accept = policy->policy_type == ADDR_POLICY_ACCEPT;
  847. const int is_ip6 = tor_addr_family(&policy->addr) == AF_INET6;
  848. tor_addr_to_str(addrbuf, &policy->addr, sizeof(addrbuf), 1);
  849. /* write accept/reject 1.2.3.4 */
  850. if (policy->is_private)
  851. addrpart = "private";
  852. else if (policy->maskbits == 0)
  853. addrpart = "*";
  854. else
  855. addrpart = addrbuf;
  856. result = tor_snprintf(buf, buflen, "%s%s%s %s",
  857. (is_ip6&&format_for_desc)?"opt ":"",
  858. is_accept ? "accept" : "reject",
  859. (is_ip6&&format_for_desc)?"6":"",
  860. addrpart);
  861. if (result < 0)
  862. return -1;
  863. written += strlen(buf);
  864. /* If the maskbits is 32 we don't need to give it. If the mask is 0,
  865. * we already wrote "*". */
  866. if (policy->maskbits < 32 && policy->maskbits > 0) {
  867. if (tor_snprintf(buf+written, buflen-written, "/%d", policy->maskbits)<0)
  868. return -1;
  869. written += strlen(buf+written);
  870. }
  871. if (policy->prt_min <= 1 && policy->prt_max == 65535) {
  872. /* There is no port set; write ":*" */
  873. if (written+4 > buflen)
  874. return -1;
  875. strlcat(buf+written, ":*", buflen-written);
  876. written += 2;
  877. } else if (policy->prt_min == policy->prt_max) {
  878. /* There is only one port; write ":80". */
  879. result = tor_snprintf(buf+written, buflen-written, ":%d", policy->prt_min);
  880. if (result<0)
  881. return -1;
  882. written += result;
  883. } else {
  884. /* There is a range of ports; write ":79-80". */
  885. result = tor_snprintf(buf+written, buflen-written, ":%d-%d",
  886. policy->prt_min, policy->prt_max);
  887. if (result<0)
  888. return -1;
  889. written += result;
  890. }
  891. if (written < buflen)
  892. buf[written] = '\0';
  893. else
  894. return -1;
  895. return (int)written;
  896. }
  897. /** Create a new exit policy summary, initially only with a single
  898. * port 1-64k item */
  899. /* XXXX This entire thing will do most stuff in O(N^2), or worse. Use an
  900. * RB-tree if that turns out to matter. */
  901. static smartlist_t *
  902. policy_summary_create(void)
  903. {
  904. smartlist_t *summary;
  905. policy_summary_item_t* item;
  906. item = tor_malloc_zero(sizeof(policy_summary_item_t));
  907. item->prt_min = 1;
  908. item->prt_max = 65535;
  909. item->reject_count = 0;
  910. item->accepted = 0;
  911. summary = smartlist_create();
  912. smartlist_add(summary, item);
  913. return summary;
  914. }
  915. /** Split the summary item in <b>item</b> at the port <b>new_starts</b>.
  916. * The current item is changed to end at new-starts - 1, the new item
  917. * copies reject_count and accepted from the old item,
  918. * starts at new_starts and ends at the port where the original item
  919. * previously ended.
  920. */
  921. static policy_summary_item_t*
  922. policy_summary_item_split(policy_summary_item_t* old, uint16_t new_starts)
  923. {
  924. policy_summary_item_t* new;
  925. new = tor_malloc_zero(sizeof(policy_summary_item_t));
  926. new->prt_min = new_starts;
  927. new->prt_max = old->prt_max;
  928. new->reject_count = old->reject_count;
  929. new->accepted = old->accepted;
  930. old->prt_max = new_starts-1;
  931. tor_assert(old->prt_min <= old->prt_max);
  932. tor_assert(new->prt_min <= new->prt_max);
  933. return new;
  934. }
  935. /* XXXX Nick says I'm going to hell for this. If he feels charitably towards
  936. * my immortal soul, he can clean it up himself. */
  937. #define AT(x) ((policy_summary_item_t*)smartlist_get(summary, x))
  938. #define REJECT_CUTOFF_COUNT (1<<25)
  939. /** Split an exit policy summary so that prt_min and prt_max
  940. * fall at exactly the start and end of an item respectively.
  941. */
  942. static int
  943. policy_summary_split(smartlist_t *summary,
  944. uint16_t prt_min, uint16_t prt_max)
  945. {
  946. int start_at_index;
  947. int i = 0;
  948. /* XXXX Do a binary search if run time matters */
  949. while (AT(i)->prt_max < prt_min)
  950. i++;
  951. if (AT(i)->prt_min != prt_min) {
  952. policy_summary_item_t* new_item;
  953. new_item = policy_summary_item_split(AT(i), prt_min);
  954. smartlist_insert(summary, i+1, new_item);
  955. i++;
  956. }
  957. start_at_index = i;
  958. while (AT(i)->prt_max < prt_max)
  959. i++;
  960. if (AT(i)->prt_max != prt_max) {
  961. policy_summary_item_t* new_item;
  962. new_item = policy_summary_item_split(AT(i), prt_max+1);
  963. smartlist_insert(summary, i+1, new_item);
  964. }
  965. return start_at_index;
  966. }
  967. /** Mark port ranges as accepted if they are below the reject_count */
  968. static void
  969. policy_summary_accept(smartlist_t *summary,
  970. uint16_t prt_min, uint16_t prt_max)
  971. {
  972. int i = policy_summary_split(summary, prt_min, prt_max);
  973. while (i < smartlist_len(summary) &&
  974. AT(i)->prt_max <= prt_max) {
  975. if (!AT(i)->accepted &&
  976. AT(i)->reject_count <= REJECT_CUTOFF_COUNT)
  977. AT(i)->accepted = 1;
  978. i++;
  979. }
  980. tor_assert(i < smartlist_len(summary) || prt_max==65535);
  981. }
  982. /** Count the number of addresses in a network with prefixlen maskbits
  983. * against the given portrange. */
  984. static void
  985. policy_summary_reject(smartlist_t *summary,
  986. maskbits_t maskbits,
  987. uint16_t prt_min, uint16_t prt_max)
  988. {
  989. int i = policy_summary_split(summary, prt_min, prt_max);
  990. /* XXX: ipv4 specific */
  991. uint64_t count = (U64_LITERAL(1) << (32-maskbits));
  992. while (i < smartlist_len(summary) &&
  993. AT(i)->prt_max <= prt_max) {
  994. AT(i)->reject_count += count;
  995. i++;
  996. }
  997. tor_assert(i < smartlist_len(summary) || prt_max==65535);
  998. }
  999. /** Add a single exit policy item to our summary:
  1000. * If it is an accept ignore it unless it is for all IP addresses
  1001. * ("*"), i.e. it's prefixlen/maskbits is 0, else call
  1002. * policy_summary_accept().
  1003. * If it's a reject ignore it if it is about one of the private
  1004. * networks, else call policy_summary_reject().
  1005. */
  1006. static void
  1007. policy_summary_add_item(smartlist_t *summary, addr_policy_t *p)
  1008. {
  1009. if (p->policy_type == ADDR_POLICY_ACCEPT) {
  1010. if (p->maskbits == 0) {
  1011. policy_summary_accept(summary, p->prt_min, p->prt_max);
  1012. }
  1013. } else if (p->policy_type == ADDR_POLICY_REJECT) {
  1014. int is_private = 0;
  1015. int i;
  1016. for (i = 0; private_nets[i]; ++i) {
  1017. tor_addr_t addr;
  1018. maskbits_t maskbits;
  1019. if (tor_addr_parse_mask_ports(private_nets[i], &addr,
  1020. &maskbits, NULL, NULL)<0) {
  1021. tor_assert(0);
  1022. }
  1023. if (tor_addr_compare(&p->addr, &addr, CMP_EXACT) == 0 &&
  1024. p->maskbits == maskbits) {
  1025. is_private = 1;
  1026. break;
  1027. }
  1028. }
  1029. if (!is_private) {
  1030. policy_summary_reject(summary, p->maskbits, p->prt_min, p->prt_max);
  1031. }
  1032. } else
  1033. tor_assert(0);
  1034. }
  1035. /** Create a string representing a summary for an exit policy.
  1036. * The summary will either be an "accept" plus a comma-seperated list of port
  1037. * ranges or a "reject" plus portranges, depending on which is shorter.
  1038. *
  1039. * If no exits are allowed at all then NULL is returned, if no ports
  1040. * are blocked instead of "reject " we return "accept 1-65535" (this
  1041. * is an exception to the shorter-representation-wins rule).
  1042. */
  1043. char *
  1044. policy_summarize(smartlist_t *policy)
  1045. {
  1046. smartlist_t *summary = policy_summary_create();
  1047. smartlist_t *accepts, *rejects;
  1048. int i, last, start_prt;
  1049. size_t accepts_len, rejects_len, shorter_len, final_size;
  1050. char *accepts_str = NULL, *rejects_str = NULL, *shorter_str, *result;
  1051. const char *prefix;
  1052. tor_assert(policy);
  1053. /* Create the summary list */
  1054. SMARTLIST_FOREACH(policy, addr_policy_t *, p, {
  1055. policy_summary_add_item(summary, p);
  1056. });
  1057. /* Now create two lists of strings, one for accepted and one
  1058. * for rejected ports. We take care to merge ranges so that
  1059. * we avoid getting stuff like "1-4,5-9,10", instead we want
  1060. * "1-10"
  1061. */
  1062. i = 0;
  1063. start_prt = 1;
  1064. accepts = smartlist_create();
  1065. rejects = smartlist_create();
  1066. while (1) {
  1067. last = i == smartlist_len(summary)-1;
  1068. if (last ||
  1069. AT(i)->accepted != AT(i+1)->accepted) {
  1070. char buf[POLICY_BUF_LEN];
  1071. if (start_prt == AT(i)->prt_max)
  1072. tor_snprintf(buf, sizeof(buf), "%d", start_prt);
  1073. else
  1074. tor_snprintf(buf, sizeof(buf), "%d-%d", start_prt, AT(i)->prt_max);
  1075. if (AT(i)->accepted)
  1076. smartlist_add(accepts, tor_strdup(buf));
  1077. else
  1078. smartlist_add(rejects, tor_strdup(buf));
  1079. if (last)
  1080. break;
  1081. start_prt = AT(i+1)->prt_min;
  1082. };
  1083. i++;
  1084. };
  1085. /* Figure out which of the two stringlists will be shorter and use
  1086. * that to build the result
  1087. */
  1088. if (smartlist_len(accepts) == 0) { /* no exits at all */
  1089. result = tor_strdup("reject 1-65535");
  1090. goto cleanup;
  1091. }
  1092. if (smartlist_len(rejects) == 0) { /* no rejects at all */
  1093. result = tor_strdup("accept 1-65535");
  1094. goto cleanup;
  1095. }
  1096. accepts_str = smartlist_join_strings(accepts, ",", 0, &accepts_len);
  1097. rejects_str = smartlist_join_strings(rejects, ",", 0, &rejects_len);
  1098. if (rejects_len > MAX_EXITPOLICY_SUMMARY_LEN &&
  1099. accepts_len > MAX_EXITPOLICY_SUMMARY_LEN) {
  1100. char *c;
  1101. shorter_str = accepts_str;
  1102. prefix = "accept";
  1103. c = shorter_str + (MAX_EXITPOLICY_SUMMARY_LEN-strlen(prefix)-1);
  1104. while (*c != ',' && c >= shorter_str)
  1105. c--;
  1106. tor_assert(c >= shorter_str);
  1107. tor_assert(*c == ',');
  1108. *c = '\0';
  1109. shorter_len = strlen(shorter_str);
  1110. } else if (rejects_len < accepts_len) {
  1111. shorter_str = rejects_str;
  1112. shorter_len = rejects_len;
  1113. prefix = "reject";
  1114. } else {
  1115. shorter_str = accepts_str;
  1116. shorter_len = accepts_len;
  1117. prefix = "accept";
  1118. }
  1119. final_size = strlen(prefix)+1+shorter_len+1;
  1120. tor_assert(final_size <= MAX_EXITPOLICY_SUMMARY_LEN+1);
  1121. result = tor_malloc(final_size);
  1122. tor_snprintf(result, final_size, "%s %s", prefix, shorter_str);
  1123. cleanup:
  1124. /* cleanup */
  1125. SMARTLIST_FOREACH(summary, policy_summary_item_t *, s, tor_free(s));
  1126. smartlist_free(summary);
  1127. tor_free(accepts_str);
  1128. SMARTLIST_FOREACH(accepts, char *, s, tor_free(s));
  1129. smartlist_free(accepts);
  1130. tor_free(rejects_str);
  1131. SMARTLIST_FOREACH(rejects, char *, s, tor_free(s));
  1132. smartlist_free(rejects);
  1133. return result;
  1134. }
  1135. /** Implementation for GETINFO control command: knows the answer for questions
  1136. * about "exit-policy/..." */
  1137. int
  1138. getinfo_helper_policies(control_connection_t *conn,
  1139. const char *question, char **answer)
  1140. {
  1141. (void) conn;
  1142. if (!strcmp(question, "exit-policy/default")) {
  1143. *answer = tor_strdup(DEFAULT_EXIT_POLICY);
  1144. }
  1145. return 0;
  1146. }
  1147. /** Release all storage held by <b>p</b>. */
  1148. void
  1149. addr_policy_list_free(smartlist_t *lst)
  1150. {
  1151. if (!lst) return;
  1152. SMARTLIST_FOREACH(lst, addr_policy_t *, policy, addr_policy_free(policy));
  1153. smartlist_free(lst);
  1154. }
  1155. /** Release all storage held by <b>p</b>. */
  1156. void
  1157. addr_policy_free(addr_policy_t *p)
  1158. {
  1159. if (p) {
  1160. if (--p->refcnt <= 0) {
  1161. if (p->is_canonical) {
  1162. policy_map_ent_t search, *found;
  1163. search.policy = p;
  1164. found = HT_REMOVE(policy_map, &policy_root, &search);
  1165. if (found) {
  1166. tor_assert(p == found->policy);
  1167. tor_free(found);
  1168. }
  1169. }
  1170. tor_free(p);
  1171. }
  1172. }
  1173. }
  1174. /** Release all storage held by policy variables. */
  1175. void
  1176. policies_free_all(void)
  1177. {
  1178. addr_policy_list_free(reachable_or_addr_policy);
  1179. reachable_or_addr_policy = NULL;
  1180. addr_policy_list_free(reachable_dir_addr_policy);
  1181. reachable_dir_addr_policy = NULL;
  1182. addr_policy_list_free(socks_policy);
  1183. socks_policy = NULL;
  1184. addr_policy_list_free(dir_policy);
  1185. dir_policy = NULL;
  1186. addr_policy_list_free(authdir_reject_policy);
  1187. authdir_reject_policy = NULL;
  1188. addr_policy_list_free(authdir_invalid_policy);
  1189. authdir_invalid_policy = NULL;
  1190. addr_policy_list_free(authdir_baddir_policy);
  1191. authdir_baddir_policy = NULL;
  1192. addr_policy_list_free(authdir_badexit_policy);
  1193. authdir_badexit_policy = NULL;
  1194. if (!HT_EMPTY(&policy_root))
  1195. log_warn(LD_MM, "Still had some address policies cached at shutdown.");
  1196. HT_CLEAR(policy_map, &policy_root);
  1197. }