__init__.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. # coding=utf-8
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2013-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  5. # Copyright (C) 2013-2017 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation; either version 2 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program 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
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License along
  19. # with this program; if not, write to the Free Software Foundation, Inc.,
  20. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. ''' Qrexec policy parser and evaluator '''
  22. import enum
  23. import itertools
  24. import json
  25. import os
  26. import os.path
  27. import socket
  28. import subprocess
  29. # don't import 'qubes.config' please, it takes 0.3s
  30. QREXEC_CLIENT = '/usr/lib/qubes/qrexec-client'
  31. QUBES_RPC_MULTIPLEXER_PATH = '/usr/lib/qubes/qubes-rpc-multiplexer'
  32. POLICY_DIR = '/etc/qubes-rpc/policy'
  33. QUBESD_INTERNAL_SOCK = '/var/run/qubesd.internal.sock'
  34. QUBESD_SOCK = '/var/run/qubesd.sock'
  35. class AccessDenied(Exception):
  36. ''' Raised when qrexec policy denied access '''
  37. pass
  38. class PolicySyntaxError(AccessDenied):
  39. ''' Syntax error in qrexec policy, abort parsing '''
  40. def __init__(self, filename, lineno, msg):
  41. super(PolicySyntaxError, self).__init__(
  42. '{}:{}: {}'.format(filename, lineno, msg))
  43. class PolicyNotFound(AccessDenied):
  44. ''' Policy was not found for this service '''
  45. def __init__(self, service_name):
  46. super(PolicyNotFound, self).__init__(
  47. 'Policy not found for service {}'.format(service_name))
  48. class Action(enum.Enum):
  49. ''' Action as defined by policy '''
  50. allow = 1
  51. deny = 2
  52. ask = 3
  53. def verify_target_value(system_info, value):
  54. ''' Check if given value names valid target
  55. This function check if given value is not only syntactically correct,
  56. but also if names valid service call target (existing domain,
  57. or valid $dispvm like keyword)
  58. :param system_info: information about the system
  59. :param value: value to be checked
  60. '''
  61. if value == '$dispvm':
  62. return True
  63. elif value == '$adminvm':
  64. return True
  65. elif value.startswith('$dispvm:'):
  66. dispvm_base = value.split(':', 1)[1]
  67. if dispvm_base not in system_info['domains']:
  68. return False
  69. dispvm_base_info = system_info['domains'][dispvm_base]
  70. return bool(dispvm_base_info['template_for_dispvms'])
  71. else:
  72. return value in system_info['domains']
  73. def verify_special_value(value, for_target=True, specific_target=False):
  74. '''
  75. Verify if given special VM-specifier ('$...') is valid
  76. :param value: value to verify
  77. :param for_target: should classify target-only values as valid (
  78. '$default', '$dispvm')
  79. :param specific_target: allow only values naming specific target
  80. (for use with target=, default= etc)
  81. :return: True or False
  82. '''
  83. # pylint: disable=too-many-return-statements
  84. # values used only for matching VMs, not naming specific one (for actual
  85. # call target)
  86. if not specific_target:
  87. if value.startswith('$tag:') and len(value) > len('$tag:'):
  88. return True
  89. if value.startswith('$type:') and len(value) > len('$type:'):
  90. return True
  91. if for_target and value.startswith('$dispvm:$tag:') and \
  92. len(value) > len('$dispvm:$tag:'):
  93. return True
  94. if value == '$anyvm':
  95. return True
  96. if for_target and value == '$default':
  97. return True
  98. # those can be used to name one specific call VM
  99. if value == '$adminvm':
  100. return True
  101. # allow only specific dispvm, not based on any $xxx keyword - don't name
  102. # $tag here specifically, to work also with any future keywords
  103. if for_target and value.startswith('$dispvm:') and \
  104. not value.startswith('$dispvm:$'):
  105. return True
  106. if for_target and value == '$dispvm':
  107. return True
  108. return False
  109. class PolicyRule(object):
  110. ''' A single line of policy file '''
  111. def __init__(self, line, filename=None, lineno=None):
  112. '''
  113. Load a single line of qrexec policy and check its syntax.
  114. Do not verify existence of named objects.
  115. :raise PolicySyntaxError: when syntax error is found
  116. :param line: a single line of actual qrexec policy (not a comment,
  117. empty line or $include)
  118. :param filename: name of the file from which this line is loaded
  119. :param lineno: line number from which this line is loaded
  120. '''
  121. self.lineno = lineno
  122. self.filename = filename
  123. try:
  124. self.source, self.target, self.full_action = line.split(maxsplit=2)
  125. except ValueError:
  126. raise PolicySyntaxError(filename, lineno, 'wrong number of fields')
  127. (action, *params) = self.full_action.replace(',', ' ').split()
  128. try:
  129. self.action = Action[action]
  130. except KeyError:
  131. raise PolicySyntaxError(filename, lineno,
  132. 'invalid action: {}'.format(action))
  133. #: alternative target, used instead of the one specified by the caller
  134. self.override_target = None
  135. #: alternative user, used instead of vm.default_user
  136. self.override_user = None
  137. #: default target when asking the user for confirmation
  138. self.default_target = None
  139. for param in params:
  140. try:
  141. param_name, value = param.split('=')
  142. except ValueError:
  143. raise PolicySyntaxError(filename, lineno,
  144. 'invalid action parameter syntax: {}'.format(param))
  145. if param_name == 'target':
  146. if self.action == Action.deny:
  147. raise PolicySyntaxError(filename, lineno,
  148. 'target= option not allowed for deny action')
  149. self.override_target = value
  150. elif param_name == 'user':
  151. if self.action == Action.deny:
  152. raise PolicySyntaxError(filename, lineno,
  153. 'user= option not allowed for deny action')
  154. self.override_user = value
  155. elif param_name == 'default_target':
  156. if self.action != Action.ask:
  157. raise PolicySyntaxError(filename, lineno,
  158. 'default_target= option allowed only for ask action')
  159. self.default_target = value
  160. else:
  161. raise PolicySyntaxError(filename, lineno,
  162. 'invalid option {} for {} action'.format(param, action))
  163. # verify special values
  164. if self.source.startswith('$'):
  165. if not verify_special_value(self.source, False, False):
  166. raise PolicySyntaxError(filename, lineno,
  167. 'invalid source specification: {}'.format(self.source))
  168. if self.target.startswith('$'):
  169. if not verify_special_value(self.target, True, False):
  170. raise PolicySyntaxError(filename, lineno,
  171. 'invalid target specification: {}'.format(self.target))
  172. if self.target == '$default' \
  173. and self.action == Action.allow \
  174. and self.override_target is None:
  175. raise PolicySyntaxError(filename, lineno,
  176. 'allow action for $default rule must specify target= option')
  177. if self.override_target is not None:
  178. if self.override_target.startswith('$') and \
  179. not verify_special_value(self.override_target, True, True):
  180. raise PolicySyntaxError(filename, lineno,
  181. 'target= option needs to name specific target')
  182. if self.default_target is not None:
  183. if self.default_target.startswith('$') and \
  184. not verify_special_value(self.default_target, True, True):
  185. raise PolicySyntaxError(filename, lineno,
  186. 'target= option needs to name specific target')
  187. @staticmethod
  188. def is_match_single(system_info, policy_value, value):
  189. '''
  190. Evaluate if a single value (VM name or '$default') matches policy
  191. specification
  192. :param system_info: information about the system
  193. :param policy_value: value from qrexec policy (either self.source or
  194. self.target)
  195. :param value: value to be compared (source or target)
  196. :return: True or False
  197. '''
  198. # pylint: disable=too-many-return-statements
  199. # not specified target matches only with $default and $anyvm policy
  200. # entry
  201. if value == '$default' or value == '':
  202. return policy_value in ('$default', '$anyvm')
  203. # if specific target used, check if it's valid
  204. # this function (is_match_single) is also used for checking call source
  205. # values, but this isn't a problem, because it will always be a
  206. # domain name (not $dispvm or such) - this is guaranteed by a nature
  207. # of qrexec call
  208. if not verify_target_value(system_info, value):
  209. return False
  210. # handle $adminvm keyword
  211. if policy_value == 'dom0':
  212. # TODO: log a warning in Qubes 4.1
  213. policy_value = '$adminvm'
  214. if value == 'dom0':
  215. value = '$adminvm'
  216. # allow any _valid_, non-dom0 target
  217. if policy_value == '$anyvm':
  218. return value != '$adminvm'
  219. # exact match, including $dispvm* and $adminvm
  220. if value == policy_value:
  221. return True
  222. # DispVM request, using tags to match
  223. if policy_value.startswith('$dispvm:$tag:') \
  224. and value.startswith('$dispvm:'):
  225. tag = policy_value.split(':', 2)[2]
  226. dispvm_base = value.split(':', 1)[1]
  227. # already checked for existence by verify_target_value call
  228. dispvm_base_info = system_info['domains'][dispvm_base]
  229. return tag in dispvm_base_info['tags']
  230. # if $dispvm* not matched above, reject it; default DispVM (bare
  231. # $dispvm) was resolved by the caller
  232. if value.startswith('$dispvm:'):
  233. return False
  234. # require $adminvm to be matched explicitly (not through $tag or $type)
  235. # - if not matched already, reject it
  236. if value == '$adminvm':
  237. return False
  238. # at this point, value name a specific target
  239. domain_info = system_info['domains'][value]
  240. if policy_value.startswith('$tag:'):
  241. tag = policy_value.split(':', 1)[1]
  242. return tag in domain_info['tags']
  243. if policy_value.startswith('$type:'):
  244. type_ = policy_value.split(':', 1)[1]
  245. return type_ == domain_info['type']
  246. return False
  247. def is_match(self, system_info, source, target):
  248. '''
  249. Check if given (source, target) matches this policy line.
  250. :param system_info: information about the system - available VMs,
  251. their types, labels, tags etc. as returned by
  252. :py:func:`app_to_system_info`
  253. :param source: name of the source VM
  254. :param target: name of the target VM, or None if not specified
  255. :return: True or False
  256. '''
  257. if not self.is_match_single(system_info, self.source, source):
  258. return False
  259. # $dispvm in policy matches _only_ $dispvm (but not $dispvm:some-vm,
  260. # even if that would be the default one)
  261. if self.target == '$dispvm' and target == '$dispvm':
  262. return True
  263. if target == '$dispvm':
  264. # resolve default DispVM, to check all kinds of $dispvm:*
  265. default_dispvm = system_info['domains'][source]['default_dispvm']
  266. if default_dispvm is None:
  267. # if this VM have no default DispVM, match only with $anyvm
  268. return self.target == '$anyvm'
  269. target = '$dispvm:' + default_dispvm
  270. if not self.is_match_single(system_info, self.target, target):
  271. return False
  272. return True
  273. def expand_target(self, system_info):
  274. '''
  275. Return domains matching target of this policy line
  276. :param system_info: information about the system
  277. :return: matching domains
  278. '''
  279. if self.target.startswith('$tag:'):
  280. tag = self.target.split(':', 1)[1]
  281. for name, domain in system_info['domains'].items():
  282. if tag in domain['tags']:
  283. yield name
  284. elif self.target.startswith('$type:'):
  285. type_ = self.target.split(':', 1)[1]
  286. for name, domain in system_info['domains'].items():
  287. if type_ == domain['type']:
  288. yield name
  289. elif self.target == '$anyvm':
  290. for name, domain in system_info['domains'].items():
  291. if name != 'dom0':
  292. yield name
  293. if domain['template_for_dispvms']:
  294. yield '$dispvm:' + name
  295. yield '$dispvm'
  296. elif self.target.startswith('$dispvm:$tag:'):
  297. tag = self.target.split(':', 2)[2]
  298. for name, domain in system_info['domains'].items():
  299. if tag in domain['tags']:
  300. if domain['template_for_dispvms']:
  301. yield '$dispvm:' + name
  302. elif self.target.startswith('$dispvm:'):
  303. dispvm_base = self.target.split(':', 1)[1]
  304. try:
  305. if system_info['domains'][dispvm_base]['template_for_dispvms']:
  306. yield self.target
  307. except KeyError:
  308. # TODO log a warning?
  309. pass
  310. elif self.target == '$adminvm':
  311. yield self.target
  312. elif self.target == '$dispvm':
  313. yield self.target
  314. else:
  315. if self.target in system_info['domains']:
  316. yield self.target
  317. def expand_override_target(self, system_info, source):
  318. '''
  319. Replace '$dispvm' with specific '$dispvm:...' value, based on qrexec
  320. call source.
  321. :param system_info: System information
  322. :param source: Source domain name
  323. :return: :py:attr:`override_target` with '$dispvm' substituted
  324. '''
  325. if self.override_target == '$dispvm':
  326. if system_info['domains'][source]['default_dispvm'] is None:
  327. return None
  328. return '$dispvm:' + system_info['domains'][source]['default_dispvm']
  329. else:
  330. return self.override_target
  331. class PolicyAction(object):
  332. ''' Object representing positive policy evaluation result -
  333. either ask or allow action '''
  334. def __init__(self, service, source, target, rule, original_target,
  335. targets_for_ask=None):
  336. #: service name
  337. self.service = service
  338. #: calling domain
  339. self.source = source
  340. #: target domain the service should be connected to, None if
  341. # not chosen yet
  342. if targets_for_ask is None or target in targets_for_ask:
  343. self.target = target
  344. else:
  345. # TODO: log a warning?
  346. self.target = None
  347. #: original target specified by the caller
  348. self.original_target = original_target
  349. #: targets for the user to choose from
  350. self.targets_for_ask = targets_for_ask
  351. #: policy rule from which this action is derived
  352. self.rule = rule
  353. if rule.action == Action.deny:
  354. # this should be really rejected by Policy.eval()
  355. raise AccessDenied(
  356. 'denied by policy {}:{}'.format(rule.filename, rule.lineno))
  357. elif rule.action == Action.ask:
  358. assert targets_for_ask is not None
  359. elif rule.action == Action.allow:
  360. assert targets_for_ask is None
  361. assert target is not None
  362. self.action = rule.action
  363. def handle_user_response(self, response, target=None):
  364. '''
  365. Handle user response for the 'ask' action
  366. :param response: whether the call was allowed or denied (bool)
  367. :param target: target chosen by the user (if reponse==True)
  368. :return: None
  369. '''
  370. assert self.action == Action.ask
  371. if response:
  372. assert target in self.targets_for_ask
  373. self.target = target
  374. self.action = Action.allow
  375. else:
  376. self.action = Action.deny
  377. raise AccessDenied(
  378. 'denied by the user {}:{}'.format(self.rule.filename,
  379. self.rule.lineno))
  380. def execute(self, caller_ident):
  381. ''' Execute allowed service call
  382. :param caller_ident: Service caller ident
  383. (`process_ident,source_name, source_id`)
  384. '''
  385. assert self.action == Action.allow
  386. assert self.target is not None
  387. if self.target == '$adminvm':
  388. self.target = 'dom0'
  389. if self.target == 'dom0':
  390. cmd = '{multiplexer} {service} {source} {original_target}'.format(
  391. multiplexer=QUBES_RPC_MULTIPLEXER_PATH,
  392. service=self.service,
  393. source=self.source,
  394. original_target=self.original_target)
  395. else:
  396. cmd = '{user}:QUBESRPC {service} {source}'.format(
  397. user=(self.rule.override_user or 'DEFAULT'),
  398. service=self.service,
  399. source=self.source)
  400. if self.target.startswith('$dispvm:'):
  401. target = self.spawn_dispvm()
  402. dispvm = True
  403. else:
  404. target = self.target
  405. dispvm = False
  406. self.ensure_target_running()
  407. qrexec_opts = ['-d', target, '-c', caller_ident]
  408. if dispvm:
  409. qrexec_opts.append('-W')
  410. try:
  411. subprocess.call([QREXEC_CLIENT] + qrexec_opts + [cmd])
  412. finally:
  413. if dispvm:
  414. self.cleanup_dispvm(target)
  415. def spawn_dispvm(self):
  416. '''
  417. Create and start Disposable VM based on AppVM specified in
  418. :py:attr:`target`
  419. :return: name of new Disposable VM
  420. '''
  421. base_appvm = self.target.split(':', 1)[1]
  422. dispvm_name = qubesd_call(base_appvm, 'admin.vm.CreateDisposable')
  423. dispvm_name = dispvm_name.decode('ascii')
  424. qubesd_call(dispvm_name, 'admin.vm.Start')
  425. return dispvm_name
  426. def ensure_target_running(self):
  427. '''
  428. Start domain if not running already
  429. :return: None
  430. '''
  431. if self.target == 'dom0':
  432. return
  433. try:
  434. qubesd_call(self.target, 'admin.vm.Start')
  435. except QubesMgmtException as e:
  436. if e.exc_type == 'QubesVMNotHaltedError':
  437. pass
  438. else:
  439. raise
  440. @staticmethod
  441. def cleanup_dispvm(dispvm):
  442. '''
  443. Kill and remove Disposable VM
  444. :param dispvm: name of Disposable VM
  445. :return: None
  446. '''
  447. qubesd_call(dispvm, 'admin.vm.Kill')
  448. class Policy(object):
  449. ''' Full policy for a given service
  450. Usage:
  451. >>> system_info = get_system_info()
  452. >>> policy = Policy('some-service')
  453. >>> action = policy.evaluate(system_info, 'source-name', 'target-name')
  454. >>> if action.action == Action.ask:
  455. >>> # ... ask the user, see action.targets_for_ask ...
  456. >>> action.handle_user_response(response, target_chosen_by_user)
  457. >>> action.execute('process-ident')
  458. '''
  459. def __init__(self, service, policy_dir=POLICY_DIR):
  460. policy_file = os.path.join(policy_dir, service)
  461. if not os.path.exists(policy_file):
  462. # fallback to policy without specific argument set (if any)
  463. policy_file = os.path.join(policy_dir, service.split('+')[0])
  464. if not os.path.exists(policy_file):
  465. raise PolicyNotFound(service)
  466. #: policy storage directory
  467. self.policy_dir = policy_dir
  468. #: service name
  469. self.service = service
  470. #: list of PolicyLine objects
  471. self.policy_rules = []
  472. try:
  473. self.load_policy_file(policy_file)
  474. except OSError as e:
  475. raise AccessDenied(
  476. 'failed to load {} file: {!s}'.format(e.filename, e))
  477. def load_policy_file(self, path):
  478. ''' Load policy file and append rules to :py:attr:`policy_rules`
  479. :param path: file to load
  480. '''
  481. with open(path) as policy_file:
  482. for lineno, line in zip(itertools.count(start=1),
  483. policy_file.readlines()):
  484. line = line.strip()
  485. if not line:
  486. # skip empty lines
  487. continue
  488. if line[0] == '#':
  489. # skip comments
  490. continue
  491. if line.startswith('$include:'):
  492. include_path = line.split(':', 1)[1]
  493. # os.path.join will leave include_path unchanged if it's
  494. # already absolute
  495. include_path = os.path.join(self.policy_dir, include_path)
  496. self.load_policy_file(include_path)
  497. else:
  498. self.policy_rules.append(PolicyRule(line, path, lineno))
  499. def find_matching_rule(self, system_info, source, target):
  500. ''' Find the first rule matching given arguments '''
  501. for rule in self.policy_rules:
  502. if rule.is_match(system_info, source, target):
  503. return rule
  504. raise AccessDenied('no matching rule found')
  505. def collect_targets_for_ask(self, system_info, source):
  506. ''' Collect targets the user can choose from in 'ask' action
  507. Word 'targets' is used intentionally instead of 'domains', because it
  508. can also contains $dispvm like keywords.
  509. '''
  510. targets = set()
  511. # iterate over rules in reversed order to easier handle 'deny'
  512. # actions - simply remove matching domains from allowed set
  513. for rule in reversed(self.policy_rules):
  514. if rule.is_match_single(system_info, rule.source, source):
  515. if rule.action == Action.deny:
  516. targets -= set(rule.expand_target(system_info))
  517. else:
  518. if rule.override_target is not None:
  519. override_target = rule.expand_override_target(
  520. system_info, source)
  521. if verify_target_value(system_info, override_target):
  522. targets.add(rule.override_target)
  523. else:
  524. targets.update(rule.expand_target(system_info))
  525. # expand default DispVM
  526. if '$dispvm' in targets:
  527. targets.remove('$dispvm')
  528. if system_info['domains'][source]['default_dispvm'] is not None:
  529. dispvm = '$dispvm:' + \
  530. system_info['domains'][source]['default_dispvm']
  531. if verify_target_value(system_info, dispvm):
  532. targets.add(dispvm)
  533. return targets
  534. def evaluate(self, system_info, source, target):
  535. ''' Evaluate policy
  536. :raise AccessDenied: when action should be denied unconditionally
  537. :return tuple(rule, considered_targets) - where considered targets is a
  538. list of possible targets for 'ask' action (rule.action == Action.ask)
  539. '''
  540. rule = self.find_matching_rule(system_info, source, target)
  541. if rule.action == Action.deny:
  542. raise AccessDenied(
  543. 'denied by policy {}:{}'.format(rule.filename, rule.lineno))
  544. if rule.override_target is not None:
  545. override_target = rule.expand_override_target(system_info, source)
  546. if not verify_target_value(system_info, override_target):
  547. raise AccessDenied('invalid target= value in {}:{}'.format(
  548. rule.filename, rule.lineno))
  549. actual_target = override_target
  550. else:
  551. actual_target = target
  552. if rule.action == Action.ask:
  553. if rule.override_target is not None:
  554. targets = [actual_target]
  555. else:
  556. targets = list(
  557. self.collect_targets_for_ask(system_info, source))
  558. if not targets:
  559. raise AccessDenied(
  560. 'policy define \'ask\' action at {}:{} but no target is '
  561. 'available to choose from'.format(
  562. rule.filename, rule.lineno))
  563. return PolicyAction(self.service, source, rule.default_target,
  564. rule, target, targets)
  565. elif rule.action == Action.allow:
  566. if actual_target == '$default':
  567. raise AccessDenied(
  568. 'policy define \'allow\' action at {}:{} but no target is '
  569. 'specified by caller or policy'.format(
  570. rule.filename, rule.lineno))
  571. if actual_target == '$dispvm':
  572. if system_info['domains'][source]['default_dispvm'] is None:
  573. raise AccessDenied(
  574. 'policy define \'allow\' action to $dispvm at {}:{} '
  575. 'but no DispVM base is set for this VM'.format(
  576. rule.filename, rule.lineno))
  577. actual_target = '$dispvm:' + \
  578. system_info['domains'][source]['default_dispvm']
  579. return PolicyAction(self.service, source,
  580. actual_target, rule, target)
  581. else:
  582. # should be unreachable
  583. raise AccessDenied(
  584. 'invalid action?! {}:{}'.format(rule.filename, rule.lineno))
  585. class QubesMgmtException(Exception):
  586. ''' Exception returned by qubesd '''
  587. def __init__(self, exc_type):
  588. super(QubesMgmtException, self).__init__()
  589. self.exc_type = exc_type
  590. def qubesd_call(dest, method, arg=None, payload=None):
  591. if method.startswith('internal.'):
  592. socket_path = QUBESD_INTERNAL_SOCK
  593. else:
  594. socket_path = QUBESD_SOCK
  595. try:
  596. client_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  597. client_socket.connect(socket_path)
  598. except IOError:
  599. # TODO:
  600. raise
  601. # src, method, dest, arg
  602. for call_arg in ('dom0', method, dest, arg):
  603. if call_arg is not None:
  604. client_socket.sendall(call_arg.encode('ascii'))
  605. client_socket.sendall(b'\0')
  606. if payload is not None:
  607. client_socket.sendall(payload)
  608. client_socket.shutdown(socket.SHUT_WR)
  609. return_data = client_socket.makefile('rb').read()
  610. if return_data.startswith(b'0\x00'):
  611. return return_data[2:]
  612. elif return_data.startswith(b'2\x00'):
  613. (_, exc_type, _traceback, _format_string, _args) = \
  614. return_data.split(b'\x00', 4)
  615. raise QubesMgmtException(exc_type.decode('ascii'))
  616. else:
  617. raise AssertionError(
  618. 'invalid qubesd response: {!r}'.format(return_data))
  619. def get_system_info():
  620. ''' Get system information
  621. This retrieve information necessary to process qrexec policy. Returned
  622. data is nested dict structure with this structure:
  623. - domains:
  624. - `<domain name>`:
  625. - tags: list of tags
  626. - type: domain type
  627. - template_for_dispvms: should DispVM based on this VM be allowed
  628. - default_dispvm: name of default AppVM for DispVMs started from here
  629. '''
  630. system_info = qubesd_call('dom0', 'internal.GetSystemInfo')
  631. return json.loads(system_info.decode('utf-8'))