policies.c 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2009, 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 port range. */
  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. !options->BridgeRelay))
  313. REJECT("Error in ExitPolicy entry.");
  314. /* The rest of these calls *append* to addr_policy. So don't actually
  315. * use the results for anything other than checking if they parse! */
  316. if (parse_addr_policy(options->DirPolicy, &addr_policy, -1))
  317. REJECT("Error in DirPolicy entry.");
  318. if (parse_addr_policy(options->SocksPolicy, &addr_policy, -1))
  319. REJECT("Error in SocksPolicy entry.");
  320. if (parse_addr_policy(options->AuthDirReject, &addr_policy,
  321. ADDR_POLICY_REJECT))
  322. REJECT("Error in AuthDirReject entry.");
  323. if (parse_addr_policy(options->AuthDirInvalid, &addr_policy,
  324. ADDR_POLICY_REJECT))
  325. REJECT("Error in AuthDirInvalid entry.");
  326. if (parse_addr_policy(options->AuthDirBadDir, &addr_policy,
  327. ADDR_POLICY_REJECT))
  328. REJECT("Error in AuthDirBadDir entry.");
  329. if (parse_addr_policy(options->AuthDirBadExit, &addr_policy,
  330. ADDR_POLICY_REJECT))
  331. REJECT("Error in AuthDirBadExit entry.");
  332. if (parse_addr_policy(options->ReachableAddresses, &addr_policy,
  333. ADDR_POLICY_ACCEPT))
  334. REJECT("Error in ReachableAddresses entry.");
  335. if (parse_addr_policy(options->ReachableORAddresses, &addr_policy,
  336. ADDR_POLICY_ACCEPT))
  337. REJECT("Error in ReachableORAddresses entry.");
  338. if (parse_addr_policy(options->ReachableDirAddresses, &addr_policy,
  339. ADDR_POLICY_ACCEPT))
  340. REJECT("Error in ReachableDirAddresses entry.");
  341. if (parse_addr_policy(options->AuthDirReject, &addr_policy,
  342. ADDR_POLICY_REJECT))
  343. REJECT("Error in AuthDirReject entry.");
  344. if (parse_addr_policy(options->AuthDirInvalid, &addr_policy,
  345. ADDR_POLICY_REJECT))
  346. REJECT("Error in AuthDirInvalid entry.");
  347. err:
  348. addr_policy_list_free(addr_policy);
  349. return *msg ? -1 : 0;
  350. #undef REJECT
  351. }
  352. /** Parse <b>string</b> in the same way that the exit policy
  353. * is parsed, and put the processed version in *<b>policy</b>.
  354. * Ignore port specifiers.
  355. */
  356. static int
  357. load_policy_from_option(config_line_t *config, smartlist_t **policy,
  358. int assume_action)
  359. {
  360. int r;
  361. addr_policy_list_free(*policy);
  362. *policy = NULL;
  363. r = parse_addr_policy(config, policy, assume_action);
  364. if (r < 0) {
  365. return -1;
  366. }
  367. if (*policy) {
  368. SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, n) {
  369. /* ports aren't used in these. */
  370. if (n->prt_min > 1 || n->prt_max != 65535) {
  371. addr_policy_t newp, *c;
  372. memcpy(&newp, n, sizeof(newp));
  373. newp.prt_min = 1;
  374. newp.prt_max = 65535;
  375. newp.is_canonical = 0;
  376. c = addr_policy_get_canonical_entry(&newp);
  377. SMARTLIST_REPLACE_CURRENT(*policy, n, c);
  378. addr_policy_free(n);
  379. }
  380. } SMARTLIST_FOREACH_END(n);
  381. }
  382. return 0;
  383. }
  384. /** Set all policies based on <b>options</b>, which should have been validated
  385. * first by validate_addr_policies. */
  386. int
  387. policies_parse_from_options(or_options_t *options)
  388. {
  389. int ret = 0;
  390. if (load_policy_from_option(options->SocksPolicy, &socks_policy, -1) < 0)
  391. ret = -1;
  392. if (load_policy_from_option(options->DirPolicy, &dir_policy, -1) < 0)
  393. ret = -1;
  394. if (load_policy_from_option(options->AuthDirReject,
  395. &authdir_reject_policy, ADDR_POLICY_REJECT) < 0)
  396. ret = -1;
  397. if (load_policy_from_option(options->AuthDirInvalid,
  398. &authdir_invalid_policy, ADDR_POLICY_REJECT) < 0)
  399. ret = -1;
  400. if (load_policy_from_option(options->AuthDirBadDir,
  401. &authdir_baddir_policy, ADDR_POLICY_REJECT) < 0)
  402. ret = -1;
  403. if (load_policy_from_option(options->AuthDirBadExit,
  404. &authdir_badexit_policy, ADDR_POLICY_REJECT) < 0)
  405. ret = -1;
  406. if (parse_reachable_addresses() < 0)
  407. ret = -1;
  408. return ret;
  409. }
  410. /** Compare two provided address policy items, and return -1, 0, or 1
  411. * if the first is less than, equal to, or greater than the second. */
  412. static int
  413. cmp_single_addr_policy(addr_policy_t *a, addr_policy_t *b)
  414. {
  415. int r;
  416. if ((r=((int)a->policy_type - (int)b->policy_type)))
  417. return r;
  418. if ((r=((int)a->is_private - (int)b->is_private)))
  419. return r;
  420. if ((r=tor_addr_compare(&a->addr, &b->addr, CMP_EXACT)))
  421. return r;
  422. if ((r=((int)a->maskbits - (int)b->maskbits)))
  423. return r;
  424. if ((r=((int)a->prt_min - (int)b->prt_min)))
  425. return r;
  426. if ((r=((int)a->prt_max - (int)b->prt_max)))
  427. return r;
  428. return 0;
  429. }
  430. /** Like cmp_single_addr_policy() above, but looks at the
  431. * whole set of policies in each case. */
  432. int
  433. cmp_addr_policies(smartlist_t *a, smartlist_t *b)
  434. {
  435. int r, i;
  436. int len_a = a ? smartlist_len(a) : 0;
  437. int len_b = b ? smartlist_len(b) : 0;
  438. for (i = 0; i < len_a && i < len_b; ++i) {
  439. if ((r = cmp_single_addr_policy(smartlist_get(a, i), smartlist_get(b, i))))
  440. return r;
  441. }
  442. if (i == len_a && i == len_b)
  443. return 0;
  444. if (i < len_a)
  445. return -1;
  446. else
  447. return 1;
  448. }
  449. /** Node in hashtable used to store address policy entries. */
  450. typedef struct policy_map_ent_t {
  451. HT_ENTRY(policy_map_ent_t) node;
  452. addr_policy_t *policy;
  453. } policy_map_ent_t;
  454. static HT_HEAD(policy_map, policy_map_ent_t) policy_root = HT_INITIALIZER();
  455. /** Return true iff a and b are equal. */
  456. static INLINE int
  457. policy_eq(policy_map_ent_t *a, policy_map_ent_t *b)
  458. {
  459. return cmp_single_addr_policy(a->policy, b->policy) == 0;
  460. }
  461. /** Return a hashcode for <b>ent</b> */
  462. static unsigned int
  463. policy_hash(policy_map_ent_t *ent)
  464. {
  465. addr_policy_t *a = ent->policy;
  466. unsigned int r;
  467. if (a->is_private)
  468. r = 0x1234abcd;
  469. else
  470. r = tor_addr_hash(&a->addr);
  471. r += a->prt_min << 8;
  472. r += a->prt_max << 16;
  473. r += a->maskbits;
  474. if (a->policy_type == ADDR_POLICY_REJECT)
  475. r ^= 0xffffffff;
  476. return r;
  477. }
  478. HT_PROTOTYPE(policy_map, policy_map_ent_t, node, policy_hash,
  479. policy_eq)
  480. HT_GENERATE(policy_map, policy_map_ent_t, node, policy_hash,
  481. policy_eq, 0.6, malloc, realloc, free)
  482. /** Given a pointer to an addr_policy_t, return a copy of the pointer to the
  483. * "canonical" copy of that addr_policy_t; the canonical copy is a single
  484. * reference-counted object. */
  485. addr_policy_t *
  486. addr_policy_get_canonical_entry(addr_policy_t *e)
  487. {
  488. policy_map_ent_t search, *found;
  489. if (e->is_canonical)
  490. return e;
  491. search.policy = e;
  492. found = HT_FIND(policy_map, &policy_root, &search);
  493. if (!found) {
  494. found = tor_malloc_zero(sizeof(policy_map_ent_t));
  495. found->policy = tor_memdup(e, sizeof(addr_policy_t));
  496. found->policy->is_canonical = 1;
  497. found->policy->refcnt = 0;
  498. HT_INSERT(policy_map, &policy_root, found);
  499. }
  500. tor_assert(!cmp_single_addr_policy(found->policy, e));
  501. ++found->policy->refcnt;
  502. return found->policy;
  503. }
  504. /** As compare_tor_addr_to_addr_policy, but instead of a tor_addr_t, takes
  505. * in host order. */
  506. addr_policy_result_t
  507. compare_addr_to_addr_policy(uint32_t addr, uint16_t port,
  508. const smartlist_t *policy)
  509. {
  510. /*XXXX deprecate this function when possible. */
  511. tor_addr_t a;
  512. tor_addr_from_ipv4h(&a, addr);
  513. return compare_tor_addr_to_addr_policy(&a, port, policy);
  514. }
  515. /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
  516. * addr and port are both known. */
  517. static addr_policy_result_t
  518. compare_known_tor_addr_to_addr_policy(const tor_addr_t *addr, uint16_t port,
  519. const smartlist_t *policy)
  520. {
  521. /* We know the address and port, and we know the policy, so we can just
  522. * compute an exact match. */
  523. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
  524. /* Address is known */
  525. if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
  526. CMP_EXACT)) {
  527. if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
  528. /* Exact match for the policy */
  529. return tmpe->policy_type == ADDR_POLICY_ACCEPT ?
  530. ADDR_POLICY_ACCEPTED : ADDR_POLICY_REJECTED;
  531. }
  532. }
  533. } SMARTLIST_FOREACH_END(tmpe);
  534. /* accept all by default. */
  535. return ADDR_POLICY_ACCEPTED;
  536. }
  537. /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
  538. * addr is known but port is not. */
  539. static addr_policy_result_t
  540. compare_known_tor_addr_to_addr_policy_noport(const tor_addr_t *addr,
  541. const smartlist_t *policy)
  542. {
  543. /* We look to see if there's a definite match. If so, we return that
  544. match's value, unless there's an intervening possible match that says
  545. something different. */
  546. int maybe_accept = 0, maybe_reject = 0;
  547. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
  548. if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
  549. CMP_EXACT)) {
  550. if (tmpe->prt_min <= 1 && tmpe->prt_max >= 65535) {
  551. /* Definitely matches, since it covers all ports. */
  552. if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
  553. /* If we already hit a clause that might trigger a 'reject', than we
  554. * can't be sure of this certain 'accept'.*/
  555. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
  556. ADDR_POLICY_ACCEPTED;
  557. } else {
  558. return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
  559. ADDR_POLICY_REJECTED;
  560. }
  561. } else {
  562. /* Might match. */
  563. if (tmpe->policy_type == ADDR_POLICY_REJECT)
  564. maybe_reject = 1;
  565. else
  566. maybe_accept = 1;
  567. }
  568. }
  569. } SMARTLIST_FOREACH_END(tmpe);
  570. /* accept all by default. */
  571. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  572. }
  573. /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
  574. * port is known but address is not. */
  575. static addr_policy_result_t
  576. compare_unknown_tor_addr_to_addr_policy(uint16_t port,
  577. const smartlist_t *policy)
  578. {
  579. /* We look to see if there's a definite match. If so, we return that
  580. match's value, unless there's an intervening possible match that says
  581. something different. */
  582. int maybe_accept = 0, maybe_reject = 0;
  583. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
  584. if (tmpe->prt_min <= port && port <= tmpe->prt_max) {
  585. if (tmpe->maskbits == 0) {
  586. /* Definitely matches, since it covers all addresses. */
  587. if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
  588. /* If we already hit a clause that might trigger a 'reject', than we
  589. * can't be sure of this certain 'accept'.*/
  590. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
  591. ADDR_POLICY_ACCEPTED;
  592. } else {
  593. return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
  594. ADDR_POLICY_REJECTED;
  595. }
  596. } else {
  597. /* Might match. */
  598. if (tmpe->policy_type == ADDR_POLICY_REJECT)
  599. maybe_reject = 1;
  600. else
  601. maybe_accept = 1;
  602. }
  603. }
  604. } SMARTLIST_FOREACH_END(tmpe);
  605. /* accept all by default. */
  606. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  607. }
  608. /** Decide whether a given addr:port is definitely accepted,
  609. * definitely rejected, probably accepted, or probably rejected by a
  610. * given policy. If <b>addr</b> is 0, we don't know the IP of the
  611. * target address. If <b>port</b> is 0, we don't know the port of the
  612. * target address. (At least one of <b>addr</b> and <b>port</b> must be
  613. * provided. If you want to know whether a policy would definitely reject
  614. * an unknown address:port, use policy_is_reject_star().)
  615. *
  616. * We could do better by assuming that some ranges never match typical
  617. * addresses (127.0.0.1, and so on). But we'll try this for now.
  618. */
  619. addr_policy_result_t
  620. compare_tor_addr_to_addr_policy(const tor_addr_t *addr, uint16_t port,
  621. const smartlist_t *policy)
  622. {
  623. if (!policy) {
  624. /* no policy? accept all. */
  625. return ADDR_POLICY_ACCEPTED;
  626. } else if (tor_addr_is_null(addr)) {
  627. tor_assert(port != 0);
  628. return compare_unknown_tor_addr_to_addr_policy(port, policy);
  629. } else if (port == 0) {
  630. return compare_known_tor_addr_to_addr_policy_noport(addr, policy);
  631. } else {
  632. return compare_known_tor_addr_to_addr_policy(addr, port, policy);
  633. }
  634. }
  635. /** Return true iff the address policy <b>a</b> covers every case that
  636. * would be covered by <b>b</b>, so that a,b is redundant. */
  637. static int
  638. addr_policy_covers(addr_policy_t *a, addr_policy_t *b)
  639. {
  640. /* We can ignore accept/reject, since "accept *:80, reject *:80" reduces
  641. * to "accept *:80". */
  642. if (a->maskbits > b->maskbits) {
  643. /* a has more fixed bits than b; it can't possibly cover b. */
  644. return 0;
  645. }
  646. if (tor_addr_compare_masked(&a->addr, &b->addr, a->maskbits, CMP_EXACT)) {
  647. /* There's a fixed bit in a that's set differently in b. */
  648. return 0;
  649. }
  650. return (a->prt_min <= b->prt_min && a->prt_max >= b->prt_max);
  651. }
  652. /** Return true iff the address policies <b>a</b> and <b>b</b> intersect,
  653. * that is, there exists an address/port that is covered by <b>a</b> that
  654. * is also covered by <b>b</b>.
  655. */
  656. static int
  657. addr_policy_intersects(addr_policy_t *a, addr_policy_t *b)
  658. {
  659. maskbits_t minbits;
  660. /* All the bits we care about are those that are set in both
  661. * netmasks. If they are equal in a and b's networkaddresses
  662. * then the networks intersect. If there is a difference,
  663. * then they do not. */
  664. if (a->maskbits < b->maskbits)
  665. minbits = a->maskbits;
  666. else
  667. minbits = b->maskbits;
  668. if (tor_addr_compare_masked(&a->addr, &b->addr, minbits, CMP_EXACT))
  669. return 0;
  670. if (a->prt_max < b->prt_min || b->prt_max < a->prt_min)
  671. return 0;
  672. return 1;
  673. }
  674. /** Add the exit policy described by <b>more</b> to <b>policy</b>.
  675. */
  676. static void
  677. append_exit_policy_string(smartlist_t **policy, const char *more)
  678. {
  679. config_line_t tmp;
  680. tmp.key = NULL;
  681. tmp.value = (char*) more;
  682. tmp.next = NULL;
  683. if (parse_addr_policy(&tmp, policy, -1)<0) {
  684. log_warn(LD_BUG, "Unable to parse internally generated policy %s",more);
  685. }
  686. }
  687. /** Detect and excise "dead code" from the policy *<b>dest</b>. */
  688. static void
  689. exit_policy_remove_redundancies(smartlist_t *dest)
  690. {
  691. addr_policy_t *ap, *tmp, *victim;
  692. int i, j;
  693. /* Step one: find a *:* entry and cut off everything after it. */
  694. for (i = 0; i < smartlist_len(dest); ++i) {
  695. ap = smartlist_get(dest, i);
  696. if (ap->maskbits == 0 && ap->prt_min <= 1 && ap->prt_max >= 65535) {
  697. /* This is a catch-all line -- later lines are unreachable. */
  698. while (i+1 < smartlist_len(dest)) {
  699. victim = smartlist_get(dest, i+1);
  700. smartlist_del(dest, i+1);
  701. addr_policy_free(victim);
  702. }
  703. break;
  704. }
  705. }
  706. /* Step two: for every entry, see if there's a redundant entry
  707. * later on, and remove it. */
  708. for (i = 0; i < smartlist_len(dest)-1; ++i) {
  709. ap = smartlist_get(dest, i);
  710. for (j = i+1; j < smartlist_len(dest); ++j) {
  711. tmp = smartlist_get(dest, j);
  712. tor_assert(j > i);
  713. if (addr_policy_covers(ap, tmp)) {
  714. char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
  715. policy_write_item(p1, sizeof(p1), tmp, 0);
  716. policy_write_item(p2, sizeof(p2), ap, 0);
  717. log(LOG_DEBUG, LD_CONFIG, "Removing exit policy %s (%d). It is made "
  718. "redundant by %s (%d).", p1, j, p2, i);
  719. smartlist_del_keeporder(dest, j--);
  720. addr_policy_free(tmp);
  721. }
  722. }
  723. }
  724. /* Step three: for every entry A, see if there's an entry B making this one
  725. * redundant later on. This is the case if A and B are of the same type
  726. * (accept/reject), A is a subset of B, and there is no other entry of
  727. * different type in between those two that intersects with A.
  728. *
  729. * Anybody want to double-check the logic here? XXX
  730. */
  731. for (i = 0; i < smartlist_len(dest)-1; ++i) {
  732. ap = smartlist_get(dest, i);
  733. for (j = i+1; j < smartlist_len(dest); ++j) {
  734. // tor_assert(j > i); // j starts out at i+1; j only increases; i only
  735. // // decreases.
  736. tmp = smartlist_get(dest, j);
  737. if (ap->policy_type != tmp->policy_type) {
  738. if (addr_policy_intersects(ap, tmp))
  739. break;
  740. } else { /* policy_types are equal. */
  741. if (addr_policy_covers(tmp, ap)) {
  742. char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
  743. policy_write_item(p1, sizeof(p1), ap, 0);
  744. policy_write_item(p2, sizeof(p2), tmp, 0);
  745. log(LOG_DEBUG, LD_CONFIG, "Removing exit policy %s. It is already "
  746. "covered by %s.", p1, p2);
  747. smartlist_del_keeporder(dest, i--);
  748. addr_policy_free(ap);
  749. break;
  750. }
  751. }
  752. }
  753. }
  754. }
  755. #define DEFAULT_EXIT_POLICY \
  756. "reject *:25,reject *:119,reject *:135-139,reject *:445," \
  757. "reject *:563,reject *:1214,reject *:4661-4666," \
  758. "reject *:6346-6429,reject *:6699,reject *:6881-6999,accept *:*"
  759. /** Parse the exit policy <b>cfg</b> into the linked list *<b>dest</b>. If
  760. * cfg doesn't end in an absolute accept or reject and if
  761. * <b>add_default_policy</b> is true, add the default exit
  762. * policy afterwards. If <b>rejectprivate</b> is true, prepend
  763. * "reject private:*" to the policy. Return -1 if we can't parse cfg,
  764. * else return 0.
  765. */
  766. int
  767. policies_parse_exit_policy(config_line_t *cfg, smartlist_t **dest,
  768. int rejectprivate, const char *local_address,
  769. int add_default_policy)
  770. {
  771. if (rejectprivate) {
  772. append_exit_policy_string(dest, "reject private:*");
  773. if (local_address) {
  774. char buf[POLICY_BUF_LEN];
  775. tor_snprintf(buf, sizeof(buf), "reject %s:*", local_address);
  776. append_exit_policy_string(dest, buf);
  777. }
  778. }
  779. if (parse_addr_policy(cfg, dest, -1))
  780. return -1;
  781. if (add_default_policy)
  782. append_exit_policy_string(dest, DEFAULT_EXIT_POLICY);
  783. else
  784. append_exit_policy_string(dest, "reject *:*");
  785. exit_policy_remove_redundancies(*dest);
  786. return 0;
  787. }
  788. /** Replace the exit policy of <b>r</b> with reject *:*. */
  789. void
  790. policies_set_router_exitpolicy_to_reject_all(routerinfo_t *r)
  791. {
  792. addr_policy_t *item;
  793. addr_policy_list_free(r->exit_policy);
  794. r->exit_policy = smartlist_create();
  795. item = router_parse_addr_policy_item_from_string("reject *:*", -1);
  796. smartlist_add(r->exit_policy, item);
  797. }
  798. /** Return true iff <b>ri</b> is "useful as an exit node", meaning
  799. * it allows exit to at least one /8 address space for at least
  800. * two of ports 80, 443, and 6667. */
  801. int
  802. exit_policy_is_general_exit(smartlist_t *policy)
  803. {
  804. static const int ports[] = { 80, 443, 6667 };
  805. int n_allowed = 0;
  806. int i;
  807. if (!policy) /*XXXX disallow NULL policies? */
  808. return 0;
  809. for (i = 0; i < 3; ++i) {
  810. SMARTLIST_FOREACH(policy, addr_policy_t *, p, {
  811. if (p->prt_min > ports[i] || p->prt_max < ports[i])
  812. continue; /* Doesn't cover our port. */
  813. if (p->maskbits > 8)
  814. continue; /* Narrower than a /8. */
  815. if (tor_addr_is_loopback(&p->addr))
  816. continue; /* 127.x or ::1. */
  817. /* We have a match that is at least a /8. */
  818. if (p->policy_type == ADDR_POLICY_ACCEPT) {
  819. ++n_allowed;
  820. break; /* stop considering this port */
  821. }
  822. });
  823. }
  824. return n_allowed >= 2;
  825. }
  826. /** Return false if <b>policy</b> might permit access to some addr:port;
  827. * otherwise if we are certain it rejects everything, return true. */
  828. int
  829. policy_is_reject_star(const smartlist_t *policy)
  830. {
  831. if (!policy) /*XXXX disallow NULL policies? */
  832. return 1;
  833. SMARTLIST_FOREACH(policy, addr_policy_t *, p, {
  834. if (p->policy_type == ADDR_POLICY_ACCEPT)
  835. return 0;
  836. else if (p->policy_type == ADDR_POLICY_REJECT &&
  837. p->prt_min <= 1 && p->prt_max == 65535 &&
  838. p->maskbits == 0)
  839. return 1;
  840. });
  841. return 1;
  842. }
  843. /** Write a single address policy to the buf_len byte buffer at buf. Return
  844. * the number of characters written, or -1 on failure. */
  845. int
  846. policy_write_item(char *buf, size_t buflen, addr_policy_t *policy,
  847. int format_for_desc)
  848. {
  849. size_t written = 0;
  850. char addrbuf[TOR_ADDR_BUF_LEN];
  851. const char *addrpart;
  852. int result;
  853. const int is_accept = policy->policy_type == ADDR_POLICY_ACCEPT;
  854. const int is_ip6 = tor_addr_family(&policy->addr) == AF_INET6;
  855. tor_addr_to_str(addrbuf, &policy->addr, sizeof(addrbuf), 1);
  856. /* write accept/reject 1.2.3.4 */
  857. if (policy->is_private)
  858. addrpart = "private";
  859. else if (policy->maskbits == 0)
  860. addrpart = "*";
  861. else
  862. addrpart = addrbuf;
  863. result = tor_snprintf(buf, buflen, "%s%s%s %s",
  864. (is_ip6&&format_for_desc)?"opt ":"",
  865. is_accept ? "accept" : "reject",
  866. (is_ip6&&format_for_desc)?"6":"",
  867. addrpart);
  868. if (result < 0)
  869. return -1;
  870. written += strlen(buf);
  871. /* If the maskbits is 32 we don't need to give it. If the mask is 0,
  872. * we already wrote "*". */
  873. if (policy->maskbits < 32 && policy->maskbits > 0) {
  874. if (tor_snprintf(buf+written, buflen-written, "/%d", policy->maskbits)<0)
  875. return -1;
  876. written += strlen(buf+written);
  877. }
  878. if (policy->prt_min <= 1 && policy->prt_max == 65535) {
  879. /* There is no port set; write ":*" */
  880. if (written+4 > buflen)
  881. return -1;
  882. strlcat(buf+written, ":*", buflen-written);
  883. written += 2;
  884. } else if (policy->prt_min == policy->prt_max) {
  885. /* There is only one port; write ":80". */
  886. result = tor_snprintf(buf+written, buflen-written, ":%d", policy->prt_min);
  887. if (result<0)
  888. return -1;
  889. written += result;
  890. } else {
  891. /* There is a range of ports; write ":79-80". */
  892. result = tor_snprintf(buf+written, buflen-written, ":%d-%d",
  893. policy->prt_min, policy->prt_max);
  894. if (result<0)
  895. return -1;
  896. written += result;
  897. }
  898. if (written < buflen)
  899. buf[written] = '\0';
  900. else
  901. return -1;
  902. return (int)written;
  903. }
  904. /** Create a new exit policy summary, initially only with a single
  905. * port 1-64k item */
  906. /* XXXX This entire thing will do most stuff in O(N^2), or worse. Use an
  907. * RB-tree if that turns out to matter. */
  908. static smartlist_t *
  909. policy_summary_create(void)
  910. {
  911. smartlist_t *summary;
  912. policy_summary_item_t* item;
  913. item = tor_malloc_zero(sizeof(policy_summary_item_t));
  914. item->prt_min = 1;
  915. item->prt_max = 65535;
  916. item->reject_count = 0;
  917. item->accepted = 0;
  918. summary = smartlist_create();
  919. smartlist_add(summary, item);
  920. return summary;
  921. }
  922. /** Split the summary item in <b>item</b> at the port <b>new_starts</b>.
  923. * The current item is changed to end at new-starts - 1, the new item
  924. * copies reject_count and accepted from the old item,
  925. * starts at new_starts and ends at the port where the original item
  926. * previously ended.
  927. */
  928. static policy_summary_item_t*
  929. policy_summary_item_split(policy_summary_item_t* old, uint16_t new_starts)
  930. {
  931. policy_summary_item_t* new;
  932. new = tor_malloc_zero(sizeof(policy_summary_item_t));
  933. new->prt_min = new_starts;
  934. new->prt_max = old->prt_max;
  935. new->reject_count = old->reject_count;
  936. new->accepted = old->accepted;
  937. old->prt_max = new_starts-1;
  938. tor_assert(old->prt_min <= old->prt_max);
  939. tor_assert(new->prt_min <= new->prt_max);
  940. return new;
  941. }
  942. /* XXXX Nick says I'm going to hell for this. If he feels charitably towards
  943. * my immortal soul, he can clean it up himself. */
  944. #define AT(x) ((policy_summary_item_t*)smartlist_get(summary, x))
  945. #define REJECT_CUTOFF_COUNT (1<<25)
  946. /** Split an exit policy summary so that prt_min and prt_max
  947. * fall at exactly the start and end of an item respectively.
  948. */
  949. static int
  950. policy_summary_split(smartlist_t *summary,
  951. uint16_t prt_min, uint16_t prt_max)
  952. {
  953. int start_at_index;
  954. int i = 0;
  955. /* XXXX Do a binary search if run time matters */
  956. while (AT(i)->prt_max < prt_min)
  957. i++;
  958. if (AT(i)->prt_min != prt_min) {
  959. policy_summary_item_t* new_item;
  960. new_item = policy_summary_item_split(AT(i), prt_min);
  961. smartlist_insert(summary, i+1, new_item);
  962. i++;
  963. }
  964. start_at_index = i;
  965. while (AT(i)->prt_max < prt_max)
  966. i++;
  967. if (AT(i)->prt_max != prt_max) {
  968. policy_summary_item_t* new_item;
  969. new_item = policy_summary_item_split(AT(i), prt_max+1);
  970. smartlist_insert(summary, i+1, new_item);
  971. }
  972. return start_at_index;
  973. }
  974. /** Mark port ranges as accepted if they are below the reject_count */
  975. static void
  976. policy_summary_accept(smartlist_t *summary,
  977. uint16_t prt_min, uint16_t prt_max)
  978. {
  979. int i = policy_summary_split(summary, prt_min, prt_max);
  980. while (i < smartlist_len(summary) &&
  981. AT(i)->prt_max <= prt_max) {
  982. if (!AT(i)->accepted &&
  983. AT(i)->reject_count <= REJECT_CUTOFF_COUNT)
  984. AT(i)->accepted = 1;
  985. i++;
  986. }
  987. tor_assert(i < smartlist_len(summary) || prt_max==65535);
  988. }
  989. /** Count the number of addresses in a network with prefixlen maskbits
  990. * against the given portrange. */
  991. static void
  992. policy_summary_reject(smartlist_t *summary,
  993. maskbits_t maskbits,
  994. uint16_t prt_min, uint16_t prt_max)
  995. {
  996. int i = policy_summary_split(summary, prt_min, prt_max);
  997. /* XXX: ipv4 specific */
  998. uint64_t count = (U64_LITERAL(1) << (32-maskbits));
  999. while (i < smartlist_len(summary) &&
  1000. AT(i)->prt_max <= prt_max) {
  1001. AT(i)->reject_count += count;
  1002. i++;
  1003. }
  1004. tor_assert(i < smartlist_len(summary) || prt_max==65535);
  1005. }
  1006. /** Add a single exit policy item to our summary:
  1007. * If it is an accept ignore it unless it is for all IP addresses
  1008. * ("*"), i.e. it's prefixlen/maskbits is 0, else call
  1009. * policy_summary_accept().
  1010. * If it's a reject ignore it if it is about one of the private
  1011. * networks, else call policy_summary_reject().
  1012. */
  1013. static void
  1014. policy_summary_add_item(smartlist_t *summary, addr_policy_t *p)
  1015. {
  1016. if (p->policy_type == ADDR_POLICY_ACCEPT) {
  1017. if (p->maskbits == 0) {
  1018. policy_summary_accept(summary, p->prt_min, p->prt_max);
  1019. }
  1020. } else if (p->policy_type == ADDR_POLICY_REJECT) {
  1021. int is_private = 0;
  1022. int i;
  1023. for (i = 0; private_nets[i]; ++i) {
  1024. tor_addr_t addr;
  1025. maskbits_t maskbits;
  1026. if (tor_addr_parse_mask_ports(private_nets[i], &addr,
  1027. &maskbits, NULL, NULL)<0) {
  1028. tor_assert(0);
  1029. }
  1030. if (tor_addr_compare(&p->addr, &addr, CMP_EXACT) == 0 &&
  1031. p->maskbits == maskbits) {
  1032. is_private = 1;
  1033. break;
  1034. }
  1035. }
  1036. if (!is_private) {
  1037. policy_summary_reject(summary, p->maskbits, p->prt_min, p->prt_max);
  1038. }
  1039. } else
  1040. tor_assert(0);
  1041. }
  1042. /** Create a string representing a summary for an exit policy.
  1043. * The summary will either be an "accept" plus a comma-separated list of port
  1044. * ranges or a "reject" plus port-ranges, depending on which is shorter.
  1045. *
  1046. * If no exits are allowed at all then NULL is returned, if no ports
  1047. * are blocked instead of "reject " we return "accept 1-65535" (this
  1048. * is an exception to the shorter-representation-wins rule).
  1049. */
  1050. char *
  1051. policy_summarize(smartlist_t *policy)
  1052. {
  1053. smartlist_t *summary = policy_summary_create();
  1054. smartlist_t *accepts, *rejects;
  1055. int i, last, start_prt;
  1056. size_t accepts_len, rejects_len, shorter_len, final_size;
  1057. char *accepts_str = NULL, *rejects_str = NULL, *shorter_str, *result;
  1058. const char *prefix;
  1059. tor_assert(policy);
  1060. /* Create the summary list */
  1061. SMARTLIST_FOREACH(policy, addr_policy_t *, p, {
  1062. policy_summary_add_item(summary, p);
  1063. });
  1064. /* Now create two lists of strings, one for accepted and one
  1065. * for rejected ports. We take care to merge ranges so that
  1066. * we avoid getting stuff like "1-4,5-9,10", instead we want
  1067. * "1-10"
  1068. */
  1069. i = 0;
  1070. start_prt = 1;
  1071. accepts = smartlist_create();
  1072. rejects = smartlist_create();
  1073. while (1) {
  1074. last = i == smartlist_len(summary)-1;
  1075. if (last ||
  1076. AT(i)->accepted != AT(i+1)->accepted) {
  1077. char buf[POLICY_BUF_LEN];
  1078. if (start_prt == AT(i)->prt_max)
  1079. tor_snprintf(buf, sizeof(buf), "%d", start_prt);
  1080. else
  1081. tor_snprintf(buf, sizeof(buf), "%d-%d", start_prt, AT(i)->prt_max);
  1082. if (AT(i)->accepted)
  1083. smartlist_add(accepts, tor_strdup(buf));
  1084. else
  1085. smartlist_add(rejects, tor_strdup(buf));
  1086. if (last)
  1087. break;
  1088. start_prt = AT(i+1)->prt_min;
  1089. };
  1090. i++;
  1091. };
  1092. /* Figure out which of the two stringlists will be shorter and use
  1093. * that to build the result
  1094. */
  1095. if (smartlist_len(accepts) == 0) { /* no exits at all */
  1096. result = tor_strdup("reject 1-65535");
  1097. goto cleanup;
  1098. }
  1099. if (smartlist_len(rejects) == 0) { /* no rejects at all */
  1100. result = tor_strdup("accept 1-65535");
  1101. goto cleanup;
  1102. }
  1103. accepts_str = smartlist_join_strings(accepts, ",", 0, &accepts_len);
  1104. rejects_str = smartlist_join_strings(rejects, ",", 0, &rejects_len);
  1105. if (rejects_len > MAX_EXITPOLICY_SUMMARY_LEN &&
  1106. accepts_len > MAX_EXITPOLICY_SUMMARY_LEN) {
  1107. char *c;
  1108. shorter_str = accepts_str;
  1109. prefix = "accept";
  1110. c = shorter_str + (MAX_EXITPOLICY_SUMMARY_LEN-strlen(prefix)-1);
  1111. while (*c != ',' && c >= shorter_str)
  1112. c--;
  1113. tor_assert(c >= shorter_str);
  1114. tor_assert(*c == ',');
  1115. *c = '\0';
  1116. shorter_len = strlen(shorter_str);
  1117. } else if (rejects_len < accepts_len) {
  1118. shorter_str = rejects_str;
  1119. shorter_len = rejects_len;
  1120. prefix = "reject";
  1121. } else {
  1122. shorter_str = accepts_str;
  1123. shorter_len = accepts_len;
  1124. prefix = "accept";
  1125. }
  1126. final_size = strlen(prefix)+1+shorter_len+1;
  1127. tor_assert(final_size <= MAX_EXITPOLICY_SUMMARY_LEN+1);
  1128. result = tor_malloc(final_size);
  1129. tor_snprintf(result, final_size, "%s %s", prefix, shorter_str);
  1130. cleanup:
  1131. /* cleanup */
  1132. SMARTLIST_FOREACH(summary, policy_summary_item_t *, s, tor_free(s));
  1133. smartlist_free(summary);
  1134. tor_free(accepts_str);
  1135. SMARTLIST_FOREACH(accepts, char *, s, tor_free(s));
  1136. smartlist_free(accepts);
  1137. tor_free(rejects_str);
  1138. SMARTLIST_FOREACH(rejects, char *, s, tor_free(s));
  1139. smartlist_free(rejects);
  1140. return result;
  1141. }
  1142. /** Implementation for GETINFO control command: knows the answer for questions
  1143. * about "exit-policy/..." */
  1144. int
  1145. getinfo_helper_policies(control_connection_t *conn,
  1146. const char *question, char **answer)
  1147. {
  1148. (void) conn;
  1149. if (!strcmp(question, "exit-policy/default")) {
  1150. *answer = tor_strdup(DEFAULT_EXIT_POLICY);
  1151. }
  1152. return 0;
  1153. }
  1154. /** Release all storage held by <b>p</b>. */
  1155. void
  1156. addr_policy_list_free(smartlist_t *lst)
  1157. {
  1158. if (!lst)
  1159. return;
  1160. SMARTLIST_FOREACH(lst, addr_policy_t *, policy, addr_policy_free(policy));
  1161. smartlist_free(lst);
  1162. }
  1163. /** Release all storage held by <b>p</b>. */
  1164. void
  1165. addr_policy_free(addr_policy_t *p)
  1166. {
  1167. if (!p)
  1168. return;
  1169. if (--p->refcnt <= 0) {
  1170. if (p->is_canonical) {
  1171. policy_map_ent_t search, *found;
  1172. search.policy = p;
  1173. found = HT_REMOVE(policy_map, &policy_root, &search);
  1174. if (found) {
  1175. tor_assert(p == found->policy);
  1176. tor_free(found);
  1177. }
  1178. }
  1179. tor_free(p);
  1180. }
  1181. }
  1182. /** Release all storage held by policy variables. */
  1183. void
  1184. policies_free_all(void)
  1185. {
  1186. addr_policy_list_free(reachable_or_addr_policy);
  1187. reachable_or_addr_policy = NULL;
  1188. addr_policy_list_free(reachable_dir_addr_policy);
  1189. reachable_dir_addr_policy = NULL;
  1190. addr_policy_list_free(socks_policy);
  1191. socks_policy = NULL;
  1192. addr_policy_list_free(dir_policy);
  1193. dir_policy = NULL;
  1194. addr_policy_list_free(authdir_reject_policy);
  1195. authdir_reject_policy = NULL;
  1196. addr_policy_list_free(authdir_invalid_policy);
  1197. authdir_invalid_policy = NULL;
  1198. addr_policy_list_free(authdir_baddir_policy);
  1199. authdir_baddir_policy = NULL;
  1200. addr_policy_list_free(authdir_badexit_policy);
  1201. authdir_badexit_policy = NULL;
  1202. if (!HT_EMPTY(&policy_root)) {
  1203. policy_map_ent_t **ent;
  1204. int n = 0;
  1205. char buf[POLICY_BUF_LEN];
  1206. log_warn(LD_MM, "Still had %d address policies cached at shutdown.",
  1207. (int)HT_SIZE(&policy_root));
  1208. /* Note the first 10 cached policies to try to figure out where they
  1209. * might be coming from. */
  1210. HT_FOREACH(ent, policy_map, &policy_root) {
  1211. if (++n > 10)
  1212. break;
  1213. if (policy_write_item(buf, sizeof(buf), (*ent)->policy, 0) >= 0)
  1214. log_warn(LD_MM," %d [%d]: %s", n, (*ent)->policy->refcnt, buf);
  1215. }
  1216. }
  1217. HT_CLEAR(policy_map, &policy_root);
  1218. }