qvm-firewall 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. #!/usr/bin/python2
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2012 Marek Marczykowski <marmarek@invisiblethingslab.com>
  6. #
  7. # This program is free software; you can redistribute it and/or
  8. # modify it under the terms of the GNU General Public License
  9. # as published by the Free Software Foundation; either version 2
  10. # of the License, or (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
  18. # along with this program; if not, write to the Free Software
  19. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  20. #
  21. #
  22. from qubes.qubes import QubesVmCollection
  23. from optparse import OptionParser;
  24. import subprocess
  25. import sys
  26. import re
  27. import os
  28. services = list()
  29. def load_services():
  30. global services
  31. services = list()
  32. pattern = re.compile("(?P<name>[a-z][a-z0-9-]+)\s+(?P<port>[0-9]+)/(?P<protocol>[a-z]+)", re.IGNORECASE)
  33. f = open('/etc/services', 'r')
  34. for line in f:
  35. match = pattern.match(line)
  36. if match is not None:
  37. service = match.groupdict()
  38. services.append( (service["name"], int(service["port"]), service["protocol"]) )
  39. f.close()
  40. def get_service_name(port):
  41. for service in services:
  42. if service[1] == port:
  43. return service[0]
  44. return str(port)
  45. def get_service_port(name):
  46. for service in services:
  47. if service[0] == name:
  48. return int(service[1])
  49. return None
  50. def parse_rule(args):
  51. if len(args) < 2:
  52. print >>sys.stderr, "ERROR: Rule must have at least address and protocol"
  53. return None
  54. address = args[0]
  55. netmask = 32
  56. proto = args[1]
  57. port = args[2] if len(args) > 2 else None
  58. port_end = None
  59. unmask = address.split("/", 1)
  60. if len(unmask) == 2:
  61. address = unmask[0]
  62. netmask = unmask[1]
  63. if netmask.isdigit():
  64. if re.match("^([0-9]{1,3}\.){3}[0-9]{1,3}$", address) is None:
  65. print >>sys.stderr, "ERROR: Only IP is allowed when specyfying netmask"
  66. return None
  67. if netmask != "":
  68. netmask = int(unmask[1])
  69. if netmask < 0 or netmask > 32:
  70. print >>sys.stderr, "ERROR: Invalid netmask"
  71. return None
  72. else:
  73. print >>sys.stderr, "ERROR: Invalid netmask"
  74. return None
  75. if address[-1:] == ".":
  76. address = address[:-1]
  77. allowed = re.compile("(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE)
  78. if not all(allowed.match(x) for x in address.split(".")):
  79. print >>sys.stderr, "ERROR: Invalid hostname"
  80. return None
  81. proto_split = proto.split('/', 1)
  82. if len(proto_split) == 2:
  83. proto = proto_split[0]
  84. port = proto_split[1]
  85. if proto not in ['tcp', 'udp', 'any']:
  86. print >>sys.stderr, "ERROR: Protocol must be one of: 'tcp', 'udp', 'any'"
  87. return None
  88. if proto != "any" and port is None:
  89. print >>sys.stderr, "ERROR: Port required for protocol %s" % args[1]
  90. return None
  91. if port is not None:
  92. port_range = port.split('-', 1)
  93. if len(port_range) == 2:
  94. port = port_range[0]
  95. port_end = port_range[1]
  96. if get_service_port(port):
  97. port = get_service_port(port)
  98. elif not port.isdigit():
  99. print >>sys.stderr, "ERROR: Invalid port/service name '%s'" % port
  100. return None
  101. else:
  102. port = int(port)
  103. if port_end is not None and not port_end.isdigit():
  104. print >>sys.stderr, "ERROR: Invalid port '%s'" % port_end
  105. return None
  106. if port_end is not None:
  107. port_end = int(port_end)
  108. rule = {}
  109. rule['address'] = address
  110. rule['netmask'] = netmask
  111. rule['proto'] = proto
  112. rule['portBegin'] = port
  113. rule['portEnd'] = port_end
  114. return rule
  115. def list_rules(rules):
  116. fields = [ "num", "address", "proto", "port(s)" ]
  117. rules_to_display = list()
  118. counter = 1
  119. for rule in rules:
  120. parsed_rule = {
  121. 'num': "{0:>2}".format(counter),
  122. 'address': rule['address'] + ('/' + str(rule['netmask']) if rule['netmask'] < 32 else ""),
  123. 'proto': rule['proto'],
  124. 'port(s)': '',
  125. }
  126. if rule['proto'] in ['tcp', 'udp']:
  127. parsed_rule['port(s)'] = str(rule['portBegin']) + \
  128. ('-' + str(rule['portEnd']) if rule['portEnd'] is not None else '')
  129. if rule['portBegin'] is not None and rule['portEnd'] is None:
  130. parsed_rule['port(s)'] = get_service_name(rule['portBegin'])
  131. rules_to_display.append(parsed_rule)
  132. counter += 1
  133. fields_width = {}
  134. for f in fields:
  135. fields_width[f] = len(f)
  136. for r in rules_to_display:
  137. if len(r[f]) > fields_width[f]:
  138. fields_width[f] = len(r[f])
  139. # Display the header
  140. s = ""
  141. for f in fields:
  142. fmt="{{0:-^{0}}}-+".format(fields_width[f] + 1)
  143. s += fmt.format('-')
  144. print s
  145. s = ""
  146. for f in fields:
  147. fmt=" {{0:^{0}}} |".format(fields_width[f])
  148. s += fmt.format(f)
  149. print s
  150. s = ""
  151. for f in fields:
  152. fmt="{{0:-^{0}}}-+".format(fields_width[f] + 1)
  153. s += fmt.format('-')
  154. print s
  155. # And the content
  156. for r in rules_to_display:
  157. s = ""
  158. for f in fields:
  159. fmt=" {{0:<{0}}} |".format(fields_width[f])
  160. s += fmt.format(r[f])
  161. print s
  162. def display_firewall(conf):
  163. print "Firewall policy: %s" % (
  164. "ALLOW all traffic except" if conf['allow'] else "DENY all traffic except")
  165. print "ICMP: %s" % ("ALLOW" if conf['allowIcmp'] else 'DENY')
  166. print "DNS: %s" % ("ALLOW" if conf['allowDns'] else 'DENY')
  167. print "Qubes yum proxy: %s" % ("ALLOW" if conf['allowYumProxy'] else 'DENY')
  168. list_rules(conf['rules'])
  169. def add_rule(conf, args):
  170. rule = parse_rule(args)
  171. if rule is None:
  172. return False
  173. conf['rules'].append(rule)
  174. return True
  175. def del_rule(conf, args):
  176. if len(args) == 1 and args[0].isdigit():
  177. rulenum = int(args[0])
  178. if rulenum < 1 or rulenum > len(conf['rules']):
  179. print >>sys.stderr, "ERROR: Rule number out of range"
  180. return False
  181. conf['rules'].pop(rulenum-1)
  182. else:
  183. rule = parse_rule(args)
  184. #print "PARSED: %s" % str(rule)
  185. #print "ALL: %s" % str(conf['rules'])
  186. if rule is None:
  187. return False
  188. try:
  189. conf['rules'].remove(rule)
  190. except ValueError:
  191. print >>sys.stderr, "ERROR: Rule not found"
  192. return False
  193. return True
  194. def allow_deny_value(s):
  195. value = None
  196. if s == "allow":
  197. value = True
  198. elif s == "deny":
  199. value = False
  200. else:
  201. print >>sys.stderr, 'ERROR: Only "allow" or "deny" allowed'
  202. exit(1)
  203. return value
  204. def main():
  205. usage = "usage: %prog [-n] <vm-name> [action] [rule spec]\n"
  206. usage += " rule specification can be one of:\n"
  207. usage += " address|hostname[/netmask] tcp|udp port[-port]\n"
  208. usage += " address|hostname[/netmask] tcp|udp service_name\n"
  209. usage += " address|hostname[/netmask] any\n"
  210. parser = OptionParser (usage)
  211. parser.add_option ("-l", "--list", dest="do_list", action="store_true", default=True,
  212. help="List firewall settings (default action)")
  213. parser.add_option ("-a", "--add", dest="do_add", action="store_true", default=False,
  214. help="Add rule")
  215. parser.add_option ("-d", "--del", dest="do_del", action="store_true", default=False,
  216. help="Remove rule (given by number or by rule spec)")
  217. parser.add_option ("-P", "--policy", dest="set_policy", action="store", default=None,
  218. help="Set firewall policy (allow/deny)")
  219. parser.add_option ("-i", "--icmp", dest="set_icmp", action="store", default=None,
  220. help="Set ICMP access (allow/deny)")
  221. parser.add_option ("-D", "--dns", dest="set_dns", action="store", default=None,
  222. help="Set DNS access (allow/deny)")
  223. parser.add_option ("-Y", "--yum-proxy", dest="set_yum_proxy", action="store", default=None,
  224. help="Set access to Qubes yum proxy (allow/deny)")
  225. parser.add_option ("-n", "--numeric", dest="numeric", action="store_true", default=False,
  226. help="Display port numbers instead of services (makes sense only with --list)")
  227. parser.add_option ("--force-root", action="store_true", dest="force_root", default=False,
  228. help="Force to run, even with root privileges")
  229. (options, args) = parser.parse_args ()
  230. if (len (args) < 1):
  231. parser.error ("You must specify VM name!")
  232. vmname = args[0]
  233. args = args[1:]
  234. if os.geteuid() == 0:
  235. if not options.force_root:
  236. print >> sys.stderr, "*** Running this tool as root is strongly discouraged, this will lead you in permissions problems."
  237. print >> sys.stderr, "Retry as unprivileged user."
  238. print >> sys.stderr, "... or use --force-root to continue anyway."
  239. exit(1)
  240. if options.do_add or options.do_del or options.set_policy or options.set_icmp or options.set_dns or options.set_yum_proxy:
  241. options.do_list = False
  242. qvm_collection = QubesVmCollection()
  243. if options.do_list:
  244. qvm_collection.lock_db_for_reading()
  245. qvm_collection.load()
  246. qvm_collection.unlock_db()
  247. else:
  248. qvm_collection.lock_db_for_writing()
  249. qvm_collection.load()
  250. vm = qvm_collection.get_vm_by_name(vmname)
  251. if vm is None:
  252. print >> sys.stderr, "A VM with the name '{0}' does not exist in the system.".format(vmname)
  253. exit(1)
  254. changed = False
  255. conf = vm.get_firewall_conf()
  256. if options.set_policy:
  257. conf['allow'] = allow_deny_value(options.set_policy)
  258. changed = True
  259. if options.set_icmp:
  260. conf['allowIcmp'] = allow_deny_value(options.set_icmp)
  261. changed = True
  262. if options.set_dns:
  263. conf['allowDns'] = allow_deny_value(options.set_dns)
  264. changed = True
  265. if options.set_yum_proxy:
  266. conf['allowYumProxy'] = allow_deny_value(options.set_yum_proxy)
  267. changed = True
  268. if options.do_add:
  269. load_services()
  270. changed = add_rule(conf, args)
  271. elif options.do_del:
  272. load_services()
  273. changed = del_rule(conf, args)
  274. elif options.do_list:
  275. if not options.numeric:
  276. load_services()
  277. if not vm.has_firewall():
  278. print "INFO: This VM has no firewall rules set, below defaults are listed"
  279. display_firewall(conf)
  280. if changed:
  281. vm.write_firewall_conf(conf)
  282. if vm.is_running():
  283. if vm.netvm is not None and vm.netvm.is_proxyvm():
  284. vm.netvm.write_iptables_xenstore_entry()
  285. qvm_collection.save()
  286. if not options.do_list:
  287. qvm_collection.unlock_db()
  288. main()