net.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2010-2016 Joanna Rutkowska <joanna@invisiblethingslab.com>
  5. # Copyright (C) 2013-2016 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. # Copyright (C) 2014-2016 Wojtek Porczyk <woju@invisiblethingslab.com>
  8. #
  9. # This program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation; either version 2 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License along
  20. # with this program; if not, write to the Free Software Foundation, Inc.,
  21. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  22. #
  23. ''' This module contains the NetVMMixin '''
  24. import os
  25. import re
  26. import libvirt # pylint: disable=import-error
  27. import qubes
  28. import qubes.events
  29. import qubes.firewall
  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, str):
  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. def _default_ip(self):
  41. if not self.is_networked():
  42. return None
  43. if self.netvm is not None:
  44. return self.netvm.get_ip_for_vm(self) # pylint: disable=no-member
  45. return self.get_ip_for_vm(self)
  46. def _setter_ip(self, prop, value):
  47. # pylint: disable=unused-argument
  48. if not isinstance(value, str):
  49. raise ValueError('IP address must be a string')
  50. value = value.lower()
  51. if re.match(r"^([0-9]{1,3}.){3}[0-9]{1,3}$", value) is None:
  52. raise ValueError('Invalid IP address value')
  53. return value
  54. def _setter_netvm(self, prop, value):
  55. # pylint: disable=unused-argument
  56. if value is None:
  57. return
  58. if not value.provides_network:
  59. raise qubes.exc.QubesValueError(
  60. 'The {!s} qube does not provide network'.format(value))
  61. if value is self \
  62. or value in self.app.domains.get_vms_connected_to(self):
  63. raise qubes.exc.QubesValueError(
  64. 'Loops in network are unsupported')
  65. return value
  66. class NetVMMixin(qubes.events.Emitter):
  67. ''' Mixin containing network functionality '''
  68. mac = qubes.property('mac', type=str,
  69. default='00:16:3E:5E:6C:00',
  70. setter=_setter_mac,
  71. doc='MAC address of the NIC emulated inside VM')
  72. ip = qubes.property('ip', type=str,
  73. default=_default_ip,
  74. setter=_setter_ip,
  75. doc='IP address of this domain.')
  76. # CORE2: swallowed uses_default_netvm
  77. netvm = qubes.VMProperty('netvm', load_stage=4, allow_none=True,
  78. default=(lambda self: self.app.default_fw_netvm if self.provides_network
  79. else self.app.default_netvm),
  80. setter=_setter_netvm,
  81. doc='''VM that provides network connection to this domain. When
  82. `None`, machine is disconnected. When absent, domain uses default
  83. NetVM.''')
  84. provides_network = qubes.property('provides_network', default=False,
  85. type=bool, setter=qubes.property.bool,
  86. doc='''If this domain can act as network provider (formerly known as
  87. NetVM or ProxyVM)''')
  88. @property
  89. def firewall_conf(self):
  90. return 'firewall.xml'
  91. #
  92. # used in networked appvms or proxyvms (netvm is not None)
  93. #
  94. @qubes.stateless_property
  95. def visible_ip(self):
  96. '''IP address of this domain as seen by the domain.'''
  97. return self.features.check_with_template('net/fake-ip', None) or \
  98. self.ip
  99. @qubes.stateless_property
  100. def visible_gateway(self):
  101. '''Default gateway of this domain as seen by the domain.'''
  102. return self.features.check_with_template('net/fake-gateway', None) or \
  103. self.netvm.gateway
  104. @qubes.stateless_property
  105. def visible_netmask(self):
  106. '''Netmask as seen by the domain.'''
  107. return self.features.check_with_template('net/fake-netmask', None) or \
  108. self.netvm.netmask
  109. #
  110. # used in netvms (provides_network=True)
  111. # those properties and methods are most likely accessed as vm.netvm.<prop>
  112. #
  113. @staticmethod
  114. def get_ip_for_vm(vm):
  115. '''Get IP address for (appvm) domain connected to this (netvm) domain.
  116. '''
  117. import qubes.vm.dispvm # pylint: disable=redefined-outer-name
  118. if isinstance(vm, qubes.vm.dispvm.DispVM):
  119. return '10.138.{}.{}'.format((vm.dispid >> 8) & 0xff,
  120. vm.dispid & 0xff)
  121. # VM technically can get address which ends in '.0'. This currently
  122. # does not happen, because qid < 253, but may happen in the future.
  123. return '10.137.{}.{}'.format((vm.qid >> 8) & 0xff, vm.qid & 0xff)
  124. @qubes.stateless_property
  125. def gateway(self):
  126. '''Gateway for other domains that use this domain as netvm.'''
  127. return self.visible_ip if self.provides_network else None
  128. @property
  129. def netmask(self):
  130. '''Netmask for gateway address.'''
  131. return '255.255.255.255' if self.is_networked() else None
  132. @property
  133. def connected_vms(self):
  134. ''' Return a generator containing all domains connected to the current
  135. NetVM.
  136. '''
  137. for vm in self.app.domains:
  138. if vm.netvm is self:
  139. yield vm
  140. #
  141. # used in both
  142. #
  143. @property
  144. def dns(self):
  145. '''Secondary DNS server set up for this domain.'''
  146. if self.netvm is not None or self.provides_network:
  147. return (
  148. '10.139.1.1',
  149. '10.139.1.2',
  150. )
  151. return None
  152. def __init__(self, *args, **kwargs):
  153. self._firewall = None
  154. super(NetVMMixin, self).__init__(*args, **kwargs)
  155. @qubes.events.handler('domain-start')
  156. def on_domain_started(self, event, **kwargs):
  157. '''Connect this domain to its downstream domains. Also reload firewall
  158. in its netvm.
  159. This is needed when starting netvm *after* its connected domains.
  160. ''' # pylint: disable=unused-argument
  161. if self.netvm:
  162. self.netvm.reload_firewall_for_vm(self) # pylint: disable=no-member
  163. for vm in self.connected_vms:
  164. if not vm.is_running():
  165. continue
  166. vm.log.info('Attaching network')
  167. # SEE: 1426
  168. vm.cleanup_vifs()
  169. try:
  170. # 1426
  171. vm.run('modprobe -r xen-netfront xennet',
  172. user='root', wait=True)
  173. except: # pylint: disable=bare-except
  174. pass
  175. try:
  176. vm.attach_network()
  177. except qubes.exc.QubesException:
  178. vm.log.warning('Cannot attach network', exc_info=1)
  179. @qubes.events.handler('domain-pre-shutdown')
  180. def shutdown_net(self, event, force=False):
  181. ''' Checks before NetVM shutdown if any connected domains are running.
  182. If `force` is `True` tries to detach network interfaces of connected
  183. vms
  184. ''' # pylint: disable=unused-argument
  185. connected_vms = [vm for vm in self.connected_vms if vm.is_running()]
  186. if connected_vms and not force:
  187. raise qubes.exc.QubesVMError(self,
  188. 'There are other VMs connected to this VM: {}'.format(
  189. ', '.join(vm.name for vm in connected_vms)))
  190. # SEE: 1426
  191. # detach network interfaces of connected VMs before shutting down,
  192. # otherwise libvirt will not notice it and will try to detach them
  193. # again (which would fail, obviously).
  194. # This code can be removed when #1426 got implemented
  195. for vm in connected_vms:
  196. if vm.is_running():
  197. try:
  198. vm.detach_network()
  199. except (qubes.exc.QubesException, libvirt.libvirtError):
  200. # ignore errors
  201. pass
  202. def attach_network(self):
  203. '''Attach network in this machine to it's netvm.'''
  204. if not self.is_running():
  205. raise qubes.exc.QubesVMNotRunningError(self)
  206. assert self.netvm is not None
  207. if not self.netvm.is_running(): # pylint: disable=no-member
  208. # pylint: disable=no-member
  209. self.log.info('Starting NetVM ({0})'.format(self.netvm.name))
  210. self.netvm.start()
  211. self.netvm.set_mapped_ip_info_for_vm(self)
  212. self.libvirt_domain.attachDevice(
  213. self.app.env.get_template('libvirt/devices/net.xml').render(
  214. vm=self))
  215. def detach_network(self):
  216. '''Detach machine from it's netvm'''
  217. if not self.is_running():
  218. raise qubes.exc.QubesVMNotRunningError(self)
  219. assert self.netvm is not None
  220. self.libvirt_domain.detachDevice(
  221. self.app.env.get_template('libvirt/devices/net.xml').render(
  222. vm=self))
  223. def is_networked(self):
  224. '''Check whether this VM can reach network (firewall notwithstanding).
  225. :returns: :py:obj:`True` if is machine can reach network, \
  226. :py:obj:`False` otherwise.
  227. :rtype: bool
  228. '''
  229. if self.provides_network:
  230. return True
  231. return self.netvm is not None
  232. def cleanup_vifs(self):
  233. '''Remove stale network device backends.
  234. Libvirt does not remove vif when backend domain is down, so we must do
  235. it manually. This method is one big hack for #1426.
  236. '''
  237. dev_basepath = '/local/domain/%d/device/vif' % self.xid
  238. for dev in self.app.vmm.xs.ls('', dev_basepath) or []:
  239. # check if backend domain is alive
  240. backend_xid = int(self.app.vmm.xs.read('',
  241. '{}/{}/backend-id'.format(dev_basepath, dev)))
  242. if backend_xid in self.app.vmm.libvirt_conn.listDomainsID():
  243. # check if device is still active
  244. if self.app.vmm.xs.read('',
  245. '{}/{}/state'.format(dev_basepath, dev)) == '4':
  246. continue
  247. # remove dead device
  248. self.app.vmm.xs.rm('', '{}/{}'.format(dev_basepath, dev))
  249. def reload_firewall_for_vm(self, vm):
  250. ''' Reload the firewall rules for the vm '''
  251. if not self.is_running():
  252. return
  253. base_dir = '/qubes-firewall/' + vm.ip + '/'
  254. # remove old entries if any (but don't touch base empty entry - it
  255. # would trigger reload right away
  256. self.qdb.rm(base_dir)
  257. # write new rules
  258. for key, value in vm.firewall.qdb_entries(addr_family=4).items():
  259. self.qdb.write(base_dir + key, value)
  260. # signal its done
  261. self.qdb.write(base_dir[:-1], '')
  262. def set_mapped_ip_info_for_vm(self, vm):
  263. '''
  264. Set configuration to possibly hide real IP from the VM.
  265. This needs to be done before executing 'script'
  266. (`/etc/xen/scripts/vif-route-qubes`) in network providing VM
  267. '''
  268. # add info about remapped IPs (VM IP hidden from the VM itself)
  269. mapped_ip_base = '/mapped-ip/{}'.format(vm.ip)
  270. if vm.visible_ip:
  271. self.qdb.write(mapped_ip_base + '/visible-ip', vm.visible_ip)
  272. else:
  273. self.qdb.rm(mapped_ip_base + '/visible-ip')
  274. if vm.visible_gateway:
  275. self.qdb.write(mapped_ip_base + '/visible-gateway',
  276. vm.visible_gateway)
  277. else:
  278. self.qdb.rm(mapped_ip_base + '/visible-gateway')
  279. @qubes.events.handler('property-del:netvm')
  280. def on_property_del_netvm(self, event, name, oldvalue=None):
  281. ''' Sets the the NetVM to default NetVM '''
  282. # pylint: disable=unused-argument
  283. # we are changing to default netvm
  284. newvalue = self.netvm
  285. if newvalue == oldvalue:
  286. return
  287. self.fire_event('property-set:netvm',
  288. name='netvm', newvalue=newvalue, oldvalue=oldvalue)
  289. @qubes.events.handler('property-pre-set:netvm')
  290. def on_property_pre_set_netvm(self, event, name, newvalue, oldvalue=None):
  291. ''' Run sanity checks before setting a new NetVM '''
  292. # pylint: disable=unused-argument
  293. if newvalue is not None:
  294. if not self.app.vmm.offline_mode \
  295. and self.is_running() and not newvalue.is_running():
  296. raise qubes.exc.QubesVMNotStartedError(newvalue,
  297. 'Cannot dynamically attach to stopped NetVM: {!r}'.format(
  298. newvalue))
  299. if oldvalue is not None:
  300. if self.is_running():
  301. self.detach_network()
  302. @qubes.events.handler('property-set:netvm')
  303. def on_property_set_netvm(self, event, name, newvalue, oldvalue=None):
  304. ''' Replaces the current NetVM with a new one and fires
  305. net-domain-connect event
  306. '''
  307. # pylint: disable=unused-argument
  308. if newvalue is None:
  309. return
  310. if self.is_running():
  311. # refresh IP, DNS etc
  312. self.create_qdb_entries()
  313. self.attach_network()
  314. newvalue.fire_event('net-domain-connect', vm=self)
  315. @qubes.events.handler('net-domain-connect')
  316. def on_net_domain_connect(self, event, vm):
  317. ''' Reloads the firewall config for vm '''
  318. # pylint: disable=unused-argument
  319. self.reload_firewall_for_vm(vm)
  320. @qubes.events.handler('domain-qdb-create')
  321. def on_domain_qdb_create(self, event):
  322. ''' Fills the QubesDB with firewall entries. Not implemented '''
  323. # SEE: 1815 fill firewall QubesDB entries
  324. pass
  325. @qubes.events.handler('firewall-changed', 'domain-spawn')
  326. def on_firewall_changed(self, event, **kwargs):
  327. ''' Reloads the firewall if vm is running and has a NetVM assigned '''
  328. # pylint: disable=unused-argument
  329. if self.is_running() and self.netvm:
  330. self.netvm.set_mapped_ip_info_for_vm(self)
  331. self.netvm.reload_firewall_for_vm(self) # pylint: disable=no-member
  332. # CORE2: swallowed get_firewall_conf, write_firewall_conf,
  333. # get_firewall_defaults
  334. @property
  335. def firewall(self):
  336. if self._firewall is None:
  337. self._firewall = qubes.firewall.Firewall(self)
  338. return self._firewall
  339. def has_firewall(self):
  340. ''' Return `True` if there are some vm specific firewall rules set '''
  341. return os.path.exists(os.path.join(self.dir_path, self.firewall_conf))