firewall.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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 Lesser General Public License along
  17. # with this program; if not, see <http://www.gnu.org/licenses/>.
  18. #
  19. #
  20. import datetime
  21. import re
  22. from PyQt4 import QtCore, QtGui # pylint: disable=import-error
  23. import qubesadmin.firewall
  24. from . import ui_newfwruledlg # pylint: disable=no-name-in-module
  25. class FirewallModifiedOutsideError(ValueError):
  26. pass
  27. class QIPAddressValidator(QtGui.QValidator):
  28. # pylint: disable=too-few-public-methods
  29. def __init__(self, parent=None):
  30. super(QIPAddressValidator, self).__init__(parent)
  31. def validate(self, input_string, pos):
  32. # pylint: disable=too-many-return-statements,no-self-use
  33. hostname = str(input_string)
  34. if len(hostname) > 255 or not hostname:
  35. return (QtGui.QValidator.Intermediate, input_string, pos)
  36. if hostname == "*":
  37. return (QtGui.QValidator.Acceptable, input_string, pos)
  38. unmask = hostname.split("/", 1)
  39. if len(unmask) == 2:
  40. hostname = unmask[0]
  41. mask = unmask[1]
  42. if mask.isdigit() or mask == "":
  43. if re.match(r"^([0-9]{1,3}\.){3}[0-9]{1,3}$", hostname) is None:
  44. return (QtGui.QValidator.Invalid, input_string, pos)
  45. if mask != "":
  46. mask = int(unmask[1])
  47. if mask < 0 or mask > 32:
  48. return (QtGui.QValidator.Invalid, input_string, pos)
  49. else:
  50. return (QtGui.QValidator.Invalid, input_string, pos)
  51. if hostname[-1:] == ".":
  52. hostname = hostname[:-1]
  53. if hostname[-1:] == "-":
  54. return (QtGui.QValidator.Intermediate, input_string, pos)
  55. allowed = re.compile(r"(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE)
  56. if all(allowed.match(x) for x in hostname.split(".")):
  57. return (QtGui.QValidator.Acceptable, input_string, pos)
  58. return (QtGui.QValidator.Invalid, input_string, pos)
  59. class NewFwRuleDlg(QtGui.QDialog, ui_newfwruledlg.Ui_NewFwRuleDlg):
  60. def __init__(self, parent=None):
  61. super(NewFwRuleDlg, self).__init__(parent)
  62. self.setupUi(self)
  63. self.set_ok_state(False)
  64. self.addressComboBox.setValidator(QIPAddressValidator())
  65. self.addressComboBox.editTextChanged.connect(
  66. self.address_editing_finished)
  67. self.serviceComboBox.setValidator(QtGui.QRegExpValidator(
  68. QtCore.QRegExp("[a-z][a-z0-9-]+|[0-9]+(-[0-9]+)?",
  69. QtCore.Qt.CaseInsensitive), None))
  70. self.serviceComboBox.setEnabled(False)
  71. self.serviceComboBox.setInsertPolicy(QtGui.QComboBox.InsertAtBottom)
  72. self.populate_combos()
  73. self.serviceComboBox.setInsertPolicy(QtGui.QComboBox.InsertAtTop)
  74. def accept(self):
  75. if self.tcp_radio.isChecked() or self.udp_radio.isChecked():
  76. if not self.serviceComboBox.currentText():
  77. msg = QtGui.QMessageBox()
  78. msg.warning(self, self.tr("Firewall rule"),
  79. self.tr("You need to fill service "
  80. "name/port for TCP/UDP rule"))
  81. return
  82. QtGui.QDialog.accept(self)
  83. def populate_combos(self):
  84. example_addresses = [
  85. "", "www.example.com",
  86. "192.168.1.100", "192.168.0.0/16",
  87. "*"
  88. ]
  89. displayed_services = [
  90. '',
  91. 'http', 'https', 'ftp', 'ftps', 'smtp',
  92. 'smtps', 'pop3', 'pop3s', 'imap', 'imaps', 'odmr',
  93. 'nntp', 'nntps', 'ssh', 'telnet', 'telnets', 'ntp',
  94. 'snmp', 'ldap', 'ldaps', 'irc', 'ircs', 'xmpp-client',
  95. 'syslog', 'printer', 'nfs', 'x11',
  96. '1024-1234'
  97. ]
  98. for address in example_addresses:
  99. self.addressComboBox.addItem(address)
  100. for service in displayed_services:
  101. self.serviceComboBox.addItem(service)
  102. def address_editing_finished(self):
  103. self.set_ok_state(True)
  104. def set_ok_state(self, ok_state):
  105. ok_button = self.buttonBox.button(QtGui.QDialogButtonBox.Ok)
  106. if ok_button is not None:
  107. ok_button.setEnabled(ok_state)
  108. def on_tcp_radio_toggled(self, checked):
  109. if checked:
  110. self.serviceComboBox.setEnabled(True)
  111. def on_udp_radio_toggled(self, checked):
  112. if checked:
  113. self.serviceComboBox.setEnabled(True)
  114. def on_any_radio_toggled(self, checked):
  115. if checked:
  116. self.serviceComboBox.setEnabled(False)
  117. class QubesFirewallRulesModel(QtCore.QAbstractItemModel):
  118. def __init__(self, parent=None):
  119. QtCore.QAbstractItemModel.__init__(self, parent)
  120. self.__column_names = {0: "Address", 1: "Service", 2: "Protocol", }
  121. self.__services = list()
  122. pattern = re.compile(
  123. r"(?P<name>[a-z][a-z0-9-]+)\s+(?P<port>[0-9]+)/"
  124. r"(?P<protocol>[a-z]+)",
  125. re.IGNORECASE)
  126. with open('/etc/services', 'r', encoding='utf-8') as file:
  127. for line in file:
  128. match = pattern.match(line)
  129. if match is not None:
  130. service = match.groupdict()
  131. self.__services.append(
  132. (service["name"], int(service["port"]),))
  133. self.fw_changed = False
  134. self.allow = None # is the default policy allow or deny
  135. self.temp_full_access_expire_time = None # temporary full access time
  136. self.__vm = None # VM that the model applies to
  137. self.__children = None # list of rules in the FW
  138. def sort(self, idx, order):
  139. rev = (order == QtCore.Qt.AscendingOrder)
  140. self.children.sort(key=lambda x: self.get_column_string(idx, x),
  141. reverse=rev)
  142. index1 = self.createIndex(0, 0)
  143. index2 = self.createIndex(len(self) - 1, len(self.__column_names) - 1)
  144. self.dataChanged.emit(index1, index2)
  145. def get_service_name(self, port):
  146. for service in self.__services:
  147. if str(service[1]) == str(port):
  148. return service[0]
  149. return str(port)
  150. def get_service_port(self, name):
  151. for service in self.__services:
  152. if service[0] == name:
  153. return service[1]
  154. return None
  155. def get_column_string(self, col, rule):
  156. # pylint: disable=too-many-return-statements
  157. # Address
  158. if col == 0:
  159. if rule.dsthost is None:
  160. return "*"
  161. if rule.dsthost.type == 'dst4' and rule.dsthost.prefixlen == '32':
  162. return str(rule.dsthost)[:-3]
  163. if rule.dsthost.type == 'dst6' and rule.dsthost.prefixlen == '128':
  164. return str(rule.dsthost)[:-4]
  165. return str(rule.dsthost)
  166. # Service
  167. if col == 1:
  168. if rule.dstports is None:
  169. return "any"
  170. if rule.dstports.range[0] != rule.dstports.range[1]:
  171. return str(rule.dstports)
  172. return self.get_service_name(rule.dstports)
  173. # Protocol
  174. if col == 2:
  175. if rule.proto is None:
  176. return "any"
  177. return str(rule.proto)
  178. return "unknown"
  179. @staticmethod
  180. def get_firewall_conf(vm):
  181. conf = {
  182. 'allow': None,
  183. 'expire': 0,
  184. 'rules': [],
  185. }
  186. allow_dns = False
  187. allow_icmp = False
  188. common_action = None
  189. reversed_rules = reversed(vm.firewall.rules)
  190. last_rule = next(reversed_rules, None)
  191. if last_rule is None:
  192. raise FirewallModifiedOutsideError('At least one rule must exist.')
  193. if last_rule == qubesadmin.firewall.Rule('action=accept') \
  194. or last_rule == qubesadmin.firewall.Rule('action=drop'):
  195. common_action = last_rule.action
  196. else:
  197. raise FirewallModifiedOutsideError('Last rule must be either '
  198. 'drop all or accept all.')
  199. dns_rule = qubesadmin.firewall.Rule(None,
  200. action='accept', specialtarget='dns')
  201. icmp_rule = qubesadmin.firewall.Rule(None,
  202. action='accept', proto='icmp')
  203. for rule in reversed_rules:
  204. if rule == dns_rule:
  205. allow_dns = True
  206. continue
  207. if rule == icmp_rule:
  208. allow_icmp = True
  209. continue
  210. if rule.specialtarget is not None or rule.icmptype is not None:
  211. raise FirewallModifiedOutsideError("Rule type unknown!")
  212. if (rule.dsthost is not None or rule.proto is not None) \
  213. and rule.expire is None:
  214. if rule.action == 'accept':
  215. conf['rules'].insert(0, rule)
  216. continue
  217. else:
  218. raise FirewallModifiedOutsideError('No blacklist support.')
  219. if rule.expire is not None and rule.dsthost is None \
  220. and rule.proto is None:
  221. conf['expire'] = int(str(rule.expire))
  222. continue
  223. raise FirewallModifiedOutsideError('it does not add up.')
  224. conf['allow'] = (common_action == 'accept')
  225. if not allow_icmp and not conf['allow']:
  226. raise FirewallModifiedOutsideError('ICMP must be allowed.')
  227. if not allow_dns and not conf['allow']:
  228. raise FirewallModifiedOutsideError('DNS must be allowed')
  229. return conf
  230. @staticmethod
  231. def write_firewall_conf(vm, conf):
  232. rules = []
  233. for rule in conf['rules']:
  234. rules.append(rule)
  235. if not conf['allow']:
  236. rules.append(qubesadmin.firewall.Rule(None,
  237. action='accept', specialtarget='dns'))
  238. if not conf['allow']:
  239. rules.append(qubesadmin.firewall.Rule(None,
  240. action='accept', proto='icmp'))
  241. if conf['allow']:
  242. rules.append(qubesadmin.firewall.Rule(None,
  243. action='accept'))
  244. else:
  245. rules.append(qubesadmin.firewall.Rule(None,
  246. action='drop'))
  247. vm.firewall.rules = rules
  248. def set_vm(self, vm):
  249. self.__vm = vm
  250. self.clear_children()
  251. conf = self.get_firewall_conf(vm)
  252. self.allow = conf["allow"]
  253. self.temp_full_access_expire_time = conf['expire']
  254. for rule in conf["rules"]:
  255. self.append_child(rule)
  256. def get_vm_name(self):
  257. return self.__vm.name
  258. def apply_rules(self, allow, temp_full_access=False,
  259. temp_full_access_time=None):
  260. assert self.__vm is not None
  261. if self.allow != allow or \
  262. (self.temp_full_access_expire_time != 0) != temp_full_access:
  263. self.fw_changed = True
  264. conf = {"allow": allow,
  265. "rules": list()
  266. }
  267. conf['rules'].extend(self.children)
  268. if temp_full_access and not allow:
  269. conf["rules"].append(qubesadmin.firewall.Rule(
  270. None,
  271. action='accept',
  272. expire=int(datetime.datetime.now().strftime("%s")) +
  273. temp_full_access_time * 60))
  274. if self.fw_changed:
  275. self.write_firewall_conf(self.__vm, conf)
  276. def populate_edit_dialog(self, dialog, row):
  277. address = self.get_column_string(0, self.children[row])
  278. dialog.addressComboBox.setItemText(0, address)
  279. dialog.addressComboBox.setCurrentIndex(0)
  280. service = self.get_column_string(1, self.children[row])
  281. if service == "any":
  282. service = ""
  283. dialog.serviceComboBox.setItemText(0, service)
  284. dialog.serviceComboBox.setCurrentIndex(0)
  285. protocol = self.get_column_string(2, self.children[row])
  286. if protocol == "tcp":
  287. dialog.tcp_radio.setChecked(True)
  288. elif protocol == "udp":
  289. dialog.udp_radio.setChecked(True)
  290. else:
  291. dialog.any_radio.setChecked(True)
  292. def run_rule_dialog(self, dialog, row=None):
  293. if dialog.exec_():
  294. address = str(dialog.addressComboBox.currentText())
  295. service = str(dialog.serviceComboBox.currentText())
  296. rule = qubesadmin.firewall.Rule(None, action='accept')
  297. if address is not None and address != "*":
  298. try:
  299. rule.dsthost = address
  300. except ValueError:
  301. QtGui.QMessageBox.warning(None, self.tr("Invalid address"),
  302. self.tr("Address '{0}' is invalid.").format(address))
  303. return
  304. if dialog.tcp_radio.isChecked():
  305. rule.proto = 'tcp'
  306. elif dialog.udp_radio.isChecked():
  307. rule.proto = 'udp'
  308. if '-' in service:
  309. try:
  310. rule.dstports = service
  311. except ValueError:
  312. QtGui.QMessageBox.warning(
  313. None,
  314. self.tr("Invalid port or service"),
  315. self.tr("Port number or service '{0}' is invalid.")
  316. .format(service))
  317. return
  318. elif service:
  319. try:
  320. rule.dstports = service
  321. except (TypeError, ValueError):
  322. if self.get_service_port(service) is not None:
  323. rule.dstports = self.get_service_port(service)
  324. else:
  325. QtGui.QMessageBox.warning(None,
  326. self.tr("Invalid port or service"),
  327. self.tr("Port number or service '{0}' is invalid.")
  328. .format(service))
  329. return
  330. if row is not None:
  331. self.set_child(row, rule)
  332. else:
  333. self.append_child(rule)
  334. def index(self, row, column, parent=QtCore.QModelIndex()):
  335. if not self.hasIndex(row, column, parent):
  336. return QtCore.QModelIndex()
  337. return self.createIndex(row, column, self.children[row])
  338. def parent(self, child): # pylint: disable=unused-argument,no-self-use
  339. return QtCore.QModelIndex()
  340. # pylint: disable=invalid-name,unused-argument
  341. def rowCount(self, parent=QtCore.QModelIndex()):
  342. return len(self)
  343. # pylint: disable=invalid-name,unused-argument
  344. def columnCount(self, parent=QtCore.QModelIndex()):
  345. return len(self.__column_names)
  346. # pylint: disable=invalid-name,no-self-use
  347. def hasChildren(self, index=QtCore.QModelIndex()):
  348. parent_item = index.internalPointer()
  349. return parent_item is None
  350. def data(self, index, role=QtCore.Qt.DisplayRole):
  351. if index.isValid() and role == QtCore.Qt.DisplayRole:
  352. return self.get_column_string(index.column(),
  353. self.children[index.row()])
  354. # pylint: disable=invalid-name
  355. def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
  356. if section < len(self.__column_names) \
  357. and orientation == QtCore.Qt.Horizontal \
  358. and role == QtCore.Qt.DisplayRole:
  359. return self.__column_names[section]
  360. @property
  361. def children(self):
  362. return self.__children
  363. def append_child(self, child):
  364. row = len(self)
  365. self.beginInsertRows(QtCore.QModelIndex(), row, row)
  366. self.children.append(child)
  367. self.endInsertRows()
  368. index = self.createIndex(row, 0, child)
  369. self.dataChanged.emit(index, index)
  370. self.fw_changed = True
  371. def remove_child(self, i):
  372. if i >= len(self):
  373. return
  374. self.beginRemoveRows(QtCore.QModelIndex(), i, i)
  375. del self.children[i]
  376. self.endRemoveRows()
  377. index = self.createIndex(i, 0)
  378. self.dataChanged.emit(index, index)
  379. self.fw_changed = True
  380. def set_child(self, i, child):
  381. self.children[i] = child
  382. index = self.createIndex(i, 0, child)
  383. self.dataChanged.emit(index, index)
  384. self.fw_changed = True
  385. def clear_children(self):
  386. self.__children = list()
  387. def __len__(self):
  388. return len(self.children)