rule-compiler.js 30 KB

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