net.py 10 KB

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