firewall.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. import datetime
  28. from qubes.qubes import QubesVmCollection
  29. from qubes.qubes import QubesException
  30. from qubes.qubes import dry_run
  31. import ui_newfwruledlg
  32. class QIPAddressValidator(QValidator):
  33. def __init__(self, parent = None):
  34. super (QIPAddressValidator, self).__init__(parent)
  35. def validate(self, input, pos):
  36. hostname = str(input)
  37. if len(hostname) > 255 or len(hostname) == 0:
  38. return (QValidator.Intermediate, pos)
  39. if hostname == "*":
  40. return (QValidator.Acceptable, pos)
  41. unmask = hostname.split("/", 1)
  42. if len(unmask) == 2:
  43. hostname = unmask[0]
  44. mask = unmask[1]
  45. if mask.isdigit() or mask == "":
  46. if re.match("^([0-9]{1,3}\.){3}[0-9]{1,3}$", hostname) is None:
  47. return (QValidator.Invalid, pos)
  48. if mask != "":
  49. mask = int(unmask[1])
  50. if mask < 0 or mask > 32:
  51. return (QValidator.Invalid, pos)
  52. else:
  53. return (QValidator.Invalid, pos)
  54. if hostname[-1:] == ".":
  55. hostname = hostname[:-1]
  56. if hostname[-1:] == "-":
  57. return (QValidator.Intermediate, pos)
  58. allowed = re.compile("(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE)
  59. if all(allowed.match(x) for x in hostname.split(".")):
  60. return (QValidator.Acceptable, pos)
  61. return (QValidator.Invalid, pos)
  62. class NewFwRuleDlg (QDialog, ui_newfwruledlg.Ui_NewFwRuleDlg):
  63. def __init__(self, parent = None):
  64. super (NewFwRuleDlg, self).__init__(parent)
  65. self.setupUi(self)
  66. self.set_ok_enabled(False)
  67. self.addressComboBox.setValidator(QIPAddressValidator())
  68. self.addressComboBox.editTextChanged.connect(self.address_editing_finished)
  69. self.serviceComboBox.setValidator(QRegExpValidator(QRegExp("[a-z][a-z0-9-]+|[0-9]+(-[0-9]+)?", Qt.CaseInsensitive), None))
  70. self.serviceComboBox.setEnabled(False)
  71. self.serviceComboBox.setInsertPolicy(QComboBox.InsertAtBottom)
  72. self.populate_combos()
  73. self.serviceComboBox.setInsertPolicy(QComboBox.InsertAtTop)
  74. def populate_combos(self):
  75. example_addresses = [
  76. "", "www.example.com",
  77. "192.168.1.100", "192.168.0.0/16",
  78. "*"
  79. ]
  80. displayed_services = [
  81. '',
  82. 'http', 'https', 'ftp', 'ftps',
  83. 'smtp', 'pop3', 'pop3s', 'imap', 'imaps', 'nntp', 'nntps',
  84. 'ssh', 'telnet', 'telnets', 'ntp', 'snmp',
  85. 'ldap', 'ldaps', 'irc', 'ircs', 'xmpp-client',
  86. 'syslog', 'printer', 'nfs', 'x11',
  87. '1024-1234'
  88. ]
  89. for address in example_addresses:
  90. self.addressComboBox.addItem(address)
  91. for service in displayed_services:
  92. self.serviceComboBox.addItem(service)
  93. def address_editing_finished(self):
  94. self.set_ok_enabled(True)
  95. def set_ok_enabled(self, on):
  96. ok_button = self.buttonBox.button(QDialogButtonBox.Ok)
  97. if ok_button is not None:
  98. ok_button.setEnabled(on)
  99. def on_tcp_radio_toggled(self, checked):
  100. if checked:
  101. self.serviceComboBox.setEnabled(True)
  102. def on_udp_radio_toggled(self, checked):
  103. if checked:
  104. self.serviceComboBox.setEnabled(True)
  105. def on_any_radio_toggled(self, checked):
  106. if checked:
  107. self.serviceComboBox.setEnabled(False)
  108. class QubesFirewallRulesModel(QAbstractItemModel):
  109. def __init__(self, parent=None):
  110. QAbstractItemModel.__init__(self, parent)
  111. self.__columnValues = {
  112. 0: lambda x: "*" if self.children[x]["address"] == "0.0.0.0" and
  113. self.children[x]["netmask"] == 0 else
  114. self.children[x]["address"] + ("" if self.children[x][ "netmask"] == 32 else
  115. " /{0}".format(self.children[x][
  116. "netmask"])),
  117. 1: lambda x: "any" if self.children[x]["portBegin"] == 0 else
  118. "{0}-{1}".format(self.children[x]["portBegin"], self.children[x][
  119. "portEnd"]) if self.children[x]["portEnd"] is not None else \
  120. self.get_service_name(self.children[x]["portBegin"]),
  121. 2: lambda x: self.children[x]["proto"], }
  122. self.__columnNames = {0: "Address", 1: "Service", 2: "Protocol", }
  123. self.__services = list()
  124. pattern = re.compile("(?P<name>[a-z][a-z0-9-]+)\s+(?P<port>[0-9]+)/(?P<protocol>[a-z]+)", re.IGNORECASE)
  125. f = open('/etc/services', 'r')
  126. for line in f:
  127. match = pattern.match(line)
  128. if match is not None:
  129. service = match.groupdict()
  130. self.__services.append( (service["name"], int(service["port"]),) )
  131. f.close()
  132. self.fw_changed = False
  133. def sort(self, idx, order):
  134. from operator import attrgetter
  135. rev = (order == Qt.AscendingOrder)
  136. if idx==0:
  137. self.children.sort(key=lambda x: x['address'], reverse = rev)
  138. if idx==1:
  139. self.children.sort(key=lambda x: self.get_service_name(x[
  140. "portBegin"]) if x["portEnd"] == None else x["portBegin"],
  141. reverse = rev)
  142. if idx==2:
  143. self.children.sort(key=lambda x: x['proto'], reverse
  144. = rev)
  145. index1 = self.createIndex(0, 0)
  146. index2 = self.createIndex(len(self)-1, len(self.__columnValues)-1)
  147. self.dataChanged.emit(index1, index2)
  148. def get_service_name(self, port):
  149. for service in self.__services:
  150. if service[1] == port:
  151. return service[0]
  152. return str(port)
  153. def get_service_port(self, name):
  154. for service in self.__services:
  155. if service[0] == name:
  156. return service[1]
  157. return None
  158. def get_column_string(self, col, row):
  159. return self.__columnValues[col](row)
  160. def set_vm(self, vm):
  161. self.__vm = vm
  162. self.clearChildren()
  163. conf = vm.get_firewall_conf()
  164. self.allow = conf["allow"]
  165. self.allowDns = conf["allowDns"]
  166. self.allowIcmp = conf["allowIcmp"]
  167. self.allowYumProxy = conf["allowYumProxy"]
  168. self.tempFullAccessExpireTime = 0
  169. for rule in conf["rules"]:
  170. self.appendChild(rule)
  171. if "expire" in rule and rule["address"] == "0.0.0.0":
  172. self.tempFullAccessExpireTime = rule["expire"]
  173. def get_vm_name(self):
  174. return self.__vm.name
  175. def apply_rules(self, allow, dns, icmp, yumproxy, tempFullAccess=False,
  176. tempFullAccessTime=None):
  177. assert self.__vm is not None
  178. if self.allow != allow or self.allowDns != dns or \
  179. self.allowIcmp != icmp or self.allowYumProxy != yumproxy or \
  180. (self.tempFullAccessExpireTime != 0) != tempFullAccess:
  181. self.fw_changed = True
  182. conf = { "allow": allow,
  183. "allowDns": dns,
  184. "allowIcmp": icmp,
  185. "allowYumProxy": yumproxy,
  186. "rules": list()
  187. }
  188. for rule in self.children:
  189. if "expire" in rule and rule["address"] == "0.0.0.0" and \
  190. rule["netmask"] == 0 and rule["proto"] == "any":
  191. # rule already present, update its time
  192. if tempFullAccess:
  193. rule["expire"] = \
  194. int(datetime.datetime.now().strftime("%s")) + \
  195. tempFullAccessTime*60
  196. tempFullAccess = False
  197. conf["rules"].append(rule)
  198. if tempFullAccess and not allow:
  199. conf["rules"].append({"address": "0.0.0.0",
  200. "netmask": 0,
  201. "proto": "any",
  202. "expire": int(
  203. datetime.datetime.now().strftime("%s"))+\
  204. tempFullAccessTime*60
  205. })
  206. if self.fw_changed:
  207. self.__vm.write_firewall_conf(conf)
  208. if self.__vm.is_running():
  209. vm = self.__vm.netvm
  210. while vm is not None:
  211. if vm.is_proxyvm() and vm.is_running():
  212. vm.write_iptables_xenstore_entry()
  213. vm = vm.netvm
  214. def index(self, row, column, parent=QModelIndex()):
  215. if not self.hasIndex(row, column, parent):
  216. return QModelIndex()
  217. return self.createIndex(row, column, self.children[row])
  218. def parent(self, child):
  219. return QModelIndex()
  220. def rowCount(self, parent=QModelIndex()):
  221. return len(self)
  222. def columnCount(self, parent=QModelIndex()):
  223. return len(self.__columnValues)
  224. def hasChildren(self, index=QModelIndex()):
  225. parentItem = index.internalPointer()
  226. if parentItem is not None:
  227. return False
  228. else:
  229. return True
  230. def data(self, index, role=Qt.DisplayRole):
  231. if index.isValid() and role == Qt.DisplayRole:
  232. return self.__columnValues[index.column()](index.row())
  233. return QVariant()
  234. def headerData(self, section, orientation, role=Qt.DisplayRole):
  235. if section < len(self.__columnNames) \
  236. and orientation == Qt.Horizontal and role == Qt.DisplayRole:
  237. return self.__columnNames[section]
  238. return QVariant()
  239. @property
  240. def children(self):
  241. return self.__children
  242. def appendChild(self, child):
  243. row = len(self)
  244. self.beginInsertRows(QModelIndex(), row, row)
  245. self.children.append(child)
  246. self.endInsertRows()
  247. index = self.createIndex(row, 0, child)
  248. self.dataChanged.emit(index, index)
  249. self.fw_changed = True
  250. def removeChild(self, i):
  251. if i >= len(self):
  252. return
  253. self.beginRemoveRows(QModelIndex(), i, i)
  254. del self.children[i]
  255. self.endRemoveRows()
  256. index = self.createIndex(i, 0)
  257. self.dataChanged.emit(index, index)
  258. self.fw_changed = True
  259. def setChild(self, i, child):
  260. self.children[i] = child
  261. index = self.createIndex(i, 0, child)
  262. self.dataChanged.emit(index, index)
  263. self.fw_changed = True
  264. def clearChildren(self):
  265. self.__children = list()
  266. def __len__(self):
  267. return len(self.children)