policies.c 36 KB

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