net.py 21 KB

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