PageRenderTime 63ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/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

Large files files are truncated, but you can click here to view the full file

  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

Large files files are truncated, but you can click here to view the full file