net.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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) & 7, vm.dispid & 7)
  120. # VM technically can get address which ends in '.0'. This currently
  121. # does not happen, because qid < 253, but may happen in the future.
  122. return '10.137.{}.{}'.format((vm.qid >> 8) & 7, vm.qid & 7)
  123. @qubes.stateless_property
  124. def gateway(self):
  125. '''Gateway for other domains that use this domain as netvm.'''
  126. return self.visible_ip if self.provides_network else None
  127. @property
  128. def netmask(self):
  129. '''Netmask for gateway address.'''
  130. return '255.255.255.255' if self.is_networked() else None
  131. @property
  132. def connected_vms(self):
  133. ''' Return a generator containing all domains connected to the current
  134. NetVM.
  135. '''
  136. for vm in self.app.domains:
  137. if vm.netvm is self:
  138. yield vm
  139. #
  140. # used in both
  141. #
  142. @property
  143. def dns(self):
  144. '''Secondary DNS server set up for this domain.'''
  145. if self.netvm is not None or self.provides_network:
  146. return (
  147. '10.139.1.1',
  148. '10.139.1.2',
  149. )
  150. return None
  151. def __init__(self, *args, **kwargs):
  152. self._firewall = None
  153. super(NetVMMixin, self).__init__(*args, **kwargs)
  154. @qubes.events.handler('domain-start')
  155. def on_domain_started(self, event, **kwargs):
  156. '''Connect this domain to its downstream domains. Also reload firewall
  157. in its netvm.
  158. This is needed when starting netvm *after* its connected domains.
  159. ''' # pylint: disable=unused-argument
  160. if self.netvm:
  161. self.netvm.reload_firewall_for_vm(self) # pylint: disable=no-member
  162. for vm in self.connected_vms:
  163. if not vm.is_running():
  164. continue
  165. vm.log.info('Attaching network')
  166. # SEE: 1426
  167. vm.cleanup_vifs()
  168. try:
  169. # 1426
  170. vm.run('modprobe -r xen-netfront xennet',
  171. user='root', wait=True)
  172. except: # pylint: disable=bare-except
  173. pass
  174. try:
  175. vm.attach_network()
  176. except qubes.exc.QubesException:
  177. vm.log.warning('Cannot attach network', exc_info=1)
  178. @qubes.events.handler('domain-pre-shutdown')
  179. def shutdown_net(self, event, force=False):
  180. ''' Checks before NetVM shutdown if any connected domains are running.
  181. If `force` is `True` tries to detach network interfaces of connected
  182. vms
  183. ''' # pylint: disable=unused-argument
  184. connected_vms = [vm for vm in self.connected_vms if vm.is_running()]
  185. if connected_vms and not force:
  186. raise qubes.exc.QubesVMError(self,
  187. 'There are other VMs connected to this VM: {}'.format(
  188. ', '.join(vm.name for vm in connected_vms)))
  189. # SEE: 1426
  190. # detach network interfaces of connected VMs before shutting down,
  191. # otherwise libvirt will not notice it and will try to detach them
  192. # again (which would fail, obviously).
  193. # This code can be removed when #1426 got implemented
  194. for vm in connected_vms:
  195. if vm.is_running():
  196. try:
  197. vm.detach_network()
  198. except (qubes.exc.QubesException, libvirt.libvirtError):
  199. # ignore errors
  200. pass
  201. def attach_network(self):
  202. '''Attach network in this machine to it's netvm.'''
  203. if not self.is_running():
  204. raise qubes.exc.QubesVMNotRunningError(self)
  205. assert self.netvm is not None
  206. if not self.netvm.is_running(): # pylint: disable=no-member
  207. # pylint: disable=no-member
  208. self.log.info('Starting NetVM ({0})'.format(self.netvm.name))
  209. self.netvm.start()
  210. self.netvm.set_mapped_ip_info_for_vm(self)
  211. self.libvirt_domain.attachDevice(
  212. self.app.env.get_template('libvirt/devices/net.xml').render(
  213. vm=self))
  214. def detach_network(self):
  215. '''Detach machine from it's netvm'''
  216. if not self.is_running():
  217. raise qubes.exc.QubesVMNotRunningError(self)
  218. assert self.netvm is not None
  219. self.libvirt_domain.detachDevice(
  220. self.app.env.get_template('libvirt/devices/net.xml').render(
  221. vm=self))
  222. def is_networked(self):
  223. '''Check whether this VM can reach network (firewall notwithstanding).
  224. :returns: :py:obj:`True` if is machine can reach network, \
  225. :py:obj:`False` otherwise.
  226. :rtype: bool
  227. '''
  228. if self.provides_network:
  229. return True
  230. return self.netvm is not None
  231. def cleanup_vifs(self):
  232. '''Remove stale network device backends.
  233. Libvirt does not remove vif when backend domain is down, so we must do
  234. it manually. This method is one big hack for #1426.
  235. '''
  236. dev_basepath = '/local/domain/%d/device/vif' % self.xid
  237. for dev in self.app.vmm.xs.ls('', dev_basepath) or []:
  238. # check if backend domain is alive
  239. backend_xid = int(self.app.vmm.xs.read('',
  240. '{}/{}/backend-id'.format(dev_basepath, dev)))
  241. if backend_xid in self.app.vmm.libvirt_conn.listDomainsID():
  242. # check if device is still active
  243. if self.app.vmm.xs.read('',
  244. '{}/{}/state'.format(dev_basepath, dev)) == '4':
  245. continue
  246. # remove dead device
  247. self.app.vmm.xs.rm('', '{}/{}'.format(dev_basepath, dev))
  248. def reload_firewall_for_vm(self, vm):
  249. ''' Reload the firewall rules for the vm '''
  250. if not self.is_running():
  251. return
  252. base_dir = '/qubes-firewall/' + vm.ip + '/'
  253. # remove old entries if any (but don't touch base empty entry - it
  254. # would trigger reload right away
  255. self.qdb.rm(base_dir)
  256. # write new rules
  257. for key, value in vm.firewall.qdb_entries(addr_family=4).items():
  258. self.qdb.write(base_dir + key, value)
  259. # signal its done
  260. self.qdb.write(base_dir[:-1], '')
  261. def set_mapped_ip_info_for_vm(self, vm):
  262. '''
  263. Set configuration to possibly hide real IP from the VM.
  264. This needs to be done before executing 'script'
  265. (`/etc/xen/scripts/vif-route-qubes`) in network providing VM
  266. '''
  267. # add info about remapped IPs (VM IP hidden from the VM itself)
  268. mapped_ip_base = '/mapped-ip/{}'.format(vm.ip)
  269. if vm.visible_ip:
  270. self.qdb.write(mapped_ip_base + '/visible-ip', vm.visible_ip)
  271. else:
  272. self.qdb.rm(mapped_ip_base + '/visible-ip')
  273. if vm.visible_gateway:
  274. self.qdb.write(mapped_ip_base + '/visible-gateway',
  275. vm.visible_gateway)
  276. else:
  277. self.qdb.rm(mapped_ip_base + '/visible-gateway')
  278. @qubes.events.handler('property-del:netvm')
  279. def on_property_del_netvm(self, event, name, oldvalue=None):
  280. ''' Sets the the NetVM to default NetVM '''
  281. # pylint: disable=unused-argument
  282. # we are changing to default netvm
  283. newvalue = self.netvm
  284. if newvalue == oldvalue:
  285. return
  286. self.fire_event('property-set:netvm',
  287. name='netvm', newvalue=newvalue, oldvalue=oldvalue)
  288. @qubes.events.handler('property-pre-set:netvm')
  289. def on_property_pre_set_netvm(self, event, name, newvalue, oldvalue=None):
  290. ''' Run sanity checks before setting a new NetVM '''
  291. # pylint: disable=unused-argument
  292. if newvalue is not None:
  293. if not self.app.vmm.offline_mode \
  294. and self.is_running() and not newvalue.is_running():
  295. raise qubes.exc.QubesVMNotStartedError(newvalue,
  296. 'Cannot dynamically attach to stopped NetVM: {!r}'.format(
  297. newvalue))
  298. if oldvalue is not None:
  299. if self.is_running():
  300. self.detach_network()
  301. @qubes.events.handler('property-set:netvm')
  302. def on_property_set_netvm(self, event, name, newvalue, oldvalue=None):
  303. ''' Replaces the current NetVM with a new one and fires
  304. net-domain-connect event
  305. '''
  306. # pylint: disable=unused-argument
  307. if newvalue is None:
  308. return
  309. if self.is_running():
  310. # refresh IP, DNS etc
  311. self.create_qdb_entries()
  312. self.attach_network()
  313. newvalue.fire_event('net-domain-connect', vm=self)
  314. @qubes.events.handler('net-domain-connect')
  315. def on_net_domain_connect(self, event, vm):
  316. ''' Reloads the firewall config for vm '''
  317. # pylint: disable=unused-argument
  318. self.reload_firewall_for_vm(vm)
  319. @qubes.events.handler('domain-qdb-create')
  320. def on_domain_qdb_create(self, event):
  321. ''' Fills the QubesDB with firewall entries. Not implemented '''
  322. # SEE: 1815 fill firewall QubesDB entries
  323. pass
  324. @qubes.events.handler('firewall-changed', 'domain-spawn')
  325. def on_firewall_changed(self, event, **kwargs):
  326. ''' Reloads the firewall if vm is running and has a NetVM assigned '''
  327. # pylint: disable=unused-argument
  328. if self.is_running() and self.netvm:
  329. self.netvm.set_mapped_ip_info_for_vm(self)
  330. self.netvm.reload_firewall_for_vm(self) # pylint: disable=no-member
  331. # CORE2: swallowed get_firewall_conf, write_firewall_conf,
  332. # get_firewall_defaults
  333. @property
  334. def firewall(self):
  335. if self._firewall is None:
  336. self._firewall = qubes.firewall.Firewall(self)
  337. return self._firewall
  338. def has_firewall(self):
  339. ''' Return `True` if there are some vm specific firewall rules set '''
  340. return os.path.exists(os.path.join(self.dir_path, self.firewall_conf))