PageRenderTime 29ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/module/_ssl/interp_ssl.py

https://bitbucket.org/pypy/pypy/
Python | 1789 lines | 1582 code | 116 blank | 91 comment | 172 complexity | a84fe082c5650c7027d865efe13e4241 MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0
  1. from rpython.rlib import rpoll, rsocket, rthread, rweakref, rgc
  2. from rpython.rlib.rarithmetic import intmask, widen, r_uint
  3. from rpython.rlib.ropenssl import *
  4. from pypy.module._socket import interp_socket
  5. from rpython.rlib._rsocket_rffi import MAX_FD_SIZE
  6. from rpython.rlib.rposix import get_saved_errno
  7. from rpython.rlib.rweakref import RWeakValueDictionary
  8. from rpython.rlib.objectmodel import specialize, compute_unique_id
  9. from rpython.rtyper.lltypesystem import lltype, rffi
  10. from pypy.interpreter.baseobjspace import W_Root
  11. from pypy.interpreter.error import OperationError, oefmt, wrap_oserror
  12. from pypy.interpreter.gateway import interp2app, unwrap_spec
  13. from pypy.interpreter.typedef import TypeDef, GetSetProperty
  14. from pypy.module._ssl.ssl_data import (
  15. LIBRARY_CODES_TO_NAMES, ERROR_CODES_TO_NAMES)
  16. # user defined constants
  17. X509_NAME_MAXLEN = 256
  18. # these mirror ssl.h
  19. PY_SSL_ERROR_NONE, PY_SSL_ERROR_SSL = 0, 1
  20. PY_SSL_ERROR_WANT_READ, PY_SSL_ERROR_WANT_WRITE = 2, 3
  21. PY_SSL_ERROR_WANT_X509_LOOKUP = 4
  22. PY_SSL_ERROR_SYSCALL = 5 # look at error stack/return value/errno
  23. PY_SSL_ERROR_ZERO_RETURN, PY_SSL_ERROR_WANT_CONNECT = 6, 7
  24. # start of non ssl.h errorcodes
  25. PY_SSL_ERROR_EOF = 8 # special case of SSL_ERROR_SYSCALL
  26. PY_SSL_ERROR_INVALID_ERROR_CODE = 9
  27. PY_SSL_CERT_NONE, PY_SSL_CERT_OPTIONAL, PY_SSL_CERT_REQUIRED = 0, 1, 2
  28. PY_SSL_CLIENT, PY_SSL_SERVER = 0, 1
  29. (PY_SSL_VERSION_SSL2, PY_SSL_VERSION_SSL3,
  30. PY_SSL_VERSION_SSL23, PY_SSL_VERSION_TLS1, PY_SSL_VERSION_TLS1_1,
  31. PY_SSL_VERSION_TLS1_2) = range(6)
  32. SOCKET_IS_NONBLOCKING, SOCKET_IS_BLOCKING = 0, 1
  33. SOCKET_HAS_TIMED_OUT, SOCKET_HAS_BEEN_CLOSED = 2, 3
  34. SOCKET_TOO_LARGE_FOR_SELECT, SOCKET_OPERATION_OK = 4, 5
  35. HAVE_RPOLL = 'poll' in dir(rpoll)
  36. constants = {}
  37. constants["SSL_ERROR_ZERO_RETURN"] = PY_SSL_ERROR_ZERO_RETURN
  38. constants["SSL_ERROR_WANT_READ"] = PY_SSL_ERROR_WANT_READ
  39. constants["SSL_ERROR_WANT_WRITE"] = PY_SSL_ERROR_WANT_WRITE
  40. constants["SSL_ERROR_WANT_X509_LOOKUP"] = PY_SSL_ERROR_WANT_X509_LOOKUP
  41. constants["SSL_ERROR_SYSCALL"] = PY_SSL_ERROR_SYSCALL
  42. constants["SSL_ERROR_SSL"] = PY_SSL_ERROR_SSL
  43. constants["SSL_ERROR_WANT_CONNECT"] = PY_SSL_ERROR_WANT_CONNECT
  44. constants["SSL_ERROR_EOF"] = PY_SSL_ERROR_EOF
  45. constants["SSL_ERROR_INVALID_ERROR_CODE"] = PY_SSL_ERROR_INVALID_ERROR_CODE
  46. constants["CERT_NONE"] = PY_SSL_CERT_NONE
  47. constants["CERT_OPTIONAL"] = PY_SSL_CERT_OPTIONAL
  48. constants["CERT_REQUIRED"] = PY_SSL_CERT_REQUIRED
  49. constants["VERIFY_DEFAULT"] = 0
  50. constants["VERIFY_CRL_CHECK_LEAF"] = X509_V_FLAG_CRL_CHECK
  51. constants["VERIFY_CRL_CHECK_CHAIN"] = X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL
  52. constants["VERIFY_X509_STRICT"] = X509_V_FLAG_X509_STRICT
  53. constants["HAS_SNI"] = HAS_SNI
  54. constants["HAS_TLS_UNIQUE"] = HAVE_OPENSSL_FINISHED
  55. constants["HAS_ECDH"] = not OPENSSL_NO_ECDH
  56. constants["HAS_NPN"] = HAS_NPN
  57. constants["HAS_ALPN"] = HAS_ALPN
  58. if not OPENSSL_NO_SSL2:
  59. constants["PROTOCOL_SSLv2"] = PY_SSL_VERSION_SSL2
  60. if not OPENSSL_NO_SSL3:
  61. constants["PROTOCOL_SSLv3"] = PY_SSL_VERSION_SSL3
  62. constants["PROTOCOL_SSLv23"] = PY_SSL_VERSION_SSL23
  63. constants["PROTOCOL_TLSv1"] = PY_SSL_VERSION_TLS1
  64. if HAVE_TLSv1_2:
  65. constants["PROTOCOL_TLSv1_1"] = PY_SSL_VERSION_TLS1_1
  66. constants["OP_NO_TLSv1_1"] = SSL_OP_NO_TLSv1_1
  67. constants["PROTOCOL_TLSv1_2"] = PY_SSL_VERSION_TLS1_2
  68. constants["OP_NO_TLSv1_2"] = SSL_OP_NO_TLSv1_2
  69. constants["OP_ALL"] = SSL_OP_ALL &~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
  70. constants["OP_NO_SSLv2"] = SSL_OP_NO_SSLv2
  71. constants["OP_NO_SSLv3"] = SSL_OP_NO_SSLv3
  72. constants["OP_NO_TLSv1"] = SSL_OP_NO_TLSv1
  73. constants["OP_CIPHER_SERVER_PREFERENCE"] = SSL_OP_CIPHER_SERVER_PREFERENCE
  74. constants["OP_SINGLE_DH_USE"] = SSL_OP_SINGLE_DH_USE
  75. constants["OP_SINGLE_ECDH_USE"] = SSL_OP_SINGLE_ECDH_USE
  76. if SSL_OP_NO_COMPRESSION is not None:
  77. constants["OP_NO_COMPRESSION"] = SSL_OP_NO_COMPRESSION
  78. constants["OPENSSL_VERSION_NUMBER"] = OPENSSL_VERSION_NUMBER
  79. ver = OPENSSL_VERSION_NUMBER
  80. ver, status = divmod(ver, 16)
  81. ver, patch = divmod(ver, 256)
  82. ver, fix = divmod(ver, 256)
  83. ver, minor = divmod(ver, 256)
  84. ver, major = divmod(ver, 256)
  85. version_info = (major, minor, fix, patch, status)
  86. constants["OPENSSL_VERSION_INFO"] = version_info
  87. constants["_OPENSSL_API_VERSION"] = version_info
  88. constants["OPENSSL_VERSION"] = SSLEAY_VERSION
  89. def ssl_error(space, msg, errno=0, w_errtype=None, errcode=0):
  90. reason_str = None
  91. lib_str = None
  92. if errcode:
  93. err_lib = libssl_ERR_GET_LIB(errcode)
  94. err_reason = libssl_ERR_GET_REASON(errcode)
  95. reason_str = ERROR_CODES_TO_NAMES.get((err_lib, err_reason), None)
  96. lib_str = LIBRARY_CODES_TO_NAMES.get(err_lib, None)
  97. msg = rffi.charp2str(libssl_ERR_reason_error_string(errcode))
  98. if not msg:
  99. msg = "unknown error"
  100. if reason_str and lib_str:
  101. msg = "[%s: %s] %s" % (lib_str, reason_str, msg)
  102. elif lib_str:
  103. msg = "[%s] %s" % (lib_str, msg)
  104. w_exception_class = w_errtype or get_exception_class(space, 'w_sslerror')
  105. if errno or errcode:
  106. w_exception = space.call_function(w_exception_class,
  107. space.wrap(errno), space.wrap(msg))
  108. else:
  109. w_exception = space.call_function(w_exception_class, space.wrap(msg))
  110. space.setattr(w_exception, space.wrap("reason"),
  111. space.wrap(reason_str) if reason_str else space.w_None)
  112. space.setattr(w_exception, space.wrap("library"),
  113. space.wrap(lib_str) if lib_str else space.w_None)
  114. return OperationError(w_exception_class, w_exception)
  115. class SSLNpnProtocols(object):
  116. def __init__(self, ctx, protos):
  117. self.protos = protos
  118. self.buf, self.bufflag = rffi.get_nonmovingbuffer(protos)
  119. NPN_STORAGE.set(rffi.cast(lltype.Unsigned, self.buf), self)
  120. # set both server and client callbacks, because the context
  121. # can be used to create both types of sockets
  122. libssl_SSL_CTX_set_next_protos_advertised_cb(
  123. ctx, self.advertiseNPN_cb, self.buf)
  124. libssl_SSL_CTX_set_next_proto_select_cb(
  125. ctx, self.selectNPN_cb, self.buf)
  126. def __del__(self):
  127. rffi.free_nonmovingbuffer(
  128. self.protos, self.buf, self.bufflag)
  129. @staticmethod
  130. def advertiseNPN_cb(s, data_ptr, len_ptr, args):
  131. npn = NPN_STORAGE.get(rffi.cast(lltype.Unsigned, args))
  132. if npn and npn.protos:
  133. data_ptr[0] = npn.buf
  134. len_ptr[0] = rffi.cast(rffi.UINT, len(npn.protos))
  135. else:
  136. data_ptr[0] = lltype.nullptr(rffi.CCHARP.TO)
  137. len_ptr[0] = rffi.cast(rffi.UINT, 0)
  138. return rffi.cast(rffi.INT, SSL_TLSEXT_ERR_OK)
  139. @staticmethod
  140. def selectNPN_cb(s, out_ptr, outlen_ptr, server, server_len, args):
  141. npn = NPN_STORAGE.get(rffi.cast(lltype.Unsigned, args))
  142. if npn and npn.protos:
  143. client = npn.buf
  144. client_len = len(npn.protos)
  145. else:
  146. client = lltype.nullptr(rffi.CCHARP.TO)
  147. client_len = 0
  148. libssl_SSL_select_next_proto(out_ptr, outlen_ptr,
  149. server, server_len,
  150. client, client_len)
  151. return rffi.cast(rffi.INT, SSL_TLSEXT_ERR_OK)
  152. class SSLAlpnProtocols(object):
  153. def __init__(self, ctx, protos):
  154. self.protos = protos
  155. self.buf, self.bufflag = rffi.get_nonmovingbuffer(protos)
  156. ALPN_STORAGE.set(rffi.cast(lltype.Unsigned, self.buf), self)
  157. with rffi.scoped_str2charp(protos) as protos_buf:
  158. if libssl_SSL_CTX_set_alpn_protos(
  159. ctx, rffi.cast(rffi.UCHARP, protos_buf), len(protos)):
  160. raise MemoryError
  161. libssl_SSL_CTX_set_alpn_select_cb(
  162. ctx, self.selectALPN_cb, self.buf)
  163. def __del__(self):
  164. rffi.free_nonmovingbuffer(
  165. self.protos, self.buf, self.bufflag)
  166. @staticmethod
  167. def selectALPN_cb(s, out_ptr, outlen_ptr, client, client_len, args):
  168. alpn = ALPN_STORAGE.get(rffi.cast(lltype.Unsigned, args))
  169. if alpn and alpn.protos:
  170. server = alpn.buf
  171. server_len = len(alpn.protos)
  172. else:
  173. server = lltype.nullptr(rffi.CCHARP.TO)
  174. server_len = 0
  175. ret = libssl_SSL_select_next_proto(out_ptr, outlen_ptr,
  176. server, server_len,
  177. client, client_len)
  178. if ret != OPENSSL_NPN_NEGOTIATED:
  179. return rffi.cast(rffi.INT, SSL_TLSEXT_ERR_NOACK)
  180. return rffi.cast(rffi.INT, SSL_TLSEXT_ERR_OK)
  181. NPN_STORAGE = RWeakValueDictionary(r_uint, SSLNpnProtocols)
  182. ALPN_STORAGE = RWeakValueDictionary(r_uint, SSLAlpnProtocols)
  183. SOCKET_STORAGE = RWeakValueDictionary(int, W_Root)
  184. if HAVE_OPENSSL_RAND:
  185. # helper routines for seeding the SSL PRNG
  186. @unwrap_spec(string=str, entropy=float)
  187. def RAND_add(space, string, entropy):
  188. """RAND_add(string, entropy)
  189. Mix string into the OpenSSL PRNG state. entropy (a float) is a lower
  190. bound on the entropy contained in string."""
  191. with rffi.scoped_nonmovingbuffer(string) as buf:
  192. libssl_RAND_add(buf, len(string), entropy)
  193. def RAND_status(space):
  194. """RAND_status() -> 0 or 1
  195. Returns 1 if the OpenSSL PRNG has been seeded with enough data
  196. and 0 if not. It is necessary to seed the PRNG with RAND_add()
  197. on some platforms before using the ssl() function."""
  198. res = libssl_RAND_status()
  199. return space.wrap(res)
  200. if HAVE_OPENSSL_RAND_EGD:
  201. @unwrap_spec(path=str)
  202. def RAND_egd(space, path):
  203. """RAND_egd(path) -> bytes
  204. Queries the entropy gather daemon (EGD) on socket path. Returns number
  205. of bytes read. Raises socket.sslerror if connection to EGD fails or
  206. if it does provide enough data to seed PRNG."""
  207. with rffi.scoped_str2charp(path) as socket_path:
  208. bytes = libssl_RAND_egd(socket_path)
  209. if bytes == -1:
  210. raise ssl_error(space,
  211. "EGD connection failed or EGD did not return "
  212. "enough data to seed the PRNG")
  213. return space.wrap(bytes)
  214. else:
  215. # Dummy func for platforms missing RAND_egd(). Most likely LibreSSL.
  216. @unwrap_spec(path=str)
  217. def RAND_egd(space, path):
  218. raise ssl_error(space, "RAND_egd unavailable")
  219. class _SSLSocket(W_Root):
  220. @staticmethod
  221. def descr_new(space, w_ctx, w_sock, socket_type,
  222. w_hostname=None, w_ssl_sock=None):
  223. self = _SSLSocket()
  224. self.space = space
  225. self.w_ctx = w_ctx
  226. self.peer_cert = lltype.nullptr(X509.TO)
  227. self.shutdown_seen_zero = False
  228. self.handshake_done = False
  229. sock_fd = space.int_w(space.call_method(w_sock, "fileno"))
  230. self.ssl = libssl_SSL_new(w_ctx.ctx) # new ssl struct
  231. self.register_finalizer(space)
  232. index = compute_unique_id(self)
  233. libssl_SSL_set_app_data(self.ssl, rffi.cast(rffi.VOIDP, index))
  234. SOCKET_STORAGE.set(index, self)
  235. libssl_SSL_set_fd(self.ssl, sock_fd) # set the socket for SSL
  236. # The ACCEPT_MOVING_WRITE_BUFFER flag is necessary because the address
  237. # of a str object may be changed by the garbage collector.
  238. libssl_SSL_set_mode(
  239. self.ssl, SSL_MODE_AUTO_RETRY | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
  240. if not space.is_none(w_hostname):
  241. if space.isinstance_w(w_hostname, space.w_unicode):
  242. w_hostname = space.call_method(w_hostname, "encode",
  243. space.wrap("idna"))
  244. libssl_SSL_set_tlsext_host_name(
  245. self.ssl, space.bytes_w(w_hostname))
  246. # If the socket is in non-blocking mode or timeout mode, set the BIO
  247. # to non-blocking mode (blocking is the default)
  248. w_timeout = space.call_method(w_sock, "gettimeout")
  249. has_timeout = not space.is_none(w_timeout)
  250. if has_timeout:
  251. # Set both the read and write BIO's to non-blocking mode
  252. libssl_BIO_set_nbio(libssl_SSL_get_rbio(self.ssl), 1)
  253. libssl_BIO_set_nbio(libssl_SSL_get_wbio(self.ssl), 1)
  254. if socket_type == PY_SSL_CLIENT:
  255. libssl_SSL_set_connect_state(self.ssl)
  256. else:
  257. libssl_SSL_set_accept_state(self.ssl)
  258. self.socket_type = socket_type
  259. self.w_socket = w_sock
  260. if w_ssl_sock:
  261. self.ssl_sock_weakref_w = rweakref.ref(w_ssl_sock)
  262. else:
  263. self.ssl_sock_weakref_w = None
  264. return self
  265. def _finalize_(self):
  266. peer_cert = self.peer_cert
  267. if peer_cert:
  268. self.peer_cert = lltype.nullptr(X509.TO)
  269. libssl_X509_free(peer_cert)
  270. ssl = self.ssl
  271. if ssl:
  272. self.ssl = lltype.nullptr(SSL.TO)
  273. libssl_SSL_free(ssl)
  274. @unwrap_spec(data='bufferstr')
  275. def write(self, space, data):
  276. """write(s) -> len
  277. Writes the string s into the SSL object. Returns the number
  278. of bytes written."""
  279. self._refresh_nonblocking(space)
  280. sockstate = checkwait(space, self.w_socket, True)
  281. if sockstate == SOCKET_HAS_TIMED_OUT:
  282. raise ssl_error(space, "The write operation timed out")
  283. elif sockstate == SOCKET_HAS_BEEN_CLOSED:
  284. raise ssl_error(space, "Underlying socket has been closed.")
  285. elif sockstate == SOCKET_TOO_LARGE_FOR_SELECT:
  286. raise ssl_error(space, "Underlying socket too large for select().")
  287. num_bytes = 0
  288. while True:
  289. err = 0
  290. num_bytes = libssl_SSL_write(self.ssl, data, len(data))
  291. err = libssl_SSL_get_error(self.ssl, num_bytes)
  292. if err == SSL_ERROR_WANT_READ:
  293. sockstate = checkwait(space, self.w_socket, False)
  294. elif err == SSL_ERROR_WANT_WRITE:
  295. sockstate = checkwait(space, self.w_socket, True)
  296. else:
  297. sockstate = SOCKET_OPERATION_OK
  298. if sockstate == SOCKET_HAS_TIMED_OUT:
  299. raise ssl_error(space, "The write operation timed out")
  300. elif sockstate == SOCKET_HAS_BEEN_CLOSED:
  301. raise ssl_error(space, "Underlying socket has been closed.")
  302. elif sockstate == SOCKET_IS_NONBLOCKING:
  303. break
  304. if err == SSL_ERROR_WANT_READ or err == SSL_ERROR_WANT_WRITE:
  305. continue
  306. else:
  307. break
  308. if num_bytes > 0:
  309. return space.wrap(num_bytes)
  310. else:
  311. raise _ssl_seterror(space, self, num_bytes)
  312. def pending(self, space):
  313. """pending() -> count
  314. Returns the number of already decrypted bytes available for read,
  315. pending on the connection."""
  316. count = libssl_SSL_pending(self.ssl)
  317. if count < 0:
  318. raise _ssl_seterror(space, self, count)
  319. return space.wrap(count)
  320. @unwrap_spec(num_bytes=int)
  321. def read(self, space, num_bytes, w_buffer=None):
  322. """read([len]) -> string
  323. Read up to len bytes from the SSL socket."""
  324. count = libssl_SSL_pending(self.ssl)
  325. if not count:
  326. sockstate = checkwait(space, self.w_socket, False)
  327. if sockstate == SOCKET_HAS_TIMED_OUT:
  328. raise ssl_error(space, "The read operation timed out")
  329. elif sockstate == SOCKET_TOO_LARGE_FOR_SELECT:
  330. raise ssl_error(space,
  331. "Underlying socket too large for select().")
  332. elif sockstate == SOCKET_HAS_BEEN_CLOSED:
  333. if libssl_SSL_get_shutdown(self.ssl) == SSL_RECEIVED_SHUTDOWN:
  334. return space.wrap('')
  335. raise ssl_error(space,
  336. "Socket closed without SSL shutdown handshake")
  337. if w_buffer:
  338. rwbuffer = space.getarg_w('w*', w_buffer)
  339. num_bytes = min(num_bytes, rwbuffer.getlength())
  340. else:
  341. rwbuffer = None
  342. with rffi.scoped_alloc_buffer(num_bytes) as buf:
  343. while True:
  344. err = 0
  345. count = libssl_SSL_read(self.ssl, buf.raw, num_bytes)
  346. err = libssl_SSL_get_error(self.ssl, count)
  347. if err == SSL_ERROR_WANT_READ:
  348. sockstate = checkwait(space, self.w_socket, False)
  349. elif err == SSL_ERROR_WANT_WRITE:
  350. sockstate = checkwait(space, self.w_socket, True)
  351. elif (err == SSL_ERROR_ZERO_RETURN and
  352. libssl_SSL_get_shutdown(self.ssl) == SSL_RECEIVED_SHUTDOWN):
  353. if rwbuffer:
  354. return space.wrap(0)
  355. else:
  356. return space.wrap("")
  357. else:
  358. sockstate = SOCKET_OPERATION_OK
  359. if sockstate == SOCKET_HAS_TIMED_OUT:
  360. raise ssl_error(space, "The read operation timed out")
  361. elif sockstate == SOCKET_IS_NONBLOCKING:
  362. break
  363. if err == SSL_ERROR_WANT_READ or err == SSL_ERROR_WANT_WRITE:
  364. continue
  365. else:
  366. break
  367. if count <= 0:
  368. raise _ssl_seterror(space, self, count)
  369. result = buf.str(count)
  370. if rwbuffer:
  371. rwbuffer.setslice(0, result)
  372. return space.wrap(count)
  373. else:
  374. return space.wrap(result)
  375. def _refresh_nonblocking(self, space):
  376. # just in case the blocking state of the socket has been changed
  377. w_timeout = space.call_method(self.w_socket, "gettimeout")
  378. nonblocking = not space.is_w(w_timeout, space.w_None)
  379. libssl_BIO_set_nbio(libssl_SSL_get_rbio(self.ssl), nonblocking)
  380. libssl_BIO_set_nbio(libssl_SSL_get_wbio(self.ssl), nonblocking)
  381. def do_handshake(self, space):
  382. self._refresh_nonblocking(space)
  383. # Actually negotiate SSL connection
  384. # XXX If SSL_do_handshake() returns 0, it's also a failure.
  385. while True:
  386. ret = libssl_SSL_do_handshake(self.ssl)
  387. err = libssl_SSL_get_error(self.ssl, ret)
  388. # XXX PyErr_CheckSignals()
  389. if err == SSL_ERROR_WANT_READ:
  390. sockstate = checkwait(space, self.w_socket, False)
  391. elif err == SSL_ERROR_WANT_WRITE:
  392. sockstate = checkwait(space, self.w_socket, True)
  393. else:
  394. sockstate = SOCKET_OPERATION_OK
  395. if sockstate == SOCKET_HAS_TIMED_OUT:
  396. raise ssl_error(space, "The handshake operation timed out")
  397. elif sockstate == SOCKET_HAS_BEEN_CLOSED:
  398. raise ssl_error(space, "Underlying socket has been closed.")
  399. elif sockstate == SOCKET_TOO_LARGE_FOR_SELECT:
  400. raise ssl_error(space,
  401. "Underlying socket too large for select().")
  402. elif sockstate == SOCKET_IS_NONBLOCKING:
  403. break
  404. if err == SSL_ERROR_WANT_READ or err == SSL_ERROR_WANT_WRITE:
  405. continue
  406. else:
  407. break
  408. if ret <= 0:
  409. raise _ssl_seterror(space, self, ret)
  410. if self.peer_cert:
  411. libssl_X509_free(self.peer_cert)
  412. self.peer_cert = libssl_SSL_get_peer_certificate(self.ssl)
  413. self.handshake_done = True
  414. def shutdown(self, space):
  415. # Guard against closed socket
  416. w_fileno = space.call_method(self.w_socket, "fileno")
  417. if space.int_w(w_fileno) < 0:
  418. raise ssl_error(space, "Underlying socket has been closed")
  419. self._refresh_nonblocking(space)
  420. zeros = 0
  421. while True:
  422. # Disable read-ahead so that unwrap can work correctly.
  423. # Otherwise OpenSSL might read in too much data,
  424. # eating clear text data that happens to be
  425. # transmitted after the SSL shutdown.
  426. # Should be safe to call repeatedly everytime this
  427. # function is used and the shutdown_seen_zero != 0
  428. # condition is met.
  429. if self.shutdown_seen_zero:
  430. libssl_SSL_set_read_ahead(self.ssl, 0)
  431. ret = libssl_SSL_shutdown(self.ssl)
  432. # if err == 1, a secure shutdown with SSL_shutdown() is complete
  433. if ret > 0:
  434. break
  435. if ret == 0:
  436. # Don't loop endlessly; instead preserve legacy
  437. # behaviour of trying SSL_shutdown() only twice.
  438. # This looks necessary for OpenSSL < 0.9.8m
  439. zeros += 1
  440. if zeros > 1:
  441. break
  442. # Shutdown was sent, now try receiving
  443. self.shutdown_seen_zero = True
  444. continue
  445. # Possibly retry shutdown until timeout or failure
  446. ssl_err = libssl_SSL_get_error(self.ssl, ret)
  447. if ssl_err == SSL_ERROR_WANT_READ:
  448. sockstate = checkwait(space, self.w_socket, False)
  449. elif ssl_err == SSL_ERROR_WANT_WRITE:
  450. sockstate = checkwait(space, self.w_socket, True)
  451. else:
  452. break
  453. if sockstate == SOCKET_HAS_TIMED_OUT:
  454. if ssl_err == SSL_ERROR_WANT_READ:
  455. raise ssl_error(space, "The read operation timed out")
  456. else:
  457. raise ssl_error(space, "The write operation timed out")
  458. elif sockstate == SOCKET_TOO_LARGE_FOR_SELECT:
  459. raise ssl_error(space,
  460. "Underlying socket too large for select().")
  461. elif sockstate != SOCKET_OPERATION_OK:
  462. # Retain the SSL error code
  463. break
  464. if ret < 0:
  465. raise _ssl_seterror(space, self, ret)
  466. return self.w_socket
  467. def cipher(self, space):
  468. if not self.ssl:
  469. return space.w_None
  470. current = libssl_SSL_get_current_cipher(self.ssl)
  471. if not current:
  472. return space.w_None
  473. name = libssl_SSL_CIPHER_get_name(current)
  474. w_name = space.wrap(rffi.charp2str(name)) if name else space.w_None
  475. proto = libssl_SSL_CIPHER_get_version(current)
  476. w_proto = space.wrap(rffi.charp2str(proto)) if proto else space.w_None
  477. bits = libssl_SSL_CIPHER_get_bits(current,
  478. lltype.nullptr(rffi.INTP.TO))
  479. w_bits = space.newint(bits)
  480. return space.newtuple([w_name, w_proto, w_bits])
  481. @unwrap_spec(der=bool)
  482. def peer_certificate(self, space, der=False):
  483. """peer_certificate([der=False]) -> certificate
  484. Returns the certificate for the peer. If no certificate was
  485. provided, returns None. If a certificate was provided, but not
  486. validated, returns an empty dictionary. Otherwise returns a
  487. dict containing information about the peer certificate.
  488. If the optional argument is True, returns a DER-encoded copy of
  489. the peer certificate, or None if no certificate was provided.
  490. This will return the certificate even if it wasn't validated.
  491. """
  492. if not self.handshake_done:
  493. raise oefmt(space.w_ValueError, "hanshake not done yet")
  494. if not self.peer_cert:
  495. return space.w_None
  496. if der:
  497. # return cert in DER-encoded format
  498. return _certificate_to_der(space, self.peer_cert)
  499. else:
  500. verification = libssl_SSL_CTX_get_verify_mode(
  501. libssl_SSL_get_SSL_CTX(self.ssl))
  502. if not verification & SSL_VERIFY_PEER:
  503. return space.newdict()
  504. else:
  505. return _decode_certificate(space, self.peer_cert)
  506. def selected_npn_protocol(self, space):
  507. if not HAS_NPN:
  508. raise oefmt(space.w_NotImplementedError,
  509. "The NPN extension requires OpenSSL 1.0.1 or later.")
  510. with lltype.scoped_alloc(rffi.CCHARPP.TO, 1) as out_ptr:
  511. with lltype.scoped_alloc(rffi.UINTP.TO, 1) as len_ptr:
  512. libssl_SSL_get0_next_proto_negotiated(self.ssl,
  513. out_ptr, len_ptr)
  514. if out_ptr[0]:
  515. return space.wrap(
  516. rffi.charpsize2str(out_ptr[0], intmask(len_ptr[0])))
  517. def selected_alpn_protocol(self, space):
  518. if not HAS_ALPN:
  519. raise oefmt(space.w_NotImplementedError,
  520. "The ALPN extension requires OpenSSL 1.0.2 or later.")
  521. with lltype.scoped_alloc(rffi.CCHARPP.TO, 1) as out_ptr:
  522. with lltype.scoped_alloc(rffi.UINTP.TO, 1) as len_ptr:
  523. libssl_SSL_get0_alpn_selected(self.ssl,
  524. out_ptr, len_ptr)
  525. if out_ptr[0]:
  526. return space.wrap(
  527. rffi.charpsize2str(out_ptr[0], intmask(len_ptr[0])))
  528. def compression_w(self, space):
  529. if not self.ssl:
  530. return space.w_None
  531. comp_method = libssl_SSL_get_current_compression(self.ssl)
  532. if not comp_method or intmask(comp_method[0].c_type) == NID_undef:
  533. return space.w_None
  534. short_name = libssl_OBJ_nid2sn(comp_method[0].c_type)
  535. if not short_name:
  536. return space.w_None
  537. return space.wrap(rffi.charp2str(short_name))
  538. def version_w(self, space):
  539. if not self.ssl:
  540. return space.w_None
  541. version = libssl_SSL_get_version(self.ssl)
  542. if not version:
  543. return space.w_None
  544. return space.wrap(rffi.charp2str(version))
  545. def tls_unique_cb_w(self, space):
  546. """Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
  547. If the TLS handshake is not yet complete, None is returned"""
  548. # In case of 'tls-unique' it will be 12 bytes for TLS, 36
  549. # bytes for older SSL, but let's be safe
  550. CB_MAXLEN = 128
  551. with lltype.scoped_alloc(rffi.CCHARP.TO, CB_MAXLEN) as buf:
  552. if (libssl_SSL_session_reused(self.ssl) ^
  553. (self.socket_type == PY_SSL_CLIENT)):
  554. # if session is resumed XOR we are the client
  555. length = libssl_SSL_get_finished(self.ssl, buf, CB_MAXLEN)
  556. else:
  557. # if a new session XOR we are the server
  558. length = libssl_SSL_get_peer_finished(self.ssl, buf, CB_MAXLEN)
  559. if length > 0:
  560. return space.newbytes(rffi.charpsize2str(buf, intmask(length)))
  561. def descr_get_context(self, space):
  562. return self.w_ctx
  563. def descr_set_context(self, space, w_ctx):
  564. ctx = space.interp_w(_SSLContext, w_ctx)
  565. if not HAS_SNI:
  566. raise oefmt(space.w_NotImplementedError,
  567. "setting a socket's context "
  568. "is not supported by your OpenSSL library")
  569. self.w_ctx = w_ctx
  570. libssl_SSL_set_SSL_CTX(self.ssl, ctx.ctx)
  571. _SSLSocket.typedef = TypeDef(
  572. "_ssl._SSLSocket",
  573. do_handshake=interp2app(_SSLSocket.do_handshake),
  574. write=interp2app(_SSLSocket.write),
  575. read=interp2app(_SSLSocket.read),
  576. pending=interp2app(_SSLSocket.pending),
  577. peer_certificate=interp2app(_SSLSocket.peer_certificate),
  578. cipher=interp2app(_SSLSocket.cipher),
  579. shutdown=interp2app(_SSLSocket.shutdown),
  580. selected_npn_protocol = interp2app(_SSLSocket.selected_npn_protocol),
  581. selected_alpn_protocol = interp2app(_SSLSocket.selected_alpn_protocol),
  582. compression = interp2app(_SSLSocket.compression_w),
  583. version = interp2app(_SSLSocket.version_w),
  584. tls_unique_cb = interp2app(_SSLSocket.tls_unique_cb_w),
  585. context=GetSetProperty(_SSLSocket.descr_get_context,
  586. _SSLSocket.descr_set_context),
  587. )
  588. def _certificate_to_der(space, certificate):
  589. with lltype.scoped_alloc(rffi.CCHARPP.TO, 1) as buf_ptr:
  590. buf_ptr[0] = lltype.nullptr(rffi.CCHARP.TO)
  591. length = libssl_i2d_X509(certificate, buf_ptr)
  592. if length < 0:
  593. raise _ssl_seterror(space, None, 0)
  594. try:
  595. return space.newbytes(rffi.charpsize2str(buf_ptr[0], length))
  596. finally:
  597. libssl_OPENSSL_free(buf_ptr[0])
  598. def _decode_certificate(space, certificate):
  599. w_retval = space.newdict()
  600. w_peer = _create_tuple_for_X509_NAME(
  601. space, libssl_X509_get_subject_name(certificate))
  602. space.setitem(w_retval, space.wrap("subject"), w_peer)
  603. w_issuer = _create_tuple_for_X509_NAME(
  604. space, libssl_X509_get_issuer_name(certificate))
  605. space.setitem(w_retval, space.wrap("issuer"), w_issuer)
  606. space.setitem(w_retval, space.wrap("version"),
  607. space.wrap(libssl_X509_get_version(certificate) + 1))
  608. biobuf = libssl_BIO_new(libssl_BIO_s_mem())
  609. try:
  610. libssl_BIO_reset(biobuf)
  611. serialNumber = libssl_X509_get_serialNumber(certificate)
  612. libssl_i2a_ASN1_INTEGER(biobuf, serialNumber)
  613. # should not exceed 20 octets, 160 bits, so buf is big enough
  614. with lltype.scoped_alloc(rffi.CCHARP.TO, 100) as buf:
  615. length = libssl_BIO_gets(biobuf, buf, 99)
  616. if length < 0:
  617. raise _ssl_seterror(space, None, length)
  618. w_serial = space.wrap(rffi.charpsize2str(buf, length))
  619. space.setitem(w_retval, space.wrap("serialNumber"), w_serial)
  620. libssl_BIO_reset(biobuf)
  621. notBefore = libssl_X509_get_notBefore(certificate)
  622. libssl_ASN1_TIME_print(biobuf, notBefore)
  623. with lltype.scoped_alloc(rffi.CCHARP.TO, 100) as buf:
  624. length = libssl_BIO_gets(biobuf, buf, 99)
  625. if length < 0:
  626. raise _ssl_seterror(space, None, length)
  627. w_date = space.wrap(rffi.charpsize2str(buf, length))
  628. space.setitem(w_retval, space.wrap("notBefore"), w_date)
  629. libssl_BIO_reset(biobuf)
  630. notAfter = libssl_X509_get_notAfter(certificate)
  631. libssl_ASN1_TIME_print(biobuf, notAfter)
  632. with lltype.scoped_alloc(rffi.CCHARP.TO, 100) as buf:
  633. length = libssl_BIO_gets(biobuf, buf, 99)
  634. if length < 0:
  635. raise _ssl_seterror(space, None, length)
  636. w_date = space.wrap(rffi.charpsize2str(buf, length))
  637. space.setitem(w_retval, space.wrap("notAfter"), w_date)
  638. finally:
  639. libssl_BIO_free(biobuf)
  640. # Now look for subjectAltName
  641. w_alt_names = _get_peer_alt_names(space, certificate)
  642. if w_alt_names is not space.w_None:
  643. space.setitem(w_retval, space.wrap("subjectAltName"), w_alt_names)
  644. # Authority Information Access: OCSP URIs
  645. w_ocsp = _get_aia_uri(space, certificate, NID_ad_OCSP)
  646. if not space.is_none(w_ocsp):
  647. space.setitem(w_retval, space.wrap("OCSP"), w_ocsp)
  648. w_issuers = _get_aia_uri(space, certificate, NID_ad_ca_issuers)
  649. if not space.is_none(w_issuers):
  650. space.setitem(w_retval, space.wrap("caIssuers"), w_issuers)
  651. # CDP (CRL distribution points)
  652. w_cdp = _get_crl_dp(space, certificate)
  653. if not space.is_none(w_cdp):
  654. space.setitem(w_retval, space.wrap("crlDistributionPoints"), w_cdp)
  655. return w_retval
  656. def _create_tuple_for_X509_NAME(space, xname):
  657. entry_count = libssl_X509_NAME_entry_count(xname)
  658. dn_w = []
  659. rdn_w = []
  660. rdn_level = -1
  661. for index in range(entry_count):
  662. entry = libssl_X509_NAME_get_entry(xname, index)
  663. # check to see if we've gotten to a new RDN
  664. entry_level = intmask(entry[0].c_set)
  665. if rdn_level >= 0:
  666. if rdn_level != entry_level:
  667. # yes, new RDN
  668. # add old RDN to DN
  669. dn_w.append(space.newtuple(list(rdn_w)))
  670. rdn_w = []
  671. rdn_level = entry_level
  672. # Now add this attribute to the current RDN
  673. name = libssl_X509_NAME_ENTRY_get_object(entry)
  674. value = libssl_X509_NAME_ENTRY_get_data(entry)
  675. attr = _create_tuple_for_attribute(space, name, value)
  676. rdn_w.append(attr)
  677. # Now, there is typically a dangling RDN
  678. if rdn_w:
  679. dn_w.append(space.newtuple(list(rdn_w)))
  680. return space.newtuple(list(dn_w))
  681. def _get_peer_alt_names(space, certificate):
  682. # this code follows the procedure outlined in
  683. # OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
  684. # function to extract the STACK_OF(GENERAL_NAME),
  685. # then iterates through the stack to add the
  686. # names.
  687. if not certificate:
  688. return space.w_None
  689. # get a memory buffer
  690. biobuf = libssl_BIO_new(libssl_BIO_s_mem())
  691. try:
  692. alt_names_w = []
  693. i = -1
  694. while True:
  695. i = libssl_X509_get_ext_by_NID(
  696. certificate, NID_subject_alt_name, i)
  697. if i < 0:
  698. break
  699. # now decode the altName
  700. ext = libssl_X509_get_ext(certificate, i)
  701. method = libssl_X509V3_EXT_get(ext)
  702. if not method:
  703. raise ssl_error(space,
  704. "No method for internalizing subjectAltName!'")
  705. with lltype.scoped_alloc(rffi.CCHARPP.TO, 1) as p_ptr:
  706. p_ptr[0] = ext[0].c_value.c_data
  707. length = intmask(ext[0].c_value.c_length)
  708. null = lltype.nullptr(rffi.VOIDP.TO)
  709. if method[0].c_it:
  710. names = rffi.cast(GENERAL_NAMES, libssl_ASN1_item_d2i(
  711. null, p_ptr, length,
  712. libssl_ASN1_ITEM_ptr(method[0].c_it)))
  713. else:
  714. names = rffi.cast(GENERAL_NAMES, method[0].c_d2i(
  715. null, p_ptr, length))
  716. try:
  717. for j in range(libssl_sk_GENERAL_NAME_num(names)):
  718. # Get a rendering of each name in the set of names
  719. name = libssl_sk_GENERAL_NAME_value(names, j)
  720. gntype = intmask(name.c_type)
  721. if gntype == GEN_DIRNAME:
  722. # we special-case DirName as a tuple of tuples of
  723. # attributes
  724. dirname = libssl_pypy_GENERAL_NAME_dirn(name)
  725. w_t = space.newtuple([
  726. space.wrap("DirName"),
  727. _create_tuple_for_X509_NAME(space, dirname)
  728. ])
  729. elif gntype in (GEN_EMAIL, GEN_DNS, GEN_URI):
  730. # GENERAL_NAME_print() doesn't handle NULL bytes in
  731. # ASN1_string correctly, CVE-2013-4238
  732. if gntype == GEN_EMAIL:
  733. v = space.wrap("email")
  734. elif gntype == GEN_DNS:
  735. v = space.wrap("DNS")
  736. elif gntype == GEN_URI:
  737. v = space.wrap("URI")
  738. else:
  739. assert False
  740. as_ = libssl_pypy_GENERAL_NAME_dirn(name)
  741. as_ = rffi.cast(ASN1_STRING, as_)
  742. buf = libssl_ASN1_STRING_data(as_)
  743. length = libssl_ASN1_STRING_length(as_)
  744. w_t = space.newtuple([
  745. v, space.wrap(rffi.charpsize2str(buf, length))])
  746. else:
  747. # for everything else, we use the OpenSSL print form
  748. if gntype not in (GEN_OTHERNAME, GEN_X400, GEN_EDIPARTY,
  749. GEN_IPADD, GEN_RID):
  750. space.warn(space.wrap("Unknown general name type"),
  751. space.w_RuntimeWarning)
  752. libssl_BIO_reset(biobuf)
  753. libssl_GENERAL_NAME_print(biobuf, name)
  754. with lltype.scoped_alloc(rffi.CCHARP.TO, 2048) as buf:
  755. length = libssl_BIO_gets(biobuf, buf, 2047)
  756. if length < 0:
  757. raise _ssl_seterror(space, None, 0)
  758. v = rffi.charpsize2str(buf, length)
  759. v1, v2 = v.split(':', 1)
  760. w_t = space.newtuple([space.wrap(v1),
  761. space.wrap(v2)])
  762. alt_names_w.append(w_t)
  763. finally:
  764. libssl_pypy_GENERAL_NAME_pop_free(names)
  765. finally:
  766. libssl_BIO_free(biobuf)
  767. if alt_names_w:
  768. return space.newtuple(list(alt_names_w))
  769. else:
  770. return space.w_None
  771. def _create_tuple_for_attribute(space, name, value):
  772. with lltype.scoped_alloc(rffi.CCHARP.TO, X509_NAME_MAXLEN) as buf:
  773. length = libssl_OBJ_obj2txt(buf, X509_NAME_MAXLEN, name, 0)
  774. if length < 0:
  775. raise _ssl_seterror(space, None, 0)
  776. w_name = space.wrap(rffi.charpsize2str(buf, length))
  777. with lltype.scoped_alloc(rffi.CCHARPP.TO, 1) as buf_ptr:
  778. length = libssl_ASN1_STRING_to_UTF8(buf_ptr, value)
  779. if length < 0:
  780. raise _ssl_seterror(space, None, 0)
  781. try:
  782. w_value = space.newbytes(rffi.charpsize2str(buf_ptr[0], length))
  783. w_value = space.call_method(w_value, "decode", space.wrap("utf-8"))
  784. finally:
  785. libssl_OPENSSL_free(buf_ptr[0])
  786. return space.newtuple([w_name, w_value])
  787. def _get_aia_uri(space, certificate, nid):
  788. info = rffi.cast(AUTHORITY_INFO_ACCESS, libssl_X509_get_ext_d2i(
  789. certificate, NID_info_access, None, None))
  790. try:
  791. if not info or libssl_sk_ACCESS_DESCRIPTION_num(info) == 0:
  792. return
  793. result_w = []
  794. for i in range(libssl_sk_ACCESS_DESCRIPTION_num(info)):
  795. ad = libssl_sk_ACCESS_DESCRIPTION_value(info, i)
  796. if libssl_OBJ_obj2nid(ad[0].c_method) != nid:
  797. continue
  798. name = ad[0].c_location
  799. gntype = intmask(name.c_type)
  800. if gntype != GEN_URI:
  801. continue
  802. uri = libssl_pypy_GENERAL_NAME_uri(name)
  803. length = intmask(uri.c_length)
  804. s_uri = rffi.charpsize2str(uri.c_data, length)
  805. result_w.append(space.wrap(s_uri))
  806. return space.newtuple(result_w[:])
  807. finally:
  808. libssl_AUTHORITY_INFO_ACCESS_free(info)
  809. def _get_crl_dp(space, certificate):
  810. if OPENSSL_VERSION_NUMBER >= 0x10001000:
  811. # Calls x509v3_cache_extensions and sets up crldp
  812. libssl_X509_check_ca(certificate)
  813. dps = certificate[0].c_crldp
  814. else:
  815. dps = rffi.cast(stack_st_DIST_POINT, libssl_X509_get_ext_d2i(
  816. certificate, NID_crl_distribution_points, None, None))
  817. if not dps:
  818. return None
  819. try:
  820. cdp_w = []
  821. for i in range(libssl_sk_DIST_POINT_num(dps)):
  822. dp = libssl_sk_DIST_POINT_value(dps, i)
  823. gns = libssl_pypy_DIST_POINT_fullname(dp)
  824. for j in range(libssl_sk_GENERAL_NAME_num(gns)):
  825. name = libssl_sk_GENERAL_NAME_value(gns, j)
  826. gntype = intmask(name.c_type)
  827. if gntype != GEN_URI:
  828. continue
  829. uri = libssl_pypy_GENERAL_NAME_uri(name)
  830. length = intmask(uri.c_length)
  831. s_uri = rffi.charpsize2str(uri.c_data, length)
  832. cdp_w.append(space.wrap(s_uri))
  833. finally:
  834. if OPENSSL_VERSION_NUMBER < 0x10001000:
  835. libssl_sk_DIST_POINT_free(dps)
  836. return space.newtuple(cdp_w[:])
  837. def checkwait(space, w_sock, writing):
  838. """If the socket has a timeout, do a select()/poll() on the socket.
  839. The argument writing indicates the direction.
  840. Returns one of the possibilities in the timeout_state enum (above)."""
  841. w_timeout = space.call_method(w_sock, "gettimeout")
  842. if space.is_w(w_timeout, space.w_None):
  843. return SOCKET_IS_BLOCKING
  844. elif space.float_w(w_timeout) == 0.0:
  845. return SOCKET_IS_NONBLOCKING
  846. sock_timeout = space.float_w(w_timeout)
  847. sock_fd = space.int_w(space.call_method(w_sock, "fileno"))
  848. # guard against closed socket
  849. if sock_fd < 0:
  850. return SOCKET_HAS_BEEN_CLOSED
  851. # see if the socket is ready
  852. # Prefer poll, if available, since you can poll() any fd
  853. # which can't be done with select().
  854. if HAVE_RPOLL:
  855. if writing:
  856. fddict = {sock_fd: rpoll.POLLOUT}
  857. else:
  858. fddict = {sock_fd: rpoll.POLLIN}
  859. # socket's timeout is in seconds, poll's timeout in ms
  860. timeout = int(sock_timeout * 1000 + 0.5)
  861. try:
  862. ready = rpoll.poll(fddict, timeout)
  863. except rpoll.PollError as e:
  864. message = e.get_msg()
  865. raise ssl_error(space, message, e.errno)
  866. else:
  867. if MAX_FD_SIZE is not None and sock_fd >= MAX_FD_SIZE:
  868. return SOCKET_TOO_LARGE_FOR_SELECT
  869. try:
  870. if writing:
  871. r, w, e = rpoll.select([], [sock_fd], [], sock_timeout)
  872. ready = w
  873. else:
  874. r, w, e = rpoll.select([sock_fd], [], [], sock_timeout)
  875. ready = r
  876. except rpoll.SelectError as e:
  877. message = e.get_msg()
  878. raise ssl_error(space, message, e.errno)
  879. if ready:
  880. return SOCKET_OPERATION_OK
  881. else:
  882. return SOCKET_HAS_TIMED_OUT
  883. def _ssl_seterror(space, ss, ret):
  884. assert ret <= 0
  885. errcode = libssl_ERR_peek_last_error()
  886. if ss is None:
  887. return ssl_error(space, None, errcode=errcode)
  888. elif ss.ssl:
  889. err = libssl_SSL_get_error(ss.ssl, ret)
  890. else:
  891. err = SSL_ERROR_SSL
  892. w_errtype = None
  893. errstr = ""
  894. errval = 0
  895. if err == SSL_ERROR_ZERO_RETURN:
  896. w_errtype = get_exception_class(space, 'w_sslzeroreturnerror')
  897. errstr = "TLS/SSL connection has been closed"
  898. errval = PY_SSL_ERROR_ZERO_RETURN
  899. elif err == SSL_ERROR_WANT_READ:
  900. w_errtype = get_exception_class(space, 'w_sslwantreaderror')
  901. errstr = "The operation did not complete (read)"
  902. errval = PY_SSL_ERROR_WANT_READ
  903. elif err == SSL_ERROR_WANT_WRITE:
  904. w_errtype = get_exception_class(space, 'w_sslwantwriteerror')
  905. errstr = "The operation did not complete (write)"
  906. errval = PY_SSL_ERROR_WANT_WRITE
  907. elif err == SSL_ERROR_WANT_X509_LOOKUP:
  908. errstr = "The operation did not complete (X509 lookup)"
  909. errval = PY_SSL_ERROR_WANT_X509_LOOKUP
  910. elif err == SSL_ERROR_WANT_CONNECT:
  911. errstr = "The operation did not complete (connect)"
  912. errval = PY_SSL_ERROR_WANT_CONNECT
  913. elif err == SSL_ERROR_SYSCALL:
  914. e = libssl_ERR_get_error()
  915. if e == 0:
  916. if ret == 0 or space.is_w(ss.w_socket, space.w_None):
  917. errstr = "EOF occurred in violation of protocol"
  918. errval = PY_SSL_ERROR_EOF
  919. elif ret == -1:
  920. # the underlying BIO reported an I/0 error
  921. error = rsocket.last_error()
  922. return interp_socket.converted_error(space, error)
  923. else:
  924. w_errtype = get_exception_class(space, 'w_sslsyscallerror')
  925. errstr = "Some I/O error occurred"
  926. errval = PY_SSL_ERROR_SYSCALL
  927. else:
  928. errstr = rffi.charp2str(libssl_ERR_error_string(e, None))
  929. errval = PY_SSL_ERROR_SYSCALL
  930. elif err == SSL_ERROR_SSL:
  931. errval = PY_SSL_ERROR_SSL
  932. if errcode != 0:
  933. errstr = rffi.charp2str(libssl_ERR_error_string(errcode, None))
  934. else:
  935. errstr = "A failure in the SSL library occurred"
  936. else:
  937. errstr = "Invalid error code"
  938. errval = PY_SSL_ERROR_INVALID_ERROR_CODE
  939. return ssl_error(space, errstr, errval, w_errtype=w_errtype,
  940. errcode=errcode)
  941. def SSLError_descr_str(space, w_exc):
  942. w_strerror = space.getattr(w_exc, space.wrap("strerror"))
  943. if not space.is_none(w_strerror):
  944. return w_strerror
  945. return space.str(space.getattr(w_exc, space.wrap("args")))
  946. class Cache:
  947. def __init__(self, space):
  948. w_socketerror = interp_socket.get_error(space, "error")
  949. self.w_sslerror = space.new_exception_class(
  950. "_ssl.SSLError", w_socketerror)
  951. space.setattr(self.w_sslerror, space.wrap('__str__'),
  952. space.wrap(interp2app(SSLError_descr_str)))
  953. self.w_sslzeroreturnerror = space.new_exception_class(
  954. "_ssl.SSLZeroReturnError", self.w_sslerror)
  955. self.w_sslwantreaderror = space.new_exception_class(
  956. "_ssl.SSLWantReadError", self.w_sslerror)
  957. self.w_sslwantwriteerror = space.new_exception_class(
  958. "_ssl.SSLWantWriteError", self.w_sslerror)
  959. self.w_sslsyscallerror = space.new_exception_class(
  960. "_ssl.SSLSyscallError", self.w_sslerror)
  961. self.w_ssleoferror = space.new_exception_class(
  962. "_ssl.SSLEOFError", self.w_sslerror)
  963. @specialize.memo()
  964. def get_exception_class(space, name):
  965. return getattr(space.fromcache(Cache), name)
  966. @unwrap_spec(filename=str)
  967. def _test_decode_cert(space, filename):
  968. cert = libssl_BIO_new(libssl_BIO_s_file())
  969. if not cert:
  970. raise ssl_error(space, "Can't malloc memory to read file")
  971. try:
  972. if libssl_BIO_read_filename(cert, filename) <= 0:
  973. raise ssl_error(space, "Can't open file")
  974. x = libssl_PEM_read_bio_X509_AUX(cert, None, None, None)
  975. if not x:
  976. raise ssl_error(space, "Error decoding PEM-encoded file")
  977. try:
  978. return _decode_certificate(space, x)
  979. finally:
  980. libssl_X509_free(x)
  981. finally:
  982. libssl_BIO_free(cert)
  983. # Data structure for the password callbacks
  984. class PasswordInfo(object):
  985. w_callable = None
  986. password = None
  987. operationerror = None
  988. PWINFO_STORAGE = {}
  989. def _password_callback(buf, size, rwflag, userdata):
  990. index = rffi.cast(lltype.Signed, userdata)
  991. pw_info = PWINFO_STORAGE.get(index, None)
  992. if not pw_info:
  993. return rffi.cast(rffi.INT, -1)
  994. space = pw_info.space
  995. password = ""
  996. if pw_info.w_callable:
  997. try:
  998. w_result = space.call_function(pw_info.w_callable)
  999. try:
  1000. password = pw_info.space.bufferstr_w(w_result)
  1001. except OperationError as e:
  1002. if not e.match(space, space.w_TypeError):
  1003. raise
  1004. raise oefmt(space.w_TypeError,
  1005. "password callback must return a string")
  1006. except OperationError as e:
  1007. pw_info.operationerror = e
  1008. return rffi.cast(rffi.INT, -1)
  1009. else:
  1010. password = pw_info.password
  1011. size = widen(size)
  1012. if len(password) > size:
  1013. pw_info.operationerror = oefmt(
  1014. space.w_ValueError,
  1015. "password cannot be longer than %d bytes", size)
  1016. return rffi.cast(rffi.INT, -1)
  1017. for i, c in enumerate(password):
  1018. buf[i] = c
  1019. return rffi.cast(rffi.INT, len(password))
  1020. class ServernameCallback(object):
  1021. w_ctx = None
  1022. space = None
  1023. SERVERNAME_CALLBACKS = RWeakValueDictionary(int, ServernameCallback)
  1024. def _servername_callback(ssl, ad, arg):
  1025. struct = SERVERNAME_CALLBACKS.get(rffi.cast(lltype.Signed, arg))
  1026. w_ctx = struct.w_ctx
  1027. space = struct.space
  1028. w_callback = struct.w_set_hostname
  1029. if not w_ctx.servername_callback:
  1030. # Possible race condition.
  1031. return rffi.cast(rffi.INT, SSL_TLSEXT_ERR_OK)
  1032. # The high-level ssl.SSLSocket object
  1033. index = rffi.cast(lltype.Signed, libssl_SSL_get_app_data(ssl))
  1034. w_ssl = SOCKET_STORAGE.get(index)
  1035. assert isinstance(w_ssl, _SSLSocket)
  1036. if w_ssl.ssl_sock_weakref_w is not None:
  1037. w_ssl_socket = w_ssl.ssl_sock_weakref_w()
  1038. else:
  1039. w_ssl_socket = space.w_None
  1040. if space.is_none(w_ssl_socket):
  1041. ad[0] = rffi.cast(rffi.INT, SSL_AD_INTERNAL_ERROR)
  1042. return rffi.cast(rffi.INT, SSL_TLSEXT_ERR_ALERT_FATAL)
  1043. servername = libssl_SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name)
  1044. try:
  1045. if not servername:
  1046. w_result = space.call_function(w_callback,
  1047. w_ssl_socket, space.w_None, w_ctx)
  1048. else:
  1049. w_servername = space.newbytes(rffi.charp2str(servername))
  1050. try:
  1051. w_servername_idna = space.call_method(
  1052. w_servername, 'decode', space.wrap('idna'))
  1053. except OperationError as e:
  1054. e.write_unraisable(space, "undecodable server name")
  1055. ad[0] = rffi.cast(rffi.INT, SSL_AD_INTERNAL_ERROR)
  1056. return rffi.cast(rffi.INT, SSL_TLSEXT_ERR_ALERT_FATAL)
  1057. w_result = space.call_function(w_callback,
  1058. w_ssl_socket,
  1059. w_servername_idna, w_ctx)
  1060. except OperationError as e:
  1061. e.write_unraisable(space, "in servername callback")
  1062. ad[0] = rffi.cast(rffi.INT, SSL_AD_HANDSHAKE_FAILURE)
  1063. return rffi.cast(rffi.INT, SSL_TLSEXT_ERR_ALERT_FATAL)
  1064. if space.is_none(w_result):
  1065. return rffi.cast(rffi.INT, SSL_TLSEXT_ERR_OK)
  1066. else:
  1067. try:
  1068. ad[0] = rffi.cast(rffi.INT, space.int_w(w_result))
  1069. except OperationError as e:
  1070. e.write_unraisable(space, "servername callback result")
  1071. ad[0] = rffi.cast(rffi.INT, SSL_AD_INTERNAL_ERROR)
  1072. return rffi.cast(rffi.INT, SSL_TLSEXT_ERR_ALERT_FATAL)
  1073. class _SSLContext(W_Root):
  1074. @staticmethod
  1075. @unwrap_spec(protocol=int)
  1076. def descr_new(space, w_subtype, protocol):
  1077. if protocol == PY_SSL_VERSION_TLS1:
  1078. method = libssl_TLSv1_method()
  1079. elif protocol == PY_SSL_VERSION_SSL3 and not OPENSSL_NO_SSL3:
  1080. method = libssl_SSLv3_method()
  1081. elif protocol == PY_SSL_VERSION_SSL2 and not OPENSSL_NO_SSL2:
  1082. method = libssl_SSLv2_method()
  1083. elif protocol == PY_SSL_VERSION_SSL23:
  1084. method = libssl_SSLv23_method()
  1085. elif protocol == PY_SSL_VERSION_TLS1_1 and HAVE_TLSv1_2:
  1086. method = libssl_TLSv1_1_method()
  1087. elif protocol == PY_SSL_VERSION_TLS1_2 and HAVE_TLSv1_2:
  1088. method = libssl_TLSv1_2_method()
  1089. else:
  1090. raise oefmt(space.w_ValueError, "invalid protocol version")
  1091. ctx = libssl_SSL_CTX_new(method)
  1092. if not ctx:
  1093. raise ssl_error(space, "failed to allocate SSL context")
  1094. rgc.add_memory_pressure(10 * 1024 * 1024)
  1095. self = space.allocate_instance(_SSLContext, w_subtype)
  1096. self.ctx = ctx
  1097. self.check_hostname = False
  1098. self.register_finalizer(space)
  1099. options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
  1100. if protocol != PY_SSL_VERSION_SSL2:
  1101. options |= SSL_OP_NO_SSLv2
  1102. libssl_SSL_CTX_set_options(ctx, options)
  1103. if not OPENSSL_NO_ECDH:
  1104. # Allow automatic ECDH curve selection (on
  1105. # OpenSSL 1.0.2+), or use prime256v1 by default.
  1106. # This is Apache mod_ssl's initialization
  1107. # policy, so we should be safe.
  1108. if libssl_SSL_CTX_set_ecdh_auto:
  1109. libssl_SSL_CTX_set_ecdh_auto(self.ctx, 1)
  1110. else:
  1111. key = libssl_EC_KEY_new_by_curve_name(NID_X9_62_prime256v1)
  1112. if not key:
  1113. raise _ssl_seterror(space, None, 0)
  1114. try:
  1115. libssl_SSL_CTX_set_tmp_ecdh(self.ctx, key)
  1116. finally:
  1117. libssl_EC_KEY_free(key)
  1118. return self
  1119. def _finalize_(self):
  1120. ctx = self.ctx
  1121. if ctx:
  1122. self.ctx = lltype.nullptr(SSL_CTX.TO)
  1123. libssl_SSL_CTX_free(ctx)
  1124. @unwrap_spec(server_side=int)
  1125. def descr_wrap_socket(self, space, w_sock, server_side, w_server_hostname=None, w_ssl_sock=None):
  1126. return _SSLSocket.descr_new(space, self, w_sock, server_side, w_server_hostname, w_ssl_sock)
  1127. @unwrap_spec(cipherlist=str)
  1128. def descr_set_ciphers(self, space, cipherlist):
  1129. ret = libssl_SSL_CTX_set_cipher_list(self.ctx, cipherlist)
  1130. if ret == 0:
  1131. libssl_ERR_clear_error()
  1132. raise ssl_error(space, "No cipher can be selected.")
  1133. def session_stats_w(self, space):
  1134. w_stats = space.newdict()
  1135. for name, ssl_func in SSL_CTX_STATS:
  1136. w_value = space.wrap(ssl_func(self.ctx))
  1137. space.setitem_str(w_stats, name, w_value)
  1138. return w_stats
  1139. def descr_set_default_verify_paths(self, space):
  1140. if not libssl_SSL_CTX_set_default_verify_paths(self.ctx):
  1141. raise ssl_error(space, "")
  1142. def descr_get_options(self, space):
  1143. return space.newlong(libssl_SSL_CTX_get_options(self.ctx))
  1144. def descr_set_options(self, space, w_new_opts):
  1145. new_opts = space.int_w(w_new_opts)
  1146. opts = libssl_SSL_CTX_get_options(self.ctx)
  1147. clear = opts & ~new_opts
  1148. set = ~opts & new_opts
  1149. if clear:
  1150. if HAVE_SSL_CTX_CLEAR_OPTIONS:
  1151. libssl_SSL_CTX_clear_options(self.ctx, clear)
  1152. else:
  1153. raise oefmt(space.w_ValueError,
  1154. "can't clear options before OpenSSL 0.9.8m")
  1155. if set:
  1156. libssl_SSL_CTX_set_options(self.ctx, set)
  1157. def descr_get_verify_mode(self, space):
  1158. mode = libssl_SSL_CTX_get_verify_mode(self.ctx)
  1159. if mode == SSL_VERIFY_NONE:
  1160. return space.newlong(PY_SSL_CERT_NONE)
  1161. elif mode == SSL_VERIFY_PEER:
  1162. return space.newlong(PY_SSL_CERT_OPTIONAL)
  1163. elif mode == SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
  1164. return space.newlong(PY_SSL_CERT_REQUIRED)
  1165. raise ssl_error(space, "invalid return value from SSL_CTX_get_verify_mode")
  1166. def descr_set_verify_mode(self, space, w_mode):
  1167. n = space.int_w(w_mode)
  1168. if n == PY_SSL_CERT_NONE:
  1169. mode = SSL_VERIFY_NONE
  1170. elif n == PY_SSL_CERT_OPTIONAL:
  1171. mode = SSL_VERIFY_PEER
  1172. elif n == PY_SSL_CERT_REQUIRED:
  1173. mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT
  1174. else:
  1175. raise oefmt(space.w_ValueError,
  1176. "invalid value for verify_mode")
  1177. if mode == SSL_VERIFY_NONE and self.check_hostname:
  1178. raise oefmt(space.w_ValueError,
  1179. "Cannot set verify_mode to CERT_NONE when "
  1180. "check_hostname is enabled.")
  1181. libssl_SSL_CTX_set_verify(self.ctx, mode, None)
  1182. def descr_get_verify_flags(self, space):
  1183. store = libssl_SSL_CTX_get_cert_store(self.ctx)
  1184. flags = libssl_X509_VERIFY_PARAM_get_flags(store[0].c_param)
  1185. return space.wrap(flags)
  1186. def descr_set_verify_flags(self, space, w_obj):
  1187. new_flags = space.int_w(w_obj)
  1188. store = libssl_SSL_CTX_get_cert_store(self.ctx)
  1189. flags = libssl_X509_VERIFY_PARAM_get_flags(store[0].c_param)
  1190. flags_clear = flags & ~new_flags
  1191. flags_set = ~flags & new_flags
  1192. if flags_clear and not libssl_X509_VERIFY_PARAM_clear_flags(
  1193. store[0].c_param, flags_clear):
  1194. raise _ssl_seterror(space, None, 0)
  1195. if flags_set and not libssl_X509_VERIFY_PARAM_set_flags(
  1196. store[0].c_param, flags_set):
  1197. raise _ssl_seterror(space, None, 0)
  1198. def descr_get_check_hostname(self, space):
  1199. return space.newbool(self.check_hostname)
  1200. def descr_set_check_hostname(self, space, w_obj):
  1201. check_hostname = space.is_true(w_obj)
  1202. if check_hostname and libssl_SSL_CTX_get_verify_mode(self.ctx) == SSL_VERIFY_NONE:
  1203. raise oefmt(space.w_ValueError,
  1204. "check_hostname needs a SSL context with either "
  1205. "CERT_OPTIONAL or CERT_REQUIRED")
  1206. self.check_hostname = check_hostname
  1207. def load_cert_chain_w(self, space, w_certfile, w_keyfile=None,
  1208. w_password=None):
  1209. if space.is_none(w_certfile):
  1210. certfile = None
  1211. else:
  1212. certfile = space.str_w(w_certfile)
  1213. if space.is_none(w_keyfile):
  1214. keyfile = certfile
  1215. else:
  1216. keyfile = space.str_w(w_keyfile)
  1217. pw_info = PasswordInfo()
  1218. pw_info.space = space
  1219. index = -1
  1220. if not space.is_none(w_password):
  1221. index = rthread.get_ident()
  1222. PWINFO_STORAGE[index] = pw_info
  1223. if space.is_true(space.callable(w_password)):
  1224. pw_info.w_callable = w_password
  1225. else:
  1226. try:
  1227. pw_info.password = space.bufferstr_w(w_password)
  1228. except OperationError as e:
  1229. if not e.match(space, space.w_TypeError):
  1230. raise
  1231. raise oefmt(space.w_TypeError,
  1232. "password should be a string or callable")
  1233. libssl_SSL_CTX_set_default_passwd_cb(
  1234. self.ctx, _password_callback)
  1235. libssl_SSL_CTX_set_default_passwd_cb_userdata(
  1236. self.ctx, rffi.cast(rffi.VOIDP, index))
  1237. try:
  1238. ret = libssl_SSL_CTX_use_certificate_chain_file(self.ctx, certfile)
  1239. if ret != 1:
  1240. if pw_info.operationerror:
  1241. libssl_ERR_clear_error()
  1242. raise pw_info.operationerror
  1243. errno = get_saved_errno()
  1244. if errno:
  1245. libssl_ERR_clear_error()
  1246. raise wrap_oserror(space, OSError(errno, ''),
  1247. exception_name = 'w_IOError')
  1248. else:
  1249. raise _ssl_seterror(space, None, -1)
  1250. ret = libssl_SSL_CTX_use_PrivateKey_file(self.ctx, keyfile,
  1251. SSL_FILETYPE_PEM)
  1252. if ret != 1:
  1253. if pw_info.operationerror:
  1254. libssl_ERR_clear_error()
  1255. raise pw_info.operationerror
  1256. errno = get_saved_errno()
  1257. if errno:
  1258. libssl_ERR_clear_error()
  1259. raise wrap_oserror(space, OSError(errno, ''),
  1260. exception_name = 'w_IOError')
  1261. else:
  1262. raise _ssl_seterror(space, None, -1)
  1263. ret = libssl_SSL_CTX_check_private_key(self.ctx)
  1264. if ret != 1:
  1265. raise _ssl_seterror(space, None, -1)
  1266. finally:
  1267. if index >= 0:
  1268. del PWINFO_STORAGE[index]
  1269. libssl_SSL_CTX_set_default_passwd_cb(
  1270. self.ctx, lltype.nullptr(pem_password_cb.TO))
  1271. libssl_SSL_CTX_set_default_passwd_cb_userdata(
  1272. self.ctx, None)
  1273. @unwrap_spec(filepath=str)
  1274. def load_dh_params_w(self, space, filepath):
  1275. bio = libssl_BIO_new_file(filepath, "r")
  1276. if not bio:
  1277. errno = get_saved_errno()
  1278. libssl_ERR_clear_error()
  1279. raise wrap_oserror(space, OSError(errno, ''),
  1280. exception_name = 'w_IOError')
  1281. try:
  1282. dh = libssl_PEM_read_bio_DHparams(bio, None, None, None)
  1283. finally:
  1284. libssl_BIO_free(bio)
  1285. if not dh:
  1286. errno = get_saved_errno()
  1287. if errno != 0:
  1288. libssl_ERR_clear_error()
  1289. raise wrap_oserror(space, OSError(errno, ''))
  1290. else:
  1291. raise _ssl_seterror(space, None, 0)
  1292. try:
  1293. if libssl_SSL_CTX_set_tmp_dh(self.ctx, dh) == 0:
  1294. raise _ssl_seterror(space, None, 0)
  1295. finally:
  1296. libssl_DH_free(dh)
  1297. def load_verify_locations_w(self, space, w_cafile=None, w_capath=None,
  1298. w_cadata=None):
  1299. if space.is_none(w_cafile):
  1300. cafile = None
  1301. else:
  1302. cafile = space.str_w(w_cafile)
  1303. if space.is_none(w_capath):
  1304. capath = None
  1305. else:
  1306. capath = space.str_w(w_capath)
  1307. if space.is_none(w_cadata):
  1308. cadata = None
  1309. ca_file_type = -1
  1310. else:
  1311. if not space.isinstance_w(w_cadata, space.w_unicode):
  1312. ca_file_type = SSL_FILETYPE_ASN1
  1313. cadata = space.bufferstr_w(w_cadata)
  1314. else:
  1315. ca_file_type = SSL_FILETYPE_PEM
  1316. try:
  1317. cadata = space.unicode_w(w_cadata).encode('ascii')
  1318. except UnicodeEncodeError:
  1319. raise oefmt(space.w_TypeError,
  1320. "cadata should be a ASCII string or a "
  1321. "bytes-like object")
  1322. if cafile is None and capath is None and cadata is None:
  1323. raise oefmt(space.w_TypeError,
  1324. "cafile and capath cannot be both omitted")
  1325. # load from cadata
  1326. if cadata is not None:
  1327. with rffi.scoped_nonmovingbuffer(cadata) as buf:
  1328. self._add_ca_certs(space, buf, len(cadata), ca_file_type)
  1329. # load cafile or capath
  1330. if cafile is not None or capath is not None:
  1331. ret = libssl_SSL_CTX_load_verify_locations(
  1332. self.ctx, cafile, capath)
  1333. if ret != 1:
  1334. errno = get_saved_errno()
  1335. if errno:
  1336. libssl_ERR_clear_error()
  1337. raise wrap_oserror(space, OSError(errno, ''),
  1338. exception_name = 'w_IOError')
  1339. else:
  1340. raise _ssl_seterror(space, None, -1)
  1341. def _add_ca_certs(self, space, data, size, ca_file_type):
  1342. biobuf = libssl_BIO_new_mem_buf(data, size)
  1343. if not biobuf:
  1344. raise ssl_error(space, "Can't allocate buffer")
  1345. try:
  1346. store = libssl_SSL_CTX_get_cert_store(self.ctx)
  1347. loaded = 0
  1348. while True:
  1349. if ca_file_type == SSL_FILETYPE_ASN1:
  1350. cert = libssl_d2i_X509_bio(
  1351. biobuf, None)
  1352. else:
  1353. cert = libssl_PEM_read_bio_X509(
  1354. biobuf, None, None, None)
  1355. if not cert:
  1356. break
  1357. try:
  1358. r = libssl_X509_STORE_add_cert(store, cert)
  1359. finally:
  1360. libssl_X509_free(cert)
  1361. if not r:
  1362. err = libssl_ERR_peek_last_error()
  1363. if (libssl_ERR_GET_LIB(err) == ERR_LIB_X509 and
  1364. libssl_ERR_GET_REASON(err) ==
  1365. X509_R_CERT_ALREADY_IN_HASH_TABLE):
  1366. # cert already in hash table, not an error
  1367. libssl_ERR_clear_error()
  1368. else:
  1369. break
  1370. loaded += 1
  1371. err = libssl_ERR_peek_last_error()
  1372. if (ca_file_type == SSL_FILETYPE_ASN1 and
  1373. loaded > 0 and
  1374. libssl_ERR_GET_LIB(err) == ERR_LIB_ASN1 and
  1375. libssl_ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG):
  1376. # EOF ASN1 file, not an error
  1377. libssl_ERR_clear_error()
  1378. elif (ca_file_type == SSL_FILETYPE_PEM and
  1379. loaded > 0 and
  1380. libssl_ERR_GET_LIB(err) == ERR_LIB_PEM and
  1381. libssl_ERR_GET_REASON(err) == PEM_R_NO_START_LINE):
  1382. # EOF PEM file, not an error
  1383. libssl_ERR_clear_error()
  1384. else:
  1385. raise _ssl_seterror(space, None, 0)
  1386. finally:
  1387. libssl_BIO_free(biobuf)
  1388. def cert_store_stats_w(self, space):
  1389. store = libssl_SSL_CTX_get_cert_store(self.ctx)
  1390. x509 = 0
  1391. x509_ca = 0
  1392. crl = 0
  1393. for i in range(libssl_sk_X509_OBJECT_num(store[0].c_objs)):
  1394. obj = libssl_sk_X509_OBJECT_value(store[0].c_objs, i)
  1395. if intmask(obj.c_type) == X509_LU_X509:
  1396. x509 += 1
  1397. if libssl_X509_check_ca(
  1398. libssl_pypy_X509_OBJECT_data_x509(obj)):
  1399. x509_ca += 1
  1400. elif intmask(obj.c_type) == X509_LU_CRL:
  1401. crl += 1
  1402. else:
  1403. # Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
  1404. # As far as I can tell they are internal states and never
  1405. # stored in a cert store
  1406. pass
  1407. w_result = space.newdict()
  1408. space.setitem(w_result,
  1409. space.wrap('x509'), space.wrap(x509))
  1410. space.setitem(w_result,
  1411. space.wrap('x509_ca'), space.wrap(x509_ca))
  1412. space.setitem(w_result,
  1413. space.wrap('crl'), space.wrap(crl))
  1414. return w_result
  1415. @unwrap_spec(protos='bufferstr')
  1416. def set_npn_protocols_w(self, space, protos):
  1417. if not HAS_NPN:
  1418. raise oefmt(space.w_NotImplementedError,
  1419. "The NPN extension requires OpenSSL 1.0.1 or later.")
  1420. self.npn_protocols = SSLNpnProtocols(self.ctx, protos)
  1421. @unwrap_spec(protos='bufferstr')
  1422. def set_alpn_protocols_w(self, space, protos):
  1423. if not HAS_ALPN:
  1424. raise oefmt(space.w_NotImplementedError,
  1425. "The ALPN extension requires OpenSSL 1.0.2 or later.")
  1426. self.alpn_protocols = SSLAlpnProtocols(self.ctx, protos)
  1427. def get_ca_certs_w(self, space, w_binary_form=None):
  1428. if w_binary_form and space.is_true(w_binary_form):
  1429. binary_mode = True
  1430. else:
  1431. binary_mode = False
  1432. rlist = []
  1433. store = libssl_SSL_CTX_get_cert_store(self.ctx)
  1434. for i in range(libssl_sk_X509_OBJECT_num(store[0].c_objs)):
  1435. obj = libssl_sk_X509_OBJECT_value(store[0].c_objs, i)
  1436. if intmask(obj.c_type) != X509_LU_X509:
  1437. # not a x509 cert
  1438. continue
  1439. # CA for any purpose
  1440. cert = libssl_pypy_X509_OBJECT_data_x509(obj)
  1441. if not libssl_X509_check_ca(cert):
  1442. continue
  1443. if binary_mode:
  1444. rlist.append(_certificate_to_der(space, cert))
  1445. else:
  1446. rlist.append(_decode_certificate(space, cert))
  1447. return space.newlist(rlist)
  1448. @unwrap_spec(name=str)
  1449. def set_ecdh_curve_w(self, space, name):
  1450. nid = libssl_OBJ_sn2nid(name)
  1451. if nid == 0:
  1452. raise oefmt(space.w_ValueError,
  1453. "unknown elliptic curve name '%s'", name)
  1454. key = libssl_EC_KEY_new_by_curve_name(nid)
  1455. if not key:
  1456. raise _ssl_seterror(space, None, 0)
  1457. try:
  1458. libssl_SSL_CTX_set_tmp_ecdh(self.ctx, key)
  1459. finally:
  1460. libssl_EC_KEY_free(key)
  1461. def set_servername_callback_w(self, space, w_callback):
  1462. if space.is_none(w_callback):
  1463. libssl_SSL_CTX_set_tlsext_servername_callback(
  1464. self.ctx, lltype.nullptr(servername_cb.TO))
  1465. self.servername_callback = None
  1466. return
  1467. if not space.is_true(space.callable(w_callback)):
  1468. raise oefmt(space.w_TypeError, "not a callable object")
  1469. callback_struct = ServernameCallback()
  1470. callback_struct.space = space
  1471. callback_struct.w_ctx = self
  1472. callback_struct.w_set_hostname = w_callback
  1473. self.servername_callback = callback_struct
  1474. index = compute_unique_id(self)
  1475. SERVERNAME_CALLBACKS.set(index, callback_struct)
  1476. libssl_SSL_CTX_set_tlsext_servername_callback(
  1477. self.ctx, _servername_callback)
  1478. libssl_SSL_CTX_set_tlsext_servername_arg(self.ctx,
  1479. rffi.cast(rffi.VOIDP, index))
  1480. _SSLContext.typedef = TypeDef(
  1481. "_ssl._SSLContext",
  1482. __new__=interp2app(_SSLContext.descr_new),
  1483. _wrap_socket=interp2app(_SSLContext.descr_wrap_socket),
  1484. set_ciphers=interp2app(_SSLContext.descr_set_ciphers),
  1485. cert_store_stats=interp2app(_SSLContext.cert_store_stats_w),
  1486. load_cert_chain=interp2app(_SSLContext.load_cert_chain_w),
  1487. load_dh_params=interp2app(_SSLContext.load_dh_params_w),
  1488. load_verify_locations=interp2app(_SSLContext.load_verify_locations_w),
  1489. session_stats = interp2app(_SSLContext.session_stats_w),
  1490. set_default_verify_paths=interp2app(_SSLContext.descr_set_default_verify_paths),
  1491. _set_npn_protocols=interp2app(_SSLContext.set_npn_protocols_w),
  1492. _set_alpn_protocols=interp2app(_SSLContext.set_alpn_protocols_w),
  1493. get_ca_certs=interp2app(_SSLContext.get_ca_certs_w),
  1494. set_ecdh_curve=interp2app(_SSLContext.set_ecdh_curve_w),
  1495. set_servername_callback=interp2app(_SSLContext.set_servername_callback_w),
  1496. options=GetSetProperty(_SSLContext.descr_get_options,
  1497. _SSLContext.descr_set_options),
  1498. verify_mode=GetSetProperty(_SSLContext.descr_get_verify_mode,
  1499. _SSLContext.descr_set_verify_mode),
  1500. verify_flags=GetSetProperty(_SSLContext.descr_get_verify_flags,
  1501. _SSLContext.descr_set_verify_flags),
  1502. check_hostname=GetSetProperty(_SSLContext.descr_get_check_hostname,
  1503. _SSLContext.descr_set_check_hostname),
  1504. )
  1505. def _asn1obj2py(space, obj):
  1506. nid = libssl_OBJ_obj2nid(obj)
  1507. if nid == NID_undef:
  1508. raise oefmt(space.w_ValueError, "Unknown object")
  1509. with rffi.scoped_alloc_buffer(100) as buf:
  1510. buflen = libssl_OBJ_obj2txt(buf.raw, 100, obj, 1)
  1511. if buflen < 0:
  1512. raise _ssl_seterror(space, None, 0)
  1513. if buflen:
  1514. w_buf = space.wrap(buf.str(buflen))
  1515. else:
  1516. w_buf = space.w_None
  1517. w_sn = space.wrap(rffi.charp2str(libssl_OBJ_nid2sn(nid)))
  1518. w_ln = space.wrap(rffi.charp2str(libssl_OBJ_nid2ln(nid)))
  1519. return space.newtuple([space.wrap(nid), w_sn, w_ln, w_buf])
  1520. @unwrap_spec(txt=str, name=bool)
  1521. def txt2obj(space, txt, name=False):
  1522. obj = libssl_OBJ_txt2obj(txt, not name)
  1523. if not obj:
  1524. raise oefmt(space.w_ValueError, "unknown object '%s'", txt)
  1525. try:
  1526. w_result = _asn1obj2py(space, obj)
  1527. finally:
  1528. libssl_ASN1_OBJECT_free(obj)
  1529. return w_result
  1530. @unwrap_spec(nid=int)
  1531. def nid2obj(space, nid):
  1532. if nid < NID_undef:
  1533. raise oefmt(space.w_ValueError, "NID must be positive")
  1534. obj = libssl_OBJ_nid2obj(nid)
  1535. if not obj:
  1536. raise oefmt(space.w_ValueError, "unknown NID %d", nid)
  1537. try:
  1538. w_result = _asn1obj2py(space, obj)
  1539. finally:
  1540. libssl_ASN1_OBJECT_free(obj)
  1541. return w_result
  1542. def w_convert_path(space, path):
  1543. if not path:
  1544. return space.w_None
  1545. else:
  1546. return space.newbytes(rffi.charp2str(path))
  1547. def get_default_verify_paths(space):
  1548. return space.newtuple([
  1549. w_convert_path(space, libssl_X509_get_default_cert_file_env()),
  1550. w_convert_path(space, libssl_X509_get_default_cert_file()),
  1551. w_convert_path(space, libssl_X509_get_default_cert_dir_env()),
  1552. w_convert_path(space, libssl_X509_get_default_cert_dir()),
  1553. ])