__init__.py 23 KB

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