firewall.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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(x.portBegin) if x.portEnd == None else x.portBegin, reverse = rev)
  165. if idx==2:
  166. self.children.sort(key=attrgetter('protocol'), reverse = rev)
  167. index1 = self.createIndex(0, 0)
  168. index2 = self.createIndex(len(self)-1, len(self.__columnValues)-1)
  169. self.dataChanged.emit(index1, index2)
  170. def get_service_name(self, port):
  171. for service in self.__services:
  172. if service[1] == port:
  173. return service[0]
  174. return str(port)
  175. def get_service_port(self, name):
  176. for service in self.__services:
  177. if service[0] == name:
  178. return service[1]
  179. return None
  180. def get_column_string(self, col, row):
  181. return self.__columnValues[col](row)
  182. def set_vm(self, vm):
  183. self.__vm = vm
  184. self.clearChildren()
  185. conf = vm.get_firewall_conf()
  186. self.allow = conf["allow"]
  187. self.allowDns = conf["allowDns"]
  188. self.allowIcmp = conf["allowIcmp"]
  189. self.allowYumProxy = conf["allowYumProxy"]
  190. for rule in conf["rules"]:
  191. self.appendChild(QubesFirewallRuleItem(
  192. rule["address"], rule["netmask"], rule["portBegin"], rule["portEnd"], rule["proto"]
  193. ))
  194. def get_vm_name(self):
  195. return self.__vm.name
  196. def apply_rules(self, allow, dns, icmp, yumproxy):
  197. assert self.__vm is not None
  198. if(self.allow != allow or self.allowDns != dns or self.allowIcmp != icmp or self.allowYumProxy != yumproxy):
  199. self.fw_changed = True
  200. conf = { "allow": allow,
  201. "allowDns": dns,
  202. "allowIcmp": icmp,
  203. "allowYumProxy": yumproxy,
  204. "rules": list()
  205. }
  206. for rule in self.children:
  207. conf["rules"].append(
  208. {
  209. "address": rule.address,
  210. "netmask": rule.netmask,
  211. "portBegin": rule.portBegin,
  212. "portEnd": rule.portEnd,
  213. "proto": rule.protocol,
  214. }
  215. )
  216. if self.fw_changed:
  217. self.__vm.write_firewall_conf(conf)
  218. if self.__vm.is_running():
  219. vm = self.__vm.netvm
  220. while vm is not None:
  221. if vm.is_proxyvm() and vm.is_running():
  222. vm.write_iptables_xenstore_entry()
  223. vm = vm.netvm
  224. def index(self, row, column, parent=QModelIndex()):
  225. if not self.hasIndex(row, column, parent):
  226. return QModelIndex()
  227. return self.createIndex(row, column, self.children[row])
  228. def parent(self, child):
  229. return QModelIndex()
  230. def rowCount(self, parent=QModelIndex()):
  231. return len(self)
  232. def columnCount(self, parent=QModelIndex()):
  233. return len(self.__columnValues)
  234. def hasChildren(self, index=QModelIndex()):
  235. parentItem = index.internalPointer()
  236. if parentItem is not None:
  237. return parentItem.hasChildren()
  238. else:
  239. return True
  240. def data(self, index, role=Qt.DisplayRole):
  241. if index.isValid() and role == Qt.DisplayRole:
  242. return self.__columnValues[index.column()](index.row())
  243. return QVariant()
  244. def headerData(self, section, orientation, role=Qt.DisplayRole):
  245. if section < len(self.__columnNames) \
  246. and orientation == Qt.Horizontal and role == Qt.DisplayRole:
  247. return self.__columnNames[section]
  248. return QVariant()
  249. @property
  250. def children(self):
  251. return self.__children
  252. def appendChild(self, child):
  253. row = len(self)
  254. self.beginInsertRows(QModelIndex(), row, row)
  255. self.children.append(child)
  256. self.endInsertRows()
  257. index = self.createIndex(row, 0, child)
  258. self.dataChanged.emit(index, index)
  259. def removeChild(self, i):
  260. if i >= len(self):
  261. return
  262. self.beginRemoveRows(QModelIndex(), i, i)
  263. del self.children[i]
  264. self.endRemoveRows()
  265. index = self.createIndex(i, 0)
  266. self.dataChanged.emit(index, index)
  267. def setChild(self, i, child):
  268. self.children[i] = child
  269. index = self.createIndex(i, 0, child)
  270. self.dataChanged.emit(index, index)
  271. def clearChildren(self):
  272. self.__children = list()
  273. def __len__(self):
  274. return len(self.children)