net.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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 self.visible_ip6 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. vm.detach_network()
  219. except (qubes.exc.QubesException, libvirt.libvirtError):
  220. vm.log.warning('Cannot detach old network', exc_info=1)
  221. try:
  222. vm.attach_network()
  223. except (qubes.exc.QubesException, libvirt.libvirtError):
  224. vm.log.warning('Cannot attach network', exc_info=1)
  225. @qubes.events.handler('domain-pre-shutdown')
  226. def shutdown_net(self, event, force=False):
  227. ''' Checks before NetVM shutdown if any connected domains are running.
  228. If `force` is `True` tries to detach network interfaces of connected
  229. vms
  230. ''' # pylint: disable=unused-argument
  231. connected_vms = [vm for vm in self.connected_vms if vm.is_running()]
  232. if connected_vms and not force:
  233. raise qubes.exc.QubesVMError(self,
  234. 'There are other VMs connected to this VM: {}'.format(
  235. ', '.join(vm.name for vm in connected_vms)))
  236. # SEE: 1426
  237. # detach network interfaces of connected VMs before shutting down,
  238. # otherwise libvirt will not notice it and will try to detach them
  239. # again (which would fail, obviously).
  240. # This code can be removed when #1426 got implemented
  241. for vm in connected_vms:
  242. if vm.is_running():
  243. try:
  244. vm.detach_network()
  245. except (qubes.exc.QubesException, libvirt.libvirtError):
  246. # ignore errors
  247. pass
  248. def attach_network(self):
  249. '''Attach network in this machine to it's netvm.'''
  250. if not self.is_running():
  251. raise qubes.exc.QubesVMNotRunningError(self)
  252. assert self.netvm is not None
  253. if not self.netvm.is_running(): # pylint: disable=no-member
  254. # pylint: disable=no-member
  255. self.log.info('Starting NetVM ({0})'.format(self.netvm.name))
  256. self.netvm.start()
  257. self.netvm.set_mapped_ip_info_for_vm(self)
  258. self.libvirt_domain.attachDevice(
  259. self.app.env.get_template('libvirt/devices/net.xml').render(
  260. vm=self))
  261. def detach_network(self):
  262. '''Detach machine from it's netvm'''
  263. if not self.is_running():
  264. raise qubes.exc.QubesVMNotRunningError(self)
  265. assert self.netvm is not None
  266. self.libvirt_domain.detachDevice(
  267. self.app.env.get_template('libvirt/devices/net.xml').render(
  268. vm=self))
  269. def is_networked(self):
  270. '''Check whether this VM can reach network (firewall notwithstanding).
  271. :returns: :py:obj:`True` if is machine can reach network, \
  272. :py:obj:`False` otherwise.
  273. :rtype: bool
  274. '''
  275. if self.provides_network:
  276. return True
  277. return self.netvm is not None
  278. def reload_firewall_for_vm(self, vm):
  279. ''' Reload the firewall rules for the vm '''
  280. if not self.is_running():
  281. return
  282. for addr_family in (4, 6):
  283. ip = vm.ip6 if addr_family == 6 else vm.ip
  284. if ip is None:
  285. continue
  286. base_dir = '/qubes-firewall/{}/'.format(ip)
  287. # remove old entries if any (but don't touch base empty entry - it
  288. # would trigger reload right away
  289. self.untrusted_qdb.rm(base_dir)
  290. # write new rules
  291. for key, value in vm.firewall.qdb_entries(
  292. addr_family=addr_family).items():
  293. self.untrusted_qdb.write(base_dir + key, value)
  294. # signal its done
  295. self.untrusted_qdb.write(base_dir[:-1], '')
  296. def set_mapped_ip_info_for_vm(self, vm):
  297. '''
  298. Set configuration to possibly hide real IP from the VM.
  299. This needs to be done before executing 'script'
  300. (`/etc/xen/scripts/vif-route-qubes`) in network providing VM
  301. '''
  302. # add info about remapped IPs (VM IP hidden from the VM itself)
  303. mapped_ip_base = '/mapped-ip/{}'.format(vm.ip)
  304. if vm.visible_ip:
  305. self.untrusted_qdb.write(mapped_ip_base + '/visible-ip',
  306. str(vm.visible_ip))
  307. else:
  308. self.untrusted_qdb.rm(mapped_ip_base + '/visible-ip')
  309. if vm.visible_gateway:
  310. self.untrusted_qdb.write(mapped_ip_base + '/visible-gateway',
  311. str(vm.visible_gateway))
  312. else:
  313. self.untrusted_qdb.rm(mapped_ip_base + '/visible-gateway')
  314. @qubes.events.handler('property-pre-del:netvm')
  315. def on_property_pre_del_netvm(self, event, name, oldvalue=None):
  316. ''' Sets the the NetVM to default NetVM '''
  317. # pylint: disable=unused-argument
  318. # we are changing to default netvm
  319. newvalue = type(self).netvm.get_default(self)
  320. # check for netvm loop
  321. _setter_netvm(self, type(self).netvm, newvalue)
  322. if newvalue == oldvalue:
  323. return
  324. self.fire_event('property-pre-set:netvm', pre_event=True,
  325. name='netvm', newvalue=newvalue, oldvalue=oldvalue)
  326. @qubes.events.handler('property-del:netvm')
  327. def on_property_del_netvm(self, event, name, oldvalue=None):
  328. ''' Sets the the NetVM to default NetVM '''
  329. # pylint: disable=unused-argument
  330. # we are changing to default netvm
  331. newvalue = self.netvm
  332. if newvalue == oldvalue:
  333. return
  334. self.fire_event('property-set:netvm',
  335. name='netvm', newvalue=newvalue, oldvalue=oldvalue)
  336. @qubes.events.handler('property-pre-set:netvm')
  337. def on_property_pre_set_netvm(self, event, name, newvalue, oldvalue=None):
  338. ''' Run sanity checks before setting a new NetVM '''
  339. # pylint: disable=unused-argument
  340. if newvalue is not None:
  341. if not self.app.vmm.offline_mode \
  342. and self.is_running() and not newvalue.is_running():
  343. raise qubes.exc.QubesVMNotStartedError(newvalue,
  344. 'Cannot dynamically attach to stopped NetVM: {!r}'.format(
  345. newvalue))
  346. # don't check oldvalue, because it's missing if it was default
  347. if self.netvm is not None:
  348. if self.is_running():
  349. self.detach_network()
  350. @qubes.events.handler('property-set:netvm')
  351. def on_property_set_netvm(self, event, name, newvalue, oldvalue=None):
  352. ''' Replaces the current NetVM with a new one and fires
  353. net-domain-connect event
  354. '''
  355. # pylint: disable=unused-argument
  356. if newvalue is None:
  357. return
  358. if self.is_running():
  359. # refresh IP, DNS etc
  360. self.create_qdb_entries()
  361. self.attach_network()
  362. newvalue.fire_event('net-domain-connect', vm=self)
  363. @qubes.events.handler('net-domain-connect')
  364. def on_net_domain_connect(self, event, vm):
  365. ''' Reloads the firewall config for vm '''
  366. # pylint: disable=unused-argument
  367. self.reload_firewall_for_vm(vm)
  368. @qubes.events.handler('domain-qdb-create')
  369. def on_domain_qdb_create(self, event):
  370. ''' Fills the QubesDB with firewall entries. '''
  371. # pylint: disable=unused-argument
  372. for vm in self.connected_vms:
  373. if vm.is_running():
  374. # keep in sync with on_firewall_changed
  375. self.set_mapped_ip_info_for_vm(vm)
  376. self.reload_firewall_for_vm(vm)
  377. @qubes.events.handler('firewall-changed', 'domain-spawn')
  378. def on_firewall_changed(self, event, **kwargs):
  379. ''' Reloads the firewall if vm is running and has a NetVM assigned '''
  380. # pylint: disable=unused-argument
  381. if self.is_running() and self.netvm:
  382. self.netvm.set_mapped_ip_info_for_vm(self)
  383. self.netvm.reload_firewall_for_vm(self) # pylint: disable=no-member
  384. # CORE2: swallowed get_firewall_conf, write_firewall_conf,
  385. # get_firewall_defaults
  386. @property
  387. def firewall(self):
  388. if self._firewall is None:
  389. self._firewall = qubes.firewall.Firewall(self)
  390. return self._firewall
  391. def has_firewall(self):
  392. ''' Return `True` if there are some vm specific firewall rules set '''
  393. return os.path.exists(os.path.join(self.dir_path, self.firewall_conf))