policies.c 49 KB

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