firewall.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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 accept(self):
  75. if self.tcp_radio.isChecked() or self.udp_radio.isChecked():
  76. if len(self.serviceComboBox.currentText()) == 0:
  77. msg = QMessageBox()
  78. msg.warning(self, self.tr("Firewall rule"),
  79. self.tr("You need to fill service name/port for TCP/UDP rule"))
  80. return
  81. QDialog.accept(self)
  82. def populate_combos(self):
  83. example_addresses = [
  84. "", "www.example.com",
  85. "192.168.1.100", "192.168.0.0/16",
  86. "*"
  87. ]
  88. displayed_services = [
  89. '',
  90. 'http', 'https', 'ftp', 'ftps', 'smtp',
  91. 'smtps', 'pop3', 'pop3s', 'imap', 'imaps', 'odmr',
  92. 'nntp', 'nntps', 'ssh', 'telnet', 'telnets', 'ntp',
  93. 'snmp', 'ldap', 'ldaps', 'irc', 'ircs', 'xmpp-client',
  94. 'syslog', 'printer', 'nfs', 'x11',
  95. '1024-1234'
  96. ]
  97. for address in example_addresses:
  98. self.addressComboBox.addItem(address)
  99. for service in displayed_services:
  100. self.serviceComboBox.addItem(service)
  101. def address_editing_finished(self):
  102. self.set_ok_enabled(True)
  103. def set_ok_enabled(self, on):
  104. ok_button = self.buttonBox.button(QDialogButtonBox.Ok)
  105. if ok_button is not None:
  106. ok_button.setEnabled(on)
  107. def on_tcp_radio_toggled(self, checked):
  108. if checked:
  109. self.serviceComboBox.setEnabled(True)
  110. def on_udp_radio_toggled(self, checked):
  111. if checked:
  112. self.serviceComboBox.setEnabled(True)
  113. def on_any_radio_toggled(self, checked):
  114. if checked:
  115. self.serviceComboBox.setEnabled(False)
  116. class QubesFirewallRulesModel(QAbstractItemModel):
  117. def __init__(self, parent=None):
  118. QAbstractItemModel.__init__(self, parent)
  119. self.__columnValues = {
  120. 0: lambda x: "*" if self.children[x]["address"] == "0.0.0.0" and
  121. self.children[x]["netmask"] == 0 else
  122. self.children[x]["address"] + ("" if self.children[x][ "netmask"] == 32 else
  123. " /{0}".format(self.children[x][
  124. "netmask"])),
  125. 1: lambda x: "any" if self.children[x]["portBegin"] == 0 else
  126. "{0}-{1}".format(self.children[x]["portBegin"], self.children[x][
  127. "portEnd"]) if self.children[x]["portEnd"] is not None else \
  128. self.get_service_name(self.children[x]["portBegin"]),
  129. 2: lambda x: self.children[x]["proto"], }
  130. self.__columnNames = {0: "Address", 1: "Service", 2: "Protocol", }
  131. self.__services = list()
  132. pattern = re.compile("(?P<name>[a-z][a-z0-9-]+)\s+(?P<port>[0-9]+)/(?P<protocol>[a-z]+)", re.IGNORECASE)
  133. f = open('/etc/services', 'r')
  134. for line in f:
  135. match = pattern.match(line)
  136. if match is not None:
  137. service = match.groupdict()
  138. self.__services.append( (service["name"], int(service["port"]),) )
  139. f.close()
  140. self.fw_changed = False
  141. def sort(self, idx, order):
  142. from operator import attrgetter
  143. rev = (order == Qt.AscendingOrder)
  144. if idx==0:
  145. self.children.sort(key=lambda x: x['address'], reverse = rev)
  146. if idx==1:
  147. self.children.sort(key=lambda x: self.get_service_name(x[
  148. "portBegin"]) if x["portEnd"] == None else x["portBegin"],
  149. reverse = rev)
  150. if idx==2:
  151. self.children.sort(key=lambda x: x['proto'], reverse
  152. = rev)
  153. index1 = self.createIndex(0, 0)
  154. index2 = self.createIndex(len(self)-1, len(self.__columnValues)-1)
  155. self.dataChanged.emit(index1, index2)
  156. def get_service_name(self, port):
  157. for service in self.__services:
  158. if service[1] == port:
  159. return service[0]
  160. return str(port)
  161. def get_service_port(self, name):
  162. for service in self.__services:
  163. if service[0] == name:
  164. return service[1]
  165. return None
  166. def get_column_string(self, col, row):
  167. return self.__columnValues[col](row)
  168. def set_vm(self, vm):
  169. self.__vm = vm
  170. self.clearChildren()
  171. conf = vm.get_firewall_conf()
  172. self.allow = conf["allow"]
  173. self.allowDns = conf["allowDns"]
  174. self.allowIcmp = conf["allowIcmp"]
  175. self.allowYumProxy = conf["allowYumProxy"]
  176. self.tempFullAccessExpireTime = 0
  177. for rule in conf["rules"]:
  178. self.appendChild(rule)
  179. if "expire" in rule and rule["address"] == "0.0.0.0":
  180. self.tempFullAccessExpireTime = rule["expire"]
  181. def get_vm_name(self):
  182. return self.__vm.name
  183. def apply_rules(self, allow, dns, icmp, yumproxy, tempFullAccess=False,
  184. tempFullAccessTime=None):
  185. assert self.__vm is not None
  186. if self.allow != allow or self.allowDns != dns or \
  187. self.allowIcmp != icmp or self.allowYumProxy != yumproxy or \
  188. (self.tempFullAccessExpireTime != 0) != tempFullAccess:
  189. self.fw_changed = True
  190. conf = { "allow": allow,
  191. "allowDns": dns,
  192. "allowIcmp": icmp,
  193. "allowYumProxy": yumproxy,
  194. "rules": list()
  195. }
  196. for rule in self.children:
  197. if "expire" in rule and rule["address"] == "0.0.0.0" and \
  198. rule["netmask"] == 0 and rule["proto"] == "any":
  199. # rule already present, update its time
  200. if tempFullAccess:
  201. rule["expire"] = \
  202. int(datetime.datetime.now().strftime("%s")) + \
  203. tempFullAccessTime*60
  204. tempFullAccess = False
  205. conf["rules"].append(rule)
  206. if tempFullAccess and not allow:
  207. conf["rules"].append({"address": "0.0.0.0",
  208. "netmask": 0,
  209. "proto": "any",
  210. "expire": int(
  211. datetime.datetime.now().strftime("%s"))+\
  212. tempFullAccessTime*60
  213. })
  214. if self.fw_changed:
  215. self.__vm.write_firewall_conf(conf)
  216. if self.__vm.is_running():
  217. vm = self.__vm.netvm
  218. while vm is not None:
  219. if vm.is_proxyvm() and vm.is_running():
  220. vm.write_iptables_qubesdb_entry()
  221. vm = vm.netvm
  222. def index(self, row, column, parent=QModelIndex()):
  223. if not self.hasIndex(row, column, parent):
  224. return QModelIndex()
  225. return self.createIndex(row, column, self.children[row])
  226. def parent(self, child):
  227. return QModelIndex()
  228. def rowCount(self, parent=QModelIndex()):
  229. return len(self)
  230. def columnCount(self, parent=QModelIndex()):
  231. return len(self.__columnValues)
  232. def hasChildren(self, index=QModelIndex()):
  233. parentItem = index.internalPointer()
  234. if parentItem is not None:
  235. return False
  236. else:
  237. return True
  238. def data(self, index, role=Qt.DisplayRole):
  239. if index.isValid() and role == Qt.DisplayRole:
  240. return self.__columnValues[index.column()](index.row())
  241. return QVariant()
  242. def headerData(self, section, orientation, role=Qt.DisplayRole):
  243. if section < len(self.__columnNames) \
  244. and orientation == Qt.Horizontal and role == Qt.DisplayRole:
  245. return self.__columnNames[section]
  246. return QVariant()
  247. @property
  248. def children(self):
  249. return self.__children
  250. def appendChild(self, child):
  251. row = len(self)
  252. self.beginInsertRows(QModelIndex(), row, row)
  253. self.children.append(child)
  254. self.endInsertRows()
  255. index = self.createIndex(row, 0, child)
  256. self.dataChanged.emit(index, index)
  257. self.fw_changed = True
  258. def removeChild(self, i):
  259. if i >= len(self):
  260. return
  261. self.beginRemoveRows(QModelIndex(), i, i)
  262. del self.children[i]
  263. self.endRemoveRows()
  264. index = self.createIndex(i, 0)
  265. self.dataChanged.emit(index, index)
  266. self.fw_changed = True
  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. self.fw_changed = True
  272. def clearChildren(self):
  273. self.__children = list()
  274. def __len__(self):
  275. return len(self.children)