__init__.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. # -*- encoding: utf8 -*-
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2017 Wojtek Porczyk <woju@invisiblethingslab.com>
  6. # Copyright (C) 2017 Marek Marczykowski-Górecki
  7. # <marmarek@invisiblethingslab.com>
  8. #
  9. # This library is free software; you can redistribute it and/or
  10. # modify it under the terms of the GNU Lesser General Public
  11. # License as published by the Free Software Foundation; either
  12. # version 2.1 of the License, or (at your option) any later version.
  13. #
  14. # This library 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 GNU
  17. # Lesser General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU Lesser General Public
  20. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  21. import asyncio
  22. import errno
  23. import functools
  24. import io
  25. import os
  26. import shutil
  27. import socket
  28. import struct
  29. import traceback
  30. import qubes.exc
  31. class ProtocolError(AssertionError):
  32. '''Raised when something is wrong with data received'''
  33. class PermissionDenied(Exception):
  34. '''Raised deliberately by handlers when we decide not to cooperate'''
  35. def method(name, *, no_payload=False, endpoints=None, **classifiers):
  36. '''Decorator factory for methods intended to appear in API.
  37. The decorated method can be called from public API using a child of
  38. :py:class:`AbstractQubesMgmt` class. The method becomes "public", and can be
  39. called using remote management interface.
  40. :param str name: qrexec rpc method name
  41. :param bool no_payload: if :py:obj:`True`, will barf on non-empty payload; \
  42. also will not pass payload at all to the method
  43. :param iterable endpoints: if specified, method serve multiple API calls
  44. generated by replacing `{endpoint}` with each value in this iterable
  45. The expected function method should have one argument (other than usual
  46. *self*), ``untrusted_payload``, which will contain the payload.
  47. .. warning::
  48. This argument has to be named such, to remind the programmer that the
  49. content of this variable is indeed untrusted.
  50. If *no_payload* is true, then the method is called with no arguments.
  51. '''
  52. def decorator(func):
  53. if no_payload:
  54. # the following assignment is needed for how closures work in Python
  55. _func = func
  56. @functools.wraps(_func)
  57. def wrapper(self, untrusted_payload, **kwargs):
  58. if untrusted_payload != b'':
  59. raise ProtocolError('unexpected payload')
  60. return _func(self, **kwargs)
  61. func = wrapper
  62. # pylint: disable=protected-access
  63. if endpoints is None:
  64. func.rpcnames = ((name, None),)
  65. else:
  66. func.rpcnames = tuple(
  67. (name.format(endpoint=endpoint), endpoint)
  68. for endpoint in endpoints)
  69. func.classifiers = classifiers
  70. return func
  71. return decorator
  72. def apply_filters(iterable, filters):
  73. '''Apply filters returned by admin-permission:... event'''
  74. for selector in filters:
  75. iterable = filter(selector, iterable)
  76. return iterable
  77. class AbstractQubesAPI:
  78. '''Common code for Qubes Management Protocol handling
  79. Different interfaces can expose different API call sets, however they share
  80. common protocol and common implementation framework. This class is the
  81. latter.
  82. To implement a new interface, inherit from this class and write at least one
  83. method and decorate it with :py:func:`api` decorator. It will have access to
  84. pre-defined attributes: :py:attr:`app`, :py:attr:`src`, :py:attr:`dest`,
  85. :py:attr:`arg` and :py:attr:`method`.
  86. There are also two helper functions for firing events associated with API
  87. calls.
  88. '''
  89. #: the preferred socket location (to be overridden in child's class)
  90. SOCKNAME = None
  91. def __init__(self, app, src, method_name, dest, arg, send_event=None):
  92. #: :py:class:`qubes.Qubes` object
  93. self.app = app
  94. #: source qube
  95. self.src = self.app.domains[src.decode('ascii')]
  96. #: destination qube
  97. self.dest = self.app.domains[dest.decode('ascii')]
  98. #: argument
  99. self.arg = arg.decode('ascii')
  100. #: name of the method
  101. self.method = method_name.decode('ascii')
  102. #: callback for sending events if applicable
  103. self.send_event = send_event
  104. #: is this operation cancellable?
  105. self.cancellable = False
  106. candidates = list(self.list_methods(self.method))
  107. if not candidates:
  108. raise ProtocolError('no such method: {!r}'.format(self.method))
  109. assert len(candidates) == 1, \
  110. 'multiple candidates for method {!r}'.format(self.method)
  111. #: the method to execute
  112. self._handler = candidates[0]
  113. self._running_handler = None
  114. @classmethod
  115. def list_methods(cls, select_method=None):
  116. for attr in dir(cls):
  117. func = getattr(cls, attr)
  118. if not callable(func):
  119. continue
  120. try:
  121. # pylint: disable=protected-access
  122. rpcnames = func.rpcnames
  123. except AttributeError:
  124. continue
  125. for mname, endpoint in rpcnames:
  126. if select_method is None or mname == select_method:
  127. yield (func, mname, endpoint)
  128. def execute(self, *, untrusted_payload):
  129. '''Execute management operation.
  130. This method is a coroutine.
  131. '''
  132. handler, _, endpoint = self._handler
  133. kwargs = {}
  134. if endpoint is not None:
  135. kwargs['endpoint'] = endpoint
  136. self._running_handler = asyncio.ensure_future(handler(self,
  137. untrusted_payload=untrusted_payload, **kwargs))
  138. return self._running_handler
  139. def cancel(self):
  140. '''If operation is cancellable, interrupt it'''
  141. if self.cancellable and self._running_handler is not None:
  142. self._running_handler.cancel()
  143. def fire_event_for_permission(self, **kwargs):
  144. '''Fire an event on the source qube to check for permission'''
  145. return self.src.fire_event('admin-permission:' + self.method,
  146. pre_event=True, dest=self.dest, arg=self.arg, **kwargs)
  147. def fire_event_for_filter(self, iterable, **kwargs):
  148. '''Fire an event on the source qube to filter for permission'''
  149. return apply_filters(iterable,
  150. self.fire_event_for_permission(**kwargs))
  151. @staticmethod
  152. def enforce(predicate):
  153. '''An assert replacement, but works even with optimisations.'''
  154. if not predicate:
  155. raise PermissionDenied()
  156. class QubesDaemonProtocol(asyncio.Protocol):
  157. buffer_size = 65536
  158. header = struct.Struct('Bx')
  159. # keep track of connections, to gracefully close them at server exit
  160. # (including cleanup of integration test)
  161. connections = set()
  162. def __init__(self, handler, *args, app, debug=False, **kwargs):
  163. super().__init__(*args, **kwargs)
  164. self.handler = handler
  165. self.app = app
  166. self.untrusted_buffer = io.BytesIO()
  167. self.len_untrusted_buffer = 0
  168. self.transport = None
  169. self.debug = debug
  170. self.event_sent = False
  171. self.mgmt = None
  172. def connection_made(self, transport):
  173. self.transport = transport
  174. self.connections.add(self)
  175. def connection_lost(self, exc):
  176. self.untrusted_buffer.close()
  177. # for cancellable operation, interrupt it, otherwise it will do nothing
  178. if self.mgmt is not None:
  179. self.mgmt.cancel()
  180. self.transport = None
  181. self.connections.remove(self)
  182. def data_received(self, untrusted_data): # pylint: disable=arguments-differ
  183. if self.len_untrusted_buffer + len(untrusted_data) > self.buffer_size:
  184. self.app.log.warning('request too long')
  185. self.transport.abort()
  186. self.untrusted_buffer.close()
  187. return
  188. self.len_untrusted_buffer += \
  189. self.untrusted_buffer.write(untrusted_data)
  190. def eof_received(self):
  191. try:
  192. src, meth, dest, arg, untrusted_payload = \
  193. self.untrusted_buffer.getvalue().split(b'\0', 4)
  194. except ValueError:
  195. self.app.log.warning('framing error')
  196. self.transport.abort()
  197. return None
  198. finally:
  199. self.untrusted_buffer.close()
  200. asyncio.ensure_future(self.respond(
  201. src, meth, dest, arg, untrusted_payload=untrusted_payload))
  202. return True
  203. @asyncio.coroutine
  204. def respond(self, src, meth, dest, arg, *, untrusted_payload):
  205. try:
  206. self.mgmt = self.handler(self.app, src, meth, dest, arg,
  207. self.send_event)
  208. response = yield from self.mgmt.execute(
  209. untrusted_payload=untrusted_payload)
  210. assert not (self.event_sent and response)
  211. if self.transport is None:
  212. return
  213. # except clauses will fall through to transport.abort() below
  214. except PermissionDenied:
  215. self.app.log.warning(
  216. 'permission denied for call %s+%s (%s → %s) '
  217. 'with payload of %d bytes',
  218. meth, arg, src, dest, len(untrusted_payload))
  219. except ProtocolError:
  220. self.app.log.warning(
  221. 'protocol error for call %s+%s (%s → %s) '
  222. 'with payload of %d bytes',
  223. meth, arg, src, dest, len(untrusted_payload))
  224. except qubes.exc.QubesException as err:
  225. msg = ('%r while calling '
  226. 'src=%r meth=%r dest=%r arg=%r len(untrusted_payload)=%d')
  227. if self.debug:
  228. self.app.log.debug(msg,
  229. err, src, meth, dest, arg, len(untrusted_payload),
  230. exc_info=1)
  231. if self.transport is not None:
  232. self.send_exception(err)
  233. self.transport.write_eof()
  234. self.transport.close()
  235. return
  236. except Exception: # pylint: disable=broad-except
  237. self.app.log.exception(
  238. 'unhandled exception while calling '
  239. 'src=%r meth=%r dest=%r arg=%r len(untrusted_payload)=%d',
  240. src, meth, dest, arg, len(untrusted_payload))
  241. else:
  242. if not self.event_sent:
  243. self.send_response(response)
  244. try:
  245. self.transport.write_eof()
  246. except NotImplementedError:
  247. pass
  248. self.transport.close()
  249. return
  250. # this is reached if from except: blocks; do not put it in finally:,
  251. # because this will prevent the good case from sending the reply
  252. if self.transport:
  253. self.transport.abort()
  254. def send_header(self, *args):
  255. self.transport.write(self.header.pack(*args))
  256. def send_response(self, content):
  257. assert not self.event_sent
  258. self.send_header(0x30)
  259. if content is not None:
  260. self.transport.write(content.encode('utf-8'))
  261. def send_event(self, subject, event, **kwargs):
  262. if self.transport is None:
  263. return
  264. self.event_sent = True
  265. self.send_header(0x31)
  266. if subject is not self.app:
  267. self.transport.write(str(subject).encode('ascii'))
  268. self.transport.write(b'\0')
  269. self.transport.write(event.encode('ascii') + b'\0')
  270. for k, v in kwargs.items():
  271. self.transport.write('{}\0{}\0'.format(k, str(v)).encode('ascii'))
  272. self.transport.write(b'\0')
  273. def send_exception(self, exc):
  274. self.send_header(0x32)
  275. self.transport.write(type(exc).__name__.encode() + b'\0')
  276. if self.debug:
  277. self.transport.write(''.join(traceback.format_exception(
  278. type(exc), exc, exc.__traceback__)).encode('utf-8'))
  279. self.transport.write(b'\0')
  280. self.transport.write(str(exc).encode('utf-8') + b'\0')
  281. def cleanup_socket(sockpath, force):
  282. '''Remove socket if stale, or force=True
  283. :param sockpath: path to a socket
  284. :param force: should remove even if still used
  285. '''
  286. if force:
  287. os.unlink(sockpath)
  288. else:
  289. sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  290. try:
  291. sock.connect(sockpath)
  292. except ConnectionRefusedError:
  293. # dead socket, remove it anyway
  294. os.unlink(sockpath)
  295. else:
  296. # woops, someone is listening
  297. sock.close()
  298. raise FileExistsError(errno.EEXIST,
  299. 'socket already exists: {!r}'.format(sockpath))
  300. @asyncio.coroutine
  301. def create_servers(*args, force=False, loop=None, **kwargs):
  302. '''Create multiple Qubes API servers
  303. :param qubes.Qubes app: the app that is a backend of the servers
  304. :param bool force: if :py:obj:`True`, unconditionally remove existing \
  305. sockets; if :py:obj:`False`, raise an error if there is some process \
  306. listening to such socket
  307. :param asyncio.Loop loop: loop
  308. *args* are supposed to be classes inheriting from
  309. :py:class:`AbstractQubesAPI`
  310. *kwargs* (like *app* or *debug* for example) are passed to
  311. :py:class:`QubesDaemonProtocol` constructor
  312. '''
  313. loop = loop or asyncio.get_event_loop()
  314. servers = []
  315. old_umask = os.umask(0o007)
  316. try:
  317. # XXX this can be optimised with asyncio.wait() to start servers in
  318. # parallel, but I currently don't see the need
  319. for handler in args:
  320. sockpath = handler.SOCKNAME
  321. assert sockpath is not None, \
  322. 'SOCKNAME needs to be overloaded in {}'.format(
  323. type(handler).__name__)
  324. if os.path.exists(sockpath):
  325. cleanup_socket(sockpath, force)
  326. server = yield from loop.create_unix_server(
  327. functools.partial(QubesDaemonProtocol, handler, **kwargs),
  328. sockpath)
  329. for sock in server.sockets:
  330. shutil.chown(sock.getsockname(), group='qubes')
  331. servers.append(server)
  332. except:
  333. for server in servers:
  334. for sock in server.sockets:
  335. try:
  336. os.unlink(sock.getsockname())
  337. except FileNotFoundError:
  338. pass
  339. server.close()
  340. if servers:
  341. yield from asyncio.wait([
  342. server.wait_closed() for server in servers])
  343. raise
  344. finally:
  345. os.umask(old_umask)
  346. return servers