net.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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. if self.netvm is None:
  253. raise qubes.exc.QubesVMError(self,
  254. 'netvm should not be {}'.format(self.netvm))
  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. if self.netvm is None:
  268. raise qubes.exc.QubesVMError(self,
  269. 'netvm should not be {}'.format(self.netvm))
  270. self.libvirt_domain.detachDevice(
  271. self.app.env.get_template('libvirt/devices/net.xml').render(
  272. vm=self))
  273. def is_networked(self):
  274. '''Check whether this VM can reach network (firewall notwithstanding).
  275. :returns: :py:obj:`True` if is machine can reach network, \
  276. :py:obj:`False` otherwise.
  277. :rtype: bool
  278. '''
  279. if self.provides_network:
  280. return True
  281. return self.netvm is not None
  282. def reload_firewall_for_vm(self, vm):
  283. ''' Reload the firewall rules for the vm '''
  284. if not self.is_running():
  285. return
  286. for addr_family in (4, 6):
  287. ip = vm.ip6 if addr_family == 6 else vm.ip
  288. if ip is None:
  289. continue
  290. base_dir = '/qubes-firewall/{}/'.format(ip)
  291. # remove old entries if any (but don't touch base empty entry - it
  292. # would trigger reload right away
  293. self.untrusted_qdb.rm(base_dir)
  294. # write new rules
  295. for key, value in vm.firewall.qdb_entries(
  296. addr_family=addr_family).items():
  297. self.untrusted_qdb.write(base_dir + key, value)
  298. # signal its done
  299. self.untrusted_qdb.write(base_dir[:-1], '')
  300. def set_mapped_ip_info_for_vm(self, vm):
  301. '''
  302. Set configuration to possibly hide real IP from the VM.
  303. This needs to be done before executing 'script'
  304. (`/etc/xen/scripts/vif-route-qubes`) in network providing VM
  305. '''
  306. # add info about remapped IPs (VM IP hidden from the VM itself)
  307. mapped_ip_base = '/mapped-ip/{}'.format(vm.ip)
  308. if vm.visible_ip:
  309. self.untrusted_qdb.write(mapped_ip_base + '/visible-ip',
  310. str(vm.visible_ip))
  311. else:
  312. self.untrusted_qdb.rm(mapped_ip_base + '/visible-ip')
  313. if vm.visible_gateway:
  314. self.untrusted_qdb.write(mapped_ip_base + '/visible-gateway',
  315. str(vm.visible_gateway))
  316. else:
  317. self.untrusted_qdb.rm(mapped_ip_base + '/visible-gateway')
  318. @qubes.events.handler('property-pre-del:netvm')
  319. def on_property_pre_del_netvm(self, event, name, oldvalue=None):
  320. ''' Sets the the NetVM to default NetVM '''
  321. # pylint: disable=unused-argument
  322. # we are changing to default netvm
  323. newvalue = type(self).netvm.get_default(self)
  324. # check for netvm loop
  325. _setter_netvm(self, type(self).netvm, newvalue)
  326. if newvalue == oldvalue:
  327. return
  328. self.fire_event('property-pre-set:netvm', pre_event=True,
  329. name='netvm', newvalue=newvalue, oldvalue=oldvalue)
  330. @qubes.events.handler('property-del:netvm')
  331. def on_property_del_netvm(self, event, name, oldvalue=None):
  332. ''' Sets the the NetVM to default NetVM '''
  333. # pylint: disable=unused-argument
  334. # we are changing to default netvm
  335. newvalue = self.netvm
  336. if newvalue == oldvalue:
  337. return
  338. self.fire_event('property-set:netvm',
  339. name='netvm', newvalue=newvalue, oldvalue=oldvalue)
  340. @qubes.events.handler('property-pre-set:netvm')
  341. def on_property_pre_set_netvm(self, event, name, newvalue, oldvalue=None):
  342. ''' Run sanity checks before setting a new NetVM '''
  343. # pylint: disable=unused-argument
  344. if newvalue is not None:
  345. if not self.app.vmm.offline_mode \
  346. and self.is_running() and not newvalue.is_running():
  347. raise qubes.exc.QubesVMNotStartedError(newvalue,
  348. 'Cannot dynamically attach to stopped NetVM: {!r}'.format(
  349. newvalue))
  350. # don't check oldvalue, because it's missing if it was default
  351. if self.netvm is not None:
  352. if self.is_running():
  353. self.detach_network()
  354. @qubes.events.handler('property-set:netvm')
  355. def on_property_set_netvm(self, event, name, newvalue, oldvalue=None):
  356. ''' Replaces the current NetVM with a new one and fires
  357. net-domain-connect event
  358. '''
  359. # pylint: disable=unused-argument
  360. if newvalue is None:
  361. return
  362. if self.is_running():
  363. # refresh IP, DNS etc
  364. self.create_qdb_entries()
  365. self.attach_network()
  366. newvalue.fire_event('net-domain-connect', vm=self)
  367. @qubes.events.handler('net-domain-connect')
  368. def on_net_domain_connect(self, event, vm):
  369. ''' Reloads the firewall config for vm '''
  370. # pylint: disable=unused-argument
  371. self.reload_firewall_for_vm(vm)
  372. @qubes.events.handler('domain-qdb-create')
  373. def on_domain_qdb_create(self, event):
  374. ''' Fills the QubesDB with firewall entries. '''
  375. # pylint: disable=unused-argument
  376. for vm in self.connected_vms:
  377. if vm.is_running():
  378. # keep in sync with on_firewall_changed
  379. self.set_mapped_ip_info_for_vm(vm)
  380. self.reload_firewall_for_vm(vm)
  381. @qubes.events.handler('firewall-changed', 'domain-spawn')
  382. def on_firewall_changed(self, event, **kwargs):
  383. ''' Reloads the firewall if vm is running and has a NetVM assigned '''
  384. # pylint: disable=unused-argument
  385. if self.is_running() and self.netvm:
  386. self.netvm.set_mapped_ip_info_for_vm(self)
  387. self.netvm.reload_firewall_for_vm(self) # pylint: disable=no-member
  388. # CORE2: swallowed get_firewall_conf, write_firewall_conf,
  389. # get_firewall_defaults
  390. @property
  391. def firewall(self):
  392. if self._firewall is None:
  393. self._firewall = qubes.firewall.Firewall(self)
  394. return self._firewall
  395. def has_firewall(self):
  396. ''' Return `True` if there are some vm specific firewall rules set '''
  397. return os.path.exists(os.path.join(self.dir_path, self.firewall_conf))