net.py 15 KB

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