qvm_firewall.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. #
  2. # The Qubes OS Project, http://www.qubes-os.org
  3. #
  4. # Copyright (C) 2016 Marek Marczykowski-Górecki
  5. # <marmarek@invisiblethingslab.com>
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation; either version 2 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License along
  18. # with this program; if not, write to the Free Software Foundation, Inc.,
  19. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20. from __future__ import print_function
  21. import argparse
  22. import sys
  23. import itertools
  24. import qubes.firewall
  25. import qubes.tools
  26. class RuleAction(argparse.Action):
  27. # pylint: disable=too-few-public-methods
  28. '''Parser action for a single firewall rule. It accept syntax:
  29. - <action> [<dsthost> [<proto> [<dstports>|<icmptype>]]]
  30. - action=<action> [specialtarget=dns] [dsthost=<dsthost>]
  31. [proto=<proto>] [dstports=<dstports>] [icmptype=<icmptype>]
  32. Or a mix of them.
  33. '''
  34. def __call__(self, _parser, namespace, values, option_string=None):
  35. if not values:
  36. setattr(namespace, self.dest, None)
  37. return
  38. assumed_order = ['action', 'dsthost', 'proto', 'dstports', 'icmptype']
  39. allowed_opts = assumed_order + ['specialtarget']
  40. kwargs = {}
  41. for opt in values:
  42. opt_elements = opt.split('=')
  43. if len(opt_elements) == 2:
  44. key, value = opt_elements
  45. elif len(opt_elements) == 1:
  46. key, value = assumed_order[0], opt
  47. else:
  48. raise argparse.ArgumentError(None,
  49. 'invalid rule description: {}'.format(opt))
  50. if key not in allowed_opts:
  51. raise argparse.ArgumentError(None,
  52. 'Invalid rule element: {}'.format(opt))
  53. kwargs[key] = value
  54. if key in assumed_order:
  55. assumed_order.remove(key)
  56. if key == 'proto' and value in ['tcp', 'udp']:
  57. assumed_order.remove('icmptype')
  58. elif key == 'proto' and value in ['icmp']:
  59. assumed_order.remove('dstports')
  60. rule = qubes.firewall.Rule(**kwargs)
  61. setattr(namespace, self.dest, rule)
  62. parser = qubes.tools.QubesArgumentParser(vmname_nargs=1)
  63. action = parser.add_subparsers(dest='command', help='action to perform')
  64. action_add = action.add_parser('add', help='add rule')
  65. action_add.add_argument('--before', type=int, default=None,
  66. help='Add rule before rule with given number, instead of at the end')
  67. action_add.add_argument('rule', nargs='+', action=RuleAction,
  68. help='rule description')
  69. action_del = action.add_parser('del', help='remove rule')
  70. action_del.add_argument('--rule-no', dest='rule_no', type=int,
  71. action='store', help='rule number')
  72. action_del.add_argument('rule', nargs='*', action=RuleAction,
  73. help='rule to be removed')
  74. action_list = action.add_parser('list', help='list rules')
  75. action_policy = action.add_parser('policy',
  76. help='get/set policy - default action')
  77. action_policy.add_argument('policy', choices=['accept', 'drop'],
  78. help='policy value', default=None, nargs='?')
  79. parser.add_argument('--reload', '-r', action='store_true',
  80. help='force reloading rules even when unchanged')
  81. parser.add_argument('--raw', action='store_true',
  82. help='output rules as raw strings, instead of nice table')
  83. def rules_list_table(vm):
  84. header = ['NO', 'ACTION', 'HOST', 'PROTOCOL', 'PORT(S)',
  85. 'SPECIAL TARGET', 'ICMP TYPE']
  86. rows = []
  87. for (rule, rule_no) in zip(vm.firewall.rules, itertools.count()):
  88. row = [str(x) if x is not None else '' for x in [
  89. rule_no,
  90. rule.action,
  91. rule.dsthost,
  92. rule.proto,
  93. rule.dstports,
  94. rule.specialtarget,
  95. rule.icmptype,
  96. ]]
  97. rows.append(row)
  98. qubes.tools.print_table([header] + rows)
  99. def rules_list_raw(vm):
  100. for rule in vm.firewall.rules:
  101. sys.stdout.write(rule.rule + '\n')
  102. def rules_add(vm, args):
  103. if args.before is not None:
  104. vm.firewall.rules.insert(args.before, args.rule)
  105. else:
  106. vm.firewall.rules.append(args.rule)
  107. vm.firewall.save()
  108. def rules_del(vm, args):
  109. if args.rule_no is not None:
  110. vm.firewall.rules.pop(args.rule_no)
  111. else:
  112. vm.firewall.rules.remove(args.rule)
  113. vm.firewall.save()
  114. def policy(vm, args):
  115. if args.policy is not None:
  116. vm.firewall.policy = args.policy
  117. vm.firewall.save()
  118. else:
  119. print(vm.firewall.policy)
  120. def main(args=None):
  121. '''Main routine of :program:`qvm-firewall`.'''
  122. try:
  123. args = parser.parse_args(args)
  124. vm = args.domains[0]
  125. if args.command == 'add':
  126. rules_add(vm, args)
  127. elif args.command == 'del':
  128. rules_del(vm, args)
  129. elif args.command == 'policy':
  130. policy(vm, args)
  131. elif args.command == 'list':
  132. if args.raw:
  133. rules_list_raw(vm)
  134. else:
  135. rules_list_table(vm)
  136. if args.reload:
  137. vm.fire_event('firewall-changed')
  138. except qubes.exc.QubesException as e:
  139. parser.print_error(str(e))
  140. return 1
  141. return 0
  142. if __name__ == '__main__':
  143. sys.exit(main())