rule-compiler.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  1. 'use strict';
  2. // Names for bits in characteristics -- 0==LSB, 63==MSB
  3. const CHARACTERISTIC_BITS = {
  4. 'inbound': 63,
  5. 'multicast': 62,
  6. 'broadcast': 61,
  7. 'ipauth': 60,
  8. 'macauth': 59,
  9. 'tcp_fin': 0,
  10. 'tcp_syn': 1,
  11. 'tcp_rst': 2,
  12. 'tcp_psh': 3,
  13. 'tcp_ack': 4,
  14. 'tcp_urg': 5,
  15. 'tcp_ece': 6,
  16. 'tcp_cwr': 7,
  17. 'tcp_ns': 8,
  18. 'tcp_rs2': 9,
  19. 'tcp_rs1': 10,
  20. 'tcp_rs0': 11
  21. };
  22. // Shorthand names for common ethernet types
  23. const ETHERTYPES = {
  24. 'ipv4': 0x0800,
  25. 'arp': 0x0806,
  26. 'wol': 0x0842,
  27. 'rarp': 0x8035,
  28. 'ipv6': 0x86dd,
  29. 'atalk': 0x809b,
  30. 'aarp': 0x80f3,
  31. 'ipx_a': 0x8137,
  32. 'ipx_b': 0x8138
  33. };
  34. // Shorthand names for common IP protocols
  35. const IP_PROTOCOLS = {
  36. 'icmp': 0x01,
  37. 'icmp4': 0x01,
  38. 'icmpv4': 0x01,
  39. 'igmp': 0x02,
  40. 'ipip': 0x04,
  41. 'tcp': 0x06,
  42. 'egp': 0x08,
  43. 'igp': 0x09,
  44. 'udp': 0x11,
  45. 'rdp': 0x1b,
  46. 'esp': 0x32,
  47. 'ah': 0x33,
  48. 'icmp6': 0x3a,
  49. 'icmpv6': 0x3a,
  50. 'l2tp': 0x73,
  51. 'sctp': 0x84,
  52. 'udplite': 0x88
  53. };
  54. // Keywords that open new blocks that must be terminated by a semicolon
  55. const OPEN_BLOCK_KEYWORDS = {
  56. 'macro': true,
  57. 'tag': true,
  58. 'cap': true,
  59. 'drop': true,
  60. 'accept': true,
  61. 'tee': true,
  62. 'watch': true,
  63. 'redirect': true,
  64. 'break': true,
  65. 'priority': true
  66. };
  67. // Reserved words that can't be used as tag, capability, or rule set names
  68. const RESERVED_WORDS = {
  69. 'macro': true,
  70. 'tag': true,
  71. 'cap': true,
  72. 'default': true,
  73. 'drop': true,
  74. 'accept': true,
  75. 'tee': true,
  76. 'watch': true,
  77. 'redirect': true,
  78. 'break': true,
  79. 'priority': true,
  80. 'ztsrc': true,
  81. 'ztdest': true,
  82. 'vlan': true,
  83. 'vlanpcp': true,
  84. 'vlandei': true,
  85. 'ethertype': true,
  86. 'macsrc': true,
  87. 'macdest': true,
  88. 'ipsrc': true,
  89. 'ipdest': true,
  90. 'iptos': true,
  91. 'ipprotocol': true,
  92. 'icmp': true,
  93. 'sport': true,
  94. 'dport': true,
  95. 'chr': true,
  96. 'framesize': true,
  97. 'random': true,
  98. 'tand': true,
  99. 'tor': true,
  100. 'txor': true,
  101. 'tdiff': true,
  102. 'teq': true,
  103. 'tseq': true,
  104. 'treq': true,
  105. 'type': true,
  106. 'enum': true,
  107. 'class': true,
  108. 'define': true,
  109. 'import': true,
  110. 'include': true,
  111. 'log': true,
  112. 'not': true,
  113. 'xor': true,
  114. 'or': true,
  115. 'and': true,
  116. 'set': true,
  117. 'var': true,
  118. 'let': true
  119. };
  120. const KEYWORD_TO_API_MAP = {
  121. 'drop': 'ACTION_DROP',
  122. 'accept': 'ACTION_ACCEPT',
  123. 'tee': 'ACTION_TEE',
  124. 'watch': 'ACTION_WATCH',
  125. 'redirect': 'ACTION_REDIRECT',
  126. 'break': 'ACTION_BREAK',
  127. 'priority': 'ACTION_PRIORITY',
  128. 'ztsrc': 'MATCH_SOURCE_ZEROTIER_ADDRESS',
  129. 'ztdest': 'MATCH_DEST_ZEROTIER_ADDRESS',
  130. 'vlan': 'MATCH_VLAN_ID',
  131. 'vlanpcp': 'MATCH_VLAN_PCP',
  132. 'vlandei': 'MATCH_VLAN_DEI',
  133. 'ethertype': 'MATCH_ETHERTYPE',
  134. 'macsrc': 'MATCH_MAC_SOURCE',
  135. 'macdest': 'MATCH_MAC_DEST',
  136. //'ipsrc': '', // special handling since we programmatically differentiate between V4 and V6
  137. //'ipdest': '', // special handling
  138. 'iptos': 'MATCH_IP_TOS',
  139. 'ipprotocol': 'MATCH_IP_PROTOCOL',
  140. 'icmp': 'MATCH_ICMP',
  141. 'sport': 'MATCH_IP_SOURCE_PORT_RANGE',
  142. 'dport': 'MATCH_IP_DEST_PORT_RANGE',
  143. 'chr': 'MATCH_CHARACTERISTICS',
  144. 'framesize': 'MATCH_FRAME_SIZE_RANGE',
  145. 'random': 'MATCH_RANDOM',
  146. 'tand': 'MATCH_TAGS_BITWISE_AND',
  147. 'tor': 'MATCH_TAGS_BITWISE_OR',
  148. 'txor': 'MATCH_TAGS_BITWISE_XOR',
  149. 'tdiff': 'MATCH_TAGS_DIFFERENCE',
  150. 'teq': 'MATCH_TAGS_EQUAL',
  151. 'tseq': 'MATCH_TAG_SENDER',
  152. 'treq': 'MATCH_TAG_RECEIVER'
  153. };
  154. // Number of args for each match
  155. const MATCH_ARG_COUNTS = {
  156. 'ztsrc': 1,
  157. 'ztdest': 1,
  158. 'vlan': 1,
  159. 'vlanpcp': 1,
  160. 'vlandei': 1,
  161. 'ethertype': 1,
  162. 'macsrc': 1,
  163. 'macdest': 1,
  164. 'ipsrc': 1,
  165. 'ipdest': 1,
  166. 'iptos': 2,
  167. 'ipprotocol': 1,
  168. 'icmp': 2,
  169. 'sport': 1,
  170. 'dport': 1,
  171. 'chr': 1,
  172. 'framesize': 1,
  173. 'random': 1,
  174. 'tand': 2,
  175. 'tor': 2,
  176. 'txor': 2,
  177. 'tdiff': 2,
  178. 'teq': 2,
  179. 'tseq': 2,
  180. 'treq': 2
  181. };
  182. // Regex of all alphanumeric characters in Unicode
  183. const INTL_ALPHANUM_REGEX = new RegExp('[0-9A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]');
  184. // Checks whether something is a valid capability, tag, or macro name
  185. function _isValidName(n)
  186. {
  187. if ((typeof n !== 'string')||(n.length === 0)) return false;
  188. if ("0123456789".indexOf(n.charAt(0)) >= 0) return false;
  189. for(let i=0;i<n.length;++i) {
  190. let c = n.charAt(i);
  191. if ((c !== '_')&&(!INTL_ALPHANUM_REGEX.test(c))) return false;
  192. }
  193. return true;
  194. }
  195. // Regexes for checking the basic syntactic validity of IP addresses
  196. const IPV6_REGEX = new RegExp('(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))');
  197. const IPV4_REGEX = new RegExp('((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])');
  198. function _parseNum(n)
  199. {
  200. try {
  201. if ((typeof n !== 'string')||(n.length === 0))
  202. return -1;
  203. n = n.toLowerCase();
  204. if ((n.length > 2)&&(n.substr(0,2) === '0x'))
  205. n = parseInt(n.substr(2),16);
  206. else n = parseInt(n,10);
  207. return (((typeof n === 'number')&&(n !== null)&&(!isNaN(n))) ? n : -1);
  208. } catch (e) {
  209. return -1;
  210. }
  211. }
  212. function _cleanMac(m)
  213. {
  214. m = m.toLowerCase();
  215. var m2 = '';
  216. let charcount = 0;
  217. for(let i=0;((i<m.length)&&(m2.length<17));++i) {
  218. let c = m.charAt(i);
  219. if ("0123456789abcdef".indexOf(c) >= 0) {
  220. m2 += c;
  221. charcount++;
  222. if ((m2.length > 0)&&(m2.length !== 17)&&(charcount >= 2) ) {
  223. m2 += ':';
  224. charcount=0;
  225. }
  226. }
  227. }
  228. return m2;
  229. }
  230. function _cleanHex(m)
  231. {
  232. m = m.toLowerCase();
  233. var m2 = '';
  234. for(let i=0;i<m.length;++i) {
  235. let c = m.charAt(i);
  236. if ("0123456789abcdef".indexOf(c) >= 0)
  237. m2 += c;
  238. }
  239. return m2;
  240. }
  241. function _renderMatches(mtree,rules,macros,caps,tags,params)
  242. {
  243. let not = false;
  244. let or = false;
  245. for(let k=0;k<mtree.length;++k) {
  246. let match = (typeof mtree[k][0] === 'string') ? mtree[k][0].toLowerCase() : '';
  247. if ((match.length === 0)||(match === 'and')) { // AND is the default
  248. continue;
  249. } else if (match === 'not') {
  250. not = true;
  251. } else if (match === 'or') {
  252. or = true;
  253. } else {
  254. let args = [];
  255. let argCount = MATCH_ARG_COUNTS[match];
  256. if (!argCount)
  257. return [ mtree[k][1],mtree[k][2],'Unrecognized match type "'+match+'".' ];
  258. for(let i=0;i<argCount;++i) {
  259. if (++k >= mtree.length)
  260. return [ mtree[k - 1][1],mtree[k - 1][2],'Missing argument(s) to match.' ];
  261. let arg = mtree[k][0];
  262. if ((typeof arg !== 'string')||(arg in RESERVED_WORDS)||(arg.length === 0))
  263. return [ mtree[k - 1][1],mtree[k - 1][2],'Missing argument(s) to match (invalid argument or argument is reserved word).' ];
  264. if (arg.charAt(0) === '$') {
  265. let tmp = params[arg];
  266. if (typeof tmp === 'undefined')
  267. return [ mtree[k][1],mtree[k][2],'Undefined variable name.' ];
  268. args.push([ tmp,mtree[k][1],mtree[k][2] ]);
  269. } else {
  270. args.push(mtree[k]);
  271. }
  272. }
  273. switch(match) {
  274. case 'ztsrc':
  275. case 'ztdest': {
  276. let zt = _cleanHex(args[0][0]);
  277. if (zt.length !== 10)
  278. return [ args[0][1],args[0][2],'Invalid ZeroTier address.' ];
  279. rules.push({
  280. 'type': KEYWORD_TO_API_MAP[match],
  281. 'not': not,
  282. 'or': or,
  283. 'zt': zt
  284. });
  285. } break;
  286. case 'vlan':
  287. case 'vlanpcp':
  288. case 'vlandei':
  289. case 'ethertype':
  290. case 'ipprotocol': {
  291. let num = null;
  292. switch (match) {
  293. case 'ethertype': num = ETHERTYPES[args[0][0]]; break;
  294. case 'ipprotocol': num = IP_PROTOCOLS[args[0][0]]; break;
  295. }
  296. if (typeof num !== 'number')
  297. num = _parseNum(args[0][0]);
  298. if ((typeof num !== 'number')||(num < 0)||(num > 0xffffffff)||(num === null))
  299. return [ args[0][1],args[0][2],'Invalid numeric value.' ];
  300. let r = {
  301. 'type': KEYWORD_TO_API_MAP[match],
  302. 'not': not,
  303. 'or': or
  304. };
  305. switch(match) {
  306. case 'vlan': r['vlanId'] = num; break;
  307. case 'vlanpcp': r['vlanPcp'] = num; break;
  308. case 'vlandei': r['vlanDei'] = num; break;
  309. case 'ethertype': r['etherType'] = num; break;
  310. case 'ipprotocol': r['ipProtocol'] = num; break;
  311. }
  312. rules.push(r);
  313. } break;
  314. case 'random': {
  315. let num = parseFloat(args[0][0])||0.0;
  316. if (num < 0.0) num = 0.0;
  317. if (num > 1.0) num = 1.0;
  318. rules.push({
  319. 'type': KEYWORD_TO_API_MAP[match],
  320. 'not': not,
  321. 'or': or,
  322. 'probability': Math.floor(4294967295 * num)
  323. });
  324. } break;
  325. case 'macsrc':
  326. case 'macdest': {
  327. let mac = _cleanMac(args[0][0]);
  328. if (mac.length !== 17)
  329. return [ args[0][1],args[0][2],'Invalid MAC address.' ];
  330. rules.push({
  331. 'type': KEYWORD_TO_API_MAP[match],
  332. 'not': not,
  333. 'or': or,
  334. 'mac': mac
  335. });
  336. } break;
  337. case 'ipsrc':
  338. case 'ipdest': {
  339. let ip = args[0][0];
  340. let slashIdx = ip.indexOf('/');
  341. if (slashIdx <= 0)
  342. return [ args[0][1],args[0][2],'Missing /bits netmask length designation in IP.' ];
  343. let ipOnly = ip.substr(0,slashIdx);
  344. if (IPV6_REGEX.test(ipOnly)) {
  345. rules.push({
  346. 'type': ((match === 'ipsrc') ? 'MATCH_IPV6_SOURCE' : 'MATCH_IPV6_DEST'),
  347. 'not': not,
  348. 'or': or,
  349. 'ip': ip
  350. });
  351. } else if (IPV4_REGEX.test(ipOnly)) {
  352. rules.push({
  353. 'type': ((match === 'ipsrc') ? 'MATCH_IPV4_SOURCE' : 'MATCH_IPV4_DEST'),
  354. 'not': not,
  355. 'or': or,
  356. 'ip': ip
  357. });
  358. } else {
  359. return [ args[0][1],args[0][2],'Invalid IP address (not valid IPv4 or IPv6).' ];
  360. }
  361. } break;
  362. case 'icmp': {
  363. let icmpType = _parseNum(args[0][0]);
  364. if ((icmpType < 0)||(icmpType > 0xff))
  365. return [ args[0][1],args[0][2],'Missing or invalid ICMP type.' ];
  366. let icmpCode = _parseNum(args[1][0]); // -1 okay, indicates don't match code
  367. if (icmpCode > 0xff)
  368. return [ args[1][1],args[1][2],'Invalid ICMP code (use -1 for none).' ];
  369. rules.push({
  370. 'type': 'MATCH_ICMP',
  371. 'not': not,
  372. 'or': or,
  373. 'icmpType': icmpType,
  374. 'icmpCode': ((icmpCode < 0) ? null : icmpCode)
  375. });
  376. } break;
  377. case 'sport':
  378. case 'dport':
  379. case 'framesize': {
  380. let arg = args[0][0];
  381. let fn = null;
  382. let tn = null;
  383. if (arg.indexOf('-') > 0) {
  384. let asplit = arg.split('-');
  385. if (asplit.length !== 2) {
  386. return [ args[0][1],args[0][2],'Invalid numeric range.' ];
  387. } else {
  388. fn = _parseNum(asplit[0]);
  389. tn = _parseNum(asplit[1]);
  390. }
  391. } else {
  392. fn = _parseNum(arg);
  393. tn = fn;
  394. }
  395. if ((fn < 0)||(fn > 0xffff)||(tn < 0)||(tn > 0xffff)||(tn < fn))
  396. return [ args[0][1],args[0][2],'Invalid numeric range.' ];
  397. rules.push({
  398. 'type': KEYWORD_TO_API_MAP[match],
  399. 'not': not,
  400. 'or': or,
  401. 'start': fn,
  402. 'end': tn
  403. });
  404. } break;
  405. case 'iptos': {
  406. let mask = _parseNum(args[0][0]);
  407. if ((typeof mask !== 'number')||(mask < 0)||(mask > 0xff)||(mask === null))
  408. return [ args[0][1],args[0][2],'Invalid mask.' ];
  409. let arg = args[1][0];
  410. let fn = null;
  411. let tn = null;
  412. if (arg.indexOf('-') > 0) {
  413. let asplit = arg.split('-');
  414. if (asplit.length !== 2) {
  415. return [ args[1][1],args[1][2],'Invalid value range.' ];
  416. } else {
  417. fn = _parseNum(asplit[0]);
  418. tn = _parseNum(asplit[1]);
  419. }
  420. } else {
  421. fn = _parseNum(arg);
  422. tn = fn;
  423. }
  424. if ((fn < 0)||(fn > 0xff)||(tn < 0)||(tn > 0xff)||(tn < fn))
  425. return [ args[1][1],args[1][2],'Invalid value range.' ];
  426. rules.push({
  427. 'type': 'MATCH_IP_TOS',
  428. 'not': not,
  429. 'or': or,
  430. 'mask': mask,
  431. 'start': fn,
  432. 'end': tn
  433. });
  434. } break;
  435. case 'chr': {
  436. let chrb = args[0][0].split(/[,]+/);
  437. let maskhi = 0;
  438. let masklo = 0;
  439. for(let i=0;i<chrb.length;++i) {
  440. if (chrb[i].length > 0) {
  441. let tmp = CHARACTERISTIC_BITS[chrb[i]];
  442. let bit = (typeof tmp === 'number') ? tmp : _parseNum(chrb[i]);
  443. if ((bit < 0)||(bit > 63))
  444. return [ args[0][1],args[0][2],'Invalid bit index (range 0-63) or unrecognized name.' ];
  445. if (bit >= 32)
  446. maskhi |= Math.abs(1 << (bit - 32));
  447. else masklo |= Math.abs(1 << bit);
  448. }
  449. }
  450. maskhi = Math.abs(maskhi).toString(16);
  451. while (maskhi.length < 8) maskhi = '0' + maskhi;
  452. masklo = Math.abs(masklo).toString(16);
  453. while (masklo.length < 8) masklo = '0' + masklo;
  454. rules.push({
  455. 'type': 'MATCH_CHARACTERISTICS',
  456. 'not': not,
  457. 'or': or,
  458. 'mask': (maskhi + masklo)
  459. });
  460. } break;
  461. case 'tand':
  462. case 'tor':
  463. case 'txor':
  464. case 'tdiff':
  465. case 'teq':
  466. case 'tseq':
  467. case 'treq': {
  468. let tag = tags[args[0][0]];
  469. let tagId = -1;
  470. let tagValue = -1;
  471. if (tag) {
  472. tagId = tag.id;
  473. tagValue = args[1][0];
  474. if (tagValue in tag.flags)
  475. tagValue = tag.flags[tagValue];
  476. else if (tagValue in tag.enums)
  477. tagValue = tag.enums[tagValue];
  478. else tagValue = _parseNum(tagValue);
  479. } else {
  480. tagId = _parseNum(args[0][0]);
  481. tagValue = _parseNum(args[1][0]);
  482. }
  483. if ((tagId < 0)||(tagId > 0xffffffff))
  484. return [ args[0][1],args[0][2],'Undefined tag name and invalid tag value.' ];
  485. if ((tagValue < 0)||(tagValue > 0xffffffff))
  486. return [ args[1][1],args[1][2],'Invalid tag value or unrecognized flag/enum name.' ];
  487. rules.push({
  488. 'type': KEYWORD_TO_API_MAP[match],
  489. 'not': not,
  490. 'or': or,
  491. 'id': tagId,
  492. 'value': tagValue
  493. });
  494. } break;
  495. }
  496. not = false;
  497. or = false;
  498. }
  499. }
  500. return null;
  501. }
  502. function _renderActions(rtree,rules,macros,caps,tags,params)
  503. {
  504. for(let k=0;k<rtree.length;++k) {
  505. let action = (typeof rtree[k][0] === 'string') ? rtree[k][0].toLowerCase() : '';
  506. if (action.length === 0) {
  507. continue;
  508. } else if (action === 'include') {
  509. if ((k + 1) >= rtree.length)
  510. return [ rtree[k][1],rtree[k][2],'Include directive is missing a macro name.' ];
  511. let macroName = rtree[k + 1][0];
  512. ++k;
  513. let macroParamArray = [];
  514. let parenIdx = macroName.indexOf('(');
  515. if (parenIdx > 0) {
  516. let pns = macroName.substr(parenIdx + 1).split(/[,)]+/);
  517. for(let k=0;k<pns.length;++k) {
  518. if (pns[k].length > 0)
  519. macroParamArray.push(pns[k]);
  520. }
  521. macroName = macroName.substr(0,parenIdx);
  522. }
  523. let macro = macros[macroName];
  524. if (!macro)
  525. return [ rtree[k][1],rtree[k][2],'Macro name not found.' ];
  526. let macroParams = {};
  527. for(let param in macro.params) {
  528. let pidx = macro.params[param];
  529. if (pidx >= macroParamArray.length)
  530. return [ rtree[k][1],rtree[k][2],'Missing one or more required macro parameter.' ];
  531. macroParams[param] = macroParamArray[pidx];
  532. }
  533. let err = _renderActions(macro.rules,rules,macros,caps,tags,macroParams);
  534. if (err !== null)
  535. return err;
  536. } else if ((action === 'drop')||(action === 'accept')||(action === 'break')) { // actions without arguments
  537. if (((k + 1) < rtree.length)&&(Array.isArray(rtree[k + 1][0]))) {
  538. let mtree = rtree[k + 1]; ++k;
  539. let err = _renderMatches(mtree,rules,macros,caps,tags,params);
  540. if (err !== null)
  541. return err;
  542. }
  543. rules.push({
  544. 'type': KEYWORD_TO_API_MAP[action]
  545. });
  546. } else if ((action === 'tee')||(action === 'watch')) { // actions with arguments (ZeroTier address)
  547. if (((k + 1) < rtree.length)&&(Array.isArray(rtree[k + 1][0]))&&(rtree[k + 1][0].length >= 2)) {
  548. let mtree = rtree[k + 1]; ++k;
  549. let maxLength = _parseNum(mtree[0][0]);
  550. if ((maxLength < -1)||(maxLength > 0xffff))
  551. return [ mtree[0][1],mtree[1][2],'Tee/watch max packet length to forward invalid or out of range.' ];
  552. let target = mtree[1][0];
  553. if ((typeof target !== 'string')||(target.length !== 10))
  554. return [ mtree[1][1],mtree[1][2],'Missing or invalid ZeroTier address target for tee/watch.' ];
  555. let err = _renderMatches(mtree.slice(2),rules,macros,caps,tags,params);
  556. if (err !== null)
  557. return err;
  558. rules.push({
  559. 'type': KEYWORD_TO_API_MAP[action],
  560. 'address': target,
  561. 'length': maxLength
  562. });
  563. } else {
  564. return [ rtree[k][1],rtree[k][2],'The tee and watch actions require two paremters (max length or 0 for all, target).' ];
  565. }
  566. } else if (action === 'redirect') {
  567. if (((k + 1) < rtree.length)&&(Array.isArray(rtree[k + 1][0]))&&(rtree[k + 1][0].length >= 1)) {
  568. let mtree = rtree[k + 1]; ++k;
  569. let target = mtree[0][0];
  570. if ((typeof target !== 'string')||(target.length !== 10))
  571. return [ mtree[0][1],mtree[0][2],'Missing or invalid ZeroTier address target for redirect.' ];
  572. let err = _renderMatches(mtree.slice(1),rules,macros,caps,tags,params);
  573. if (err !== null)
  574. return err;
  575. rules.push({
  576. 'type': KEYWORD_TO_API_MAP[action],
  577. 'address': target
  578. });
  579. } else {
  580. return [ rtree[k][1],rtree[k][2],'The redirect action requires a target parameter.' ];
  581. }
  582. } else {
  583. return [ rtree[k][1],rtree[k][2],'Unrecognized action or directive in rule set.' ];
  584. }
  585. }
  586. return null;
  587. }
  588. function compile(src,rules,caps,tags)
  589. {
  590. try {
  591. if (typeof src !== 'string')
  592. return [ 0,0,'"src" parameter must be a string.' ];
  593. // Pass 1: parse source into a tree of arrays of elements. Each element is a 3-item
  594. // tuple consisting of string, line number, and character index in line to enable
  595. // informative error messages to be returned.
  596. var blockStack = [ [] ];
  597. var curr = [ '',-1,-1 ];
  598. var skipRestOfLine = false;
  599. for(let idx=0,lineNo=1,lineIdx=0;idx<src.length;++idx,++lineIdx) {
  600. let ch = src.charAt(idx);
  601. if (skipRestOfLine) {
  602. if ((ch === '\r')||(ch === '\n')) {
  603. skipRestOfLine = false;
  604. ++lineNo;
  605. lineIdx = 0;
  606. }
  607. } else {
  608. switch(ch) {
  609. case '\n':
  610. ++lineNo;
  611. lineIdx = 0;
  612. case '\r':
  613. case '\t':
  614. case ' ':
  615. if (curr[0].length > 0) {
  616. let endOfBlock = false;
  617. if (curr[0].charAt(curr[0].length - 1) === ';') {
  618. endOfBlock = true;
  619. curr[0] = curr[0].substr(0,curr[0].length - 1);
  620. }
  621. if (curr[0].length > 0) {
  622. blockStack[blockStack.length - 1].push(curr);
  623. }
  624. if ((endOfBlock)&&(blockStack.length > 1)&&(blockStack[blockStack.length - 1].length > 0)) {
  625. blockStack[blockStack.length - 2].push(blockStack[blockStack.length - 1]);
  626. blockStack.pop();
  627. } else if (curr[0] in OPEN_BLOCK_KEYWORDS) {
  628. blockStack.push([]);
  629. }
  630. curr = [ '',-1,-1 ];
  631. }
  632. break;
  633. default:
  634. if (curr[0].length === 0) {
  635. if (ch === '#') {
  636. skipRestOfLine = true;
  637. continue;
  638. } else {
  639. curr[1] = lineNo;
  640. curr[2] = lineIdx;
  641. }
  642. }
  643. curr[0] += ch;
  644. break;
  645. }
  646. }
  647. }
  648. if (curr[0].length > 0) {
  649. if (curr[0].charAt(curr[0].length - 1) === ';')
  650. curr[0] = curr[0].substr(0,curr[0].length - 1);
  651. if (curr[0].length > 0)
  652. blockStack[blockStack.length - 1].push(curr);
  653. }
  654. while ((blockStack.length > 1)&&(blockStack[blockStack.length - 1].length > 0)) {
  655. blockStack[blockStack.length - 2].push(blockStack[blockStack.length - 1]);
  656. blockStack.pop();
  657. }
  658. var parsed = blockStack[0];
  659. // Pass 2: parse tree into capabilities, tags, rule sets, and document-level rules.
  660. let baseRuleTree = [];
  661. let macros = {};
  662. for(let i=0;i<parsed.length;++i) {
  663. let keyword = (typeof parsed[i][0] === 'string') ? parsed[i][0].toLowerCase() : null;
  664. if (keyword === 'macro') {
  665. // Define macros
  666. if ( ((i + 1) >= parsed.length) || (!Array.isArray(parsed[i + 1])) || (parsed[i + 1].length < 1) || (!Array.isArray(parsed[i + 1][0])) )
  667. return [ parsed[i][1],parsed[i][2],'Macro definition is missing name.' ];
  668. let macro = parsed[++i];
  669. let macroName = macro[0][0].toLowerCase();
  670. let params = {};
  671. let parenIdx = macroName.indexOf('(');
  672. if (parenIdx > 0) {
  673. let pns = macroName.substr(parenIdx + 1).split(/[,)]+/);
  674. for(let k=0;k<pns.length;++k) {
  675. if (pns[k].length > 0)
  676. params[pns[k]] = k;
  677. }
  678. macroName = macroName.substr(0,parenIdx);
  679. }
  680. if (!_isValidName(macroName))
  681. return [ macro[0][1],macro[0][2],'Invalid macro name.' ];
  682. if (macroName in RESERVED_WORDS)
  683. return [ macro[0][1],macro[0][2],'Macro name is a reserved word.' ];
  684. if (macroName in macros)
  685. return [ macro[0][1],macro[0][2],'Multiple definition of macro name.' ];
  686. macros[macroName] = {
  687. params: params,
  688. rules: macro.slice(1)
  689. };
  690. } else if (keyword === 'tag') {
  691. // Define tags
  692. if ( ((i + 1) >= parsed.length) || (!Array.isArray(parsed[i + 1])) || (parsed[i + 1].length < 1) || (!Array.isArray(parsed[i + 1][0])) )
  693. return [ parsed[i][1],parsed[i][2],'Tag definition is missing name.' ];
  694. let tag = parsed[++i];
  695. let tagName = tag[0][0].toLowerCase();
  696. if (!_isValidName(tagName))
  697. return [ tag[0][1],tag[0][2],'Invalid tag name.' ];
  698. if (tagName in RESERVED_WORDS)
  699. return [ tag[0][1],tag[0][2],'Tag name is a reserved word.' ];
  700. if (tagName in tags)
  701. return [ tag[0][1],tag[0][2],'Multiple definition of tag name.' ];
  702. let flags = {};
  703. let enums = {};
  704. let id = -1;
  705. let dfl = null;
  706. for(let k=1;k<tag.length;++k) {
  707. let tkeyword = tag[k][0].toLowerCase();
  708. if (tkeyword === 'id') {
  709. if (id >= 0)
  710. return [ tag[k][1],tag[k][2],'Duplicate tag id definition.' ];
  711. if ((k + 1) >= tag.length)
  712. return [ tag[k][1],tag[k][2],'Missing numeric value for ID.' ];
  713. id = _parseNum(tag[++k][0]);
  714. if ((id < 0)||(id > 0xffffffff))
  715. return [ tag[k][1],tag[k][2],'Invalid or out of range tag ID.' ];
  716. } else if (tkeyword === 'default') {
  717. if (dfl !== null)
  718. return [ tag[k][1],tag[k][2],'Duplicate tag default directive.' ];
  719. if ((k + 1) >= tag.length)
  720. return [ tag[k][1],tag[k][2],'Missing value for default.' ];
  721. dfl = tag[++k][0];
  722. } else if (tkeyword === 'flag') {
  723. if ((k + 2) >= tag.length)
  724. return [ tag[k][1],tag[k][2],'Missing tag flag name or bit index.' ];
  725. ++k;
  726. let bits = tag[k][0].split(/[,]+/);
  727. let mask = 0;
  728. for(let j=0;j<bits.length;++j) {
  729. let b = bits[j].toLowerCase();
  730. if (b in flags) {
  731. mask |= flags[b];
  732. } else {
  733. b = _parseNum(b);
  734. if ((b < 0)||(b > 31))
  735. return [ tag[k][1],tag[k][2],'Bit index invalid, out of range, or references an undefined flag name.' ];
  736. mask |= (1 << b);
  737. }
  738. }
  739. let flagName = tag[++k][0].toLowerCase();
  740. if (!_isValidName(flagName))
  741. return [ tag[k][1],tag[k][2],'Invalid or reserved flag name.' ];
  742. if (flagName in flags)
  743. return [ tag[k][1],tag[k][2],'Duplicate flag name in tag definition.' ];
  744. flags[flagName] = mask;
  745. } else if (tkeyword === 'enum') {
  746. if ((k + 2) >= tag.length)
  747. return [ tag[k][1],tag[k][2],'Missing tag enum name or value.' ];
  748. ++k;
  749. let value = _parseNum(tag[k][0]);
  750. if ((value < 0)||(value > 0xffffffff))
  751. return [ tag[k][1],tag[k][2],'Tag enum value invalid or out of range.' ];
  752. let enumName = tag[++k][0].toLowerCase();
  753. if (!_isValidName(enumName))
  754. return [ tag[k][1],tag[k][2],'Invalid or reserved tag enum name.' ];
  755. if (enumName in enums)
  756. return [ tag[k][1],tag[k][2],'Duplicate enum name in tag definition.' ];
  757. enums[enumName] = value;
  758. } else {
  759. return [ tag[k][1],tag[k][2],'Unrecognized keyword in tag definition.' ];
  760. }
  761. }
  762. if (id < 0)
  763. return [ tag[0][1],tag[0][2],'Tag definition is missing a numeric ID.' ];
  764. if (typeof dfl === 'string') {
  765. let dfl2 = enums[dfl];
  766. if (typeof dfl2 === 'number') {
  767. dfl = dfl2;
  768. } else {
  769. dfl2 = flags[dfl];
  770. if (typeof dfl2 === 'number') {
  771. dfl = dfl2;
  772. } else {
  773. dfl = Math.abs(parseInt(dfl)||0) & 0xffffffff;
  774. }
  775. }
  776. } else if (typeof dfl === 'number') {
  777. dfl = Math.abs(dfl) & 0xffffffff;
  778. }
  779. tags[tagName] = {
  780. 'id': id,
  781. 'default': dfl,
  782. 'enums': enums,
  783. 'flags': flags
  784. };
  785. } else if (keyword === 'cap') {
  786. // Define capabilities
  787. if ( ((i + 1) >= parsed.length) || (!Array.isArray(parsed[i + 1])) || (parsed[i + 1].length < 1) || (!Array.isArray(parsed[i + 1][0])) )
  788. return [ parsed[i][1],parsed[i][2],'Capability definition is missing name.' ];
  789. let cap = parsed[++i];
  790. let capName = cap[0][0].toLowerCase();
  791. if (!_isValidName(capName))
  792. return [ cap[0][1],cap[0][2],'Invalid capability name.' ];
  793. if (capName in RESERVED_WORDS)
  794. return [ cap[0][1],cap[0][2],'Capability name is a reserved word.' ];
  795. if (capName in caps)
  796. return [ cap[0][1],cap[0][2],'Multiple definition of capability name.' ];
  797. let capRules = [];
  798. let id = -1;
  799. let dfl = false;
  800. for(let k=1;k<cap.length;++k) {
  801. let dn = (typeof cap[k][0] === 'string') ? cap[k][0].toLowerCase() : null;
  802. if (dn === 'id') {
  803. if (id >= 0)
  804. return [ cap[k][1],cap[k][2],'Duplicate id directive in capability definition.' ];
  805. if ((k + 1) >= cap.length)
  806. return [ cap[k][1],cap[k][2],'Missing value for ID.' ];
  807. id = _parseNum(cap[++k][0]);
  808. if ((id < 0)||(id > 0xffffffff))
  809. return [ cap[k - 1][1],cap[k - 1][2],'Invalid or out of range capability ID.' ];
  810. for(let cn in caps) {
  811. if (caps[cn].id === id)
  812. return [ cap[k - 1][1],cap[k - 1][2],'Duplicate capability ID.' ];
  813. }
  814. } else if (dn === 'default') {
  815. dfl = true;
  816. } else {
  817. capRules.push(cap[k]);
  818. }
  819. }
  820. if (id < 0)
  821. return [ cap[0][1],cap[0][2],'Capability definition is missing a numeric ID.' ];
  822. caps[capName] = {
  823. 'id': id,
  824. 'default': dfl,
  825. 'rules': capRules
  826. };
  827. } else {
  828. baseRuleTree.push(parsed[i]);
  829. }
  830. }
  831. // Pass 3: render low-level ZeroTier rules arrays for capabilities and base.
  832. for(let capName in caps) {
  833. let r = [];
  834. let err = _renderActions(caps[capName].rules,r,macros,caps,tags,{});
  835. if (err !== null)
  836. return err;
  837. caps[capName].rules = r;
  838. }
  839. let err = _renderActions(baseRuleTree,rules,macros,caps,tags,{});
  840. if (err !== null)
  841. return err;
  842. return null;
  843. } catch (e) {
  844. console.log(e.stack);
  845. return [ 0,0,'Unexpected exception: '+e.toString() ];
  846. }
  847. }
  848. exports.compile = compile;