policies.c 102 KB

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