net.py 14 KB

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