firewall.py 17 KB

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