PageRenderTime 27ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/M2Crypto/SSL/Connection.py

https://gitlab.com/mitr/m2crypto
Python | 613 lines | 558 code | 20 blank | 35 comment | 11 complexity | 89843bf25fc7a45ad15128853ea53950 MD5 | raw file
  1. from __future__ import absolute_import
  2. """SSL Connection aka socket
  3. Copyright (c) 1999-2004 Ng Pheng Siong. All rights reserved.
  4. Portions created by Open Source Applications Foundation (OSAF) are
  5. Copyright (C) 2004-2007 OSAF. All Rights Reserved.
  6. Copyright 2008 Heikki Toivonen. All rights reserved.
  7. """
  8. import logging
  9. import socket
  10. from M2Crypto import BIO, X509, m2, util # noqa
  11. from M2Crypto.SSL import Checker, Context, timeout # noqa
  12. from M2Crypto.SSL import SSLError
  13. from M2Crypto.SSL.Cipher import Cipher, Cipher_Stack
  14. from M2Crypto.SSL.Session import Session
  15. if util.py27plus:
  16. from typing import Any, AnyStr, Callable, Dict, List, Optional, Tuple, Union # noqa
  17. __all__ = ['Connection',
  18. 'timeout', # XXX Not really, but for documentation purposes
  19. ]
  20. log = logging.getLogger(__name__)
  21. def _serverPostConnectionCheck(*args, **kw):
  22. # type: (*List[Any], **Dict[Any, Any]) -> int
  23. return 1
  24. class Connection:
  25. """An SSL connection."""
  26. clientPostConnectionCheck = Checker.Checker()
  27. serverPostConnectionCheck = _serverPostConnectionCheck
  28. m2_bio_free = m2.bio_free
  29. m2_ssl_free = m2.ssl_free
  30. def __init__(self, ctx, sock=None, family=socket.AF_INET):
  31. # type: (Context, socket.socket, int) -> None
  32. """
  33. @param ctx: SSL.Context
  34. @param sock: socket to be used
  35. @param family: socket family
  36. """
  37. self.ctx = ctx
  38. self.ssl = m2.ssl_new(self.ctx.ctx)
  39. if sock is not None:
  40. self.socket = sock
  41. else:
  42. self.socket = socket.socket(family, socket.SOCK_STREAM)
  43. self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  44. self._fileno = self.socket.fileno()
  45. self._timeout = self.socket.gettimeout()
  46. if self._timeout is None:
  47. self._timeout = -1.0
  48. self.ssl_close_flag = m2.bio_noclose
  49. if self.ctx.post_connection_check is not None:
  50. self.set_post_connection_check_callback(
  51. self.ctx.post_connection_check)
  52. def __del__(self):
  53. # type: () -> None
  54. if getattr(self, 'sslbio', None):
  55. self.m2_bio_free(self.sslbio)
  56. if getattr(self, 'sockbio', None):
  57. self.m2_bio_free(self.sockbio)
  58. if self.ssl_close_flag == m2.bio_noclose and \
  59. getattr(self, 'ssl', None):
  60. self.m2_ssl_free(self.ssl)
  61. self.socket.close()
  62. def close(self):
  63. # type: () -> None
  64. m2.ssl_shutdown(self.ssl)
  65. def clear(self):
  66. # type: () -> int
  67. """
  68. If there were errors in this connection, call clear() rather
  69. than close() to end it, so that bad sessions will be cleared
  70. from cache.
  71. """
  72. return m2.ssl_clear(self.ssl)
  73. def set_shutdown(self, mode):
  74. # type: (int) -> None
  75. """Sets the shutdown state of the Connection to mode.
  76. The shutdown state of an ssl connection is a bitmask of (use
  77. m2.SSL_* constants):
  78. 0 No shutdown setting, yet.
  79. SSL_SENT_SHUTDOWN
  80. A "close notify" shutdown alert was sent to the peer, the
  81. connection is being considered closed and the session is
  82. closed and correct.
  83. SSL_RECEIVED_SHUTDOWN
  84. A shutdown alert was received form the peer, either a normal
  85. "close notify" or a fatal error.
  86. SSL_SENT_SHUTDOWN and SSL_RECEIVED_SHUTDOWN can be set at the
  87. same time.
  88. @param mode: set the mode bitmask.
  89. """
  90. m2.ssl_set_shutdown1(self.ssl, mode)
  91. def get_shutdown(self):
  92. # type: () -> None
  93. """Get the current shutdown mode of the Connection."""
  94. return m2.ssl_get_shutdown(self.ssl)
  95. def bind(self, addr):
  96. # type: (util.AddrType) -> None
  97. self.socket.bind(addr)
  98. def listen(self, qlen=5):
  99. # type: (int) -> None
  100. self.socket.listen(qlen)
  101. def ssl_get_error(self, ret):
  102. # type: (int) -> int
  103. return m2.ssl_get_error(self.ssl, ret)
  104. def set_bio(self, readbio, writebio):
  105. # type: (BIO.BIO, BIO.BIO) -> None
  106. """Explicitly set read and write bios
  107. Connects the BIOs for the read and write operations of the
  108. TLS/SSL (encrypted) side of ssl.
  109. The SSL engine inherits the behaviour of both BIO objects,
  110. respectively. If a BIO is non-blocking, the Connection will also
  111. have non-blocking behaviour.
  112. If there was already a BIO connected to Connection, BIO_free()
  113. will be called (for both the reading and writing side, if
  114. different).
  115. @param readbio: BIO for reading
  116. @param writebio: BIO for writing.
  117. """
  118. m2.ssl_set_bio(self.ssl, readbio._ptr(), writebio._ptr())
  119. def set_client_CA_list_from_file(self, cafile):
  120. # type: (AnyStr) -> None
  121. """Set the acceptable client CA list.
  122. If the client returns a certificate, it must have been issued by
  123. one of the CAs listed in cafile.
  124. Makes sense only for servers.
  125. @param cafile: Filename from which to load the CA list.
  126. @return: 0 A failure while manipulating the STACK_OF(X509_NAME)
  127. object occurred or the X509_NAME could not be
  128. extracted from cacert. Check the error stack to find
  129. out the reason.
  130. 1 The operation succeeded.
  131. """
  132. m2.ssl_set_client_CA_list_from_file(self.ssl, cafile)
  133. def set_client_CA_list_from_context(self):
  134. # type: () -> None
  135. """
  136. Set the acceptable client CA list. If the client
  137. returns a certificate, it must have been issued by
  138. one of the CAs listed in context.
  139. Makes sense only for servers.
  140. """
  141. m2.ssl_set_client_CA_list_from_context(self.ssl, self.ctx.ctx)
  142. def setup_addr(self, addr):
  143. # type: (util.AddrType) -> None
  144. self.addr = addr
  145. def set_ssl_close_flag(self, flag):
  146. # type: (int) -> None
  147. """
  148. By default, SSL struct will be freed in __del__. Call with
  149. m2.bio_close to override this default.
  150. @param flag: either m2.bio_close or m2.bio_noclose
  151. """
  152. if flag not in (m2.bio_close, m2.bio_noclose):
  153. raise ValueError("flag must be m2.bio_close or m2.bio_noclose")
  154. self.ssl_close_flag = flag
  155. def setup_ssl(self):
  156. # type: () -> None
  157. # Make a BIO_s_socket.
  158. self.sockbio = m2.bio_new_socket(self.socket.fileno(), 0)
  159. # Link SSL struct with the BIO_socket.
  160. m2.ssl_set_bio(self.ssl, self.sockbio, self.sockbio)
  161. # Make a BIO_f_ssl.
  162. self.sslbio = m2.bio_new(m2.bio_f_ssl())
  163. # Link BIO_f_ssl with the SSL struct.
  164. m2.bio_set_ssl(self.sslbio, self.ssl, m2.bio_noclose)
  165. def _setup_ssl(self, addr):
  166. # type: (util.AddrType) -> None
  167. """Deprecated"""
  168. self.setup_addr(addr)
  169. self.setup_ssl()
  170. def set_accept_state(self):
  171. # type: () -> None
  172. """Sets Connection to work in the server mode."""
  173. m2.ssl_set_accept_state(self.ssl)
  174. def accept_ssl(self):
  175. # type: () -> Optional[int]
  176. """Waits for a TLS/SSL client to initiate the TLS/SSL handshake.
  177. The communication channel must already have been set and
  178. assigned to the ssl by setting an underlying BIO.
  179. @return: 0 The TLS/SSL handshake was not successful but was shut
  180. down controlled and by the specifications of the
  181. TLS/SSL protocol. Call get_error() with the return
  182. value ret to find out the reason.
  183. 1 The TLS/SSL handshake was successfully completed,
  184. a TLS/SSL connection has been established.
  185. <0 The TLS/SSL handshake was not successful because
  186. a fatal error occurred either at the protocol level
  187. or a connection failure occurred. The shutdown was
  188. not clean. It can also occur of action is need to
  189. continue the operation for non-blocking BIOs. Call
  190. get_error() with the return value ret to find
  191. out the reason.
  192. """
  193. return m2.ssl_accept(self.ssl, self._timeout)
  194. def accept(self):
  195. # type: () -> Tuple[Connection, util.AddrType]
  196. """Accept an SSL connection.
  197. The return value is a pair (ssl, addr) where ssl is a new SSL
  198. connection object and addr is the address bound to the other end
  199. of the SSL connection.
  200. @return: tuple of Connection and addr. Address can take very
  201. various forms (see socket documentation), for IPv4 it is
  202. tuple(str, int), for IPv6 a tuple of four (host, port, flowinfo,
  203. scopeid), where the last two are optional ints.
  204. """
  205. sock, addr = self.socket.accept()
  206. ssl = Connection(self.ctx, sock)
  207. ssl.addr = addr
  208. ssl.setup_ssl()
  209. ssl.set_accept_state()
  210. ssl.accept_ssl()
  211. check = getattr(self, 'postConnectionCheck',
  212. self.serverPostConnectionCheck)
  213. if check is not None:
  214. if not check(ssl.get_peer_cert(), ssl.addr[0]):
  215. raise Checker.SSLVerificationError(
  216. 'post connection check failed')
  217. return ssl, addr
  218. def set_connect_state(self):
  219. # type: () -> None
  220. """Sets Connection to work in the client mode."""
  221. m2.ssl_set_connect_state(self.ssl)
  222. def connect_ssl(self):
  223. # type: () -> Optional[int]
  224. return m2.ssl_connect(self.ssl, self._timeout)
  225. def connect(self, addr):
  226. # type: (util.AddrType) -> int
  227. """Overloading socket.connect()
  228. @param addr: addresses have various depending on their type
  229. @return:status of ssl_connect()
  230. """
  231. self.socket.connect(addr)
  232. self.addr = addr
  233. self.setup_ssl()
  234. self.set_connect_state()
  235. ret = self.connect_ssl()
  236. check = getattr(self, 'postConnectionCheck',
  237. self.clientPostConnectionCheck)
  238. if check is not None:
  239. if not check(self.get_peer_cert(), self.addr[0]):
  240. raise Checker.SSLVerificationError(
  241. 'post connection check failed')
  242. return ret
  243. def shutdown(self, how):
  244. # type: (int) -> None
  245. m2.ssl_set_shutdown(self.ssl, how)
  246. def renegotiate(self):
  247. # type: () -> int
  248. """Renegotiate this connection's SSL parameters."""
  249. return m2.ssl_renegotiate(self.ssl)
  250. def pending(self):
  251. # type: () -> int
  252. """Return the numbers of octets that can be read from the connection."""
  253. return m2.ssl_pending(self.ssl)
  254. def _write_bio(self, data):
  255. # type: (bytes) -> int
  256. return m2.ssl_write(self.ssl, data, self._timeout)
  257. def _write_nbio(self, data):
  258. # type: (bytes) -> int
  259. return m2.ssl_write_nbio(self.ssl, data)
  260. def _read_bio(self, size=1024):
  261. # type: (int) -> bytes
  262. if size <= 0:
  263. raise ValueError('size <= 0')
  264. return m2.ssl_read(self.ssl, size, self._timeout)
  265. def _read_nbio(self, size=1024):
  266. # type: (int) -> bytes
  267. if size <= 0:
  268. raise ValueError('size <= 0')
  269. return m2.ssl_read_nbio(self.ssl, size)
  270. def write(self, data):
  271. # type: (bytes) -> int
  272. if self._timeout != 0.0:
  273. return self._write_bio(data)
  274. return self._write_nbio(data)
  275. sendall = send = write
  276. def read(self, size=1024):
  277. # type: (int) -> bytes
  278. if self._timeout != 0.0:
  279. return self._read_bio(size)
  280. return self._read_nbio(size)
  281. recv = read
  282. def setblocking(self, mode):
  283. # type: (int) -> None
  284. """Set this connection's underlying socket to _mode_.
  285. Set blocking or non-blocking mode of the socket: if flag is 0,
  286. the socket is set to non-blocking, else to blocking mode.
  287. Initially all sockets are in blocking mode. In non-blocking mode,
  288. if a recv() call doesn't find any data, or if a send() call can't
  289. immediately dispose of the data, a error exception is raised;
  290. in blocking mode, the calls block until they can proceed.
  291. s.setblocking(0) is equivalent to s.settimeout(0.0);
  292. s.setblocking(1) is equivalent to s.settimeout(None).
  293. @param mode: new mode to be set
  294. """
  295. self.socket.setblocking(mode)
  296. if mode:
  297. self._timeout = -1.0
  298. else:
  299. self._timeout = 0.0
  300. def settimeout(self, timeout):
  301. # type: (float) -> None
  302. """Set this connection's underlying socket's timeout to _timeout_."""
  303. self.socket.settimeout(timeout)
  304. self._timeout = timeout
  305. if self._timeout is None:
  306. self._timeout = -1.0
  307. def fileno(self):
  308. # type: () -> int
  309. return self.socket.fileno()
  310. def getsockopt(self, level, optname, buflen=None):
  311. # type: (int, int, Optional[int]) -> Union[int, bytes]
  312. """Get the value of the given socket option.
  313. @param level: level at which the option resides.
  314. To manipulate options at the sockets API level, level is
  315. specified as socket.SOL_SOCKET. To manipulate options at
  316. any other level the protocol number of the appropriate
  317. protocol controlling the option is supplied. For example,
  318. to indicate that an option is to be interpreted by the
  319. TCP protocol, level should be set to the protocol number
  320. of socket.SOL_TCP; see getprotoent(3).
  321. @param optname: The value of the given socket option is
  322. described in the Unix man page getsockopt(2)). The needed
  323. symbolic constants (SO_* etc.) are defined in the socket
  324. module.
  325. @param buflen: If it is absent, an integer option is assumed
  326. and its integer value is returned by the function. If
  327. buflen is present, it specifies the maximum length of the
  328. buffer used to receive the option in, and this buffer is
  329. returned as a bytes object.
  330. @return: Either integer or bytes value of the option. It is up
  331. to the caller to decode the contents of the buffer (see
  332. the optional built-in module struct for a way to decode
  333. C structures encoded as byte strings).
  334. """
  335. return self.socket.getsockopt(level, optname, buflen)
  336. def setsockopt(self, level, optname, value=None):
  337. # type: (int, int, Union[int, bytes, None]) -> Optional[bytes]
  338. """Set the value of the given socket option.
  339. @param level: same as with getsockopt() above
  340. @param optname: same as with getsockopt() above
  341. @param value: an integer or a string representing a buffer. In
  342. the latter case it is up to the caller to ensure
  343. that the string contains the proper bits (see the
  344. optional built-in module struct for a way to
  345. encode C structures as strings).
  346. @return: None for success or the error handler for failure.
  347. """
  348. return self.socket.setsockopt(level, optname, value)
  349. def get_context(self):
  350. # type: () -> SSL.Context
  351. """Return the SSL.Context object associated with this connection."""
  352. return m2.ssl_get_ssl_ctx(self.ssl)
  353. def get_state(self):
  354. # type: () -> bytes
  355. """Return the SSL state of this connection.
  356. During its use, an SSL objects passes several states. The state
  357. is internally maintained. Querying the state information is not
  358. very informative before or when a connection has been
  359. established. It however can be of significant interest during
  360. the handshake.
  361. @return: 6 letter string indicating the current state of the SSL
  362. object ssl.
  363. """
  364. return m2.ssl_get_state(self.ssl)
  365. def verify_ok(self):
  366. # type: () -> bool
  367. return (m2.ssl_get_verify_result(self.ssl) == m2.X509_V_OK)
  368. def get_verify_mode(self):
  369. # type: () -> int
  370. """Return the peer certificate verification mode."""
  371. return m2.ssl_get_verify_mode(self.ssl)
  372. def get_verify_depth(self):
  373. # type: () -> int
  374. """Return the peer certificate verification depth."""
  375. return m2.ssl_get_verify_depth(self.ssl)
  376. def get_verify_result(self):
  377. # type: () -> int
  378. """Return the peer certificate verification result."""
  379. return m2.ssl_get_verify_result(self.ssl)
  380. def get_peer_cert(self):
  381. # type: () -> X509.X509
  382. """Return the peer certificate.
  383. If the peer did not provide a certificate, return None.
  384. """
  385. c = m2.ssl_get_peer_cert(self.ssl)
  386. if c is None:
  387. return None
  388. # Need to free the pointer coz OpenSSL doesn't.
  389. return X509.X509(c, 1)
  390. def get_peer_cert_chain(self):
  391. # type: () -> Optional[X509.X509_Stack]
  392. """Return the peer certificate chain; if the peer did not provide
  393. a certificate chain, return None.
  394. @warning: The returned chain will be valid only for as long as the
  395. connection object is alive. Once the connection object gets freed,
  396. the chain will be freed as well.
  397. """
  398. c = m2.ssl_get_peer_cert_chain(self.ssl)
  399. if c is None:
  400. return None
  401. # No need to free the pointer coz OpenSSL does.
  402. return X509.X509_Stack(c)
  403. def get_cipher(self):
  404. # type: () -> Optional[SSL.Cipher]
  405. """Return an M2Crypto.SSL.Cipher object for this connection; if the
  406. connection has not been initialised with a cipher suite, return None.
  407. """
  408. c = m2.ssl_get_current_cipher(self.ssl)
  409. if c is None:
  410. return None
  411. return Cipher(c)
  412. def get_ciphers(self):
  413. # type: () -> Optional[SSL:Cipher_Stack]
  414. """Return an M2Crypto.SSL.Cipher_Stack object for this
  415. connection; if the connection has not been initialised with
  416. cipher suites, return None.
  417. """
  418. c = m2.ssl_get_ciphers(self.ssl)
  419. if c is None:
  420. return None
  421. return Cipher_Stack(c)
  422. def get_cipher_list(self, idx=0):
  423. # type: (int) -> str
  424. """Return the cipher suites for this connection as a string object."""
  425. return m2.ssl_get_cipher_list(self.ssl, idx)
  426. def set_cipher_list(self, cipher_list):
  427. # type: (str) -> int
  428. """Set the cipher suites for this connection."""
  429. return m2.ssl_set_cipher_list(self.ssl, cipher_list)
  430. def makefile(self, mode='rb', bufsize=-1):
  431. # type: (AnyStr, int) -> socket._fileobject
  432. return socket._fileobject(self, mode, bufsize)
  433. def getsockname(self):
  434. # type: () -> util.AddrType
  435. """Return the socket's own address.
  436. This is useful to find out the port number of an IPv4/v6 socket,
  437. for instance. (The format of the address returned depends
  438. on the address family -- see above.)
  439. @return:socket's address as addr type
  440. """
  441. return self.socket.getsockname()
  442. def getpeername(self):
  443. # type: () -> util.AddrType
  444. """Return the remote address to which the socket is connected.
  445. This is useful to find out the port number of a remote IPv4/v6 socket,
  446. for instance.
  447. On some systems this function is not supported.
  448. @return:
  449. """
  450. return self.socket.getpeername()
  451. def set_session_id_ctx(self, id):
  452. # type: (bytes) -> int
  453. ret = m2.ssl_set_session_id_context(self.ssl, id)
  454. if not ret:
  455. raise SSLError(m2.err_reason_error_string(m2.err_get_error()))
  456. def get_session(self):
  457. # type: () -> SSL.Session
  458. sess = m2.ssl_get_session(self.ssl)
  459. return Session(sess)
  460. def set_session(self, session):
  461. # type: (SSL.Session) -> None
  462. m2.ssl_set_session(self.ssl, session._ptr())
  463. def get_default_session_timeout(self):
  464. # type: () -> int
  465. return m2.ssl_get_default_session_timeout(self.ssl)
  466. def get_socket_read_timeout(self):
  467. # type: () -> SSL.timeout
  468. return timeout.struct_to_timeout(
  469. self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO,
  470. timeout.struct_size()))
  471. def get_socket_write_timeout(self):
  472. # type: () -> SSL.timeout
  473. return timeout.struct_to_timeout(
  474. self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_SNDTIMEO,
  475. timeout.struct_size()))
  476. def set_socket_read_timeout(self, timeo):
  477. # type: (SSL.timeout) -> None
  478. assert isinstance(timeo, timeout.timeout)
  479. self.socket.setsockopt(
  480. socket.SOL_SOCKET, socket.SO_RCVTIMEO, timeo.pack())
  481. def set_socket_write_timeout(self, timeo):
  482. # type: (SSL.timeout) -> None
  483. assert isinstance(timeo, timeout.timeout)
  484. self.socket.setsockopt(
  485. socket.SOL_SOCKET, socket.SO_SNDTIMEO, timeo.pack())
  486. def get_version(self):
  487. # type: () -> str
  488. "Return the TLS/SSL protocol version for this connection."
  489. return m2.ssl_get_version(self.ssl)
  490. def set_post_connection_check_callback(self, postConnectionCheck): # noqa
  491. # type: (Callable) -> None
  492. self.postConnectionCheck = postConnectionCheck
  493. def set_tlsext_host_name(self, name):
  494. # type: (bytes) -> None
  495. """Set the requested hostname for the SNI (Server Name Indication)
  496. extension.
  497. """
  498. m2.ssl_set_tlsext_host_name(self.ssl, name)