firewall.py 16 KB

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