net.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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. def _setter_provides_network(self, prop, value):
  71. value = qubes.property.bool(self, prop, value)
  72. if not value:
  73. if list(self.connected_vms):
  74. raise qubes.exc.QubesValueError(
  75. 'The qube is still used by other qubes, change theirs '
  76. '\'netvm\' first')
  77. return value
  78. class NetVMMixin(qubes.events.Emitter):
  79. ''' Mixin containing network functionality '''
  80. mac = qubes.property('mac', type=str,
  81. default='00:16:3e:5e:6c:00',
  82. setter=_setter_mac,
  83. doc='MAC address of the NIC emulated inside VM')
  84. ip = qubes.property('ip', type=ipaddress.IPv4Address,
  85. default=_default_ip,
  86. doc='IP address of this domain.')
  87. ip6 = qubes.property('ip6', type=ipaddress.IPv6Address,
  88. default=_default_ip6,
  89. doc='IPv6 address of this domain.')
  90. # CORE2: swallowed uses_default_netvm
  91. netvm = qubes.VMProperty('netvm', load_stage=4, allow_none=True,
  92. default=(lambda self: self.app.default_netvm),
  93. setter=_setter_netvm,
  94. doc='''VM that provides network connection to this domain. When
  95. `None`, machine is disconnected. When absent, domain uses default
  96. NetVM.''')
  97. provides_network = qubes.property('provides_network', default=False,
  98. type=bool, setter=_setter_provides_network,
  99. doc='''If this domain can act as network provider (formerly known as
  100. NetVM or ProxyVM)''')
  101. @property
  102. def firewall_conf(self):
  103. return 'firewall.xml'
  104. #
  105. # used in networked appvms or proxyvms (netvm is not None)
  106. #
  107. @qubes.stateless_property
  108. def visible_ip(self):
  109. '''IP address of this domain as seen by the domain.'''
  110. return self.features.check_with_template('net.fake-ip', None) or \
  111. self.ip
  112. @qubes.stateless_property
  113. def visible_ip6(self):
  114. '''IPv6 address of this domain as seen by the domain.'''
  115. return self.ip6
  116. @qubes.stateless_property
  117. def visible_gateway(self):
  118. '''Default gateway of this domain as seen by the domain.'''
  119. return self.features.check_with_template('net.fake-gateway', None) or \
  120. (self.netvm.gateway if self.netvm else None)
  121. @qubes.stateless_property
  122. def visible_gateway6(self):
  123. '''Default (IPv6) gateway of this domain as seen by the domain.'''
  124. if self.features.check_with_netvm('ipv6', False):
  125. return self.netvm.gateway6 if self.netvm else None
  126. return None
  127. @qubes.stateless_property
  128. def visible_netmask(self):
  129. '''Netmask as seen by the domain.'''
  130. return self.features.check_with_template('net.fake-netmask', None) or \
  131. (self.netvm.netmask if self.netvm else None)
  132. #
  133. # used in netvms (provides_network=True)
  134. # those properties and methods are most likely accessed as vm.netvm.<prop>
  135. #
  136. @staticmethod
  137. def get_ip_for_vm(vm):
  138. '''Get IP address for (appvm) domain connected to this (netvm) domain.
  139. '''
  140. import qubes.vm.dispvm # pylint: disable=redefined-outer-name
  141. if isinstance(vm, qubes.vm.dispvm.DispVM):
  142. return ipaddress.IPv4Address('10.138.{}.{}'.format(
  143. (vm.dispid >> 8) & 0xff, vm.dispid & 0xff))
  144. # VM technically can get address which ends in '.0'. This currently
  145. # does not happen, because qid < 253, but may happen in the future.
  146. return ipaddress.IPv4Address('10.137.{}.{}'.format(
  147. (vm.qid >> 8) & 0xff, vm.qid & 0xff))
  148. @staticmethod
  149. def get_ip6_for_vm(vm):
  150. '''Get IPv6 address for (appvm) domain connected to this (netvm) domain.
  151. Default address is constructed with Qubes-specific site-local prefix,
  152. and IPv4 suffix (0xa89 is 10.137.).
  153. '''
  154. import qubes.vm.dispvm # pylint: disable=redefined-outer-name
  155. if isinstance(vm, qubes.vm.dispvm.DispVM):
  156. return ipaddress.IPv6Address('{}::a8a:{:x}'.format(
  157. qubes.config.qubes_ipv6_prefix, vm.dispid))
  158. return ipaddress.IPv6Address('{}::a89:{:x}'.format(
  159. qubes.config.qubes_ipv6_prefix, vm.qid))
  160. @qubes.stateless_property
  161. def gateway(self):
  162. '''Gateway for other domains that use this domain as netvm.'''
  163. return self.visible_ip if self.provides_network else None
  164. @qubes.stateless_property
  165. def gateway6(self):
  166. '''Gateway (IPv6) for other domains that use this domain as netvm.'''
  167. if self.features.check_with_netvm('ipv6', False):
  168. return self.visible_ip6 if self.provides_network else \
  169. None
  170. return None
  171. @property
  172. def netmask(self):
  173. '''Netmask for gateway address.'''
  174. return '255.255.255.255' if self.is_networked() else None
  175. @property
  176. def connected_vms(self):
  177. ''' Return a generator containing all domains connected to the current
  178. NetVM.
  179. '''
  180. for vm in self.app.domains:
  181. if getattr(vm, 'netvm', None) is self:
  182. yield vm
  183. #
  184. # used in both
  185. #
  186. @property
  187. def dns(self):
  188. '''Secondary DNS server set up for this domain.'''
  189. if self.netvm is not None or self.provides_network:
  190. return (
  191. '10.139.1.1',
  192. '10.139.1.2',
  193. )
  194. return None
  195. def __init__(self, *args, **kwargs):
  196. self._firewall = None
  197. super().__init__(*args, **kwargs)
  198. @qubes.events.handler('domain-load')
  199. def on_domain_load_netvm_loop_check(self, event):
  200. # pylint: disable=unused-argument
  201. # make sure there are no netvm loops - which could cause qubesd
  202. # looping infinitely
  203. if self is self.netvm:
  204. self.log.error(
  205. 'vm \'%s\' network-connected to itself, breaking the '
  206. 'connection', self.name)
  207. self.netvm = None
  208. elif self.netvm in self.app.domains.get_vms_connected_to(self):
  209. self.log.error(
  210. 'netvm loop detected on \'%s\', breaking the connection',
  211. self.name)
  212. self.netvm = None
  213. @qubes.events.handler('domain-shutdown')
  214. def on_domain_shutdown(self, event, **kwargs):
  215. '''Cleanup network interfaces of connected, running VMs.
  216. This will allow re-reconnecting them cleanly later.
  217. '''
  218. # pylint: disable=unused-argument
  219. for vm in self.connected_vms:
  220. if not vm.is_running():
  221. continue
  222. try:
  223. vm.detach_network()
  224. except (qubes.exc.QubesException, libvirt.libvirtError):
  225. # ignore errors
  226. pass
  227. @qubes.events.handler('domain-start')
  228. def on_domain_started(self, event, **kwargs):
  229. '''Connect this domain to its downstream domains. Also reload firewall
  230. in its netvm.
  231. This is needed when starting netvm *after* its connected domains.
  232. ''' # pylint: disable=unused-argument
  233. if self.netvm:
  234. self.netvm.reload_firewall_for_vm(self) # pylint: disable=no-member
  235. for vm in self.connected_vms:
  236. if not vm.is_running():
  237. continue
  238. vm.log.info('Attaching network')
  239. try:
  240. vm.attach_network()
  241. except (qubes.exc.QubesException, libvirt.libvirtError):
  242. vm.log.warning('Cannot attach network', exc_info=1)
  243. @qubes.events.handler('domain-pre-shutdown')
  244. def on_domain_pre_shutdown(self, event, force=False):
  245. ''' Checks before NetVM shutdown if any connected domains are running.
  246. If `force` is `True` tries to detach network interfaces of connected
  247. vms
  248. ''' # pylint: disable=unused-argument
  249. connected_vms = [vm for vm in self.connected_vms if vm.is_running()]
  250. if connected_vms and not force:
  251. raise qubes.exc.QubesVMError(self,
  252. 'There are other VMs connected to this VM: {}'.format(
  253. ', '.join(vm.name for vm in connected_vms)))
  254. def attach_network(self):
  255. '''Attach network in this machine to it's netvm.'''
  256. if not self.is_running():
  257. raise qubes.exc.QubesVMNotRunningError(self)
  258. if self.netvm is None:
  259. raise qubes.exc.QubesVMError(self,
  260. 'netvm should not be {}'.format(self.netvm))
  261. if not self.netvm.is_running(): # pylint: disable=no-member
  262. # pylint: disable=no-member
  263. self.log.info('Starting NetVM ({0})'.format(self.netvm.name))
  264. self.netvm.start()
  265. self.netvm.set_mapped_ip_info_for_vm(self)
  266. self.libvirt_domain.attachDevice(
  267. self.app.env.get_template('libvirt/devices/net.xml').render(
  268. vm=self))
  269. def detach_network(self):
  270. '''Detach machine from it's netvm'''
  271. if not self.is_running():
  272. raise qubes.exc.QubesVMNotRunningError(self)
  273. if self.netvm is None:
  274. raise qubes.exc.QubesVMError(self,
  275. 'netvm should not be {}'.format(self.netvm))
  276. self.libvirt_domain.detachDevice(
  277. self.app.env.get_template('libvirt/devices/net.xml').render(
  278. vm=self))
  279. def is_networked(self):
  280. '''Check whether this VM can reach network (firewall notwithstanding).
  281. :returns: :py:obj:`True` if is machine can reach network, \
  282. :py:obj:`False` otherwise.
  283. :rtype: bool
  284. '''
  285. if self.provides_network:
  286. return True
  287. return self.netvm is not None
  288. def reload_firewall_for_vm(self, vm):
  289. ''' Reload the firewall rules for the vm '''
  290. if not self.is_running():
  291. return
  292. for addr_family in (4, 6):
  293. ip = vm.ip6 if addr_family == 6 else vm.ip
  294. if ip is None:
  295. continue
  296. base_dir = '/qubes-firewall/{}/'.format(ip)
  297. # remove old entries if any (but don't touch base empty entry - it
  298. # would trigger reload right away
  299. self.untrusted_qdb.rm(base_dir)
  300. # write new rules
  301. for key, value in vm.firewall.qdb_entries(
  302. addr_family=addr_family).items():
  303. self.untrusted_qdb.write(base_dir + key, value)
  304. # signal its done
  305. self.untrusted_qdb.write(base_dir[:-1], '')
  306. def set_mapped_ip_info_for_vm(self, vm):
  307. '''
  308. Set configuration to possibly hide real IP from the VM.
  309. This needs to be done before executing 'script'
  310. (`/etc/xen/scripts/vif-route-qubes`) in network providing VM
  311. '''
  312. # add info about remapped IPs (VM IP hidden from the VM itself)
  313. mapped_ip_base = '/mapped-ip/{}'.format(vm.ip)
  314. if vm.visible_ip:
  315. self.untrusted_qdb.write(mapped_ip_base + '/visible-ip',
  316. str(vm.visible_ip))
  317. else:
  318. self.untrusted_qdb.rm(mapped_ip_base + '/visible-ip')
  319. if vm.visible_gateway:
  320. self.untrusted_qdb.write(mapped_ip_base + '/visible-gateway',
  321. str(vm.visible_gateway))
  322. else:
  323. self.untrusted_qdb.rm(mapped_ip_base + '/visible-gateway')
  324. def reload_connected_ips(self):
  325. '''
  326. Update list of IPs possibly connected to this machine.
  327. This is used by qubes-firewall to implement anti-spoofing.
  328. '''
  329. connected_ips = [str(vm.visible_ip) for vm in self.connected_vms
  330. if vm.visible_ip is not None]
  331. connected_ips6 = [str(vm.visible_ip6) for vm in self.connected_vms
  332. if vm.visible_ip6 is not None]
  333. self.untrusted_qdb.write(
  334. '/connected-ips',
  335. ' '.join(connected_ips))
  336. self.untrusted_qdb.write(
  337. '/connected-ips6',
  338. ' '.join(connected_ips6))
  339. @qubes.events.handler('property-pre-reset:netvm')
  340. def on_property_pre_reset_netvm(self, event, name, oldvalue=None):
  341. ''' Sets the the NetVM to default NetVM '''
  342. # pylint: disable=unused-argument
  343. # we are changing to default netvm
  344. newvalue = type(self).netvm.get_default(self)
  345. # check for netvm loop
  346. _setter_netvm(self, type(self).netvm, newvalue)
  347. if newvalue == oldvalue:
  348. return
  349. self.fire_event('property-pre-set:netvm', pre_event=True,
  350. name='netvm', newvalue=newvalue, oldvalue=oldvalue)
  351. @qubes.events.handler('property-reset:netvm')
  352. def on_property_reset_netvm(self, event, name, oldvalue=None):
  353. ''' Sets the the NetVM to default NetVM '''
  354. # pylint: disable=unused-argument
  355. # we are changing to default netvm
  356. newvalue = self.netvm
  357. if newvalue == oldvalue:
  358. return
  359. self.fire_event('property-set:netvm',
  360. name='netvm', newvalue=newvalue, oldvalue=oldvalue)
  361. @qubes.events.handler('property-pre-set:netvm')
  362. def on_property_pre_set_netvm(self, event, name, newvalue, oldvalue=None):
  363. ''' Run sanity checks before setting a new NetVM '''
  364. # pylint: disable=unused-argument
  365. if newvalue is not None:
  366. if not self.app.vmm.offline_mode \
  367. and self.is_running() and not newvalue.is_running():
  368. raise qubes.exc.QubesVMNotStartedError(newvalue,
  369. 'Cannot dynamically attach to stopped NetVM: {!r}'.format(
  370. newvalue))
  371. # don't check oldvalue, because it's missing if it was default
  372. if self.netvm is not None:
  373. if self.is_running():
  374. self.detach_network()
  375. @qubes.events.handler('property-set:netvm')
  376. def on_property_set_netvm(self, event, name, newvalue, oldvalue=None):
  377. ''' Replaces the current NetVM with a new one and fires
  378. net-domain-connect event
  379. '''
  380. # pylint: disable=unused-argument
  381. if oldvalue is not None and oldvalue.is_running():
  382. oldvalue.reload_connected_ips()
  383. if newvalue is None:
  384. return
  385. if newvalue.is_running():
  386. newvalue.reload_connected_ips()
  387. if self.is_running():
  388. # refresh IP, DNS etc
  389. self.create_qdb_entries()
  390. self.attach_network()
  391. newvalue.fire_event('net-domain-connect', vm=self)
  392. @qubes.events.handler('net-domain-connect')
  393. def on_net_domain_connect(self, event, vm):
  394. ''' Reloads the firewall config for vm '''
  395. # pylint: disable=unused-argument
  396. self.reload_firewall_for_vm(vm)
  397. @qubes.events.handler('property-set:ip', 'property-reset:ip')
  398. def on_property_set_ip(self, _event, name, newvalue=None, oldvalue=None):
  399. # pylint: disable=unused-argument
  400. if newvalue == oldvalue:
  401. return
  402. if self.provides_network:
  403. self.fire_event('property-reset:gateway', name='gateway')
  404. self.fire_event('property-reset:visible_ip', name='visible_ip')
  405. for vm in self.connected_vms:
  406. vm.fire_event(
  407. 'property-reset:visible_gateway', name='visible_gateway')
  408. @qubes.events.handler('property-set:ip6', 'property-reset:ipv6')
  409. def on_property_set_ip6(self, _event, name, newvalue=None, oldvalue=None):
  410. # pylint: disable=unused-argument
  411. if newvalue == oldvalue:
  412. return
  413. if self.provides_network:
  414. self.fire_event('property-reset:gateway6', name='gateway6')
  415. self.fire_event('property-reset:visible_ip6', name='visible_ip6')
  416. for vm in self.connected_vms:
  417. vm.fire_event(
  418. 'property-reset:visible_gateway6', name='visible_gateway6')
  419. @qubes.events.handler('feature-set:net.fake-ip')
  420. def on_feature_set_net_fake_ip(self, event, name, newvalue, oldvalue=None):
  421. # pylint: disable=unused-argument
  422. if oldvalue == newvalue:
  423. return
  424. self.fire_event('property-reset:visible_ip', name='visible_ip')
  425. for vm in self.connected_vms:
  426. vm.fire_event(
  427. 'property-reset:visible_gateway', name='visible_gateway')
  428. @qubes.events.handler('feature-set:ipv6')
  429. def on_feature_set_ipv6(self, event, name, newvalue, oldvalue=None):
  430. # pylint: disable=unused-argument
  431. if oldvalue == newvalue:
  432. return
  433. self.fire_event('property-reset:visible_ip6', name='visible_ip6')
  434. for vm in self.connected_vms:
  435. vm.fire_event(
  436. 'property-reset:visible_gateway6', name='visible_gateway6')
  437. @qubes.events.handler('property-set:provides_network')
  438. def on_property_set_provides(
  439. self, _event, name, newvalue, oldvalue=None):
  440. # pylint: disable=unused-argument
  441. if newvalue == oldvalue:
  442. return
  443. self.fire_event('property-reset:gateway', name='gateway')
  444. self.fire_event('property-reset:gateway6', name='gateway6')
  445. @qubes.events.handler('domain-qdb-create')
  446. def on_domain_qdb_create(self, event):
  447. ''' Fills the QubesDB with firewall entries. '''
  448. # pylint: disable=unused-argument
  449. # Keep the following in sync with on_firewall_changed.
  450. self.reload_connected_ips()
  451. for vm in self.connected_vms:
  452. if vm.is_running():
  453. self.set_mapped_ip_info_for_vm(vm)
  454. self.reload_firewall_for_vm(vm)
  455. @qubes.events.handler('firewall-changed', 'domain-spawn')
  456. def on_firewall_changed(self, event, **kwargs):
  457. ''' Reloads the firewall if vm is running and has a NetVM assigned '''
  458. # pylint: disable=unused-argument
  459. if self.is_running() and self.netvm:
  460. self.netvm.reload_connected_ips()
  461. self.netvm.set_mapped_ip_info_for_vm(self)
  462. self.netvm.reload_firewall_for_vm(self) # pylint: disable=no-member
  463. # CORE2: swallowed get_firewall_conf, write_firewall_conf,
  464. # get_firewall_defaults
  465. @property
  466. def firewall(self):
  467. if self._firewall is None:
  468. self._firewall = qubes.firewall.Firewall(self)
  469. return self._firewall
  470. def has_firewall(self):
  471. ''' Return `True` if there are some vm specific firewall rules set '''
  472. return os.path.exists(os.path.join(self.dir_path, self.firewall_conf))