fw4.uc 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375
  1. const fs = require("fs");
  2. const uci = require("uci");
  3. const ubus = require("ubus");
  4. const STATEFILE = "/var/run/fw4.state";
  5. const PARSE_LIST = 0x01;
  6. const FLATTEN_LIST = 0x02;
  7. const NO_INVERT = 0x04;
  8. const UNSUPPORTED = 0x08;
  9. const REQUIRED = 0x10;
  10. const DEPRECATED = 0x20;
  11. const ipv4_icmptypes = {
  12. "any": [ 0xFF, 0, 0xFF ],
  13. "echo-reply": [ 0, 0, 0xFF ],
  14. "pong": [ 0, 0, 0xFF ], /* Alias */
  15. "destination-unreachable": [ 3, 0, 0xFF ],
  16. "network-unreachable": [ 3, 0, 0 ],
  17. "host-unreachable": [ 3, 1, 1 ],
  18. "protocol-unreachable": [ 3, 2, 2 ],
  19. "port-unreachable": [ 3, 3, 3 ],
  20. "fragmentation-needed": [ 3, 4, 4 ],
  21. "source-route-failed": [ 3, 5, 5 ],
  22. "network-unknown": [ 3, 6, 6 ],
  23. "host-unknown": [ 3, 7, 7 ],
  24. "network-prohibited": [ 3, 9, 9 ],
  25. "host-prohibited": [ 3, 10, 10 ],
  26. "TOS-network-unreachable": [ 3, 11, 11 ],
  27. "TOS-host-unreachable": [ 3, 12, 12 ],
  28. "communication-prohibited": [ 3, 13, 13 ],
  29. "host-precedence-violation": [ 3, 14, 14 ],
  30. "precedence-cutoff": [ 3, 15, 15 ],
  31. "source-quench": [ 4, 0, 0xFF ],
  32. "redirect": [ 5, 0, 0xFF ],
  33. "network-redirect": [ 5, 0, 0 ],
  34. "host-redirect": [ 5, 1, 1 ],
  35. "TOS-network-redirect": [ 5, 2, 2 ],
  36. "TOS-host-redirect": [ 5, 3, 3 ],
  37. "echo-request": [ 8, 0, 0xFF ],
  38. "ping": [ 8, 0, 0xFF ], /* Alias */
  39. "router-advertisement": [ 9, 0, 0xFF ],
  40. "router-solicitation": [ 10, 0, 0xFF ],
  41. "time-exceeded": [ 11, 0, 0xFF ],
  42. "ttl-exceeded": [ 11, 0, 0xFF ], /* Alias */
  43. "ttl-zero-during-transit": [ 11, 0, 0 ],
  44. "ttl-zero-during-reassembly": [ 11, 1, 1 ],
  45. "parameter-problem": [ 12, 0, 0xFF ],
  46. "ip-header-bad": [ 12, 0, 0 ],
  47. "required-option-missing": [ 12, 1, 1 ],
  48. "timestamp-request": [ 13, 0, 0xFF ],
  49. "timestamp-reply": [ 14, 0, 0xFF ],
  50. "address-mask-request": [ 17, 0, 0xFF ],
  51. "address-mask-reply": [ 18, 0, 0xFF ]
  52. };
  53. const ipv6_icmptypes = {
  54. /* "name": [ type-code, code-min, code-max ] */
  55. "destination-unreachable": [ 1, 0, 0xFF ],
  56. "no-route": [ 1, 0, 0 ],
  57. "communication-prohibited": [ 1, 1, 1 ],
  58. "address-unreachable": [ 1, 3, 3 ],
  59. "port-unreachable": [ 1, 4, 4 ],
  60. "packet-too-big": [ 2, 0, 0xFF ],
  61. "time-exceeded": [ 3, 0, 0xFF ],
  62. "ttl-exceeded": [ 3, 0, 0xFF ], /* Alias */
  63. "ttl-zero-during-transit": [ 3, 0, 0 ],
  64. "ttl-zero-during-reassembly": [ 3, 1, 1 ],
  65. "parameter-problem": [ 4, 0, 0xFF ],
  66. "bad-header": [ 4, 0, 0 ],
  67. "unknown-header-type": [ 4, 1, 1 ],
  68. "unknown-option": [ 4, 2, 2 ],
  69. "echo-request": [ 128, 0, 0xFF ],
  70. "ping": [ 128, 0, 0xFF ], /* Alias */
  71. "echo-reply": [ 129, 0, 0xFF ],
  72. "pong": [ 129, 0, 0xFF ], /* Alias */
  73. /* only code zero (0) */
  74. "multicast-listener-query": [ 130, 0, 0xFF ],
  75. "multicast-listener-report": [ 131, 0, 0xFF ],
  76. "multicast-listener-done": [ 132, 0, 0xFF ],
  77. "router-solicitation": [ 133, 0, 0xFF ],
  78. "router-advertisement": [ 134, 0, 0xFF ],
  79. "neighbour-solicitation": [ 135, 0, 0xFF ],
  80. "neighbor-solicitation": [ 135, 0, 0xFF ], /* Alias */
  81. "neighbour-advertisement": [ 136, 0, 0xFF ],
  82. "neighbor-advertisement": [ 136, 0, 0xFF ], /* Alias */
  83. "redirect": [ 137, 0, 0xFF ],
  84. /* codes 0, 1, 255 */
  85. "router-renumbering": [ 138, 0, 0xFF ],
  86. /* codes 0, 1, 2 */
  87. "node-info-query": [ 139, 0, 0xFF ],
  88. /* codes 0, 1, 2 */
  89. "node-info-response": [ 140, 0, 0xFF ],
  90. "inverse-neighbour-discovery-solicitation-message": [ 141, 0, 0xFF ],
  91. "inverse-neighbor-discovery-solicitation-message": [ 141, 0, 0xFF ], /* Alias */
  92. "inverse-neighbour-discovery-advertisement-message": [ 142, 0, 0xFF ],
  93. "inverse-neighbor-discovery-advertisement-message": [ 142, 0, 0xFF ], /* Alias */
  94. "v2-multicast-listener-report": [ 143, 0, 0xFF ],
  95. "home-agent-address-discovery-request-message": [ 144, 0, 0xFF ],
  96. "home-agent-address-discovery-reply-message": [ 145, 0, 0xFF ],
  97. "mobile-prefix-solicitation": [ 146, 0, 0xFF ],
  98. "mobile-prefix-advertisement": [ 147, 0, 0xFF ],
  99. /* SEND */
  100. "certification-path-solicitation-message": [ 148, 0, 0xFF ],
  101. "certification-path-advertisement-message": [ 149, 0, 0xFF ],
  102. "seamoby-protocol-message": [ 150, 0, 0xFF ],
  103. /* IPv6 multicast: FF02:0:0:0:0:0:0:6A, no code fields */
  104. "multicast-router-advertisement": [ 151, 0, 0xFF ],
  105. "multicast-router-solicitation": [ 152, 0, 0xFF ],
  106. "multicast-router-termination": [ 153, 0, 0xFF ],
  107. /* codes 0-5, 6-255 */
  108. "fmipv6-message": [ 154, 0, 0xFF ],
  109. "rpl-control-message": [ 155, 0, 0xFF ],
  110. "ilnpv6-locator-update-message": [ 156, 0, 0xFF ],
  111. /* codes 0-4, 5-15 */
  112. "duplicate-address-request": [ 157, 0, 0xFF ],
  113. /* codes 0-4, 5-15 */
  114. "duplicate-address-confirmation": [ 158, 0, 0xFF ],
  115. /* Multicast Protocol for Low-Power */
  116. "mpl-control-message": [ 159, 0, 0xFF ],
  117. /* codes 0, 1-255 */
  118. "extended-echo-request": [ 160, 0, 0xFF ],
  119. "extended-ping": [ 160, 0, 0xFF ], /* Alias */
  120. /* codes 0-4, 5-255 */
  121. "extended-echo-reply": [ 161, 0, 0xFF ],
  122. "extended-pong": [ 161, 0, 0xFF ] /* Alias */
  123. };
  124. const dscp_classes = {
  125. "CS0": 0x00,
  126. "CS1": 0x08,
  127. "CS2": 0x10,
  128. "CS3": 0x18,
  129. "CS4": 0x20,
  130. "CS5": 0x28,
  131. "CS6": 0x30,
  132. "CS7": 0x38,
  133. "BE": 0x00,
  134. "LE": 0x01,
  135. "AF11": 0x0a,
  136. "AF12": 0x0c,
  137. "AF13": 0x0e,
  138. "AF21": 0x12,
  139. "AF22": 0x14,
  140. "AF23": 0x16,
  141. "AF31": 0x1a,
  142. "AF32": 0x1c,
  143. "AF33": 0x1e,
  144. "AF41": 0x22,
  145. "AF42": 0x24,
  146. "AF43": 0x26,
  147. "EF": 0x2e
  148. };
  149. function to_mask(bits, v6) {
  150. let m = [], n = false;
  151. if (bits < 0) {
  152. n = true;
  153. bits = -bits;
  154. }
  155. if (bits > (v6 ? 128 : 32))
  156. return null;
  157. for (let i = 0; i < (v6 ? 16 : 4); i++) {
  158. let b = (bits < 8) ? bits : 8;
  159. m[i] = (n ? ~(0xff << (8 - b)) : (0xff << (8 - b))) & 0xff;
  160. bits -= b;
  161. }
  162. return arrtoip(m);
  163. }
  164. function to_bits(mask) {
  165. let a = iptoarr(mask);
  166. if (!a)
  167. return null;
  168. let bits = 0;
  169. for (let i = 0, z = false; i < length(a); i++) {
  170. z ||= !a[i];
  171. while (!z && (a[i] & 0x80)) {
  172. a[i] = (a[i] << 1) & 0xff;
  173. bits++;
  174. }
  175. if (a[i])
  176. return null;
  177. }
  178. return bits;
  179. }
  180. function apply_mask(addr, mask) {
  181. let a = iptoarr(addr);
  182. if (!a)
  183. return null;
  184. if (type(mask) == "int") {
  185. for (let i = 0; i < length(a); i++) {
  186. let b = (mask < 8) ? mask : 8;
  187. a[i] &= (0xff << (8 - b)) & 0xff;
  188. mask -= b;
  189. }
  190. }
  191. else {
  192. let m = iptoarr(mask);
  193. if (!m || length(a) != length(m))
  194. return null;
  195. for (let i = 0; i < length(a); i++)
  196. a[i] &= m[i];
  197. }
  198. return arrtoip(a);
  199. }
  200. function to_array(x) {
  201. if (type(x) == "array")
  202. return x;
  203. if (x == null)
  204. return [];
  205. if (type(x) == "object")
  206. return [ x ];
  207. x = trim("" + x);
  208. return (x == "") ? [] : split(x, /[ \t]+/);
  209. }
  210. function filter_pos(x) {
  211. let rv = filter(x, e => !e.invert);
  212. return length(rv) ? rv : null;
  213. }
  214. function filter_neg(x) {
  215. let rv = filter(x, e => e.invert);
  216. return length(rv) ? rv : null;
  217. }
  218. function null_if_empty(x) {
  219. return length(x) ? x : null;
  220. }
  221. function subnets_split_af(x) {
  222. let rv = {};
  223. for (let ag in to_array(x)) {
  224. for (let a in filter(ag.addrs, a => (a.family == 4)))
  225. push(rv[0] ||= [], { ...a, invert: ag.invert });
  226. for (let a in filter(ag.addrs, a => (a.family == 6)))
  227. push(rv[1] ||= [], { ...a, invert: ag.invert });
  228. }
  229. if (rv[0] || rv[1])
  230. rv.family = (!rv[0] ^ !rv[1]) ? (rv[0] ? 4 : 6) : 0;
  231. return rv;
  232. }
  233. function subnets_group_by_masking(x) {
  234. let groups = [], plain = [], nc = [], invert_plain = [], invert_masked = [];
  235. for (let a in to_array(x)) {
  236. if (a.bits == -1 && !a.invert)
  237. push(nc, a);
  238. else if (!a.invert)
  239. push(plain, a);
  240. else if (a.bits == -1)
  241. push(invert_masked, a);
  242. else
  243. push(invert_plain, a);
  244. }
  245. for (let a in nc)
  246. push(groups, [ null, null_if_empty(invert_plain), [ a, ...invert_masked ] ]);
  247. if (length(plain)) {
  248. push(groups, [
  249. plain,
  250. null_if_empty(invert_plain),
  251. null_if_empty(invert_masked)
  252. ]);
  253. }
  254. else if (!length(groups)) {
  255. push(groups, [
  256. null,
  257. null_if_empty(invert_plain),
  258. null_if_empty(invert_masked)
  259. ]);
  260. }
  261. return groups;
  262. }
  263. function ensure_tcpudp(x) {
  264. if (length(filter(x, p => (p.name == "tcp" || p.name == "udp"))))
  265. return true;
  266. let rest = filter(x, p => !p.any),
  267. any = filter(x, p => p.any);
  268. if (length(any) && !length(rest)) {
  269. splice(x, 0);
  270. push(x, { name: "tcp" }, { name: "udp" });
  271. return true;
  272. }
  273. return false;
  274. }
  275. let is_family = (x, v) => (!x.family || x.family == v);
  276. let family_is_ipv4 = (x) => (!x.family || x.family == 4);
  277. let family_is_ipv6 = (x) => (!x.family || x.family == 6);
  278. function infer_family(f, objects) {
  279. let res = f;
  280. let by = null;
  281. for (let i = 0; i < length(objects); i += 2) {
  282. let objs = to_array(objects[i]),
  283. desc = objects[i + 1];
  284. for (let obj in objs) {
  285. if (!obj || !obj.family || obj.family == res)
  286. continue;
  287. if (!res) {
  288. res = obj.family;
  289. by = obj.desc;
  290. continue;
  291. }
  292. return by
  293. ? `references IPv${obj.family} only ${desc} but is restricted to IPv${res} by ${by}`
  294. : `is restricted to IPv${res} but referenced ${desc} is IPv${obj.family} only`;
  295. }
  296. }
  297. return res;
  298. }
  299. function map_setmatch(set, match, proto) {
  300. if (!set || (('inet_service' in set.types) && proto != 'tcp' && proto != 'udp'))
  301. return null;
  302. let fields = [];
  303. for (let i, t in set.types) {
  304. let dir = ((match.dir?.[i] || set.directions[i] || 'src') == 'src' ? 's' : 'd');
  305. switch (t) {
  306. case 'ipv4_addr':
  307. fields[i] = `ip ${dir}addr`;
  308. break;
  309. case 'ipv6_addr':
  310. fields[i] = `ip6 ${dir}addr`;
  311. break;
  312. case 'ether_addr':
  313. if (dir != 's')
  314. return NaN;
  315. fields[i] = 'ether saddr';
  316. break;
  317. case 'inet_service':
  318. fields[i] = `${proto} ${dir}port`;
  319. break;
  320. }
  321. }
  322. return fields;
  323. }
  324. function resolve_lower_devices(devstatus, devname) {
  325. let dir = fs.opendir(`/sys/class/net/${devname}`);
  326. let devs = [];
  327. if (dir) {
  328. switch (devstatus[devname]?.devtype) {
  329. case 'vlan':
  330. case 'bridge':
  331. let e;
  332. while ((e = dir.read()) != null)
  333. if (index(e, "lower_") === 0)
  334. push(devs, ...resolve_lower_devices(devstatus, substr(e, 6)));
  335. break;
  336. default:
  337. push(devs, devname);
  338. break;
  339. }
  340. dir.close();
  341. }
  342. return devs;
  343. }
  344. function nft_json_command(...args) {
  345. let cmd = [ "/usr/sbin/nft", "--terse", "--json", ...args ];
  346. let nft = fs.popen(join(" ", cmd), "r");
  347. let info;
  348. if (nft) {
  349. try {
  350. info = filter(json(nft.read("all"))?.nftables,
  351. item => (type(item) == "object" && !item.metainfo));
  352. }
  353. catch (e) {
  354. warn(`Unable to parse nftables JSON output: ${e}\n`);
  355. }
  356. nft.close();
  357. }
  358. else {
  359. warn(`Unable to popen() ${cmd}: ${fs.error()}\n`);
  360. }
  361. return info || [];
  362. }
  363. function nft_try_hw_offload(devices) {
  364. let nft_test = `
  365. add table inet fw4-hw-offload-test;
  366. add flowtable inet fw4-hw-offload-test ft {
  367. hook ingress priority 0;
  368. devices = { "${join('", "', devices)}" };
  369. flags offload;
  370. }
  371. `;
  372. let rc = system(`/usr/sbin/nft -c '${replace(nft_test, "'", "'\\''")}' 2>/dev/null`);
  373. return (rc == 0);
  374. }
  375. return {
  376. read_kernel_version: function() {
  377. let fd = fs.open("/proc/version", "r"),
  378. v = 0;
  379. if (fd) {
  380. let m = match(fd.read("line"), /^Linux version ([0-9]+)\.([0-9]+)\.([0-9]+)/);
  381. v = m ? (+m[1] << 24) | (+m[2] << 16) | (+m[3] << 8) : 0;
  382. fd.close();
  383. }
  384. return v;
  385. },
  386. resolve_hw_offload_devices: function() {
  387. if (!this.default_option("flow_offloading_hw"))
  388. return null;
  389. let devstatus = null;
  390. let devices = null;
  391. let bus = ubus.connect();
  392. if (bus) {
  393. devstatus = bus.call("network.device", "status") || {};
  394. bus.disconnect();
  395. }
  396. for (let zone in this.zones())
  397. for (let device in zone.related_physdevs)
  398. push(devices ||= [], ...resolve_lower_devices(devstatus, device));
  399. if (!devices)
  400. return null;
  401. devices = sort(uniq(devices));
  402. if (!nft_try_hw_offload(devices)) {
  403. this.warn('Hardware flow offloading unavailable, falling back to software offloading');
  404. this.state.defaults.flow_offloading_hw = false;
  405. return null;
  406. }
  407. return devices;
  408. },
  409. resolve_offload_devices: function() {
  410. if (!this.default_option("flow_offloading"))
  411. return [];
  412. let devices = this.resolve_hw_offload_devices();
  413. if (!devices) {
  414. devices = [];
  415. for (let zone in this.zones())
  416. for (let device in zone.related_physdevs)
  417. if (fs.access(`/sys/class/net/${device}`))
  418. push(devices, device);
  419. devices = sort(uniq(devices));
  420. }
  421. return devices;
  422. },
  423. check_set_types: function() {
  424. let sets = {};
  425. for (let item in nft_json_command("list", "sets", "inet"))
  426. if (item.set?.table == "fw4")
  427. sets[item.set.name] = (type(item.set.type) == "array") ? item.set.type : [ item.set.type ];
  428. return sets;
  429. },
  430. check_flowtable: function() {
  431. for (let item in nft_json_command("list", "flowtables", "inet"))
  432. if (item.flowtable?.table == "fw4" && item.flowtable?.name == "ft")
  433. return true;
  434. return false;
  435. },
  436. read_state: function() {
  437. let fd = fs.open(STATEFILE, "r");
  438. let state = null;
  439. if (fd) {
  440. try {
  441. state = json(fd.read("all"));
  442. }
  443. catch (e) {
  444. warn(`Unable to parse '${STATEFILE}': ${e}\n`);
  445. }
  446. fd.close();
  447. }
  448. return state;
  449. },
  450. read_ubus: function() {
  451. let self = this,
  452. ifaces, services,
  453. rules = [], networks = {},
  454. bus = ubus.connect();
  455. if (bus) {
  456. ifaces = bus.call("network.interface", "dump");
  457. services = bus.call("service", "get_data", { "type": "firewall" });
  458. bus.disconnect();
  459. }
  460. else {
  461. warn(`Unable to connect to ubus: ${ubus.error()}\n`);
  462. }
  463. //
  464. // Gather logical network information from ubus
  465. //
  466. if (type(ifaces?.interface) == "array") {
  467. for (let ifc in ifaces.interface) {
  468. let net = {
  469. up: ifc.up,
  470. device: ifc.l3_device ?? ifc.device,
  471. physdev: ifc.device,
  472. zone: ifc.data?.zone
  473. };
  474. if (type(ifc["ipv4-address"]) == "array") {
  475. for (let addr in ifc["ipv4-address"]) {
  476. push(net.ipaddrs ||= [], {
  477. family: 4,
  478. addr: addr.address,
  479. mask: to_mask(addr.mask, false),
  480. bits: addr.mask
  481. });
  482. }
  483. }
  484. if (type(ifc["ipv6-address"]) == "array") {
  485. for (let addr in ifc["ipv6-address"]) {
  486. push(net.ipaddrs ||= [], {
  487. family: 6,
  488. addr: addr.address,
  489. mask: to_mask(addr.mask, true),
  490. bits: addr.mask
  491. });
  492. }
  493. }
  494. if (type(ifc["ipv6-prefix-assignment"]) == "array") {
  495. for (let addr in ifc["ipv6-prefix-assignment"]) {
  496. if (addr["local-address"]) {
  497. push(net.ipaddrs ||= [], {
  498. family: 6,
  499. addr: addr["local-address"].address,
  500. mask: to_mask(addr["local-address"].mask, true),
  501. bits: addr["local-address"].mask
  502. });
  503. }
  504. }
  505. }
  506. if (type(ifc.data?.firewall) == "array") {
  507. let n = 0;
  508. for (let rulespec in ifc.data.firewall) {
  509. push(rules, {
  510. ...rulespec,
  511. name: (rulespec.type != 'ipset') ? `ubus:${ifc.interface}[${ifc.proto}] ${rulespec.type || 'rule'} ${n}` : rulespec.name,
  512. device: rulespec.device ?? ifc.l3_device ?? ifc.device
  513. });
  514. n++;
  515. }
  516. }
  517. networks[ifc.interface] = net;
  518. }
  519. }
  520. //
  521. // Gather firewall rule definitions from ubus services
  522. //
  523. if (type(services) == "object") {
  524. for (let svcname, service in services) {
  525. if (type(service?.firewall) == "array") {
  526. let n = 0;
  527. for (let rulespec in services[svcname].firewall) {
  528. push(rules, {
  529. ...rulespec,
  530. name: (rulespec.type != 'ipset') ? `ubus:${svcname} ${rulespec.type || 'rule'} ${n}` : rulespec.name
  531. });
  532. n++;
  533. }
  534. }
  535. for (let svcinst, instance in service) {
  536. if (type(instance?.firewall) == "array") {
  537. let n = 0;
  538. for (let rulespec in instance.firewall) {
  539. push(rules, {
  540. ...rulespec,
  541. name: (rulespec.type != 'ipset') ? `ubus:${svcname}[${svcinst}] ${rulespec.type || 'rule'} ${n}` : rulespec.name
  542. });
  543. n++;
  544. }
  545. }
  546. }
  547. }
  548. }
  549. return {
  550. networks: networks,
  551. ubus_rules: rules
  552. };
  553. },
  554. load: function(use_statefile) {
  555. let self = this;
  556. this.state = use_statefile ? this.read_state() : null;
  557. this.cursor = uci.cursor();
  558. this.cursor.load("firewall");
  559. this.cursor.load("/usr/share/firewall4/helpers");
  560. if (!this.state)
  561. this.state = this.read_ubus();
  562. this.kernel = this.read_kernel_version();
  563. //
  564. // Read helper mapping
  565. //
  566. this.cursor.foreach("helpers", "helper", h => self.parse_helper(h));
  567. //
  568. // Read default policies
  569. //
  570. this.cursor.foreach("firewall", "defaults", d => self.parse_defaults(d));
  571. if (!this.state.defaults)
  572. this.parse_defaults({});
  573. //
  574. // Build list of ipsets
  575. //
  576. if (!this.state.ipsets) {
  577. map(filter(this.state.ubus_rules, n => (n.type == "ipset")), s => self.parse_ipset(s));
  578. this.cursor.foreach("firewall", "ipset", s => self.parse_ipset(s));
  579. }
  580. //
  581. // Build list of logical zones
  582. //
  583. if (!this.state.zones)
  584. this.cursor.foreach("firewall", "zone", z => self.parse_zone(z));
  585. //
  586. // Build list of rules
  587. //
  588. map(filter(this.state.ubus_rules, r => (r.type == "rule")), r => self.parse_rule(r));
  589. this.cursor.foreach("firewall", "rule", r => self.parse_rule(r));
  590. //
  591. // Build list of forwardings
  592. //
  593. this.cursor.foreach("firewall", "forwarding", f => self.parse_forwarding(f));
  594. //
  595. // Build list of redirects
  596. //
  597. map(filter(this.state.ubus_rules, r => (r.type == "redirect")), r => self.parse_redirect(r));
  598. this.cursor.foreach("firewall", "redirect", r => self.parse_redirect(r));
  599. //
  600. // Build list of snats
  601. //
  602. map(filter(this.state.ubus_rules, n => (n.type == "nat")), n => self.parse_nat(n));
  603. this.cursor.foreach("firewall", "nat", n => self.parse_nat(n));
  604. //
  605. // Build list of includes
  606. //
  607. this.cursor.foreach("firewall", "include", i => self.parse_include(i));
  608. //
  609. // Discover automatic includes
  610. //
  611. if (this.default_option("auto_includes")) {
  612. for (let position in [ 'ruleset-pre', 'ruleset-post', 'table-pre', 'table-post', 'chain-pre', 'chain-post' ])
  613. for (let chain in (position in [ 'chain-pre', 'chain-post' ]) ? fs.lsdir(`/usr/share/nftables.d/${position}`) : [ null ])
  614. for (let path in fs.glob(`/usr/share/nftables.d/${position}${chain ? `/${chain}` : ''}/*.nft`))
  615. if (fs.access(path))
  616. this.parse_include({ type: 'nftables', position, chain, path });
  617. }
  618. if (use_statefile) {
  619. let fd = fs.open(STATEFILE, "w");
  620. if (fd) {
  621. fd.write({
  622. zones: this.state.zones,
  623. ipsets: this.state.ipsets,
  624. networks: this.state.networks,
  625. ubus_rules: this.state.ubus_rules,
  626. includes: this.state.includes
  627. });
  628. fd.close();
  629. }
  630. else {
  631. warn(`Unable to write '${STATEFILE}': ${fs.error()}\n`);
  632. }
  633. }
  634. },
  635. warn: function(fmt, ...args) {
  636. if (getenv("QUIET"))
  637. return;
  638. let msg = sprintf(fmt, ...args);
  639. if (getenv("TTY"))
  640. warn(`\033[33m${msg}\033[m\n`);
  641. else
  642. warn(`[!] ${msg}\n`);
  643. },
  644. get: function(sid, opt) {
  645. return this.cursor.get("firewall", sid, opt);
  646. },
  647. get_all: function(sid) {
  648. return this.cursor.get_all("firewall", sid);
  649. },
  650. parse_options: function(s, spec) {
  651. let rv = {};
  652. for (let key, val in spec) {
  653. let datatype = `parse_${val[0]}`,
  654. defval = val[1],
  655. flags = val[2] || 0,
  656. parsefn = (flags & PARSE_LIST) ? "parse_list" : "parse_opt";
  657. let res = this[parsefn](s, key, datatype, defval, flags);
  658. if (res !== res)
  659. return false;
  660. if (type(res) == "object" && res.invert && (flags & NO_INVERT)) {
  661. this.warn_section(s, `option '${key}' must not be negated`);
  662. return false;
  663. }
  664. if (res != null) {
  665. if (flags & DEPRECATED)
  666. this.warn_section(s, `option '${key}' is deprecated by fw4`);
  667. else if (flags & UNSUPPORTED)
  668. this.warn_section(s, `option '${key}' is not supported by fw4`);
  669. else
  670. rv[key] = res;
  671. }
  672. }
  673. for (let opt in s) {
  674. if (index(opt, '.') != 0 && opt != 'type' && !exists(spec, opt)) {
  675. this.warn_section(s, `specifies unknown option '${opt}'`);
  676. }
  677. }
  678. return rv;
  679. },
  680. parse_subnet: function(subnet) {
  681. let parts = split(subnet, "/");
  682. let a, b, m, n;
  683. switch (length(parts)) {
  684. case 2:
  685. a = iptoarr(parts[0]);
  686. m = iptoarr(parts[1]);
  687. if (!a)
  688. return null;
  689. if (m) {
  690. if (length(a) != length(m))
  691. return null;
  692. b = to_bits(parts[1]);
  693. /* allow non-contiguous masks such as `::ffff:ffff:ffff:ffff` */
  694. if (b == null) {
  695. b = -1;
  696. for (let i, x in m)
  697. a[i] &= x;
  698. }
  699. m = arrtoip(m);
  700. }
  701. else {
  702. b = +parts[1];
  703. if (type(b) != "int")
  704. return null;
  705. m = to_mask(b, length(a) == 16);
  706. b = max(-1, b);
  707. }
  708. return [{
  709. family: (length(a) == 16) ? 6 : 4,
  710. addr: arrtoip(a),
  711. mask: m,
  712. bits: b
  713. }];
  714. case 1:
  715. parts = split(parts[0], "-");
  716. switch (length(parts)) {
  717. case 2:
  718. a = iptoarr(parts[0]);
  719. b = iptoarr(parts[1]);
  720. if (a && b && length(a) == length(b)) {
  721. return [{
  722. family: (length(a) == 16) ? 6 : 4,
  723. addr: arrtoip(a),
  724. addr2: arrtoip(b),
  725. range: true
  726. }];
  727. }
  728. break;
  729. case 1:
  730. a = iptoarr(parts[0]);
  731. if (a) {
  732. return [{
  733. family: (length(a) == 16) ? 6 : 4,
  734. addr: arrtoip(a),
  735. mask: to_mask(length(a) * 8, length(a) == 16),
  736. bits: length(a) * 8
  737. }];
  738. }
  739. n = this.state.networks[parts[0]];
  740. if (n)
  741. return [ ...(n.ipaddrs || []) ];
  742. }
  743. }
  744. return null;
  745. },
  746. parse_enum: function(val, choices) {
  747. if (type(val) == "string") {
  748. val = lc(val);
  749. for (let i = 0; i < length(choices); i++)
  750. if (lc(substr(choices[i], 0, length(val))) == val)
  751. return choices[i];
  752. }
  753. return null;
  754. },
  755. section_id: function(sid) {
  756. let s = this.get_all(sid);
  757. if (!s)
  758. return null;
  759. if (s[".anonymous"]) {
  760. let c = 0;
  761. this.cursor.foreach("firewall", s[".type"], function(ss) {
  762. if (ss[".name"] == s[".name"])
  763. return false;
  764. c++;
  765. });
  766. return `@${s['.type']}[${c}]`;
  767. }
  768. return s[".name"];
  769. },
  770. warn_section: function(s, msg) {
  771. if (s[".name"]) {
  772. if (s.name)
  773. this.warn("Section %s (%s) %s", this.section_id(s[".name"]), s.name, msg);
  774. else
  775. this.warn("Section %s %s", this.section_id(s[".name"]), msg);
  776. }
  777. else {
  778. if (s.name)
  779. this.warn("ubus %s (%s) %s", s.type || "rule", s.name, msg);
  780. else
  781. this.warn("ubus %s %s", s.type || "rule", msg);
  782. }
  783. },
  784. parse_policy: function(val) {
  785. return this.parse_enum(val, [
  786. "accept",
  787. "reject",
  788. "drop"
  789. ]);
  790. },
  791. parse_bool: function(val) {
  792. if (val == "1" || val == "on" || val == "true" || val == "yes")
  793. return true;
  794. else if (val == "0" || val == "off" || val == "false" || val == "no")
  795. return false;
  796. else
  797. return null;
  798. },
  799. parse_family: function(val) {
  800. if (val == 'any' || val == 'all' || val == '*')
  801. return 0;
  802. else if (val == 'inet' || index(val, '4') > -1)
  803. return 4;
  804. else if (index(val, '6') > -1)
  805. return 6;
  806. return null;
  807. },
  808. parse_zone_ref: function(val) {
  809. if (val == null)
  810. return null;
  811. if (val == '*')
  812. return { any: true };
  813. for (let zone in this.state.zones) {
  814. if (zone.name == val) {
  815. return {
  816. any: false,
  817. zone: zone
  818. };
  819. }
  820. }
  821. return null;
  822. },
  823. parse_device: function(val) {
  824. let rv = this.parse_invert(val);
  825. if (!rv)
  826. return null;
  827. if (rv.val == '*')
  828. rv.any = true;
  829. else
  830. rv.device = rv.val;
  831. return rv;
  832. },
  833. parse_direction: function(val) {
  834. if (val == 'in' || val == 'ingress')
  835. return false;
  836. else if (val == 'out' || val == 'egress')
  837. return true;
  838. return null;
  839. },
  840. parse_setmatch: function(val) {
  841. let rv = this.parse_invert(val);
  842. if (!rv)
  843. return null;
  844. rv.val = trim(replace(rv.val, /^[^ \t]+/, function(m) {
  845. rv.name = m;
  846. return '';
  847. }));
  848. let dir = split(rv.val, /[ \t,]/);
  849. for (let i = 0; i < 3 && i < length(dir); i++) {
  850. if (dir[i] == "dst" || dir[i] == "dest")
  851. (rv.dir ||= [])[i] = "dst";
  852. else if (dir[i] == "src")
  853. (rv.dir ||= [])[i] = "src";
  854. }
  855. return length(rv.name) ? rv : null;
  856. },
  857. parse_cthelper: function(val) {
  858. let rv = this.parse_invert(val);
  859. if (!rv)
  860. return null;
  861. let helper = filter(this.state.helpers, h => (h.name == rv.val))?.[0];
  862. return helper ? { ...rv, ...helper } : null;
  863. },
  864. parse_protocol: function(val) {
  865. let p = this.parse_invert(val);
  866. if (!p)
  867. return null;
  868. p.val = lc(p.val);
  869. switch (p.val) {
  870. case 'all':
  871. case 'any':
  872. case '*':
  873. p.any = true;
  874. break;
  875. case '1':
  876. case 'icmp':
  877. p.name = 'icmp';
  878. break;
  879. case '58':
  880. case 'icmpv6':
  881. case 'ipv6-icmp':
  882. p.name = 'ipv6-icmp';
  883. break;
  884. case 'tcpudp':
  885. return [
  886. { invert: p.invert, name: 'tcp' },
  887. { invert: p.invert, name: 'udp' }
  888. ];
  889. case '6':
  890. p.name = 'tcp';
  891. break;
  892. case '17':
  893. p.name = 'udp';
  894. break;
  895. default:
  896. p.name = p.val;
  897. }
  898. return (p.any || length(p.name)) ? p : null;
  899. },
  900. parse_mac: function(val) {
  901. let mac = this.parse_invert(val);
  902. let m = mac ? match(mac.val, /^([0-9a-f]{1,2})[:-]([0-9a-f]{1,2})[:-]([0-9a-f]{1,2})[:-]([0-9a-f]{1,2})[:-]([0-9a-f]{1,2})[:-]([0-9a-f]{1,2})$/i) : null;
  903. if (!m)
  904. return null;
  905. mac.mac = sprintf('%02x:%02x:%02x:%02x:%02x:%02x',
  906. hex(m[1]), hex(m[2]), hex(m[3]),
  907. hex(m[4]), hex(m[5]), hex(m[6]));
  908. return mac;
  909. },
  910. parse_port: function(val) {
  911. let port = this.parse_invert(val);
  912. let m = port ? match(port.val, /^([0-9]{1,5})([-:]([0-9]{1,5}))?$/i) : null;
  913. if (!m)
  914. return null;
  915. if (m[3]) {
  916. let min_port = +m[1];
  917. let max_port = +m[3];
  918. if (min_port > max_port ||
  919. min_port < 0 || max_port < 0 ||
  920. min_port > 65535 || max_port > 65535)
  921. return null;
  922. port.min = min_port;
  923. port.max = max_port;
  924. }
  925. else {
  926. let pn = +m[1];
  927. if (pn != pn || pn < 0 || pn > 65535)
  928. return null;
  929. port.min = pn;
  930. port.max = pn;
  931. }
  932. return port;
  933. },
  934. parse_network: function(val) {
  935. let rv = this.parse_invert(val);
  936. if (!rv)
  937. return null;
  938. let nets = this.parse_subnet(rv.val);
  939. if (nets === null)
  940. return null;
  941. if (length(nets))
  942. rv.addrs = [ ...nets ];
  943. return rv;
  944. },
  945. parse_icmptype: function(val) {
  946. let rv = {};
  947. if (exists(ipv4_icmptypes, val)) {
  948. rv.family = 4;
  949. rv.type = ipv4_icmptypes[val][0];
  950. rv.code_min = ipv4_icmptypes[val][1];
  951. rv.code_max = ipv4_icmptypes[val][2];
  952. }
  953. if (exists(ipv6_icmptypes, val)) {
  954. rv.family = rv.family ? 0 : 6;
  955. rv.type6 = ipv6_icmptypes[val][0];
  956. rv.code6_min = ipv6_icmptypes[val][1];
  957. rv.code6_max = ipv6_icmptypes[val][2];
  958. }
  959. if (!exists(rv, "family")) {
  960. let m = match(val, /^([0-9]+)(\/([0-9]+))?$/);
  961. if (!m)
  962. return null;
  963. if (m[3]) {
  964. rv.type = +m[1];
  965. rv.code_min = +m[3];
  966. rv.code_max = rv.code_min;
  967. }
  968. else {
  969. rv.type = +m[1];
  970. rv.code_min = 0;
  971. rv.code_max = 0xFF;
  972. }
  973. if (rv.type > 0xFF || rv.code_min > 0xFF || rv.code_max > 0xFF)
  974. return null;
  975. rv.family = 0;
  976. rv.type6 = rv.type;
  977. rv.code6_min = rv.code_min;
  978. rv.code6_max = rv.code_max;
  979. }
  980. return rv;
  981. },
  982. parse_invert: function(val) {
  983. if (val == null)
  984. return null;
  985. let rv = { invert: false };
  986. rv.val = trim(replace(val, /^[ \t]*!/, () => (rv.invert = true, '')));
  987. return length(rv.val) ? rv : null;
  988. },
  989. parse_limit: function(val) {
  990. let rv = this.parse_invert(val);
  991. let m = rv ? match(rv.val, /^([0-9]+)(\/([a-z]+))?$/) : null;
  992. if (!m)
  993. return null;
  994. let n = +m[1];
  995. let u = m[3] ? this.parse_enum(m[3], [ "second", "minute", "hour", "day" ]) : "second";
  996. if (!u)
  997. return null;
  998. rv.rate = n;
  999. rv.unit = u;
  1000. return rv;
  1001. },
  1002. parse_int: function(val) {
  1003. let n = +val;
  1004. return (n == n) ? n : null;
  1005. },
  1006. parse_date: function(val) {
  1007. let d = match(val, /^([0-9]{4})(-([0-9]{1,2})(-([0-9]{1,2})(T([0-9:]+))?)?)?$/);
  1008. if (d == null || d[1] < 1970 || d[1] > 2038 || d[3] > 12 || d[5] > 31)
  1009. return null;
  1010. let t = this.parse_time(d[7] ?? "0");
  1011. if (t == null)
  1012. return null;
  1013. return {
  1014. year: +d[1],
  1015. month: +d[3] || 1,
  1016. day: +d[5] || 1,
  1017. ...t
  1018. };
  1019. },
  1020. parse_time: function(val) {
  1021. let t = match(val, /^([0-9]{1,2})(:([0-9]{1,2})(:([0-9]{1,2}))?)?$/);
  1022. if (t == null || t[1] > 23 || t[3] > 59 || t[5] > 59)
  1023. return null;
  1024. return {
  1025. hour: +t[1],
  1026. min: +t[3],
  1027. sec: +t[5]
  1028. };
  1029. },
  1030. parse_weekdays: function(val) {
  1031. let rv = this.parse_invert(val);
  1032. if (!rv)
  1033. return null;
  1034. for (let day in to_array(rv.val)) {
  1035. day = this.parse_enum(day, [
  1036. "Monday",
  1037. "Tuesday",
  1038. "Wednesday",
  1039. "Thursday",
  1040. "Friday",
  1041. "Saturday",
  1042. "Sunday"
  1043. ]);
  1044. if (!day)
  1045. return null;
  1046. (rv.days ||= {})[day] = true;
  1047. }
  1048. rv.days = keys(rv.days);
  1049. return rv.days ? rv : null;
  1050. },
  1051. parse_monthdays: function(val) {
  1052. let rv = this.parse_invert(val);
  1053. if (!rv)
  1054. return null;
  1055. for (let day in to_array(rv.val)) {
  1056. day = +day;
  1057. if (day < 1 || day > 31)
  1058. return null;
  1059. (rv.days ||= [])[day] = true;
  1060. }
  1061. return rv.days ? rv : null;
  1062. },
  1063. parse_mark: function(val) {
  1064. let rv = this.parse_invert(val);
  1065. let m = rv ? match(rv.val, /^(0?x?[0-9a-f]+)(\/(0?x?[0-9a-f]+))?$/i) : null;
  1066. if (!m)
  1067. return null;
  1068. let n = +m[1];
  1069. if (n != n || n > 0xFFFFFFFF)
  1070. return null;
  1071. rv.mark = n;
  1072. rv.mask = 0xFFFFFFFF;
  1073. if (m[3]) {
  1074. n = +m[3];
  1075. if (n != n || n > 0xFFFFFFFF)
  1076. return null;
  1077. rv.mask = n;
  1078. }
  1079. return rv;
  1080. },
  1081. parse_dscp: function(val) {
  1082. let rv = this.parse_invert(val);
  1083. if (!rv)
  1084. return null;
  1085. rv.val = uc(rv.val);
  1086. if (exists(dscp_classes, rv.val)) {
  1087. rv.dscp = dscp_classes[rv.val];
  1088. }
  1089. else {
  1090. let n = +rv.val;
  1091. if (n != n || n < 0 || n > 0x3F)
  1092. return null;
  1093. rv.dscp = n;
  1094. }
  1095. return rv;
  1096. },
  1097. parse_target: function(val) {
  1098. return this.parse_enum(val, [
  1099. "accept",
  1100. "reject",
  1101. "drop",
  1102. "notrack",
  1103. "helper",
  1104. "mark",
  1105. "dscp",
  1106. "dnat",
  1107. "snat",
  1108. "masquerade",
  1109. "accept",
  1110. "reject",
  1111. "drop"
  1112. ]);
  1113. },
  1114. parse_reject_code: function(val) {
  1115. return this.parse_enum(val, [
  1116. "tcp-reset",
  1117. "port-unreachable",
  1118. "admin-prohibited",
  1119. "host-unreachable",
  1120. "no-route"
  1121. ]);
  1122. },
  1123. parse_reflection_source: function(val) {
  1124. return this.parse_enum(val, [
  1125. "internal",
  1126. "external"
  1127. ]);
  1128. },
  1129. parse_ipsettype: function(val) {
  1130. let m = match(val, /^(src|dst|dest)_(.+)$/);
  1131. let t = this.parse_enum(m ? m[2] : val, [
  1132. "ip",
  1133. "port",
  1134. "mac",
  1135. "net",
  1136. "set"
  1137. ]);
  1138. return t ? [ (!m || m[1] == 'src') ? 'src' : 'dst', t ] : null;
  1139. },
  1140. parse_ipsetentry: function(val, set) {
  1141. let values = split(val, /[ \t]+/);
  1142. if (length(values) != length(set.types))
  1143. return null;
  1144. let rv = [];
  1145. let ip, mac, port;
  1146. for (let i, t in set.types) {
  1147. switch (t) {
  1148. case 'ipv4_addr':
  1149. ip = filter(this.parse_subnet(values[i]), a => (a.family == 4));
  1150. switch (length(ip) ?? 0) {
  1151. case 0: return null;
  1152. case 1: break;
  1153. default: this.warn("Set entry '%s' resolves to multiple addresses, using first one", values[i]);
  1154. }
  1155. rv[i] = ("net" in set.fw4types) ? `${ip[0].addr}/${ip[0].bits}` : ip[0].addr;
  1156. break;
  1157. case 'ipv6_addr':
  1158. ip = filter(this.parse_subnet(values[i]), a => (a.family == 6));
  1159. switch (length(ip) ?? 0) {
  1160. case 0: return null;
  1161. case 1: break;
  1162. case 2: this.warn("Set entry '%s' resolves to multiple addresses, using first one", values[i]);
  1163. }
  1164. rv[i] = ("net" in set.fw4types) ? `${ip[0].addr}/${ip[0].bits}` : ip[0].addr;
  1165. break;
  1166. case 'ether_addr':
  1167. mac = this.parse_mac(values[i]);
  1168. if (!mac || mac.invert)
  1169. return null;
  1170. rv[i] = mac.mac;
  1171. break;
  1172. case 'inet_service':
  1173. port = this.parse_port(values[i]);
  1174. if (!port || port.invert || port.min != port.max)
  1175. return null;
  1176. rv[i] = port.min;
  1177. break;
  1178. default:
  1179. rv[i] = values[i];
  1180. }
  1181. }
  1182. return length(rv) ? rv : null;
  1183. },
  1184. parse_includetype: function(val) {
  1185. return this.parse_enum(val, [
  1186. "script",
  1187. "nftables"
  1188. ]);
  1189. },
  1190. parse_includeposition: function(val) {
  1191. return replace(this.parse_enum(val, [
  1192. "ruleset-prepend",
  1193. "ruleset-postpend",
  1194. "ruleset-append",
  1195. "table-prepend",
  1196. "table-postpend",
  1197. "table-append",
  1198. "chain-prepend",
  1199. "chain-postpend",
  1200. "chain-append"
  1201. ]), "postpend", "append");
  1202. },
  1203. parse_identifier: function(val) {
  1204. return match(val, /^[a-zA-Z_.][a-zA-Z0-9\/_.-]*$/)?.[0];
  1205. },
  1206. parse_string: function(val) {
  1207. return "" + val;
  1208. },
  1209. parse_opt: function(s, opt, fn, defval, flags) {
  1210. let val = s[opt];
  1211. if (val === null) {
  1212. if (flags & REQUIRED) {
  1213. this.warn_section(s, `option '${opt}' is mandatory but not set`);
  1214. return NaN;
  1215. }
  1216. val = defval;
  1217. }
  1218. if (type(val) == "array") {
  1219. this.warn_section(s, `option '${opt}' must not be a list`);
  1220. return NaN;
  1221. }
  1222. else if (val == null) {
  1223. return null;
  1224. }
  1225. let res = this[fn](val);
  1226. if (res === null) {
  1227. this.warn_section(s, `option '${opt}' specifies invalid value '${val}'`);
  1228. return NaN;
  1229. }
  1230. return res;
  1231. },
  1232. parse_list: function(s, opt, fn, defval, flags) {
  1233. let val = s[opt];
  1234. let rv = [];
  1235. if (val == null) {
  1236. if (flags & REQUIRED) {
  1237. this.warn_section(s, `option '${opt}' is mandatory but not set`);
  1238. return NaN;
  1239. }
  1240. val = defval;
  1241. }
  1242. for (val in to_array(val)) {
  1243. let res = this[fn](val);
  1244. if (res === null) {
  1245. this.warn_section(s, `option '${opt}' specifies invalid value '${val}'`);
  1246. return NaN;
  1247. }
  1248. if (flags & FLATTEN_LIST)
  1249. push(rv, ...to_array(res));
  1250. else
  1251. push(rv, res);
  1252. }
  1253. return length(rv) ? rv : null;
  1254. },
  1255. quote: function(s, force) {
  1256. if (force === true || !match(s, /^([0-9A-Fa-f:.\/-]+)( \. [0-9A-Fa-f:.\/-]+)*$/))
  1257. return `"${replace(s, '"', "'")}"`;
  1258. return s;
  1259. },
  1260. cidr: function(a) {
  1261. if (a.range)
  1262. return `${a.addr}-${a.addr2}`;
  1263. if ((a.family == 4 && a.bits == 32) ||
  1264. (a.family == 6 && a.bits == 128))
  1265. return a.addr;
  1266. if (a.bits >= 0)
  1267. return `${apply_mask(a.addr, a.bits)}/${a.bits}`;
  1268. return `${a.addr}/${a.mask}`;
  1269. },
  1270. host: function(a, v6brackets) {
  1271. return a.range
  1272. ? `${a.addr}-${a.addr2}`
  1273. : (a.family == 6 && v6brackets)
  1274. ? `[${apply_mask(a.addr, a.bits)}]` : apply_mask(a.addr, a.bits);
  1275. },
  1276. port: function(p) {
  1277. if (p.min == p.max)
  1278. return `${p.min}`;
  1279. return `${p.min}-${p.max}`;
  1280. },
  1281. set: function(v, force) {
  1282. let seen = {};
  1283. v = filter(to_array(v), item => !seen[item]++);
  1284. if (force || length(v) != 1)
  1285. return `{ ${join(', ', map(v, this.quote))} }`;
  1286. return this.quote(v[0]);
  1287. },
  1288. concat: function(v) {
  1289. return join(' . ', to_array(v));
  1290. },
  1291. ipproto: function(family) {
  1292. switch (family) {
  1293. case 4:
  1294. return "ip";
  1295. case 6:
  1296. return "ip6";
  1297. }
  1298. },
  1299. nfproto: function(family, human_readable) {
  1300. switch (family) {
  1301. case 4:
  1302. return human_readable ? "IPv4" : "ipv4";
  1303. case 6:
  1304. return human_readable ? "IPv6" : "ipv6";
  1305. default:
  1306. return human_readable ? "IPv4/IPv6" : null;
  1307. }
  1308. },
  1309. l4proto: function(family, proto) {
  1310. switch (proto.name) {
  1311. case 'icmp':
  1312. switch (family ?? 0) {
  1313. case 0:
  1314. return this.set(['icmp', 'ipv6-icmp']);
  1315. case 6:
  1316. return 'ipv6-icmp';
  1317. }
  1318. default:
  1319. return proto.name;
  1320. }
  1321. },
  1322. datetime: function(stamp) {
  1323. return sprintf('"%04d-%02d-%02d %02d:%02d:%02d"',
  1324. stamp.year, stamp.month, stamp.day,
  1325. stamp.hour, stamp.min, stamp.sec);
  1326. },
  1327. date: function(stamp) {
  1328. return sprintf('"%04d-%02d-%02d"', stamp.year, stamp.month, stamp.day);
  1329. },
  1330. datestamp: function(stamp) {
  1331. return exists(stamp, 'hour') ? this.datetime(stamp) : this.date(stamp);
  1332. },
  1333. time: function(stamp) {
  1334. return sprintf('"%02d:%02d:%02d"', stamp.hour, stamp.min, stamp.sec);
  1335. },
  1336. hex: function(n) {
  1337. return sprintf('0x%x', n);
  1338. },
  1339. is_loopback_dev: function(dev) {
  1340. return !!(+fs.readfile(`/sys/class/net/${dev}/flags`) & 0x8);
  1341. },
  1342. is_loopback_addr: function(addr) {
  1343. return (index(addr, "127.") == 0 || addr == "::1" || addr == "::1/128");
  1344. },
  1345. filter_loopback_devs: function(devs, invert) {
  1346. return null_if_empty(filter(devs, d => (this.is_loopback_dev(d) == invert)));
  1347. },
  1348. filter_loopback_addrs: function(addrs, invert) {
  1349. return null_if_empty(filter(addrs, a => (this.is_loopback_addr(a) == invert)));
  1350. },
  1351. input_policy: function(reject_as_drop) {
  1352. return (!reject_as_drop || this.state.defaults.input != 'reject') ? this.state.defaults.input : 'drop';
  1353. },
  1354. output_policy: function(reject_as_drop) {
  1355. return (!reject_as_drop || this.state.defaults.output != 'reject') ? this.state.defaults.output : 'drop';
  1356. },
  1357. forward_policy: function(reject_as_drop) {
  1358. return (!reject_as_drop || this.state.defaults.forward != 'reject') ? this.state.defaults.forward : 'drop';
  1359. },
  1360. default_option: function(flag) {
  1361. return this.state.defaults[flag];
  1362. },
  1363. helpers: function() {
  1364. return this.state.helpers;
  1365. },
  1366. zones: function() {
  1367. return this.state.zones;
  1368. },
  1369. rules: function(chain) {
  1370. return filter(this.state.rules, r => (r.chain == chain));
  1371. },
  1372. redirects: function(chain) {
  1373. return filter(this.state.redirects, r => (r.chain == chain));
  1374. },
  1375. ipsets: function() {
  1376. return this.state.ipsets;
  1377. },
  1378. includes: function(position, chain) {
  1379. let stmts = [];
  1380. let pad = '';
  1381. let pre = '';
  1382. switch (position) {
  1383. case 'table-prepend':
  1384. case 'table-append':
  1385. pad = '\t';
  1386. pre = '\n';
  1387. break;
  1388. case 'chain-prepend':
  1389. case 'chain-append':
  1390. pad = '\t\t';
  1391. break;
  1392. default:
  1393. pre = '\n';
  1394. }
  1395. push(stmts, pre);
  1396. for (let inc in this.state.includes)
  1397. if (inc.type == 'nftables' && inc.position == position && (!chain || inc.chain == chain))
  1398. push(stmts, `${pad}include "${inc.path}"\n`);
  1399. print(length(stmts) > 1 ? join('', stmts) : '');
  1400. },
  1401. parse_setfile: function(set, cb) {
  1402. let fd = fs.open(set.loadfile, "r");
  1403. if (!fd) {
  1404. warn(`Unable to load file '${set.loadfile}' for set '${set.name}': ${fs.error()}\n`);
  1405. return;
  1406. }
  1407. let count = 0;
  1408. for (let line = fd.read("line"); length(line); line = fd.read("line")) {
  1409. line = trim(line);
  1410. if (length(line) == 0 || ord(line) == 35)
  1411. continue;
  1412. let v = this.parse_ipsetentry(line, set);
  1413. if (!v) {
  1414. this.warn(`Skipping invalid entry '${line}' in file '${set.loadfile}' for set '${set.name}'`);
  1415. continue;
  1416. }
  1417. cb(v);
  1418. count++;
  1419. }
  1420. fd.close();
  1421. return count;
  1422. },
  1423. print_setentries: function(set) {
  1424. let first = true;
  1425. let printer = (entry) => {
  1426. if (first) {
  1427. print("\t\telements = {\n");
  1428. first = false;
  1429. }
  1430. print("\t\t\t", join(" . ", entry), ",\n");
  1431. };
  1432. map(set.entries, printer);
  1433. if (set.loadfile)
  1434. this.parse_setfile(set, printer);
  1435. if (!first)
  1436. print("\t\t}\n");
  1437. },
  1438. parse_helper: function(data) {
  1439. let helper = this.parse_options(data, {
  1440. name: [ "string", null, REQUIRED ],
  1441. description: [ "string" ],
  1442. module: [ "string" ],
  1443. family: [ "family" ],
  1444. proto: [ "protocol", null, PARSE_LIST | FLATTEN_LIST | NO_INVERT ],
  1445. port: [ "port", null, NO_INVERT ]
  1446. });
  1447. if (helper === false) {
  1448. this.warn("Helper definition '%s' skipped due to invalid options", data.name || data['.name']);
  1449. return;
  1450. }
  1451. else if (helper.proto.any) {
  1452. this.warn("Helper definition '%s' must not specify wildcard protocol", data.name || data['.name']);
  1453. return;
  1454. }
  1455. else if (length(helper.proto) > 1) {
  1456. this.warn("Helper definition '%s' must not specify multiple protocols", data.name || data['.name']);
  1457. return;
  1458. }
  1459. helper.available = (fs.stat(`/sys/module/${helper.module}`)?.type == "directory");
  1460. push(this.state.helpers ||= [], helper);
  1461. },
  1462. parse_defaults: function(data) {
  1463. if (this.state.defaults) {
  1464. this.warn_section(data, ": ignoring duplicate defaults section");
  1465. return;
  1466. }
  1467. let defs = this.parse_options(data, {
  1468. input: [ "policy", "drop" ],
  1469. output: [ "policy", "drop" ],
  1470. forward: [ "policy", "drop" ],
  1471. drop_invalid: [ "bool" ],
  1472. tcp_reject_code: [ "reject_code", "tcp-reset" ],
  1473. any_reject_code: [ "reject_code", "port-unreachable" ],
  1474. syn_flood: [ "bool" ],
  1475. synflood_protect: [ "bool" ],
  1476. synflood_rate: [ "limit", "25/second" ],
  1477. synflood_burst: [ "int", "50" ],
  1478. tcp_syncookies: [ "bool", "1" ],
  1479. tcp_ecn: [ "int" ],
  1480. tcp_window_scaling: [ "bool", "1" ],
  1481. accept_redirects: [ "bool" ],
  1482. accept_source_route: [ "bool" ],
  1483. auto_helper: [ "bool", "1" ],
  1484. custom_chains: [ "bool", null, UNSUPPORTED ],
  1485. disable_ipv6: [ "bool", null, UNSUPPORTED ],
  1486. flow_offloading: [ "bool", "0" ],
  1487. flow_offloading_hw: [ "bool", "0" ],
  1488. auto_includes: [ "bool", "1" ]
  1489. });
  1490. if (defs.synflood_protect === null)
  1491. defs.synflood_protect = defs.syn_flood;
  1492. delete defs.syn_flood;
  1493. this.state.defaults = defs;
  1494. },
  1495. parse_zone: function(data) {
  1496. let zone = this.parse_options(data, {
  1497. enabled: [ "bool", "1" ],
  1498. name: [ "identifier", null, REQUIRED ],
  1499. family: [ "family" ],
  1500. network: [ "device", null, PARSE_LIST ],
  1501. device: [ "device", null, PARSE_LIST ],
  1502. subnet: [ "network", null, PARSE_LIST ],
  1503. input: [ "policy", this.state.defaults ? this.state.defaults.input : "drop" ],
  1504. output: [ "policy", this.state.defaults ? this.state.defaults.output : "drop" ],
  1505. forward: [ "policy", this.state.defaults ? this.state.defaults.forward : "drop" ],
  1506. masq: [ "bool" ],
  1507. masq_allow_invalid: [ "bool" ],
  1508. masq_src: [ "network", null, PARSE_LIST ],
  1509. masq_dest: [ "network", null, PARSE_LIST ],
  1510. masq6: [ "bool" ],
  1511. extra: [ "string", null, UNSUPPORTED ],
  1512. extra_src: [ "string", null, UNSUPPORTED ],
  1513. extra_dest: [ "string", null, UNSUPPORTED ],
  1514. mtu_fix: [ "bool" ],
  1515. custom_chains: [ "bool", null, UNSUPPORTED ],
  1516. log: [ "int" ],
  1517. log_limit: [ "limit" ],
  1518. auto_helper: [ "bool", "1" ],
  1519. helper: [ "cthelper", null, PARSE_LIST ],
  1520. counter: [ "bool", "1" ]
  1521. });
  1522. if (zone === false) {
  1523. this.warn_section(data, "skipped due to invalid options");
  1524. return;
  1525. }
  1526. else if (!zone.enabled) {
  1527. this.warn_section(data, "is disabled, ignoring section");
  1528. return;
  1529. }
  1530. for (let helper in zone.helper) {
  1531. if (!helper.available) {
  1532. this.warn_section(data, `uses unavailable ct helper '${zone.helper.name}'`);
  1533. }
  1534. }
  1535. if (zone.mtu_fix && this.kernel < 0x040a0000) {
  1536. this.warn_section(data, "option 'mtu_fix' requires kernel 4.10 or later");
  1537. return;
  1538. }
  1539. if (this.state.defaults?.auto_helper === false)
  1540. zone.auto_helper = false;
  1541. let match_devices = [];
  1542. let related_physdevs = [];
  1543. let related_subnets = [];
  1544. let related_ubus_networks = [];
  1545. let match_subnets, masq_src_subnets, masq_dest_subnets;
  1546. for (let name, net in this.state.networks) {
  1547. if (net.zone === zone.name)
  1548. push(related_ubus_networks, { invert: false, device: name });
  1549. }
  1550. zone.network = [ ...to_array(zone.network), ...related_ubus_networks ];
  1551. for (let e in zone.network) {
  1552. if (exists(this.state.networks, e.device)) {
  1553. let net = this.state.networks[e.device];
  1554. if (net.device) {
  1555. push(match_devices, {
  1556. invert: e.invert,
  1557. device: net.device
  1558. });
  1559. }
  1560. if (net.physdev && !e.invert)
  1561. push(related_physdevs, net.physdev);
  1562. push(related_subnets, ...(net.ipaddrs || []));
  1563. }
  1564. }
  1565. push(match_devices, ...to_array(zone.device));
  1566. match_subnets = subnets_split_af(zone.subnet);
  1567. masq_src_subnets = subnets_split_af(zone.masq_src);
  1568. masq_dest_subnets = subnets_split_af(zone.masq_dest);
  1569. push(related_subnets, ...(match_subnets[0] || []), ...(match_subnets[1] || []));
  1570. let match_rules = [];
  1571. let add_rule = (family, devices, subnets, zone) => {
  1572. let r = {};
  1573. r.family = family;
  1574. r.devices_pos = null_if_empty(devices[0]);
  1575. r.devices_neg = null_if_empty(devices[1]);
  1576. r.devices_neg_wildcard = null_if_empty(devices[2]);
  1577. r.subnets_pos = map(subnets[0], this.cidr);
  1578. r.subnets_neg = map(subnets[1], this.cidr);
  1579. r.subnets_masked = subnets[2];
  1580. push(match_rules, r);
  1581. };
  1582. let family = infer_family(zone.family, [
  1583. match_subnets, "subnet list"
  1584. ]);
  1585. if (type(family) == "string") {
  1586. this.warn_section(data, `${family}, skipping`);
  1587. return;
  1588. }
  1589. // group non-inverted device matches into wildcard and non-wildcard ones
  1590. let devices = [], plain_devices = [], plain_invert_devices = [], wildcard_invert_devices = [];
  1591. for (let device in match_devices) {
  1592. let m = match(device.device, /^([^+]*)(\+)?$/);
  1593. if (!m) {
  1594. this.warn_section(data, `skipping invalid wildcard pattern '${device.device}'`);
  1595. continue;
  1596. }
  1597. // filter `+` (match any device) since nftables does not support
  1598. // wildcard only matches
  1599. if (!device.invert && m[0] == '+')
  1600. continue;
  1601. // replace inverted `+` (match no device) with invalid pattern
  1602. if (device.invert && m[0] == '+') {
  1603. device.device = '/never/';
  1604. device.invert = false;
  1605. }
  1606. // replace "name+" matches with "name*"
  1607. else if (m[2] == '+')
  1608. device.device = m[1] + '*';
  1609. device.wildcard = !!m[2];
  1610. if (!device.invert && device.wildcard)
  1611. push(devices, [ [ device.device ], plain_invert_devices, wildcard_invert_devices ]);
  1612. else if (!device.invert)
  1613. push(plain_devices, device.device);
  1614. else if (device.wildcard)
  1615. push(wildcard_invert_devices, device.device);
  1616. else
  1617. push(plain_invert_devices, device.device);
  1618. }
  1619. if (length(plain_devices))
  1620. push(devices, [
  1621. plain_devices,
  1622. plain_invert_devices,
  1623. wildcard_invert_devices
  1624. ]);
  1625. else if (!length(devices))
  1626. push(devices, [
  1627. null,
  1628. plain_invert_devices,
  1629. wildcard_invert_devices
  1630. ]);
  1631. // emit zone jump rules for each device group
  1632. if (length(match_devices) || length(match_subnets[0]) || length(match_subnets[1])) {
  1633. for (let devgroup in devices) {
  1634. // check if there's no AF specific bits, in this case we can do AF agnostic matching
  1635. if (!family && !length(match_subnets[0]) && !length(match_subnets[1])) {
  1636. add_rule(0, devgroup, [], zone);
  1637. }
  1638. // we need to emit one or two AF specific rules
  1639. else {
  1640. if (!family || family == 4)
  1641. for (let subnets in subnets_group_by_masking(match_subnets[0]))
  1642. add_rule(4, devgroup, subnets, zone);
  1643. if (!family || family == 6)
  1644. for (let subnets in subnets_group_by_masking(match_subnets[1]))
  1645. add_rule(6, devgroup, subnets, zone);
  1646. }
  1647. }
  1648. }
  1649. zone.family = family;
  1650. zone.match_rules = match_rules;
  1651. zone.masq4_src_subnets = subnets_group_by_masking(masq_src_subnets[0]);
  1652. zone.masq4_dest_subnets = subnets_group_by_masking(masq_dest_subnets[0]);
  1653. zone.masq6_src_subnets = subnets_group_by_masking(masq_src_subnets[1]);
  1654. zone.masq6_dest_subnets = subnets_group_by_masking(masq_dest_subnets[1]);
  1655. zone.sflags = {};
  1656. zone.sflags[zone.input] = true;
  1657. zone.dflags = {};
  1658. zone.dflags[zone.output] = true;
  1659. zone.dflags[zone.forward] = true;
  1660. zone.match_devices = map(filter(match_devices, d => !d.invert), d => d.device);
  1661. zone.match_subnets = map(filter(related_subnets, s => !s.invert && s.bits != -1), this.cidr);
  1662. zone.related_subnets = related_subnets;
  1663. zone.related_physdevs = related_physdevs;
  1664. if (zone.masq || zone.masq6)
  1665. zone.dflags.snat = true;
  1666. if ((zone.auto_helper && !(zone.masq || zone.masq6)) || length(zone.helper)) {
  1667. zone.dflags.helper = true;
  1668. for (let helper in (length(zone.helper) ? zone.helper : this.state.helpers)) {
  1669. if (!helper.available)
  1670. continue;
  1671. for (let proto in helper.proto) {
  1672. push(this.state.rules ||= [], {
  1673. chain: `helper_${zone.name}`,
  1674. family: helper.family,
  1675. name: helper.description || helper.name,
  1676. proto: proto,
  1677. src: zone,
  1678. dports_pos: [ this.port(helper.port) ],
  1679. target: "helper",
  1680. set_helper: helper
  1681. });
  1682. }
  1683. }
  1684. }
  1685. push(this.state.zones ||= [], zone);
  1686. },
  1687. parse_forwarding: function(data) {
  1688. let fwd = this.parse_options(data, {
  1689. enabled: [ "bool", "1" ],
  1690. name: [ "string" ],
  1691. family: [ "family" ],
  1692. src: [ "zone_ref", null, REQUIRED ],
  1693. dest: [ "zone_ref", null, REQUIRED ]
  1694. });
  1695. if (fwd === false) {
  1696. this.warn_section(data, "skipped due to invalid options");
  1697. return;
  1698. }
  1699. else if (!fwd.enabled) {
  1700. this.warn_section(data, "is disabled, ignoring section");
  1701. return;
  1702. }
  1703. let add_rule = (family, fwd) => {
  1704. let f = {
  1705. ...fwd,
  1706. family: family,
  1707. proto: { any: true }
  1708. };
  1709. f.name ||= `Accept ${fwd.src.any ? "any" : fwd.src.zone.name} to ${fwd.dest.any ? "any" : fwd.dest.zone.name} ${family ? `${this.nfproto(family, true)} ` : ''}forwarding`;
  1710. f.chain = fwd.src.any ? "forward" : `forward_${fwd.src.zone.name}`;
  1711. if (fwd.dest.any)
  1712. f.target = "accept";
  1713. else
  1714. f.jump_chain = `accept_to_${fwd.dest.zone.name}`;
  1715. push(this.state.rules ||= [], f);
  1716. };
  1717. /* inherit family restrictions from related zones */
  1718. let family = infer_family(fwd.family, [
  1719. fwd.src?.zone, "source zone",
  1720. fwd.dest?.zone, "destination zone"
  1721. ]);
  1722. if (type(family) == "string") {
  1723. this.warn_section(data, `${family}, skipping`);
  1724. return;
  1725. }
  1726. add_rule(family, fwd);
  1727. if (fwd.dest.zone)
  1728. fwd.dest.zone.dflags.accept = true;
  1729. },
  1730. parse_rule: function(data) {
  1731. let rule = this.parse_options(data, {
  1732. enabled: [ "bool", "1" ],
  1733. name: [ "string", this.section_id(data[".name"]) ],
  1734. _name: [ "string", null, DEPRECATED ],
  1735. family: [ "family" ],
  1736. src: [ "zone_ref" ],
  1737. dest: [ "zone_ref" ],
  1738. device: [ "device", null, NO_INVERT ],
  1739. direction: [ "direction" ],
  1740. ipset: [ "setmatch" ],
  1741. helper: [ "cthelper" ],
  1742. set_helper: [ "cthelper", null, NO_INVERT ],
  1743. proto: [ "protocol", "tcpudp", PARSE_LIST | FLATTEN_LIST ],
  1744. src_ip: [ "network", null, PARSE_LIST ],
  1745. src_mac: [ "mac", null, PARSE_LIST ],
  1746. src_port: [ "port", null, PARSE_LIST ],
  1747. dest_ip: [ "network", null, PARSE_LIST ],
  1748. dest_port: [ "port", null, PARSE_LIST ],
  1749. icmp_type: [ "icmptype", null, PARSE_LIST ],
  1750. extra: [ "string", null, UNSUPPORTED ],
  1751. limit: [ "limit" ],
  1752. limit_burst: [ "int" ],
  1753. utc_time: [ "bool" ],
  1754. start_date: [ "date" ],
  1755. stop_date: [ "date" ],
  1756. start_time: [ "time" ],
  1757. stop_time: [ "time" ],
  1758. weekdays: [ "weekdays" ],
  1759. monthdays: [ "monthdays", null, UNSUPPORTED ],
  1760. mark: [ "mark" ],
  1761. set_mark: [ "mark", null, NO_INVERT ],
  1762. set_xmark: [ "mark", null, NO_INVERT ],
  1763. dscp: [ "dscp" ],
  1764. set_dscp: [ "dscp", null, NO_INVERT ],
  1765. counter: [ "bool", "1" ],
  1766. log: [ "string" ],
  1767. log_limit: [ "limit" ],
  1768. target: [ "target" ]
  1769. });
  1770. if (rule === false) {
  1771. this.warn_section(data, "skipped due to invalid options");
  1772. return;
  1773. }
  1774. else if (!rule.enabled) {
  1775. this.warn_section(data, "is disabled, ignoring section");
  1776. return;
  1777. }
  1778. if (rule.target in ["helper", "notrack"] && (!rule.src || !rule.src.zone)) {
  1779. this.warn_section(data, `must specify a source zone for target '${rule.target}'`);
  1780. return;
  1781. }
  1782. else if (rule.target == "dscp" && !rule.set_dscp) {
  1783. this.warn_section(data, "must specify option 'set_dscp' for target 'dscp'");
  1784. return;
  1785. }
  1786. else if (rule.target == "mark" && !rule.set_mark && !rule.set_xmark) {
  1787. this.warn_section(data, "must specify option 'set_mark' or 'set_xmark' for target 'mark'");
  1788. return;
  1789. }
  1790. else if (rule.target == "helper" && !rule.set_helper) {
  1791. this.warn_section(data, "must specify option 'set_helper' for target 'helper'");
  1792. return;
  1793. }
  1794. else if (rule.device?.any) {
  1795. this.warn_section(data, "must not specify '*' as device");
  1796. return;
  1797. }
  1798. switch (this.parse_bool(rule.log)) {
  1799. case true:
  1800. rule.log = `${rule.name}: `;
  1801. break;
  1802. case false:
  1803. delete rule.log;
  1804. }
  1805. let ipset;
  1806. if (rule.ipset) {
  1807. ipset = filter(this.state.ipsets, s => (s.name == rule.ipset.name))?.[0];
  1808. if (!ipset) {
  1809. this.warn_section(data, `references unknown set '${rule.ipset.name}'`);
  1810. return;
  1811. }
  1812. if (('inet_service' in ipset.types) && !ensure_tcpudp(rule.proto)) {
  1813. this.warn_section(data, "references named set with port match but no UDP/TCP protocol, ignoring section");
  1814. return;
  1815. }
  1816. }
  1817. let need_src_action_chain = (rule) => (rule.src?.zone?.log && rule.target != "accept");
  1818. let add_rule = (family, proto, saddrs, daddrs, sports, dports, icmptypes, icmpcodes, ipset, rule) => {
  1819. let r = {
  1820. ...rule,
  1821. family: family,
  1822. proto: proto,
  1823. has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
  1824. has_ports: !!(length(sports) || length(dports)),
  1825. saddrs_pos: map(saddrs[0], this.cidr),
  1826. saddrs_neg: map(saddrs[1], this.cidr),
  1827. saddrs_masked: saddrs[2],
  1828. daddrs_pos: map(daddrs[0], this.cidr),
  1829. daddrs_neg: map(daddrs[1], this.cidr),
  1830. daddrs_masked: daddrs[2],
  1831. sports_pos: map(filter_pos(sports), this.port),
  1832. sports_neg: map(filter_neg(sports), this.port),
  1833. dports_pos: map(filter_pos(dports), this.port),
  1834. dports_neg: map(filter_neg(dports), this.port),
  1835. smacs_pos: map(filter_pos(rule.src_mac), m => m.mac),
  1836. smacs_neg: map(filter_neg(rule.src_mac), m => m.mac),
  1837. icmp_types: map(icmptypes, i => (family == 4 ? i.type : i.type6)),
  1838. icmp_codes: map(icmpcodes, ic => `${(family == 4) ? ic.type : ic.type6} . ${(family == 4) ? ic.code_min : ic.code6_min}`)
  1839. };
  1840. if (!length(r.icmp_types))
  1841. delete r.icmp_types;
  1842. if (!length(r.icmp_codes))
  1843. delete r.icmp_codes;
  1844. if (r.set_mark) {
  1845. r.set_xmark = {
  1846. invert: r.set_mark.invert,
  1847. mark: r.set_mark.mark,
  1848. mask: r.set_mark.mark | r.set_mark.mask
  1849. };
  1850. delete r.set_mark;
  1851. }
  1852. let set_types = map_setmatch(ipset, rule.ipset, proto.name);
  1853. if (set_types !== set_types) {
  1854. this.warn_section(data, "destination MAC address matching not supported");
  1855. return;
  1856. } else if (set_types) {
  1857. r.ipset = { ...r.ipset, fields: set_types };
  1858. }
  1859. if (r.target == "notrack") {
  1860. r.chain = `notrack_${r.src.zone.name}`;
  1861. r.src.zone.dflags.notrack = true;
  1862. }
  1863. else if (r.target == "helper") {
  1864. r.chain = `helper_${r.src.zone.name}`;
  1865. r.src.zone.dflags.helper = true;
  1866. }
  1867. else if (r.target == "mark" || r.target == "dscp") {
  1868. if ((r.src?.any && r.dest?.any) || (r.src?.zone && r.dest?.zone))
  1869. r.chain = "mangle_forward";
  1870. else if (r.src?.any && r.dest?.zone)
  1871. r.chain = "mangle_postrouting";
  1872. else if (r.src?.zone && r.dest?.any)
  1873. r.chain = "mangle_prerouting";
  1874. else if (r.src && !r.dest)
  1875. r.chain = "mangle_input";
  1876. else
  1877. r.chain = "mangle_output";
  1878. if (r.src?.zone) {
  1879. r.src.zone.dflags[r.target] = true;
  1880. r.iifnames = null_if_empty(r.src.zone.match_devices);
  1881. }
  1882. if (r.dest?.zone) {
  1883. r.dest.zone.dflags[r.target] = true;
  1884. r.oifnames = null_if_empty(r.dest.zone.match_devices);
  1885. }
  1886. }
  1887. else {
  1888. r.chain = "output";
  1889. if (r.src) {
  1890. if (!r.src.any)
  1891. r.chain = `${r.dest ? "forward" : "input"}_${r.src.zone.name}`;
  1892. else
  1893. r.chain = r.dest ? "forward" : "input";
  1894. }
  1895. if (r.dest && !r.src) {
  1896. if (!r.dest.any)
  1897. r.chain = sprintf("output_%s", r.dest.zone.name);
  1898. else
  1899. r.chain = "output";
  1900. }
  1901. if (r.target && r.dest && !r.dest.any) {
  1902. r.jump_chain = `${r.target}_to_${r.dest.zone.name}`;
  1903. r.dest.zone.dflags[r.target] = true;
  1904. }
  1905. else if (r.target && need_src_action_chain(r)) {
  1906. r.jump_chain = `${r.target}_from_${r.src.zone.name}`;
  1907. r.src.zone.sflags[r.target] = true;
  1908. }
  1909. else if (r.target == "reject")
  1910. r.jump_chain = "handle_reject";
  1911. }
  1912. if (r.device)
  1913. r[r.direction ? "oifnames" : "iifnames"] = [ r.device.device ];
  1914. push(this.state.rules ||= [], r);
  1915. };
  1916. for (let proto in rule.proto) {
  1917. let sip, dip, sports, dports, itypes4, itypes6;
  1918. let family = rule.family;
  1919. switch (proto.name) {
  1920. case "icmp":
  1921. itypes4 = filter(rule.icmp_type || [], family_is_ipv4);
  1922. itypes6 = filter(rule.icmp_type || [], family_is_ipv6);
  1923. break;
  1924. case "ipv6-icmp":
  1925. family = 6;
  1926. itypes6 = filter(rule.icmp_type || [], family_is_ipv6);
  1927. break;
  1928. case "tcp":
  1929. case "udp":
  1930. sports = rule.src_port;
  1931. dports = rule.dest_port;
  1932. break;
  1933. }
  1934. sip = subnets_split_af(rule.src_ip);
  1935. dip = subnets_split_af(rule.dest_ip);
  1936. family = infer_family(family, [
  1937. ipset, "set match",
  1938. sip, "source IP",
  1939. dip, "destination IP",
  1940. rule.src?.zone, "source zone",
  1941. rule.dest?.zone, "destination zone",
  1942. rule.helper, "helper match",
  1943. rule.set_helper, "helper to set"
  1944. ]);
  1945. if (type(family) == "string") {
  1946. this.warn_section(data, `${family}, skipping`);
  1947. continue;
  1948. }
  1949. let has_ipv4_specifics = (length(sip[0]) || length(dip[0]) || length(itypes4) || rule.dscp !== null);
  1950. let has_ipv6_specifics = (length(sip[1]) || length(dip[1]) || length(itypes6) || rule.dscp !== null);
  1951. /* if no family was configured, infer target family from IP addresses */
  1952. if (family === null) {
  1953. if (has_ipv4_specifics && !has_ipv6_specifics)
  1954. family = 4;
  1955. else if (has_ipv6_specifics && !has_ipv4_specifics)
  1956. family = 6;
  1957. else
  1958. family = 0;
  1959. }
  1960. /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
  1961. if (!family && rule.target != "dscp" && !has_ipv4_specifics && !has_ipv6_specifics) {
  1962. add_rule(0, proto, [], [], sports, dports, null, null, null, rule);
  1963. }
  1964. /* we need to emit one or two AF specific rules */
  1965. else {
  1966. if (family == 0 || family == 4) {
  1967. let icmp_types = filter(itypes4, i => (i.code_min == 0 && i.code_max == 0xFF));
  1968. let icmp_codes = filter(itypes4, i => (i.code_min != 0 || i.code_max != 0xFF));
  1969. for (let saddrs in subnets_group_by_masking(sip[0])) {
  1970. for (let daddrs in subnets_group_by_masking(dip[0])) {
  1971. if (length(icmp_types) || (!length(icmp_types) && !length(icmp_codes)))
  1972. add_rule(4, proto, saddrs, daddrs, sports, dports, icmp_types, null, ipset, rule);
  1973. if (length(icmp_codes))
  1974. add_rule(4, proto, saddrs, daddrs, sports, dports, null, icmp_codes, ipset, rule);
  1975. }
  1976. }
  1977. }
  1978. if (family == 0 || family == 6) {
  1979. let icmp_types = filter(itypes6, i => (i.code_min == 0 && i.code_max == 0xFF));
  1980. let icmp_codes = filter(itypes6, i => (i.code_min != 0 || i.code_max != 0xFF));
  1981. for (let saddrs in subnets_group_by_masking(sip[1])) {
  1982. for (let daddrs in subnets_group_by_masking(dip[1])) {
  1983. if (length(icmp_types) || (!length(icmp_types) && !length(icmp_codes)))
  1984. add_rule(6, proto, saddrs, daddrs, sports, dports, icmp_types, null, ipset, rule);
  1985. if (length(icmp_codes))
  1986. add_rule(6, proto, saddrs, daddrs, sports, dports, null, icmp_codes, ipset, rule);
  1987. }
  1988. }
  1989. }
  1990. }
  1991. }
  1992. },
  1993. parse_redirect: function(data) {
  1994. let redir = this.parse_options(data, {
  1995. enabled: [ "bool", "1" ],
  1996. name: [ "string", this.section_id(data[".name"]) ],
  1997. _name: [ "string", null, DEPRECATED ],
  1998. family: [ "family" ],
  1999. src: [ "zone_ref" ],
  2000. dest: [ "zone_ref" ],
  2001. ipset: [ "setmatch" ],
  2002. helper: [ "cthelper", null, NO_INVERT ],
  2003. proto: [ "protocol", "tcpudp", PARSE_LIST | FLATTEN_LIST ],
  2004. src_ip: [ "network" ],
  2005. src_mac: [ "mac", null, PARSE_LIST ],
  2006. src_port: [ "port" ],
  2007. src_dip: [ "network" ],
  2008. src_dport: [ "port" ],
  2009. dest_ip: [ "network" ],
  2010. dest_port: [ "port" ],
  2011. extra: [ "string", null, UNSUPPORTED ],
  2012. limit: [ "limit" ],
  2013. limit_burst: [ "int" ],
  2014. utc_time: [ "bool" ],
  2015. start_date: [ "date" ],
  2016. stop_date: [ "date" ],
  2017. start_time: [ "time" ],
  2018. stop_time: [ "time" ],
  2019. weekdays: [ "weekdays" ],
  2020. monthdays: [ "monthdays", null, UNSUPPORTED ],
  2021. mark: [ "mark" ],
  2022. reflection: [ "bool", "1" ],
  2023. reflection_src: [ "reflection_source", "internal" ],
  2024. reflection_zone: [ "zone_ref", null, PARSE_LIST ],
  2025. counter: [ "bool", "1" ],
  2026. log: [ "string" ],
  2027. log_limit: [ "limit" ],
  2028. target: [ "target", "dnat" ]
  2029. });
  2030. if (redir === false) {
  2031. this.warn_section(data, "skipped due to invalid options");
  2032. return;
  2033. }
  2034. else if (!redir.enabled) {
  2035. this.warn_section(data, "is disabled, ignoring section");
  2036. return;
  2037. }
  2038. if (!(redir.target in ["dnat", "snat"])) {
  2039. this.warn_section(data, "has invalid target specified, defaulting to dnat");
  2040. redir.target = "dnat";
  2041. }
  2042. switch (this.parse_bool(redir.log)) {
  2043. case true:
  2044. redir.log = `${redir.name}: `;
  2045. break;
  2046. case false:
  2047. delete redir.log;
  2048. }
  2049. let ipset;
  2050. if (redir.ipset) {
  2051. ipset = filter(this.state.ipsets, s => (s.name == redir.ipset.name))?.[0];
  2052. if (!ipset) {
  2053. this.warn_section(data, `references unknown set '${redir.ipset.name}'`);
  2054. return;
  2055. }
  2056. if (('inet_service' in ipset.types) && !ensure_tcpudp(redir.proto)) {
  2057. this.warn_section(data, "references named set with port match but no UDP/TCP protocol, ignoring section");
  2058. return;
  2059. }
  2060. }
  2061. let resolve_dest = (redir) => {
  2062. for (let zone in this.state.zones) {
  2063. for (let zone_addr in zone.related_subnets) {
  2064. for (let dest_addr in redir.dest_ip.addrs) {
  2065. if (dest_addr.family != zone_addr.family)
  2066. continue;
  2067. let a = apply_mask(dest_addr.addr, zone_addr.mask);
  2068. let b = apply_mask(zone_addr.addr, zone_addr.mask);
  2069. if (a != b)
  2070. continue;
  2071. redir.dest = {
  2072. any: false,
  2073. zone: zone
  2074. };
  2075. return true;
  2076. }
  2077. }
  2078. }
  2079. return false;
  2080. };
  2081. if (redir.target == "dnat") {
  2082. if (!redir.src)
  2083. return this.warn_section(data, "has no source specified");
  2084. else if (redir.src.any)
  2085. return this.warn_section(data, "must not have source '*' for dnat target");
  2086. else if (redir.dest_ip && redir.dest_ip.invert)
  2087. return this.warn_section(data, "must not specify a negated 'dest_ip' value");
  2088. else if (redir.dest_ip && length(filter(redir.dest_ip.addrs, a => a.bits == -1)))
  2089. return this.warn_section(data, "must not use non-contiguous masks in 'dest_ip'");
  2090. if (!redir.dest && redir.dest_ip && resolve_dest(redir))
  2091. this.warn_section(data, `does not specify a destination, assuming '${redir.dest.zone.name}'`);
  2092. if (!redir.dest_port)
  2093. redir.dest_port = redir.src_dport;
  2094. if (redir.reflection && redir.dest?.zone && redir.src.zone.masq) {
  2095. redir.dest.zone.dflags.accept = true;
  2096. redir.dest.zone.dflags.dnat = true;
  2097. redir.dest.zone.dflags.snat = true;
  2098. }
  2099. if (redir.helper)
  2100. redir.src.zone.dflags.helper = true;
  2101. redir.src.zone.dflags[redir.target] = true;
  2102. }
  2103. else {
  2104. if (!redir.dest)
  2105. return this.warn_section(data, "has no destination specified");
  2106. else if (redir.dest.any)
  2107. return this.warn_section(data, "must not have destination '*' for snat target");
  2108. else if (!redir.src_dip)
  2109. return this.warn_section(data, "has no 'src_dip' option specified");
  2110. else if (redir.src_dip.invert)
  2111. return this.warn_section(data, "must not specify a negated 'src_dip' value");
  2112. else if (length(filter(redir.src_dip.addrs, a => a.bits == -1)))
  2113. return this.warn_section(data, "must not use non-contiguous masks in 'src_dip'");
  2114. else if (redir.src_mac)
  2115. return this.warn_section(data, "must not use 'src_mac' option for snat target");
  2116. else if (redir.helper)
  2117. return this.warn_section(data, "must not use 'helper' option for snat target");
  2118. redir.dest.zone.dflags[redir.target] = true;
  2119. }
  2120. let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, ipset, redir) => {
  2121. let r = {
  2122. ...redir,
  2123. family: family,
  2124. proto: proto,
  2125. has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
  2126. has_ports: !!(sport || dport || rport),
  2127. saddrs_pos: map(saddrs[0], this.cidr),
  2128. saddrs_neg: map(saddrs[1], this.cidr),
  2129. saddrs_masked: saddrs[2],
  2130. daddrs_pos: map(daddrs[0], this.cidr),
  2131. daddrs_neg: map(daddrs[1], this.cidr),
  2132. daddrs_masked: daddrs[2],
  2133. sports_pos: map(filter_pos(to_array(sport)), this.port),
  2134. sports_neg: map(filter_neg(to_array(sport)), this.port),
  2135. dports_pos: map(filter_pos(to_array(dport)), this.port),
  2136. dports_neg: map(filter_neg(to_array(dport)), this.port),
  2137. smacs_pos: map(filter_pos(redir.src_mac), m => m.mac),
  2138. smacs_neg: map(filter_neg(redir.src_mac), m => m.mac),
  2139. raddr: raddrs ? raddrs[0] : null,
  2140. rport: rport
  2141. };
  2142. let set_types = map_setmatch(ipset, redir.ipset, proto.name);
  2143. if (set_types !== set_types) {
  2144. this.warn_section(data, "destination MAC address matching not supported");
  2145. return;
  2146. } else if (set_types) {
  2147. r.ipset = { ...r.ipset, fields: set_types };
  2148. }
  2149. switch (r.target) {
  2150. case "dnat":
  2151. r.chain = `dstnat_${r.src.zone.name}`;
  2152. r.src.zone.dflags.dnat = true;
  2153. if (!r.raddr)
  2154. r.target = "redirect";
  2155. break;
  2156. case "snat":
  2157. r.chain = `srcnat_${r.dest.zone.name}`;
  2158. r.dest.zone.dflags.snat = true;
  2159. break;
  2160. }
  2161. push(this.state.redirects ||= [], r);
  2162. };
  2163. let to_hostaddr = (a) => {
  2164. let bits = (a.family == 4) ? 32 : 128;
  2165. return {
  2166. family: a.family,
  2167. addr: apply_mask(a.addr, bits),
  2168. bits: bits
  2169. };
  2170. };
  2171. for (let proto in redir.proto) {
  2172. let sip, dip, rip, iip, eip, refip, sport, dport, rport;
  2173. let family = redir.family;
  2174. if (proto.name == "ipv6-icmp")
  2175. family = 6;
  2176. switch (redir.target) {
  2177. case "dnat":
  2178. sip = subnets_split_af(redir.src_ip);
  2179. dip = subnets_split_af(redir.src_dip);
  2180. rip = subnets_split_af(redir.dest_ip);
  2181. switch (proto.name) {
  2182. case "tcp":
  2183. case "udp":
  2184. sport = redir.src_port;
  2185. dport = redir.src_dport;
  2186. rport = redir.dest_port;
  2187. break;
  2188. }
  2189. break;
  2190. case "snat":
  2191. sip = subnets_split_af(redir.src_ip);
  2192. dip = subnets_split_af(redir.dest_ip);
  2193. rip = subnets_split_af(redir.src_dip);
  2194. switch (proto.name) {
  2195. case "tcp":
  2196. case "udp":
  2197. sport = redir.src_port;
  2198. dport = redir.dest_port;
  2199. rport = redir.src_dport;
  2200. break;
  2201. }
  2202. break;
  2203. }
  2204. family = infer_family(family, [
  2205. ipset, "set match",
  2206. sip, "source IP",
  2207. dip, "destination IP",
  2208. rip, "rewrite IP",
  2209. redir.src?.zone, "source zone",
  2210. redir.dest?.zone, "destination zone",
  2211. redir.helper, "helper match"
  2212. ]);
  2213. if (type(family) == "string") {
  2214. this.warn_section(data, `${family}, skipping`);
  2215. continue;
  2216. }
  2217. /* build reflection rules */
  2218. if (redir.target == "dnat" && redir.reflection &&
  2219. (length(rip[0]) || length(rip[1])) && redir.src?.zone && redir.dest?.zone) {
  2220. let refredir = {
  2221. name: `${redir.name} (reflection)`,
  2222. helper: redir.helper,
  2223. // XXX: this likely makes no sense for reflection rules
  2224. //src_mac: redir.src_mac,
  2225. limit: redir.limit,
  2226. limit_burst: redir.limit_burst,
  2227. start_date: redir.start_date,
  2228. stop_date: redir.stop_date,
  2229. start_time: redir.start_time,
  2230. stop_time: redir.stop_time,
  2231. weekdays: redir.weekdays,
  2232. mark: redir.mark
  2233. };
  2234. let eaddrs = length(dip) ? dip : subnets_split_af({ addrs: map(redir.src.zone.related_subnets, to_hostaddr) });
  2235. let rzones = length(redir.reflection_zone) ? redir.reflection_zone : [ redir.dest ];
  2236. for (let rzone in rzones) {
  2237. if (!is_family(rzone, family)) {
  2238. this.warn_section(data,
  2239. `is restricted to IPv${family} but referenced reflection zone is IPv${rzone.family} only, skipping`);
  2240. continue;
  2241. }
  2242. let iaddrs = subnets_split_af({ addrs: rzone.zone.related_subnets });
  2243. let refaddrs = (redir.reflection_src == "internal") ? iaddrs : eaddrs;
  2244. for (let i = 0; i <= 1; i++) {
  2245. if (redir.src.zone[i ? "masq6" : "masq"] && length(rip[i])) {
  2246. let snat_addr = refaddrs[i]?.[0];
  2247. /* For internal reflection sources try to find a suitable candiate IP
  2248. * among the reflection zone subnets which is within the same subnet
  2249. * as the original DNAT destination. If we can't find any matching
  2250. * one then simply take the first candidate. */
  2251. if (redir.reflection_src == "internal") {
  2252. for (let zone_addr in rzone.zone.related_subnets) {
  2253. if (zone_addr.family != rip[i][0].family)
  2254. continue;
  2255. let r = apply_mask(rip[i][0].addr, zone_addr.mask);
  2256. let a = apply_mask(zone_addr.addr, zone_addr.mask);
  2257. if (r != a)
  2258. continue;
  2259. snat_addr = zone_addr;
  2260. break;
  2261. }
  2262. }
  2263. if (!snat_addr) {
  2264. this.warn_section(data, `${redir.reflection_src || "external"} rewrite IP cannot be determined, disabling reflection`);
  2265. }
  2266. else if (!length(iaddrs[i])) {
  2267. this.warn_section(data, "internal address range cannot be determined, disabling reflection");
  2268. }
  2269. else if (!length(eaddrs[i])) {
  2270. this.warn_section(data, "external address range cannot be determined, disabling reflection");
  2271. }
  2272. else {
  2273. refredir.src = rzone;
  2274. refredir.dest = null;
  2275. refredir.target = "dnat";
  2276. for (let saddrs in subnets_group_by_masking(iaddrs[i]))
  2277. for (let daddrs in subnets_group_by_masking(eaddrs[i]))
  2278. add_rule(i ? 6 : 4, proto, saddrs, daddrs, rip[i], sport, dport, rport, null, refredir);
  2279. refredir.src = null;
  2280. refredir.dest = rzone;
  2281. refredir.target = "snat";
  2282. for (let daddrs in subnets_group_by_masking(rip[i]))
  2283. for (let saddrs in subnets_group_by_masking(iaddrs[i]))
  2284. add_rule(i ? 6 : 4, proto, saddrs, daddrs, [ to_hostaddr(snat_addr) ], null, rport, null, null, refredir);
  2285. }
  2286. }
  2287. }
  2288. }
  2289. }
  2290. if (length(rip[0]) > 1 || length(rip[1]) > 1)
  2291. this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
  2292. let has_ip4_addr = length(sip[0]) || length(dip[0]) || length(rip[0]),
  2293. has_ip6_addr = length(sip[1]) || length(dip[1]) || length(rip[1]),
  2294. has_any_addr = has_ip4_addr || has_ip6_addr;
  2295. /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
  2296. if (!family && !has_any_addr) {
  2297. /* for backwards compatibility, treat unspecified family as IPv4 unless user explicitly requested any (0) */
  2298. if (family == null)
  2299. family = 4;
  2300. add_rule(family, proto, [], [], null, sport, dport, rport, null, redir);
  2301. }
  2302. /* we need to emit one or two AF specific rules */
  2303. else {
  2304. if ((!family || family == 4) && (!has_any_addr || has_ip4_addr)) {
  2305. for (let saddrs in subnets_group_by_masking(sip[0]))
  2306. for (let daddrs in subnets_group_by_masking(dip[0]))
  2307. add_rule(4, proto, saddrs, daddrs, rip[0], sport, dport, rport, ipset, redir);
  2308. }
  2309. if ((!family || family == 6) && (!has_any_addr || has_ip6_addr)) {
  2310. for (let saddrs in subnets_group_by_masking(sip[1]))
  2311. for (let daddrs in subnets_group_by_masking(dip[1]))
  2312. add_rule(6, proto, saddrs, daddrs, rip[1], sport, dport, rport, ipset, redir);
  2313. }
  2314. }
  2315. }
  2316. },
  2317. parse_nat: function(data) {
  2318. let snat = this.parse_options(data, {
  2319. enabled: [ "bool", "1" ],
  2320. name: [ "string", this.section_id(data[".name"]) ],
  2321. family: [ "family" ],
  2322. src: [ "zone_ref" ],
  2323. device: [ "string" ],
  2324. ipset: [ "setmatch", null, UNSUPPORTED ],
  2325. proto: [ "protocol", "all", PARSE_LIST | FLATTEN_LIST ],
  2326. src_ip: [ "network" ],
  2327. src_port: [ "port" ],
  2328. snat_ip: [ "network", null, NO_INVERT ],
  2329. snat_port: [ "port", null, NO_INVERT ],
  2330. dest_ip: [ "network" ],
  2331. dest_port: [ "port" ],
  2332. extra: [ "string", null, UNSUPPORTED ],
  2333. limit: [ "limit" ],
  2334. limit_burst: [ "int" ],
  2335. connlimit_ports: [ "bool" ],
  2336. utc_time: [ "bool" ],
  2337. start_date: [ "date" ],
  2338. stop_date: [ "date" ],
  2339. start_time: [ "time" ],
  2340. stop_time: [ "time" ],
  2341. weekdays: [ "weekdays" ],
  2342. monthdays: [ "monthdays", null, UNSUPPORTED ],
  2343. mark: [ "mark" ],
  2344. counter: [ "bool", "1" ],
  2345. log: [ "string" ],
  2346. target: [ "target", "masquerade" ]
  2347. });
  2348. if (snat === false) {
  2349. this.warn_section(data, "skipped due to invalid options");
  2350. return;
  2351. }
  2352. else if (!snat.enabled) {
  2353. this.warn_section(data, "is disabled, ignoring section");
  2354. return;
  2355. }
  2356. if (!(snat.target in ["accept", "snat", "masquerade"])) {
  2357. this.warn_section(data, "has invalid target specified, defaulting to masquerade");
  2358. snat.target = "masquerade";
  2359. }
  2360. if (snat.target == "snat" && !snat.snat_ip && !snat.snat_port) {
  2361. this.warn_section(data, "needs either 'snat_ip' or 'snat_port' for target snat, ignoring section");
  2362. return;
  2363. }
  2364. else if (snat.target != "snat" && snat.snat_ip) {
  2365. this.warn_section(data, "must not use 'snat_ip' for non-snat target, ignoring section");
  2366. return;
  2367. }
  2368. else if (snat.target != "snat" && snat.snat_port) {
  2369. this.warn_section(data, "must not use 'snat_port' for non-snat target, ignoring section");
  2370. return;
  2371. }
  2372. if ((snat.snat_port || snat.src_port || snat.dest_port) && !ensure_tcpudp(snat.proto)) {
  2373. this.warn_section(data, "specifies ports but no UDP/TCP protocol, ignoring section");
  2374. return;
  2375. }
  2376. if (snat.snat_ip && length(filter(snat.snat_ip.addrs, a => a.bits == -1 || a.invert))) {
  2377. this.warn_section(data, "must not use inversion or non-contiguous masks in 'snat_ip', ignoring section");
  2378. return;
  2379. }
  2380. switch (this.parse_bool(snat.log)) {
  2381. case true:
  2382. snat.log = `${snat.name}: `;
  2383. break;
  2384. case false:
  2385. delete snat.log;
  2386. }
  2387. let add_rule = (family, proto, saddrs, daddrs, raddrs, sport, dport, rport, snat) => {
  2388. let n = {
  2389. ...snat,
  2390. family: family,
  2391. proto: proto,
  2392. has_addrs: !!(saddrs[0] || saddrs[1] || saddrs[2] || daddrs[0] || daddrs[1] || daddrs[2]),
  2393. has_ports: !!(sport || dport),
  2394. saddrs_pos: map(saddrs[0], this.cidr),
  2395. saddrs_neg: map(saddrs[1], this.cidr),
  2396. saddrs_masked: saddrs[2],
  2397. daddrs_pos: map(daddrs[0], this.cidr),
  2398. daddrs_neg: map(daddrs[1], this.cidr),
  2399. daddrs_masked: daddrs[2],
  2400. sports_pos: map(filter_pos(to_array(sport)), this.port),
  2401. sports_neg: map(filter_neg(to_array(sport)), this.port),
  2402. dports_pos: map(filter_pos(to_array(dport)), this.port),
  2403. dports_neg: map(filter_neg(to_array(dport)), this.port),
  2404. raddr: raddrs ? raddrs[0] : null,
  2405. rport: rport,
  2406. chain: snat.src?.zone ? `srcnat_${snat.src.zone.name}` : "srcnat"
  2407. };
  2408. push(this.state.redirects ||= [], n);
  2409. };
  2410. for (let proto in snat.proto) {
  2411. let sip, dip, rip, sport, dport, rport;
  2412. let family = snat.family;
  2413. sip = subnets_split_af(snat.src_ip);
  2414. dip = subnets_split_af(snat.dest_ip);
  2415. rip = subnets_split_af(snat.snat_ip);
  2416. switch (proto.name) {
  2417. case "tcp":
  2418. case "udp":
  2419. sport = snat.src_port;
  2420. dport = snat.dest_port;
  2421. rport = snat.snat_port;
  2422. break;
  2423. }
  2424. if (length(rip[0]) > 1 || length(rip[1]) > 1)
  2425. this.warn_section(data, "specifies multiple rewrite addresses, using only first one");
  2426. family = infer_family(family, [
  2427. sip, "source IP",
  2428. dip, "destination IP",
  2429. rip, "rewrite IP",
  2430. snat.src?.zone, "source zone"
  2431. ]);
  2432. if (type(family) == "string") {
  2433. this.warn_section(data, `${family}, skipping`);
  2434. continue;
  2435. }
  2436. if (snat.src?.zone)
  2437. snat.src.zone.dflags.snat = true;
  2438. /* if no family was configured, infer target family from IP addresses */
  2439. if (family === null) {
  2440. if ((length(sip[0]) || length(dip[0]) || length(rip[0])) && !length(sip[1]) && !length(dip[1]) && !length(rip[1]))
  2441. family = 4;
  2442. else if ((length(sip[1]) || length(dip[1]) || length(rip[1])) && !length(sip[0]) && !length(dip[0]) && !length(rip[0]))
  2443. family = 6;
  2444. else
  2445. family = 4; /* default to IPv4 only for backwards compatibility, unless an explict family any was configured */
  2446. }
  2447. /* check if there's no AF specific bits, in this case we can do an AF agnostic rule */
  2448. if (!family && !length(sip[0]) && !length(sip[1]) && !length(dip[0]) && !length(dip[1]) && !length(rip[0]) && !length(rip[1])) {
  2449. add_rule(0, proto, [], [], null, sport, dport, rport, snat);
  2450. }
  2451. /* we need to emit one or two AF specific rules */
  2452. else {
  2453. if (family == 0 || family == 4)
  2454. for (let saddr in subnets_group_by_masking(sip[0]))
  2455. for (let daddr in subnets_group_by_masking(dip[0]))
  2456. add_rule(4, proto, saddr, daddr, rip[0], sport, dport, rport, snat);
  2457. if (family == 0 || family == 6)
  2458. for (let saddr in subnets_group_by_masking(sip[1]))
  2459. for (let daddr in subnets_group_by_masking(dip[1]))
  2460. add_rule(6, proto, saddr, daddr, rip[1], sport, dport, rport, snat);
  2461. }
  2462. }
  2463. },
  2464. parse_include: function(data) {
  2465. let inc = this.parse_options(data, {
  2466. enabled: [ "bool", "1" ],
  2467. path: [ "string", null, REQUIRED ],
  2468. type: [ "includetype", "script" ],
  2469. fw4_compatible: [ "bool", data.path != "/etc/firewall.user" ],
  2470. family: [ "family", null, UNSUPPORTED ],
  2471. reload: [ "bool", null, UNSUPPORTED ],
  2472. position: [ "includeposition" ],
  2473. chain: [ "identifier" ]
  2474. });
  2475. if (!inc.enabled) {
  2476. this.warn_section(data, "is disabled, ignoring section");
  2477. return;
  2478. }
  2479. if (inc.type == "script" && !inc.fw4_compatible) {
  2480. this.warn_section(data, "is not marked as compatible with fw4, ignoring section");
  2481. this.warn_section(data, "requires 'option fw4_compatible 1' to be considered compatible");
  2482. return;
  2483. }
  2484. for (let opt in [ "table", "chain", "position" ]) {
  2485. if (inc.type != "nftables" && inc[opt]) {
  2486. this.warn_section(data, `must not specify '${opt}' for non-nftables includes, ignoring section`);
  2487. return;
  2488. }
  2489. }
  2490. switch (inc.position ??= 'table-append') {
  2491. case 'ruleset-prepend':
  2492. case 'ruleset-append':
  2493. case 'table-prepend':
  2494. case 'table-append':
  2495. if (inc.chain)
  2496. this.warn_section(data, `specifies 'chain' which has no effect for position ${inc.position}`);
  2497. delete inc.chain;
  2498. break;
  2499. case 'chain-prepend':
  2500. case 'chain-append':
  2501. if (!inc.chain) {
  2502. this.warn_section(data, `must specify 'chain' for position ${inc.position}, ignoring section`);
  2503. return;
  2504. }
  2505. break;
  2506. }
  2507. let path = fs.readlink(inc.path) ?? inc.path;
  2508. if (!fs.access(path)) {
  2509. this.warn_section(data, `specifies unreachable path '${path}', ignoring section`);
  2510. return;
  2511. }
  2512. if (!data['.name'])
  2513. this.warn(`Automatically including '${path}'`);
  2514. push(this.state.includes ||= [], { ...inc, path });
  2515. },
  2516. parse_ipset: function(data) {
  2517. let ipset = this.parse_options(data, {
  2518. enabled: [ "bool", "1" ],
  2519. reload_set: [ "bool" ],
  2520. counters: [ "bool" ],
  2521. comment: [ "string" ],
  2522. name: [ "identifier", null, REQUIRED ],
  2523. family: [ "family", "4" ],
  2524. storage: [ "string", null, UNSUPPORTED ],
  2525. match: [ "ipsettype", null, PARSE_LIST ],
  2526. iprange: [ "string", null, UNSUPPORTED ],
  2527. portrange: [ "string", null, UNSUPPORTED ],
  2528. netmask: [ "int", null, UNSUPPORTED ],
  2529. maxelem: [ "int" ],
  2530. hashsize: [ "int", null, UNSUPPORTED ],
  2531. timeout: [ "int", "-1" ],
  2532. external: [ "string", null, UNSUPPORTED ],
  2533. entry: [ "string", null, PARSE_LIST ],
  2534. loadfile: [ "string" ]
  2535. });
  2536. if (ipset === false) {
  2537. this.warn_section(data, "skipped due to invalid options");
  2538. return;
  2539. }
  2540. else if (!ipset.enabled) {
  2541. this.warn_section(data, "is disabled, ignoring section");
  2542. return;
  2543. }
  2544. if (ipset.family == 0) {
  2545. this.warn_section(data, "must not specify family 'any'");
  2546. return;
  2547. }
  2548. else if (!length(ipset.match)) {
  2549. this.warn_section(data, "has no datatypes assigned");
  2550. return;
  2551. }
  2552. let dirs = map(ipset.match, m => m[0]),
  2553. types = map(ipset.match, m => m[1]),
  2554. interval = false;
  2555. if ("set" in types) {
  2556. this.warn_section(data, "match type 'set' is not supported");
  2557. return;
  2558. }
  2559. if ("net" in types) {
  2560. if (this.kernel < 0x05060000) {
  2561. this.warn_section(data, "match type 'net' requires kernel 5.6 or later");
  2562. return;
  2563. }
  2564. interval = true;
  2565. }
  2566. let s = {
  2567. ...ipset,
  2568. fw4types: types,
  2569. types: map(types, (t) => {
  2570. switch (t) {
  2571. case 'ip':
  2572. case 'net':
  2573. return (ipset.family == 4) ? 'ipv4_addr' : 'ipv6_addr';
  2574. case 'mac':
  2575. return 'ether_addr';
  2576. case 'port':
  2577. return 'inet_service';
  2578. }
  2579. }),
  2580. directions: dirs,
  2581. interval: interval
  2582. };
  2583. if (s.interval)
  2584. push(s.flags ??= [], 'interval');
  2585. if (s.timeout >= 0)
  2586. push(s.flags ??= [], 'timeout');
  2587. s.entries = filter(map(ipset.entry, (e) => {
  2588. let v = this.parse_ipsetentry(e, s);
  2589. if (!v)
  2590. this.warn_section(data, `ignoring invalid ipset entry '${e}'`);
  2591. return v;
  2592. }), (e) => (e != null));
  2593. push(this.state.ipsets ||= [], s);
  2594. }
  2595. };