qvm_firewall.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. 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. dst4 synonym for dsthost
  86. dst6 synonym for dsthost
  87. dsthost IP, network or hostname
  88. (e.g. 10.5.3.2, 192.168.0.0/16,
  89. www.example.com, fd00::/8)
  90. dstports port or port range
  91. (e.g. 443 or 1200-1400)
  92. icmptype icmp type number (e.g. 8 for echo requests)
  93. proto icmp, tcp or udp
  94. specialtarget only the value dns is currently supported,
  95. it matches the configured dns servers of
  96. a VM
  97. expire the rule is automatically removed at the time given as
  98. seconds since 1/1/1970, or +seconds (e.g. +300 for a rule
  99. to expire in 5 minutes)
  100. """
  101. parser = qubesadmin.tools.QubesArgumentParser(vmname_nargs=1, epilog=epilog,
  102. formatter_class=argparse.RawTextHelpFormatter)
  103. action = parser.add_subparsers(dest='command', help='action to perform')
  104. action_add = action.add_parser('add', help='add rule')
  105. action_add.add_argument('--before', type=int, default=None,
  106. help='Add rule before rule with given number instead at the end')
  107. action_add.add_argument('rule', metavar='match', nargs='+', action=RuleAction,
  108. help='rule description')
  109. action_del = action.add_parser('del', help='remove rule')
  110. action_del.add_argument('--rule-no', dest='rule_no', type=int,
  111. action='store', help='rule number')
  112. action_del.add_argument('rule', metavar='match', nargs='*', action=RuleAction,
  113. help='rule to be removed')
  114. action_list = action.add_parser('list', help='list rules')
  115. action_reset = action.add_parser(
  116. 'reset',
  117. help='remove all firewall rules and reset to default '
  118. '(accept all connections)')
  119. parser.add_argument('--reload', '-r', action='store_true',
  120. help='force reload of rules even when unchanged')
  121. parser.add_argument('--raw', action='store_true',
  122. help='output rules as raw strings, instead of nice table')
  123. def rules_list_table(vm):
  124. '''Print rules to stdout in human-readable form (table)
  125. :param vm: VM object
  126. :return: None
  127. '''
  128. header = ['NO', 'ACTION', 'HOST', 'PROTOCOL', 'PORT(S)',
  129. 'SPECIAL TARGET', 'ICMP TYPE', 'EXPIRE', 'COMMENT']
  130. rows = []
  131. for (rule, rule_no) in zip(vm.firewall.rules, itertools.count()):
  132. row = [x.pretty_value if x is not None else '-' for x in [
  133. rule.action,
  134. rule.dsthost,
  135. rule.proto,
  136. rule.dstports,
  137. rule.specialtarget,
  138. rule.icmptype,
  139. rule.expire,
  140. rule.comment,
  141. ]]
  142. rows.append([str(rule_no)] + row)
  143. qubesadmin.tools.print_table([header] + rows)
  144. def rules_list_raw(vm):
  145. '''Print rules in machine-readable form (as specified in Admin API)
  146. :param vm: VM object
  147. :return: None
  148. '''
  149. for rule in vm.firewall.rules:
  150. sys.stdout.write(rule.rule + '\n')
  151. def rules_add(vm, args):
  152. '''Add a rule defined by args.rule'''
  153. if args.before is not None:
  154. vm.firewall.rules.insert(args.before, args.rule)
  155. else:
  156. vm.firewall.rules.append(args.rule)
  157. vm.firewall.save_rules()
  158. def rules_del(vm, args):
  159. '''Delete a rule according to args.rule/args.rule_no'''
  160. if args.rule_no is not None:
  161. vm.firewall.rules.pop(args.rule_no)
  162. else:
  163. vm.firewall.rules.remove(args.rule)
  164. vm.firewall.save_rules()
  165. def main(args=None, app=None):
  166. '''Main routine of :program:`qvm-firewall`.'''
  167. try:
  168. args = parser.parse_args(args, app=app)
  169. vm = args.domains[0]
  170. if args.command == 'add':
  171. rules_add(vm, args)
  172. elif args.command == 'del':
  173. rules_del(vm, args)
  174. elif args.command == 'reset':
  175. vm.firewall.rules.clear()
  176. vm.firewall.rules.append(qubesadmin.firewall.Rule('action=accept'))
  177. vm.firewall.save_rules()
  178. else:
  179. if args.raw:
  180. rules_list_raw(vm)
  181. else:
  182. rules_list_table(vm)
  183. if args.reload:
  184. vm.firewall.reload()
  185. except qubesadmin.exc.QubesException as e:""
  186. parser.print_error(str(e))
  187. return 1
  188. return 0
  189. if __name__ == '__main__':
  190. sys.exit(main())