net.py 10 KB

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