Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

util.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. ###############################################################################
  2. #
  3. # The MIT License (MIT)
  4. #
  5. # Copyright (c) typedef int GmbH
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining a copy
  8. # of this software and associated documentation files (the "Software"), to deal
  9. # in the Software without restriction, including without limitation the rights
  10. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. # copies of the Software, and to permit persons to whom the Software is
  12. # furnished to do so, subject to the following conditions:
  13. #
  14. # The above copyright notice and this permission notice shall be included in
  15. # all copies or substantial portions of the Software.
  16. #
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. # THE SOFTWARE.
  24. #
  25. ###############################################################################
  26. import os
  27. import hashlib
  28. import threading
  29. from typing import Optional, Union, Dict, Any
  30. from twisted.internet.defer import Deferred
  31. from twisted.internet.address import IPv4Address, UNIXAddress
  32. from twisted.internet.interfaces import ITransport, IProcessTransport
  33. from autobahn.wamp.types import TransportDetails
  34. try:
  35. from twisted.internet.stdio import PipeAddress
  36. except ImportError:
  37. # stdio.PipeAddress is only avail on Twisted 13.0+
  38. PipeAddress = type(None)
  39. try:
  40. from twisted.internet.address import IPv6Address
  41. _HAS_IPV6 = True
  42. except ImportError:
  43. _HAS_IPV6 = False
  44. IPv6Address = type(None)
  45. try:
  46. from twisted.internet.interfaces import ISSLTransport
  47. from twisted.protocols.tls import TLSMemoryBIOProtocol
  48. from OpenSSL.SSL import Connection
  49. _HAS_TLS = True
  50. except ImportError:
  51. _HAS_TLS = False
  52. __all = (
  53. 'sleep',
  54. 'peer2str',
  55. 'transport_channel_id',
  56. 'extract_peer_certificate',
  57. 'create_transport_details',
  58. )
  59. def sleep(delay, reactor=None):
  60. """
  61. Inline sleep for use in co-routines (Twisted ``inlineCallback`` decorated functions).
  62. .. seealso::
  63. * `twisted.internet.defer.inlineCallbacks <http://twistedmatrix.com/documents/current/api/twisted.internet.defer.html#inlineCallbacks>`__
  64. * `twisted.internet.interfaces.IReactorTime <http://twistedmatrix.com/documents/current/api/twisted.internet.interfaces.IReactorTime.html>`__
  65. :param delay: Time to sleep in seconds.
  66. :type delay: float
  67. :param reactor: The Twisted reactor to use.
  68. :type reactor: None or provider of ``IReactorTime``.
  69. """
  70. if not reactor:
  71. from twisted.internet import reactor
  72. d = Deferred()
  73. reactor.callLater(delay, d.callback, None)
  74. return d
  75. def peer2str(transport: Union[ITransport, IProcessTransport]) -> str:
  76. """
  77. Return a *peer descriptor* given a Twisted transport, for example:
  78. * ``tcp4:127.0.0.1:52914``: a TCPv4 socket
  79. * ``unix:/tmp/server.sock``: a Unix domain socket
  80. * ``process:142092``: a Pipe originating from a spawning (parent) process
  81. * ``pipe``: a Pipe terminating in a spawned (child) process
  82. :returns: Returns a string representation of the peer of the Twisted transport.
  83. """
  84. # IMPORTANT: we need to _first_ test for IProcessTransport
  85. if IProcessTransport.providedBy(transport):
  86. # note the PID of the forked process in the peer descriptor
  87. res = "process:{}".format(transport.pid)
  88. elif ITransport.providedBy(transport):
  89. addr: Union[IPv4Address, IPv6Address, UNIXAddress, PipeAddress] = transport.getPeer()
  90. if isinstance(addr, IPv4Address):
  91. res = "tcp4:{0}:{1}".format(addr.host, addr.port)
  92. elif _HAS_IPV6 and isinstance(addr, IPv6Address):
  93. res = "tcp6:{0}:{1}".format(addr.host, addr.port)
  94. elif isinstance(addr, UNIXAddress):
  95. if addr.name:
  96. res = "unix:{0}".format(addr.name)
  97. else:
  98. res = "unix"
  99. elif isinstance(addr, PipeAddress):
  100. # sadly, we don't have a way to get at the PID of the other side of the pipe
  101. # res = "pipe"
  102. res = "process:{0}".format(os.getppid())
  103. else:
  104. # gracefully fallback if we can't map the peer's address
  105. res = "unknown"
  106. else:
  107. # gracefully fallback if we can't map the peer's transport
  108. res = "unknown"
  109. return res
  110. if not _HAS_TLS:
  111. def transport_channel_id(transport: object, is_server: bool, channel_id_type: Optional[str] = None) -> Optional[bytes]:
  112. if channel_id_type is None:
  113. return b'\x00' * 32
  114. else:
  115. raise RuntimeError('cannot determine TLS channel ID of type "{}" when TLS is not available on this system'.format(channel_id_type))
  116. else:
  117. def transport_channel_id(transport: object, is_server: bool, channel_id_type: Optional[str] = None) -> Optional[bytes]:
  118. """
  119. Return TLS channel ID of WAMP transport of the given TLS channel ID type.
  120. Application-layer user authentication protocols are vulnerable to generic credential forwarding attacks,
  121. where an authentication credential sent by a client C to a server M may then be used by M to impersonate C at
  122. another server S.
  123. To prevent such credential forwarding attacks, modern authentication protocols rely on channel bindings.
  124. For example, WAMP-cryptosign can use the tls-unique channel identifier provided by the TLS layer to strongly
  125. bind authentication credentials to the underlying channel, so that a credential received on one TLS channel
  126. cannot be forwarded on another.
  127. :param transport: The Twisted TLS transport to extract the TLS channel ID from. If the transport isn't
  128. TLS based, and non-empty ``channel_id_type`` is requested, ``None`` will be returned. If the transport
  129. is indeed TLS based, an empty ``channel_id_type`` of ``None`` is requested, 32 NUL bytes will be returned.
  130. :param is_server: Flag indicating that the transport is a server transport.
  131. :param channel_id_type: TLS channel ID type, if set currently only ``"tls-unique"`` is supported.
  132. :returns: The TLS channel ID (32 bytes).
  133. """
  134. if channel_id_type is None:
  135. return b'\x00' * 32
  136. if channel_id_type not in ['tls-unique']:
  137. raise RuntimeError('invalid TLS channel ID type "{}" requested'.format(channel_id_type))
  138. if not isinstance(transport, TLSMemoryBIOProtocol):
  139. raise RuntimeError(
  140. 'cannot determine TLS channel ID of type "{}" when TLS is not available on this transport {}'.format(
  141. channel_id_type, type(transport)))
  142. # get access to the OpenSSL connection underlying the Twisted protocol
  143. # https://twistedmatrix.com/documents/current/api/twisted.protocols.tls.TLSMemoryBIOProtocol.html#getHandle
  144. connection: Connection = transport.getHandle()
  145. assert connection and isinstance(connection, Connection)
  146. # Obtain latest TLS Finished message that we expected from peer, or None if handshake is not completed.
  147. # http://www.pyopenssl.org/en/stable/api/ssl.html#OpenSSL.SSL.Connection.get_peer_finished
  148. is_not_resumed = True
  149. if channel_id_type == 'tls-unique':
  150. # see also: https://bugs.python.org/file22646/tls_channel_binding.patch
  151. if is_server != is_not_resumed:
  152. # for routers (=servers) XOR new sessions, the channel ID is based on the TLS Finished message we
  153. # expected to receive from the client: contents of the message or None if the TLS handshake has
  154. # not yet completed.
  155. tls_finished_msg = connection.get_peer_finished()
  156. else:
  157. # for clients XOR resumed sessions, the channel ID is based on the TLS Finished message we sent
  158. # to the router (=server): contents of the message or None if the TLS handshake has not yet completed.
  159. tls_finished_msg = connection.get_finished()
  160. if tls_finished_msg is None:
  161. # this can occur when:
  162. # 1. we made a successful connection (in a TCP sense) but something failed with
  163. # the TLS handshake (e.g. invalid certificate)
  164. # 2. the TLS handshake has not yet completed
  165. return b'\x00' * 32
  166. else:
  167. m = hashlib.sha256()
  168. m.update(tls_finished_msg)
  169. return m.digest()
  170. else:
  171. raise NotImplementedError('should not arrive here (unhandled channel_id_type "{}")'.format(channel_id_type))
  172. if not _HAS_TLS:
  173. def extract_peer_certificate(transport: object) -> Optional[Dict[str, Any]]:
  174. """
  175. Dummy when no TLS is available.
  176. :param transport: Ignored.
  177. :return: Always return ``None``.
  178. """
  179. return None
  180. else:
  181. def extract_peer_certificate(transport: TLSMemoryBIOProtocol) -> Optional[Dict[str, Any]]:
  182. """
  183. Extract TLS x509 client certificate information from a Twisted stream transport, and
  184. return a dict with x509 TLS client certificate information (if the client provided a
  185. TLS client certificate).
  186. :param transport: The secure transport from which to extract the peer certificate (if present).
  187. :returns: If the peer provided a certificate, the parsed certificate information set.
  188. """
  189. # check if the Twisted transport is a TLSMemoryBIOProtocol
  190. if not (ISSLTransport.providedBy(transport) and hasattr(transport, 'getPeerCertificate')):
  191. return None
  192. cert = transport.getPeerCertificate()
  193. if cert:
  194. # extract x509 name components from an OpenSSL X509Name object
  195. def maybe_bytes(_value):
  196. if isinstance(_value, bytes):
  197. return _value.decode('utf8')
  198. else:
  199. return _value
  200. result = {
  201. 'md5': '{}'.format(maybe_bytes(cert.digest('md5'))).upper(),
  202. 'sha1': '{}'.format(maybe_bytes(cert.digest('sha1'))).upper(),
  203. 'sha256': '{}'.format(maybe_bytes(cert.digest('sha256'))).upper(),
  204. 'expired': bool(cert.has_expired()),
  205. 'hash': maybe_bytes(cert.subject_name_hash()),
  206. 'serial': int(cert.get_serial_number()),
  207. 'signature_algorithm': maybe_bytes(cert.get_signature_algorithm()),
  208. 'version': int(cert.get_version()),
  209. 'not_before': maybe_bytes(cert.get_notBefore()),
  210. 'not_after': maybe_bytes(cert.get_notAfter()),
  211. 'extensions': []
  212. }
  213. for i in range(cert.get_extension_count()):
  214. ext = cert.get_extension(i)
  215. ext_info = {
  216. 'name': '{}'.format(maybe_bytes(ext.get_short_name())),
  217. 'value': '{}'.format(maybe_bytes(ext)),
  218. 'critical': ext.get_critical() != 0
  219. }
  220. result['extensions'].append(ext_info)
  221. for entity, name in [('subject', cert.get_subject()), ('issuer', cert.get_issuer())]:
  222. result[entity] = {}
  223. for key, value in name.get_components():
  224. key = maybe_bytes(key)
  225. value = maybe_bytes(value)
  226. result[entity]['{}'.format(key).lower()] = '{}'.format(value)
  227. return result
  228. def create_transport_details(transport: Union[ITransport, IProcessTransport], is_server: bool) -> TransportDetails:
  229. """
  230. Create transport details from Twisted transport.
  231. :param transport: The Twisted transport to extract information from.
  232. :param is_server: Flag indicating whether this transport side is a "server" (as in TCP server).
  233. :return: Transport details object filled with information from the Twisted transport.
  234. """
  235. peer = peer2str(transport)
  236. own_pid = os.getpid()
  237. if hasattr(threading, 'get_native_id'):
  238. # New in Python 3.8
  239. # https://docs.python.org/3/library/threading.html?highlight=get_native_id#threading.get_native_id
  240. own_tid = threading.get_native_id()
  241. else:
  242. own_tid = threading.get_ident()
  243. own_fd = -1
  244. if _HAS_TLS and ISSLTransport.providedBy(transport):
  245. channel_id = {
  246. # this will only be filled when the TLS opening handshake is complete (!)
  247. 'tls-unique': transport_channel_id(transport, is_server, 'tls-unique'),
  248. }
  249. channel_type = TransportDetails.CHANNEL_TYPE_TLS
  250. peer_cert = extract_peer_certificate(transport)
  251. is_secure = True
  252. else:
  253. channel_id = {}
  254. channel_type = TransportDetails.CHANNEL_TYPE_TCP
  255. peer_cert = None
  256. is_secure = False
  257. # FIXME: really set a default (websocket)?
  258. channel_framing = TransportDetails.CHANNEL_FRAMING_WEBSOCKET
  259. td = TransportDetails(channel_type=channel_type, channel_framing=channel_framing, peer=peer,
  260. is_server=is_server, own_pid=own_pid, own_tid=own_tid, own_fd=own_fd,
  261. is_secure=is_secure, channel_id=channel_id, peer_cert=peer_cert)
  262. return td