rule-compiler.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  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. };
  66. // Reserved words that can't be used as tag, capability, or rule set names
  67. const RESERVED_WORDS = {
  68. 'macro': true,
  69. 'tag': true,
  70. 'cap': true,
  71. 'default': true,
  72. 'drop': true,
  73. 'accept': true,
  74. 'tee': true,
  75. 'watch': true,
  76. 'redirect': true,
  77. 'break': true,
  78. 'ztsrc': true,
  79. 'ztdest': true,
  80. 'vlan': true,
  81. 'vlanpcp': true,
  82. 'vlandei': true,
  83. 'ethertype': true,
  84. 'macsrc': true,
  85. 'macdest': true,
  86. 'ipsrc': true,
  87. 'ipdest': true,
  88. 'iptos': true,
  89. 'ipprotocol': true,
  90. 'icmp': true,
  91. 'sport': true,
  92. 'dport': true,
  93. 'chr': true,
  94. 'framesize': true,
  95. 'random': true,
  96. 'tand': true,
  97. 'tor': true,
  98. 'txor': true,
  99. 'tdiff': true,
  100. 'teq': true,
  101. 'tseq': true,
  102. 'treq': true,
  103. 'type': true,
  104. 'enum': true,
  105. 'class': true,
  106. 'define': true,
  107. 'import': true,
  108. 'include': true,
  109. 'log': true,
  110. 'not': true,
  111. 'xor': true,
  112. 'or': true,
  113. 'and': true,
  114. 'set': true,
  115. 'var': true,
  116. 'let': true
  117. };
  118. const KEYWORD_TO_API_MAP = {
  119. 'drop': 'ACTION_DROP',
  120. 'accept': 'ACTION_ACCEPT',
  121. 'tee': 'ACTION_TEE',
  122. 'watch': 'ACTION_WATCH',
  123. 'redirect': 'ACTION_REDIRECT',
  124. 'break': 'ACTION_BREAK',
  125. 'ztsrc': 'MATCH_SOURCE_ZEROTIER_ADDRESS',
  126. 'ztdest': 'MATCH_DEST_ZEROTIER_ADDRESS',
  127. 'vlan': 'MATCH_VLAN_ID',
  128. 'vlanpcp': 'MATCH_VLAN_PCP',
  129. 'vlandei': 'MATCH_VLAN_DEI',
  130. 'ethertype': 'MATCH_ETHERTYPE',
  131. 'macsrc': 'MATCH_MAC_SOURCE',
  132. 'macdest': 'MATCH_MAC_DEST',
  133. //'ipsrc': '', // special handling since we programmatically differentiate between V4 and V6
  134. //'ipdest': '', // special handling
  135. 'iptos': 'MATCH_IP_TOS',
  136. 'ipprotocol': 'MATCH_IP_PROTOCOL',
  137. 'icmp': 'MATCH_ICMP',
  138. 'sport': 'MATCH_IP_SOURCE_PORT_RANGE',
  139. 'dport': 'MATCH_IP_DEST_PORT_RANGE',
  140. 'chr': 'MATCH_CHARACTERISTICS',
  141. 'framesize': 'MATCH_FRAME_SIZE_RANGE',
  142. 'random': 'MATCH_RANDOM',
  143. 'tand': 'MATCH_TAGS_BITWISE_AND',
  144. 'tor': 'MATCH_TAGS_BITWISE_OR',
  145. 'txor': 'MATCH_TAGS_BITWISE_XOR',
  146. 'tdiff': 'MATCH_TAGS_DIFFERENCE',
  147. 'teq': 'MATCH_TAGS_EQUAL',
  148. 'tseq': 'MATCH_TAG_SENDER',
  149. 'treq': 'MATCH_TAG_RECEIVER'
  150. };
  151. // Number of args for each match
  152. const MATCH_ARG_COUNTS = {
  153. 'ztsrc': 1,
  154. 'ztdest': 1,
  155. 'vlan': 1,
  156. 'vlanpcp': 1,
  157. 'vlandei': 1,
  158. 'ethertype': 1,
  159. 'macsrc': 1,
  160. 'macdest': 1,
  161. 'ipsrc': 1,
  162. 'ipdest': 1,
  163. 'iptos': 2,
  164. 'ipprotocol': 1,
  165. 'icmp': 2,
  166. 'sport': 1,
  167. 'dport': 1,
  168. 'chr': 1,
  169. 'framesize': 1,
  170. 'random': 1,
  171. 'tand': 2,
  172. 'tor': 2,
  173. 'txor': 2,
  174. 'tdiff': 2,
  175. 'teq': 2,
  176. 'tseq': 2,
  177. 'treq': 2
  178. };
  179. // Regex of all alphanumeric characters in Unicode
  180. 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]');
  181. // Checks whether something is a valid capability, tag, or macro name
  182. function _isValidName(n)
  183. {
  184. if ((typeof n !== 'string')||(n.length === 0)) return false;
  185. if ("0123456789".indexOf(n.charAt(0)) >= 0) return false;
  186. for(let i=0;i<n.length;++i) {
  187. let c = n.charAt(i);
  188. if ((c !== '_')&&(!INTL_ALPHANUM_REGEX.test(c))) return false;
  189. }
  190. return true;
  191. }
  192. // Regexes for checking the basic syntactic validity of IP addresses
  193. 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]))');
  194. 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])');
  195. function _parseNum(n)
  196. {
  197. try {
  198. if ((typeof n !== 'string')||(n.length === 0))
  199. return -1;
  200. n = n.toLowerCase();
  201. if ((n.length > 2)&&(n.substr(0,2) === '0x'))
  202. n = parseInt(n.substr(2),16);
  203. else n = parseInt(n,10);
  204. return (((typeof n === 'number')&&(n !== null)&&(!isNaN(n))) ? n : -1);
  205. } catch (e) {
  206. return -1;
  207. }
  208. }
  209. function _cleanMac(m)
  210. {
  211. m = m.toLowerCase();
  212. var m2 = '';
  213. for(let i=0;((i<m.length)&&(m2.length<17));++i) {
  214. let c = m.charAt(i);
  215. if ("0123456789abcdef".indexOf(c) >= 0) {
  216. m2 += c;
  217. if ((m2.length > 0)&&(m2.length !== 17)&&((m2.length & 1) === 0))
  218. m2 += ':';
  219. }
  220. }
  221. return m2;
  222. }
  223. function _cleanHex(m)
  224. {
  225. m = m.toLowerCase();
  226. var m2 = '';
  227. for(let i=0;i<m.length;++i) {
  228. let c = m.charAt(i);
  229. if ("0123456789abcdef".indexOf(c) >= 0)
  230. m2 += c;
  231. }
  232. return m2;
  233. }
  234. function _renderMatches(mtree,rules,macros,caps,tags,params)
  235. {
  236. let not = false;
  237. let or = false;
  238. for(let k=0;k<mtree.length;++k) {
  239. let match = (typeof mtree[k][0] === 'string') ? mtree[k][0].toLowerCase() : '';
  240. if ((match.length === 0)||(match === 'and')) { // AND is the default
  241. continue;
  242. } else if (match === 'not') {
  243. not = true;
  244. } else if (match === 'or') {
  245. or = true;
  246. } else {
  247. let args = [];
  248. let argCount = MATCH_ARG_COUNTS[match];
  249. if (!argCount)
  250. return [ mtree[k][1],mtree[k][2],'Unrecognized match type "'+match+'".' ];
  251. for(let i=0;i<argCount;++i) {
  252. if (++k >= mtree.length)
  253. return [ mtree[k - 1][1],mtree[k - 1][2],'Missing argument(s) to match.' ];
  254. let arg = mtree[k][0];
  255. if ((typeof arg !== 'string')||(arg in RESERVED_WORDS)||(arg.length === 0))
  256. return [ mtree[k - 1][1],mtree[k - 1][2],'Missing argument(s) to match (invalid argument or argument is reserved word).' ];
  257. if (arg.charAt(0) === '$') {
  258. let tmp = params[arg];
  259. if (typeof tmp === 'undefined')
  260. return [ mtree[k][1],mtree[k][2],'Undefined variable name.' ];
  261. args.push([ tmp,mtree[k][1],mtree[k][2] ]);
  262. } else {
  263. args.push(mtree[k]);
  264. }
  265. }
  266. switch(match) {
  267. case 'ztsrc':
  268. case 'ztdest': {
  269. let zt = _cleanHex(args[0][0]);
  270. if (zt.length !== 10)
  271. return [ args[0][1],args[0][2],'Invalid ZeroTier address.' ];
  272. rules.push({
  273. 'type': KEYWORD_TO_API_MAP[match],
  274. 'not': not,
  275. 'or': or,
  276. 'zt': zt
  277. });
  278. } break;
  279. case 'vlan':
  280. case 'vlanpcp':
  281. case 'vlandei':
  282. case 'ethertype':
  283. case 'ipprotocol': {
  284. let num = null;
  285. switch (match) {
  286. case 'ethertype': num = ETHERTYPES[args[0][0]]; break;
  287. case 'ipprotocol': num = IP_PROTOCOLS[args[0][0]]; break;
  288. }
  289. if (typeof num !== 'number')
  290. num = _parseNum(args[0][0]);
  291. if ((typeof num !== 'number')||(num < 0)||(num > 0xffffffff)||(num === null))
  292. return [ args[0][1],args[0][2],'Invalid numeric value.' ];
  293. let r = {
  294. 'type': KEYWORD_TO_API_MAP[match],
  295. 'not': not,
  296. 'or': or
  297. };
  298. switch(match) {
  299. case 'vlan': r['vlanId'] = num; break;
  300. case 'vlanpcp': r['vlanPcp'] = num; break;
  301. case 'vlandei': r['vlanDei'] = num; break;
  302. case 'ethertype': r['etherType'] = num; break;
  303. case 'ipprotocol': r['ipProtocol'] = num; break;
  304. }
  305. rules.push(r);
  306. } break;
  307. case 'random': {
  308. let num = parseFloat(args[0][0])||0.0;
  309. if (num < 0.0) num = 0.0;
  310. if (num > 1.0) num = 1.0;
  311. rules.push({
  312. 'type': KEYWORD_TO_API_MAP[match],
  313. 'not': not,
  314. 'or': or,
  315. 'probability': Math.floor(4294967295 * num)
  316. });
  317. } break;
  318. case 'macsrc':
  319. case 'macdest': {
  320. let mac = _cleanMac(args[0][0]);
  321. if (mac.length !== 17)
  322. return [ args[0][1],args[0][2],'Invalid MAC address.' ];
  323. rules.push({
  324. 'type': KEYWORD_TO_API_MAP[match],
  325. 'not': not,
  326. 'or': or,
  327. 'mac': mac
  328. });
  329. } break;
  330. case 'ipsrc':
  331. case 'ipdest': {
  332. let ip = args[0][0];
  333. let slashIdx = ip.indexOf('/');
  334. if (slashIdx <= 0)
  335. return [ args[0][1],args[0][2],'Missing /bits netmask length designation in IP.' ];
  336. let ipOnly = ip.substr(0,slashIdx);
  337. if (IPV6_REGEX.test(ipOnly)) {
  338. rules.push({
  339. 'type': ((match === 'ipsrc') ? 'MATCH_IPV6_SOURCE' : 'MATCH_IPV6_DEST'),
  340. 'not': not,
  341. 'or': or,
  342. 'ip': ip
  343. });
  344. } else if (IPV4_REGEX.test(ipOnly)) {
  345. rules.push({
  346. 'type': ((match === 'ipsrc') ? 'MATCH_IPV4_SOURCE' : 'MATCH_IPV4_DEST'),
  347. 'not': not,
  348. 'or': or,
  349. 'ip': ip
  350. });
  351. } else {
  352. return [ args[0][1],args[0][2],'Invalid IP address (not valid IPv4 or IPv6).' ];
  353. }
  354. } break;
  355. case 'icmp': {
  356. let icmpType = _parseNum(args[0][0]);
  357. if ((icmpType < 0)||(icmpType > 0xff))
  358. return [ args[0][1],args[0][2],'Missing or invalid ICMP type.' ];
  359. let icmpCode = _parseNum(args[1][0]); // -1 okay, indicates don't match code
  360. if (icmpCode > 0xff)
  361. return [ args[1][1],args[1][2],'Invalid ICMP code (use -1 for none).' ];
  362. rules.push({
  363. 'type': 'MATCH_ICMP',
  364. 'not': not,
  365. 'or': or,
  366. 'icmpType': icmpType,
  367. 'icmpCode': ((icmpCode < 0) ? null : icmpCode)
  368. });
  369. } break;
  370. case 'sport':
  371. case 'dport':
  372. case 'framesize': {
  373. let arg = args[0][0];
  374. let fn = null;
  375. let tn = null;
  376. if (arg.indexOf('-') > 0) {
  377. let asplit = arg.split('-');
  378. if (asplit.length !== 2) {
  379. return [ args[0][1],args[0][2],'Invalid numeric range.' ];
  380. } else {
  381. fn = _parseNum(asplit[0]);
  382. tn = _parseNum(asplit[1]);
  383. }
  384. } else {
  385. fn = _parseNum(arg);
  386. tn = fn;
  387. }
  388. if ((fn < 0)||(fn > 0xffff)||(tn < 0)||(tn > 0xffff)||(tn < fn))
  389. return [ args[0][1],args[0][2],'Invalid numeric range.' ];
  390. rules.push({
  391. 'type': KEYWORD_TO_API_MAP[match],
  392. 'not': not,
  393. 'or': or,
  394. 'start': fn,
  395. 'end': tn
  396. });
  397. } break;
  398. case 'iptos': {
  399. let mask = _parseNum(args[0][0]);
  400. if ((typeof mask !== 'number')||(mask < 0)||(mask > 0xff)||(mask === null))
  401. return [ args[0][1],args[0][2],'Invalid mask.' ];
  402. let arg = args[1][0];
  403. let fn = null;
  404. let tn = null;
  405. if (arg.indexOf('-') > 0) {
  406. let asplit = arg.split('-');
  407. if (asplit.length !== 2) {
  408. return [ args[1][1],args[1][2],'Invalid value range.' ];
  409. } else {
  410. fn = _parseNum(asplit[0]);
  411. tn = _parseNum(asplit[1]);
  412. }
  413. } else {
  414. fn = _parseNum(arg);
  415. tn = fn;
  416. }
  417. if ((fn < 0)||(fn > 0xff)||(tn < 0)||(tn > 0xff)||(tn < fn))
  418. return [ args[1][1],args[1][2],'Invalid value range.' ];
  419. rules.push({
  420. 'type': 'MATCH_IP_TOS',
  421. 'not': not,
  422. 'or': or,
  423. 'mask': mask,
  424. 'start': fn,
  425. 'end': tn
  426. });
  427. } break;
  428. case 'chr': {
  429. let chrb = args[0][0].split(/[,]+/);
  430. let maskhi = 0;
  431. let masklo = 0;
  432. for(let i=0;i<chrb.length;++i) {
  433. if (chrb[i].length > 0) {
  434. let tmp = CHARACTERISTIC_BITS[chrb[i]];
  435. let bit = (typeof tmp === 'number') ? tmp : _parseNum(chrb[i]);
  436. if ((bit < 0)||(bit > 63))
  437. return [ args[0][1],args[0][2],'Invalid bit index (range 0-63) or unrecognized name.' ];
  438. if (bit >= 32)
  439. maskhi |= Math.abs(1 << (bit - 32));
  440. else masklo |= Math.abs(1 << bit);
  441. }
  442. }
  443. maskhi = Math.abs(maskhi).toString(16);
  444. while (maskhi.length < 8) maskhi = '0' + maskhi;
  445. masklo = Math.abs(masklo).toString(16);
  446. while (masklo.length < 8) masklo = '0' + masklo;
  447. rules.push({
  448. 'type': 'MATCH_CHARACTERISTICS',
  449. 'not': not,
  450. 'or': or,
  451. 'mask': (maskhi + masklo)
  452. });
  453. } break;
  454. case 'tand':
  455. case 'tor':
  456. case 'txor':
  457. case 'tdiff':
  458. case 'teq':
  459. case 'tseq':
  460. case 'treq': {
  461. let tag = tags[args[0][0]];
  462. let tagId = -1;
  463. let tagValue = -1;
  464. if (tag) {
  465. tagId = tag.id;
  466. tagValue = args[1][0];
  467. if (tagValue in tag.flags)
  468. tagValue = tag.flags[tagValue];
  469. else if (tagValue in tag.enums)
  470. tagValue = tag.enums[tagValue];
  471. else tagValue = _parseNum(tagValue);
  472. } else {
  473. tagId = _parseNum(args[0][0]);
  474. tagValue = _parseNum(args[1][0]);
  475. }
  476. if ((tagId < 0)||(tagId > 0xffffffff))
  477. return [ args[0][1],args[0][2],'Undefined tag name and invalid tag value.' ];
  478. if ((tagValue < 0)||(tagValue > 0xffffffff))
  479. return [ args[1][1],args[1][2],'Invalid tag value or unrecognized flag/enum name.' ];
  480. rules.push({
  481. 'type': KEYWORD_TO_API_MAP[match],
  482. 'not': not,
  483. 'or': or,
  484. 'id': tagId,
  485. 'value': tagValue
  486. });
  487. } break;
  488. }
  489. not = false;
  490. or = false;
  491. }
  492. }
  493. return null;
  494. }
  495. function _renderActions(rtree,rules,macros,caps,tags,params)
  496. {
  497. for(let k=0;k<rtree.length;++k) {
  498. let action = (typeof rtree[k][0] === 'string') ? rtree[k][0].toLowerCase() : '';
  499. if (action.length === 0) {
  500. continue;
  501. } else if (action === 'include') {
  502. if ((k + 1) >= rtree.length)
  503. return [ rtree[k][1],rtree[k][2],'Include directive is missing a macro name.' ];
  504. let macroName = rtree[k + 1][0];
  505. ++k;
  506. let macroParamArray = [];
  507. let parenIdx = macroName.indexOf('(');
  508. if (parenIdx > 0) {
  509. let pns = macroName.substr(parenIdx + 1).split(/[,)]+/);
  510. for(let k=0;k<pns.length;++k) {
  511. if (pns[k].length > 0)
  512. macroParamArray.push(pns[k]);
  513. }
  514. macroName = macroName.substr(0,parenIdx);
  515. }
  516. let macro = macros[macroName];
  517. if (!macro)
  518. return [ rtree[k][1],rtree[k][2],'Macro name not found.' ];
  519. let macroParams = {};
  520. for(let param in macro.params) {
  521. let pidx = macro.params[param];
  522. if (pidx >= macroParamArray.length)
  523. return [ rtree[k][1],rtree[k][2],'Missing one or more required macro parameter.' ];
  524. macroParams[param] = macroParamArray[pidx];
  525. }
  526. let err = _renderActions(macro.rules,rules,macros,caps,tags,macroParams);
  527. if (err !== null)
  528. return err;
  529. } else if ((action === 'drop')||(action === 'accept')||(action === 'break')) { // actions without arguments
  530. if (((k + 1) < rtree.length)&&(Array.isArray(rtree[k + 1][0]))) {
  531. let mtree = rtree[k + 1]; ++k;
  532. let err = _renderMatches(mtree,rules,macros,caps,tags,params);
  533. if (err !== null)
  534. return err;
  535. }
  536. rules.push({
  537. 'type': KEYWORD_TO_API_MAP[action]
  538. });
  539. } else if ((action === 'tee')||(action === 'watch')) { // actions with arguments (ZeroTier address)
  540. if (((k + 1) < rtree.length)&&(Array.isArray(rtree[k + 1][0]))&&(rtree[k + 1][0].length >= 2)) {
  541. let mtree = rtree[k + 1]; ++k;
  542. let maxLength = _parseNum(mtree[0][0]);
  543. if ((maxLength < -1)||(maxLength > 0xffff))
  544. return [ mtree[0][1],mtree[1][2],'Tee/watch max packet length to forward invalid or out of range.' ];
  545. let target = mtree[1][0];
  546. if ((typeof target !== 'string')||(target.length !== 10))
  547. return [ mtree[1][1],mtree[1][2],'Missing or invalid ZeroTier address target for tee/watch.' ];
  548. let err = _renderMatches(mtree.slice(2),rules,macros,caps,tags,params);
  549. if (err !== null)
  550. return err;
  551. rules.push({
  552. 'type': KEYWORD_TO_API_MAP[action],
  553. 'address': target,
  554. 'length': maxLength
  555. });
  556. } else {
  557. return [ rtree[k][1],rtree[k][2],'The tee and watch actions require two paremters (max length or 0 for all, target).' ];
  558. }
  559. } else if (action === 'redirect') {
  560. if (((k + 1) < rtree.length)&&(Array.isArray(rtree[k + 1][0]))&&(rtree[k + 1][0].length >= 1)) {
  561. let mtree = rtree[k + 1]; ++k;
  562. let target = mtree[0][0];
  563. if ((typeof target !== 'string')||(target.length !== 10))
  564. return [ mtree[0][1],mtree[0][2],'Missing or invalid ZeroTier address target for redirect.' ];
  565. let err = _renderMatches(mtree.slice(1),rules,macros,caps,tags,params);
  566. if (err !== null)
  567. return err;
  568. rules.push({
  569. 'type': KEYWORD_TO_API_MAP[action],
  570. 'address': target
  571. });
  572. } else {
  573. return [ rtree[k][1],rtree[k][2],'The redirect action requires a target parameter.' ];
  574. }
  575. } else {
  576. return [ rtree[k][1],rtree[k][2],'Unrecognized action or directive in rule set.' ];
  577. }
  578. }
  579. return null;
  580. }
  581. function compile(src,rules,caps,tags)
  582. {
  583. try {
  584. if (typeof src !== 'string')
  585. return [ 0,0,'"src" parameter must be a string.' ];
  586. // Pass 1: parse source into a tree of arrays of elements. Each element is a 3-item
  587. // tuple consisting of string, line number, and character index in line to enable
  588. // informative error messages to be returned.
  589. var blockStack = [ [] ];
  590. var curr = [ '',-1,-1 ];
  591. var skipRestOfLine = false;
  592. for(let idx=0,lineNo=1,lineIdx=0;idx<src.length;++idx,++lineIdx) {
  593. let ch = src.charAt(idx);
  594. if (skipRestOfLine) {
  595. if ((ch === '\r')||(ch === '\n')) {
  596. skipRestOfLine = false;
  597. ++lineNo;
  598. lineIdx = 0;
  599. }
  600. } else {
  601. switch(ch) {
  602. case '\n':
  603. ++lineNo;
  604. lineIdx = 0;
  605. case '\r':
  606. case '\t':
  607. case ' ':
  608. if (curr[0].length > 0) {
  609. let endOfBlock = false;
  610. if (curr[0].charAt(curr[0].length - 1) === ';') {
  611. endOfBlock = true;
  612. curr[0] = curr[0].substr(0,curr[0].length - 1);
  613. }
  614. if (curr[0].length > 0) {
  615. blockStack[blockStack.length - 1].push(curr);
  616. }
  617. if ((endOfBlock)&&(blockStack.length > 1)&&(blockStack[blockStack.length - 1].length > 0)) {
  618. blockStack[blockStack.length - 2].push(blockStack[blockStack.length - 1]);
  619. blockStack.pop();
  620. } else if (curr[0] in OPEN_BLOCK_KEYWORDS) {
  621. blockStack.push([]);
  622. }
  623. curr = [ '',-1,-1 ];
  624. }
  625. break;
  626. default:
  627. if (curr[0].length === 0) {
  628. if (ch === '#') {
  629. skipRestOfLine = true;
  630. continue;
  631. } else {
  632. curr[1] = lineNo;
  633. curr[2] = lineIdx;
  634. }
  635. }
  636. curr[0] += ch;
  637. break;
  638. }
  639. }
  640. }
  641. if (curr[0].length > 0) {
  642. if (curr[0].charAt(curr[0].length - 1) === ';')
  643. curr[0] = curr[0].substr(0,curr[0].length - 1);
  644. if (curr[0].length > 0)
  645. blockStack[blockStack.length - 1].push(curr);
  646. }
  647. while ((blockStack.length > 1)&&(blockStack[blockStack.length - 1].length > 0)) {
  648. blockStack[blockStack.length - 2].push(blockStack[blockStack.length - 1]);
  649. blockStack.pop();
  650. }
  651. var parsed = blockStack[0];
  652. // Pass 2: parse tree into capabilities, tags, rule sets, and document-level rules.
  653. let baseRuleTree = [];
  654. let macros = {};
  655. for(let i=0;i<parsed.length;++i) {
  656. let keyword = (typeof parsed[i][0] === 'string') ? parsed[i][0].toLowerCase() : null;
  657. if (keyword === 'macro') {
  658. // Define macros
  659. if ( ((i + 1) >= parsed.length) || (!Array.isArray(parsed[i + 1])) || (parsed[i + 1].length < 1) || (!Array.isArray(parsed[i + 1][0])) )
  660. return [ parsed[i][1],parsed[i][2],'Macro definition is missing name.' ];
  661. let macro = parsed[++i];
  662. let macroName = macro[0][0].toLowerCase();
  663. let params = {};
  664. let parenIdx = macroName.indexOf('(');
  665. if (parenIdx > 0) {
  666. let pns = macroName.substr(parenIdx + 1).split(/[,)]+/);
  667. for(let k=0;k<pns.length;++k) {
  668. if (pns[k].length > 0)
  669. params[pns[k]] = k;
  670. }
  671. macroName = macroName.substr(0,parenIdx);
  672. }
  673. if (!_isValidName(macroName))
  674. return [ macro[0][1],macro[0][2],'Invalid macro name.' ];
  675. if (macroName in RESERVED_WORDS)
  676. return [ macro[0][1],macro[0][2],'Macro name is a reserved word.' ];
  677. if (macroName in macros)
  678. return [ macro[0][1],macro[0][2],'Multiple definition of macro name.' ];
  679. macros[macroName] = {
  680. params: params,
  681. rules: macro.slice(1)
  682. };
  683. } else if (keyword === 'tag') {
  684. // Define tags
  685. if ( ((i + 1) >= parsed.length) || (!Array.isArray(parsed[i + 1])) || (parsed[i + 1].length < 1) || (!Array.isArray(parsed[i + 1][0])) )
  686. return [ parsed[i][1],parsed[i][2],'Tag definition is missing name.' ];
  687. let tag = parsed[++i];
  688. let tagName = tag[0][0].toLowerCase();
  689. if (!_isValidName(tagName))
  690. return [ tag[0][1],tag[0][2],'Invalid tag name.' ];
  691. if (tagName in RESERVED_WORDS)
  692. return [ tag[0][1],tag[0][2],'Tag name is a reserved word.' ];
  693. if (tagName in tags)
  694. return [ tag[0][1],tag[0][2],'Multiple definition of tag name.' ];
  695. let flags = {};
  696. let enums = {};
  697. let id = -1;
  698. let dfl = null;
  699. for(let k=1;k<tag.length;++k) {
  700. let tkeyword = tag[k][0].toLowerCase();
  701. if (tkeyword === 'id') {
  702. if (id >= 0)
  703. return [ tag[k][1],tag[k][2],'Duplicate tag id definition.' ];
  704. if ((k + 1) >= tag.length)
  705. return [ tag[k][1],tag[k][2],'Missing numeric value for ID.' ];
  706. id = _parseNum(tag[++k][0]);
  707. if ((id < 0)||(id > 0xffffffff))
  708. return [ tag[k][1],tag[k][2],'Invalid or out of range tag ID.' ];
  709. } else if (tkeyword === 'default') {
  710. if (dfl !== null)
  711. return [ tag[k][1],tag[k][2],'Duplicate tag default directive.' ];
  712. if ((k + 1) >= tag.length)
  713. return [ tag[k][1],tag[k][2],'Missing value for default.' ];
  714. dfl = tag[++k][0]||null;
  715. } else if (tkeyword === 'flag') {
  716. if ((k + 2) >= tag.length)
  717. return [ tag[k][1],tag[k][2],'Missing tag flag name or bit index.' ];
  718. ++k;
  719. let bits = tag[k][0].split(/[,]+/);
  720. let mask = 0;
  721. for(let j=0;j<bits.length;++j) {
  722. let b = bits[j].toLowerCase();
  723. if (b in flags) {
  724. mask |= flags[b];
  725. } else {
  726. b = _parseNum(b);
  727. if ((b < 0)||(b > 31))
  728. return [ tag[k][1],tag[k][2],'Bit index invalid, out of range, or references an undefined flag name.' ];
  729. mask |= (1 << b);
  730. }
  731. }
  732. let flagName = tag[++k][0].toLowerCase();
  733. if (!_isValidName(flagName))
  734. return [ tag[k][1],tag[k][2],'Invalid or reserved flag name.' ];
  735. if (flagName in flags)
  736. return [ tag[k][1],tag[k][2],'Duplicate flag name in tag definition.' ];
  737. flags[flagName] = mask;
  738. } else if (tkeyword === 'enum') {
  739. if ((k + 2) >= tag.length)
  740. return [ tag[k][1],tag[k][2],'Missing tag enum name or value.' ];
  741. ++k;
  742. let value = _parseNum(tag[k][0]);
  743. if ((value < 0)||(value > 0xffffffff))
  744. return [ tag[k][1],tag[k][2],'Tag enum value invalid or out of range.' ];
  745. let enumName = tag[++k][0].toLowerCase();
  746. if (!_isValidName(enumName))
  747. return [ tag[k][1],tag[k][2],'Invalid or reserved tag enum name.' ];
  748. if (enumName in enums)
  749. return [ tag[k][1],tag[k][2],'Duplicate enum name in tag definition.' ];
  750. enums[enumName] = value;
  751. } else {
  752. return [ tag[k][1],tag[k][2],'Unrecognized keyword in tag definition.' ];
  753. }
  754. }
  755. if (id < 0)
  756. return [ tag[0][1],tag[0][2],'Tag definition is missing a numeric ID.' ];
  757. if (dfl) {
  758. let dfl2 = enums[dfl];
  759. if (typeof dfl2 === 'number') {
  760. dfl = dfl2;
  761. } else {
  762. dfl2 = flags[dfl];
  763. if (typeof dfl2 === 'number') {
  764. dfl = dfl2;
  765. } else {
  766. dfl = _parseNum(dfl)||0;
  767. if (dfl < 0)
  768. dfl = 0;
  769. else dfl &= 0xffffffff;
  770. }
  771. }
  772. }
  773. tags[tagName] = {
  774. 'id': id,
  775. 'default': dfl,
  776. 'enums': enums,
  777. 'flags': flags
  778. };
  779. } else if (keyword === 'cap') {
  780. // Define capabilities
  781. if ( ((i + 1) >= parsed.length) || (!Array.isArray(parsed[i + 1])) || (parsed[i + 1].length < 1) || (!Array.isArray(parsed[i + 1][0])) )
  782. return [ parsed[i][1],parsed[i][2],'Capability definition is missing name.' ];
  783. let cap = parsed[++i];
  784. let capName = cap[0][0].toLowerCase();
  785. if (!_isValidName(capName))
  786. return [ cap[0][1],cap[0][2],'Invalid capability name.' ];
  787. if (capName in RESERVED_WORDS)
  788. return [ cap[0][1],cap[0][2],'Capability name is a reserved word.' ];
  789. if (capName in caps)
  790. return [ cap[0][1],cap[0][2],'Multiple definition of capability name.' ];
  791. let capRules = [];
  792. let id = -1;
  793. let dfl = false;
  794. for(let k=1;k<cap.length;++k) {
  795. let dn = (typeof cap[k][0] === 'string') ? cap[k][0].toLowerCase() : null;
  796. if (dn === 'id') {
  797. if (id >= 0)
  798. return [ cap[k][1],cap[k][2],'Duplicate id directive in capability definition.' ];
  799. if ((k + 1) >= cap.length)
  800. return [ cap[k][1],cap[k][2],'Missing value for ID.' ];
  801. id = _parseNum(cap[++k][0]);
  802. if ((id < 0)||(id > 0xffffffff))
  803. return [ cap[k - 1][1],cap[k - 1][2],'Invalid or out of range capability ID.' ];
  804. for(let cn in caps) {
  805. if (caps[cn].id === id)
  806. return [ cap[k - 1][1],cap[k - 1][2],'Duplicate capability ID.' ];
  807. }
  808. } else if (dn === 'default') {
  809. dfl = true;
  810. } else {
  811. capRules.push(cap[k]);
  812. }
  813. }
  814. if (id < 0)
  815. return [ cap[0][1],cap[0][2],'Capability definition is missing a numeric ID.' ];
  816. caps[capName] = {
  817. 'id': id,
  818. 'default': dfl,
  819. 'rules': capRules
  820. };
  821. } else {
  822. baseRuleTree.push(parsed[i]);
  823. }
  824. }
  825. // Pass 3: render low-level ZeroTier rules arrays for capabilities and base.
  826. for(let capName in caps) {
  827. let r = [];
  828. let err = _renderActions(caps[capName].rules,r,macros,caps,tags,{});
  829. if (err !== null)
  830. return err;
  831. caps[capName].rules = r;
  832. }
  833. let err = _renderActions(baseRuleTree,rules,macros,caps,tags,{});
  834. if (err !== null)
  835. return err;
  836. return null;
  837. } catch (e) {
  838. console.log(e.stack);
  839. return [ 0,0,'Unexpected exception: '+e.toString() ];
  840. }
  841. }
  842. exports.compile = compile;