firewall.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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') 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 = list(reversed(vm.firewall.rules))
  190. last_rule = reversed_rules.pop(0)
  191. if last_rule == qubesadmin.firewall.Rule('action=accept') \
  192. or last_rule == qubesadmin.firewall.Rule('action=drop'):
  193. common_action = last_rule.action
  194. else:
  195. FirewallModifiedOutsideError('Last rule must be either '
  196. 'drop all or accept all.')
  197. dns_rule = qubesadmin.firewall.Rule(None,
  198. action='accept', specialtarget='dns')
  199. icmp_rule = qubesadmin.firewall.Rule(None,
  200. action='accept', proto='icmp')
  201. while reversed_rules:
  202. rule = reversed_rules.pop(0)
  203. if rule == dns_rule:
  204. allow_dns = True
  205. continue
  206. if rule == icmp_rule:
  207. allow_icmp = True
  208. continue
  209. if rule.specialtarget is not None or rule.icmptype is not None:
  210. raise FirewallModifiedOutsideError("Rule type unknown!")
  211. if (rule.dsthost is not None or rule.proto is not None) \
  212. and rule.expire is None:
  213. if rule.action == 'accept':
  214. conf['rules'].insert(0, rule)
  215. continue
  216. else:
  217. raise FirewallModifiedOutsideError('No blacklist support.')
  218. if rule.expire is not None and rule.dsthost is None \
  219. and rule.proto is None:
  220. conf['expire'] = int(str(rule.expire))
  221. continue
  222. raise FirewallModifiedOutsideError('it does not add up.')
  223. conf['allow'] = (common_action == 'accept')
  224. if not allow_icmp and not conf['allow']:
  225. raise FirewallModifiedOutsideError('ICMP must be allowed.')
  226. if not allow_dns and not conf['allow']:
  227. raise FirewallModifiedOutsideError('DNS must be allowed')
  228. return conf
  229. @staticmethod
  230. def write_firewall_conf(vm, conf):
  231. rules = []
  232. for rule in conf['rules']:
  233. rules.append(rule)
  234. if not conf['allow']:
  235. rules.append(qubesadmin.firewall.Rule(None,
  236. action='accept', specialtarget='dns'))
  237. if not conf['allow']:
  238. rules.append(qubesadmin.firewall.Rule(None,
  239. action='accept', proto='icmp'))
  240. if conf['allow']:
  241. rules.append(qubesadmin.firewall.Rule(None,
  242. action='accept'))
  243. else:
  244. rules.append(qubesadmin.firewall.Rule(None,
  245. action='drop'))
  246. vm.firewall.rules = rules
  247. def set_vm(self, vm):
  248. self.__vm = vm
  249. self.clear_children()
  250. conf = self.get_firewall_conf(vm)
  251. self.allow = conf["allow"]
  252. self.temp_full_access_expire_time = conf['expire']
  253. for rule in conf["rules"]:
  254. self.append_child(rule)
  255. def get_vm_name(self):
  256. return self.__vm.name
  257. def apply_rules(self, allow, temp_full_access=False,
  258. temp_full_access_time=None):
  259. assert self.__vm is not None
  260. if self.allow != allow or \
  261. (self.temp_full_access_expire_time != 0) != temp_full_access:
  262. self.fw_changed = True
  263. conf = {"allow": allow,
  264. "rules": list()
  265. }
  266. conf['rules'].extend(self.children)
  267. if temp_full_access and not allow:
  268. conf["rules"].append(qubesadmin.firewall.Rule(
  269. None,
  270. action='accept',
  271. expire=int(datetime.datetime.now().strftime("%s")) +
  272. temp_full_access_time * 60))
  273. if self.fw_changed:
  274. self.write_firewall_conf(self.__vm, conf)
  275. def populate_edit_dialog(self, dialog, row):
  276. address = self.get_column_string(0, self.children[row])
  277. dialog.addressComboBox.setItemText(0, address)
  278. dialog.addressComboBox.setCurrentIndex(0)
  279. service = self.get_column_string(1, self.children[row])
  280. if service == "any":
  281. service = ""
  282. dialog.serviceComboBox.setItemText(0, service)
  283. dialog.serviceComboBox.setCurrentIndex(0)
  284. protocol = self.get_column_string(2, self.children[row])
  285. if protocol == "tcp":
  286. dialog.tcp_radio.setChecked(True)
  287. elif protocol == "udp":
  288. dialog.udp_radio.setChecked(True)
  289. else:
  290. dialog.any_radio.setChecked(True)
  291. def run_rule_dialog(self, dialog, row=None):
  292. if dialog.exec_():
  293. address = str(dialog.addressComboBox.currentText())
  294. service = str(dialog.serviceComboBox.currentText())
  295. rule = qubesadmin.firewall.Rule(None, action='accept')
  296. if address is not None and address != "*":
  297. try:
  298. rule.dsthost = address
  299. except ValueError:
  300. QtGui.QMessageBox.warning(None, self.tr("Invalid address"),
  301. self.tr("Address '{0}' is invalid.").format(address))
  302. if dialog.tcp_radio.isChecked():
  303. rule.proto = 'tcp'
  304. elif dialog.udp_radio.isChecked():
  305. rule.proto = 'udp'
  306. if '-' in service:
  307. try:
  308. rule.dstports = service
  309. except ValueError:
  310. QtGui.QMessageBox.warning(
  311. None,
  312. self.tr("Invalid port or service"),
  313. self.tr("Port number or service '{0}' is invalid.")
  314. .format(service))
  315. elif service:
  316. try:
  317. rule.dstports = service
  318. except (TypeError, ValueError):
  319. if self.get_service_port(service) is not None:
  320. rule.dstports = self.get_service_port(service)
  321. else:
  322. QtGui.QMessageBox.warning(None,
  323. self.tr("Invalid port or service"),
  324. self.tr("Port number or service '{0}' is invalid.")
  325. .format(service))
  326. if row is not None:
  327. self.set_child(row, rule)
  328. else:
  329. self.append_child(rule)
  330. def index(self, row, column, parent=QtCore.QModelIndex()):
  331. if not self.hasIndex(row, column, parent):
  332. return QtCore.QModelIndex()
  333. return self.createIndex(row, column, self.children[row])
  334. def parent(self, child): # pylint: disable=unused-argument,no-self-use
  335. return QtCore.QModelIndex()
  336. # pylint: disable=invalid-name,unused-argument
  337. def rowCount(self, parent=QtCore.QModelIndex()):
  338. return len(self)
  339. # pylint: disable=invalid-name,unused-argument
  340. def columnCount(self, parent=QtCore.QModelIndex()):
  341. return len(self.__column_names)
  342. # pylint: disable=invalid-name,no-self-use
  343. def hasChildren(self, index=QtCore.QModelIndex()):
  344. parent_item = index.internalPointer()
  345. return parent_item is None
  346. def data(self, index, role=QtCore.Qt.DisplayRole):
  347. if index.isValid() and role == QtCore.Qt.DisplayRole:
  348. return self.get_column_string(index.column(),
  349. self.children[index.row()])
  350. # pylint: disable=invalid-name
  351. def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
  352. if section < len(self.__column_names) \
  353. and orientation == QtCore.Qt.Horizontal \
  354. and role == QtCore.Qt.DisplayRole:
  355. return self.__column_names[section]
  356. @property
  357. def children(self):
  358. return self.__children
  359. def append_child(self, child):
  360. row = len(self)
  361. self.beginInsertRows(QtCore.QModelIndex(), row, row)
  362. self.children.append(child)
  363. self.endInsertRows()
  364. index = self.createIndex(row, 0, child)
  365. self.dataChanged.emit(index, index)
  366. self.fw_changed = True
  367. def remove_child(self, i):
  368. if i >= len(self):
  369. return
  370. self.beginRemoveRows(QtCore.QModelIndex(), i, i)
  371. del self.children[i]
  372. self.endRemoveRows()
  373. index = self.createIndex(i, 0)
  374. self.dataChanged.emit(index, index)
  375. self.fw_changed = True
  376. def set_child(self, i, child):
  377. self.children[i] = child
  378. index = self.createIndex(i, 0, child)
  379. self.dataChanged.emit(index, index)
  380. self.fw_changed = True
  381. def clear_children(self):
  382. self.__children = list()
  383. def __len__(self):
  384. return len(self.children)