net.py 11 KB

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