fw4.uc 76 KB

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