firewall.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. #
  2. # The Qubes OS Project, http://www.qubes-os.org
  3. #
  4. # Copyright (C) 2011 Tomasz Sterna <tomek@xiaoka.com>
  5. #
  6. # This program is free software; you can redistribute it and/or
  7. # modify it under the terms of the GNU General Public License
  8. # as published by the Free Software Foundation; either version 2
  9. # of the License, or (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program; if not, write to the Free Software
  18. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. #
  20. #
  21. import sys
  22. import os
  23. import re
  24. import xml.etree.ElementTree
  25. from PyQt4.QtCore import *
  26. from PyQt4.QtGui import *
  27. from qubes.qubes import QubesVmCollection
  28. from qubes.qubes import QubesException
  29. from qubes.qubes import dry_run
  30. import ui_newfwruledlg
  31. class QIPAddressValidator(QValidator):
  32. def __init__(self, parent = None):
  33. super (QIPAddressValidator, self).__init__(parent)
  34. def validate(self, input, pos):
  35. hostname = str(input)
  36. if len(hostname) > 255 or len(hostname) == 0:
  37. return (QValidator.Intermediate, pos)
  38. if hostname == "*":
  39. return (QValidator.Acceptable, pos)
  40. unmask = hostname.split("/", 1)
  41. if len(unmask) == 2:
  42. hostname = unmask[0]
  43. mask = unmask[1]
  44. if mask.isdigit() or mask == "":
  45. if re.match("^([0-9]{1,3}\.){3}[0-9]{1,3}$", hostname) is None:
  46. return (QValidator.Invalid, pos)
  47. if mask != "":
  48. mask = int(unmask[1])
  49. if mask < 0 or mask > 32:
  50. return (QValidator.Invalid, pos)
  51. else:
  52. return (QValidator.Invalid, pos)
  53. if hostname[-1:] == ".":
  54. hostname = hostname[:-1]
  55. if hostname[-1:] == "-":
  56. return (QValidator.Intermediate, pos)
  57. allowed = re.compile("(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE)
  58. if all(allowed.match(x) for x in hostname.split(".")):
  59. return (QValidator.Acceptable, pos)
  60. return (QValidator.Invalid, pos)
  61. class NewFwRuleDlg (QDialog, ui_newfwruledlg.Ui_NewFwRuleDlg):
  62. def __init__(self, parent = None):
  63. super (NewFwRuleDlg, self).__init__(parent)
  64. self.setupUi(self)
  65. self.set_ok_enabled(False)
  66. self.addressComboBox.setValidator(QIPAddressValidator())
  67. self.addressComboBox.editTextChanged.connect(self.address_editing_finished)
  68. self.serviceComboBox.setValidator(QRegExpValidator(QRegExp("[a-z][a-z0-9-]+|[0-9]+(-[0-9]+)?", Qt.CaseInsensitive), None))
  69. self.serviceComboBox.setEnabled(False)
  70. self.serviceComboBox.setInsertPolicy(QComboBox.InsertAtBottom)
  71. self.populate_combos()
  72. self.serviceComboBox.setInsertPolicy(QComboBox.InsertAtTop)
  73. def populate_combos(self):
  74. example_addresses = [
  75. "", "www.example.com",
  76. "192.168.1.100", "192.168.0.0/16",
  77. "*"
  78. ]
  79. displayed_services = [
  80. '',
  81. 'http', 'https', 'ftp', 'ftps',
  82. 'smtp', 'pop3', 'pop3s', 'imap', 'imaps', 'nntp', 'nntps',
  83. 'ssh', 'telnet', 'telnets', 'ntp', 'snmp',
  84. 'ldap', 'ldaps', 'irc', 'ircs', 'xmpp-client',
  85. 'syslog', 'printer', 'nfs', 'x11',
  86. '1024-1234'
  87. ]
  88. for address in example_addresses:
  89. self.addressComboBox.addItem(address)
  90. for service in displayed_services:
  91. self.serviceComboBox.addItem(service)
  92. def address_editing_finished(self):
  93. self.set_ok_enabled(True)
  94. def set_ok_enabled(self, on):
  95. ok_button = self.buttonBox.button(QDialogButtonBox.Ok)
  96. if ok_button is not None:
  97. ok_button.setEnabled(on)
  98. def on_tcp_radio_toggled(self, checked):
  99. if checked:
  100. self.serviceComboBox.setEnabled(True)
  101. def on_udp_radio_toggled(self, checked):
  102. if checked:
  103. self.serviceComboBox.setEnabled(True)
  104. def on_any_radio_toggled(self, checked):
  105. if checked:
  106. self.serviceComboBox.setEnabled(False)
  107. class QubesFirewallRuleItem(object):
  108. def __init__(self, address = str(), netmask = 32, portBegin = 0, portEnd = None, protocol = "any"):
  109. self.__address = address
  110. self.__netmask = netmask
  111. self.__portBegin = portBegin
  112. self.__portEnd = portEnd
  113. self.__protocol = protocol
  114. @property
  115. def address(self):
  116. return self.__address
  117. @property
  118. def netmask(self):
  119. return self.__netmask
  120. @property
  121. def portBegin(self):
  122. return self.__portBegin
  123. @property
  124. def portEnd(self):
  125. return self.__portEnd
  126. @property
  127. def protocol(self):
  128. return self.__protocol
  129. def hasChildren(self):
  130. return False
  131. class QubesFirewallRulesModel(QAbstractItemModel):
  132. def __init__(self, parent=None):
  133. QAbstractItemModel.__init__(self, parent)
  134. self.__columnValues = {
  135. 0: lambda x: "*" if self.children[x].address == "0.0.0.0" and self.children[x].netmask == 0 \
  136. else self.children[x].address + ("" if self.children[x].netmask == 32 \
  137. else " /{0}".format(self.children[x].netmask)),
  138. 1: lambda x: "any" if self.children[x].portBegin == 0 \
  139. else "{0}-{1}".format(self.children[x].portBegin, self.children[x].portEnd) if self.children[x].portEnd is not None \
  140. else self.get_service_name(self.children[x].portBegin),
  141. 2: lambda x: self.children[x].protocol,
  142. }
  143. self.__columnNames = {
  144. 0: "Address",
  145. 1: "Service",
  146. 2: "Protocol",
  147. }
  148. self.__services = list()
  149. pattern = re.compile("(?P<name>[a-z][a-z0-9-]+)\s+(?P<port>[0-9]+)/(?P<protocol>[a-z]+)", re.IGNORECASE)
  150. f = open('/etc/services', 'r')
  151. for line in f:
  152. match = pattern.match(line)
  153. if match is not None:
  154. service = match.groupdict()
  155. self.__services.append( (service["name"], int(service["port"]),) )
  156. f.close()
  157. self.fw_changed = False
  158. def sort(self, idx, order):
  159. from operator import attrgetter
  160. rev = (order == Qt.AscendingOrder)
  161. if idx==0:
  162. self.children.sort(key=attrgetter('address'), reverse = rev)
  163. if idx==1:
  164. self.children.sort(key=lambda x: self.get_service_name(attrgetter('portBegin')) if attrgetter('portEnd') == None else attrgetter('portBegin'), reverse = rev)
  165. if idx==2:
  166. self.children.sort(key=attrgetter('protocol'), reverse = rev)
  167. def get_service_name(self, port):
  168. for service in self.__services:
  169. if service[1] == port:
  170. return service[0]
  171. return str(port)
  172. def get_service_port(self, name):
  173. for service in self.__services:
  174. if service[0] == name:
  175. return service[1]
  176. return None
  177. def get_column_string(self, col, row):
  178. return self.__columnValues[col](row)
  179. def set_vm(self, vm):
  180. self.__vm = vm
  181. self.clearChildren()
  182. conf = vm.get_firewall_conf()
  183. self.allow = conf["allow"]
  184. self.allowDns = conf["allowDns"]
  185. self.allowIcmp = conf["allowIcmp"]
  186. for rule in conf["rules"]:
  187. self.appendChild(QubesFirewallRuleItem(
  188. rule["address"], rule["netmask"], rule["portBegin"], rule["portEnd"], rule["proto"]
  189. ))
  190. def get_vm_name(self):
  191. return self.__vm.name
  192. def apply_rules(self, allow, dns, icmp):
  193. assert self.__vm is not None
  194. if(self.allow != allow or self.allowDns != dns or self.allowIcmp != icmp):
  195. self.fw_changed = True
  196. conf = { "allow": allow,
  197. "allowDns": dns,
  198. "allowIcmp": icmp,
  199. "rules": list()
  200. }
  201. for rule in self.children:
  202. conf["rules"].append(
  203. {
  204. "address": rule.address,
  205. "netmask": rule.netmask,
  206. "portBegin": rule.portBegin,
  207. "portEnd": rule.portEnd,
  208. "proto": rule.protocol,
  209. }
  210. )
  211. if self.fw_changed:
  212. self.__vm.write_firewall_conf(conf)
  213. qvm_collection = QubesVmCollection()
  214. qvm_collection.lock_db_for_reading()
  215. qvm_collection.load()
  216. qvm_collection.unlock_db()
  217. for vm in qvm_collection.values():
  218. if vm.is_proxyvm():
  219. vm.write_iptables_xenstore_entry()
  220. def index(self, row, column, parent=QModelIndex()):
  221. if not self.hasIndex(row, column, parent):
  222. return QModelIndex()
  223. return self.createIndex(row, column, self.children[row])
  224. def parent(self, child):
  225. return QModelIndex()
  226. def rowCount(self, parent=QModelIndex()):
  227. return len(self)
  228. def columnCount(self, parent=QModelIndex()):
  229. return len(self.__columnValues)
  230. def hasChildren(self, index=QModelIndex()):
  231. parentItem = index.internalPointer()
  232. if parentItem is not None:
  233. return parentItem.hasChildren()
  234. else:
  235. return True
  236. def data(self, index, role=Qt.DisplayRole):
  237. if index.isValid() and role == Qt.DisplayRole:
  238. return self.__columnValues[index.column()](index.row())
  239. return QVariant()
  240. def headerData(self, section, orientation, role=Qt.DisplayRole):
  241. if section < len(self.__columnNames) \
  242. and orientation == Qt.Horizontal and role == Qt.DisplayRole:
  243. return self.__columnNames[section]
  244. return QVariant()
  245. @property
  246. def children(self):
  247. return self.__children
  248. def appendChild(self, child):
  249. row = len(self)
  250. self.beginInsertRows(QModelIndex(), row, row)
  251. self.children.append(child)
  252. self.endInsertRows()
  253. index = self.createIndex(row, 0, child)
  254. self.dataChanged.emit(index, index)
  255. def removeChild(self, i):
  256. if i >= len(self):
  257. return
  258. self.beginRemoveRows(QModelIndex(), i, i)
  259. del self.children[i]
  260. self.endRemoveRows()
  261. index = self.createIndex(i, 0)
  262. self.dataChanged.emit(index, index)
  263. def setChild(self, i, child):
  264. self.children[i] = child
  265. index = self.createIndex(i, 0, child)
  266. self.dataChanged.emit(index, index)
  267. def clearChildren(self):
  268. self.__children = list()
  269. def __len__(self):
  270. return len(self.children)