services.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. # -*- encoding: utf-8 -*-
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2017 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. #
  8. # This library is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU Lesser General Public
  10. # License as published by the Free Software Foundation; either
  11. # version 2.1 of the License, or (at your option) any later version.
  12. #
  13. # This library is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. # Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public
  19. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  20. """Extension responsible for qvm-service framework"""
  21. import os
  22. import qubes.ext
  23. import qubes.config
  24. class ServicesExtension(qubes.ext.Extension):
  25. """This extension export features with 'service.' prefix to QubesDB in
  26. /qubes-service/ tree.
  27. """
  28. @staticmethod
  29. def add_dom0_service(vm, service):
  30. try:
  31. os.makedirs(
  32. qubes.config.system_path['dom0_services_dir'], exist_ok=True)
  33. service = '{}/{}'.format(
  34. qubes.config.system_path['dom0_services_dir'], service)
  35. if not os.path.exists(service):
  36. os.mknod(service)
  37. except PermissionError:
  38. vm.log.warning("Cannot write to {}".format(
  39. qubes.config.system_path['dom0_services_dir']))
  40. @staticmethod
  41. def remove_dom0_service(vm, service):
  42. try:
  43. service = '{}/{}'.format(
  44. qubes.config.system_path['dom0_services_dir'], service)
  45. if os.path.exists(service):
  46. os.remove(service)
  47. except PermissionError:
  48. vm.log.warning("Cannot write to {}".format(
  49. qubes.config.system_path['dom0_services_dir']))
  50. # pylint: disable=no-self-use
  51. @qubes.ext.handler('domain-qdb-create')
  52. def on_domain_qdb_create(self, vm, event):
  53. """Actually export features"""
  54. # pylint: disable=unused-argument
  55. for feature, value in vm.features.items():
  56. if not feature.startswith('service.'):
  57. continue
  58. service = feature[len('service.'):]
  59. # forcefully convert to '0' or '1'
  60. vm.untrusted_qdb.write('/qubes-service/{}'.format(service),
  61. str(int(bool(value))))
  62. # always set meminfo-writer according to maxmem
  63. vm.untrusted_qdb.write('/qubes-service/meminfo-writer',
  64. '1' if vm.maxmem > 0 else '0')
  65. @qubes.ext.handler('domain-feature-set:*')
  66. def on_domain_feature_set(self, vm, event, feature, value, oldvalue=None):
  67. """Update /qubes-service/ QubesDB tree in runtime"""
  68. # pylint: disable=unused-argument
  69. # TODO: remove this compatibility hack in Qubes 4.1
  70. if feature == 'service.meminfo-writer':
  71. # if someone try to enable meminfo-writer ...
  72. if value:
  73. # ... reset maxmem to default
  74. vm.maxmem = qubes.property.DEFAULT
  75. else:
  76. # otherwise, set to 0
  77. vm.maxmem = 0
  78. # in any case, remove the entry, as it does not indicate memory
  79. # balancing state anymore
  80. del vm.features['service.meminfo-writer']
  81. if not vm.is_running():
  82. return
  83. if not feature.startswith('service.'):
  84. return
  85. service = feature[len('service.'):]
  86. # forcefully convert to '0' or '1'
  87. vm.untrusted_qdb.write('/qubes-service/{}'.format(service),
  88. str(int(bool(value))))
  89. if vm.name == "dom0":
  90. if str(int(bool(value))) == "1":
  91. self.add_dom0_service(vm, service)
  92. else:
  93. self.remove_dom0_service(vm, service)
  94. @qubes.ext.handler('domain-feature-delete:*')
  95. def on_domain_feature_delete(self, vm, event, feature):
  96. """Update /qubes-service/ QubesDB tree in runtime"""
  97. # pylint: disable=unused-argument
  98. if not vm.is_running():
  99. return
  100. if not feature.startswith('service.'):
  101. return
  102. service = feature[len('service.'):]
  103. # this one is excluded from user control
  104. if service == 'meminfo-writer':
  105. return
  106. vm.untrusted_qdb.rm('/qubes-service/{}'.format(service))
  107. if vm.name == "dom0":
  108. self.remove_dom0_service(vm, service)
  109. @qubes.ext.handler('domain-load')
  110. def on_domain_load(self, vm, event):
  111. """Migrate meminfo-writer service into maxmem"""
  112. # pylint: disable=no-self-use,unused-argument
  113. if 'service.meminfo-writer' in vm.features:
  114. # if was set to false, force maxmem=0
  115. # otherwise, simply ignore as the default is fine
  116. if not vm.features['service.meminfo-writer']:
  117. vm.maxmem = 0
  118. del vm.features['service.meminfo-writer']
  119. if vm.name == "dom0":
  120. for feature, value in vm.features.items():
  121. if not feature.startswith('service.'):
  122. continue
  123. service = feature[len('service.'):]
  124. if str(int(bool(value))) == "1":
  125. self.add_dom0_service(vm, service)
  126. else:
  127. self.remove_dom0_service(vm, service)
  128. @qubes.ext.handler('features-request')
  129. def supported_services(self, vm, event, untrusted_features):
  130. """Handle advertisement of supported services"""
  131. # pylint: disable=no-self-use,unused-argument
  132. if getattr(vm, 'template', None):
  133. vm.log.warning(
  134. 'Ignoring qubes.FeaturesRequest from template-based VM')
  135. return
  136. new_supported_services = set()
  137. for requested_service in untrusted_features:
  138. if not requested_service.startswith('supported-service.'):
  139. continue
  140. if untrusted_features[requested_service] == '1':
  141. # only allow to advertise service as supported, lack of entry
  142. # means service is not supported
  143. new_supported_services.add(requested_service)
  144. del untrusted_features
  145. # if no service is supported, ignore the whole thing - do not clear
  146. # all services in case of empty request (manual or such)
  147. if not new_supported_services:
  148. return
  149. old_supported_services = set(
  150. feat for feat in vm.features
  151. if feat.startswith('supported-service.') and vm.features[feat])
  152. for feature in new_supported_services.difference(
  153. old_supported_services):
  154. vm.features[feature] = True
  155. if feature == 'supported-service.apparmor' and \
  156. not 'apparmor' in vm.features:
  157. vm.features['apparmor'] = True
  158. for feature in old_supported_services.difference(
  159. new_supported_services):
  160. del vm.features[feature]
  161. if feature == 'supported-service.apparmor' and \
  162. 'apparmor' in vm.features and vm.features['apparmor'] == '1':
  163. del vm.features['apparmor']