net.py 12 KB

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