rule-compiler.js 30 KB

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