__init__.py 27 KB

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