policies.c 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2015, 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. #define POLICIES_PRIVATE
  10. #include "or.h"
  11. #include "config.h"
  12. #include "dirserv.h"
  13. #include "networkstatus.h"
  14. #include "nodelist.h"
  15. #include "policies.h"
  16. #include "router.h"
  17. #include "routerparse.h"
  18. #include "geoip.h"
  19. #include "ht.h"
  20. /** Policy that addresses for incoming SOCKS connections must match. */
  21. static smartlist_t *socks_policy = NULL;
  22. /** Policy that addresses for incoming directory connections must match. */
  23. static smartlist_t *dir_policy = NULL;
  24. /** Policy that addresses for incoming router descriptors must match in order
  25. * to be published by us. */
  26. static smartlist_t *authdir_reject_policy = NULL;
  27. /** Policy that addresses for incoming router descriptors must match in order
  28. * to be marked as valid in our networkstatus. */
  29. static smartlist_t *authdir_invalid_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. "[::]/8",
  57. "[fc00::]/7", "[fe80::]/10", "[fec0::]/10", "[ff00::]/8", "[::]/127",
  58. NULL
  59. };
  60. static int policies_parse_exit_policy_internal(
  61. config_line_t *cfg,
  62. smartlist_t **dest,
  63. int ipv6_exit,
  64. int rejectprivate,
  65. const smartlist_t *configured_addresses,
  66. int reject_interface_addresses,
  67. int reject_configured_port_addresses,
  68. int add_default_policy);
  69. /** Replace all "private" entries in *<b>policy</b> with their expanded
  70. * equivalents. */
  71. void
  72. policy_expand_private(smartlist_t **policy)
  73. {
  74. uint16_t port_min, port_max;
  75. int i;
  76. smartlist_t *tmp;
  77. if (!*policy) /*XXXX disallow NULL policies? */
  78. return;
  79. tmp = smartlist_new();
  80. SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, p) {
  81. if (! p->is_private) {
  82. smartlist_add(tmp, p);
  83. continue;
  84. }
  85. for (i = 0; private_nets[i]; ++i) {
  86. addr_policy_t newpolicy;
  87. memcpy(&newpolicy, p, sizeof(addr_policy_t));
  88. newpolicy.is_private = 0;
  89. newpolicy.is_canonical = 0;
  90. if (tor_addr_parse_mask_ports(private_nets[i], 0,
  91. &newpolicy.addr,
  92. &newpolicy.maskbits, &port_min, &port_max)<0) {
  93. tor_assert(0);
  94. }
  95. smartlist_add(tmp, addr_policy_get_canonical_entry(&newpolicy));
  96. }
  97. addr_policy_free(p);
  98. } SMARTLIST_FOREACH_END(p);
  99. smartlist_free(*policy);
  100. *policy = tmp;
  101. }
  102. /** Expand each of the AF_UNSPEC elements in *<b>policy</b> (which indicate
  103. * protocol-neutral wildcards) into a pair of wildcard elements: one IPv4-
  104. * specific and one IPv6-specific. */
  105. void
  106. policy_expand_unspec(smartlist_t **policy)
  107. {
  108. smartlist_t *tmp;
  109. if (!*policy)
  110. return;
  111. tmp = smartlist_new();
  112. SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, p) {
  113. sa_family_t family = tor_addr_family(&p->addr);
  114. if (family == AF_INET6 || family == AF_INET || p->is_private) {
  115. smartlist_add(tmp, p);
  116. } else if (family == AF_UNSPEC) {
  117. addr_policy_t newpolicy_ipv4;
  118. addr_policy_t newpolicy_ipv6;
  119. memcpy(&newpolicy_ipv4, p, sizeof(addr_policy_t));
  120. memcpy(&newpolicy_ipv6, p, sizeof(addr_policy_t));
  121. newpolicy_ipv4.is_canonical = 0;
  122. newpolicy_ipv6.is_canonical = 0;
  123. if (p->maskbits != 0) {
  124. log_warn(LD_BUG, "AF_UNSPEC policy with maskbits==%d", p->maskbits);
  125. newpolicy_ipv4.maskbits = 0;
  126. newpolicy_ipv6.maskbits = 0;
  127. }
  128. tor_addr_from_ipv4h(&newpolicy_ipv4.addr, 0);
  129. tor_addr_from_ipv6_bytes(&newpolicy_ipv6.addr,
  130. "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
  131. smartlist_add(tmp, addr_policy_get_canonical_entry(&newpolicy_ipv4));
  132. smartlist_add(tmp, addr_policy_get_canonical_entry(&newpolicy_ipv6));
  133. addr_policy_free(p);
  134. } else {
  135. log_warn(LD_BUG, "Funny-looking address policy with family %d", family);
  136. smartlist_add(tmp, p);
  137. }
  138. } SMARTLIST_FOREACH_END(p);
  139. smartlist_free(*policy);
  140. *policy = tmp;
  141. }
  142. /**
  143. * Given a linked list of config lines containing "accept[6]" and "reject[6]"
  144. * tokens, parse them and append the result to <b>dest</b>. Return -1
  145. * if any tokens are malformed (and don't append any), else return 0.
  146. *
  147. * If <b>assume_action</b> is nonnegative, then insert its action
  148. * (ADDR_POLICY_ACCEPT or ADDR_POLICY_REJECT) for items that specify no
  149. * action.
  150. */
  151. static int
  152. parse_addr_policy(config_line_t *cfg, smartlist_t **dest,
  153. int assume_action)
  154. {
  155. smartlist_t *result;
  156. smartlist_t *entries;
  157. addr_policy_t *item;
  158. int malformed_list;
  159. int r = 0;
  160. if (!cfg)
  161. return 0;
  162. result = smartlist_new();
  163. entries = smartlist_new();
  164. for (; cfg; cfg = cfg->next) {
  165. smartlist_split_string(entries, cfg->value, ",",
  166. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  167. SMARTLIST_FOREACH_BEGIN(entries, const char *, ent) {
  168. log_debug(LD_CONFIG,"Adding new entry '%s'",ent);
  169. malformed_list = 0;
  170. item = router_parse_addr_policy_item_from_string(ent, assume_action,
  171. &malformed_list);
  172. if (item) {
  173. smartlist_add(result, item);
  174. } else if (malformed_list) {
  175. /* the error is so severe the entire list should be discarded */
  176. log_warn(LD_CONFIG, "Malformed policy '%s'. Discarding entire policy "
  177. "list.", ent);
  178. r = -1;
  179. } else {
  180. /* the error is minor: don't add the item, but keep processing the
  181. * rest of the policies in the list */
  182. log_debug(LD_CONFIG, "Ignored policy '%s' due to non-fatal error. "
  183. "The remainder of the policy list will be used.",
  184. ent);
  185. }
  186. } SMARTLIST_FOREACH_END(ent);
  187. SMARTLIST_FOREACH(entries, char *, ent, tor_free(ent));
  188. smartlist_clear(entries);
  189. }
  190. smartlist_free(entries);
  191. if (r == -1) {
  192. addr_policy_list_free(result);
  193. } else {
  194. policy_expand_private(&result);
  195. policy_expand_unspec(&result);
  196. if (*dest) {
  197. smartlist_add_all(*dest, result);
  198. smartlist_free(result);
  199. } else {
  200. *dest = result;
  201. }
  202. }
  203. return r;
  204. }
  205. /** Helper: parse the Reachable(Dir|OR)?Addresses fields into
  206. * reachable_(or|dir)_addr_policy. The options should already have
  207. * been validated by validate_addr_policies.
  208. */
  209. static int
  210. parse_reachable_addresses(void)
  211. {
  212. const or_options_t *options = get_options();
  213. int ret = 0;
  214. if (options->ReachableDirAddresses &&
  215. options->ReachableORAddresses &&
  216. options->ReachableAddresses) {
  217. log_warn(LD_CONFIG,
  218. "Both ReachableDirAddresses and ReachableORAddresses are set. "
  219. "ReachableAddresses setting will be ignored.");
  220. }
  221. addr_policy_list_free(reachable_or_addr_policy);
  222. reachable_or_addr_policy = NULL;
  223. if (!options->ReachableORAddresses && options->ReachableAddresses)
  224. log_info(LD_CONFIG,
  225. "Using ReachableAddresses as ReachableORAddresses.");
  226. if (parse_addr_policy(options->ReachableORAddresses ?
  227. options->ReachableORAddresses :
  228. options->ReachableAddresses,
  229. &reachable_or_addr_policy, ADDR_POLICY_ACCEPT)) {
  230. log_warn(LD_CONFIG,
  231. "Error parsing Reachable%sAddresses entry; ignoring.",
  232. options->ReachableORAddresses ? "OR" : "");
  233. ret = -1;
  234. }
  235. addr_policy_list_free(reachable_dir_addr_policy);
  236. reachable_dir_addr_policy = NULL;
  237. if (!options->ReachableDirAddresses && options->ReachableAddresses)
  238. log_info(LD_CONFIG,
  239. "Using ReachableAddresses as ReachableDirAddresses");
  240. if (parse_addr_policy(options->ReachableDirAddresses ?
  241. options->ReachableDirAddresses :
  242. options->ReachableAddresses,
  243. &reachable_dir_addr_policy, ADDR_POLICY_ACCEPT)) {
  244. if (options->ReachableDirAddresses)
  245. log_warn(LD_CONFIG,
  246. "Error parsing ReachableDirAddresses entry; ignoring.");
  247. ret = -1;
  248. }
  249. /* We ignore ReachableAddresses for relays */
  250. if (!server_mode(options)) {
  251. if ((reachable_or_addr_policy
  252. && policy_is_reject_star(reachable_or_addr_policy, AF_UNSPEC))
  253. || (reachable_dir_addr_policy
  254. && policy_is_reject_star(reachable_dir_addr_policy, AF_UNSPEC))) {
  255. log_warn(LD_CONFIG, "Tor cannot connect to the Internet if "
  256. "ReachableAddresses, ReachableORAddresses, or "
  257. "ReachableDirAddresses reject all addresses. Please accept "
  258. "some addresses in these options.");
  259. } else if (options->ClientUseIPv4 == 1
  260. && ((reachable_or_addr_policy
  261. && policy_is_reject_star(reachable_or_addr_policy, AF_INET))
  262. || (reachable_dir_addr_policy
  263. && policy_is_reject_star(reachable_dir_addr_policy, AF_INET)))) {
  264. log_warn(LD_CONFIG, "You have set ClientUseIPv4 1, but "
  265. "ReachableAddresses, ReachableORAddresses, or "
  266. "ReachableDirAddresses reject all IPv4 addresses. "
  267. "Tor will not connect using IPv4.");
  268. } else if (fascist_firewall_use_ipv6(options)
  269. && ((reachable_or_addr_policy
  270. && policy_is_reject_star(reachable_or_addr_policy, AF_INET6))
  271. || (reachable_dir_addr_policy
  272. && policy_is_reject_star(reachable_dir_addr_policy, AF_INET6)))) {
  273. log_warn(LD_CONFIG, "You have configured tor to use IPv6 "
  274. "(ClientUseIPv6 1 or UseBridges 1), but "
  275. "ReachableAddresses, ReachableORAddresses, or "
  276. "ReachableDirAddresses reject all IPv6 addresses. "
  277. "Tor will not connect using IPv6.");
  278. }
  279. }
  280. return ret;
  281. }
  282. /** Return true iff the firewall options, including ClientUseIPv4 0 and
  283. * ClientUseIPv6 0, might block any address:port combination.
  284. */
  285. int
  286. firewall_is_fascist_or(void)
  287. {
  288. const or_options_t *options = get_options();
  289. /* Assume every non-bridge relay has an IPv4 address.
  290. * Clients which use bridges may only know the IPv6 address of their
  291. * bridge. */
  292. return (reachable_or_addr_policy != NULL || options->ClientUseIPv4 == 0
  293. || (options->ClientUseIPv6 == 0 && options->UseBridges == 1));
  294. }
  295. /** Return true iff <b>policy</b> (possibly NULL) will allow a
  296. * connection to <b>addr</b>:<b>port</b>.
  297. */
  298. static int
  299. addr_policy_permits_tor_addr(const tor_addr_t *addr, uint16_t port,
  300. smartlist_t *policy)
  301. {
  302. addr_policy_result_t p;
  303. p = compare_tor_addr_to_addr_policy(addr, port, policy);
  304. switch (p) {
  305. case ADDR_POLICY_PROBABLY_ACCEPTED:
  306. case ADDR_POLICY_ACCEPTED:
  307. return 1;
  308. case ADDR_POLICY_PROBABLY_REJECTED:
  309. case ADDR_POLICY_REJECTED:
  310. return 0;
  311. default:
  312. log_warn(LD_BUG, "Unexpected result: %d", (int)p);
  313. return 0;
  314. }
  315. }
  316. /** Return true iff <b> policy</b> (possibly NULL) will allow a connection to
  317. * <b>addr</b>:<b>port</b>. <b>addr</b> is an IPv4 address given in host
  318. * order. */
  319. /* XXXX deprecate when possible. */
  320. static int
  321. addr_policy_permits_address(uint32_t addr, uint16_t port,
  322. smartlist_t *policy)
  323. {
  324. tor_addr_t a;
  325. tor_addr_from_ipv4h(&a, addr);
  326. return addr_policy_permits_tor_addr(&a, port, policy);
  327. }
  328. /** Return true iff we think our firewall will let us make a connection to
  329. * addr:port.
  330. *
  331. * If we are configured as a server, ignore any address family preference and
  332. * just use IPv4.
  333. * Otherwise:
  334. * - return false for all IPv4 addresses:
  335. * - if ClientUseIPv4 is 0, or
  336. * if pref_only and pref_ipv6 are both true;
  337. * - return false for all IPv6 addresses:
  338. * - if fascist_firewall_use_ipv6() is 0, or
  339. * - if pref_only is true and pref_ipv6 is false.
  340. *
  341. * Return false if addr is NULL or tor_addr_is_null(), or if port is 0. */
  342. STATIC int
  343. fascist_firewall_allows_address(const tor_addr_t *addr,
  344. uint16_t port,
  345. smartlist_t *firewall_policy,
  346. int pref_only, int pref_ipv6)
  347. {
  348. const or_options_t *options = get_options();
  349. if (!addr || tor_addr_is_null(addr) || !port) {
  350. return 0;
  351. }
  352. if (!server_mode(options)) {
  353. if (tor_addr_family(addr) == AF_INET &&
  354. (!options->ClientUseIPv4 || (pref_only && pref_ipv6)))
  355. return 0;
  356. /* Bridges can always use IPv6 */
  357. if (tor_addr_family(addr) == AF_INET6 &&
  358. (!fascist_firewall_use_ipv6(options) || (pref_only && !pref_ipv6)))
  359. return 0;
  360. }
  361. return addr_policy_permits_tor_addr(addr, port,
  362. firewall_policy);
  363. }
  364. /** Is this client configured to use IPv6?
  365. * Clients use IPv6 if ClientUseIPv6 is 1, or UseBridges is 1.
  366. */
  367. int fascist_firewall_use_ipv6(const or_options_t *options)
  368. {
  369. return (options->ClientUseIPv6 == 1 || options->UseBridges == 1);
  370. }
  371. /** Do we prefer to connect to IPv6, ignoring ClientPreferIPv6ORPort and
  372. * ClientPreferIPv6DirPort?
  373. * If we're unsure, return -1, otherwise, return 1 for IPv6 and 0 for IPv4.
  374. */
  375. static int
  376. fascist_firewall_prefer_ipv6_impl(const or_options_t *options)
  377. {
  378. /*
  379. Cheap implementation of config options ClientUseIPv4 & ClientUseIPv6 --
  380. If we're a server or IPv6 is disabled, use IPv4.
  381. If IPv4 is disabled, use IPv6.
  382. */
  383. if (server_mode(options) || !fascist_firewall_use_ipv6(options)) {
  384. return 0;
  385. }
  386. if (!options->ClientUseIPv4) {
  387. return 1;
  388. }
  389. return -1;
  390. }
  391. /** Do we prefer to connect to IPv6 ORPorts?
  392. */
  393. int
  394. fascist_firewall_prefer_ipv6_orport(const or_options_t *options)
  395. {
  396. int pref_ipv6 = fascist_firewall_prefer_ipv6_impl(options);
  397. if (pref_ipv6 >= 0) {
  398. return pref_ipv6;
  399. }
  400. /* We can use both IPv4 and IPv6 - which do we prefer? */
  401. if (options->ClientPreferIPv6ORPort == 1) {
  402. return 1;
  403. }
  404. /* For bridge clients, ClientPreferIPv6ORPort auto means "prefer IPv6". */
  405. if (options->UseBridges && options->ClientPreferIPv6ORPort != 0) {
  406. return 1;
  407. }
  408. return 0;
  409. }
  410. /** Do we prefer to connect to IPv6 DirPorts?
  411. */
  412. int
  413. fascist_firewall_prefer_ipv6_dirport(const or_options_t *options)
  414. {
  415. int pref_ipv6 = fascist_firewall_prefer_ipv6_impl(options);
  416. if (pref_ipv6 >= 0) {
  417. return pref_ipv6;
  418. }
  419. /* We can use both IPv4 and IPv6 - which do we prefer? */
  420. if (options->ClientPreferIPv6DirPort == 1) {
  421. return 1;
  422. }
  423. /* For bridge clients, ClientPreferIPv6ORPort auto means "prefer IPv6".
  424. * XX/teor - do bridge clients ever use a DirPort? */
  425. if (options->UseBridges && options->ClientPreferIPv6DirPort != 0) {
  426. return 1;
  427. }
  428. return 0;
  429. }
  430. /** Return true iff we think our firewall will let us make a connection to
  431. * addr:port. Uses ReachableORAddresses or ReachableDirAddresses based on
  432. * fw_connection.
  433. * If pref_only, return false if addr is not in the client's preferred address
  434. * family.
  435. */
  436. int
  437. fascist_firewall_allows_address_addr(const tor_addr_t *addr, uint16_t port,
  438. firewall_connection_t fw_connection,
  439. int pref_only)
  440. {
  441. const or_options_t *options = get_options();
  442. if (fw_connection == FIREWALL_OR_CONNECTION) {
  443. return fascist_firewall_allows_address(addr, port,
  444. reachable_or_addr_policy,
  445. pref_only,
  446. fascist_firewall_prefer_ipv6_orport(options));
  447. } else if (fw_connection == FIREWALL_DIR_CONNECTION) {
  448. return fascist_firewall_allows_address(addr, port,
  449. reachable_dir_addr_policy,
  450. pref_only,
  451. fascist_firewall_prefer_ipv6_dirport(options));
  452. } else {
  453. log_warn(LD_BUG, "Bad firewall_connection_t value %d.",
  454. fw_connection);
  455. return 0;
  456. }
  457. }
  458. /** Return true iff we think our firewall will let us make a connection to
  459. * addr:port (ap). Uses ReachableORAddresses or ReachableDirAddresses based on
  460. * fw_connection.
  461. * If pref_only, return false if addr is not in the client's preferred address
  462. * family.
  463. */
  464. int
  465. fascist_firewall_allows_address_ap(const tor_addr_port_t *ap,
  466. firewall_connection_t fw_connection,
  467. int pref_only)
  468. {
  469. tor_assert(ap);
  470. return fascist_firewall_allows_address_addr(&ap->addr, ap->port,
  471. fw_connection, pref_only);
  472. }
  473. /* Return true iff we think our firewall will let us make a connection to
  474. * ipv4h_or_addr:ipv4_or_port. ipv4h_or_addr is interpreted in host order.
  475. * Uses ReachableORAddresses or ReachableDirAddresses based on
  476. * fw_connection.
  477. * If pref_only, return false if addr is not in the client's preferred address
  478. * family. */
  479. int
  480. fascist_firewall_allows_address_ipv4h(uint32_t ipv4h_or_addr,
  481. uint16_t ipv4_or_port,
  482. firewall_connection_t fw_connection,
  483. int pref_only)
  484. {
  485. tor_addr_t ipv4_or_addr;
  486. tor_addr_from_ipv4h(&ipv4_or_addr, ipv4h_or_addr);
  487. return fascist_firewall_allows_address_addr(&ipv4_or_addr, ipv4_or_port,
  488. fw_connection, pref_only);
  489. }
  490. /** Return true iff we think our firewall will let us make a connection to
  491. * ipv4h_addr/ipv6_addr. Uses ipv4_orport/ipv6_orport/ReachableORAddresses or
  492. * ipv4_dirport/ipv6_dirport/ReachableDirAddresses based on IPv4/IPv6 and
  493. * <b>fw_connection</b>.
  494. * If pref_only, return false if addr is not in the client's preferred address
  495. * family. */
  496. static int
  497. fascist_firewall_allows_base(uint32_t ipv4h_addr, uint16_t ipv4_orport,
  498. uint16_t ipv4_dirport,
  499. const tor_addr_t *ipv6_addr, uint16_t ipv6_orport,
  500. uint16_t ipv6_dirport,
  501. firewall_connection_t fw_connection,
  502. int pref_only)
  503. {
  504. if (fascist_firewall_allows_address_ipv4h(ipv4h_addr,
  505. (fw_connection == FIREWALL_OR_CONNECTION
  506. ? ipv4_orport
  507. : ipv4_dirport),
  508. fw_connection,
  509. pref_only)) {
  510. return 1;
  511. }
  512. if (fascist_firewall_allows_address_addr(ipv6_addr,
  513. (fw_connection == FIREWALL_OR_CONNECTION
  514. ? ipv6_orport
  515. : ipv6_dirport),
  516. fw_connection,
  517. pref_only)) {
  518. return 1;
  519. }
  520. return 0;
  521. }
  522. /** Like fascist_firewall_allows_ri, but doesn't consult the node. */
  523. static int
  524. fascist_firewall_allows_ri_impl(const routerinfo_t *ri,
  525. firewall_connection_t fw_connection,
  526. int pref_only)
  527. {
  528. if (!ri) {
  529. return 0;
  530. }
  531. /* Assume IPv4 and IPv6 DirPorts are the same */
  532. return fascist_firewall_allows_base(ri->addr, ri->or_port, ri->dir_port,
  533. &ri->ipv6_addr, ri->ipv6_orport,
  534. ri->dir_port, fw_connection, pref_only);
  535. }
  536. /** Like fascist_firewall_allows_rs, but doesn't consult the node. */
  537. static int
  538. fascist_firewall_allows_rs_impl(const routerstatus_t *rs,
  539. firewall_connection_t fw_connection,
  540. int pref_only)
  541. {
  542. if (!rs) {
  543. return 0;
  544. }
  545. /* Assume IPv4 and IPv6 DirPorts are the same */
  546. return fascist_firewall_allows_base(rs->addr, rs->or_port, rs->dir_port,
  547. &rs->ipv6_addr, rs->ipv6_orport,
  548. rs->dir_port, fw_connection, pref_only);
  549. }
  550. /** Return true iff we think our firewall will let us make a connection to
  551. * <b>rs</b> on either its IPv4 or IPv6 address. Uses
  552. * or_port/ipv6_orport/ReachableORAddresses or dir_port/ReachableDirAddresses
  553. * based on IPv4/IPv6 and <b>fw_connection</b>.
  554. * If pref_only, return false if addr is not in the client's preferred address
  555. * family.
  556. * Consults the corresponding node if the addresses in rs are not permitted. */
  557. int
  558. fascist_firewall_allows_rs(const routerstatus_t *rs,
  559. firewall_connection_t fw_connection, int pref_only)
  560. {
  561. if (!rs) {
  562. return 0;
  563. }
  564. /* Assume IPv4 and IPv6 DirPorts are the same */
  565. if (fascist_firewall_allows_rs_impl(rs, fw_connection, pref_only)) {
  566. return 1;
  567. } else {
  568. const node_t *node = node_get_by_id(rs->identity_digest);
  569. return fascist_firewall_allows_node(node, fw_connection, pref_only);
  570. }
  571. }
  572. /** Like fascist_firewall_allows_md, but doesn't consult the node. */
  573. static int
  574. fascist_firewall_allows_md_impl(const microdesc_t *md,
  575. firewall_connection_t fw_connection,
  576. int pref_only)
  577. {
  578. if (!md) {
  579. return 0;
  580. }
  581. /* Can't check dirport, it doesn't have one */
  582. if (fw_connection == FIREWALL_DIR_CONNECTION) {
  583. return 0;
  584. }
  585. /* Also can't check IPv4, doesn't have that either */
  586. return fascist_firewall_allows_address_addr(&md->ipv6_addr, md->ipv6_orport,
  587. fw_connection, pref_only);
  588. }
  589. /** Return true iff we think our firewall will let us make a connection to
  590. * <b>node</b>:
  591. * - if <b>preferred</b> is true, on its preferred address,
  592. * - if not, on either its IPv4 or IPv6 address.
  593. * Uses or_port/ipv6_orport/ReachableORAddresses or
  594. * dir_port/ReachableDirAddresses based on IPv4/IPv6 and <b>fw_connection</b>.
  595. * If pref_only, return false if addr is not in the client's preferred address
  596. * family. */
  597. int
  598. fascist_firewall_allows_node(const node_t *node,
  599. firewall_connection_t fw_connection,
  600. int pref_only)
  601. {
  602. if (!node) {
  603. return 0;
  604. }
  605. node_assert_ok(node);
  606. /* Sometimes, the rs is missing the IPv6 address info, and we need to go
  607. * all the way to the md */
  608. if (node->ri && fascist_firewall_allows_ri_impl(node->ri, fw_connection,
  609. pref_only)) {
  610. return 1;
  611. } else if (node->rs && fascist_firewall_allows_rs_impl(node->rs,
  612. fw_connection,
  613. pref_only)) {
  614. return 1;
  615. } else if (node->md && fascist_firewall_allows_md_impl(node->md,
  616. fw_connection,
  617. pref_only)) {
  618. return 1;
  619. } else {
  620. /* If we know nothing, assume it's unreachable, we'll never get an address
  621. * to connect to. */
  622. return 0;
  623. }
  624. }
  625. /** Return true iff we think our firewall will let us make a connection to
  626. * <b>ds</b> on either its IPv4 or IPv6 address. Uses ReachableORAddresses or
  627. * ReachableDirAddresses based on <b>fw_connection</b> (some directory
  628. * connections are tunneled over ORPorts).
  629. * If pref_only, return false if addr is not in the client's preferred address
  630. * family. */
  631. int
  632. fascist_firewall_allows_dir_server(const dir_server_t *ds,
  633. firewall_connection_t fw_connection,
  634. int pref_only)
  635. {
  636. if (!ds) {
  637. return 0;
  638. }
  639. /* A dir_server_t always has a fake_status. As long as it has the same
  640. * addresses/ports in both fake_status and dir_server_t, this works fine.
  641. * (See #17867.)
  642. * This function relies on fascist_firewall_allows_rs looking up the node on
  643. * failure, because it will get the latest info for the relay. */
  644. return fascist_firewall_allows_rs(&ds->fake_status, fw_connection,
  645. pref_only);
  646. }
  647. /** If a and b are both valid and allowed by fw_connection,
  648. * choose one based on want_a and return it.
  649. * Otherwise, return whichever is allowed.
  650. * Otherwise, return NULL.
  651. * If pref_only, only return an address if it's in the client's preferred
  652. * address family. */
  653. static const tor_addr_port_t *
  654. fascist_firewall_choose_address_impl(const tor_addr_port_t *a,
  655. const tor_addr_port_t *b,
  656. int want_a,
  657. firewall_connection_t fw_connection,
  658. int pref_only)
  659. {
  660. const tor_addr_port_t *use_a = NULL;
  661. const tor_addr_port_t *use_b = NULL;
  662. if (fascist_firewall_allows_address_ap(a, fw_connection, pref_only)) {
  663. use_a = a;
  664. }
  665. if (fascist_firewall_allows_address_ap(b, fw_connection, pref_only)) {
  666. use_b = b;
  667. }
  668. /* If both are allowed */
  669. if (use_a && use_b) {
  670. /* Choose a if we want it */
  671. return (want_a ? use_a : use_b);
  672. } else {
  673. /* Choose a if we have it */
  674. return (use_a ? use_a : use_b);
  675. }
  676. }
  677. /** If a and b are both valid and preferred by fw_connection,
  678. * choose one based on want_a and return it.
  679. * Otherwise, return whichever is preferred.
  680. * If neither are preferred, and pref_only is false:
  681. * - If a and b are both allowed by fw_connection,
  682. * choose one based on want_a and return it.
  683. * - Otherwise, return whichever is preferred.
  684. * Otherwise, return NULL. */
  685. const tor_addr_port_t *
  686. fascist_firewall_choose_address(const tor_addr_port_t *a,
  687. const tor_addr_port_t *b,
  688. int want_a,
  689. firewall_connection_t fw_connection,
  690. int pref_only)
  691. {
  692. const tor_addr_port_t *pref = fascist_firewall_choose_address_impl(
  693. a, b, want_a,
  694. fw_connection,
  695. 1);
  696. if (pref_only || pref) {
  697. /* If there is a preferred address, use it. If we can only use preferred
  698. * addresses, and neither address is preferred, pref will be NULL, and we
  699. * want to return NULL, so return it. */
  700. return pref;
  701. } else {
  702. /* If there's no preferred address, and we can return addresses that are
  703. * not preferred, use an address that's allowed */
  704. return fascist_firewall_choose_address_impl(a, b, want_a, fw_connection,
  705. 0);
  706. }
  707. }
  708. /** Copy an address and port into <b>ap</b> that we think our firewall will
  709. * let us connect to. Uses ipv4_addr/ipv6_addr and
  710. * ipv4_orport/ipv6_orport/ReachableORAddresses or
  711. * ipv4_dirport/ipv6_dirport/ReachableDirAddresses based on IPv4/IPv6 and
  712. * <b>fw_connection</b>.
  713. * If pref_only, only choose preferred addresses. In either case, choose
  714. * a preferred address before an address that's not preferred.
  715. * If neither address is chosen, return 0, else return 1. */
  716. static int
  717. fascist_firewall_choose_address_base(const tor_addr_t *ipv4_addr,
  718. uint16_t ipv4_orport,
  719. uint16_t ipv4_dirport,
  720. const tor_addr_t *ipv6_addr,
  721. uint16_t ipv6_orport,
  722. uint16_t ipv6_dirport,
  723. firewall_connection_t fw_connection,
  724. int pref_only,
  725. tor_addr_port_t* ap)
  726. {
  727. const tor_addr_port_t *result = NULL;
  728. /* This argument is ignored as long as the address pair is IPv4/IPv6,
  729. * because we always have a preference in a client.
  730. * For bridge clients, this selects the preferred address, which was
  731. * previously IPv6 (if a bridge has both), so we keep that behaviour. */
  732. const int bridge_client_prefer_ipv4 = 0;
  733. tor_assert(ipv6_addr);
  734. tor_assert(ap);
  735. tor_addr_port_t ipv4_ap;
  736. tor_addr_copy(&ipv4_ap.addr, ipv4_addr);
  737. ipv4_ap.port = (fw_connection == FIREWALL_OR_CONNECTION
  738. ? ipv4_orport
  739. : ipv4_dirport);
  740. tor_addr_port_t ipv6_ap;
  741. tor_addr_copy(&ipv6_ap.addr, ipv6_addr);
  742. ipv6_ap.port = (fw_connection == FIREWALL_OR_CONNECTION
  743. ? ipv6_orport
  744. : ipv6_dirport);
  745. result = fascist_firewall_choose_address(&ipv4_ap, &ipv6_ap,
  746. bridge_client_prefer_ipv4,
  747. fw_connection, pref_only);
  748. if (result) {
  749. tor_addr_copy(&ap->addr, &result->addr);
  750. ap->port = result->port;
  751. return 1;
  752. } else {
  753. return 0;
  754. }
  755. }
  756. /** Like fascist_firewall_choose_address_base, but takes a host-order IPv4
  757. * address as the first parameter. */
  758. static int
  759. fascist_firewall_choose_address_ipv4h(uint32_t ipv4h_addr,
  760. uint16_t ipv4_orport,
  761. uint16_t ipv4_dirport,
  762. const tor_addr_t *ipv6_addr,
  763. uint16_t ipv6_orport,
  764. uint16_t ipv6_dirport,
  765. firewall_connection_t fw_connection,
  766. int pref_only,
  767. tor_addr_port_t* ap)
  768. {
  769. tor_addr_t ipv4_addr;
  770. tor_addr_from_ipv4h(&ipv4_addr, ipv4h_addr);
  771. return fascist_firewall_choose_address_base(&ipv4_addr, ipv4_orport,
  772. ipv4_dirport, ipv6_addr,
  773. ipv6_orport, ipv6_dirport,
  774. fw_connection, pref_only, ap);
  775. }
  776. #define IPV6_OR_LOOKUP(r, identity_digest, ipv6_or_ap) \
  777. STMT_BEGIN \
  778. if (!(r)->ipv6_orport || tor_addr_is_null(&(r)->ipv6_addr)) { \
  779. const node_t *node = node_get_by_id((identity_digest)); \
  780. if (node) { \
  781. node_get_pref_ipv6_orport(node, &(ipv6_or_ap)); \
  782. } else { \
  783. tor_addr_make_null(&(ipv6_or_ap).addr, AF_INET6); \
  784. (ipv6_or_ap).port = 0; \
  785. } \
  786. } else { \
  787. tor_addr_copy(&(ipv6_or_ap).addr, &(r)->ipv6_addr); \
  788. (ipv6_or_ap).port = (r)->ipv6_orport; \
  789. } \
  790. STMT_END
  791. /** Copy an address and port from <b>rs</b> into <b>ap</b> that we think our
  792. * firewall will let us connect to. Uses ipv4h_addr/ipv6_addr and
  793. * ipv4_orport/ipv6_orport/ReachableORAddresses or
  794. * ipv4_dirport/ipv6_dirport/ReachableDirAddresses based on IPv4/IPv6 and
  795. * <b>fw_connection</b>.
  796. * If pref_only, only choose preferred addresses. In either case, choose
  797. * a preferred address before an address that's not preferred.
  798. * If neither address is chosen, return 0, else return 1.
  799. * Consults the corresponding node if the addresses in rs are not valid. */
  800. int
  801. fascist_firewall_choose_address_rs(const routerstatus_t *rs,
  802. firewall_connection_t fw_connection,
  803. int pref_only, tor_addr_port_t* ap)
  804. {
  805. if (!rs) {
  806. return 0;
  807. }
  808. tor_assert(ap);
  809. /* Don't do the lookup if the IPv6 address/port in rs is OK.
  810. * If it's OK, assume the dir_port is also OK. */
  811. tor_addr_port_t ipv6_or_ap;
  812. IPV6_OR_LOOKUP(rs, rs->identity_digest, ipv6_or_ap);
  813. /* Assume IPv4 and IPv6 DirPorts are the same.
  814. * Assume the IPv6 OR and Dir addresses are the same. */
  815. return fascist_firewall_choose_address_ipv4h(rs->addr,
  816. rs->or_port,
  817. rs->dir_port,
  818. &ipv6_or_ap.addr,
  819. ipv6_or_ap.port,
  820. rs->dir_port,
  821. fw_connection,
  822. pref_only,
  823. ap);
  824. }
  825. /** Copy an address and port from <b>node</b> into <b>ap</b> that we think our
  826. * firewall will let us connect to. Uses ipv4h_addr/ipv6_addr and
  827. * ipv4_orport/ipv6_orport/ReachableORAddresses or
  828. * ipv4_dirport/ipv6_dirport/ReachableDirAddresses based on IPv4/IPv6 and
  829. * <b>fw_connection</b>.
  830. * If pref_only, only choose preferred addresses. In either case, choose
  831. * a preferred address before an address that's not preferred.
  832. * If neither address is chosen, return 0, else return 1. */
  833. int
  834. fascist_firewall_choose_address_node(const node_t *node,
  835. firewall_connection_t fw_connection,
  836. int pref_only, tor_addr_port_t *ap)
  837. {
  838. if (!node) {
  839. return 0;
  840. }
  841. node_assert_ok(node);
  842. tor_addr_port_t ipv4_or_ap;
  843. node_get_prim_orport(node, &ipv4_or_ap);
  844. tor_addr_port_t ipv4_dir_ap;
  845. node_get_prim_dirport(node, &ipv4_dir_ap);
  846. tor_addr_port_t ipv6_or_ap;
  847. node_get_pref_ipv6_orport(node, &ipv6_or_ap);
  848. tor_addr_port_t ipv6_dir_ap;
  849. node_get_pref_ipv6_dirport(node, &ipv6_dir_ap);
  850. /* Assume the IPv6 OR and Dir addresses are the same. */
  851. return fascist_firewall_choose_address_base(&ipv4_or_ap.addr,
  852. ipv4_or_ap.port,
  853. ipv4_dir_ap.port,
  854. &ipv6_or_ap.addr,
  855. ipv6_or_ap.port,
  856. ipv6_dir_ap.port,
  857. fw_connection,
  858. pref_only,
  859. ap);
  860. }
  861. /** Copy an address and port from <b>ds</b> into <b>ap</b> that we think our
  862. * firewall will let us connect to. Uses ipv4h_addr/ipv6_addr and
  863. * ipv4_orport/ipv6_orport/ReachableORAddresses or
  864. * ipv4_dirport/ipv6_dirport/ReachableDirAddresses based on IPv4/IPv6 and
  865. * <b>fw_connection</b>.
  866. * If pref_only, only choose preferred addresses. In either case, choose
  867. * a preferred address before an address that's not preferred.
  868. * If neither address is chosen, return 0, else return 1. */
  869. int
  870. fascist_firewall_choose_address_dir_server(const dir_server_t *ds,
  871. firewall_connection_t fw_connection,
  872. int pref_only, tor_addr_port_t *ap)
  873. {
  874. if (!ds) {
  875. return 0;
  876. }
  877. /* A dir_server_t always has a fake_status. As long as it has the same
  878. * addresses/ports in both fake_status and dir_server_t, this works fine.
  879. * (See #17867.)
  880. * This function relies on fascist_firewall_choose_address_rs looking up the
  881. * addresses from the node if it can, because that will get the latest info
  882. * for the relay. */
  883. return fascist_firewall_choose_address_rs(&ds->fake_status, fw_connection,
  884. pref_only, ap);
  885. }
  886. /** Return 1 if <b>addr</b> is permitted to connect to our dir port,
  887. * based on <b>dir_policy</b>. Else return 0.
  888. */
  889. int
  890. dir_policy_permits_address(const tor_addr_t *addr)
  891. {
  892. return addr_policy_permits_tor_addr(addr, 1, dir_policy);
  893. }
  894. /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
  895. * based on <b>socks_policy</b>. Else return 0.
  896. */
  897. int
  898. socks_policy_permits_address(const tor_addr_t *addr)
  899. {
  900. return addr_policy_permits_tor_addr(addr, 1, socks_policy);
  901. }
  902. /** Return true iff the address <b>addr</b> is in a country listed in the
  903. * case-insensitive list of country codes <b>cc_list</b>. */
  904. static int
  905. addr_is_in_cc_list(uint32_t addr, const smartlist_t *cc_list)
  906. {
  907. country_t country;
  908. const char *name;
  909. tor_addr_t tar;
  910. if (!cc_list)
  911. return 0;
  912. /* XXXXipv6 */
  913. tor_addr_from_ipv4h(&tar, addr);
  914. country = geoip_get_country_by_addr(&tar);
  915. name = geoip_get_country_name(country);
  916. return smartlist_contains_string_case(cc_list, name);
  917. }
  918. /** Return 1 if <b>addr</b>:<b>port</b> is permitted to publish to our
  919. * directory, based on <b>authdir_reject_policy</b>. Else return 0.
  920. */
  921. int
  922. authdir_policy_permits_address(uint32_t addr, uint16_t port)
  923. {
  924. if (! addr_policy_permits_address(addr, port, authdir_reject_policy))
  925. return 0;
  926. return !addr_is_in_cc_list(addr, get_options()->AuthDirRejectCCs);
  927. }
  928. /** Return 1 if <b>addr</b>:<b>port</b> is considered valid in our
  929. * directory, based on <b>authdir_invalid_policy</b>. Else return 0.
  930. */
  931. int
  932. authdir_policy_valid_address(uint32_t addr, uint16_t port)
  933. {
  934. if (! addr_policy_permits_address(addr, port, authdir_invalid_policy))
  935. return 0;
  936. return !addr_is_in_cc_list(addr, get_options()->AuthDirInvalidCCs);
  937. }
  938. /** Return 1 if <b>addr</b>:<b>port</b> should be marked as a bad exit,
  939. * based on <b>authdir_badexit_policy</b>. Else return 0.
  940. */
  941. int
  942. authdir_policy_badexit_address(uint32_t addr, uint16_t port)
  943. {
  944. if (! addr_policy_permits_address(addr, port, authdir_badexit_policy))
  945. return 1;
  946. return addr_is_in_cc_list(addr, get_options()->AuthDirBadExitCCs);
  947. }
  948. #define REJECT(arg) \
  949. STMT_BEGIN *msg = tor_strdup(arg); goto err; STMT_END
  950. /** Config helper: If there's any problem with the policy configuration
  951. * options in <b>options</b>, return -1 and set <b>msg</b> to a newly
  952. * allocated description of the error. Else return 0. */
  953. int
  954. validate_addr_policies(const or_options_t *options, char **msg)
  955. {
  956. /* XXXX Maybe merge this into parse_policies_from_options, to make sure
  957. * that the two can't go out of sync. */
  958. smartlist_t *addr_policy=NULL;
  959. *msg = NULL;
  960. if (policies_parse_exit_policy_from_options(options,0,NULL,&addr_policy)) {
  961. REJECT("Error in ExitPolicy entry.");
  962. }
  963. static int warned_about_exitrelay = 0;
  964. const int exitrelay_setting_is_auto = options->ExitRelay == -1;
  965. const int policy_accepts_something =
  966. ! (policy_is_reject_star(addr_policy, AF_INET) &&
  967. policy_is_reject_star(addr_policy, AF_INET6));
  968. if (server_mode(options) &&
  969. ! warned_about_exitrelay &&
  970. exitrelay_setting_is_auto &&
  971. policy_accepts_something) {
  972. /* Policy accepts something */
  973. warned_about_exitrelay = 1;
  974. log_warn(LD_CONFIG,
  975. "Tor is running as an exit relay%s. If you did not want this "
  976. "behavior, please set the ExitRelay option to 0. If you do "
  977. "want to run an exit Relay, please set the ExitRelay option "
  978. "to 1 to disable this warning, and for forward compatibility.",
  979. options->ExitPolicy == NULL ?
  980. " with the default exit policy" : "");
  981. if (options->ExitPolicy == NULL) {
  982. log_warn(LD_CONFIG,
  983. "In a future version of Tor, ExitRelay 0 may become the "
  984. "default when no ExitPolicy is given.");
  985. }
  986. }
  987. /* The rest of these calls *append* to addr_policy. So don't actually
  988. * use the results for anything other than checking if they parse! */
  989. if (parse_addr_policy(options->DirPolicy, &addr_policy, -1))
  990. REJECT("Error in DirPolicy entry.");
  991. if (parse_addr_policy(options->SocksPolicy, &addr_policy, -1))
  992. REJECT("Error in SocksPolicy entry.");
  993. if (parse_addr_policy(options->AuthDirReject, &addr_policy,
  994. ADDR_POLICY_REJECT))
  995. REJECT("Error in AuthDirReject entry.");
  996. if (parse_addr_policy(options->AuthDirInvalid, &addr_policy,
  997. ADDR_POLICY_REJECT))
  998. REJECT("Error in AuthDirInvalid entry.");
  999. if (parse_addr_policy(options->AuthDirBadExit, &addr_policy,
  1000. ADDR_POLICY_REJECT))
  1001. REJECT("Error in AuthDirBadExit entry.");
  1002. if (parse_addr_policy(options->ReachableAddresses, &addr_policy,
  1003. ADDR_POLICY_ACCEPT))
  1004. REJECT("Error in ReachableAddresses entry.");
  1005. if (parse_addr_policy(options->ReachableORAddresses, &addr_policy,
  1006. ADDR_POLICY_ACCEPT))
  1007. REJECT("Error in ReachableORAddresses entry.");
  1008. if (parse_addr_policy(options->ReachableDirAddresses, &addr_policy,
  1009. ADDR_POLICY_ACCEPT))
  1010. REJECT("Error in ReachableDirAddresses entry.");
  1011. err:
  1012. addr_policy_list_free(addr_policy);
  1013. return *msg ? -1 : 0;
  1014. #undef REJECT
  1015. }
  1016. /** Parse <b>string</b> in the same way that the exit policy
  1017. * is parsed, and put the processed version in *<b>policy</b>.
  1018. * Ignore port specifiers.
  1019. */
  1020. static int
  1021. load_policy_from_option(config_line_t *config, const char *option_name,
  1022. smartlist_t **policy,
  1023. int assume_action)
  1024. {
  1025. int r;
  1026. int killed_any_ports = 0;
  1027. addr_policy_list_free(*policy);
  1028. *policy = NULL;
  1029. r = parse_addr_policy(config, policy, assume_action);
  1030. if (r < 0) {
  1031. return -1;
  1032. }
  1033. if (*policy) {
  1034. SMARTLIST_FOREACH_BEGIN(*policy, addr_policy_t *, n) {
  1035. /* ports aren't used in these. */
  1036. if (n->prt_min > 1 || n->prt_max != 65535) {
  1037. addr_policy_t newp, *c;
  1038. memcpy(&newp, n, sizeof(newp));
  1039. newp.prt_min = 1;
  1040. newp.prt_max = 65535;
  1041. newp.is_canonical = 0;
  1042. c = addr_policy_get_canonical_entry(&newp);
  1043. SMARTLIST_REPLACE_CURRENT(*policy, n, c);
  1044. addr_policy_free(n);
  1045. killed_any_ports = 1;
  1046. }
  1047. } SMARTLIST_FOREACH_END(n);
  1048. }
  1049. if (killed_any_ports) {
  1050. log_warn(LD_CONFIG, "Ignoring ports in %s option.", option_name);
  1051. }
  1052. return 0;
  1053. }
  1054. /** Set all policies based on <b>options</b>, which should have been validated
  1055. * first by validate_addr_policies. */
  1056. int
  1057. policies_parse_from_options(const or_options_t *options)
  1058. {
  1059. int ret = 0;
  1060. if (load_policy_from_option(options->SocksPolicy, "SocksPolicy",
  1061. &socks_policy, -1) < 0)
  1062. ret = -1;
  1063. if (load_policy_from_option(options->DirPolicy, "DirPolicy",
  1064. &dir_policy, -1) < 0)
  1065. ret = -1;
  1066. if (load_policy_from_option(options->AuthDirReject, "AuthDirReject",
  1067. &authdir_reject_policy, ADDR_POLICY_REJECT) < 0)
  1068. ret = -1;
  1069. if (load_policy_from_option(options->AuthDirInvalid, "AuthDirInvalid",
  1070. &authdir_invalid_policy, ADDR_POLICY_REJECT) < 0)
  1071. ret = -1;
  1072. if (load_policy_from_option(options->AuthDirBadExit, "AuthDirBadExit",
  1073. &authdir_badexit_policy, ADDR_POLICY_REJECT) < 0)
  1074. ret = -1;
  1075. if (parse_reachable_addresses() < 0)
  1076. ret = -1;
  1077. return ret;
  1078. }
  1079. /** Compare two provided address policy items, and return -1, 0, or 1
  1080. * if the first is less than, equal to, or greater than the second. */
  1081. static int
  1082. cmp_single_addr_policy(addr_policy_t *a, addr_policy_t *b)
  1083. {
  1084. int r;
  1085. if ((r=((int)a->policy_type - (int)b->policy_type)))
  1086. return r;
  1087. if ((r=((int)a->is_private - (int)b->is_private)))
  1088. return r;
  1089. /* refcnt and is_canonical are irrelevant to equality,
  1090. * they are hash table implementation details */
  1091. if ((r=tor_addr_compare(&a->addr, &b->addr, CMP_EXACT)))
  1092. return r;
  1093. if ((r=((int)a->maskbits - (int)b->maskbits)))
  1094. return r;
  1095. if ((r=((int)a->prt_min - (int)b->prt_min)))
  1096. return r;
  1097. if ((r=((int)a->prt_max - (int)b->prt_max)))
  1098. return r;
  1099. return 0;
  1100. }
  1101. /** Like cmp_single_addr_policy() above, but looks at the
  1102. * whole set of policies in each case. */
  1103. int
  1104. cmp_addr_policies(smartlist_t *a, smartlist_t *b)
  1105. {
  1106. int r, i;
  1107. int len_a = a ? smartlist_len(a) : 0;
  1108. int len_b = b ? smartlist_len(b) : 0;
  1109. for (i = 0; i < len_a && i < len_b; ++i) {
  1110. if ((r = cmp_single_addr_policy(smartlist_get(a, i), smartlist_get(b, i))))
  1111. return r;
  1112. }
  1113. if (i == len_a && i == len_b)
  1114. return 0;
  1115. if (i < len_a)
  1116. return -1;
  1117. else
  1118. return 1;
  1119. }
  1120. /** Node in hashtable used to store address policy entries. */
  1121. typedef struct policy_map_ent_t {
  1122. HT_ENTRY(policy_map_ent_t) node;
  1123. addr_policy_t *policy;
  1124. } policy_map_ent_t;
  1125. /* DOCDOC policy_root */
  1126. static HT_HEAD(policy_map, policy_map_ent_t) policy_root = HT_INITIALIZER();
  1127. /** Return true iff a and b are equal. */
  1128. static inline int
  1129. policy_eq(policy_map_ent_t *a, policy_map_ent_t *b)
  1130. {
  1131. return cmp_single_addr_policy(a->policy, b->policy) == 0;
  1132. }
  1133. /** Return a hashcode for <b>ent</b> */
  1134. static unsigned int
  1135. policy_hash(const policy_map_ent_t *ent)
  1136. {
  1137. const addr_policy_t *a = ent->policy;
  1138. addr_policy_t aa;
  1139. memset(&aa, 0, sizeof(aa));
  1140. aa.prt_min = a->prt_min;
  1141. aa.prt_max = a->prt_max;
  1142. aa.maskbits = a->maskbits;
  1143. aa.policy_type = a->policy_type;
  1144. aa.is_private = a->is_private;
  1145. if (a->is_private) {
  1146. aa.is_private = 1;
  1147. } else {
  1148. tor_addr_copy_tight(&aa.addr, &a->addr);
  1149. }
  1150. return (unsigned) siphash24g(&aa, sizeof(aa));
  1151. }
  1152. HT_PROTOTYPE(policy_map, policy_map_ent_t, node, policy_hash,
  1153. policy_eq)
  1154. HT_GENERATE2(policy_map, policy_map_ent_t, node, policy_hash,
  1155. policy_eq, 0.6, tor_reallocarray_, tor_free_)
  1156. /** Given a pointer to an addr_policy_t, return a copy of the pointer to the
  1157. * "canonical" copy of that addr_policy_t; the canonical copy is a single
  1158. * reference-counted object. */
  1159. addr_policy_t *
  1160. addr_policy_get_canonical_entry(addr_policy_t *e)
  1161. {
  1162. policy_map_ent_t search, *found;
  1163. if (e->is_canonical)
  1164. return e;
  1165. search.policy = e;
  1166. found = HT_FIND(policy_map, &policy_root, &search);
  1167. if (!found) {
  1168. found = tor_malloc_zero(sizeof(policy_map_ent_t));
  1169. found->policy = tor_memdup(e, sizeof(addr_policy_t));
  1170. found->policy->is_canonical = 1;
  1171. found->policy->refcnt = 0;
  1172. HT_INSERT(policy_map, &policy_root, found);
  1173. }
  1174. tor_assert(!cmp_single_addr_policy(found->policy, e));
  1175. ++found->policy->refcnt;
  1176. return found->policy;
  1177. }
  1178. /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
  1179. * addr and port are both known. */
  1180. static addr_policy_result_t
  1181. compare_known_tor_addr_to_addr_policy(const tor_addr_t *addr, uint16_t port,
  1182. const smartlist_t *policy)
  1183. {
  1184. /* We know the address and port, and we know the policy, so we can just
  1185. * compute an exact match. */
  1186. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
  1187. if (tmpe->addr.family == AF_UNSPEC) {
  1188. log_warn(LD_BUG, "Policy contains an AF_UNSPEC address, which only "
  1189. "matches other AF_UNSPEC addresses.");
  1190. }
  1191. /* Address is known */
  1192. if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
  1193. CMP_EXACT)) {
  1194. if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
  1195. /* Exact match for the policy */
  1196. return tmpe->policy_type == ADDR_POLICY_ACCEPT ?
  1197. ADDR_POLICY_ACCEPTED : ADDR_POLICY_REJECTED;
  1198. }
  1199. }
  1200. } SMARTLIST_FOREACH_END(tmpe);
  1201. /* accept all by default. */
  1202. return ADDR_POLICY_ACCEPTED;
  1203. }
  1204. /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
  1205. * addr is known but port is not. */
  1206. static addr_policy_result_t
  1207. compare_known_tor_addr_to_addr_policy_noport(const tor_addr_t *addr,
  1208. const smartlist_t *policy)
  1209. {
  1210. /* We look to see if there's a definite match. If so, we return that
  1211. match's value, unless there's an intervening possible match that says
  1212. something different. */
  1213. int maybe_accept = 0, maybe_reject = 0;
  1214. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
  1215. if (tmpe->addr.family == AF_UNSPEC) {
  1216. log_warn(LD_BUG, "Policy contains an AF_UNSPEC address, which only "
  1217. "matches other AF_UNSPEC addresses.");
  1218. }
  1219. if (!tor_addr_compare_masked(addr, &tmpe->addr, tmpe->maskbits,
  1220. CMP_EXACT)) {
  1221. if (tmpe->prt_min <= 1 && tmpe->prt_max >= 65535) {
  1222. /* Definitely matches, since it covers all ports. */
  1223. if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
  1224. /* If we already hit a clause that might trigger a 'reject', than we
  1225. * can't be sure of this certain 'accept'.*/
  1226. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
  1227. ADDR_POLICY_ACCEPTED;
  1228. } else {
  1229. return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
  1230. ADDR_POLICY_REJECTED;
  1231. }
  1232. } else {
  1233. /* Might match. */
  1234. if (tmpe->policy_type == ADDR_POLICY_REJECT)
  1235. maybe_reject = 1;
  1236. else
  1237. maybe_accept = 1;
  1238. }
  1239. }
  1240. } SMARTLIST_FOREACH_END(tmpe);
  1241. /* accept all by default. */
  1242. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  1243. }
  1244. /** Helper for compare_tor_addr_to_addr_policy. Implements the case where
  1245. * port is known but address is not. */
  1246. static addr_policy_result_t
  1247. compare_unknown_tor_addr_to_addr_policy(uint16_t port,
  1248. const smartlist_t *policy)
  1249. {
  1250. /* We look to see if there's a definite match. If so, we return that
  1251. match's value, unless there's an intervening possible match that says
  1252. something different. */
  1253. int maybe_accept = 0, maybe_reject = 0;
  1254. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, tmpe) {
  1255. if (tmpe->addr.family == AF_UNSPEC) {
  1256. log_warn(LD_BUG, "Policy contains an AF_UNSPEC address, which only "
  1257. "matches other AF_UNSPEC addresses.");
  1258. }
  1259. if (tmpe->prt_min <= port && port <= tmpe->prt_max) {
  1260. if (tmpe->maskbits == 0) {
  1261. /* Definitely matches, since it covers all addresses. */
  1262. if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
  1263. /* If we already hit a clause that might trigger a 'reject', than we
  1264. * can't be sure of this certain 'accept'.*/
  1265. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
  1266. ADDR_POLICY_ACCEPTED;
  1267. } else {
  1268. return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
  1269. ADDR_POLICY_REJECTED;
  1270. }
  1271. } else {
  1272. /* Might match. */
  1273. if (tmpe->policy_type == ADDR_POLICY_REJECT)
  1274. maybe_reject = 1;
  1275. else
  1276. maybe_accept = 1;
  1277. }
  1278. }
  1279. } SMARTLIST_FOREACH_END(tmpe);
  1280. /* accept all by default. */
  1281. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  1282. }
  1283. /** Decide whether a given addr:port is definitely accepted,
  1284. * definitely rejected, probably accepted, or probably rejected by a
  1285. * given policy. If <b>addr</b> is 0, we don't know the IP of the
  1286. * target address. If <b>port</b> is 0, we don't know the port of the
  1287. * target address. (At least one of <b>addr</b> and <b>port</b> must be
  1288. * provided. If you want to know whether a policy would definitely reject
  1289. * an unknown address:port, use policy_is_reject_star().)
  1290. *
  1291. * We could do better by assuming that some ranges never match typical
  1292. * addresses (127.0.0.1, and so on). But we'll try this for now.
  1293. */
  1294. MOCK_IMPL(addr_policy_result_t,
  1295. compare_tor_addr_to_addr_policy,(const tor_addr_t *addr, uint16_t port,
  1296. const smartlist_t *policy))
  1297. {
  1298. if (!policy) {
  1299. /* no policy? accept all. */
  1300. return ADDR_POLICY_ACCEPTED;
  1301. } else if (addr == NULL || tor_addr_is_null(addr)) {
  1302. if (port == 0) {
  1303. log_info(LD_BUG, "Rejecting null address with 0 port (family %d)",
  1304. addr ? tor_addr_family(addr) : -1);
  1305. return ADDR_POLICY_REJECTED;
  1306. }
  1307. return compare_unknown_tor_addr_to_addr_policy(port, policy);
  1308. } else if (port == 0) {
  1309. return compare_known_tor_addr_to_addr_policy_noport(addr, policy);
  1310. } else {
  1311. return compare_known_tor_addr_to_addr_policy(addr, port, policy);
  1312. }
  1313. }
  1314. /** Return true iff the address policy <b>a</b> covers every case that
  1315. * would be covered by <b>b</b>, so that a,b is redundant. */
  1316. static int
  1317. addr_policy_covers(addr_policy_t *a, addr_policy_t *b)
  1318. {
  1319. if (tor_addr_family(&a->addr) != tor_addr_family(&b->addr)) {
  1320. /* You can't cover a different family. */
  1321. return 0;
  1322. }
  1323. /* We can ignore accept/reject, since "accept *:80, reject *:80" reduces
  1324. * to "accept *:80". */
  1325. if (a->maskbits > b->maskbits) {
  1326. /* a has more fixed bits than b; it can't possibly cover b. */
  1327. return 0;
  1328. }
  1329. if (tor_addr_compare_masked(&a->addr, &b->addr, a->maskbits, CMP_EXACT)) {
  1330. /* There's a fixed bit in a that's set differently in b. */
  1331. return 0;
  1332. }
  1333. return (a->prt_min <= b->prt_min && a->prt_max >= b->prt_max);
  1334. }
  1335. /** Return true iff the address policies <b>a</b> and <b>b</b> intersect,
  1336. * that is, there exists an address/port that is covered by <b>a</b> that
  1337. * is also covered by <b>b</b>.
  1338. */
  1339. static int
  1340. addr_policy_intersects(addr_policy_t *a, addr_policy_t *b)
  1341. {
  1342. maskbits_t minbits;
  1343. /* All the bits we care about are those that are set in both
  1344. * netmasks. If they are equal in a and b's networkaddresses
  1345. * then the networks intersect. If there is a difference,
  1346. * then they do not. */
  1347. if (a->maskbits < b->maskbits)
  1348. minbits = a->maskbits;
  1349. else
  1350. minbits = b->maskbits;
  1351. if (tor_addr_compare_masked(&a->addr, &b->addr, minbits, CMP_EXACT))
  1352. return 0;
  1353. if (a->prt_max < b->prt_min || b->prt_max < a->prt_min)
  1354. return 0;
  1355. return 1;
  1356. }
  1357. /** Add the exit policy described by <b>more</b> to <b>policy</b>.
  1358. */
  1359. STATIC void
  1360. append_exit_policy_string(smartlist_t **policy, const char *more)
  1361. {
  1362. config_line_t tmp;
  1363. tmp.key = NULL;
  1364. tmp.value = (char*) more;
  1365. tmp.next = NULL;
  1366. if (parse_addr_policy(&tmp, policy, -1)<0) {
  1367. log_warn(LD_BUG, "Unable to parse internally generated policy %s",more);
  1368. }
  1369. }
  1370. /** Add "reject <b>addr</b>:*" to <b>dest</b>, creating the list as needed. */
  1371. void
  1372. addr_policy_append_reject_addr(smartlist_t **dest, const tor_addr_t *addr)
  1373. {
  1374. tor_assert(dest);
  1375. tor_assert(addr);
  1376. addr_policy_t p, *add;
  1377. memset(&p, 0, sizeof(p));
  1378. p.policy_type = ADDR_POLICY_REJECT;
  1379. p.maskbits = tor_addr_family(addr) == AF_INET6 ? 128 : 32;
  1380. tor_addr_copy(&p.addr, addr);
  1381. p.prt_min = 1;
  1382. p.prt_max = 65535;
  1383. add = addr_policy_get_canonical_entry(&p);
  1384. if (!*dest)
  1385. *dest = smartlist_new();
  1386. smartlist_add(*dest, add);
  1387. log_debug(LD_CONFIG, "Adding a reject ExitPolicy 'reject %s:*'",
  1388. fmt_addr(addr));
  1389. }
  1390. /* Is addr public for the purposes of rejection? */
  1391. static int
  1392. tor_addr_is_public_for_reject(const tor_addr_t *addr)
  1393. {
  1394. return (!tor_addr_is_null(addr) && !tor_addr_is_internal(addr, 0)
  1395. && !tor_addr_is_multicast(addr));
  1396. }
  1397. /* Add "reject <b>addr</b>:*" to <b>dest</b>, creating the list as needed.
  1398. * Filter the address, only adding an IPv4 reject rule if ipv4_rules
  1399. * is true, and similarly for ipv6_rules. Check each address returns true for
  1400. * tor_addr_is_public_for_reject before adding it.
  1401. */
  1402. static void
  1403. addr_policy_append_reject_addr_filter(smartlist_t **dest,
  1404. const tor_addr_t *addr,
  1405. int ipv4_rules,
  1406. int ipv6_rules)
  1407. {
  1408. tor_assert(dest);
  1409. tor_assert(addr);
  1410. /* Only reject IP addresses which are public */
  1411. if (tor_addr_is_public_for_reject(addr)) {
  1412. /* Reject IPv4 addresses and IPv6 addresses based on the filters */
  1413. int is_ipv4 = tor_addr_is_v4(addr);
  1414. if ((is_ipv4 && ipv4_rules) || (!is_ipv4 && ipv6_rules)) {
  1415. addr_policy_append_reject_addr(dest, addr);
  1416. }
  1417. }
  1418. }
  1419. /** Add "reject addr:*" to <b>dest</b>, for each addr in addrs, creating the
  1420. * list as needed. */
  1421. void
  1422. addr_policy_append_reject_addr_list(smartlist_t **dest,
  1423. const smartlist_t *addrs)
  1424. {
  1425. tor_assert(dest);
  1426. tor_assert(addrs);
  1427. SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, addr) {
  1428. addr_policy_append_reject_addr(dest, addr);
  1429. } SMARTLIST_FOREACH_END(addr);
  1430. }
  1431. /** Add "reject addr:*" to <b>dest</b>, for each addr in addrs, creating the
  1432. * list as needed. Filter using */
  1433. static void
  1434. addr_policy_append_reject_addr_list_filter(smartlist_t **dest,
  1435. const smartlist_t *addrs,
  1436. int ipv4_rules,
  1437. int ipv6_rules)
  1438. {
  1439. tor_assert(dest);
  1440. tor_assert(addrs);
  1441. SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, addr) {
  1442. addr_policy_append_reject_addr_filter(dest, addr, ipv4_rules, ipv6_rules);
  1443. } SMARTLIST_FOREACH_END(addr);
  1444. }
  1445. /** Detect and excise "dead code" from the policy *<b>dest</b>. */
  1446. static void
  1447. exit_policy_remove_redundancies(smartlist_t *dest)
  1448. {
  1449. addr_policy_t *ap, *tmp;
  1450. int i, j;
  1451. /* Step one: kill every ipv4 thing after *4:*, every IPv6 thing after *6:*
  1452. */
  1453. {
  1454. int kill_v4=0, kill_v6=0;
  1455. for (i = 0; i < smartlist_len(dest); ++i) {
  1456. sa_family_t family;
  1457. ap = smartlist_get(dest, i);
  1458. family = tor_addr_family(&ap->addr);
  1459. if ((family == AF_INET && kill_v4) ||
  1460. (family == AF_INET6 && kill_v6)) {
  1461. smartlist_del_keeporder(dest, i--);
  1462. addr_policy_free(ap);
  1463. continue;
  1464. }
  1465. if (ap->maskbits == 0 && ap->prt_min <= 1 && ap->prt_max >= 65535) {
  1466. /* This is a catch-all line -- later lines are unreachable. */
  1467. if (family == AF_INET) {
  1468. kill_v4 = 1;
  1469. } else if (family == AF_INET6) {
  1470. kill_v6 = 1;
  1471. }
  1472. }
  1473. }
  1474. }
  1475. /* Step two: for every entry, see if there's a redundant entry
  1476. * later on, and remove it. */
  1477. for (i = 0; i < smartlist_len(dest)-1; ++i) {
  1478. ap = smartlist_get(dest, i);
  1479. for (j = i+1; j < smartlist_len(dest); ++j) {
  1480. tmp = smartlist_get(dest, j);
  1481. tor_assert(j > i);
  1482. if (addr_policy_covers(ap, tmp)) {
  1483. char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
  1484. policy_write_item(p1, sizeof(p1), tmp, 0);
  1485. policy_write_item(p2, sizeof(p2), ap, 0);
  1486. log_debug(LD_CONFIG, "Removing exit policy %s (%d). It is made "
  1487. "redundant by %s (%d).", p1, j, p2, i);
  1488. smartlist_del_keeporder(dest, j--);
  1489. addr_policy_free(tmp);
  1490. }
  1491. }
  1492. }
  1493. /* Step three: for every entry A, see if there's an entry B making this one
  1494. * redundant later on. This is the case if A and B are of the same type
  1495. * (accept/reject), A is a subset of B, and there is no other entry of
  1496. * different type in between those two that intersects with A.
  1497. *
  1498. * Anybody want to double-check the logic here? XXX
  1499. */
  1500. for (i = 0; i < smartlist_len(dest)-1; ++i) {
  1501. ap = smartlist_get(dest, i);
  1502. for (j = i+1; j < smartlist_len(dest); ++j) {
  1503. // tor_assert(j > i); // j starts out at i+1; j only increases; i only
  1504. // // decreases.
  1505. tmp = smartlist_get(dest, j);
  1506. if (ap->policy_type != tmp->policy_type) {
  1507. if (addr_policy_intersects(ap, tmp))
  1508. break;
  1509. } else { /* policy_types are equal. */
  1510. if (addr_policy_covers(tmp, ap)) {
  1511. char p1[POLICY_BUF_LEN], p2[POLICY_BUF_LEN];
  1512. policy_write_item(p1, sizeof(p1), ap, 0);
  1513. policy_write_item(p2, sizeof(p2), tmp, 0);
  1514. log_debug(LD_CONFIG, "Removing exit policy %s. It is already "
  1515. "covered by %s.", p1, p2);
  1516. smartlist_del_keeporder(dest, i--);
  1517. addr_policy_free(ap);
  1518. break;
  1519. }
  1520. }
  1521. }
  1522. }
  1523. }
  1524. /** Reject private helper for policies_parse_exit_policy_internal: rejects
  1525. * publicly routable addresses on this exit relay.
  1526. *
  1527. * Add reject entries to the linked list *dest:
  1528. * - if configured_addresses is non-NULL, add entries that reject each
  1529. * tor_addr_t* in the list as a destination.
  1530. * - if reject_interface_addresses is true, add entries that reject each
  1531. * public IPv4 and IPv6 address of each interface on this machine.
  1532. * - if reject_configured_port_addresses is true, add entries that reject
  1533. * each IPv4 and IPv6 address configured for a port.
  1534. *
  1535. * IPv6 entries are only added if ipv6_exit is true. (All IPv6 addresses are
  1536. * already blocked by policies_parse_exit_policy_internal if ipv6_exit is
  1537. * false.)
  1538. *
  1539. * The list *dest is created as needed.
  1540. */
  1541. void
  1542. policies_parse_exit_policy_reject_private(
  1543. smartlist_t **dest,
  1544. int ipv6_exit,
  1545. const smartlist_t *configured_addresses,
  1546. int reject_interface_addresses,
  1547. int reject_configured_port_addresses)
  1548. {
  1549. tor_assert(dest);
  1550. /* Reject configured addresses, if they are from public netblocks. */
  1551. if (configured_addresses) {
  1552. addr_policy_append_reject_addr_list_filter(dest, configured_addresses,
  1553. 1, ipv6_exit);
  1554. }
  1555. /* Reject configured port addresses, if they are from public netblocks. */
  1556. if (reject_configured_port_addresses) {
  1557. const smartlist_t *port_addrs = get_configured_ports();
  1558. SMARTLIST_FOREACH_BEGIN(port_addrs, port_cfg_t *, port) {
  1559. /* Only reject port IP addresses, not port unix sockets */
  1560. if (!port->is_unix_addr) {
  1561. addr_policy_append_reject_addr_filter(dest, &port->addr, 1, ipv6_exit);
  1562. }
  1563. } SMARTLIST_FOREACH_END(port);
  1564. }
  1565. /* Reject local addresses from public netblocks on any interface. */
  1566. if (reject_interface_addresses) {
  1567. smartlist_t *public_addresses = NULL;
  1568. /* Reject public IPv4 addresses on any interface */
  1569. public_addresses = get_interface_address6_list(LOG_INFO, AF_INET, 0);
  1570. addr_policy_append_reject_addr_list_filter(dest, public_addresses, 1, 0);
  1571. free_interface_address6_list(public_addresses);
  1572. /* Don't look for IPv6 addresses if we're configured as IPv4-only */
  1573. if (ipv6_exit) {
  1574. /* Reject public IPv6 addresses on any interface */
  1575. public_addresses = get_interface_address6_list(LOG_INFO, AF_INET6, 0);
  1576. addr_policy_append_reject_addr_list_filter(dest, public_addresses, 0, 1);
  1577. free_interface_address6_list(public_addresses);
  1578. }
  1579. }
  1580. /* If addresses were added multiple times, remove all but one of them. */
  1581. if (*dest) {
  1582. exit_policy_remove_redundancies(*dest);
  1583. }
  1584. }
  1585. /**
  1586. * Iterate through <b>policy</b> looking for redundant entries. Log a
  1587. * warning message with the first redundant entry, if any is found.
  1588. */
  1589. static void
  1590. policies_log_first_redundant_entry(const smartlist_t *policy)
  1591. {
  1592. int found_final_effective_entry = 0;
  1593. int first_redundant_entry = 0;
  1594. tor_assert(policy);
  1595. SMARTLIST_FOREACH_BEGIN(policy, const addr_policy_t *, p) {
  1596. sa_family_t family;
  1597. int found_ipv4_wildcard = 0, found_ipv6_wildcard = 0;
  1598. const int i = p_sl_idx;
  1599. /* Look for accept/reject *[4|6|]:* entires */
  1600. if (p->prt_min <= 1 && p->prt_max == 65535 && p->maskbits == 0) {
  1601. family = tor_addr_family(&p->addr);
  1602. /* accept/reject *:* may have already been expanded into
  1603. * accept/reject *4:*,accept/reject *6:*
  1604. * But handle both forms.
  1605. */
  1606. if (family == AF_INET || family == AF_UNSPEC) {
  1607. found_ipv4_wildcard = 1;
  1608. }
  1609. if (family == AF_INET6 || family == AF_UNSPEC) {
  1610. found_ipv6_wildcard = 1;
  1611. }
  1612. }
  1613. /* We also find accept *4:*,reject *6:* ; and
  1614. * accept *4:*,<other policies>,accept *6:* ; and similar.
  1615. * That's ok, because they make any subsequent entries redundant. */
  1616. if (found_ipv4_wildcard && found_ipv6_wildcard) {
  1617. found_final_effective_entry = 1;
  1618. /* if we're not on the final entry in the list */
  1619. if (i < smartlist_len(policy) - 1) {
  1620. first_redundant_entry = i + 1;
  1621. }
  1622. break;
  1623. }
  1624. } SMARTLIST_FOREACH_END(p);
  1625. /* Work out if there are redundant trailing entries in the policy list */
  1626. if (found_final_effective_entry && first_redundant_entry > 0) {
  1627. const addr_policy_t *p;
  1628. /* Longest possible policy is
  1629. * "accept6 ffff:ffff:..255/128:10000-65535",
  1630. * which contains a max-length IPv6 address, plus 24 characters. */
  1631. char line[TOR_ADDR_BUF_LEN + 32];
  1632. tor_assert(first_redundant_entry < smartlist_len(policy));
  1633. p = smartlist_get(policy, first_redundant_entry);
  1634. /* since we've already parsed the policy into an addr_policy_t struct,
  1635. * we might not log exactly what the user typed in */
  1636. policy_write_item(line, TOR_ADDR_BUF_LEN + 32, p, 0);
  1637. log_warn(LD_DIR, "Exit policy '%s' and all following policies are "
  1638. "redundant, as it follows accept/reject *:* rules for both "
  1639. "IPv4 and IPv6. They will be removed from the exit policy. (Use "
  1640. "accept/reject *:* as the last entry in any exit policy.)",
  1641. line);
  1642. }
  1643. }
  1644. #define DEFAULT_EXIT_POLICY \
  1645. "reject *:25,reject *:119,reject *:135-139,reject *:445," \
  1646. "reject *:563,reject *:1214,reject *:4661-4666," \
  1647. "reject *:6346-6429,reject *:6699,reject *:6881-6999,accept *:*"
  1648. /** Parse the exit policy <b>cfg</b> into the linked list *<b>dest</b>.
  1649. *
  1650. * If <b>ipv6_exit</b> is false, prepend "reject *6:*" to the policy.
  1651. *
  1652. * If <b>rejectprivate</b> is true:
  1653. * - prepend "reject private:*" to the policy.
  1654. * - prepend entries that reject publicly routable addresses on this exit
  1655. * relay by calling policies_parse_exit_policy_reject_private
  1656. *
  1657. * If cfg doesn't end in an absolute accept or reject and if
  1658. * <b>add_default_policy</b> is true, add the default exit
  1659. * policy afterwards.
  1660. *
  1661. * Return -1 if we can't parse cfg, else return 0.
  1662. *
  1663. * This function is used to parse the exit policy from our torrc. For
  1664. * the functions used to parse the exit policy from a router descriptor,
  1665. * see router_add_exit_policy.
  1666. */
  1667. static int
  1668. policies_parse_exit_policy_internal(config_line_t *cfg,
  1669. smartlist_t **dest,
  1670. int ipv6_exit,
  1671. int rejectprivate,
  1672. const smartlist_t *configured_addresses,
  1673. int reject_interface_addresses,
  1674. int reject_configured_port_addresses,
  1675. int add_default_policy)
  1676. {
  1677. if (!ipv6_exit) {
  1678. append_exit_policy_string(dest, "reject *6:*");
  1679. }
  1680. if (rejectprivate) {
  1681. /* Reject IPv4 and IPv6 reserved private netblocks */
  1682. append_exit_policy_string(dest, "reject private:*");
  1683. /* Reject IPv4 and IPv6 publicly routable addresses on this exit relay */
  1684. policies_parse_exit_policy_reject_private(
  1685. dest, ipv6_exit,
  1686. configured_addresses,
  1687. reject_interface_addresses,
  1688. reject_configured_port_addresses);
  1689. }
  1690. if (parse_addr_policy(cfg, dest, -1))
  1691. return -1;
  1692. /* Before we add the default policy and final rejects, check to see if
  1693. * there are any lines after accept *:* or reject *:*. These lines have no
  1694. * effect, and are most likely an error. */
  1695. policies_log_first_redundant_entry(*dest);
  1696. if (add_default_policy) {
  1697. append_exit_policy_string(dest, DEFAULT_EXIT_POLICY);
  1698. } else {
  1699. append_exit_policy_string(dest, "reject *4:*");
  1700. append_exit_policy_string(dest, "reject *6:*");
  1701. }
  1702. exit_policy_remove_redundancies(*dest);
  1703. return 0;
  1704. }
  1705. /** Parse exit policy in <b>cfg</b> into <b>dest</b> smartlist.
  1706. *
  1707. * Prepend an entry that rejects all IPv6 destinations unless
  1708. * <b>EXIT_POLICY_IPV6_ENABLED</b> bit is set in <b>options</b> bitmask.
  1709. *
  1710. * If <b>EXIT_POLICY_REJECT_PRIVATE</b> bit is set in <b>options</b>:
  1711. * - prepend an entry that rejects all destinations in all netblocks
  1712. * reserved for private use.
  1713. * - prepend entries that reject publicly routable addresses on this exit
  1714. * relay by calling policies_parse_exit_policy_internal
  1715. *
  1716. * If <b>EXIT_POLICY_ADD_DEFAULT</b> bit is set in <b>options</b>, append
  1717. * default exit policy entries to <b>result</b> smartlist.
  1718. */
  1719. int
  1720. policies_parse_exit_policy(config_line_t *cfg, smartlist_t **dest,
  1721. exit_policy_parser_cfg_t options,
  1722. const smartlist_t *configured_addresses)
  1723. {
  1724. int ipv6_enabled = (options & EXIT_POLICY_IPV6_ENABLED) ? 1 : 0;
  1725. int reject_private = (options & EXIT_POLICY_REJECT_PRIVATE) ? 1 : 0;
  1726. int add_default = (options & EXIT_POLICY_ADD_DEFAULT) ? 1 : 0;
  1727. return policies_parse_exit_policy_internal(cfg,dest,ipv6_enabled,
  1728. reject_private,
  1729. configured_addresses,
  1730. reject_private,
  1731. reject_private,
  1732. add_default);
  1733. }
  1734. /** Helper function that adds a copy of addr to a smartlist as long as it is
  1735. * non-NULL and not tor_addr_is_null().
  1736. *
  1737. * The caller is responsible for freeing all the tor_addr_t* in the smartlist.
  1738. */
  1739. static void
  1740. policies_copy_addr_to_smartlist(smartlist_t *addr_list, const tor_addr_t *addr)
  1741. {
  1742. if (addr && !tor_addr_is_null(addr)) {
  1743. tor_addr_t *addr_copy = tor_malloc(sizeof(tor_addr_t));
  1744. tor_addr_copy(addr_copy, addr);
  1745. smartlist_add(addr_list, addr_copy);
  1746. }
  1747. }
  1748. /** Helper function that adds ipv4h_addr to a smartlist as a tor_addr_t *,
  1749. * as long as it is not tor_addr_is_null(), by converting it to a tor_addr_t
  1750. * and passing it to policies_add_addr_to_smartlist.
  1751. *
  1752. * The caller is responsible for freeing all the tor_addr_t* in the smartlist.
  1753. */
  1754. static void
  1755. policies_copy_ipv4h_to_smartlist(smartlist_t *addr_list, uint32_t ipv4h_addr)
  1756. {
  1757. if (ipv4h_addr) {
  1758. tor_addr_t ipv4_tor_addr;
  1759. tor_addr_from_ipv4h(&ipv4_tor_addr, ipv4h_addr);
  1760. policies_copy_addr_to_smartlist(addr_list, &ipv4_tor_addr);
  1761. }
  1762. }
  1763. /** Helper function that adds copies of
  1764. * or_options->OutboundBindAddressIPv[4|6]_ to a smartlist as tor_addr_t *, as
  1765. * long as or_options is non-NULL, and the addresses are not
  1766. * tor_addr_is_null(), by passing them to policies_add_addr_to_smartlist.
  1767. *
  1768. * The caller is responsible for freeing all the tor_addr_t* in the smartlist.
  1769. */
  1770. static void
  1771. policies_copy_outbound_addresses_to_smartlist(smartlist_t *addr_list,
  1772. const or_options_t *or_options)
  1773. {
  1774. if (or_options) {
  1775. policies_copy_addr_to_smartlist(addr_list,
  1776. &or_options->OutboundBindAddressIPv4_);
  1777. policies_copy_addr_to_smartlist(addr_list,
  1778. &or_options->OutboundBindAddressIPv6_);
  1779. }
  1780. }
  1781. /** Parse <b>ExitPolicy</b> member of <b>or_options</b> into <b>result</b>
  1782. * smartlist.
  1783. * If <b>or_options->IPv6Exit</b> is false, prepend an entry that
  1784. * rejects all IPv6 destinations.
  1785. *
  1786. * If <b>or_options->ExitPolicyRejectPrivate</b> is true:
  1787. * - prepend an entry that rejects all destinations in all netblocks reserved
  1788. * for private use.
  1789. * - if local_address is non-zero, treat it as a host-order IPv4 address, and
  1790. * add it to the list of configured addresses.
  1791. * - if ipv6_local_address is non-NULL, and not the null tor_addr_t, add it
  1792. * to the list of configured addresses.
  1793. * - if or_options->OutboundBindAddressIPv4_ is not the null tor_addr_t, add
  1794. * it to the list of configured addresses.
  1795. * - if or_options->OutboundBindAddressIPv6_ is not the null tor_addr_t, add
  1796. * it to the list of configured addresses.
  1797. *
  1798. * If <b>or_options->BridgeRelay</b> is false, append entries of default
  1799. * Tor exit policy into <b>result</b> smartlist.
  1800. *
  1801. * If or_options->ExitRelay is false, then make our exit policy into
  1802. * "reject *:*" regardless.
  1803. */
  1804. int
  1805. policies_parse_exit_policy_from_options(const or_options_t *or_options,
  1806. uint32_t local_address,
  1807. const tor_addr_t *ipv6_local_address,
  1808. smartlist_t **result)
  1809. {
  1810. exit_policy_parser_cfg_t parser_cfg = 0;
  1811. smartlist_t *configured_addresses = NULL;
  1812. int rv = 0;
  1813. /* Short-circuit for non-exit relays */
  1814. if (or_options->ExitRelay == 0) {
  1815. append_exit_policy_string(result, "reject *4:*");
  1816. append_exit_policy_string(result, "reject *6:*");
  1817. return 0;
  1818. }
  1819. configured_addresses = smartlist_new();
  1820. /* Configure the parser */
  1821. if (or_options->IPv6Exit) {
  1822. parser_cfg |= EXIT_POLICY_IPV6_ENABLED;
  1823. }
  1824. if (or_options->ExitPolicyRejectPrivate) {
  1825. parser_cfg |= EXIT_POLICY_REJECT_PRIVATE;
  1826. }
  1827. if (!or_options->BridgeRelay) {
  1828. parser_cfg |= EXIT_POLICY_ADD_DEFAULT;
  1829. }
  1830. /* Copy the configured addresses into the tor_addr_t* list */
  1831. policies_copy_ipv4h_to_smartlist(configured_addresses, local_address);
  1832. policies_copy_addr_to_smartlist(configured_addresses, ipv6_local_address);
  1833. policies_copy_outbound_addresses_to_smartlist(configured_addresses,
  1834. or_options);
  1835. rv = policies_parse_exit_policy(or_options->ExitPolicy, result, parser_cfg,
  1836. configured_addresses);
  1837. SMARTLIST_FOREACH(configured_addresses, tor_addr_t *, a, tor_free(a));
  1838. smartlist_free(configured_addresses);
  1839. return rv;
  1840. }
  1841. /** Add "reject *:*" to the end of the policy in *<b>dest</b>, allocating
  1842. * *<b>dest</b> as needed. */
  1843. void
  1844. policies_exit_policy_append_reject_star(smartlist_t **dest)
  1845. {
  1846. append_exit_policy_string(dest, "reject *4:*");
  1847. append_exit_policy_string(dest, "reject *6:*");
  1848. }
  1849. /** Replace the exit policy of <b>node</b> with reject *:* */
  1850. void
  1851. policies_set_node_exitpolicy_to_reject_all(node_t *node)
  1852. {
  1853. node->rejects_all = 1;
  1854. }
  1855. /** Return 1 if there is at least one /8 subnet in <b>policy</b> that
  1856. * allows exiting to <b>port</b>. Otherwise, return 0. */
  1857. static int
  1858. exit_policy_is_general_exit_helper(smartlist_t *policy, int port)
  1859. {
  1860. uint32_t mask, ip, i;
  1861. /* Is this /8 rejected (1), or undecided (0)? */
  1862. char subnet_status[256];
  1863. memset(subnet_status, 0, sizeof(subnet_status));
  1864. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, p) {
  1865. if (tor_addr_family(&p->addr) != AF_INET)
  1866. continue; /* IPv4 only for now */
  1867. if (p->prt_min > port || p->prt_max < port)
  1868. continue; /* Doesn't cover our port. */
  1869. mask = 0;
  1870. tor_assert(p->maskbits <= 32);
  1871. if (p->maskbits)
  1872. mask = UINT32_MAX<<(32-p->maskbits);
  1873. ip = tor_addr_to_ipv4h(&p->addr);
  1874. /* Calculate the first and last subnet that this exit policy touches
  1875. * and set it as loop boundaries. */
  1876. for (i = ((mask & ip)>>24); i <= (~((mask & ip) ^ mask)>>24); ++i) {
  1877. tor_addr_t addr;
  1878. if (subnet_status[i] != 0)
  1879. continue; /* We already reject some part of this /8 */
  1880. tor_addr_from_ipv4h(&addr, i<<24);
  1881. if (tor_addr_is_internal(&addr, 0))
  1882. continue; /* Local or non-routable addresses */
  1883. if (p->policy_type == ADDR_POLICY_ACCEPT) {
  1884. if (p->maskbits > 8)
  1885. continue; /* Narrower than a /8. */
  1886. /* We found an allowed subnet of at least size /8. Done
  1887. * for this port! */
  1888. return 1;
  1889. } else if (p->policy_type == ADDR_POLICY_REJECT) {
  1890. subnet_status[i] = 1;
  1891. }
  1892. }
  1893. } SMARTLIST_FOREACH_END(p);
  1894. return 0;
  1895. }
  1896. /** Return true iff <b>ri</b> is "useful as an exit node", meaning
  1897. * it allows exit to at least one /8 address space for at least
  1898. * two of ports 80, 443, and 6667. */
  1899. int
  1900. exit_policy_is_general_exit(smartlist_t *policy)
  1901. {
  1902. static const int ports[] = { 80, 443, 6667 };
  1903. int n_allowed = 0;
  1904. int i;
  1905. if (!policy) /*XXXX disallow NULL policies? */
  1906. return 0;
  1907. for (i = 0; i < 3; ++i) {
  1908. n_allowed += exit_policy_is_general_exit_helper(policy, ports[i]);
  1909. }
  1910. return n_allowed >= 2;
  1911. }
  1912. /** Return false if <b>policy</b> might permit access to some addr:port;
  1913. * otherwise if we are certain it rejects everything, return true. */
  1914. int
  1915. policy_is_reject_star(const smartlist_t *policy, sa_family_t family)
  1916. {
  1917. if (!policy) /*XXXX disallow NULL policies? */
  1918. return 1;
  1919. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, p) {
  1920. if (p->policy_type == ADDR_POLICY_ACCEPT &&
  1921. (tor_addr_family(&p->addr) == family ||
  1922. tor_addr_family(&p->addr) == AF_UNSPEC)) {
  1923. return 0;
  1924. } else if (p->policy_type == ADDR_POLICY_REJECT &&
  1925. p->prt_min <= 1 && p->prt_max == 65535 &&
  1926. p->maskbits == 0 &&
  1927. (tor_addr_family(&p->addr) == family ||
  1928. tor_addr_family(&p->addr) == AF_UNSPEC)) {
  1929. return 1;
  1930. }
  1931. } SMARTLIST_FOREACH_END(p);
  1932. return 1;
  1933. }
  1934. /** Write a single address policy to the buf_len byte buffer at buf. Return
  1935. * the number of characters written, or -1 on failure. */
  1936. int
  1937. policy_write_item(char *buf, size_t buflen, const addr_policy_t *policy,
  1938. int format_for_desc)
  1939. {
  1940. size_t written = 0;
  1941. char addrbuf[TOR_ADDR_BUF_LEN];
  1942. const char *addrpart;
  1943. int result;
  1944. const int is_accept = policy->policy_type == ADDR_POLICY_ACCEPT;
  1945. const sa_family_t family = tor_addr_family(&policy->addr);
  1946. const int is_ip6 = (family == AF_INET6);
  1947. tor_addr_to_str(addrbuf, &policy->addr, sizeof(addrbuf), 1);
  1948. /* write accept/reject 1.2.3.4 */
  1949. if (policy->is_private) {
  1950. addrpart = "private";
  1951. } else if (policy->maskbits == 0) {
  1952. if (format_for_desc)
  1953. addrpart = "*";
  1954. else if (family == AF_INET6)
  1955. addrpart = "*6";
  1956. else if (family == AF_INET)
  1957. addrpart = "*4";
  1958. else
  1959. addrpart = "*";
  1960. } else {
  1961. addrpart = addrbuf;
  1962. }
  1963. result = tor_snprintf(buf, buflen, "%s%s %s",
  1964. is_accept ? "accept" : "reject",
  1965. (is_ip6&&format_for_desc)?"6":"",
  1966. addrpart);
  1967. if (result < 0)
  1968. return -1;
  1969. written += strlen(buf);
  1970. /* If the maskbits is 32 (IPv4) or 128 (IPv6) we don't need to give it. If
  1971. the mask is 0, we already wrote "*". */
  1972. if (policy->maskbits < (is_ip6?128:32) && policy->maskbits > 0) {
  1973. if (tor_snprintf(buf+written, buflen-written, "/%d", policy->maskbits)<0)
  1974. return -1;
  1975. written += strlen(buf+written);
  1976. }
  1977. if (policy->prt_min <= 1 && policy->prt_max == 65535) {
  1978. /* There is no port set; write ":*" */
  1979. if (written+4 > buflen)
  1980. return -1;
  1981. strlcat(buf+written, ":*", buflen-written);
  1982. written += 2;
  1983. } else if (policy->prt_min == policy->prt_max) {
  1984. /* There is only one port; write ":80". */
  1985. result = tor_snprintf(buf+written, buflen-written, ":%d", policy->prt_min);
  1986. if (result<0)
  1987. return -1;
  1988. written += result;
  1989. } else {
  1990. /* There is a range of ports; write ":79-80". */
  1991. result = tor_snprintf(buf+written, buflen-written, ":%d-%d",
  1992. policy->prt_min, policy->prt_max);
  1993. if (result<0)
  1994. return -1;
  1995. written += result;
  1996. }
  1997. if (written < buflen)
  1998. buf[written] = '\0';
  1999. else
  2000. return -1;
  2001. return (int)written;
  2002. }
  2003. /** Create a new exit policy summary, initially only with a single
  2004. * port 1-64k item */
  2005. /* XXXX This entire thing will do most stuff in O(N^2), or worse. Use an
  2006. * RB-tree if that turns out to matter. */
  2007. static smartlist_t *
  2008. policy_summary_create(void)
  2009. {
  2010. smartlist_t *summary;
  2011. policy_summary_item_t* item;
  2012. item = tor_malloc_zero(sizeof(policy_summary_item_t));
  2013. item->prt_min = 1;
  2014. item->prt_max = 65535;
  2015. item->reject_count = 0;
  2016. item->accepted = 0;
  2017. summary = smartlist_new();
  2018. smartlist_add(summary, item);
  2019. return summary;
  2020. }
  2021. /** Split the summary item in <b>item</b> at the port <b>new_starts</b>.
  2022. * The current item is changed to end at new-starts - 1, the new item
  2023. * copies reject_count and accepted from the old item,
  2024. * starts at new_starts and ends at the port where the original item
  2025. * previously ended.
  2026. */
  2027. static policy_summary_item_t*
  2028. policy_summary_item_split(policy_summary_item_t* old, uint16_t new_starts)
  2029. {
  2030. policy_summary_item_t* new;
  2031. new = tor_malloc_zero(sizeof(policy_summary_item_t));
  2032. new->prt_min = new_starts;
  2033. new->prt_max = old->prt_max;
  2034. new->reject_count = old->reject_count;
  2035. new->accepted = old->accepted;
  2036. old->prt_max = new_starts-1;
  2037. tor_assert(old->prt_min <= old->prt_max);
  2038. tor_assert(new->prt_min <= new->prt_max);
  2039. return new;
  2040. }
  2041. /* XXXX Nick says I'm going to hell for this. If he feels charitably towards
  2042. * my immortal soul, he can clean it up himself. */
  2043. #define AT(x) ((policy_summary_item_t*)smartlist_get(summary, x))
  2044. #define REJECT_CUTOFF_COUNT (1<<25)
  2045. /** Split an exit policy summary so that prt_min and prt_max
  2046. * fall at exactly the start and end of an item respectively.
  2047. */
  2048. static int
  2049. policy_summary_split(smartlist_t *summary,
  2050. uint16_t prt_min, uint16_t prt_max)
  2051. {
  2052. int start_at_index;
  2053. int i = 0;
  2054. while (AT(i)->prt_max < prt_min)
  2055. i++;
  2056. if (AT(i)->prt_min != prt_min) {
  2057. policy_summary_item_t* new_item;
  2058. new_item = policy_summary_item_split(AT(i), prt_min);
  2059. smartlist_insert(summary, i+1, new_item);
  2060. i++;
  2061. }
  2062. start_at_index = i;
  2063. while (AT(i)->prt_max < prt_max)
  2064. i++;
  2065. if (AT(i)->prt_max != prt_max) {
  2066. policy_summary_item_t* new_item;
  2067. new_item = policy_summary_item_split(AT(i), prt_max+1);
  2068. smartlist_insert(summary, i+1, new_item);
  2069. }
  2070. return start_at_index;
  2071. }
  2072. /** Mark port ranges as accepted if they are below the reject_count */
  2073. static void
  2074. policy_summary_accept(smartlist_t *summary,
  2075. uint16_t prt_min, uint16_t prt_max)
  2076. {
  2077. int i = policy_summary_split(summary, prt_min, prt_max);
  2078. while (i < smartlist_len(summary) &&
  2079. AT(i)->prt_max <= prt_max) {
  2080. if (!AT(i)->accepted &&
  2081. AT(i)->reject_count <= REJECT_CUTOFF_COUNT)
  2082. AT(i)->accepted = 1;
  2083. i++;
  2084. }
  2085. tor_assert(i < smartlist_len(summary) || prt_max==65535);
  2086. }
  2087. /** Count the number of addresses in a network with prefixlen maskbits
  2088. * against the given portrange. */
  2089. static void
  2090. policy_summary_reject(smartlist_t *summary,
  2091. maskbits_t maskbits,
  2092. uint16_t prt_min, uint16_t prt_max)
  2093. {
  2094. int i = policy_summary_split(summary, prt_min, prt_max);
  2095. /* XXX: ipv4 specific */
  2096. uint64_t count = (U64_LITERAL(1) << (32-maskbits));
  2097. while (i < smartlist_len(summary) &&
  2098. AT(i)->prt_max <= prt_max) {
  2099. AT(i)->reject_count += count;
  2100. i++;
  2101. }
  2102. tor_assert(i < smartlist_len(summary) || prt_max==65535);
  2103. }
  2104. /** Add a single exit policy item to our summary:
  2105. * If it is an accept ignore it unless it is for all IP addresses
  2106. * ("*"), i.e. it's prefixlen/maskbits is 0, else call
  2107. * policy_summary_accept().
  2108. * If it's a reject ignore it if it is about one of the private
  2109. * networks, else call policy_summary_reject().
  2110. */
  2111. static void
  2112. policy_summary_add_item(smartlist_t *summary, addr_policy_t *p)
  2113. {
  2114. if (p->policy_type == ADDR_POLICY_ACCEPT) {
  2115. if (p->maskbits == 0) {
  2116. policy_summary_accept(summary, p->prt_min, p->prt_max);
  2117. }
  2118. } else if (p->policy_type == ADDR_POLICY_REJECT) {
  2119. int is_private = 0;
  2120. int i;
  2121. for (i = 0; private_nets[i]; ++i) {
  2122. tor_addr_t addr;
  2123. maskbits_t maskbits;
  2124. if (tor_addr_parse_mask_ports(private_nets[i], 0, &addr,
  2125. &maskbits, NULL, NULL)<0) {
  2126. tor_assert(0);
  2127. }
  2128. if (tor_addr_compare(&p->addr, &addr, CMP_EXACT) == 0 &&
  2129. p->maskbits == maskbits) {
  2130. is_private = 1;
  2131. break;
  2132. }
  2133. }
  2134. if (!is_private) {
  2135. policy_summary_reject(summary, p->maskbits, p->prt_min, p->prt_max);
  2136. }
  2137. } else
  2138. tor_assert(0);
  2139. }
  2140. /** Create a string representing a summary for an exit policy.
  2141. * The summary will either be an "accept" plus a comma-separated list of port
  2142. * ranges or a "reject" plus port-ranges, depending on which is shorter.
  2143. *
  2144. * If no exits are allowed at all then "reject 1-65535" is returned. If no
  2145. * ports are blocked instead of "reject " we return "accept 1-65535". (These
  2146. * are an exception to the shorter-representation-wins rule).
  2147. */
  2148. char *
  2149. policy_summarize(smartlist_t *policy, sa_family_t family)
  2150. {
  2151. smartlist_t *summary = policy_summary_create();
  2152. smartlist_t *accepts, *rejects;
  2153. int i, last, start_prt;
  2154. size_t accepts_len, rejects_len;
  2155. char *accepts_str = NULL, *rejects_str = NULL, *shorter_str, *result;
  2156. const char *prefix;
  2157. tor_assert(policy);
  2158. /* Create the summary list */
  2159. SMARTLIST_FOREACH_BEGIN(policy, addr_policy_t *, p) {
  2160. sa_family_t f = tor_addr_family(&p->addr);
  2161. if (f != AF_INET && f != AF_INET6) {
  2162. log_warn(LD_BUG, "Weird family when summarizing address policy");
  2163. }
  2164. if (f != family)
  2165. continue;
  2166. /* XXXX-ipv6 More family work is needed */
  2167. policy_summary_add_item(summary, p);
  2168. } SMARTLIST_FOREACH_END(p);
  2169. /* Now create two lists of strings, one for accepted and one
  2170. * for rejected ports. We take care to merge ranges so that
  2171. * we avoid getting stuff like "1-4,5-9,10", instead we want
  2172. * "1-10"
  2173. */
  2174. i = 0;
  2175. start_prt = 1;
  2176. accepts = smartlist_new();
  2177. rejects = smartlist_new();
  2178. while (1) {
  2179. last = i == smartlist_len(summary)-1;
  2180. if (last ||
  2181. AT(i)->accepted != AT(i+1)->accepted) {
  2182. char buf[POLICY_BUF_LEN];
  2183. if (start_prt == AT(i)->prt_max)
  2184. tor_snprintf(buf, sizeof(buf), "%d", start_prt);
  2185. else
  2186. tor_snprintf(buf, sizeof(buf), "%d-%d", start_prt, AT(i)->prt_max);
  2187. if (AT(i)->accepted)
  2188. smartlist_add(accepts, tor_strdup(buf));
  2189. else
  2190. smartlist_add(rejects, tor_strdup(buf));
  2191. if (last)
  2192. break;
  2193. start_prt = AT(i+1)->prt_min;
  2194. };
  2195. i++;
  2196. };
  2197. /* Figure out which of the two stringlists will be shorter and use
  2198. * that to build the result
  2199. */
  2200. if (smartlist_len(accepts) == 0) { /* no exits at all */
  2201. result = tor_strdup("reject 1-65535");
  2202. goto cleanup;
  2203. }
  2204. if (smartlist_len(rejects) == 0) { /* no rejects at all */
  2205. result = tor_strdup("accept 1-65535");
  2206. goto cleanup;
  2207. }
  2208. accepts_str = smartlist_join_strings(accepts, ",", 0, &accepts_len);
  2209. rejects_str = smartlist_join_strings(rejects, ",", 0, &rejects_len);
  2210. if (rejects_len > MAX_EXITPOLICY_SUMMARY_LEN-strlen("reject")-1 &&
  2211. accepts_len > MAX_EXITPOLICY_SUMMARY_LEN-strlen("accept")-1) {
  2212. char *c;
  2213. shorter_str = accepts_str;
  2214. prefix = "accept";
  2215. c = shorter_str + (MAX_EXITPOLICY_SUMMARY_LEN-strlen(prefix)-1);
  2216. while (*c != ',' && c >= shorter_str)
  2217. c--;
  2218. tor_assert(c >= shorter_str);
  2219. tor_assert(*c == ',');
  2220. *c = '\0';
  2221. } else if (rejects_len < accepts_len) {
  2222. shorter_str = rejects_str;
  2223. prefix = "reject";
  2224. } else {
  2225. shorter_str = accepts_str;
  2226. prefix = "accept";
  2227. }
  2228. tor_asprintf(&result, "%s %s", prefix, shorter_str);
  2229. cleanup:
  2230. /* cleanup */
  2231. SMARTLIST_FOREACH(summary, policy_summary_item_t *, s, tor_free(s));
  2232. smartlist_free(summary);
  2233. tor_free(accepts_str);
  2234. SMARTLIST_FOREACH(accepts, char *, s, tor_free(s));
  2235. smartlist_free(accepts);
  2236. tor_free(rejects_str);
  2237. SMARTLIST_FOREACH(rejects, char *, s, tor_free(s));
  2238. smartlist_free(rejects);
  2239. return result;
  2240. }
  2241. /** Convert a summarized policy string into a short_policy_t. Return NULL
  2242. * if the string is not well-formed. */
  2243. short_policy_t *
  2244. parse_short_policy(const char *summary)
  2245. {
  2246. const char *orig_summary = summary;
  2247. short_policy_t *result;
  2248. int is_accept;
  2249. int n_entries;
  2250. short_policy_entry_t entries[MAX_EXITPOLICY_SUMMARY_LEN]; /* overkill */
  2251. const char *next;
  2252. if (!strcmpstart(summary, "accept ")) {
  2253. is_accept = 1;
  2254. summary += strlen("accept ");
  2255. } else if (!strcmpstart(summary, "reject ")) {
  2256. is_accept = 0;
  2257. summary += strlen("reject ");
  2258. } else {
  2259. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Unrecognized policy summary keyword");
  2260. return NULL;
  2261. }
  2262. n_entries = 0;
  2263. for ( ; *summary; summary = next) {
  2264. const char *comma = strchr(summary, ',');
  2265. unsigned low, high;
  2266. char dummy;
  2267. char ent_buf[32];
  2268. size_t len;
  2269. next = comma ? comma+1 : strchr(summary, '\0');
  2270. len = comma ? (size_t)(comma - summary) : strlen(summary);
  2271. if (n_entries == MAX_EXITPOLICY_SUMMARY_LEN) {
  2272. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Impossibly long policy summary %s",
  2273. escaped(orig_summary));
  2274. return NULL;
  2275. }
  2276. if (! TOR_ISDIGIT(*summary) || len > (sizeof(ent_buf)-1)) {
  2277. /* unrecognized entry format. skip it. */
  2278. continue;
  2279. }
  2280. if (len < 1) {
  2281. /* empty; skip it. */
  2282. /* XXX This happens to be unreachable, since if len==0, then *summary is
  2283. * ',' or '\0', and the TOR_ISDIGIT test above would have failed. */
  2284. continue;
  2285. }
  2286. memcpy(ent_buf, summary, len);
  2287. ent_buf[len] = '\0';
  2288. if (tor_sscanf(ent_buf, "%u-%u%c", &low, &high, &dummy) == 2) {
  2289. if (low<1 || low>65535 || high<1 || high>65535 || low>high) {
  2290. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  2291. "Found bad entry in policy summary %s", escaped(orig_summary));
  2292. return NULL;
  2293. }
  2294. } else if (tor_sscanf(ent_buf, "%u%c", &low, &dummy) == 1) {
  2295. if (low<1 || low>65535) {
  2296. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  2297. "Found bad entry in policy summary %s", escaped(orig_summary));
  2298. return NULL;
  2299. }
  2300. high = low;
  2301. } else {
  2302. log_fn(LOG_PROTOCOL_WARN, LD_DIR,"Found bad entry in policy summary %s",
  2303. escaped(orig_summary));
  2304. return NULL;
  2305. }
  2306. entries[n_entries].min_port = low;
  2307. entries[n_entries].max_port = high;
  2308. n_entries++;
  2309. }
  2310. if (n_entries == 0) {
  2311. log_fn(LOG_PROTOCOL_WARN, LD_DIR,
  2312. "Found no port-range entries in summary %s", escaped(orig_summary));
  2313. return NULL;
  2314. }
  2315. {
  2316. size_t size = STRUCT_OFFSET(short_policy_t, entries) +
  2317. sizeof(short_policy_entry_t)*(n_entries);
  2318. result = tor_malloc_zero(size);
  2319. tor_assert( (char*)&result->entries[n_entries-1] < ((char*)result)+size);
  2320. }
  2321. result->is_accept = is_accept;
  2322. result->n_entries = n_entries;
  2323. memcpy(result->entries, entries, sizeof(short_policy_entry_t)*n_entries);
  2324. return result;
  2325. }
  2326. /** Write <b>policy</b> back out into a string. Used only for unit tests
  2327. * currently. */
  2328. char *
  2329. write_short_policy(const short_policy_t *policy)
  2330. {
  2331. int i;
  2332. char *answer;
  2333. smartlist_t *sl = smartlist_new();
  2334. smartlist_add_asprintf(sl, "%s", policy->is_accept ? "accept " : "reject ");
  2335. for (i=0; i < policy->n_entries; i++) {
  2336. const short_policy_entry_t *e = &policy->entries[i];
  2337. if (e->min_port == e->max_port) {
  2338. smartlist_add_asprintf(sl, "%d", e->min_port);
  2339. } else {
  2340. smartlist_add_asprintf(sl, "%d-%d", e->min_port, e->max_port);
  2341. }
  2342. if (i < policy->n_entries-1)
  2343. smartlist_add(sl, tor_strdup(","));
  2344. }
  2345. answer = smartlist_join_strings(sl, "", 0, NULL);
  2346. SMARTLIST_FOREACH(sl, char *, a, tor_free(a));
  2347. smartlist_free(sl);
  2348. return answer;
  2349. }
  2350. /** Release all storage held in <b>policy</b>. */
  2351. void
  2352. short_policy_free(short_policy_t *policy)
  2353. {
  2354. tor_free(policy);
  2355. }
  2356. /** See whether the <b>addr</b>:<b>port</b> address is likely to be accepted
  2357. * or rejected by the summarized policy <b>policy</b>. Return values are as
  2358. * for compare_tor_addr_to_addr_policy. Unlike the regular addr_policy
  2359. * functions, requires the <b>port</b> be specified. */
  2360. addr_policy_result_t
  2361. compare_tor_addr_to_short_policy(const tor_addr_t *addr, uint16_t port,
  2362. const short_policy_t *policy)
  2363. {
  2364. int i;
  2365. int found_match = 0;
  2366. int accept;
  2367. tor_assert(port != 0);
  2368. if (addr && tor_addr_is_null(addr))
  2369. addr = NULL; /* Unspec means 'no address at all,' in this context. */
  2370. if (addr && get_options()->ClientRejectInternalAddresses &&
  2371. (tor_addr_is_internal(addr, 0) || tor_addr_is_loopback(addr)))
  2372. return ADDR_POLICY_REJECTED;
  2373. for (i=0; i < policy->n_entries; ++i) {
  2374. const short_policy_entry_t *e = &policy->entries[i];
  2375. if (e->min_port <= port && port <= e->max_port) {
  2376. found_match = 1;
  2377. break;
  2378. }
  2379. }
  2380. if (found_match)
  2381. accept = policy->is_accept;
  2382. else
  2383. accept = ! policy->is_accept;
  2384. /* ???? are these right? -NM */
  2385. /* We should be sure not to return ADDR_POLICY_ACCEPTED in the accept
  2386. * case here, because it would cause clients to believe that the node
  2387. * allows exit enclaving. Trying it anyway would open up a cool attack
  2388. * where the node refuses due to exitpolicy, the client reacts in
  2389. * surprise by rewriting the node's exitpolicy to reject *:*, and then
  2390. * a bad guy targets users by causing them to attempt such connections
  2391. * to 98% of the exits.
  2392. *
  2393. * Once microdescriptors can handle addresses in special cases (e.g. if
  2394. * we ever solve ticket 1774), we can provide certainty here. -RD */
  2395. if (accept)
  2396. return ADDR_POLICY_PROBABLY_ACCEPTED;
  2397. else
  2398. return ADDR_POLICY_REJECTED;
  2399. }
  2400. /** Return true iff <b>policy</b> seems reject all ports */
  2401. int
  2402. short_policy_is_reject_star(const short_policy_t *policy)
  2403. {
  2404. /* This doesn't need to be as much on the lookout as policy_is_reject_star,
  2405. * since policy summaries are from the consensus or from consensus
  2406. * microdescs.
  2407. */
  2408. tor_assert(policy);
  2409. /* Check for an exact match of "reject 1-65535". */
  2410. return (policy->is_accept == 0 && policy->n_entries == 1 &&
  2411. policy->entries[0].min_port == 1 &&
  2412. policy->entries[0].max_port == 65535);
  2413. }
  2414. /** Decide whether addr:port is probably or definitely accepted or rejected by
  2415. * <b>node</b>. See compare_tor_addr_to_addr_policy for details on addr/port
  2416. * interpretation. */
  2417. addr_policy_result_t
  2418. compare_tor_addr_to_node_policy(const tor_addr_t *addr, uint16_t port,
  2419. const node_t *node)
  2420. {
  2421. if (node->rejects_all)
  2422. return ADDR_POLICY_REJECTED;
  2423. if (addr && tor_addr_family(addr) == AF_INET6) {
  2424. const short_policy_t *p = NULL;
  2425. if (node->ri)
  2426. p = node->ri->ipv6_exit_policy;
  2427. else if (node->md)
  2428. p = node->md->ipv6_exit_policy;
  2429. if (p)
  2430. return compare_tor_addr_to_short_policy(addr, port, p);
  2431. else
  2432. return ADDR_POLICY_REJECTED;
  2433. }
  2434. if (node->ri) {
  2435. return compare_tor_addr_to_addr_policy(addr, port, node->ri->exit_policy);
  2436. } else if (node->md) {
  2437. if (node->md->exit_policy == NULL)
  2438. return ADDR_POLICY_REJECTED;
  2439. else
  2440. return compare_tor_addr_to_short_policy(addr, port,
  2441. node->md->exit_policy);
  2442. } else {
  2443. return ADDR_POLICY_PROBABLY_REJECTED;
  2444. }
  2445. }
  2446. /**
  2447. * Given <b>policy_list</b>, a list of addr_policy_t, produce a string
  2448. * representation of the list.
  2449. * If <b>include_ipv4</b> is true, include IPv4 entries.
  2450. * If <b>include_ipv6</b> is true, include IPv6 entries.
  2451. */
  2452. char *
  2453. policy_dump_to_string(const smartlist_t *policy_list,
  2454. int include_ipv4,
  2455. int include_ipv6)
  2456. {
  2457. smartlist_t *policy_string_list;
  2458. char *policy_string = NULL;
  2459. policy_string_list = smartlist_new();
  2460. SMARTLIST_FOREACH_BEGIN(policy_list, addr_policy_t *, tmpe) {
  2461. char *pbuf;
  2462. int bytes_written_to_pbuf;
  2463. if ((tor_addr_family(&tmpe->addr) == AF_INET6) && (!include_ipv6)) {
  2464. continue; /* Don't include IPv6 parts of address policy */
  2465. }
  2466. if ((tor_addr_family(&tmpe->addr) == AF_INET) && (!include_ipv4)) {
  2467. continue; /* Don't include IPv4 parts of address policy */
  2468. }
  2469. pbuf = tor_malloc(POLICY_BUF_LEN);
  2470. bytes_written_to_pbuf = policy_write_item(pbuf,POLICY_BUF_LEN, tmpe, 1);
  2471. if (bytes_written_to_pbuf < 0) {
  2472. log_warn(LD_BUG, "policy_dump_to_string ran out of room!");
  2473. tor_free(pbuf);
  2474. goto done;
  2475. }
  2476. smartlist_add(policy_string_list,pbuf);
  2477. } SMARTLIST_FOREACH_END(tmpe);
  2478. policy_string = smartlist_join_strings(policy_string_list, "\n", 0, NULL);
  2479. done:
  2480. SMARTLIST_FOREACH(policy_string_list, char *, str, tor_free(str));
  2481. smartlist_free(policy_string_list);
  2482. return policy_string;
  2483. }
  2484. /** Implementation for GETINFO control command: knows the answer for questions
  2485. * about "exit-policy/..." */
  2486. int
  2487. getinfo_helper_policies(control_connection_t *conn,
  2488. const char *question, char **answer,
  2489. const char **errmsg)
  2490. {
  2491. (void) conn;
  2492. (void) errmsg;
  2493. if (!strcmp(question, "exit-policy/default")) {
  2494. *answer = tor_strdup(DEFAULT_EXIT_POLICY);
  2495. } else if (!strcmp(question, "exit-policy/reject-private/default")) {
  2496. smartlist_t *private_policy_strings;
  2497. const char **priv = private_nets;
  2498. private_policy_strings = smartlist_new();
  2499. while (*priv != NULL) {
  2500. /* IPv6 addresses are in "[]" and contain ":",
  2501. * IPv4 addresses are not in "[]" and contain "." */
  2502. smartlist_add_asprintf(private_policy_strings, "reject %s:*", *priv);
  2503. priv++;
  2504. }
  2505. *answer = smartlist_join_strings(private_policy_strings,
  2506. ",", 0, NULL);
  2507. SMARTLIST_FOREACH(private_policy_strings, char *, str, tor_free(str));
  2508. smartlist_free(private_policy_strings);
  2509. } else if (!strcmp(question, "exit-policy/reject-private/relay")) {
  2510. const or_options_t *options = get_options();
  2511. const routerinfo_t *me = router_get_my_routerinfo();
  2512. if (!me) {
  2513. *errmsg = "router_get_my_routerinfo returned NULL";
  2514. return -1;
  2515. }
  2516. if (!options->ExitPolicyRejectPrivate) {
  2517. *answer = tor_strdup("");
  2518. return 0;
  2519. }
  2520. smartlist_t *private_policy_list = smartlist_new();
  2521. smartlist_t *configured_addresses = smartlist_new();
  2522. /* Copy the configured addresses into the tor_addr_t* list */
  2523. policies_copy_ipv4h_to_smartlist(configured_addresses, me->addr);
  2524. policies_copy_addr_to_smartlist(configured_addresses, &me->ipv6_addr);
  2525. policies_copy_outbound_addresses_to_smartlist(configured_addresses,
  2526. options);
  2527. policies_parse_exit_policy_reject_private(
  2528. &private_policy_list,
  2529. options->IPv6Exit,
  2530. configured_addresses,
  2531. 1, 1);
  2532. *answer = policy_dump_to_string(private_policy_list, 1, 1);
  2533. addr_policy_list_free(private_policy_list);
  2534. SMARTLIST_FOREACH(configured_addresses, tor_addr_t *, a, tor_free(a));
  2535. smartlist_free(configured_addresses);
  2536. } else if (!strcmpstart(question, "exit-policy/")) {
  2537. const routerinfo_t *me = router_get_my_routerinfo();
  2538. int include_ipv4 = 0;
  2539. int include_ipv6 = 0;
  2540. if (!strcmp(question, "exit-policy/ipv4")) {
  2541. include_ipv4 = 1;
  2542. } else if (!strcmp(question, "exit-policy/ipv6")) {
  2543. include_ipv6 = 1;
  2544. } else if (!strcmp(question, "exit-policy/full")) {
  2545. include_ipv4 = include_ipv6 = 1;
  2546. } else {
  2547. return 0; /* No such key. */
  2548. }
  2549. if (!me) {
  2550. *errmsg = "router_get_my_routerinfo returned NULL";
  2551. return -1;
  2552. }
  2553. *answer = router_dump_exit_policy_to_string(me,include_ipv4,include_ipv6);
  2554. }
  2555. return 0;
  2556. }
  2557. /** Release all storage held by <b>p</b>. */
  2558. void
  2559. addr_policy_list_free(smartlist_t *lst)
  2560. {
  2561. if (!lst)
  2562. return;
  2563. SMARTLIST_FOREACH(lst, addr_policy_t *, policy, addr_policy_free(policy));
  2564. smartlist_free(lst);
  2565. }
  2566. /** Release all storage held by <b>p</b>. */
  2567. void
  2568. addr_policy_free(addr_policy_t *p)
  2569. {
  2570. if (!p)
  2571. return;
  2572. if (--p->refcnt <= 0) {
  2573. if (p->is_canonical) {
  2574. policy_map_ent_t search, *found;
  2575. search.policy = p;
  2576. found = HT_REMOVE(policy_map, &policy_root, &search);
  2577. if (found) {
  2578. tor_assert(p == found->policy);
  2579. tor_free(found);
  2580. }
  2581. }
  2582. tor_free(p);
  2583. }
  2584. }
  2585. /** Release all storage held by policy variables. */
  2586. void
  2587. policies_free_all(void)
  2588. {
  2589. addr_policy_list_free(reachable_or_addr_policy);
  2590. reachable_or_addr_policy = NULL;
  2591. addr_policy_list_free(reachable_dir_addr_policy);
  2592. reachable_dir_addr_policy = NULL;
  2593. addr_policy_list_free(socks_policy);
  2594. socks_policy = NULL;
  2595. addr_policy_list_free(dir_policy);
  2596. dir_policy = NULL;
  2597. addr_policy_list_free(authdir_reject_policy);
  2598. authdir_reject_policy = NULL;
  2599. addr_policy_list_free(authdir_invalid_policy);
  2600. authdir_invalid_policy = NULL;
  2601. addr_policy_list_free(authdir_badexit_policy);
  2602. authdir_badexit_policy = NULL;
  2603. if (!HT_EMPTY(&policy_root)) {
  2604. policy_map_ent_t **ent;
  2605. int n = 0;
  2606. char buf[POLICY_BUF_LEN];
  2607. log_warn(LD_MM, "Still had %d address policies cached at shutdown.",
  2608. (int)HT_SIZE(&policy_root));
  2609. /* Note the first 10 cached policies to try to figure out where they
  2610. * might be coming from. */
  2611. HT_FOREACH(ent, policy_map, &policy_root) {
  2612. if (++n > 10)
  2613. break;
  2614. if (policy_write_item(buf, sizeof(buf), (*ent)->policy, 0) >= 0)
  2615. log_warn(LD_MM," %d [%d]: %s", n, (*ent)->policy->refcnt, buf);
  2616. }
  2617. }
  2618. HT_CLEAR(policy_map, &policy_root);
  2619. }