net.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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 library is free software; you can redistribute it and/or
  10. # modify it under the terms of the GNU Lesser General Public
  11. # License as published by the Free Software Foundation; either
  12. # version 2.1 of the License, or (at your option) any later version.
  13. #
  14. # This library 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 GNU
  17. # Lesser General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU Lesser General Public
  20. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  21. #
  22. ''' This module contains the NetVMMixin '''
  23. import ipaddress
  24. import os
  25. import re
  26. import libvirt # pylint: disable=import-error
  27. import qubes
  28. import qubes.config
  29. import qubes.events
  30. import qubes.firewall
  31. import qubes.exc
  32. def _setter_mac(self, prop, value):
  33. ''' Helper for setting the MAC address '''
  34. # pylint: disable=unused-argument
  35. if not isinstance(value, str):
  36. raise ValueError('MAC address must be a string')
  37. value = value.lower()
  38. if re.match(r"^([0-9a-f][0-9a-f]:){5}[0-9a-f][0-9a-f]$", value) is None:
  39. raise ValueError('Invalid MAC address value')
  40. return value
  41. def _default_ip(self):
  42. if not self.is_networked():
  43. return None
  44. if self.netvm is not None:
  45. return self.netvm.get_ip_for_vm(self) # pylint: disable=no-member
  46. return self.get_ip_for_vm(self)
  47. def _default_ip6(self):
  48. if not self.is_networked():
  49. return None
  50. if not self.features.check_with_netvm('ipv6', False):
  51. return None
  52. if self.netvm is not None:
  53. return self.netvm.get_ip6_for_vm(self) # pylint: disable=no-member
  54. return self.get_ip6_for_vm(self)
  55. def _setter_netvm(self, prop, value):
  56. # pylint: disable=unused-argument
  57. if value is None:
  58. return None
  59. if not value.provides_network:
  60. raise qubes.exc.QubesValueError(
  61. 'The {!s} qube does not provide network'.format(value))
  62. # skip check for netvm loops during qubes.xml loading, to avoid tricky
  63. # loading order
  64. if self.events_enabled:
  65. if value is self \
  66. or value in self.app.domains.get_vms_connected_to(self):
  67. raise qubes.exc.QubesValueError(
  68. 'Loops in network are unsupported')
  69. return value
  70. class NetVMMixin(qubes.events.Emitter):
  71. ''' Mixin containing network functionality '''
  72. mac = qubes.property('mac', type=str,
  73. default='00:16:3E:5E:6C:00',
  74. setter=_setter_mac,
  75. doc='MAC address of the NIC emulated inside VM')
  76. ip = qubes.property('ip', type=ipaddress.IPv4Address,
  77. default=_default_ip,
  78. doc='IP address of this domain.')
  79. ip6 = qubes.property('ip6', type=ipaddress.IPv6Address,
  80. default=_default_ip6,
  81. doc='IPv6 address of this domain.')
  82. # CORE2: swallowed uses_default_netvm
  83. netvm = qubes.VMProperty('netvm', load_stage=4, allow_none=True,
  84. default=(lambda self: self.app.default_netvm),
  85. setter=_setter_netvm,
  86. doc='''VM that provides network connection to this domain. When
  87. `None`, machine is disconnected. When absent, domain uses default
  88. NetVM.''')
  89. provides_network = qubes.property('provides_network', default=False,
  90. type=bool, setter=qubes.property.bool,
  91. doc='''If this domain can act as network provider (formerly known as
  92. NetVM or ProxyVM)''')
  93. @property
  94. def firewall_conf(self):
  95. return 'firewall.xml'
  96. #
  97. # used in networked appvms or proxyvms (netvm is not None)
  98. #
  99. @qubes.stateless_property
  100. def visible_ip(self):
  101. '''IP address of this domain as seen by the domain.'''
  102. return self.features.check_with_template('net.fake-ip', None) or \
  103. self.ip
  104. @qubes.stateless_property
  105. def visible_ip6(self):
  106. '''IPv6 address of this domain as seen by the domain.'''
  107. return self.ip6
  108. @qubes.stateless_property
  109. def visible_gateway(self):
  110. '''Default gateway of this domain as seen by the domain.'''
  111. return self.features.check_with_template('net.fake-gateway', None) or \
  112. (self.netvm.gateway if self.netvm else None)
  113. @qubes.stateless_property
  114. def visible_gateway6(self):
  115. '''Default (IPv6) gateway of this domain as seen by the domain.'''
  116. if self.features.check_with_netvm('ipv6', False):
  117. return self.netvm.gateway6 if self.netvm else None
  118. return None
  119. @qubes.stateless_property
  120. def visible_netmask(self):
  121. '''Netmask as seen by the domain.'''
  122. return self.features.check_with_template('net.fake-netmask', None) or \
  123. (self.netvm.netmask if self.netvm else None)
  124. #
  125. # used in netvms (provides_network=True)
  126. # those properties and methods are most likely accessed as vm.netvm.<prop>
  127. #
  128. @staticmethod
  129. def get_ip_for_vm(vm):
  130. '''Get IP address for (appvm) domain connected to this (netvm) domain.
  131. '''
  132. import qubes.vm.dispvm # pylint: disable=redefined-outer-name
  133. if isinstance(vm, qubes.vm.dispvm.DispVM):
  134. return ipaddress.IPv4Address('10.138.{}.{}'.format(
  135. (vm.dispid >> 8) & 0xff, vm.dispid & 0xff))
  136. # VM technically can get address which ends in '.0'. This currently
  137. # does not happen, because qid < 253, but may happen in the future.
  138. return ipaddress.IPv4Address('10.137.{}.{}'.format(
  139. (vm.qid >> 8) & 0xff, vm.qid & 0xff))
  140. @staticmethod
  141. def get_ip6_for_vm(vm):
  142. '''Get IPv6 address for (appvm) domain connected to this (netvm) domain.
  143. Default address is constructed with Qubes-specific site-local prefix,
  144. and IPv4 suffix (0xa89 is 10.137.).
  145. '''
  146. import qubes.vm.dispvm # pylint: disable=redefined-outer-name
  147. if isinstance(vm, qubes.vm.dispvm.DispVM):
  148. return ipaddress.IPv6Address('{}::a8a:{:x}'.format(
  149. qubes.config.qubes_ipv6_prefix, vm.dispid))
  150. return ipaddress.IPv6Address('{}::a89:{:x}'.format(
  151. qubes.config.qubes_ipv6_prefix, vm.qid))
  152. @qubes.stateless_property
  153. def gateway(self):
  154. '''Gateway for other domains that use this domain as netvm.'''
  155. return self.visible_ip if self.provides_network else None
  156. @qubes.stateless_property
  157. def gateway6(self):
  158. '''Gateway (IPv6) for other domains that use this domain as netvm.'''
  159. if self.features.check_with_netvm('ipv6', False):
  160. return 'fe80::fcff:ffff:feff:ffff' if self.provides_network else \
  161. None
  162. return None
  163. @property
  164. def netmask(self):
  165. '''Netmask for gateway address.'''
  166. return '255.255.255.255' if self.is_networked() else None
  167. @property
  168. def connected_vms(self):
  169. ''' Return a generator containing all domains connected to the current
  170. NetVM.
  171. '''
  172. for vm in self.app.domains:
  173. if getattr(vm, 'netvm', None) is self:
  174. yield vm
  175. #
  176. # used in both
  177. #
  178. @property
  179. def dns(self):
  180. '''Secondary DNS server set up for this domain.'''
  181. if self.netvm is not None or self.provides_network:
  182. return (
  183. '10.139.1.1',
  184. '10.139.1.2',
  185. )
  186. return None
  187. def __init__(self, *args, **kwargs):
  188. self._firewall = None
  189. super(NetVMMixin, self).__init__(*args, **kwargs)
  190. @qubes.events.handler('domain-load')
  191. def on_domain_load_netvm_loop_check(self, event):
  192. # pylint: disable=unused-argument
  193. # make sure there are no netvm loops - which could cause qubesd
  194. # looping infinitely
  195. if self is self.netvm:
  196. self.log.error(
  197. 'vm \'%s\' network-connected to itself, breaking the '
  198. 'connection', self.name)
  199. self.netvm = None
  200. elif self.netvm in self.app.domains.get_vms_connected_to(self):
  201. self.log.error(
  202. 'netvm loop detected on \'%s\', breaking the connection',
  203. self.name)
  204. self.netvm = None
  205. @qubes.events.handler('domain-start')
  206. def on_domain_started(self, event, **kwargs):
  207. '''Connect this domain to its downstream domains. Also reload firewall
  208. in its netvm.
  209. This is needed when starting netvm *after* its connected domains.
  210. ''' # pylint: disable=unused-argument
  211. if self.netvm:
  212. self.netvm.reload_firewall_for_vm(self) # pylint: disable=no-member
  213. for vm in self.connected_vms:
  214. if not vm.is_running():
  215. continue
  216. vm.log.info('Attaching network')
  217. try:
  218. # 1426
  219. vm.run('modprobe -r xen-netfront xennet',
  220. user='root', wait=True)
  221. except: # pylint: disable=bare-except
  222. pass
  223. try:
  224. vm.attach_network()
  225. except qubes.exc.QubesException:
  226. vm.log.warning('Cannot attach network', exc_info=1)
  227. @qubes.events.handler('domain-pre-shutdown')
  228. def shutdown_net(self, event, force=False):
  229. ''' Checks before NetVM shutdown if any connected domains are running.
  230. If `force` is `True` tries to detach network interfaces of connected
  231. vms
  232. ''' # pylint: disable=unused-argument
  233. connected_vms = [vm for vm in self.connected_vms if vm.is_running()]
  234. if connected_vms and not force:
  235. raise qubes.exc.QubesVMError(self,
  236. 'There are other VMs connected to this VM: {}'.format(
  237. ', '.join(vm.name for vm in connected_vms)))
  238. # SEE: 1426
  239. # detach network interfaces of connected VMs before shutting down,
  240. # otherwise libvirt will not notice it and will try to detach them
  241. # again (which would fail, obviously).
  242. # This code can be removed when #1426 got implemented
  243. for vm in connected_vms:
  244. if vm.is_running():
  245. try:
  246. vm.detach_network()
  247. except (qubes.exc.QubesException, libvirt.libvirtError):
  248. # ignore errors
  249. pass
  250. def attach_network(self):
  251. '''Attach network in this machine to it's netvm.'''
  252. if not self.is_running():
  253. raise qubes.exc.QubesVMNotRunningError(self)
  254. assert self.netvm is not None
  255. if not self.netvm.is_running(): # pylint: disable=no-member
  256. # pylint: disable=no-member
  257. self.log.info('Starting NetVM ({0})'.format(self.netvm.name))
  258. self.netvm.start()
  259. self.netvm.set_mapped_ip_info_for_vm(self)
  260. self.libvirt_domain.attachDevice(
  261. self.app.env.get_template('libvirt/devices/net.xml').render(
  262. vm=self))
  263. def detach_network(self):
  264. '''Detach machine from it's netvm'''
  265. if not self.is_running():
  266. raise qubes.exc.QubesVMNotRunningError(self)
  267. assert self.netvm is not None
  268. self.libvirt_domain.detachDevice(
  269. self.app.env.get_template('libvirt/devices/net.xml').render(
  270. vm=self))
  271. def is_networked(self):
  272. '''Check whether this VM can reach network (firewall notwithstanding).
  273. :returns: :py:obj:`True` if is machine can reach network, \
  274. :py:obj:`False` otherwise.
  275. :rtype: bool
  276. '''
  277. if self.provides_network:
  278. return True
  279. return self.netvm is not None
  280. def reload_firewall_for_vm(self, vm):
  281. ''' Reload the firewall rules for the vm '''
  282. if not self.is_running():
  283. return
  284. for addr_family in (4, 6):
  285. ip = vm.ip6 if addr_family == 6 else vm.ip
  286. if ip is None:
  287. continue
  288. base_dir = '/qubes-firewall/{}/'.format(ip)
  289. # remove old entries if any (but don't touch base empty entry - it
  290. # would trigger reload right away
  291. self.untrusted_qdb.rm(base_dir)
  292. # write new rules
  293. for key, value in vm.firewall.qdb_entries(
  294. addr_family=addr_family).items():
  295. self.untrusted_qdb.write(base_dir + key, value)
  296. # signal its done
  297. self.untrusted_qdb.write(base_dir[:-1], '')
  298. def set_mapped_ip_info_for_vm(self, vm):
  299. '''
  300. Set configuration to possibly hide real IP from the VM.
  301. This needs to be done before executing 'script'
  302. (`/etc/xen/scripts/vif-route-qubes`) in network providing VM
  303. '''
  304. # add info about remapped IPs (VM IP hidden from the VM itself)
  305. mapped_ip_base = '/mapped-ip/{}'.format(vm.ip)
  306. if vm.visible_ip:
  307. self.untrusted_qdb.write(mapped_ip_base + '/visible-ip',
  308. str(vm.visible_ip))
  309. else:
  310. self.untrusted_qdb.rm(mapped_ip_base + '/visible-ip')
  311. if vm.visible_gateway:
  312. self.untrusted_qdb.write(mapped_ip_base + '/visible-gateway',
  313. str(vm.visible_gateway))
  314. else:
  315. self.untrusted_qdb.rm(mapped_ip_base + '/visible-gateway')
  316. @qubes.events.handler('property-pre-del:netvm')
  317. def on_property_pre_del_netvm(self, event, name, oldvalue=None):
  318. ''' Sets the the NetVM to default NetVM '''
  319. # pylint: disable=unused-argument
  320. # we are changing to default netvm
  321. newvalue = type(self).netvm.get_default(self)
  322. # check for netvm loop
  323. _setter_netvm(self, type(self).netvm, newvalue)
  324. if newvalue == oldvalue:
  325. return
  326. self.fire_event('property-pre-set:netvm', pre_event=True,
  327. name='netvm', newvalue=newvalue, oldvalue=oldvalue)
  328. @qubes.events.handler('property-del:netvm')
  329. def on_property_del_netvm(self, event, name, oldvalue=None):
  330. ''' Sets the the NetVM to default NetVM '''
  331. # pylint: disable=unused-argument
  332. # we are changing to default netvm
  333. newvalue = self.netvm
  334. if newvalue == oldvalue:
  335. return
  336. self.fire_event('property-set:netvm',
  337. name='netvm', newvalue=newvalue, oldvalue=oldvalue)
  338. @qubes.events.handler('property-pre-set:netvm')
  339. def on_property_pre_set_netvm(self, event, name, newvalue, oldvalue=None):
  340. ''' Run sanity checks before setting a new NetVM '''
  341. # pylint: disable=unused-argument
  342. if newvalue is not None:
  343. if not self.app.vmm.offline_mode \
  344. and self.is_running() and not newvalue.is_running():
  345. raise qubes.exc.QubesVMNotStartedError(newvalue,
  346. 'Cannot dynamically attach to stopped NetVM: {!r}'.format(
  347. newvalue))
  348. if oldvalue is not None:
  349. if self.is_running():
  350. self.detach_network()
  351. @qubes.events.handler('property-set:netvm')
  352. def on_property_set_netvm(self, event, name, newvalue, oldvalue=None):
  353. ''' Replaces the current NetVM with a new one and fires
  354. net-domain-connect event
  355. '''
  356. # pylint: disable=unused-argument
  357. if newvalue is None:
  358. return
  359. if self.is_running():
  360. # refresh IP, DNS etc
  361. self.create_qdb_entries()
  362. self.attach_network()
  363. newvalue.fire_event('net-domain-connect', vm=self)
  364. @qubes.events.handler('net-domain-connect')
  365. def on_net_domain_connect(self, event, vm):
  366. ''' Reloads the firewall config for vm '''
  367. # pylint: disable=unused-argument
  368. self.reload_firewall_for_vm(vm)
  369. @qubes.events.handler('domain-qdb-create')
  370. def on_domain_qdb_create(self, event):
  371. ''' Fills the QubesDB with firewall entries. '''
  372. # pylint: disable=unused-argument
  373. for vm in self.connected_vms:
  374. if vm.is_running():
  375. # keep in sync with on_firewall_changed
  376. self.set_mapped_ip_info_for_vm(vm)
  377. self.reload_firewall_for_vm(vm)
  378. @qubes.events.handler('firewall-changed', 'domain-spawn')
  379. def on_firewall_changed(self, event, **kwargs):
  380. ''' Reloads the firewall if vm is running and has a NetVM assigned '''
  381. # pylint: disable=unused-argument
  382. if self.is_running() and self.netvm:
  383. self.netvm.set_mapped_ip_info_for_vm(self)
  384. self.netvm.reload_firewall_for_vm(self) # pylint: disable=no-member
  385. # CORE2: swallowed get_firewall_conf, write_firewall_conf,
  386. # get_firewall_defaults
  387. @property
  388. def firewall(self):
  389. if self._firewall is None:
  390. self._firewall = qubes.firewall.Firewall(self)
  391. return self._firewall
  392. def has_firewall(self):
  393. ''' Return `True` if there are some vm specific firewall rules set '''
  394. return os.path.exists(os.path.join(self.dir_path, self.firewall_conf))