policies.c 51 KB

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