PageRenderTime 57ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/pypy/module/_ssl/interp_ssl.py

https://bitbucket.org/dac_io/pypy
Python | 917 lines | 808 code | 54 blank | 55 comment | 66 complexity | afa450c48dd04e9c608de63921ce6746 MD5 | raw file
  1. from __future__ import with_statement
  2. from pypy.rpython.lltypesystem import rffi, lltype
  3. from pypy.interpreter.error import OperationError
  4. from pypy.interpreter.baseobjspace import Wrappable
  5. from pypy.interpreter.typedef import TypeDef
  6. from pypy.interpreter.gateway import interp2app, unwrap_spec
  7. from pypy.rlib.rarithmetic import intmask
  8. from pypy.rlib import rpoll, rsocket
  9. from pypy.rlib.ropenssl import *
  10. from pypy.module._socket import interp_socket
  11. ## user defined constants
  12. X509_NAME_MAXLEN = 256
  13. ## # these mirror ssl.h
  14. PY_SSL_ERROR_NONE, PY_SSL_ERROR_SSL = 0, 1
  15. PY_SSL_ERROR_WANT_READ, PY_SSL_ERROR_WANT_WRITE = 2, 3
  16. PY_SSL_ERROR_WANT_X509_LOOKUP = 4
  17. PY_SSL_ERROR_SYSCALL = 5 # look at error stack/return value/errno
  18. PY_SSL_ERROR_ZERO_RETURN, PY_SSL_ERROR_WANT_CONNECT = 6, 7
  19. # start of non ssl.h errorcodes
  20. PY_SSL_ERROR_EOF = 8 # special case of SSL_ERROR_SYSCALL
  21. PY_SSL_ERROR_INVALID_ERROR_CODE = 9
  22. PY_SSL_CERT_NONE, PY_SSL_CERT_OPTIONAL, PY_SSL_CERT_REQUIRED = 0, 1, 2
  23. PY_SSL_CLIENT, PY_SSL_SERVER = 0, 1
  24. (PY_SSL_VERSION_SSL2, PY_SSL_VERSION_SSL3,
  25. PY_SSL_VERSION_SSL23, PY_SSL_VERSION_TLS1) = range(4)
  26. SOCKET_IS_NONBLOCKING, SOCKET_IS_BLOCKING = 0, 1
  27. SOCKET_HAS_TIMED_OUT, SOCKET_HAS_BEEN_CLOSED = 2, 3
  28. SOCKET_TOO_LARGE_FOR_SELECT, SOCKET_OPERATION_OK = 4, 5
  29. HAVE_RPOLL = True # Even win32 has rpoll.poll
  30. constants = {}
  31. constants["SSL_ERROR_ZERO_RETURN"] = PY_SSL_ERROR_ZERO_RETURN
  32. constants["SSL_ERROR_WANT_READ"] = PY_SSL_ERROR_WANT_READ
  33. constants["SSL_ERROR_WANT_WRITE"] = PY_SSL_ERROR_WANT_WRITE
  34. constants["SSL_ERROR_WANT_X509_LOOKUP"] = PY_SSL_ERROR_WANT_X509_LOOKUP
  35. constants["SSL_ERROR_SYSCALL"] = PY_SSL_ERROR_SYSCALL
  36. constants["SSL_ERROR_SSL"] = PY_SSL_ERROR_SSL
  37. constants["SSL_ERROR_WANT_CONNECT"] = PY_SSL_ERROR_WANT_CONNECT
  38. constants["SSL_ERROR_EOF"] = PY_SSL_ERROR_EOF
  39. constants["SSL_ERROR_INVALID_ERROR_CODE"] = PY_SSL_ERROR_INVALID_ERROR_CODE
  40. constants["CERT_NONE"] = PY_SSL_CERT_NONE
  41. constants["CERT_OPTIONAL"] = PY_SSL_CERT_OPTIONAL
  42. constants["CERT_REQUIRED"] = PY_SSL_CERT_REQUIRED
  43. if not OPENSSL_NO_SSL2:
  44. constants["PROTOCOL_SSLv2"] = PY_SSL_VERSION_SSL2
  45. constants["PROTOCOL_SSLv3"] = PY_SSL_VERSION_SSL3
  46. constants["PROTOCOL_SSLv23"] = PY_SSL_VERSION_SSL23
  47. constants["PROTOCOL_TLSv1"] = PY_SSL_VERSION_TLS1
  48. constants["OPENSSL_VERSION_NUMBER"] = OPENSSL_VERSION_NUMBER
  49. ver = OPENSSL_VERSION_NUMBER
  50. ver, status = divmod(ver, 16)
  51. ver, patch = divmod(ver, 256)
  52. ver, fix = divmod(ver, 256)
  53. ver, minor = divmod(ver, 256)
  54. ver, major = divmod(ver, 256)
  55. constants["OPENSSL_VERSION_INFO"] = (major, minor, fix, patch, status)
  56. constants["OPENSSL_VERSION"] = SSLEAY_VERSION
  57. def ssl_error(space, msg, errno=0):
  58. w_exception_class = get_error(space)
  59. w_exception = space.call_function(w_exception_class,
  60. space.wrap(errno), space.wrap(msg))
  61. return OperationError(w_exception_class, w_exception)
  62. if HAVE_OPENSSL_RAND:
  63. # helper routines for seeding the SSL PRNG
  64. @unwrap_spec(string=str, entropy=float)
  65. def RAND_add(space, string, entropy):
  66. """RAND_add(string, entropy)
  67. Mix string into the OpenSSL PRNG state. entropy (a float) is a lower
  68. bound on the entropy contained in string."""
  69. buf = rffi.str2charp(string)
  70. try:
  71. libssl_RAND_add(buf, len(string), entropy)
  72. finally:
  73. rffi.free_charp(buf)
  74. def RAND_status(space):
  75. """RAND_status() -> 0 or 1
  76. Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
  77. It is necessary to seed the PRNG with RAND_add() on some platforms before
  78. using the ssl() function."""
  79. res = libssl_RAND_status()
  80. return space.wrap(res)
  81. @unwrap_spec(path=str)
  82. def RAND_egd(space, path):
  83. """RAND_egd(path) -> bytes
  84. Queries the entropy gather daemon (EGD) on socket path. Returns number
  85. of bytes read. Raises socket.sslerror if connection to EGD fails or
  86. if it does provide enough data to seed PRNG."""
  87. socket_path = rffi.str2charp(path)
  88. try:
  89. bytes = libssl_RAND_egd(socket_path)
  90. finally:
  91. rffi.free_charp(socket_path)
  92. if bytes == -1:
  93. msg = "EGD connection failed or EGD did not return"
  94. msg += " enough data to seed the PRNG"
  95. raise ssl_error(space, msg)
  96. return space.wrap(bytes)
  97. class SSLObject(Wrappable):
  98. def __init__(self, space):
  99. self.space = space
  100. self.w_socket = None
  101. self.ctx = lltype.nullptr(SSL_CTX.TO)
  102. self.ssl = lltype.nullptr(SSL.TO)
  103. self.peer_cert = lltype.nullptr(X509.TO)
  104. self._server = lltype.malloc(rffi.CCHARP.TO, X509_NAME_MAXLEN, flavor='raw')
  105. self._server[0] = '\0'
  106. self._issuer = lltype.malloc(rffi.CCHARP.TO, X509_NAME_MAXLEN, flavor='raw')
  107. self._issuer[0] = '\0'
  108. self.shutdown_seen_zero = False
  109. def server(self):
  110. return self.space.wrap(rffi.charp2str(self._server))
  111. def issuer(self):
  112. return self.space.wrap(rffi.charp2str(self._issuer))
  113. def __del__(self):
  114. self.enqueue_for_destruction(self.space, SSLObject.destructor,
  115. '__del__() method of ')
  116. def destructor(self):
  117. assert isinstance(self, SSLObject)
  118. if self.peer_cert:
  119. libssl_X509_free(self.peer_cert)
  120. if self.ssl:
  121. libssl_SSL_free(self.ssl)
  122. if self.ctx:
  123. libssl_SSL_CTX_free(self.ctx)
  124. lltype.free(self._server, flavor='raw')
  125. lltype.free(self._issuer, flavor='raw')
  126. @unwrap_spec(data='bufferstr')
  127. def write(self, data):
  128. """write(s) -> len
  129. Writes the string s into the SSL object. Returns the number
  130. of bytes written."""
  131. self._refresh_nonblocking(self.space)
  132. sockstate = check_socket_and_wait_for_timeout(self.space,
  133. self.w_socket, True)
  134. if sockstate == SOCKET_HAS_TIMED_OUT:
  135. raise ssl_error(self.space, "The write operation timed out")
  136. elif sockstate == SOCKET_HAS_BEEN_CLOSED:
  137. raise ssl_error(self.space, "Underlying socket has been closed.")
  138. elif sockstate == SOCKET_TOO_LARGE_FOR_SELECT:
  139. raise ssl_error(self.space, "Underlying socket too large for select().")
  140. num_bytes = 0
  141. while True:
  142. err = 0
  143. num_bytes = libssl_SSL_write(self.ssl, data, len(data))
  144. err = libssl_SSL_get_error(self.ssl, num_bytes)
  145. if err == SSL_ERROR_WANT_READ:
  146. sockstate = check_socket_and_wait_for_timeout(self.space,
  147. self.w_socket, False)
  148. elif err == SSL_ERROR_WANT_WRITE:
  149. sockstate = check_socket_and_wait_for_timeout(self.space,
  150. self.w_socket, True)
  151. else:
  152. sockstate = SOCKET_OPERATION_OK
  153. if sockstate == SOCKET_HAS_TIMED_OUT:
  154. raise ssl_error(self.space, "The write operation timed out")
  155. elif sockstate == SOCKET_HAS_BEEN_CLOSED:
  156. raise ssl_error(self.space, "Underlying socket has been closed.")
  157. elif sockstate == SOCKET_IS_NONBLOCKING:
  158. break
  159. if err == SSL_ERROR_WANT_READ or err == SSL_ERROR_WANT_WRITE:
  160. continue
  161. else:
  162. break
  163. if num_bytes > 0:
  164. return self.space.wrap(num_bytes)
  165. else:
  166. raise _ssl_seterror(self.space, self, num_bytes)
  167. def pending(self):
  168. """pending() -> count
  169. Returns the number of already decrypted bytes available for read,
  170. pending on the connection."""
  171. count = libssl_SSL_pending(self.ssl)
  172. if count < 0:
  173. raise _ssl_seterror(self.space, self, count)
  174. return self.space.wrap(count)
  175. @unwrap_spec(num_bytes=int)
  176. def read(self, num_bytes=1024):
  177. """read([len]) -> string
  178. Read up to len bytes from the SSL socket."""
  179. count = libssl_SSL_pending(self.ssl)
  180. if not count:
  181. sockstate = check_socket_and_wait_for_timeout(self.space,
  182. self.w_socket, False)
  183. if sockstate == SOCKET_HAS_TIMED_OUT:
  184. raise ssl_error(self.space, "The read operation timed out")
  185. elif sockstate == SOCKET_TOO_LARGE_FOR_SELECT:
  186. raise ssl_error(self.space, "Underlying socket too large for select().")
  187. elif sockstate == SOCKET_HAS_BEEN_CLOSED:
  188. if libssl_SSL_get_shutdown(self.ssl) == SSL_RECEIVED_SHUTDOWN:
  189. return self.space.wrap('')
  190. raise ssl_error(self.space, "Socket closed without SSL shutdown handshake")
  191. raw_buf, gc_buf = rffi.alloc_buffer(num_bytes)
  192. while True:
  193. err = 0
  194. count = libssl_SSL_read(self.ssl, raw_buf, num_bytes)
  195. err = libssl_SSL_get_error(self.ssl, count)
  196. if err == SSL_ERROR_WANT_READ:
  197. sockstate = check_socket_and_wait_for_timeout(self.space,
  198. self.w_socket, False)
  199. elif err == SSL_ERROR_WANT_WRITE:
  200. sockstate = check_socket_and_wait_for_timeout(self.space,
  201. self.w_socket, True)
  202. elif (err == SSL_ERROR_ZERO_RETURN and
  203. libssl_SSL_get_shutdown(self.ssl) == SSL_RECEIVED_SHUTDOWN):
  204. return self.space.wrap("")
  205. else:
  206. sockstate = SOCKET_OPERATION_OK
  207. if sockstate == SOCKET_HAS_TIMED_OUT:
  208. raise ssl_error(self.space, "The read operation timed out")
  209. elif sockstate == SOCKET_IS_NONBLOCKING:
  210. break
  211. if err == SSL_ERROR_WANT_READ or err == SSL_ERROR_WANT_WRITE:
  212. continue
  213. else:
  214. break
  215. if count <= 0:
  216. raise _ssl_seterror(self.space, self, count)
  217. result = rffi.str_from_buffer(raw_buf, gc_buf, num_bytes, count)
  218. rffi.keep_buffer_alive_until_here(raw_buf, gc_buf)
  219. return self.space.wrap(result)
  220. def _refresh_nonblocking(self, space):
  221. # just in case the blocking state of the socket has been changed
  222. w_timeout = space.call_method(self.w_socket, "gettimeout")
  223. nonblocking = not space.is_w(w_timeout, space.w_None)
  224. libssl_BIO_set_nbio(libssl_SSL_get_rbio(self.ssl), nonblocking)
  225. libssl_BIO_set_nbio(libssl_SSL_get_wbio(self.ssl), nonblocking)
  226. def do_handshake(self, space):
  227. self._refresh_nonblocking(space)
  228. # Actually negotiate SSL connection
  229. # XXX If SSL_do_handshake() returns 0, it's also a failure.
  230. while True:
  231. ret = libssl_SSL_do_handshake(self.ssl)
  232. err = libssl_SSL_get_error(self.ssl, ret)
  233. # XXX PyErr_CheckSignals()
  234. if err == SSL_ERROR_WANT_READ:
  235. sockstate = check_socket_and_wait_for_timeout(
  236. space, self.w_socket, False)
  237. elif err == SSL_ERROR_WANT_WRITE:
  238. sockstate = check_socket_and_wait_for_timeout(
  239. space, self.w_socket, True)
  240. else:
  241. sockstate = SOCKET_OPERATION_OK
  242. if sockstate == SOCKET_HAS_TIMED_OUT:
  243. raise ssl_error(space, "The handshake operation timed out")
  244. elif sockstate == SOCKET_HAS_BEEN_CLOSED:
  245. raise ssl_error(space, "Underlying socket has been closed.")
  246. elif sockstate == SOCKET_TOO_LARGE_FOR_SELECT:
  247. raise ssl_error(space, "Underlying socket too large for select().")
  248. elif sockstate == SOCKET_IS_NONBLOCKING:
  249. break
  250. if err == SSL_ERROR_WANT_READ or err == SSL_ERROR_WANT_WRITE:
  251. continue
  252. else:
  253. break
  254. if ret <= 0:
  255. raise _ssl_seterror(space, self, ret)
  256. if self.peer_cert:
  257. libssl_X509_free(self.peer_cert)
  258. self.peer_cert = libssl_SSL_get_peer_certificate(self.ssl)
  259. if self.peer_cert:
  260. libssl_X509_NAME_oneline(
  261. libssl_X509_get_subject_name(self.peer_cert),
  262. self._server, X509_NAME_MAXLEN)
  263. libssl_X509_NAME_oneline(
  264. libssl_X509_get_issuer_name(self.peer_cert),
  265. self._issuer, X509_NAME_MAXLEN)
  266. def shutdown(self, space):
  267. # Guard against closed socket
  268. w_fileno = space.call_method(self.w_socket, "fileno")
  269. if space.int_w(w_fileno) < 0:
  270. raise ssl_error(space, "Underlying socket has been closed")
  271. self._refresh_nonblocking(space)
  272. zeros = 0
  273. while True:
  274. # Disable read-ahead so that unwrap can work correctly.
  275. # Otherwise OpenSSL might read in too much data,
  276. # eating clear text data that happens to be
  277. # transmitted after the SSL shutdown.
  278. # Should be safe to call repeatedly everytime this
  279. # function is used and the shutdown_seen_zero != 0
  280. # condition is met.
  281. if self.shutdown_seen_zero:
  282. libssl_SSL_set_read_ahead(self.ssl, 0)
  283. ret = libssl_SSL_shutdown(self.ssl)
  284. # if err == 1, a secure shutdown with SSL_shutdown() is complete
  285. if ret > 0:
  286. break
  287. if ret == 0:
  288. # Don't loop endlessly; instead preserve legacy
  289. # behaviour of trying SSL_shutdown() only twice.
  290. # This looks necessary for OpenSSL < 0.9.8m
  291. zeros += 1
  292. if zeros > 1:
  293. break
  294. # Shutdown was sent, now try receiving
  295. self.shutdown_seen_zero = True
  296. continue
  297. # Possibly retry shutdown until timeout or failure
  298. ssl_err = libssl_SSL_get_error(self.ssl, ret)
  299. if ssl_err == SSL_ERROR_WANT_READ:
  300. sockstate = check_socket_and_wait_for_timeout(
  301. self.space, self.w_socket, False)
  302. elif ssl_err == SSL_ERROR_WANT_WRITE:
  303. sockstate = check_socket_and_wait_for_timeout(
  304. self.space, self.w_socket, True)
  305. else:
  306. break
  307. if sockstate == SOCKET_HAS_TIMED_OUT:
  308. if ssl_err == SSL_ERROR_WANT_READ:
  309. raise ssl_error(self.space, "The read operation timed out")
  310. else:
  311. raise ssl_error(self.space, "The write operation timed out")
  312. elif sockstate == SOCKET_TOO_LARGE_FOR_SELECT:
  313. raise ssl_error(space, "Underlying socket too large for select().")
  314. elif sockstate != SOCKET_OPERATION_OK:
  315. # Retain the SSL error code
  316. break
  317. if ret < 0:
  318. raise _ssl_seterror(space, self, ret)
  319. return self.w_socket
  320. def cipher(self, space):
  321. if not self.ssl:
  322. return space.w_None
  323. current = libssl_SSL_get_current_cipher(self.ssl)
  324. if not current:
  325. return space.w_None
  326. name = libssl_SSL_CIPHER_get_name(current)
  327. if name:
  328. w_name = space.wrap(rffi.charp2str(name))
  329. else:
  330. w_name = space.w_None
  331. proto = libssl_SSL_CIPHER_get_version(current)
  332. if proto:
  333. w_proto = space.wrap(rffi.charp2str(name))
  334. else:
  335. w_proto = space.w_None
  336. bits = libssl_SSL_CIPHER_get_bits(current,
  337. lltype.nullptr(rffi.INTP.TO))
  338. w_bits = space.newint(bits)
  339. return space.newtuple([w_name, w_proto, w_bits])
  340. @unwrap_spec(der=bool)
  341. def peer_certificate(self, der=False):
  342. """peer_certificate([der=False]) -> certificate
  343. Returns the certificate for the peer. If no certificate was provided,
  344. returns None. If a certificate was provided, but not validated, returns
  345. an empty dictionary. Otherwise returns a dict containing information
  346. about the peer certificate.
  347. If the optional argument is True, returns a DER-encoded copy of the
  348. peer certificate, or None if no certificate was provided. This will
  349. return the certificate even if it wasn't validated."""
  350. if not self.peer_cert:
  351. return self.space.w_None
  352. if der:
  353. # return cert in DER-encoded format
  354. with lltype.scoped_alloc(rffi.CCHARPP.TO, 1) as buf_ptr:
  355. buf_ptr[0] = lltype.nullptr(rffi.CCHARP.TO)
  356. length = libssl_i2d_X509(self.peer_cert, buf_ptr)
  357. if length < 0:
  358. raise _ssl_seterror(self.space, self, length)
  359. try:
  360. # this is actually an immutable bytes sequence
  361. return self.space.wrap(rffi.charpsize2str(buf_ptr[0],
  362. length))
  363. finally:
  364. libssl_OPENSSL_free(buf_ptr[0])
  365. else:
  366. verification = libssl_SSL_CTX_get_verify_mode(
  367. libssl_SSL_get_SSL_CTX(self.ssl))
  368. if not verification & SSL_VERIFY_PEER:
  369. return self.space.newdict()
  370. else:
  371. return _decode_certificate(self.space, self.peer_cert)
  372. def _decode_certificate(space, certificate, verbose=False):
  373. w_retval = space.newdict()
  374. w_peer = _create_tuple_for_X509_NAME(
  375. space, libssl_X509_get_subject_name(certificate))
  376. space.setitem(w_retval, space.wrap("subject"), w_peer)
  377. if verbose:
  378. w_issuer = _create_tuple_for_X509_NAME(
  379. space, libssl_X509_get_issuer_name(certificate))
  380. space.setitem(w_retval, space.wrap("issuer"), w_issuer)
  381. space.setitem(w_retval, space.wrap("version"),
  382. space.wrap(libssl_X509_get_version(certificate)))
  383. biobuf = libssl_BIO_new(libssl_BIO_s_mem())
  384. try:
  385. if verbose:
  386. libssl_BIO_reset(biobuf)
  387. serialNumber = libssl_X509_get_serialNumber(certificate)
  388. libssl_i2a_ASN1_INTEGER(biobuf, serialNumber)
  389. # should not exceed 20 octets, 160 bits, so buf is big enough
  390. with lltype.scoped_alloc(rffi.CCHARP.TO, 100) as buf:
  391. length = libssl_BIO_gets(biobuf, buf, 99)
  392. if length < 0:
  393. raise _ssl_seterror(space, None, length)
  394. w_serial = space.wrap(rffi.charpsize2str(buf, length))
  395. space.setitem(w_retval, space.wrap("serialNumber"), w_serial)
  396. libssl_BIO_reset(biobuf)
  397. notBefore = libssl_X509_get_notBefore(certificate)
  398. libssl_ASN1_TIME_print(biobuf, notBefore)
  399. with lltype.scoped_alloc(rffi.CCHARP.TO, 100) as buf:
  400. length = libssl_BIO_gets(biobuf, buf, 99)
  401. if length < 0:
  402. raise _ssl_seterror(space, None, length)
  403. w_date = space.wrap(rffi.charpsize2str(buf, length))
  404. space.setitem(w_retval, space.wrap("notBefore"), w_date)
  405. libssl_BIO_reset(biobuf)
  406. notAfter = libssl_X509_get_notAfter(certificate)
  407. libssl_ASN1_TIME_print(biobuf, notAfter)
  408. with lltype.scoped_alloc(rffi.CCHARP.TO, 100) as buf:
  409. length = libssl_BIO_gets(biobuf, buf, 99)
  410. if length < 0:
  411. raise _ssl_seterror(space, None, length)
  412. w_date = space.wrap(rffi.charpsize2str(buf, length))
  413. space.setitem(w_retval, space.wrap("notAfter"), w_date)
  414. finally:
  415. libssl_BIO_free(biobuf)
  416. # Now look for subjectAltName
  417. w_alt_names = _get_peer_alt_names(space, certificate)
  418. if w_alt_names is not space.w_None:
  419. space.setitem(w_retval, space.wrap("subjectAltName"), w_alt_names)
  420. return w_retval
  421. def _create_tuple_for_X509_NAME(space, xname):
  422. entry_count = libssl_X509_NAME_entry_count(xname)
  423. dn_w = []
  424. rdn_w = []
  425. rdn_level = -1
  426. for index in range(entry_count):
  427. entry = libssl_X509_NAME_get_entry(xname, index)
  428. # check to see if we've gotten to a new RDN
  429. entry_level = intmask(entry[0].c_set)
  430. if rdn_level >= 0:
  431. if rdn_level != entry_level:
  432. # yes, new RDN
  433. # add old RDN to DN
  434. dn_w.append(space.newtuple(list(rdn_w)))
  435. rdn_w = []
  436. rdn_level = entry_level
  437. # Now add this attribute to the current RDN
  438. name = libssl_X509_NAME_ENTRY_get_object(entry)
  439. value = libssl_X509_NAME_ENTRY_get_data(entry)
  440. attr = _create_tuple_for_attribute(space, name, value)
  441. rdn_w.append(attr)
  442. # Now, there is typically a dangling RDN
  443. if rdn_w:
  444. dn_w.append(space.newtuple(list(rdn_w)))
  445. return space.newtuple(list(dn_w))
  446. def _get_peer_alt_names(space, certificate):
  447. # this code follows the procedure outlined in
  448. # OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
  449. # function to extract the STACK_OF(GENERAL_NAME),
  450. # then iterates through the stack to add the
  451. # names.
  452. if not certificate:
  453. return space.w_None
  454. # get a memory buffer
  455. biobuf = libssl_BIO_new(libssl_BIO_s_mem())
  456. try:
  457. alt_names_w = []
  458. i = 0
  459. while True:
  460. i = libssl_X509_get_ext_by_NID(
  461. certificate, NID_subject_alt_name, i)
  462. if i < 0:
  463. break
  464. # now decode the altName
  465. ext = libssl_X509_get_ext(certificate, i)
  466. method = libssl_X509V3_EXT_get(ext)
  467. if not method:
  468. raise ssl_error(space,
  469. "No method for internalizing subjectAltName!'")
  470. with lltype.scoped_alloc(rffi.CCHARPP.TO, 1) as p_ptr:
  471. p_ptr[0] = ext[0].c_value.c_data
  472. length = intmask(ext[0].c_value.c_length)
  473. null = lltype.nullptr(rffi.VOIDP.TO)
  474. if method[0].c_it:
  475. names = rffi.cast(GENERAL_NAMES, libssl_ASN1_item_d2i(
  476. null, p_ptr, length,
  477. libssl_ASN1_ITEM_ptr(method[0].c_it)))
  478. else:
  479. names = rffi.cast(GENERAL_NAMES, method[0].c_d2i(
  480. null, p_ptr, length))
  481. for j in range(libssl_sk_GENERAL_NAME_num(names)):
  482. # Get a rendering of each name in the set of names
  483. name = libssl_sk_GENERAL_NAME_value(names, j)
  484. if intmask(name[0].c_type) == GEN_DIRNAME:
  485. # we special-case DirName as a tuple of tuples of attributes
  486. dirname = libssl_pypy_GENERAL_NAME_dirn(name)
  487. w_t = space.newtuple([
  488. space.wrap("DirName"),
  489. _create_tuple_for_X509_NAME(space, dirname)
  490. ])
  491. else:
  492. # for everything else, we use the OpenSSL print form
  493. libssl_BIO_reset(biobuf)
  494. libssl_GENERAL_NAME_print(biobuf, name)
  495. with lltype.scoped_alloc(rffi.CCHARP.TO, 2048) as buf:
  496. length = libssl_BIO_gets(biobuf, buf, 2047)
  497. if length < 0:
  498. raise _ssl_seterror(space, None, 0)
  499. v = rffi.charpsize2str(buf, length)
  500. v1, v2 = v.split(':', 1)
  501. w_t = space.newtuple([space.wrap(v1),
  502. space.wrap(v2)])
  503. alt_names_w.append(w_t)
  504. finally:
  505. libssl_BIO_free(biobuf)
  506. if alt_names_w:
  507. return space.newtuple(list(alt_names_w))
  508. else:
  509. return space.w_None
  510. def _create_tuple_for_attribute(space, name, value):
  511. with lltype.scoped_alloc(rffi.CCHARP.TO, X509_NAME_MAXLEN) as buf:
  512. length = libssl_OBJ_obj2txt(buf, X509_NAME_MAXLEN, name, 0)
  513. if length < 0:
  514. raise _ssl_seterror(space, None, 0)
  515. w_name = space.wrap(rffi.charpsize2str(buf, length))
  516. with lltype.scoped_alloc(rffi.CCHARPP.TO, 1) as buf_ptr:
  517. length = libssl_ASN1_STRING_to_UTF8(buf_ptr, value)
  518. if length < 0:
  519. raise _ssl_seterror(space, None, 0)
  520. w_value = space.wrap(rffi.charpsize2str(buf_ptr[0], length))
  521. w_value = space.call_method(w_value, "decode", space.wrap("utf-8"))
  522. return space.newtuple([w_name, w_value])
  523. SSLObject.typedef = TypeDef("SSLObject",
  524. server = interp2app(SSLObject.server),
  525. issuer = interp2app(SSLObject.issuer),
  526. write = interp2app(SSLObject.write),
  527. pending = interp2app(SSLObject.pending),
  528. read = interp2app(SSLObject.read),
  529. do_handshake = interp2app(SSLObject.do_handshake),
  530. shutdown = interp2app(SSLObject.shutdown),
  531. cipher = interp2app(SSLObject.cipher),
  532. peer_certificate = interp2app(SSLObject.peer_certificate),
  533. )
  534. def new_sslobject(space, w_sock, side, w_key_file, w_cert_file,
  535. cert_mode, protocol, w_cacerts_file, w_ciphers):
  536. ss = SSLObject(space)
  537. sock_fd = space.int_w(space.call_method(w_sock, "fileno"))
  538. w_timeout = space.call_method(w_sock, "gettimeout")
  539. if space.is_w(w_timeout, space.w_None):
  540. has_timeout = False
  541. else:
  542. has_timeout = True
  543. if space.is_w(w_key_file, space.w_None):
  544. key_file = None
  545. else:
  546. key_file = space.str_w(w_key_file)
  547. if space.is_w(w_cert_file, space.w_None):
  548. cert_file = None
  549. else:
  550. cert_file = space.str_w(w_cert_file)
  551. if space.is_w(w_cacerts_file, space.w_None):
  552. cacerts_file = None
  553. else:
  554. cacerts_file = space.str_w(w_cacerts_file)
  555. if space.is_w(w_ciphers, space.w_None):
  556. ciphers = None
  557. else:
  558. ciphers = space.str_w(w_ciphers)
  559. if side == PY_SSL_SERVER and (not key_file or not cert_file):
  560. raise ssl_error(space, "Both the key & certificate files "
  561. "must be specified for server-side operation")
  562. # set up context
  563. if protocol == PY_SSL_VERSION_TLS1:
  564. method = libssl_TLSv1_method()
  565. elif protocol == PY_SSL_VERSION_SSL3:
  566. method = libssl_SSLv3_method()
  567. elif protocol == PY_SSL_VERSION_SSL2 and not OPENSSL_NO_SSL2:
  568. method = libssl_SSLv2_method()
  569. elif protocol == PY_SSL_VERSION_SSL23:
  570. method = libssl_SSLv23_method()
  571. else:
  572. raise ssl_error(space, "Invalid SSL protocol variant specified")
  573. ss.ctx = libssl_SSL_CTX_new(method)
  574. if not ss.ctx:
  575. raise ssl_error(space, "Could not create SSL context")
  576. if ciphers:
  577. ret = libssl_SSL_CTX_set_cipher_list(ss.ctx, ciphers)
  578. if ret == 0:
  579. raise ssl_error(space, "No cipher can be selected.")
  580. if cert_mode != PY_SSL_CERT_NONE:
  581. if not cacerts_file:
  582. raise ssl_error(space,
  583. "No root certificates specified for "
  584. "verification of other-side certificates.")
  585. ret = libssl_SSL_CTX_load_verify_locations(ss.ctx, cacerts_file, None)
  586. if ret != 1:
  587. raise _ssl_seterror(space, None, 0)
  588. if key_file:
  589. ret = libssl_SSL_CTX_use_PrivateKey_file(ss.ctx, key_file,
  590. SSL_FILETYPE_PEM)
  591. if ret < 1:
  592. raise ssl_error(space, "SSL_CTX_use_PrivateKey_file error")
  593. ret = libssl_SSL_CTX_use_certificate_chain_file(ss.ctx, cert_file)
  594. if ret < 1:
  595. raise ssl_error(space, "SSL_CTX_use_certificate_chain_file error")
  596. # ssl compatibility
  597. libssl_SSL_CTX_set_options(ss.ctx,
  598. SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)
  599. verification_mode = SSL_VERIFY_NONE
  600. if cert_mode == PY_SSL_CERT_OPTIONAL:
  601. verification_mode = SSL_VERIFY_PEER
  602. elif cert_mode == PY_SSL_CERT_REQUIRED:
  603. verification_mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT
  604. libssl_SSL_CTX_set_verify(ss.ctx, verification_mode, None)
  605. ss.ssl = libssl_SSL_new(ss.ctx) # new ssl struct
  606. libssl_SSL_set_fd(ss.ssl, sock_fd) # set the socket for SSL
  607. libssl_SSL_set_mode(ss.ssl, SSL_MODE_AUTO_RETRY)
  608. # If the socket is in non-blocking mode or timeout mode, set the BIO
  609. # to non-blocking mode (blocking is the default)
  610. if has_timeout:
  611. # Set both the read and write BIO's to non-blocking mode
  612. libssl_BIO_set_nbio(libssl_SSL_get_rbio(ss.ssl), 1)
  613. libssl_BIO_set_nbio(libssl_SSL_get_wbio(ss.ssl), 1)
  614. libssl_SSL_set_connect_state(ss.ssl)
  615. if side == PY_SSL_CLIENT:
  616. libssl_SSL_set_connect_state(ss.ssl)
  617. else:
  618. libssl_SSL_set_accept_state(ss.ssl)
  619. ss.w_socket = w_sock
  620. return ss
  621. def check_socket_and_wait_for_timeout(space, w_sock, writing):
  622. """If the socket has a timeout, do a select()/poll() on the socket.
  623. The argument writing indicates the direction.
  624. Returns one of the possibilities in the timeout_state enum (above)."""
  625. w_timeout = space.call_method(w_sock, "gettimeout")
  626. if space.is_w(w_timeout, space.w_None):
  627. return SOCKET_IS_BLOCKING
  628. elif space.float_w(w_timeout) == 0.0:
  629. return SOCKET_IS_NONBLOCKING
  630. sock_timeout = space.float_w(w_timeout)
  631. sock_fd = space.int_w(space.call_method(w_sock, "fileno"))
  632. # guard against closed socket
  633. if sock_fd < 0:
  634. return SOCKET_HAS_BEEN_CLOSED
  635. # see if the socket is ready
  636. # Prefer poll, if available, since you can poll() any fd
  637. # which can't be done with select().
  638. if HAVE_RPOLL:
  639. if writing:
  640. fddict = {sock_fd: rpoll.POLLOUT}
  641. else:
  642. fddict = {sock_fd: rpoll.POLLIN}
  643. # socket's timeout is in seconds, poll's timeout in ms
  644. timeout = int(sock_timeout * 1000 + 0.5)
  645. ready = rpoll.poll(fddict, timeout)
  646. else:
  647. if MAX_FD_SIZE is not None and sock_fd >= MAX_FD_SIZE:
  648. return SOCKET_TOO_LARGE_FOR_SELECT
  649. if writing:
  650. r, w, e = rpoll.select([], [sock_fd], [], sock_timeout)
  651. ready = w
  652. else:
  653. r, w, e = rpoll.select([sock_fd], [], [], sock_timeout)
  654. ready = r
  655. if ready:
  656. return SOCKET_OPERATION_OK
  657. else:
  658. return SOCKET_HAS_TIMED_OUT
  659. def _ssl_seterror(space, ss, ret):
  660. assert ret <= 0
  661. if ss and ss.ssl:
  662. err = libssl_SSL_get_error(ss.ssl, ret)
  663. else:
  664. err = SSL_ERROR_SSL
  665. errstr = ""
  666. errval = 0
  667. if err == SSL_ERROR_ZERO_RETURN:
  668. errstr = "TLS/SSL connection has been closed"
  669. errval = PY_SSL_ERROR_ZERO_RETURN
  670. elif err == SSL_ERROR_WANT_READ:
  671. errstr = "The operation did not complete (read)"
  672. errval = PY_SSL_ERROR_WANT_READ
  673. elif err == SSL_ERROR_WANT_WRITE:
  674. errstr = "The operation did not complete (write)"
  675. errval = PY_SSL_ERROR_WANT_WRITE
  676. elif err == SSL_ERROR_WANT_X509_LOOKUP:
  677. errstr = "The operation did not complete (X509 lookup)"
  678. errval = PY_SSL_ERROR_WANT_X509_LOOKUP
  679. elif err == SSL_ERROR_WANT_CONNECT:
  680. errstr = "The operation did not complete (connect)"
  681. errval = PY_SSL_ERROR_WANT_CONNECT
  682. elif err == SSL_ERROR_SYSCALL:
  683. e = libssl_ERR_get_error()
  684. if e == 0:
  685. if ret == 0 or space.is_w(ss.w_socket, space.w_None):
  686. errstr = "EOF occurred in violation of protocol"
  687. errval = PY_SSL_ERROR_EOF
  688. elif ret == -1:
  689. # the underlying BIO reported an I/0 error
  690. error = rsocket.last_error()
  691. return interp_socket.converted_error(space, error)
  692. else:
  693. errstr = "Some I/O error occurred"
  694. errval = PY_SSL_ERROR_SYSCALL
  695. else:
  696. errstr = rffi.charp2str(libssl_ERR_error_string(e, None))
  697. errval = PY_SSL_ERROR_SYSCALL
  698. elif err == SSL_ERROR_SSL:
  699. e = libssl_ERR_get_error()
  700. errval = PY_SSL_ERROR_SSL
  701. if e != 0:
  702. errstr = rffi.charp2str(libssl_ERR_error_string(e, None))
  703. else:
  704. errstr = "A failure in the SSL library occurred"
  705. else:
  706. errstr = "Invalid error code"
  707. errval = PY_SSL_ERROR_INVALID_ERROR_CODE
  708. return ssl_error(space, errstr, errval)
  709. @unwrap_spec(side=int, cert_mode=int, protocol=int)
  710. def sslwrap(space, w_socket, side, w_key_file=None, w_cert_file=None,
  711. cert_mode=PY_SSL_CERT_NONE, protocol=PY_SSL_VERSION_SSL23,
  712. w_cacerts_file=None, w_ciphers=None):
  713. """sslwrap(socket, side, [keyfile, certfile]) -> sslobject"""
  714. return space.wrap(new_sslobject(
  715. space, w_socket, side, w_key_file, w_cert_file,
  716. cert_mode, protocol,
  717. w_cacerts_file, w_ciphers))
  718. class Cache:
  719. def __init__(self, space):
  720. w_socketerror = interp_socket.get_error(space, "error")
  721. self.w_error = space.new_exception_class(
  722. "_ssl.SSLError", w_socketerror)
  723. def get_error(space):
  724. return space.fromcache(Cache).w_error
  725. @unwrap_spec(filename=str, verbose=bool)
  726. def _test_decode_cert(space, filename, verbose=True):
  727. cert = libssl_BIO_new(libssl_BIO_s_file())
  728. if not cert:
  729. raise ssl_error(space, "Can't malloc memory to read file")
  730. try:
  731. if libssl_BIO_read_filename(cert, filename) <= 0:
  732. raise ssl_error(space, "Can't open file")
  733. x = libssl_PEM_read_bio_X509_AUX(cert, None, None, None)
  734. if not x:
  735. raise ssl_error(space, "Error decoding PEM-encoded file")
  736. try:
  737. return _decode_certificate(space, x, verbose)
  738. finally:
  739. libssl_X509_free(x)
  740. finally:
  741. libssl_BIO_free(cert)
  742. # this function is needed to perform locking on shared data
  743. # structures. (Note that OpenSSL uses a number of global data
  744. # structures that will be implicitly shared whenever multiple threads
  745. # use OpenSSL.) Multi-threaded applications will crash at random if
  746. # it is not set.
  747. #
  748. # locking_function() must be able to handle up to CRYPTO_num_locks()
  749. # different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and
  750. # releases it otherwise.
  751. #
  752. # filename and line are the file number of the function setting the
  753. # lock. They can be useful for debugging.
  754. _ssl_locks = []
  755. def _ssl_thread_locking_function(mode, n, filename, line):
  756. n = intmask(n)
  757. if n < 0 or n >= len(_ssl_locks):
  758. return
  759. if intmask(mode) & CRYPTO_LOCK:
  760. _ssl_locks[n].acquire(True)
  761. else:
  762. _ssl_locks[n].release()
  763. def _ssl_thread_id_function():
  764. from pypy.module.thread import ll_thread
  765. return rffi.cast(rffi.LONG, ll_thread.get_ident())
  766. def setup_ssl_threads():
  767. from pypy.module.thread import ll_thread
  768. for i in range(libssl_CRYPTO_num_locks()):
  769. _ssl_locks.append(ll_thread.allocate_lock())
  770. libssl_CRYPTO_set_locking_callback(_ssl_thread_locking_function)
  771. libssl_CRYPTO_set_id_callback(_ssl_thread_id_function)