qvm_firewall.py 7.0 KB

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