qvm_firewall.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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 sys
  24. import itertools
  25. import qubesadmin.exc
  26. import qubesadmin.firewall
  27. import qubesadmin.tools
  28. class RuleAction(argparse.Action):
  29. # pylint: disable=too-few-public-methods
  30. '''Parser action for a single firewall rule. It accept syntax:
  31. - <action> [<dsthost> [<proto> [<dstports>|<icmptype>]]]
  32. - action=<action> [specialtarget=dns] [dsthost=<dsthost>]
  33. [proto=<proto>] [dstports=<dstports>] [icmptype=<icmptype>]
  34. Or a mix of them.
  35. '''
  36. def __call__(self, _parser, namespace, values, option_string=None):
  37. if not values:
  38. setattr(namespace, self.dest, None)
  39. return
  40. assumed_order = ['action', 'dsthost', 'proto', 'dstports', 'icmptype']
  41. allowed_opts = assumed_order + ['specialtarget', 'comment']
  42. kwargs = {}
  43. for opt in values:
  44. opt_elements = opt.split('=')
  45. if len(opt_elements) == 2:
  46. key, value = opt_elements
  47. elif len(opt_elements) == 1:
  48. key, value = assumed_order[0], opt
  49. else:
  50. raise argparse.ArgumentError(None,
  51. 'invalid rule description: {}'.format(opt))
  52. if key not in allowed_opts:
  53. raise argparse.ArgumentError(None,
  54. 'Invalid rule element: {}'.format(opt))
  55. kwargs[key] = value
  56. if key in assumed_order:
  57. assumed_order.remove(key)
  58. if key == 'proto' and value in ['tcp', 'udp']:
  59. assumed_order.remove('icmptype')
  60. elif key == 'proto' and value in ['icmp']:
  61. assumed_order.remove('dstports')
  62. rule = qubesadmin.firewall.Rule(None, **kwargs)
  63. setattr(namespace, self.dest, rule)
  64. parser = qubesadmin.tools.QubesArgumentParser(vmname_nargs=1)
  65. action = parser.add_subparsers(dest='command', help='action to perform')
  66. action_add = action.add_parser('add', help='add rule')
  67. action_add.add_argument('--before', type=int, default=None,
  68. help='Add rule before rule with given number, instead of at the end')
  69. action_add.add_argument('rule', nargs='+', action=RuleAction,
  70. help='rule description')
  71. action_del = action.add_parser('del', help='remove rule')
  72. action_del.add_argument('--rule-no', dest='rule_no', type=int,
  73. action='store', help='rule number')
  74. action_del.add_argument('rule', nargs='*', action=RuleAction,
  75. help='rule to be removed')
  76. action_list = action.add_parser('list', help='list rules')
  77. parser.add_argument('--reload', '-r', action='store_true',
  78. help='force reloading rules even when unchanged')
  79. parser.add_argument('--raw', action='store_true',
  80. help='output rules as raw strings, instead of nice table')
  81. def rules_list_table(vm):
  82. '''Print rules to stdout in human-readable form (table)
  83. :param vm: VM object
  84. :return: None
  85. '''
  86. header = ['NO', 'ACTION', 'HOST', 'PROTOCOL', 'PORT(S)',
  87. 'SPECIAL TARGET', 'ICMP TYPE', 'COMMENT']
  88. rows = []
  89. for (rule, rule_no) in zip(vm.firewall.rules, itertools.count()):
  90. row = [str(x) if x is not None else '-' for x in [
  91. rule_no,
  92. rule.action,
  93. rule.dsthost,
  94. rule.proto,
  95. rule.dstports,
  96. rule.specialtarget,
  97. rule.icmptype,
  98. rule.comment,
  99. ]]
  100. rows.append(row)
  101. qubesadmin.tools.print_table([header] + rows)
  102. def rules_list_raw(vm):
  103. '''Print rules in machine-readable form (as specified in Admin API)
  104. :param vm: VM object
  105. :return: None
  106. '''
  107. for rule in vm.firewall.rules:
  108. sys.stdout.write(rule.rule + '\n')
  109. def rules_add(vm, args):
  110. '''Add a rule defined by args.rule'''
  111. if args.before is not None:
  112. vm.firewall.rules.insert(args.before, args.rule)
  113. else:
  114. vm.firewall.rules.append(args.rule)
  115. vm.firewall.save_rules()
  116. def rules_del(vm, args):
  117. '''Delete a rule according to args.rule/args.rule_no'''
  118. if args.rule_no is not None:
  119. vm.firewall.rules.pop(args.rule_no)
  120. else:
  121. vm.firewall.rules.remove(args.rule)
  122. vm.firewall.save_rules()
  123. def main(args=None, app=None):
  124. '''Main routine of :program:`qvm-firewall`.'''
  125. try:
  126. args = parser.parse_args(args, app=app)
  127. vm = args.domains[0]
  128. if args.command == 'add':
  129. rules_add(vm, args)
  130. elif args.command == 'del':
  131. rules_del(vm, args)
  132. elif args.command == 'list':
  133. if args.raw:
  134. rules_list_raw(vm)
  135. else:
  136. rules_list_table(vm)
  137. if args.reload:
  138. vm.firewall.reload()
  139. except qubesadmin.exc.QubesException as e:
  140. parser.print_error(str(e))
  141. return 1
  142. return 0
  143. if __name__ == '__main__':
  144. sys.exit(main())