net.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. #!/usr/bin/python2 -O
  2. # vim: fileencoding=utf-8
  3. #
  4. # The Qubes OS Project, https://www.qubes-os.org/
  5. #
  6. # Copyright (C) 2010-2016 Joanna Rutkowska <joanna@invisiblethingslab.com>
  7. # Copyright (C) 2013-2016 Marek Marczykowski-Górecki
  8. # <marmarek@invisiblethingslab.com>
  9. # Copyright (C) 2014-2016 Wojtek Porczyk <woju@invisiblethingslab.com>
  10. #
  11. # This program is free software; you can redistribute it and/or modify
  12. # it under the terms of the GNU General Public License as published by
  13. # the Free Software Foundation; either version 2 of the License, or
  14. # (at your option) any later version.
  15. #
  16. # This program is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU General Public License along
  22. # with this program; if not, write to the Free Software Foundation, Inc.,
  23. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  24. #
  25. ''' This module contains the NetVMMixin '''
  26. import os
  27. import re
  28. import libvirt # pylint: disable=import-error
  29. import qubes
  30. import qubes.events
  31. import qubes.firewall
  32. import qubes.exc
  33. def _setter_mac(self, prop, value):
  34. ''' Helper for setting the MAC address '''
  35. # pylint: disable=unused-argument
  36. if not isinstance(value, basestring):
  37. raise ValueError('MAC address must be a string')
  38. value = value.lower()
  39. if re.match(r"^([0-9a-f][0-9a-f]:){5}[0-9a-f][0-9a-f]$", value) is None:
  40. raise ValueError('Invalid MAC address value')
  41. return value
  42. class NetVMMixin(qubes.events.Emitter):
  43. ''' Mixin containing network functionality '''
  44. mac = qubes.property('mac', type=str,
  45. default='00:16:3E:5E:6C:00',
  46. setter=_setter_mac,
  47. ls_width=17,
  48. doc='MAC address of the NIC emulated inside VM')
  49. # CORE2: swallowed uses_default_netvm
  50. netvm = qubes.VMProperty('netvm', load_stage=4, allow_none=True,
  51. default=(lambda self: self.app.default_fw_netvm if self.provides_network
  52. else self.app.default_netvm),
  53. ls_width=31,
  54. doc='''VM that provides network connection to this domain. When
  55. `None`, machine is disconnected. When absent, domain uses default
  56. NetVM.''')
  57. provides_network = qubes.property('provides_network', default=False,
  58. type=bool, setter=qubes.property.bool,
  59. doc='''If this domain can act as network provider (formerly known as
  60. NetVM or ProxyVM)''')
  61. firewall_conf = qubes.property('firewall_conf', type=str,
  62. default='firewall.xml')
  63. #
  64. # used in networked appvms or proxyvms (netvm is not None)
  65. #
  66. @qubes.tools.qvm_ls.column(width=15)
  67. @property
  68. def ip(self):
  69. '''IP address of this domain.'''
  70. if not self.is_networked():
  71. return None
  72. if self.netvm is not None:
  73. return self.netvm.get_ip_for_vm(self) # pylint: disable=no-member
  74. else:
  75. return self.get_ip_for_vm(self)
  76. #
  77. # used in netvms (provides_network=True)
  78. # those properties and methods are most likely accessed as vm.netvm.<prop>
  79. #
  80. @staticmethod
  81. def get_ip_for_vm(vm):
  82. '''Get IP address for (appvm) domain connected to this (netvm) domain.
  83. '''
  84. import qubes.vm.dispvm # pylint: disable=redefined-outer-name
  85. if isinstance(vm, qubes.vm.dispvm.DispVM):
  86. return '10.138.{}.{}'.format((vm.dispid >> 8) & 7, vm.dispid & 7)
  87. # VM technically can get address which ends in '.0'. This currently
  88. # does not happen, because qid < 253, but may happen in the future.
  89. return '10.137.{}.{}'.format((vm.qid >> 8) & 7, vm.qid & 7)
  90. @qubes.tools.qvm_ls.column(head='IPBACK', width=15)
  91. @property
  92. def gateway(self):
  93. '''Gateway for other domains that use this domain as netvm.'''
  94. return self.ip if self.provides_network else None
  95. @qubes.tools.qvm_ls.column(width=15)
  96. @property
  97. def netmask(self):
  98. '''Netmask for gateway address.'''
  99. return '255.255.255.255' if self.is_networked() else None
  100. @property
  101. def connected_vms(self):
  102. ''' Return a generator containing all domains connected to the current
  103. NetVM.
  104. '''
  105. for vm in self.app.domains:
  106. if vm.netvm is self:
  107. yield vm
  108. #
  109. # used in both
  110. #
  111. @qubes.tools.qvm_ls.column(width=15)
  112. @property
  113. def dns(self):
  114. '''Secondary DNS server set up for this domain.'''
  115. if self.netvm is not None or self.provides_network:
  116. return (
  117. '10.139.1.1',
  118. '10.139.1.2',
  119. )
  120. else:
  121. return None
  122. def __init__(self, *args, **kwargs):
  123. self._firewall = None
  124. super(NetVMMixin, self).__init__(*args, **kwargs)
  125. @qubes.events.handler('domain-start')
  126. def on_domain_started(self, event, **kwargs):
  127. '''Connect this domain to its downstream domains. Also reload firewall
  128. in its netvm.
  129. This is needed when starting netvm *after* its connected domains.
  130. ''' # pylint: disable=unused-argument
  131. if self.netvm:
  132. self.netvm.reload_firewall_for_vm(self) # pylint: disable=no-member
  133. for vm in self.connected_vms:
  134. if not vm.is_running():
  135. continue
  136. vm.log.info('Attaching network')
  137. # SEE: 1426
  138. vm.cleanup_vifs()
  139. try:
  140. # 1426
  141. vm.run('modprobe -r xen-netfront xennet',
  142. user='root', wait=True)
  143. except: # pylint: disable=bare-except
  144. pass
  145. try:
  146. vm.attach_network()
  147. except qubes.exc.QubesException:
  148. vm.log.warning('Cannot attach network', exc_info=1)
  149. @qubes.events.handler('domain-pre-shutdown')
  150. def shutdown_net(self, event, force=False):
  151. ''' Checks before NetVM shutdown if any connected domains are running.
  152. If `force` is `True` tries to detach network interfaces of connected
  153. vms
  154. ''' # pylint: disable=unused-argument
  155. connected_vms = [vm for vm in self.connected_vms if vm.is_running()]
  156. if connected_vms and not force:
  157. raise qubes.exc.QubesVMError(self,
  158. 'There are other VMs connected to this VM: {}'.format(
  159. ', '.join(vm.name for vm in connected_vms)))
  160. # SEE: 1426
  161. # detach network interfaces of connected VMs before shutting down,
  162. # otherwise libvirt will not notice it and will try to detach them
  163. # again (which would fail, obviously).
  164. # This code can be removed when #1426 got implemented
  165. for vm in connected_vms:
  166. if vm.is_running():
  167. try:
  168. vm.detach_network()
  169. except (qubes.exc.QubesException, libvirt.libvirtError):
  170. # ignore errors
  171. pass
  172. def attach_network(self):
  173. '''Attach network in this machine to it's netvm.'''
  174. if not self.is_running():
  175. raise qubes.exc.QubesVMNotRunningError(self)
  176. assert self.netvm is not None
  177. if not self.netvm.is_running(): # pylint: disable=no-member
  178. # pylint: disable=no-member
  179. self.log.info('Starting NetVM ({0})'.format(self.netvm.name))
  180. self.netvm.start()
  181. self.libvirt_domain.attachDevice(
  182. self.app.env.get_template('libvirt/devices/net.xml').render(
  183. vm=self))
  184. def detach_network(self):
  185. '''Detach machine from it's netvm'''
  186. if not self.is_running():
  187. raise qubes.exc.QubesVMNotRunningError(self)
  188. assert self.netvm is not None
  189. self.libvirt_domain.detachDevice(
  190. self.app.env.get_template('libvirt/devices/net.xml').render(
  191. vm=self))
  192. def is_networked(self):
  193. '''Check whether this VM can reach network (firewall notwithstanding).
  194. :returns: :py:obj:`True` if is machine can reach network, \
  195. :py:obj:`False` otherwise.
  196. :rtype: bool
  197. '''
  198. if self.provides_network:
  199. return True
  200. return self.netvm is not None
  201. def cleanup_vifs(self):
  202. '''Remove stale network device backends.
  203. Libvirt does not remove vif when backend domain is down, so we must do
  204. it manually. This method is one big hack for #1426.
  205. '''
  206. dev_basepath = '/local/domain/%d/device/vif' % self.xid
  207. for dev in self.app.vmm.xs.ls('', dev_basepath):
  208. # check if backend domain is alive
  209. backend_xid = int(self.app.vmm.xs.read('',
  210. '{}/{}/backend-id'.format(dev_basepath, dev)))
  211. if backend_xid in self.app.vmm.libvirt_conn.listDomainsID():
  212. # check if device is still active
  213. if self.app.vmm.xs.read('',
  214. '{}/{}/state'.format(dev_basepath, dev)) == '4':
  215. continue
  216. # remove dead device
  217. self.app.vmm.xs.rm('', '{}/{}'.format(dev_basepath, dev))
  218. def reload_firewall_for_vm(self, vm):
  219. ''' Reload the firewall rules for the vm '''
  220. if not self.is_running():
  221. return
  222. base_dir = '/qubes-firewall/' + vm.ip + '/'
  223. # remove old entries if any (but don't touch base empty entry - it
  224. # would trigger reload right away
  225. self.qdb.rm(base_dir)
  226. # write new rules
  227. for key, value in vm.firewall.qdb_entries().items():
  228. self.qdb.write(base_dir + key, value)
  229. # signal its done
  230. self.qdb.write(base_dir[:-1], '')
  231. @qubes.events.handler('property-del:netvm')
  232. def on_property_del_netvm(self, event, prop, old_netvm=None):
  233. ''' Sets the the NetVM to default NetVM '''
  234. # pylint: disable=unused-argument
  235. # we are changing to default netvm
  236. new_netvm = self.netvm
  237. if new_netvm == old_netvm:
  238. return
  239. self.fire_event('property-set:netvm', 'netvm', new_netvm, old_netvm)
  240. @qubes.events.handler('property-pre-set:netvm')
  241. def on_property_pre_set_netvm(self, event, name, new_netvm, old_netvm=None):
  242. ''' Run sanity checks before setting a new NetVM '''
  243. # pylint: disable=unused-argument
  244. if new_netvm is not None:
  245. if not new_netvm.provides_network:
  246. raise qubes.exc.QubesValueError(
  247. 'The {!s} qube does not provide network'.format(new_netvm))
  248. if new_netvm is self \
  249. or new_netvm in self.app.domains.get_vms_connected_to(self):
  250. raise qubes.exc.QubesValueError(
  251. 'Loops in network are unsupported')
  252. if not self.app.vmm.offline_mode \
  253. and self.is_running() and not new_netvm.is_running():
  254. raise qubes.exc.QubesVMNotStartedError(new_netvm,
  255. 'Cannot dynamically attach to stopped NetVM: {!r}'.format(
  256. new_netvm))
  257. if old_netvm is not None:
  258. if self.is_running():
  259. self.detach_network()
  260. @qubes.events.handler('property-set:netvm')
  261. def on_property_set_netvm(self, event, name, new_netvm, old_netvm=None):
  262. ''' Replaces the current NetVM with a new one and fires
  263. net-domain-connect event
  264. '''
  265. # pylint: disable=unused-argument
  266. if new_netvm is None:
  267. return
  268. if self.is_running():
  269. # refresh IP, DNS etc
  270. self.create_qdb_entries()
  271. self.attach_network()
  272. new_netvm.fire_event('net-domain-connect', self) # SEE: 1811
  273. @qubes.events.handler('net-domain-connect')
  274. def on_net_domain_connect(self, event, vm):
  275. ''' Reloads the firewall config for vm '''
  276. # pylint: disable=unused-argument
  277. self.reload_firewall_for_vm(vm)
  278. @qubes.events.handler('domain-qdb-create')
  279. def on_domain_qdb_create(self, event):
  280. ''' Fills the QubesDB with firewall entries. Not implemented '''
  281. # SEE: 1815 fill firewall QubesDB entries
  282. pass
  283. @qubes.events.handler('firewall-changed', 'domain-spawn')
  284. def on_firewall_changed(self, event, **kwargs):
  285. ''' Reloads the firewall if vm is running and has a NetVM assigned '''
  286. # pylint: disable=unused-argument
  287. if self.is_running() and self.netvm:
  288. self.netvm.reload_firewall_for_vm(self) # pylint: disable=no-member
  289. # CORE2: swallowed get_firewall_conf, write_firewall_conf,
  290. # get_firewall_defaults
  291. @property
  292. def firewall(self):
  293. if self._firewall is None:
  294. self._firewall = qubes.firewall.Firewall(self)
  295. return self._firewall
  296. def has_firewall(self):
  297. ''' Return `True` if there are some vm specific firewall rules set '''
  298. return os.path.exists(os.path.join(self.dir_path, self.firewall_conf))