qvm_firewall.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. # encoding=utf-8
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2016 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU Lesser General Public License as published by
  10. # the Free Software Foundation; either version 2.1 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public License along
  19. # with this program; if not, write to the Free Software Foundation, Inc.,
  20. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. '''qvm-firewall tool'''
  22. import argparse
  23. import datetime
  24. import sys
  25. import itertools
  26. import qubesadmin.exc
  27. import qubesadmin.firewall
  28. import qubesadmin.tools
  29. class RuleAction(argparse.Action):
  30. # pylint: disable=too-few-public-methods
  31. '''Parser action for a single firewall rule. It accept syntax:
  32. - <action> [<dsthost> [<proto> [<dstports>|<icmptype>]]]
  33. - action=<action> [specialtarget=dns] [dsthost=<dsthost>]
  34. [proto=<proto>] [dstports=<dstports>] [icmptype=<icmptype>]
  35. Or a mix of them.
  36. '''
  37. def __call__(self, _parser, namespace, values, option_string=None):
  38. if not values:
  39. setattr(namespace, self.dest, None)
  40. return
  41. assumed_order = ['action', 'forwardtype', 'dsthost', 'proto', 'srcports', 'dstports', 'icmptype']
  42. allowed_opts = assumed_order + ['specialtarget', 'comment', 'expire']
  43. kwargs = {}
  44. for opt in values:
  45. if opt[-1] == '=':
  46. raise argparse.ArgumentError(
  47. None, 'invalid rule description: {}'.format(opt))
  48. opt_elements = opt.split('=')
  49. if len(opt_elements) == 2:
  50. key, value = opt_elements
  51. elif len(opt_elements) == 1:
  52. key, value = assumed_order[0], opt
  53. else:
  54. raise argparse.ArgumentError(None,
  55. 'invalid rule description: {}'.format(opt))
  56. if key in ['dst4', 'dst6']:
  57. key = 'dsthost'
  58. if key not in allowed_opts:
  59. raise argparse.ArgumentError(None,
  60. 'Invalid rule element: {}'.format(opt))
  61. if key == 'expire' and value.startswith('+'):
  62. value = (datetime.datetime.now() +
  63. datetime.timedelta(seconds=int(value[1:]))).\
  64. strftime('%s')
  65. kwargs[key] = value
  66. if key in assumed_order:
  67. assumed_order.remove(key)
  68. if key == 'proto' and value in ['tcp', 'udp']:
  69. assumed_order.remove('icmptype')
  70. elif key == 'proto' and value in ['icmp']:
  71. assumed_order.remove('dstports')
  72. rule = qubesadmin.firewall.Rule(None, **kwargs)
  73. setattr(namespace, self.dest, rule)
  74. epilog = """
  75. Rules can be given as positional arguments:
  76. <action> [<dsthost> [<proto> [<dstports>|<icmptype>]]]
  77. And as keyword arguments:
  78. action=<action> [specialtarget=dns] [dsthost=<dsthost>]
  79. [proto=<proto>] [dstports=<dstports>] [icmptype=<icmptype>]
  80. [expire=<expire>]
  81. Both formats, positional and keyword arguments, can be used
  82. interchangeably.
  83. Available matches:
  84. action accept, drop or forward
  85. forwardtype internal or external (only with action=forward)
  86. dst4 synonym for dsthost
  87. dst6 synonym for dsthost
  88. dsthost IP, network or hostname
  89. (e.g. 10.5.3.2, 192.168.0.0/16,
  90. www.example.com, fd00::/8)
  91. dstports port or port range
  92. (e.g. 443 or 1200-1400)
  93. srcports port in input (only with action=forward)
  94. icmptype icmp type number (e.g. 8 for echo requests)
  95. proto icmp, tcp or udp
  96. specialtarget only the value dns is currently supported,
  97. it matches the configured dns servers of
  98. a VM
  99. expire the rule is automatically removed at the time given as
  100. seconds since 1/1/1970, or +seconds (e.g. +300 for a rule
  101. to expire in 5 minutes)
  102. """
  103. parser = qubesadmin.tools.QubesArgumentParser(vmname_nargs=1, epilog=epilog,
  104. formatter_class=argparse.RawTextHelpFormatter)
  105. action = parser.add_subparsers(dest='command', help='action to perform')
  106. action_add = action.add_parser('add', help='add rule')
  107. action_add.add_argument('--before', type=int, default=None,
  108. help='Add rule before rule with given number instead at the end')
  109. action_add.add_argument('rule', metavar='match', nargs='+', action=RuleAction,
  110. help='rule description')
  111. action_del = action.add_parser('del', help='remove rule')
  112. action_del.add_argument('--rule-no', dest='rule_no', type=int,
  113. action='store', help='rule number')
  114. action_del.add_argument('rule', metavar='match', nargs='*', action=RuleAction,
  115. help='rule to be removed')
  116. action_list = action.add_parser('list', help='list rules')
  117. action_reset = action.add_parser(
  118. 'reset',
  119. help='remove all firewall rules and reset to default '
  120. '(accept all connections)')
  121. parser.add_argument('--reload', '-r', action='store_true',
  122. help='force reload of rules even when unchanged')
  123. parser.add_argument('--raw', action='store_true',
  124. help='output rules as raw strings, instead of nice table')
  125. def rules_list_table(vm):
  126. '''Print rules to stdout in human-readable form (table)
  127. :param vm: VM object
  128. :return: None
  129. '''
  130. header = ['NO', 'ACTION', 'FORWARD TYPE', 'HOST', 'PROTOCOL', 'SRCPORT(S)',
  131. 'DSTPORT(S)', 'SPECIAL TARGET', 'ICMP TYPE', 'EXPIRE', 'COMMENT']
  132. rows = []
  133. for (rule, rule_no) in zip(vm.firewall.rules, itertools.count()):
  134. row = [x.pretty_value if x is not None else '-' for x in [
  135. rule.action,
  136. rule.forwardtype,
  137. rule.dsthost,
  138. rule.proto,
  139. rule.srcports,
  140. rule.dstports,
  141. rule.specialtarget,
  142. rule.icmptype,
  143. rule.expire,
  144. rule.comment,
  145. ]]
  146. rows.append([str(rule_no)] + row)
  147. qubesadmin.tools.print_table([header] + rows)
  148. def rules_list_raw(vm):
  149. '''Print rules in machine-readable form (as specified in Admin API)
  150. :param vm: VM object
  151. :return: None
  152. '''
  153. for rule in vm.firewall.rules:
  154. sys.stdout.write(rule.rule + '\n')
  155. def rules_add(vm, args):
  156. '''Add a rule defined by args.rule'''
  157. if args.before is not None:
  158. vm.firewall.rules.insert(args.before, args.rule)
  159. else:
  160. vm.firewall.rules.append(args.rule)
  161. vm.firewall.save_rules()
  162. def rules_del(vm, args):
  163. '''Delete a rule according to args.rule/args.rule_no'''
  164. if args.rule_no is not None:
  165. vm.firewall.rules.pop(args.rule_no)
  166. else:
  167. vm.firewall.rules.remove(args.rule)
  168. vm.firewall.save_rules()
  169. def main(args=None, app=None):
  170. '''Main routine of :program:`qvm-firewall`.'''
  171. try:
  172. args = parser.parse_args(args, app=app)
  173. vm = args.domains[0]
  174. if args.command == 'add':
  175. rules_add(vm, args)
  176. elif args.command == 'del':
  177. rules_del(vm, args)
  178. elif args.command == 'reset':
  179. vm.firewall.rules.clear()
  180. vm.firewall.rules.append(qubesadmin.firewall.Rule('action=accept'))
  181. vm.firewall.save_rules()
  182. else:
  183. if args.raw:
  184. rules_list_raw(vm)
  185. else:
  186. rules_list_table(vm)
  187. if args.reload:
  188. vm.firewall.reload()
  189. except qubesadmin.exc.QubesException as e:
  190. parser.print_error(str(e))
  191. return 1
  192. return 0
  193. if __name__ == '__main__':
  194. sys.exit(main())