net.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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 re
  27. import libvirt # pylint: disable=import-error
  28. import qubes
  29. import qubes.events
  30. import qubes.exc
  31. def _setter_mac(self, prop, value):
  32. ''' Helper for setting the MAC address '''
  33. # pylint: disable=unused-argument
  34. if not isinstance(value, basestring):
  35. raise ValueError('MAC address must be a string')
  36. value = value.lower()
  37. if re.match(r"^([0-9a-f][0-9a-f]:){5}[0-9a-f][0-9a-f]$", value) is None:
  38. raise ValueError('Invalid MAC address value')
  39. return value
  40. class NetVMMixin(qubes.events.Emitter):
  41. ''' Mixin containing network functionality '''
  42. mac = qubes.property('mac', type=str,
  43. default='00:16:3E:5E:6C:00',
  44. setter=_setter_mac,
  45. ls_width=17,
  46. doc='MAC address of the NIC emulated inside VM')
  47. # CORE2: swallowed uses_default_netvm
  48. netvm = qubes.VMProperty('netvm', load_stage=4, allow_none=True,
  49. default=(lambda self: self.app.default_fw_netvm if self.provides_network
  50. else self.app.default_netvm),
  51. ls_width=31,
  52. doc='''VM that provides network connection to this domain. When
  53. `None`, machine is disconnected. When absent, domain uses default
  54. NetVM.''')
  55. provides_network = qubes.property('provides_network', default=False,
  56. type=bool, setter=qubes.property.bool,
  57. doc='''If this domain can act as network provider (formerly known as
  58. NetVM or ProxyVM)''')
  59. #
  60. # used in networked appvms or proxyvms (netvm is not None)
  61. #
  62. @qubes.tools.qvm_ls.column(width=15)
  63. @property
  64. def ip(self):
  65. '''IP address of this domain.'''
  66. if not self.is_networked():
  67. return None
  68. if self.netvm is not None:
  69. return self.netvm.get_ip_for_vm(self) # pylint: disable=no-member
  70. else:
  71. return self.get_ip_for_vm(self)
  72. #
  73. # used in netvms (provides_network=True)
  74. # those properties and methods are most likely accessed as vm.netvm.<prop>
  75. #
  76. @staticmethod
  77. def get_ip_for_vm(vm):
  78. '''Get IP address for (appvm) domain connected to this (netvm) domain.
  79. '''
  80. import qubes.vm.dispvm # pylint: disable=redefined-outer-name
  81. if isinstance(vm, qubes.vm.dispvm.DispVM):
  82. return '10.138.{}.{}'.format((vm.dispid >> 8) & 7, vm.dispid & 7)
  83. # VM technically can get address which ends in '.0'. This currently
  84. # does not happen, because qid < 253, but may happen in the future.
  85. return '10.137.{}.{}'.format((vm.qid >> 8) & 7, vm.qid & 7)
  86. @qubes.tools.qvm_ls.column(head='IPBACK', width=15)
  87. @property
  88. def gateway(self):
  89. '''Gateway for other domains that use this domain as netvm.'''
  90. return self.ip if self.provides_network else None
  91. @qubes.tools.qvm_ls.column(width=15)
  92. @property
  93. def netmask(self):
  94. '''Netmask for gateway address.'''
  95. return '255.255.255.255' if self.is_networked() else None
  96. @property
  97. def connected_vms(self):
  98. ''' Return a generator containing all domains connected to the current
  99. NetVM.
  100. '''
  101. for vm in self.app.domains:
  102. if vm.netvm is self:
  103. yield vm
  104. #
  105. # used in both
  106. #
  107. @qubes.tools.qvm_ls.column(width=15)
  108. @property
  109. def dns(self):
  110. '''Secondary DNS server set up for this domain.'''
  111. if self.netvm is not None or self.provides_network:
  112. return (
  113. '10.139.1.1',
  114. '10.139.1.2',
  115. )
  116. else:
  117. return None
  118. def __init__(self, *args, **kwargs):
  119. super(NetVMMixin, self).__init__(*args, **kwargs)
  120. @qubes.events.handler('domain-start')
  121. def on_domain_started(self, event, **kwargs):
  122. '''Connect this domain to its downstream domains. Also reload firewall
  123. in its netvm.
  124. This is needed when starting netvm *after* its connected domains.
  125. ''' # pylint: disable=unused-argument
  126. if self.netvm:
  127. self.netvm.reload_firewall_for_vm(self) # pylint: disable=no-member
  128. for vm in self.connected_vms:
  129. if not vm.is_running():
  130. continue
  131. vm.log.info('Attaching network')
  132. # SEE: 1426
  133. vm.cleanup_vifs()
  134. try:
  135. # 1426
  136. vm.run('modprobe -r xen-netfront xennet',
  137. user='root', wait=True)
  138. except: # pylint: disable=bare-except
  139. pass
  140. try:
  141. vm.attach_network(wait=False)
  142. except qubes.exc.QubesException:
  143. vm.log.warning('Cannot attach network', exc_info=1)
  144. @qubes.events.handler('domain-pre-shutdown')
  145. def shutdown_net(self, event, force=False):
  146. ''' Checks before NetVM shutdown if any connected domains are running.
  147. If `force` is `True` tries to detach network interfaces of connected
  148. vms
  149. ''' # pylint: disable=unused-argument
  150. connected_vms = [vm for vm in self.connected_vms if vm.is_running()]
  151. if connected_vms and not force:
  152. raise qubes.exc.QubesVMError(self,
  153. 'There are other VMs connected to this VM: {}'.format(
  154. ', '.join(vm.name for vm in connected_vms)))
  155. # SEE: 1426
  156. # detach network interfaces of connected VMs before shutting down,
  157. # otherwise libvirt will not notice it and will try to detach them
  158. # again (which would fail, obviously).
  159. # This code can be removed when #1426 got implemented
  160. for vm in connected_vms:
  161. if vm.is_running():
  162. try:
  163. vm.detach_network()
  164. except (qubes.exc.QubesException, libvirt.libvirtError):
  165. # ignore errors
  166. pass
  167. def attach_network(self):
  168. '''Attach network in this machine to it's netvm.'''
  169. if not self.is_running():
  170. raise qubes.exc.QubesVMNotRunningError(self)
  171. assert self.netvm is not None
  172. if not self.netvm.is_running(): # pylint: disable=no-member
  173. # pylint: disable=no-member
  174. self.log.info('Starting NetVM ({0})'.format(self.netvm.name))
  175. self.netvm.start()
  176. self.libvirt_domain.attachDevice(
  177. self.app.env.get_template('libvirt/devices/net.xml').render(
  178. vm=self))
  179. def detach_network(self):
  180. '''Detach machine from it's netvm'''
  181. if not self.is_running():
  182. raise qubes.exc.QubesVMNotRunningError(self)
  183. assert self.netvm is not None
  184. self.libvirt_domain.attachDevice(
  185. self.app.env.get_template('libvirt/devices/net.xml').render(
  186. vm=self))
  187. def is_networked(self):
  188. '''Check whether this VM can reach network (firewall notwithstanding).
  189. :returns: :py:obj:`True` if is machine can reach network, \
  190. :py:obj:`False` otherwise.
  191. :rtype: bool
  192. '''
  193. if self.provides_network:
  194. return True
  195. return self.netvm is not None
  196. def cleanup_vifs(self):
  197. '''Remove stale network device backends.
  198. Libvirt does not remove vif when backend domain is down, so we must do
  199. it manually. This method is one big hack for #1426.
  200. '''
  201. dev_basepath = '/local/domain/%d/device/vif' % self.xid
  202. for dev in self.app.vmm.xs.ls('', dev_basepath):
  203. # check if backend domain is alive
  204. backend_xid = int(self.app.vmm.xs.read('',
  205. '{}/{}/backend-id'.format(dev_basepath, dev)))
  206. if backend_xid in self.app.vmm.libvirt_conn.listDomainsID():
  207. # check if device is still active
  208. if self.app.vmm.xs.read('',
  209. '{}/{}/state'.format(dev_basepath, dev)) == '4':
  210. continue
  211. # remove dead device
  212. self.app.vmm.xs.rm('', '{}/{}'.format(dev_basepath, dev))
  213. def reload_firewall_for_vm(self, vm):
  214. ''' Reload the firewall rules for the vm '''
  215. # SEE:1815
  216. pass
  217. @qubes.events.handler('property-del:netvm')
  218. def on_property_del_netvm(self, event, prop, old_netvm=None):
  219. ''' Sets the the NetVM to default NetVM '''
  220. # pylint: disable=unused-argument
  221. # we are changing to default netvm
  222. new_netvm = self.netvm
  223. if new_netvm == old_netvm:
  224. return
  225. self.fire_event('property-set:netvm', 'netvm', new_netvm, old_netvm)
  226. @qubes.events.handler('property-pre-set:netvm')
  227. def on_property_pre_set_netvm(self, event, name, new_netvm, old_netvm=None):
  228. ''' Run sanity checks before setting a new NetVM '''
  229. # pylint: disable=unused-argument
  230. if new_netvm is None:
  231. return
  232. if not new_netvm.provides_network:
  233. raise qubes.exc.QubesValueError(
  234. 'The {!s} qube does not provide network'.format(new_netvm))
  235. if new_netvm is self \
  236. or new_netvm in self.app.domains.get_vms_connected_to(self):
  237. raise qubes.exc.QubesValueError('Loops in network are unsupported')
  238. if not self.app.vmm.offline_mode and self.is_running() \
  239. and not new_netvm.is_running():
  240. raise qubes.exc.QubesVMNotStartedError(new_netvm,
  241. 'Cannot dynamically attach to stopped NetVM: {!r}'.format(
  242. new_netvm))
  243. @qubes.events.handler('property-set:netvm')
  244. def on_property_set_netvm(self, event, name, new_netvm, old_netvm=None):
  245. ''' Replaces the current NetVM with a new one and fires
  246. net-domain-connect event
  247. '''
  248. # pylint: disable=unused-argument
  249. if self.netvm is not None:
  250. if self.is_running():
  251. self.detach_network()
  252. if new_netvm is None:
  253. return
  254. if self.is_running():
  255. # refresh IP, DNS etc
  256. self.create_qdb_entries()
  257. self.attach_network()
  258. new_netvm.fire_event('net-domain-connect', self) # SEE: 1811
  259. @qubes.events.handler('net-domain-connect')
  260. def on_net_domain_connect(self, event, vm):
  261. ''' Reloads the firewall config for vm '''
  262. # pylint: disable=unused-argument
  263. self.reload_firewall_for_vm(vm)
  264. @qubes.events.handler('domain-qdb-create')
  265. def on_domain_qdb_create(self, event):
  266. ''' Fills the QubesDB with firewall entries. Not implemented '''
  267. # SEE: 1815 fill firewall QubesDB entries
  268. pass
  269. @qubes.events.handler('firewall-changed', 'domain-spawn')
  270. def on_firewall_changed(self, event, **kwargs):
  271. ''' Reloads the firewall if vm is running and has a NetVM assigned '''
  272. # pylint: disable=unused-argument
  273. if self.is_running() and self.netvm:
  274. self.netvm.reload_firewall_for_vm(self) # pylint: disable=no-member