policies.c 50 KB

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