qvm_firewall.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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', 'dsthost', 'proto', 'dstports', 'icmptype']
  42. allowed_opts = assumed_order + ['specialtarget', 'comment', 'expire']
  43. kwargs = {}
  44. for opt in values:
  45. opt_elements = opt.split('=')
  46. if len(opt_elements) == 2:
  47. key, value = opt_elements
  48. elif len(opt_elements) == 1:
  49. key, value = assumed_order[0], opt
  50. else:
  51. raise argparse.ArgumentError(None,
  52. 'invalid rule description: {}'.format(opt))
  53. if key in ['dst4', 'dst6']:
  54. key = 'dsthost'
  55. if key not in allowed_opts:
  56. raise argparse.ArgumentError(None,
  57. 'Invalid rule element: {}'.format(opt))
  58. if key == 'expire' and value.startswith('+'):
  59. value = (datetime.datetime.now() +
  60. datetime.timedelta(seconds=int(value[1:]))).\
  61. strftime('%s')
  62. kwargs[key] = value
  63. if key in assumed_order:
  64. assumed_order.remove(key)
  65. if key == 'proto' and value in ['tcp', 'udp']:
  66. assumed_order.remove('icmptype')
  67. elif key == 'proto' and value in ['icmp']:
  68. assumed_order.remove('dstports')
  69. rule = qubesadmin.firewall.Rule(None, **kwargs)
  70. setattr(namespace, self.dest, rule)
  71. epilog = """
  72. Rules can be given as positional arguments:
  73. <action> [<dsthost> [<proto> [<dstports>|<icmptype>]]]
  74. And as keyword arguments:
  75. action=<action> [specialtarget=dns] [dsthost=<dsthost>]
  76. [proto=<proto>] [dstports=<dstports>] [icmptype=<icmptype>]
  77. [expire=<expire>]
  78. Both formats, positional and keyword arguments, can be used
  79. interchangeably.
  80. Available matches:
  81. action: accept or drop
  82. dst4 synonym for dsthost
  83. dst6 synonym for dsthost
  84. dsthost IP, network or hostname
  85. (e.g. 10.5.3.2, 192.168.0.0/16,
  86. www.example.com, fd00::/8)
  87. dstports port or port range
  88. (e.g. 443 or 1200-1400)
  89. icmptype icmp type number (e.g. 8 for echo requests)
  90. proto icmp, tcp or udp
  91. specialtarget only the value dns is currently supported,
  92. it matches the configured dns servers of
  93. a VM
  94. expire the rule is automatically removed at the time given as
  95. seconds since 1/1/1970, or +seconds (e.g. +300 for a rule
  96. to expire in 5 minutes)
  97. """
  98. parser = qubesadmin.tools.QubesArgumentParser(vmname_nargs=1, epilog=epilog,
  99. formatter_class=argparse.RawTextHelpFormatter)
  100. action = parser.add_subparsers(dest='command', help='action to perform')
  101. action_add = action.add_parser('add', help='add rule')
  102. action_add.add_argument('--before', type=int, default=None,
  103. help='Add rule before rule with given number instead at the end')
  104. action_add.add_argument('rule', metavar='match', nargs='+', action=RuleAction,
  105. help='rule description')
  106. action_del = action.add_parser('del', help='remove rule')
  107. action_del.add_argument('--rule-no', dest='rule_no', type=int,
  108. action='store', help='rule number')
  109. action_del.add_argument('rule', metavar='match', nargs='*', action=RuleAction,
  110. help='rule to be removed')
  111. action_list = action.add_parser('list', help='list rules')
  112. action_reset = action.add_parser(
  113. 'reset',
  114. help='remove all firewall rules and reset to default '
  115. '(accept all connections)')
  116. parser.add_argument('--reload', '-r', action='store_true',
  117. help='force reload of rules even when unchanged')
  118. parser.add_argument('--raw', action='store_true',
  119. help='output rules as raw strings, instead of nice table')
  120. def rules_list_table(vm):
  121. '''Print rules to stdout in human-readable form (table)
  122. :param vm: VM object
  123. :return: None
  124. '''
  125. header = ['NO', 'ACTION', 'HOST', 'PROTOCOL', 'PORT(S)',
  126. 'SPECIAL TARGET', 'ICMP TYPE', 'EXPIRE', 'COMMENT']
  127. rows = []
  128. for (rule, rule_no) in zip(vm.firewall.rules, itertools.count()):
  129. row = [x.pretty_value if x is not None else '-' for x in [
  130. rule.action,
  131. rule.dsthost,
  132. rule.proto,
  133. rule.dstports,
  134. rule.specialtarget,
  135. rule.icmptype,
  136. rule.expire,
  137. rule.comment,
  138. ]]
  139. rows.append([str(rule_no)] + row)
  140. qubesadmin.tools.print_table([header] + rows)
  141. def rules_list_raw(vm):
  142. '''Print rules in machine-readable form (as specified in Admin API)
  143. :param vm: VM object
  144. :return: None
  145. '''
  146. for rule in vm.firewall.rules:
  147. sys.stdout.write(rule.rule + '\n')
  148. def rules_add(vm, args):
  149. '''Add a rule defined by args.rule'''
  150. if args.before is not None:
  151. vm.firewall.rules.insert(args.before, args.rule)
  152. else:
  153. vm.firewall.rules.append(args.rule)
  154. vm.firewall.save_rules()
  155. def rules_del(vm, args):
  156. '''Delete a rule according to args.rule/args.rule_no'''
  157. if args.rule_no is not None:
  158. vm.firewall.rules.pop(args.rule_no)
  159. else:
  160. vm.firewall.rules.remove(args.rule)
  161. vm.firewall.save_rules()
  162. def main(args=None, app=None):
  163. '''Main routine of :program:`qvm-firewall`.'''
  164. try:
  165. args = parser.parse_args(args, app=app)
  166. vm = args.domains[0]
  167. if args.command == 'add':
  168. rules_add(vm, args)
  169. elif args.command == 'del':
  170. rules_del(vm, args)
  171. elif args.command == 'reset':
  172. vm.firewall.rules.clear()
  173. vm.firewall.rules.append(qubesadmin.firewall.Rule('action=accept'))
  174. vm.firewall.save_rules()
  175. else:
  176. if args.raw:
  177. rules_list_raw(vm)
  178. else:
  179. rules_list_table(vm)
  180. if args.reload:
  181. vm.firewall.reload()
  182. except qubesadmin.exc.QubesException as e:
  183. parser.print_error(str(e))
  184. return 1
  185. return 0
  186. if __name__ == '__main__':
  187. sys.exit(main())