| 1 |
import os |
| 2 |
import pathlib |
| 3 |
import sys |
| 4 |
import time |
| 5 |
import _thread |
| 6 |
import threading |
| 7 |
import warnings |
| 8 |
import weakref |
| 9 |
import __pypy__ |
| 10 |
|
| 11 |
try: |
| 12 |
from _pypy_openssl import ffi |
| 13 |
from _pypy_openssl import lib |
| 14 |
except ImportError as e: |
| 15 |
import os |
| 16 |
msg = "\n\nThe _ssl cffi module either doesn't exist or is incompatible with your machine's shared libraries.\n" + \ |
| 17 |
"If you have a compiler installed, you can try to rebuild it by running:\n" + \ |
| 18 |
"cd %s\n" % os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) + \ |
| 19 |
"%s _ssl_build.py\n" % sys.executable |
| 20 |
raise ModuleNotFoundError(str(e) + msg, name='_cffi_ssl') |
| 21 |
|
| 22 |
from _cffi_ssl._stdssl.certificate import (_test_decode_cert, |
| 23 |
_decode_certificate, _certificate_to_der, _PySSL_CertificateFromX509Stack, |
| 24 |
newCertificate) |
| 25 |
from _cffi_ssl._stdssl.utility import (_str_with_len, _bytes_with_len, |
| 26 |
_str_to_ffi_buffer, _str_from_buf, _cstr_decode_fs) |
| 27 |
from _cffi_ssl._stdssl.error import ( |
| 28 |
ssl_error, pyssl_error, SSLError, SSLCertVerificationError, |
| 29 |
SSLZeroReturnError, SSLWantReadError, SSLWantWriteError, SSLSyscallError, |
| 30 |
SSLEOFError) |
| 31 |
from _cffi_ssl._stdssl.error import (SSL_ERROR_NONE, |
| 32 |
SSL_ERROR_SSL, SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE, |
| 33 |
SSL_ERROR_WANT_X509_LOOKUP, SSL_ERROR_SYSCALL, |
| 34 |
SSL_ERROR_ZERO_RETURN, SSL_ERROR_WANT_CONNECT, |
| 35 |
SSL_ERROR_EOF, SSL_ERROR_NO_SOCKET, SSL_ERROR_INVALID_ERROR_CODE, |
| 36 |
pyerr_write_unraisable) |
| 37 |
from _cffi_ssl._stdssl.certificate import PY_SSL_ENCODING_PEM as ENCODING_PEM |
| 38 |
from _cffi_ssl._stdssl.certificate import PY_SSL_ENCODING_DER as ENCODING_DER |
| 39 |
from _cffi_ssl._stdssl import error |
| 40 |
from _pypy_util_cffi import StackNew |
| 41 |
from select import select |
| 42 |
import socket |
| 43 |
from enum import IntEnum as _IntEnum |
| 44 |
|
| 45 |
if sys.platform == 'win32': |
| 46 |
from _cffi_ssl._stdssl.win32_extra import enum_certificates, enum_crls |
| 47 |
HAVE_POLL = False |
| 48 |
else: |
| 49 |
from select import poll, POLLIN, POLLOUT |
| 50 |
HAVE_POLL = True |
| 51 |
|
| 52 |
_MAX_INT = 2147483647 |
| 53 |
OPENSSL_VERSION = ffi.string(lib.OPENSSL_VERSION_TEXT).decode('utf-8') |
| 54 |
OPENSSL_VERSION_NUMBER = lib.OPENSSL_VERSION_NUMBER |
| 55 |
ver = OPENSSL_VERSION_NUMBER |
| 56 |
ver, status = divmod(ver, 16) |
| 57 |
ver, patch = divmod(ver, 256) |
| 58 |
ver, fix = divmod(ver, 256) |
| 59 |
ver, minor = divmod(ver, 256) |
| 60 |
ver, major = divmod(ver, 256) |
| 61 |
version_info = (major, minor, fix, patch, status) |
| 62 |
OPENSSL_VERSION_INFO = version_info |
| 63 |
_OPENSSL_API_VERSION = version_info |
| 64 |
del ver, version_info, status, patch, fix, minor, major |
| 65 |
|
| 66 |
HAS_ECDH = True |
| 67 |
HAS_SNI = bool(lib.Cryptography_HAS_TLSEXT_HOSTNAME) |
| 68 |
HAS_ALPN = bool(lib.Cryptography_HAS_ALPN) |
| 69 |
HAS_NPN = False |
| 70 |
HAS_CTRL_GET_MAX_PROTO_VERSION = bool(lib.Cryptography_HAS_CTRL_GET_MAX_PROTO_VERSION) |
| 71 |
HAS_TLS_UNIQUE = True |
| 72 |
|
| 73 |
CLIENT = 0 |
| 74 |
SERVER = 1 |
| 75 |
|
| 76 |
VERIFY_DEFAULT = 0 |
| 77 |
VERIFY_CRL_CHECK_LEAF = lib.X509_V_FLAG_CRL_CHECK |
| 78 |
VERIFY_CRL_CHECK_CHAIN = lib.X509_V_FLAG_CRL_CHECK | lib.X509_V_FLAG_CRL_CHECK_ALL |
| 79 |
VERIFY_X509_STRICT = lib.X509_V_FLAG_X509_STRICT |
| 80 |
VERIFY_ALLOW_PROXY_CERTS = lib.X509_V_FLAG_ALLOW_PROXY_CERTS |
| 81 |
VERIFY_X509_TRUSTED_FIRST = lib.X509_V_FLAG_TRUSTED_FIRST |
| 82 |
if lib.Cryptography_HAS_X509_V_FLAG_PARTIAL_CHAIN: |
| 83 |
VERIFY_X509_PARTIAL_CHAIN = lib.X509_V_FLAG_PARTIAL_CHAIN |
| 84 |
if lib.Cryptography_HAS_X509_CHECK_FLAG_NEVER_CHECK_SUBJECT: |
| 85 |
HOSTFLAG_NEVER_CHECK_SUBJECT = lib.X509_CHECK_FLAG_NEVER_CHECK_SUBJECT |
| 86 |
|
| 87 |
CERT_NONE = 0 |
| 88 |
CERT_OPTIONAL = 1 |
| 89 |
CERT_REQUIRED = 2 |
| 90 |
|
| 91 |
for name in dir(lib): |
| 92 |
if name.startswith('SSL_OP'): |
| 93 |
value = getattr(lib, name) |
| 94 |
if value != 0: |
| 95 |
globals()[name[4:]] = getattr(lib, name) |
| 96 |
|
| 97 |
OP_ALL = lib.SSL_OP_ALL & ~lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS |
| 98 |
OP_NO_SSLv2 = lib.SSL_OP_NO_SSLv2 |
| 99 |
OP_NO_SSLv3 = lib.SSL_OP_NO_SSLv3 |
| 100 |
OP_NO_TLSv1_3 = lib.SSL_OP_NO_TLSv1_3 |
| 101 |
if OPENSSL_VERSION_INFO > (1, 1, 0, 0, 0): |
| 102 |
|
| 103 |
|
| 104 |
OP_ENABLE_MIDDLEBOX_COMPAT = 0x00100000 |
| 105 |
OP_NO_RENEGOTIATION = 0x40000000 |
| 106 |
|
| 107 |
|
| 108 |
SSL_CLIENT = 0 |
| 109 |
SSL_SERVER = 1 |
| 110 |
|
| 111 |
SSL_CB_MAXLEN=128 |
| 112 |
|
| 113 |
if lib.Cryptography_HAS_SSL2: |
| 114 |
PROTOCOL_SSLv2 = 0 |
| 115 |
SSLv3_method_ok = False |
| 116 |
if lib.Cryptography_HAS_SSL3_METHOD: |
| 117 |
|
| 118 |
ctx = lib.SSL_CTX_new(lib.SSLv3_method()) |
| 119 |
if ctx: |
| 120 |
PROTOCOL_SSLv3 = 1 |
| 121 |
lib.SSL_CTX_free(ctx) |
| 122 |
SSLv3_method_ok = True |
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
|
| 132 |
|
| 133 |
|
| 134 |
|
| 135 |
|
| 136 |
PY_SSL_DEFAULT_CIPHER_STRING = b"@SECLEVEL=2:ECDH+AESGCM:ECDH+CHACHA20:ECDH+AES:DHE+AES:!aNULL:!eNULL:!aDSS:!SHA1:!AESCCM" |
| 137 |
|
| 138 |
PROTOCOL_SSLv23 = 2 |
| 139 |
PROTOCOL_TLS = PROTOCOL_SSLv23 |
| 140 |
PROTOCOL_TLSv1 = 3 |
| 141 |
PROTOCOL_TLSv1 = 3 |
| 142 |
PROTOCOL_TLSv1_1 = 4 |
| 143 |
PROTOCOL_TLSv1_2 = 5 |
| 144 |
PROTOCOL_TLS_CLIENT = 0x10 |
| 145 |
PROTOCOL_TLS_SERVER = 0x11 |
| 146 |
HAS_SSLv2 = bool(lib.Cryptography_HAS_SSL2) |
| 147 |
HAS_SSLv3 = SSLv3_method_ok |
| 148 |
HAS_TLSv1 = True |
| 149 |
HAS_TLSv1_1 = bool(lib.Cryptography_HAS_TLSv1_1) |
| 150 |
HAS_TLSv1_2 = bool(lib.Cryptography_HAS_TLSv1_2) |
| 151 |
HAS_TLSv1_3 = bool(lib.Cryptography_HAS_TLSv1_3) |
| 152 |
|
| 153 |
|
| 154 |
PROTO_MINIMUM_SUPPORTED = -2 |
| 155 |
PROTO_MAXIMUM_SUPPORTED = -1 |
| 156 |
PROTO_SSLv3 = 0x300 |
| 157 |
PROTO_TLSv1 = 0x301 |
| 158 |
PROTO_TLSv1_1 = 0x302 |
| 159 |
PROTO_TLSv1_2 = 0x303 |
| 160 |
PROTO_TLSv1_3 = 0x304 |
| 161 |
|
| 162 |
|
| 163 |
|
| 164 |
|
| 165 |
if HAS_SSLv3: |
| 166 |
PROTO_MINIMUM_AVAILABLE = PROTO_SSLv3 |
| 167 |
elif HAS_TLSv1: |
| 168 |
PROTO_MINIMUM_AVAILABLE = PROTO_TLSv1 |
| 169 |
elif HAS_TLSv1_1: |
| 170 |
PROTO_MINIMUM_AVAILABLE = PROTO_TLSv1_1 |
| 171 |
elif HAS_TLSv1_2: |
| 172 |
PROTO_MINIMUM_AVAILABLE = PROTO_TLSv1_2 |
| 173 |
elif HAS_TLSv1_3: |
| 174 |
PROTO_MINIMUM_AVAILABLE = PROTO_TLSv1_3 |
| 175 |
else: |
| 176 |
raise ValueError("PROTO_MINIMUM_AVAILABLE not found") |
| 177 |
|
| 178 |
if HAS_TLSv1_3: |
| 179 |
PROTO_MAXIMUM_AVAILABLE = PROTO_TLSv1_3 |
| 180 |
elif HAS_TLSv1_2: |
| 181 |
PROTO_MAXIMUM_AVAILABLE = PROTO_TLSv1_2 |
| 182 |
elif HAS_TLSv1_1: |
| 183 |
PROTO_MAXIMUM_AVAILABLE = PROTO_TLSv1_1 |
| 184 |
elif HAS_TLSv1: |
| 185 |
PROTO_MAXIMUM_AVAILABLE = PROTO_TLSv1 |
| 186 |
elif HAS_SSLv3: |
| 187 |
PROTO_MAXIMUM_AVAILABLE = PROTO_SSLv3 |
| 188 |
else: |
| 189 |
raise ValueError("PROTO_MAXIMUM_AVAILABLE not found") |
| 190 |
|
| 191 |
|
| 192 |
_PROTOCOL_NAMES = (name for name in dir(lib) if name.startswith('PROTOCOL_')) |
| 193 |
|
| 194 |
_IntEnum._convert_('_SSLMethod', __name__, |
| 195 |
lambda name: name.startswith('PROTOCOL_')) |
| 196 |
|
| 197 |
if HAS_TLS_UNIQUE: |
| 198 |
CHANNEL_BINDING_TYPES = ['tls-unique'] |
| 199 |
else: |
| 200 |
CHANNEL_BINDING_TYPES = [] |
| 201 |
|
| 202 |
for name in error.SSL_AD_NAMES: |
| 203 |
lib_attr = 'SSL_AD_' + name |
| 204 |
attr = 'ALERT_DESCRIPTION_' + name |
| 205 |
if hasattr(lib, lib_attr): |
| 206 |
globals()[attr] = getattr(lib, lib_attr) |
| 207 |
|
| 208 |
|
| 209 |
_DEFAULT_CIPHERS = "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK" |
| 210 |
|
| 211 |
|
| 212 |
lib.SSL_load_error_strings() |
| 213 |
lib.SSL_library_init() |
| 214 |
if (lib.Cryptography_HAS_LOCKING_CALLBACKS and |
| 215 |
lib.CRYPTO_get_locking_callback() == ffi.NULL): |
| 216 |
lib.Cryptography_setup_ssl_threads() |
| 217 |
lib.OpenSSL_add_all_algorithms() |
| 218 |
|
| 219 |
|
| 220 |
class ErrState(): |
| 221 |
ws = 0 |
| 222 |
c = 0 |
| 223 |
ssl = 0 |
| 224 |
|
| 225 |
NO_ERROR = ErrState() |
| 226 |
|
| 227 |
|
| 228 |
def _PySSL_errno(failed, ssl, retcode): |
| 229 |
if failed: |
| 230 |
err = ErrState() |
| 231 |
if sys.platform == 'win32': |
| 232 |
err.ws = lib.WSAGetLastError() |
| 233 |
err.c = ffi.errno |
| 234 |
err.ssl = lib.SSL_get_error(ssl, retcode) |
| 235 |
return err |
| 236 |
return NO_ERROR |
| 237 |
|
| 238 |
def check_signals(): |
| 239 |
|
| 240 |
|
| 241 |
pass |
| 242 |
|
| 243 |
def _socket_timeout(s): |
| 244 |
if s is None: |
| 245 |
return 0.0 |
| 246 |
t = s.gettimeout() |
| 247 |
if t is None: |
| 248 |
return -1.0 |
| 249 |
return t |
| 250 |
|
| 251 |
class PasswordInfo(object): |
| 252 |
callable = None |
| 253 |
password = None |
| 254 |
operationerror = None |
| 255 |
handle = None |
| 256 |
PWINFO_STORAGE = {} |
| 257 |
|
| 258 |
def _Cryptography_pem_password_cb(buf, size, rwflag, userdata): |
| 259 |
pw_info = ffi.from_handle(userdata) |
| 260 |
|
| 261 |
password = pw_info.password |
| 262 |
|
| 263 |
if pw_info.callable: |
| 264 |
try: |
| 265 |
password = pw_info.callable() |
| 266 |
except Exception as e: |
| 267 |
pw_info.operationerror = e |
| 268 |
return 0 |
| 269 |
|
| 270 |
if not isinstance(password, (str, bytes, bytearray)): |
| 271 |
pw_info.operationerror = TypeError("password callback must return a string") |
| 272 |
return 0 |
| 273 |
|
| 274 |
password = _str_to_ffi_buffer(password) |
| 275 |
|
| 276 |
if (len(password) > size): |
| 277 |
pw_info.operationerror = ValueError("password cannot be longer than %d bytes" % size) |
| 278 |
return 0 |
| 279 |
|
| 280 |
ffi.memmove(buf, password, len(password)) |
| 281 |
return len(password) |
| 282 |
|
| 283 |
if 0: |
| 284 |
ffi.def_extern(_Cryptography_pem_password_cb) |
| 285 |
Cryptography_pem_password_cb = lib.Cryptography_pem_password_cb |
| 286 |
else: |
| 287 |
Cryptography_pem_password_cb = ffi.callback("int(char*,int,int,void*)")(_Cryptography_pem_password_cb) |
| 288 |
|
| 289 |
if hasattr(time, 'monotonic'): |
| 290 |
def _monotonic_clock(): |
| 291 |
return time.monotonic() |
| 292 |
else: |
| 293 |
def _monotonic_clock(): |
| 294 |
return time.clock_gettime(time.CLOCK_MONOTONIC) |
| 295 |
|
| 296 |
def _ssl_select(sock, writing, timeout): |
| 297 |
if HAVE_POLL: |
| 298 |
p = poll() |
| 299 |
|
| 300 |
|
| 301 |
if sock is None or timeout == 0: |
| 302 |
return SOCKET_IS_NONBLOCKING |
| 303 |
elif timeout < 0: |
| 304 |
t = _socket_timeout(sock) |
| 305 |
if t > 0: |
| 306 |
return SOCKET_HAS_TIMED_OUT |
| 307 |
else: |
| 308 |
return SOCKET_IS_BLOCKING |
| 309 |
|
| 310 |
|
| 311 |
if sock.fileno() < 0: |
| 312 |
return SOCKET_HAS_BEEN_CLOSED |
| 313 |
|
| 314 |
|
| 315 |
|
| 316 |
if HAVE_POLL: |
| 317 |
p.register(sock.fileno(), POLLOUT if writing else POLLIN) |
| 318 |
|
| 319 |
rc = len(p.poll(timeout * 1000.0)) |
| 320 |
else: |
| 321 |
|
| 322 |
fd = sock.fileno() |
| 323 |
|
| 324 |
|
| 325 |
if writing: |
| 326 |
rr, wr, xr = select([],[fd],[], timeout) |
| 327 |
else: |
| 328 |
rr, wr, xr = select([fd],[],[], timeout) |
| 329 |
rc = len(rr) + len(wr) |
| 330 |
if rc != 0: |
| 331 |
return SOCKET_OPERATION_OK |
| 332 |
return SOCKET_HAS_TIMED_OUT |
| 333 |
|
| 334 |
SOCKET_IS_NONBLOCKING = 0 |
| 335 |
SOCKET_IS_BLOCKING = 1 |
| 336 |
SOCKET_HAS_TIMED_OUT = 2 |
| 337 |
SOCKET_HAS_BEEN_CLOSED = 3 |
| 338 |
SOCKET_TOO_LARGE_FOR_SELECT = 4 |
| 339 |
SOCKET_OPERATION_OK = 5 |
| 340 |
|
| 341 |
class _SSLSocket(object): |
| 342 |
|
| 343 |
@staticmethod |
| 344 |
def _new__ssl_socket(sslctx, sock, socket_type, server_hostname, owner, |
| 345 |
session, inbio, outbio): |
| 346 |
self = _SSLSocket(sslctx) |
| 347 |
ctx = sslctx.ctx |
| 348 |
self.owner = None |
| 349 |
|
| 350 |
if (socket_type == SSL_SERVER and sslctx.protocol == PROTOCOL_TLS_CLIENT): |
| 351 |
raise ssl_error("Cannot create a server socket with a " |
| 352 |
"PROTOCOL_TLS_CLIENT context", 0) |
| 353 |
if (socket_type == SSL_CLIENT and sslctx.protocol == PROTOCOL_TLS_SERVER): |
| 354 |
raise ssl_error("Cannot create a client socket with a " |
| 355 |
"PROTOCOL_TLS_SERVER context", 0) |
| 356 |
|
| 357 |
if server_hostname: |
| 358 |
self.server_hostname = server_hostname.decode('ascii', 'strict') |
| 359 |
if '\x00' in self.server_hostname: |
| 360 |
raise TypeError("argument must be encoded string without null " |
| 361 |
"bytes, not {}".format(type(server_hostname))) |
| 362 |
else: |
| 363 |
self.server_hostname = None |
| 364 |
|
| 365 |
lib.ERR_clear_error() |
| 366 |
self.ssl = ssl = ffi.gc(lib.SSL_new(ctx), lib.SSL_free) |
| 367 |
|
| 368 |
|
| 369 |
if OPENSSL_VERSION_INFO < (1, 1, 1, 12): |
| 370 |
params = lib.SSL_CTX_get0_param(ctx) |
| 371 |
lib.X509_VERIFY_PARAM_set_hostflags(params, sslctx.hostflags); |
| 372 |
|
| 373 |
self._app_data_handle = ffi.new_handle(self) |
| 374 |
lib.SSL_set_app_data(ssl, ffi.cast("char*", self._app_data_handle)) |
| 375 |
if sock: |
| 376 |
lib.SSL_set_fd(ssl, sock.fileno()) |
| 377 |
else: |
| 378 |
|
| 379 |
|
| 380 |
|
| 381 |
lib.BIO_up_ref(inbio.bio); |
| 382 |
lib.BIO_up_ref(outbio.bio); |
| 383 |
lib.SSL_set_bio(self.ssl, inbio.bio, outbio.bio) |
| 384 |
|
| 385 |
mode = lib.SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
| 386 |
mode |= lib.SSL_MODE_AUTO_RETRY |
| 387 |
lib.SSL_set_mode(ssl, mode) |
| 388 |
|
| 389 |
if HAS_TLSv1_3: |
| 390 |
if sslctx._post_handshake_auth == 1: |
| 391 |
if socket_type == SSL_SERVER: |
| 392 |
|
| 393 |
|
| 394 |
|
| 395 |
mode = lib.SSL_get_verify_mode(self.ssl) |
| 396 |
if (mode & lib.SSL_VERIFY_PEER): |
| 397 |
verify_cb = lib.SSL_get_verify_callback(self.ssl) |
| 398 |
mode |= lib.SSL_VERIFY_POST_HANDSHAKE |
| 399 |
lib.SSL_set_verify(ssl, mode, verify_cb) |
| 400 |
else: |
| 401 |
lib.SSL_set_post_handshake_auth(ssl, 1) |
| 402 |
|
| 403 |
if server_hostname is not None: |
| 404 |
self._ssl_configure_hostname(server_hostname) |
| 405 |
|
| 406 |
|
| 407 |
|
| 408 |
|
| 409 |
|
| 410 |
timeout = _socket_timeout(sock) |
| 411 |
if sock and timeout >= 0: |
| 412 |
lib.BIO_set_nbio(lib.SSL_get_rbio(ssl), 1) |
| 413 |
lib.BIO_set_nbio(lib.SSL_get_wbio(ssl), 1) |
| 414 |
|
| 415 |
if socket_type == SSL_CLIENT: |
| 416 |
lib.SSL_set_connect_state(ssl) |
| 417 |
else: |
| 418 |
lib.SSL_set_accept_state(ssl) |
| 419 |
self.socket_type = socket_type |
| 420 |
|
| 421 |
if sock: |
| 422 |
self.socket = weakref.ref(sock) |
| 423 |
|
| 424 |
if owner is not None: |
| 425 |
self.owner = owner |
| 426 |
if session is not None: |
| 427 |
self.session = session |
| 428 |
|
| 429 |
return self |
| 430 |
|
| 431 |
def __init__(self, sslctx): |
| 432 |
self.ctx = sslctx |
| 433 |
self.ssl = ffi.NULL |
| 434 |
self.shutdown_seen_zero = 0 |
| 435 |
self._owner = None |
| 436 |
self.server_hostname = None |
| 437 |
self.socket = None |
| 438 |
|
| 439 |
def _ssl_configure_hostname(self, server_hostname): |
| 440 |
|
| 441 |
|
| 442 |
|
| 443 |
length = len(server_hostname) |
| 444 |
if length == 0 or server_hostname[0] == '.': |
| 445 |
raise ValueError("server_hostname cannot be an empty string or " |
| 446 |
"start with a leading dot.") |
| 447 |
|
| 448 |
|
| 449 |
ip = lib.a2i_IPADDRESS(server_hostname) |
| 450 |
if not ip: |
| 451 |
lib.ERR_clear_error() |
| 452 |
if not lib.SSL_set_tlsext_host_name(self.ssl, server_hostname): |
| 453 |
raise ssl_error(None) |
| 454 |
if self.ctx.check_hostname: |
| 455 |
param = lib.SSL_get0_param(self.ssl) |
| 456 |
if not ip: |
| 457 |
if not lib.X509_VERIFY_PARAM_set1_host( |
| 458 |
param, server_hostname, len(server_hostname)): |
| 459 |
raise ssl_error(None) |
| 460 |
else: |
| 461 |
if not lib.X509_VERIFY_PARAM_set1_ip( |
| 462 |
param, lib.ASN1_STRING_get0_data(ip), lib.ASN1_STRING_length(ip)): |
| 463 |
raise ssl_error(None) |
| 464 |
|
| 465 |
@property |
| 466 |
def owner(self): |
| 467 |
if self._owner is None: |
| 468 |
return None |
| 469 |
return self._owner() |
| 470 |
|
| 471 |
@owner.setter |
| 472 |
def owner(self, value): |
| 473 |
if value is None: |
| 474 |
self._owner = None |
| 475 |
else: |
| 476 |
self._owner = weakref.ref(value) |
| 477 |
|
| 478 |
@property |
| 479 |
def context(self): |
| 480 |
return self.ctx |
| 481 |
|
| 482 |
@context.setter |
| 483 |
def context(self, value): |
| 484 |
""" _setter_context(ctx) |
| 485 |
|
| 486 |
This changes the context associated with the SSLSocket. This is typically |
| 487 |
used from within a callback function set by the sni_callback |
| 488 |
on the SSLContext to change the certificate information associated with the |
| 489 |
SSLSocket before the cryptographic exchange handshake messages |
| 490 |
""" |
| 491 |
if isinstance(value, _SSLContext): |
| 492 |
if not HAS_SNI: |
| 493 |
raise NotImplementedError("setting a socket's " |
| 494 |
"context is not supported by your OpenSSL library") |
| 495 |
self.ctx = value |
| 496 |
lib.SSL_set_SSL_CTX(self.ssl, self.ctx.ctx); |
| 497 |
else: |
| 498 |
raise TypeError("The value must be a SSLContext") |
| 499 |
|
| 500 |
@property |
| 501 |
def server_side(self): |
| 502 |
return self.socket_type == SSL_SERVER |
| 503 |
|
| 504 |
def do_handshake(self): |
| 505 |
sock = self.get_socket_or_connection_gone() |
| 506 |
ssl = self.ssl |
| 507 |
timeout = _socket_timeout(sock) |
| 508 |
if sock: |
| 509 |
nonblocking = timeout >= 0 |
| 510 |
lib.BIO_set_nbio(lib.SSL_get_rbio(ssl), nonblocking) |
| 511 |
lib.BIO_set_nbio(lib.SSL_get_wbio(ssl), nonblocking) |
| 512 |
|
| 513 |
has_timeout = timeout > 0 |
| 514 |
deadline = -1 |
| 515 |
if has_timeout: |
| 516 |
deadline = _monotonic_clock() + timeout; |
| 517 |
|
| 518 |
|
| 519 |
while True: |
| 520 |
|
| 521 |
ret = lib.SSL_do_handshake(ssl) |
| 522 |
err = _PySSL_errno(ret<1, self.ssl, ret) |
| 523 |
|
| 524 |
self.err = err |
| 525 |
|
| 526 |
check_signals() |
| 527 |
|
| 528 |
if has_timeout: |
| 529 |
|
| 530 |
timeout = deadline - _monotonic_clock() |
| 531 |
|
| 532 |
if err.ssl == SSL_ERROR_WANT_READ: |
| 533 |
sockstate = _ssl_select(sock, 0, timeout) |
| 534 |
elif err.ssl == SSL_ERROR_WANT_WRITE: |
| 535 |
sockstate = _ssl_select(sock, 1, timeout) |
| 536 |
else: |
| 537 |
sockstate = SOCKET_OPERATION_OK |
| 538 |
|
| 539 |
if sockstate == SOCKET_HAS_TIMED_OUT: |
| 540 |
raise TimeoutError("The handshake operation timed out") |
| 541 |
elif sockstate == SOCKET_HAS_BEEN_CLOSED: |
| 542 |
raise SSLError("Underlying socket has been closed.") |
| 543 |
elif sockstate == SOCKET_TOO_LARGE_FOR_SELECT: |
| 544 |
raise SSLError("Underlying socket too large for select().") |
| 545 |
elif sockstate == SOCKET_IS_NONBLOCKING: |
| 546 |
break |
| 547 |
if not (err.ssl == SSL_ERROR_WANT_READ or err.ssl == SSL_ERROR_WANT_WRITE): |
| 548 |
break |
| 549 |
if ret < 1: |
| 550 |
raise pyssl_error(self, ret) |
| 551 |
|
| 552 |
return None |
| 553 |
|
| 554 |
def getpeercert(self, binary_mode): |
| 555 |
if not lib.SSL_is_init_finished(self.ssl): |
| 556 |
raise ValueError("handshake not done yet") |
| 557 |
peer_cert = lib.SSL_get_peer_certificate(self.ssl); |
| 558 |
if peer_cert == ffi.NULL: |
| 559 |
return None |
| 560 |
|
| 561 |
if binary_mode: |
| 562 |
|
| 563 |
return _certificate_to_der(peer_cert) |
| 564 |
else: |
| 565 |
verification = lib.SSL_get_verify_mode(self.ssl) |
| 566 |
if (verification & lib.SSL_VERIFY_PEER) == 0: |
| 567 |
return {} |
| 568 |
else: |
| 569 |
return _decode_certificate(peer_cert) |
| 570 |
|
| 571 |
def get_verified_chain(self): |
| 572 |
chain = lib.SSL_get0_verified_chain(self.ssl) |
| 573 |
if not chain: |
| 574 |
return None |
| 575 |
return _PySSL_CertificateFromX509Stack(chain, 1) |
| 576 |
|
| 577 |
def get_unverified_chain(self): |
| 578 |
chain = lib.SSL_get_peer_cert_chain(self.ssl) |
| 579 |
if not chain: |
| 580 |
return None |
| 581 |
retval = _PySSL_CertificateFromX509Stack(chain, 1) |
| 582 |
|
| 583 |
if self.socket_type == SSL_SERVER: |
| 584 |
peer = lib.SSL_get_peer_certificate(self.ssl) |
| 585 |
if not peer: |
| 586 |
peerobj = None |
| 587 |
else: |
| 588 |
try: |
| 589 |
peerobj = newCertificate(peer, 0) |
| 590 |
except ValueError: |
| 591 |
lib.X509_free(peer) |
| 592 |
raise |
| 593 |
retval.insert(0, peerobj) |
| 594 |
return retval |
| 595 |
|
| 596 |
|
| 597 |
|
| 598 |
def write(self, bytestring): |
| 599 |
return self._write_with_length(_str_to_ffi_buffer(bytestring), len(bytestring)) |
| 600 |
|
| 601 |
def _write_with_length(self, b, lgt): |
| 602 |
sock = self.get_socket_or_connection_gone() |
| 603 |
ssl = self.ssl |
| 604 |
|
| 605 |
timeout = _socket_timeout(sock) |
| 606 |
if sock: |
| 607 |
nonblocking = timeout >= 0 |
| 608 |
lib.BIO_set_nbio(lib.SSL_get_rbio(ssl), nonblocking) |
| 609 |
lib.BIO_set_nbio(lib.SSL_get_wbio(ssl), nonblocking) |
| 610 |
|
| 611 |
|
| 612 |
has_timeout = timeout > 0 |
| 613 |
if has_timeout: |
| 614 |
deadline = _monotonic_clock() + timeout |
| 615 |
|
| 616 |
sockstate = _ssl_select(sock, 1, timeout) |
| 617 |
if sockstate == SOCKET_HAS_TIMED_OUT: |
| 618 |
raise TimeoutError("The write operation timed out") |
| 619 |
elif sockstate == SOCKET_HAS_BEEN_CLOSED: |
| 620 |
raise ssl_error("Underlying socket has been closed.") |
| 621 |
elif sockstate == SOCKET_TOO_LARGE_FOR_SELECT: |
| 622 |
raise ssl_error("Underlying socket too large for select().") |
| 623 |
|
| 624 |
count = ffi.new("size_t[1]", [0]) |
| 625 |
while True: |
| 626 |
retval = lib.SSL_write_ex(self.ssl, b, lgt, count) |
| 627 |
err = _PySSL_errno(retval==0, self.ssl, retval) |
| 628 |
self.err = err |
| 629 |
|
| 630 |
check_signals() |
| 631 |
|
| 632 |
if has_timeout: |
| 633 |
timeout = deadline - _monotonic_clock() |
| 634 |
|
| 635 |
if err.ssl == SSL_ERROR_WANT_READ: |
| 636 |
sockstate = _ssl_select(sock, 0, timeout) |
| 637 |
elif err.ssl == SSL_ERROR_WANT_WRITE: |
| 638 |
sockstate = _ssl_select(sock, 1, timeout) |
| 639 |
else: |
| 640 |
sockstate = SOCKET_OPERATION_OK |
| 641 |
|
| 642 |
if sockstate == SOCKET_HAS_TIMED_OUT: |
| 643 |
raise TimeoutError("The write operation timed out") |
| 644 |
elif sockstate == SOCKET_HAS_BEEN_CLOSED: |
| 645 |
raise ssl_error("Underlying socket has been closed.") |
| 646 |
elif sockstate == SOCKET_IS_NONBLOCKING: |
| 647 |
break |
| 648 |
if not (err.ssl == SSL_ERROR_WANT_READ or err.ssl == SSL_ERROR_WANT_WRITE): |
| 649 |
break |
| 650 |
|
| 651 |
if retval ==0: |
| 652 |
raise pyssl_error(self, retval) |
| 653 |
return count[0] |
| 654 |
|
| 655 |
def read(self, length, buffer_into=None): |
| 656 |
if length < 0 and buffer_into is None: |
| 657 |
raise ValueError("size should not be negative") |
| 658 |
|
| 659 |
if buffer_into is None: |
| 660 |
return self._read_no_buf(length) |
| 661 |
return self._read_buf(length, buffer_into) |
| 662 |
|
| 663 |
def _read_no_buf(self, length): |
| 664 |
ssl = self.ssl |
| 665 |
sock = self.get_socket_or_connection_gone() |
| 666 |
|
| 667 |
if length == 0: |
| 668 |
return b"" |
| 669 |
count = ffi.new("size_t[1]", [0]) |
| 670 |
with StackNew("char[]", length) as dest: |
| 671 |
mem = dest |
| 672 |
|
| 673 |
if sock: |
| 674 |
timeout = _socket_timeout(sock) |
| 675 |
nonblocking = timeout >= 0 |
| 676 |
lib.BIO_set_nbio(lib.SSL_get_rbio(ssl), nonblocking) |
| 677 |
lib.BIO_set_nbio(lib.SSL_get_wbio(ssl), nonblocking) |
| 678 |
|
| 679 |
deadline = 0 |
| 680 |
timeout = _socket_timeout(sock) |
| 681 |
|
| 682 |
has_timeout = timeout > 0 |
| 683 |
if has_timeout: |
| 684 |
deadline = _monotonic_clock() + timeout |
| 685 |
|
| 686 |
shutdown = False |
| 687 |
while True: |
| 688 |
retval = lib.SSL_read_ex(self.ssl, mem, length, count) |
| 689 |
err = _PySSL_errno(retval==0, self.ssl, count[0]) |
| 690 |
self.err = err |
| 691 |
|
| 692 |
check_signals() |
| 693 |
|
| 694 |
if has_timeout: |
| 695 |
timeout = deadline - _monotonic_clock() |
| 696 |
|
| 697 |
if err.ssl == SSL_ERROR_WANT_READ: |
| 698 |
sockstate = _ssl_select(sock, 0, timeout) |
| 699 |
elif err.ssl == SSL_ERROR_WANT_WRITE: |
| 700 |
sockstate = _ssl_select(sock, 1, timeout) |
| 701 |
elif err.ssl == SSL_ERROR_ZERO_RETURN and \ |
| 702 |
lib.SSL_get_shutdown(self.ssl) == lib.SSL_RECEIVED_SHUTDOWN: |
| 703 |
count[0] = 0 |
| 704 |
retval = 1 |
| 705 |
break; |
| 706 |
else: |
| 707 |
sockstate = SOCKET_OPERATION_OK |
| 708 |
|
| 709 |
if sockstate == SOCKET_HAS_TIMED_OUT: |
| 710 |
raise TimeoutError("The read operation timed out") |
| 711 |
elif sockstate == SOCKET_IS_NONBLOCKING: |
| 712 |
break |
| 713 |
if not (err.ssl == SSL_ERROR_WANT_READ or err.ssl == SSL_ERROR_WANT_WRITE): |
| 714 |
break |
| 715 |
|
| 716 |
if retval == 0: |
| 717 |
raise pyssl_error(self, retval) |
| 718 |
|
| 719 |
return _bytes_with_len(dest, count[0]) |
| 720 |
|
| 721 |
def _read_buf(self, length, buffer_into): |
| 722 |
ssl = self.ssl |
| 723 |
sock = self.get_socket_or_connection_gone() |
| 724 |
|
| 725 |
mem = ffi.from_buffer(buffer_into) |
| 726 |
max_mem = len(mem) |
| 727 |
if length <= 0 or length > max_mem: |
| 728 |
length = max_mem |
| 729 |
if length > _MAX_INT: |
| 730 |
raise OverflowError("maximum length can't fit in a C 'int'") |
| 731 |
if max_mem == 0: |
| 732 |
return 0 |
| 733 |
|
| 734 |
if sock: |
| 735 |
timeout = _socket_timeout(sock) |
| 736 |
nonblocking = timeout >= 0 |
| 737 |
lib.BIO_set_nbio(lib.SSL_get_rbio(ssl), nonblocking) |
| 738 |
lib.BIO_set_nbio(lib.SSL_get_wbio(ssl), nonblocking) |
| 739 |
|
| 740 |
timeout = _socket_timeout(sock) |
| 741 |
deadline = 0 |
| 742 |
has_timeout = timeout > 0 |
| 743 |
if has_timeout: |
| 744 |
deadline = _monotonic_clock() + timeout |
| 745 |
|
| 746 |
shutdown = False |
| 747 |
count = ffi.new("size_t[1]", [0]) |
| 748 |
while True: |
| 749 |
retval = lib.SSL_read_ex(self.ssl, mem, length, count); |
| 750 |
err = _PySSL_errno(retval==0, self.ssl, count[0]) |
| 751 |
self.err = err |
| 752 |
|
| 753 |
check_signals() |
| 754 |
|
| 755 |
if has_timeout: |
| 756 |
timeout = deadline - _monotonic_clock() |
| 757 |
|
| 758 |
if err.ssl == SSL_ERROR_WANT_READ: |
| 759 |
sockstate = _ssl_select(sock, 0, timeout) |
| 760 |
elif err.ssl == SSL_ERROR_WANT_WRITE: |
| 761 |
sockstate = _ssl_select(sock, 1, timeout) |
| 762 |
elif err.ssl == SSL_ERROR_ZERO_RETURN and \ |
| 763 |
lib.SSL_get_shutdown(self.ssl) == lib.SSL_RECEIVED_SHUTDOWN: |
| 764 |
count[0] = 0 |
| 765 |
retval = 1 |
| 766 |
break; |
| 767 |
else: |
| 768 |
sockstate = SOCKET_OPERATION_OK |
| 769 |
|
| 770 |
if sockstate == SOCKET_HAS_TIMED_OUT: |
| 771 |
raise TimeoutError("The read operation timed out") |
| 772 |
elif sockstate == SOCKET_IS_NONBLOCKING: |
| 773 |
break |
| 774 |
if not (err.ssl == SSL_ERROR_WANT_READ or err.ssl == SSL_ERROR_WANT_WRITE): |
| 775 |
break |
| 776 |
|
| 777 |
if retval == 0: |
| 778 |
raise pyssl_error(self, retval) |
| 779 |
|
| 780 |
return count[0] |
| 781 |
|
| 782 |
if HAS_ALPN: |
| 783 |
def selected_alpn_protocol(self): |
| 784 |
out = ffi.new("const unsigned char **") |
| 785 |
outlen = ffi.new("unsigned int*") |
| 786 |
|
| 787 |
lib.SSL_get0_alpn_selected(self.ssl, out, outlen); |
| 788 |
if out[0] == ffi.NULL: |
| 789 |
return None |
| 790 |
return _str_with_len(out[0], outlen[0]); |
| 791 |
|
| 792 |
def shared_ciphers(self): |
| 793 |
|
| 794 |
|
| 795 |
|
| 796 |
|
| 797 |
|
| 798 |
|
| 799 |
|
| 800 |
|
| 801 |
|
| 802 |
server_ciphers = lib.SSL_get_ciphers(self.ssl) |
| 803 |
if server_ciphers == ffi.NULL: |
| 804 |
return None |
| 805 |
client_ciphers = lib.SSL_get_client_ciphers(self.ssl) |
| 806 |
if client_ciphers == ffi.NULL: |
| 807 |
return None |
| 808 |
res = [] |
| 809 |
count = lib.sk_SSL_CIPHER_num(server_ciphers) |
| 810 |
for i in range(count): |
| 811 |
cipher = lib.sk_SSL_CIPHER_value(server_ciphers, i) |
| 812 |
if lib.sk_SSL_CIPHER_find(client_ciphers, cipher) < 0: |
| 813 |
continue |
| 814 |
tup = cipher_to_tuple(cipher) |
| 815 |
if not tup: |
| 816 |
return None |
| 817 |
res.append(tup) |
| 818 |
return res |
| 819 |
|
| 820 |
def cipher(self): |
| 821 |
if self.ssl == ffi.NULL: |
| 822 |
return None |
| 823 |
current = lib.SSL_get_current_cipher(self.ssl) |
| 824 |
if current == ffi.NULL: |
| 825 |
return None |
| 826 |
return cipher_to_tuple(current) |
| 827 |
|
| 828 |
def compression(self): |
| 829 |
if not lib.Cryptography_HAS_COMPRESSION or self.ssl == ffi.NULL: |
| 830 |
return None |
| 831 |
|
| 832 |
comp_method = lib.SSL_get_current_compression(self.ssl); |
| 833 |
if comp_method == ffi.NULL: |
| 834 |
return None |
| 835 |
short_name = lib.SSL_COMP_get_name(comp_method) |
| 836 |
if short_name == ffi.NULL: |
| 837 |
return None |
| 838 |
return _cstr_decode_fs(short_name) |
| 839 |
|
| 840 |
def version(self): |
| 841 |
if self.ssl == ffi.NULL: |
| 842 |
return None |
| 843 |
if not lib.SSL_is_init_finished(self.ssl): |
| 844 |
return None |
| 845 |
version = _str_from_buf(lib.SSL_get_version(self.ssl)) |
| 846 |
if version == "unknown": |
| 847 |
return None |
| 848 |
return version |
| 849 |
|
| 850 |
def get_socket_or_None(self): |
| 851 |
if self.socket is None: |
| 852 |
return None |
| 853 |
return self.socket() |
| 854 |
|
| 855 |
def get_socket_or_connection_gone(self): |
| 856 |
""" There are three states: |
| 857 |
1) self.socket is None (In C that would mean: self->Socket == NULL) |
| 858 |
2) self.socket() is None (-> The socket is gone) |
| 859 |
3) self.socket() is not None |
| 860 |
This method returns True if there is not weakref object allocated |
| 861 |
""" |
| 862 |
if not self.ssl: |
| 863 |
raise TypeError("requires a valid context") |
| 864 |
if self.socket is None: |
| 865 |
return None |
| 866 |
sock = self.socket() |
| 867 |
if not sock: |
| 868 |
raise ssl_error("Underlying socket connection gone", SSL_ERROR_NO_SOCKET) |
| 869 |
return sock |
| 870 |
|
| 871 |
def shutdown(self): |
| 872 |
sock = None |
| 873 |
nonblocking = False |
| 874 |
ssl = self.ssl |
| 875 |
|
| 876 |
if self.socket is not None: |
| 877 |
|
| 878 |
sock = self.socket() |
| 879 |
if sock is None or sock.fileno() < 0: |
| 880 |
raise ssl_error("Underlying socket connection gone", SSL_ERROR_NO_SOCKET) |
| 881 |
|
| 882 |
timeout = _socket_timeout(sock) |
| 883 |
nonblocking = timeout >= 0 |
| 884 |
lib.BIO_set_nbio(lib.SSL_get_rbio(ssl), nonblocking) |
| 885 |
lib.BIO_set_nbio(lib.SSL_get_wbio(ssl), nonblocking) |
| 886 |
else: |
| 887 |
timeout = 0 |
| 888 |
|
| 889 |
has_timeout = (timeout > 0); |
| 890 |
if has_timeout: |
| 891 |
deadline = _monotonic_clock() + timeout; |
| 892 |
|
| 893 |
zeros = 0 |
| 894 |
|
| 895 |
while True: |
| 896 |
|
| 897 |
|
| 898 |
|
| 899 |
|
| 900 |
|
| 901 |
|
| 902 |
|
| 903 |
|
| 904 |
if self.shutdown_seen_zero: |
| 905 |
lib.SSL_set_read_ahead(self.ssl, 0) |
| 906 |
ret = lib.SSL_shutdown(self.ssl) |
| 907 |
self.err = err = _PySSL_errno(ret<0, self.ssl, ret) |
| 908 |
|
| 909 |
|
| 910 |
if ret > 0: |
| 911 |
break |
| 912 |
if ret == 0: |
| 913 |
|
| 914 |
|
| 915 |
|
| 916 |
zeros += 1 |
| 917 |
if zeros > 1: |
| 918 |
break |
| 919 |
|
| 920 |
self.shutdown_seen_zero = 1 |
| 921 |
continue |
| 922 |
|
| 923 |
if has_timeout: |
| 924 |
timeout = deadline - _monotonic_clock() |
| 925 |
|
| 926 |
|
| 927 |
if err.ssl == SSL_ERROR_WANT_READ: |
| 928 |
sockstate = _ssl_select(sock, 0, timeout) |
| 929 |
elif err.ssl == SSL_ERROR_WANT_WRITE: |
| 930 |
sockstate = _ssl_select(sock, 1, timeout) |
| 931 |
else: |
| 932 |
break |
| 933 |
|
| 934 |
if sockstate == SOCKET_HAS_TIMED_OUT: |
| 935 |
if err.ssl == SSL_ERROR_WANT_READ: |
| 936 |
raise TimeoutError("The read operation timed out") |
| 937 |
else: |
| 938 |
raise TimeoutError("The write operation timed out") |
| 939 |
elif sockstate == SOCKET_TOO_LARGE_FOR_SELECT: |
| 940 |
raise ssl_error("Underlying socket too large for select().") |
| 941 |
elif sockstate != SOCKET_OPERATION_OK: |
| 942 |
|
| 943 |
break; |
| 944 |
|
| 945 |
if ret < 0: |
| 946 |
raise pyssl_error(self, err) |
| 947 |
if sock: |
| 948 |
return sock |
| 949 |
else: |
| 950 |
return None |
| 951 |
|
| 952 |
def get_channel_binding(self, cb_type): |
| 953 |
buf = ffi.new("char[]", SSL_CB_MAXLEN) |
| 954 |
if cb_type == 'tls-unique': |
| 955 |
if lib.SSL_session_reused(self.ssl) ^ self.socket_type: |
| 956 |
length = lib.SSL_get_finished(self.ssl, buf, SSL_CB_MAXLEN) |
| 957 |
else: |
| 958 |
length = lib.SSL_get_peer_finished(self.ssl, buf, SSL_CB_MAXLEN) |
| 959 |
else: |
| 960 |
raise ValueError(f"'{cb_type}' channel binding type not implemented") |
| 961 |
if length == 0: |
| 962 |
return None |
| 963 |
return _bytes_with_len(buf, length) |
| 964 |
|
| 965 |
def verify_client_post_handshake(self): |
| 966 |
|
| 967 |
if not HAS_TLSv1_3: |
| 968 |
raise NotImplementedError("Post-handshake auth is not supported by " |
| 969 |
"your OpenSSL version.") |
| 970 |
err = lib.SSL_verify_client_post_handshake(self.ssl); |
| 971 |
if err == 0: |
| 972 |
raise ssl_error(None) |
| 973 |
|
| 974 |
def pending(self): |
| 975 |
count = lib.SSL_pending(self.ssl) |
| 976 |
if count < 0: |
| 977 |
raise pyssl_error(self, count) |
| 978 |
else: |
| 979 |
return count |
| 980 |
|
| 981 |
def tls_unique_cb(self): |
| 982 |
buf = ffi.new("char[]", SSL_CB_MAXLEN) |
| 983 |
|
| 984 |
if lib.SSL_session_reused(self.ssl) ^ (not self.server_side): |
| 985 |
|
| 986 |
length = lib.SSL_get_finished(self.ssl, buf, SSL_CB_MAXLEN) |
| 987 |
else: |
| 988 |
|
| 989 |
length = lib.SSL_get_peer_finished(self.ssl, buf, SSL_CB_MAXLEN) |
| 990 |
|
| 991 |
|
| 992 |
if length == 0: |
| 993 |
return None |
| 994 |
|
| 995 |
return _bytes_with_len(buf, length) |
| 996 |
|
| 997 |
if HAS_NPN: |
| 998 |
def selected_npn_protocol(self): |
| 999 |
out = ffi.new("unsigned char**") |
| 1000 |
outlen = ffi.new("unsigned int*") |
| 1001 |
lib.SSL_get0_next_proto_negotiated(self.ssl, out, outlen) |
| 1002 |
if (out[0] == ffi.NULL): |
| 1003 |
return None |
| 1004 |
return _str_with_len(out[0], outlen[0]) |
| 1005 |
|
| 1006 |
@property |
| 1007 |
def session(self): |
| 1008 |
"Get / set SSLSession." |
| 1009 |
return SSLSession(self) |
| 1010 |
|
| 1011 |
@session.setter |
| 1012 |
def session(self, value): |
| 1013 |
if not isinstance(value, SSLSession): |
| 1014 |
raise TypeError("Value is not a SSLSession.") |
| 1015 |
if self.ctx.ctx != value._ctx.ctx: |
| 1016 |
raise ValueError("Session refers to a different SSLContext.") |
| 1017 |
if self.socket_type != SSL_CLIENT: |
| 1018 |
raise ValueError("Cannot set session for server-side SSLSocket.") |
| 1019 |
if lib.SSL_is_init_finished(self.ssl): |
| 1020 |
raise ValueError("Cannot set session after handshake.") |
| 1021 |
if not lib.SSL_set_session(self.ssl, value._session): |
| 1022 |
raise pyssl_error(self, 0) |
| 1023 |
|
| 1024 |
@property |
| 1025 |
def session_reused(self): |
| 1026 |
"Was the client session reused during handshake?" |
| 1027 |
return bool(lib.SSL_session_reused(self.ssl)) |
| 1028 |
|
| 1029 |
|
| 1030 |
|
| 1031 |
def _fs_decode(name): |
| 1032 |
return name.decode(sys.getfilesystemencoding()) |
| 1033 |
def _fs_converter(name, argname): |
| 1034 |
""" name must not be None """ |
| 1035 |
if isinstance(name, pathlib.Path): |
| 1036 |
name = str(name) |
| 1037 |
if isinstance(name, str): |
| 1038 |
return name.encode(sys.getfilesystemencoding()) |
| 1039 |
elif isinstance(name, bytes): |
| 1040 |
return bytes(name) |
| 1041 |
raise TypeError(f"{argname} should be a valid filesystem path") |
| 1042 |
|
| 1043 |
|
| 1044 |
def cipher_to_tuple(cipher): |
| 1045 |
ccipher_name = lib.SSL_CIPHER_get_name(cipher) |
| 1046 |
if ccipher_name == ffi.NULL: |
| 1047 |
cipher_name = None |
| 1048 |
else: |
| 1049 |
cipher_name = _str_from_buf(ccipher_name) |
| 1050 |
|
| 1051 |
ccipher_protocol = lib.SSL_CIPHER_get_version(cipher) |
| 1052 |
if ccipher_protocol == ffi.NULL: |
| 1053 |
cipher_protocol = None |
| 1054 |
else: |
| 1055 |
cipher_protocol = _str_from_buf(ccipher_protocol) |
| 1056 |
|
| 1057 |
bits = lib.SSL_CIPHER_get_bits(cipher, ffi.NULL) |
| 1058 |
return (cipher_name, cipher_protocol, bits) |
| 1059 |
|
| 1060 |
def cipher_to_dict(cipher): |
| 1061 |
ccipher_name = lib.SSL_CIPHER_get_name(cipher) |
| 1062 |
buf = ffi.new('char[512]') |
| 1063 |
alg_bits = ffi.new('int[4]') |
| 1064 |
if ccipher_name == ffi.NULL: |
| 1065 |
cipher_name = None |
| 1066 |
else: |
| 1067 |
cipher_name = _str_from_buf(ccipher_name) |
| 1068 |
|
| 1069 |
ccipher_protocol = lib.SSL_CIPHER_get_version(cipher) |
| 1070 |
if ccipher_protocol == ffi.NULL: |
| 1071 |
cipher_protocol = None |
| 1072 |
else: |
| 1073 |
cipher_protocol = _str_from_buf(ccipher_protocol) |
| 1074 |
|
| 1075 |
cipher_id = lib.SSL_CIPHER_get_id(cipher); |
| 1076 |
lib.SSL_CIPHER_description(cipher, buf, 511) |
| 1077 |
description = _str_from_buf(buf) |
| 1078 |
strength_bits = lib.SSL_CIPHER_get_bits(cipher, alg_bits) |
| 1079 |
ret = { |
| 1080 |
'id' : cipher_id, |
| 1081 |
'name' : cipher_name, |
| 1082 |
'protocol' : cipher_protocol, |
| 1083 |
'description' : description, |
| 1084 |
'strength_bits': strength_bits, |
| 1085 |
'alg_bits' : alg_bits[0], |
| 1086 |
} |
| 1087 |
if OPENSSL_VERSION_INFO > (1, 1, 0, 0, 0): |
| 1088 |
aead = lib.SSL_CIPHER_is_aead(cipher) |
| 1089 |
nid = lib.SSL_CIPHER_get_cipher_nid(cipher) |
| 1090 |
skcipher = lib.OBJ_nid2ln(nid) if nid != lib.NID_undef else None |
| 1091 |
nid = lib.SSL_CIPHER_get_digest_nid(cipher); |
| 1092 |
digest = lib.OBJ_nid2ln(nid) if nid != lib.NID_undef else None |
| 1093 |
nid = lib.SSL_CIPHER_get_kx_nid(cipher); |
| 1094 |
kx = lib.OBJ_nid2ln(nid) if nid != lib.NID_undef else None |
| 1095 |
nid = lib.SSL_CIPHER_get_auth_nid(cipher); |
| 1096 |
auth = lib.OBJ_nid2ln(nid) if nid != lib.NID_undef else None |
| 1097 |
ret.update({'aead' : bool(aead), |
| 1098 |
'symmmetric' : skcipher, |
| 1099 |
'digest' : digest, |
| 1100 |
'kea' : kx, |
| 1101 |
'auth' : auth, |
| 1102 |
}) |
| 1103 |
return ret |
| 1104 |
|
| 1105 |
|
| 1106 |
class SSLSession(object): |
| 1107 |
def __new__(cls, ssl): |
| 1108 |
self = object.__new__(cls) |
| 1109 |
session = lib.SSL_get1_session(ssl.ssl) |
| 1110 |
if not session: |
| 1111 |
return None |
| 1112 |
self._session = ffi.gc(session, lib.SSL_SESSION_free) |
| 1113 |
self._ctx = ssl.ctx |
| 1114 |
return self |
| 1115 |
|
| 1116 |
def __eq__(self, other): |
| 1117 |
if not isinstance(other, SSLSession): |
| 1118 |
return NotImplemented; |
| 1119 |
return self.id == other.id |
| 1120 |
|
| 1121 |
@property |
| 1122 |
def id(self): |
| 1123 |
lenp = ffi.new("unsigned int*") |
| 1124 |
id = lib.SSL_SESSION_get_id(self._session, lenp) |
| 1125 |
return ffi.unpack(id, lenp[0]) |
| 1126 |
|
| 1127 |
@property |
| 1128 |
def time(self): |
| 1129 |
return lib.SSL_SESSION_get_time(self._session) |
| 1130 |
|
| 1131 |
@property |
| 1132 |
def timeout(self): |
| 1133 |
return lib.SSL_SESSION_get_timeout(self._session) |
| 1134 |
|
| 1135 |
@property |
| 1136 |
def has_ticket(self): |
| 1137 |
return bool(lib.SSL_SESSION_has_ticket(self._session)) |
| 1138 |
|
| 1139 |
@property |
| 1140 |
def ticket_lifetime_hint(self): |
| 1141 |
return lib.SSL_SESSION_get_ticket_lifetime_hint(self._session) |
| 1142 |
|
| 1143 |
|
| 1144 |
SSL_CTX_STATS_NAMES = """ |
| 1145 |
number connect connect_good connect_renegotiate accept accept_good |
| 1146 |
accept_renegotiate hits misses timeouts cache_full""".split() |
| 1147 |
SSL_CTX_STATS = [] |
| 1148 |
for name in SSL_CTX_STATS_NAMES: |
| 1149 |
attr = 'SSL_CTX_sess_'+name |
| 1150 |
assert hasattr(lib, attr) |
| 1151 |
SSL_CTX_STATS.append((name, getattr(lib, attr))) |
| 1152 |
|
| 1153 |
HAS_KEYLOG = hasattr(lib, "SSL_CTX_set_keylog_callback") |
| 1154 |
|
| 1155 |
slots = ['ctx', '_check_hostname', |
| 1156 |
'alpn_protocols', '_alpn_protocols_handle', '_protocol' |
| 1157 |
'npn_protocols', 'set_hostname', '_post_handshake_auth', |
| 1158 |
'_sni_cb', '_sni_cb_handle', '_npn_protocols_handle', |
| 1159 |
] |
| 1160 |
if HAS_KEYLOG: |
| 1161 |
slots += ['_keylog_filename', 'keylog_bio'] |
| 1162 |
|
| 1163 |
class _SSLContext(object): |
| 1164 |
__slots__ = tuple(slots) |
| 1165 |
def __new__(cls, protocol): |
| 1166 |
self = object.__new__(cls) |
| 1167 |
self.ctx = ffi.NULL |
| 1168 |
self._sni_cb = None |
| 1169 |
self._msg_cb = None |
| 1170 |
if HAS_KEYLOG: |
| 1171 |
self._keylog_filename = None |
| 1172 |
self.keylog_bio = None |
| 1173 |
if protocol == PROTOCOL_TLSv1: |
| 1174 |
warnings.warn("ssl.PROTOCOL_TLSv1 is deprecated", DeprecationWarning) |
| 1175 |
method = lib.TLSv1_method() |
| 1176 |
elif lib.Cryptography_HAS_TLSv1_1 and protocol == PROTOCOL_TLSv1_1: |
| 1177 |
warnings.warn("ssl.PROTOCOL_TLSv1_1 is deprecated", DeprecationWarning) |
| 1178 |
method = lib.TLSv1_1_method() |
| 1179 |
elif lib.Cryptography_HAS_TLSv1_2 and protocol == PROTOCOL_TLSv1_2 : |
| 1180 |
warnings.warn("ssl.PROTOCOL_TLSv1_2 is deprecated", DeprecationWarning) |
| 1181 |
method = lib.TLSv1_2_method() |
| 1182 |
elif SSLv3_method_ok and protocol == PROTOCOL_SSLv3: |
| 1183 |
warnings.warn("ssl.PROTOCOL_SSLv3 is deprecated", DeprecationWarning) |
| 1184 |
method = lib.SSLv3_method() |
| 1185 |
elif lib.Cryptography_HAS_SSL2 and protocol == PROTOCOL_SSLv2: |
| 1186 |
method = lib.SSLv2_method() |
| 1187 |
elif protocol == PROTOCOL_SSLv23: |
| 1188 |
warnings.warn("ssl.PROTOCOL_TLS is deprecated", DeprecationWarning) |
| 1189 |
method = lib.TLS_method() |
| 1190 |
elif protocol == PROTOCOL_TLS_CLIENT: |
| 1191 |
method = lib.TLS_client_method() |
| 1192 |
elif protocol == PROTOCOL_TLS_SERVER: |
| 1193 |
method = lib.TLS_server_method() |
| 1194 |
else: |
| 1195 |
raise ValueError("invalid protocol version") |
| 1196 |
|
| 1197 |
self.ctx = ffi.gc(lib.SSL_CTX_new(method), lib.SSL_CTX_free) |
| 1198 |
__pypy__.add_memory_pressure(1000) |
| 1199 |
if self.ctx == ffi.NULL: |
| 1200 |
raise ssl_error("failed to allocate SSL context") |
| 1201 |
self._post_handshake_auth = 0; |
| 1202 |
self._protocol = protocol |
| 1203 |
self.hostflags = lib.X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS |
| 1204 |
|
| 1205 |
|
| 1206 |
if protocol == PROTOCOL_TLS_CLIENT: |
| 1207 |
self._check_hostname = True |
| 1208 |
self._set_verify_mode(CERT_REQUIRED) |
| 1209 |
else: |
| 1210 |
self._check_hostname = False |
| 1211 |
self._set_verify_mode(CERT_NONE) |
| 1212 |
|
| 1213 |
options = lib.SSL_OP_ALL & ~lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS |
| 1214 |
if not lib.Cryptography_HAS_SSL2 or protocol != PROTOCOL_SSLv2: |
| 1215 |
options |= lib.SSL_OP_NO_SSLv2 |
| 1216 |
if not SSLv3_method_ok or protocol != PROTOCOL_SSLv3: |
| 1217 |
options |= lib.SSL_OP_NO_SSLv3 |
| 1218 |
|
| 1219 |
|
| 1220 |
options |= lib.SSL_OP_NO_COMPRESSION |
| 1221 |
options |= lib.SSL_OP_CIPHER_SERVER_PREFERENCE |
| 1222 |
options |= lib.SSL_OP_SINGLE_DH_USE |
| 1223 |
options |= lib.SSL_OP_SINGLE_ECDH_USE |
| 1224 |
lib.SSL_CTX_set_options(self.ctx, options) |
| 1225 |
|
| 1226 |
|
| 1227 |
|
| 1228 |
if not lib.SSL_CTX_set_cipher_list(self.ctx, PY_SSL_DEFAULT_CIPHER_STRING): |
| 1229 |
lib.ERR_clear_error() |
| 1230 |
raise SSLError("No cipher can be selected.") |
| 1231 |
|
| 1232 |
lib.SSL_CTX_set_mode(self.ctx, lib.SSL_MODE_RELEASE_BUFFERS) |
| 1233 |
if HAS_ECDH: |
| 1234 |
|
| 1235 |
|
| 1236 |
|
| 1237 |
|
| 1238 |
if lib.Cryptography_HAS_SET_ECDH_AUTO: |
| 1239 |
lib.SSL_CTX_set_ecdh_auto(self.ctx, 1) |
| 1240 |
else: |
| 1241 |
key = lib.EC_KEY_new_by_curve_name(lib.NID_X9_62_prime256v1) |
| 1242 |
lib.SSL_CTX_set_tmp_ecdh(self.ctx, key) |
| 1243 |
lib.EC_KEY_free(key) |
| 1244 |
lib.SSL_CTX_set_session_id_context(self.ctx, b"Python", len(b"Python")) |
| 1245 |
params = lib.SSL_CTX_get0_param(self.ctx); |
| 1246 |
if lib.Cryptography_HAS_X509_V_FLAG_TRUSTED_FIRST: |
| 1247 |
|
| 1248 |
|
| 1249 |
lib.X509_VERIFY_PARAM_set_flags(params, lib.X509_V_FLAG_TRUSTED_FIRST) |
| 1250 |
lib.X509_VERIFY_PARAM_set_hostflags(params, self.hostflags); |
| 1251 |
if HAS_TLSv1_3: |
| 1252 |
self._post_handshake_auth = 0 |
| 1253 |
lib.SSL_CTX_set_post_handshake_auth(self.ctx, self.post_handshake_auth) |
| 1254 |
return self |
| 1255 |
|
| 1256 |
if OPENSSL_VERSION_NUMBER > 0x10101000: |
| 1257 |
@property |
| 1258 |
def num_tickets(self): |
| 1259 |
return lib.SSL_CTX_get_num_tickets(self.ctx) |
| 1260 |
|
| 1261 |
@num_tickets.setter |
| 1262 |
def num_tickets(self, arg, userdata=None): |
| 1263 |
|
| 1264 |
num = int(arg) |
| 1265 |
if num < 0: |
| 1266 |
raise ValueError('value must be non-negative') |
| 1267 |
if self.protocol not in (PROTOCOL_TLS_SERVER,): |
| 1268 |
raise ValueError("SSLContext is not a server context") |
| 1269 |
if lib.SSL_CTX_set_num_tickets(self.ctx, num) != 1: |
| 1270 |
raise ValueError("failed to set num tickets") |
| 1271 |
|
| 1272 |
@property |
| 1273 |
def options(self): |
| 1274 |
return lib.SSL_CTX_get_options(self.ctx) |
| 1275 |
|
| 1276 |
@options.setter |
| 1277 |
def options(self, value): |
| 1278 |
opt_no = ( |
| 1279 |
lib.SSL_OP_NO_SSLv2 | lib.SSL_OP_NO_SSLv3 | lib.SSL_OP_NO_TLSv1 | |
| 1280 |
lib.SSL_OP_NO_TLSv1_1 | lib.SSL_OP_NO_TLSv1_2 | lib.SSL_OP_NO_TLSv1_3 |
| 1281 |
) |
| 1282 |
try: |
| 1283 |
new_opts = int(value) |
| 1284 |
except ValueError: |
| 1285 |
raise TypeError(f"argument must be int, not '{type(value).__name__}'") from None |
| 1286 |
opts = lib.SSL_CTX_get_options(self.ctx) |
| 1287 |
clear = opts & ~new_opts |
| 1288 |
set = ~opts & new_opts |
| 1289 |
if set & opt_no != 0: |
| 1290 |
warnings.warn("ssl.OP_NO_SSL*/ssl.OP_NO_TLS* options are " |
| 1291 |
"deprecated", DeprecationWarning, stacklevel=2) |
| 1292 |
if clear: |
| 1293 |
if lib.Cryptography_HAS_SSL_CTX_CLEAR_OPTIONS: |
| 1294 |
lib.SSL_CTX_clear_options(self.ctx, clear) |
| 1295 |
else: |
| 1296 |
raise ValueError("can't clear options before OpenSSL 0.9.8m") |
| 1297 |
if set: |
| 1298 |
lib.SSL_CTX_set_options(self.ctx, set) |
| 1299 |
|
| 1300 |
def _set_verify_mode(self, n): |
| 1301 |
if n == CERT_NONE: |
| 1302 |
mode = lib.SSL_VERIFY_NONE |
| 1303 |
elif n == CERT_OPTIONAL: |
| 1304 |
mode = lib.SSL_VERIFY_PEER |
| 1305 |
elif n == CERT_REQUIRED: |
| 1306 |
mode = lib.SSL_VERIFY_PEER | lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
| 1307 |
else: |
| 1308 |
raise ValueError("invalid value for verify_mode") |
| 1309 |
|
| 1310 |
|
| 1311 |
|
| 1312 |
|
| 1313 |
|
| 1314 |
verify_cb = lib.SSL_CTX_get_verify_callback(self.ctx); |
| 1315 |
lib.SSL_CTX_set_verify(self.ctx, mode, verify_cb); |
| 1316 |
|
| 1317 |
@property |
| 1318 |
def verify_mode(self): |
| 1319 |
|
| 1320 |
mask = (lib.SSL_VERIFY_NONE | lib.SSL_VERIFY_PEER | |
| 1321 |
lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT) |
| 1322 |
mode = lib.SSL_CTX_get_verify_mode(self.ctx) & mask |
| 1323 |
if mode == lib.SSL_VERIFY_NONE: |
| 1324 |
return CERT_NONE |
| 1325 |
elif mode == lib.SSL_VERIFY_PEER: |
| 1326 |
return CERT_OPTIONAL |
| 1327 |
elif mode == lib.SSL_VERIFY_PEER | lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT: |
| 1328 |
return CERT_REQUIRED |
| 1329 |
raise ssl_error("invalid return value from SSL_CTX_get_verify_mode") |
| 1330 |
|
| 1331 |
@verify_mode.setter |
| 1332 |
def verify_mode(self, value): |
| 1333 |
n = int(value) |
| 1334 |
if n == CERT_NONE and self.check_hostname: |
| 1335 |
raise ValueError("Cannot set verify_mode to CERT_NONE when " \ |
| 1336 |
"check_hostname is enabled.") |
| 1337 |
self._set_verify_mode(n) |
| 1338 |
|
| 1339 |
@property |
| 1340 |
def verify_flags(self): |
| 1341 |
param = lib.SSL_CTX_get0_param(self.ctx) |
| 1342 |
flags = lib.X509_VERIFY_PARAM_get_flags(param) |
| 1343 |
return int(flags) |
| 1344 |
|
| 1345 |
@verify_flags.setter |
| 1346 |
def verify_flags(self, value): |
| 1347 |
new_flags = int(value) |
| 1348 |
param = lib.SSL_CTX_get0_param(self.ctx) |
| 1349 |
flags = lib.X509_VERIFY_PARAM_get_flags(param); |
| 1350 |
clear = flags & ~new_flags; |
| 1351 |
set = ~flags & new_flags; |
| 1352 |
if clear: |
| 1353 |
if not lib.X509_VERIFY_PARAM_clear_flags(param, clear): |
| 1354 |
raise ssl_error(None) |
| 1355 |
if set: |
| 1356 |
if not lib.X509_VERIFY_PARAM_set_flags(param, set): |
| 1357 |
raise ssl_error(None) |
| 1358 |
|
| 1359 |
if HAS_CTRL_GET_MAX_PROTO_VERSION: |
| 1360 |
def set_min_max_proto_version(self, arg, what): |
| 1361 |
v = int(arg) |
| 1362 |
if self.protocol not in (PROTOCOL_TLS_CLIENT, PROTOCOL_TLS_SERVER, |
| 1363 |
PROTOCOL_TLS): |
| 1364 |
raise ValueError("The context's protocol doesn't support" |
| 1365 |
"modification of highest and lowest version.") |
| 1366 |
|
| 1367 |
|
| 1368 |
if v == PROTO_SSLv3: |
| 1369 |
warnings.warn("ssl.TLSVersion.SSLv3 is deprecated", DeprecationWarning) |
| 1370 |
elif v == PROTO_TLSv1: |
| 1371 |
warnings.warn("ssl.TLSVersion.TLSv1 is deprecated", DeprecationWarning) |
| 1372 |
elif v == PROTO_TLSv1_1: |
| 1373 |
warnings.warn("ssl.TLSVersion.TLSv1_1 is deprecated", DeprecationWarning) |
| 1374 |
elif v in (PROTO_MINIMUM_SUPPORTED, PROTO_MAXIMUM_SUPPORTED, |
| 1375 |
PROTO_TLSv1_2, PROTO_TLSv1_3): |
| 1376 |
pass |
| 1377 |
else: |
| 1378 |
raise ValueError(f"Unsupported TLS/SSL version '{v}'") |
| 1379 |
|
| 1380 |
if what == 0: |
| 1381 |
if v == PROTO_MINIMUM_SUPPORTED: |
| 1382 |
v = 0 |
| 1383 |
elif v == PROTO_MAXIMUM_SUPPORTED: |
| 1384 |
|
| 1385 |
v = PROTO_MAXIMUM_AVAILABLE |
| 1386 |
result = lib.SSL_CTX_set_min_proto_version(self.ctx, v) |
| 1387 |
else: |
| 1388 |
if v == PROTO_MAXIMUM_SUPPORTED: |
| 1389 |
v = 0 |
| 1390 |
elif v == PROTO_MINIMUM_SUPPORTED: |
| 1391 |
|
| 1392 |
v = PROTO_MINIMUM_AVAILABLE |
| 1393 |
result = lib.SSL_CTX_set_max_proto_version(self.ctx, v) |
| 1394 |
if result == 0: |
| 1395 |
raise ValueError('Unsupported protocol version 0x%x' % v) |
| 1396 |
return result |
| 1397 |
|
| 1398 |
@property |
| 1399 |
def minimum_version(self): |
| 1400 |
v = lib.SSL_CTX_get_min_proto_version(self.ctx) |
| 1401 |
if v == 0: |
| 1402 |
v = PROTO_MINIMUM_SUPPORTED |
| 1403 |
return v |
| 1404 |
|
| 1405 |
@minimum_version.setter |
| 1406 |
def minimum_version(self, arg): |
| 1407 |
return self.set_min_max_proto_version(arg, 0); |
| 1408 |
|
| 1409 |
@property |
| 1410 |
def maximum_version(self): |
| 1411 |
v = lib.SSL_CTX_get_max_proto_version(self.ctx) |
| 1412 |
if v == 0: |
| 1413 |
v = PROTO_MAXIMUM_SUPPORTED |
| 1414 |
return v |
| 1415 |
|
| 1416 |
@maximum_version.setter |
| 1417 |
def maximum_version(self, arg): |
| 1418 |
return self.set_min_max_proto_version(arg, 1); |
| 1419 |
|
| 1420 |
|
| 1421 |
@property |
| 1422 |
def protocol(self): |
| 1423 |
return self._protocol |
| 1424 |
|
| 1425 |
@property |
| 1426 |
def check_hostname(self): |
| 1427 |
return self._check_hostname |
| 1428 |
|
| 1429 |
@check_hostname.setter |
| 1430 |
def check_hostname(self, value): |
| 1431 |
check_hostname = bool(value) |
| 1432 |
if check_hostname and lib.SSL_CTX_get_verify_mode(self.ctx) == lib.SSL_VERIFY_NONE: |
| 1433 |
self._set_verify_mode(CERT_REQUIRED) |
| 1434 |
self._check_hostname = check_hostname |
| 1435 |
|
| 1436 |
|
| 1437 |
@property |
| 1438 |
def _host_flags(self): |
| 1439 |
return self.hostflags |
| 1440 |
|
| 1441 |
@_host_flags.setter |
| 1442 |
def _host_flags(self, arg): |
| 1443 |
new_flags = int(arg) |
| 1444 |
param = lib.SSL_CTX_get0_param(self.ctx); |
| 1445 |
self.hostflags = new_flags; |
| 1446 |
lib.X509_VERIFY_PARAM_set_hostflags(param, new_flags) |
| 1447 |
|
| 1448 |
def set_ciphers(self, cipherlist): |
| 1449 |
cipherlistbuf = _str_to_ffi_buffer(cipherlist) |
| 1450 |
ret = lib.SSL_CTX_set_cipher_list(self.ctx, cipherlistbuf) |
| 1451 |
if ret == 0: |
| 1452 |
|
| 1453 |
|
| 1454 |
|
| 1455 |
lib.ERR_clear_error() |
| 1456 |
raise ssl_error("No cipher can be selected.") |
| 1457 |
|
| 1458 |
def get_ciphers(self): |
| 1459 |
ssl = lib.SSL_new(self.ctx) |
| 1460 |
try: |
| 1461 |
ciphers = lib.SSL_get_ciphers(ssl) |
| 1462 |
if ciphers == ffi.NULL: |
| 1463 |
return None |
| 1464 |
count = lib.sk_SSL_CIPHER_num(ciphers) |
| 1465 |
res = [None] * count |
| 1466 |
for i in range(count): |
| 1467 |
dct = cipher_to_dict(lib.sk_SSL_CIPHER_value(ciphers, i)) |
| 1468 |
res[i] = dct |
| 1469 |
return res |
| 1470 |
finally: |
| 1471 |
lib.SSL_free(ssl) |
| 1472 |
|
| 1473 |
def load_cert_chain(self, certfile, keyfile=None, password=None): |
| 1474 |
if keyfile is None: |
| 1475 |
keyfile = certfile |
| 1476 |
pw_info = PasswordInfo() |
| 1477 |
index = -1 |
| 1478 |
orig_passwd_cb = lib.SSL_CTX_get_default_passwd_cb(self.ctx) |
| 1479 |
orig_passwd_userdata = lib.SSL_CTX_get_default_passwd_cb_userdata(self.ctx) |
| 1480 |
if password is not None: |
| 1481 |
|
| 1482 |
if callable(password): |
| 1483 |
pw_info.callable = password |
| 1484 |
else: |
| 1485 |
if isinstance(password, (str, bytes, bytearray)): |
| 1486 |
pw_info.password = password |
| 1487 |
else: |
| 1488 |
raise TypeError("password should be a string or callable") |
| 1489 |
|
| 1490 |
pw_info.handle = ffi.new_handle(pw_info) |
| 1491 |
index = _thread.get_ident() |
| 1492 |
PWINFO_STORAGE[index] = pw_info |
| 1493 |
lib.SSL_CTX_set_default_passwd_cb(self.ctx, Cryptography_pem_password_cb) |
| 1494 |
lib.SSL_CTX_set_default_passwd_cb_userdata(self.ctx, pw_info.handle) |
| 1495 |
|
| 1496 |
prev_errno = ffi.errno |
| 1497 |
try: |
| 1498 |
ffi.errno = 0 |
| 1499 |
certfilebuf = _str_to_ffi_buffer(_fs_converter(certfile, "certfile")) |
| 1500 |
ret = lib.SSL_CTX_use_certificate_chain_file(self.ctx, certfilebuf) |
| 1501 |
if ret != 1: |
| 1502 |
if pw_info.operationerror: |
| 1503 |
lib.ERR_clear_error() |
| 1504 |
raise pw_info.operationerror |
| 1505 |
_errno = ffi.errno |
| 1506 |
if _errno: |
| 1507 |
lib.ERR_clear_error() |
| 1508 |
raise OSError(_errno, "Error") |
| 1509 |
else: |
| 1510 |
raise ssl_error(None) |
| 1511 |
|
| 1512 |
ffi.errno = 0 |
| 1513 |
buf = _str_to_ffi_buffer(_fs_converter(keyfile, "keyfile")) |
| 1514 |
ret = lib.SSL_CTX_use_PrivateKey_file(self.ctx, buf, |
| 1515 |
lib.SSL_FILETYPE_PEM) |
| 1516 |
if ret != 1: |
| 1517 |
if pw_info.operationerror: |
| 1518 |
lib.ERR_clear_error() |
| 1519 |
raise pw_info.operationerror |
| 1520 |
_errno = ffi.errno |
| 1521 |
if _errno: |
| 1522 |
lib.ERR_clear_error() |
| 1523 |
raise OSError(_errno, None) |
| 1524 |
else: |
| 1525 |
raise ssl_error(None) |
| 1526 |
|
| 1527 |
ret = lib.SSL_CTX_check_private_key(self.ctx) |
| 1528 |
if ret != 1: |
| 1529 |
raise ssl_error(None) |
| 1530 |
finally: |
| 1531 |
ffi.errno = prev_errno |
| 1532 |
if index >= 0: |
| 1533 |
del PWINFO_STORAGE[index] |
| 1534 |
lib.SSL_CTX_set_default_passwd_cb(self.ctx, orig_passwd_cb) |
| 1535 |
lib.SSL_CTX_set_default_passwd_cb_userdata(self.ctx, orig_passwd_userdata) |
| 1536 |
|
| 1537 |
|
| 1538 |
def _wrap_socket(self, sock, server_side, server_hostname=None, *, |
| 1539 |
owner=None, session=None): |
| 1540 |
if server_hostname: |
| 1541 |
server_hostname = server_hostname.encode('ascii') |
| 1542 |
return _SSLSocket._new__ssl_socket(self, sock, server_side, |
| 1543 |
server_hostname, owner, session, None, None) |
| 1544 |
|
| 1545 |
def load_verify_locations(self, cafile=None, capath=None, cadata=None): |
| 1546 |
prev_errno = ffi.errno |
| 1547 |
try: |
| 1548 |
ffi.errno = 0 |
| 1549 |
if cadata is None: |
| 1550 |
ca_file_type = -1 |
| 1551 |
else: |
| 1552 |
if not isinstance(cadata, str): |
| 1553 |
ca_file_type = lib.SSL_FILETYPE_ASN1 |
| 1554 |
else: |
| 1555 |
ca_file_type = lib.SSL_FILETYPE_PEM |
| 1556 |
try: |
| 1557 |
cadata = cadata.encode('ascii') |
| 1558 |
except UnicodeEncodeError: |
| 1559 |
raise TypeError("cadata should be a ASCII string or a bytes-like object") |
| 1560 |
if cafile is None and capath is None and cadata is None: |
| 1561 |
raise TypeError("cafile and capath cannot be both omitted") |
| 1562 |
|
| 1563 |
if cadata is not None: |
| 1564 |
buf = _str_to_ffi_buffer(cadata) |
| 1565 |
self._add_ca_certs(buf, len(buf), ca_file_type) |
| 1566 |
|
| 1567 |
|
| 1568 |
if cafile is not None or capath is not None: |
| 1569 |
if cafile is None: |
| 1570 |
cafilebuf = ffi.NULL |
| 1571 |
else: |
| 1572 |
cafilebuf = _str_to_ffi_buffer(_fs_converter(cafile, "cafile")) |
| 1573 |
if capath is None: |
| 1574 |
capathbuf = ffi.NULL |
| 1575 |
else: |
| 1576 |
capathbuf = _str_to_ffi_buffer(_fs_converter(capath, "capath")) |
| 1577 |
ret = lib.SSL_CTX_load_verify_locations(self.ctx, cafilebuf, capathbuf) |
| 1578 |
if ret != 1: |
| 1579 |
_errno = ffi.errno |
| 1580 |
if _errno: |
| 1581 |
lib.ERR_clear_error() |
| 1582 |
raise OSError(_errno, '') |
| 1583 |
else: |
| 1584 |
raise ssl_error(None) |
| 1585 |
finally: |
| 1586 |
ffi.errno = prev_errno |
| 1587 |
|
| 1588 |
def _add_ca_certs(self, data, size, ca_file_type): |
| 1589 |
biobuf = lib.BIO_new_mem_buf(data, size) |
| 1590 |
if biobuf == ffi.NULL: |
| 1591 |
raise ssl_error("Can't allocate buffer") |
| 1592 |
try: |
| 1593 |
store = lib.SSL_CTX_get_cert_store(self.ctx) |
| 1594 |
loaded = 0 |
| 1595 |
while True: |
| 1596 |
if ca_file_type == lib.SSL_FILETYPE_ASN1: |
| 1597 |
cert = lib.d2i_X509_bio(biobuf, ffi.NULL) |
| 1598 |
else: |
| 1599 |
cert = lib.PEM_read_bio_X509(biobuf, ffi.NULL, |
| 1600 |
lib.SSL_CTX_get_default_passwd_cb(self.ctx), |
| 1601 |
lib.SSL_CTX_get_default_passwd_cb_userdata(self.ctx), |
| 1602 |
) |
| 1603 |
if not cert: |
| 1604 |
break |
| 1605 |
try: |
| 1606 |
r = lib.X509_STORE_add_cert(store, cert) |
| 1607 |
finally: |
| 1608 |
lib.X509_free(cert) |
| 1609 |
if not r: |
| 1610 |
err = lib.ERR_peek_last_error() |
| 1611 |
if (lib.ERR_GET_LIB(err) == lib.ERR_LIB_X509 and |
| 1612 |
lib.ERR_GET_REASON(err) == |
| 1613 |
lib.X509_R_CERT_ALREADY_IN_HASH_TABLE): |
| 1614 |
|
| 1615 |
lib.ERR_clear_error() |
| 1616 |
else: |
| 1617 |
break |
| 1618 |
loaded += 1 |
| 1619 |
|
| 1620 |
err = lib.ERR_peek_last_error() |
| 1621 |
if loaded == 0: |
| 1622 |
if ca_file_type == lib.SSL_FILETYPE_PEM: |
| 1623 |
msg = "no start line: cadata does not contain a certificate" |
| 1624 |
else: |
| 1625 |
msg = "not enough data: cadata does not contain a certificate"; |
| 1626 |
raise ssl_error(msg) |
| 1627 |
elif (ca_file_type == lib.SSL_FILETYPE_ASN1 and |
| 1628 |
loaded > 0 and |
| 1629 |
lib.ERR_GET_LIB(err) == lib.ERR_LIB_ASN1 and |
| 1630 |
lib.ERR_GET_REASON(err) == lib.ASN1_R_HEADER_TOO_LONG): |
| 1631 |
|
| 1632 |
lib.ERR_clear_error() |
| 1633 |
elif (ca_file_type == lib.SSL_FILETYPE_PEM and |
| 1634 |
lib.ERR_GET_LIB(err) == lib.ERR_LIB_PEM and |
| 1635 |
lib.ERR_GET_REASON(err) == lib.PEM_R_NO_START_LINE): |
| 1636 |
|
| 1637 |
lib.ERR_clear_error() |
| 1638 |
elif err != 0: |
| 1639 |
raise ssl_error(None) |
| 1640 |
finally: |
| 1641 |
lib.BIO_free(biobuf) |
| 1642 |
|
| 1643 |
@property |
| 1644 |
def sni_callback(self): |
| 1645 |
r"""Set a callback that will be called when a server name is |
| 1646 |
provided by the SSL/TLS client in the SNI extension. |
| 1647 |
|
| 1648 |
If the argument is None then the callback is disabled. The method |
| 1649 |
is called with the SSLSocket, the server name as a string, and the |
| 1650 |
SSLContext object. See RFC 6066 for details of the SNI |
| 1651 |
extension. |
| 1652 |
""" |
| 1653 |
|
| 1654 |
return self._sni_cb |
| 1655 |
|
| 1656 |
@sni_callback.setter |
| 1657 |
def sni_callback(self, cb): |
| 1658 |
if self._protocol == PROTOCOL_TLS_CLIENT: |
| 1659 |
raise ValueError('sni_callback cannot be set on TLS_CLIENT context') |
| 1660 |
if not HAS_SNI: |
| 1661 |
raise NotImplementedError("The TLS extension servername callback, " |
| 1662 |
"SSL_CTX_set_tlsext_servername_callback, " |
| 1663 |
"is not in the current OpenSSL library.") |
| 1664 |
if cb is None: |
| 1665 |
lib.SSL_CTX_set_tlsext_servername_callback(self.ctx, ffi.NULL) |
| 1666 |
self._sni_cb = None |
| 1667 |
lib.SSL_CTX_set_tlsext_servername_arg(self.ctx, ffi.NULL) |
| 1668 |
self._sni_cb_handle = None |
| 1669 |
return |
| 1670 |
if not callable(cb): |
| 1671 |
lib.SSL_CTX_set_tlsext_servername_callback(self.ctx, ffi.NULL) |
| 1672 |
raise TypeError("not a callable object") |
| 1673 |
self._sni_cb = GenericCallback(cb, self) |
| 1674 |
self._sni_cb_handle = sni_cb = ffi.new_handle(self._sni_cb) |
| 1675 |
lib.SSL_CTX_set_tlsext_servername_callback(self.ctx, _servername_callback) |
| 1676 |
lib.SSL_CTX_set_tlsext_servername_arg(self.ctx, sni_cb) |
| 1677 |
|
| 1678 |
@property |
| 1679 |
def _msg_callback(self): |
| 1680 |
return self._msg_cb |
| 1681 |
|
| 1682 |
@_msg_callback.setter |
| 1683 |
def _msg_callback(self, arg, userdata=None): |
| 1684 |
|
| 1685 |
if arg is None: |
| 1686 |
lib.SSL_CTX_set_msg_callback(self.ctx, ffi.NULL) |
| 1687 |
self._msg_cb = None |
| 1688 |
if not callable(arg): |
| 1689 |
lib.SSL_CTX_set_msg_callback(self.ctx, ffi.NULL) |
| 1690 |
self._msg_cb = None |
| 1691 |
raise TypeError('not a callable object') |
| 1692 |
self._msg_cb = arg |
| 1693 |
lib.SSL_CTX_set_msg_callback(self.ctx, _msg_callback) |
| 1694 |
|
| 1695 |
if HAS_KEYLOG: |
| 1696 |
@property |
| 1697 |
def keylog_filename(self): |
| 1698 |
return self._keylog_filename |
| 1699 |
|
| 1700 |
@keylog_filename.setter |
| 1701 |
def keylog_filename(self, arg): |
| 1702 |
|
| 1703 |
|
| 1704 |
lib.SSL_CTX_set_keylog_callback(self.ctx, ffi.NULL) |
| 1705 |
if (self.keylog_bio != None): |
| 1706 |
bio = self.keylog_bio |
| 1707 |
self.keylog_bio = None |
| 1708 |
lib.BIO_free_all(bio) |
| 1709 |
if arg is None: |
| 1710 |
self._keylog_filename = None |
| 1711 |
return 0 |
| 1712 |
if not isinstance(arg, str): |
| 1713 |
raise TypeError("str path expected") |
| 1714 |
buf = _fs_converter(arg, "arg") |
| 1715 |
mode = ffi.new("char[]", b"at") |
| 1716 |
ffi.errno = 0 |
| 1717 |
self.keylog_bio = lib.BIO_new_file(buf, mode) |
| 1718 |
if self.keylog_bio == ffi.NULL: |
| 1719 |
_errno = ffi.errno |
| 1720 |
lib.ERR_clear_error() |
| 1721 |
raise OSError(_errno, '') |
| 1722 |
self._keylog_filename = arg |
| 1723 |
|
| 1724 |
if lib.BIO_tell(self.keylog_bio) == 0: |
| 1725 |
lib.BIO_puts(self.keylog_bio, |
| 1726 |
"# TLS secrets log file, generated by OpenSSL / Python\n".encode()) |
| 1727 |
lib.BIO_flush(self.keylog_bio) |
| 1728 |
lib.SSL_CTX_set_keylog_callback(self.ctx, _keylog_callback) |
| 1729 |
return 0 |
| 1730 |
|
| 1731 |
def cert_store_stats(self): |
| 1732 |
store = lib.SSL_CTX_get_cert_store(self.ctx) |
| 1733 |
x509 = 0 |
| 1734 |
x509_ca = 0 |
| 1735 |
crl = 0 |
| 1736 |
objs = lib.X509_STORE_get1_objects(store) |
| 1737 |
if not objs: |
| 1738 |
raise MemoryError("failed to query cert store") |
| 1739 |
count = lib.sk_X509_OBJECT_num(objs) |
| 1740 |
for i in range(count): |
| 1741 |
obj = lib.sk_X509_OBJECT_value(objs, i) |
| 1742 |
_type = lib.X509_OBJECT_get_type(obj) |
| 1743 |
if _type == lib.X509_LU_X509: |
| 1744 |
x509 += 1 |
| 1745 |
cert = lib.X509_OBJECT_get0_X509(obj) |
| 1746 |
if lib.X509_check_ca(cert): |
| 1747 |
x509_ca += 1 |
| 1748 |
elif _type == lib.X509_LU_CRL: |
| 1749 |
crl += 1 |
| 1750 |
else: |
| 1751 |
|
| 1752 |
pass |
| 1753 |
lib.sk_X509_OBJECT_pop_free(objs, lib.X509_OBJECT_free); |
| 1754 |
return {'x509': x509, 'x509_ca': x509_ca, 'crl': crl} |
| 1755 |
|
| 1756 |
|
| 1757 |
def session_stats(self): |
| 1758 |
stats = {} |
| 1759 |
for name, ssl_func in SSL_CTX_STATS: |
| 1760 |
stats[name] = ssl_func(self.ctx) |
| 1761 |
return stats |
| 1762 |
|
| 1763 |
def set_default_verify_paths(self): |
| 1764 |
if (not os.environ.get('SSL_CERT_FILE') and |
| 1765 |
not os.environ.get('SSL_CERT_DIR') and |
| 1766 |
not sys.platform == 'win32'): |
| 1767 |
locations = get_default_verify_paths() |
| 1768 |
self.load_verify_locations(locations[1], locations[3]) |
| 1769 |
return |
| 1770 |
if not lib.SSL_CTX_set_default_verify_paths(self.ctx): |
| 1771 |
raise ssl_error(None) |
| 1772 |
|
| 1773 |
def load_dh_params(self, filepath): |
| 1774 |
sys.audit("open", filepath, 'rb', 0) |
| 1775 |
prev_errno = ffi.errno |
| 1776 |
try: |
| 1777 |
ffi.errno = 0 |
| 1778 |
if filepath is None: |
| 1779 |
raise TypeError("filepath must not be None") |
| 1780 |
buf = _fs_converter(filepath, "filepath") |
| 1781 |
mode = ffi.new("char[]",b"rb") |
| 1782 |
ffi.errno = 0 |
| 1783 |
bio = lib.BIO_new_file(buf, mode) |
| 1784 |
if bio == ffi.NULL: |
| 1785 |
_errno = ffi.errno |
| 1786 |
lib.ERR_clear_error() |
| 1787 |
raise OSError(_errno, '') |
| 1788 |
try: |
| 1789 |
dh = lib.PEM_read_bio_DHparams(bio, ffi.NULL, ffi.NULL, ffi.NULL) |
| 1790 |
finally: |
| 1791 |
lib.BIO_free(bio) |
| 1792 |
if dh == ffi.NULL: |
| 1793 |
_errno = ffi.errno |
| 1794 |
if _errno != 0: |
| 1795 |
lib.ERR_clear_error() |
| 1796 |
raise OSError(_errno, '') |
| 1797 |
else: |
| 1798 |
raise ssl_error(None) |
| 1799 |
try: |
| 1800 |
if lib.SSL_CTX_set_tmp_dh(self.ctx, dh) == 0: |
| 1801 |
raise ssl_error(None) |
| 1802 |
finally: |
| 1803 |
lib.DH_free(dh) |
| 1804 |
finally: |
| 1805 |
ffi.errno = prev_errno |
| 1806 |
|
| 1807 |
def get_ca_certs(self, binary_form=None): |
| 1808 |
binary_mode = bool(binary_form) |
| 1809 |
_list = [] |
| 1810 |
store = lib.SSL_CTX_get_cert_store(self.ctx) |
| 1811 |
objs = lib.X509_STORE_get1_objects(store) |
| 1812 |
if not objs: |
| 1813 |
raise MemoryError("failed to query cert store") |
| 1814 |
try: |
| 1815 |
count = lib.sk_X509_OBJECT_num(objs) |
| 1816 |
for i in range(count): |
| 1817 |
obj = lib.sk_X509_OBJECT_value(objs, i) |
| 1818 |
_type = lib.X509_OBJECT_get_type(obj) |
| 1819 |
if _type != lib.X509_LU_X509: |
| 1820 |
|
| 1821 |
continue |
| 1822 |
|
| 1823 |
cert = lib.X509_OBJECT_get0_X509(obj) |
| 1824 |
if not lib.X509_check_ca(cert): |
| 1825 |
continue |
| 1826 |
if binary_mode: |
| 1827 |
_list.append(_certificate_to_der(cert)) |
| 1828 |
else: |
| 1829 |
_list.append(_decode_certificate(cert)) |
| 1830 |
finally: |
| 1831 |
lib.sk_X509_OBJECT_pop_free(objs, lib.X509_OBJECT_free); |
| 1832 |
return _list |
| 1833 |
|
| 1834 |
def set_ecdh_curve(self, name): |
| 1835 |
|
| 1836 |
if name is None: |
| 1837 |
raise TypeError() |
| 1838 |
buf = _fs_converter(name, "name") |
| 1839 |
nid = lib.OBJ_sn2nid(buf) |
| 1840 |
if nid == 0: |
| 1841 |
raise ValueError("unknown elliptic curve name '%s'" % name) |
| 1842 |
key = lib.EC_KEY_new_by_curve_name(nid) |
| 1843 |
if not key: |
| 1844 |
raise ssl_error(None) |
| 1845 |
try: |
| 1846 |
lib.SSL_CTX_set_tmp_ecdh(self.ctx, key) |
| 1847 |
finally: |
| 1848 |
lib.EC_KEY_free(key) |
| 1849 |
|
| 1850 |
def _set_alpn_protocols(self, protos): |
| 1851 |
if HAS_ALPN: |
| 1852 |
self.alpn_protocols = protocols = ffi.from_buffer(protos) |
| 1853 |
length = len(protocols) |
| 1854 |
|
| 1855 |
if lib.SSL_CTX_set_alpn_protos(self.ctx,ffi.cast("unsigned char*", protocols), length): |
| 1856 |
return MemoryError() |
| 1857 |
self._alpn_protocols_handle = handle = ffi.new_handle(self) |
| 1858 |
lib.SSL_CTX_set_alpn_select_cb(self.ctx, select_alpn_callback, handle) |
| 1859 |
else: |
| 1860 |
raise NotImplementedError("The ALPN extension requires OpenSSL 1.0.2 or later.") |
| 1861 |
|
| 1862 |
def _set_npn_protocols(self, protos): |
| 1863 |
if HAS_NPN: |
| 1864 |
self.npn_protocols = ffi.from_buffer(protos) |
| 1865 |
handle = ffi.new_handle(self) |
| 1866 |
self._npn_protocols_handle = handle |
| 1867 |
lib.SSL_CTX_set_next_protos_advertised_cb(self.ctx, advertise_npn_callback, handle) |
| 1868 |
lib.SSL_CTX_set_next_proto_select_cb(self.ctx, select_npn_callback, handle) |
| 1869 |
else: |
| 1870 |
raise NotImplementedError("The NPN extension has been dropped.") |
| 1871 |
|
| 1872 |
def _wrap_bio(self, incoming, outgoing, server_side, server_hostname, *, |
| 1873 |
owner=None, session=None): |
| 1874 |
|
| 1875 |
|
| 1876 |
hostname = None |
| 1877 |
if server_hostname is not None: |
| 1878 |
hostname = server_hostname.encode("ascii") |
| 1879 |
|
| 1880 |
sock = _SSLSocket._new__ssl_socket( |
| 1881 |
self, None, server_side, hostname, owner, session, incoming, |
| 1882 |
outgoing) |
| 1883 |
return sock |
| 1884 |
|
| 1885 |
@property |
| 1886 |
def post_handshake_auth(self): |
| 1887 |
if HAS_TLSv1_3: |
| 1888 |
return bool(self._post_handshake_auth) |
| 1889 |
return None |
| 1890 |
|
| 1891 |
@post_handshake_auth.setter |
| 1892 |
def post_handshake_auth(self, arg): |
| 1893 |
if arg is None: |
| 1894 |
raise AttributeError("cannot delete attribute") |
| 1895 |
pha = int(bool(arg)) |
| 1896 |
|
| 1897 |
self._post_handshake_auth = pha |
| 1898 |
|
| 1899 |
return 0; |
| 1900 |
|
| 1901 |
def __del__(self): |
| 1902 |
|
| 1903 |
if HAS_KEYLOG and self.keylog_bio: |
| 1904 |
lib.BIO_free_all(self.keylog_bio) |
| 1905 |
self.keylog_bio = None |
| 1906 |
|
| 1907 |
|
| 1908 |
|
| 1909 |
if HAS_SNI: |
| 1910 |
@ffi.callback("int(SSL*,int*,void*)") |
| 1911 |
def _servername_callback(s, al, arg): |
| 1912 |
scb = ffi.from_handle(arg) |
| 1913 |
ssl_ctx = scb.ctx |
| 1914 |
servername = lib.SSL_get_servername(s, lib.TLSEXT_NAMETYPE_host_name) |
| 1915 |
set_hostname = scb.callback |
| 1916 |
|
| 1917 |
|
| 1918 |
|
| 1919 |
|
| 1920 |
if set_hostname is None: |
| 1921 |
|
| 1922 |
|
| 1923 |
|
| 1924 |
|
| 1925 |
|
| 1926 |
return lib.SSL_TLSEXT_ERR_OK |
| 1927 |
|
| 1928 |
ssl = ffi.from_handle(lib.SSL_get_app_data(s)) |
| 1929 |
assert isinstance(ssl, _SSLSocket) |
| 1930 |
|
| 1931 |
|
| 1932 |
|
| 1933 |
|
| 1934 |
|
| 1935 |
|
| 1936 |
|
| 1937 |
|
| 1938 |
|
| 1939 |
ssl_socket = ssl.owner |
| 1940 |
if not ssl_socket: |
| 1941 |
ssl_socket = ssl.get_socket_or_None() |
| 1942 |
|
| 1943 |
if ssl_socket is None: |
| 1944 |
al[0] = lib.SSL_AD_INTERNAL_ERROR |
| 1945 |
return lib.SSL_TLSEXT_ERR_ALERT_FATAL |
| 1946 |
|
| 1947 |
if servername == ffi.NULL: |
| 1948 |
try: |
| 1949 |
result = set_hostname(ssl_socket, None, ssl_ctx) |
| 1950 |
except Exception as e: |
| 1951 |
pyerr_write_unraisable(e, set_hostname) |
| 1952 |
al[0] = lib.SSL_AD_HANDSHAKE_FAILURE |
| 1953 |
return lib.SSL_TLSEXT_ERR_ALERT_FATAL |
| 1954 |
else: |
| 1955 |
servername = ffi.string(servername) |
| 1956 |
|
| 1957 |
try: |
| 1958 |
|
| 1959 |
|
| 1960 |
servername_str = servername.decode("ascii") |
| 1961 |
except UnicodeDecodeError as e: |
| 1962 |
pyerr_write_unraisable(e, servername) |
| 1963 |
|
| 1964 |
try: |
| 1965 |
result = set_hostname(ssl_socket, servername_str, ssl_ctx) |
| 1966 |
except Exception as e: |
| 1967 |
pyerr_write_unraisable(e, set_hostname) |
| 1968 |
al[0] = lib.SSL_AD_HANDSHAKE_FAILURE |
| 1969 |
return lib.SSL_TLSEXT_ERR_ALERT_FATAL |
| 1970 |
|
| 1971 |
if result is not None: |
| 1972 |
|
| 1973 |
|
| 1974 |
|
| 1975 |
|
| 1976 |
try: |
| 1977 |
if isinstance(result, int): |
| 1978 |
al[0] = result |
| 1979 |
else: |
| 1980 |
if result is not None: |
| 1981 |
if hasattr(result,'__int__'): |
| 1982 |
al[0] = result.__int__() |
| 1983 |
return lib.SSL_TLSEXT_ERR_ALERT_FATAL |
| 1984 |
|
| 1985 |
raise TypeError("an integer is required (got type %s)" % result) |
| 1986 |
except TypeError as e: |
| 1987 |
pyerr_write_unraisable(e, result) |
| 1988 |
al[0] = lib.SSL_AD_INTERNAL_ERROR |
| 1989 |
return lib.SSL_TLSEXT_ERR_ALERT_FATAL |
| 1990 |
else: |
| 1991 |
|
| 1992 |
return lib.SSL_TLSEXT_ERR_OK |
| 1993 |
|
| 1994 |
@ffi.callback("void(int, int, int, const void*, size_t, SSL*, void*)") |
| 1995 |
def _msg_callback(write_p, version, content_type, buf, length, ssl, arg): |
| 1996 |
ssl_obj = ffi.from_handle(lib.SSL_get_app_data(ssl)) |
| 1997 |
cbuf = ffi.cast('const char *', buf) |
| 1998 |
assert isinstance(ssl_obj, _SSLSocket) |
| 1999 |
if ssl_obj.ctx._msg_cb is None: |
| 2000 |
return |
| 2001 |
if ssl_obj.owner: |
| 2002 |
ssl_socket = ssl_obj.owner |
| 2003 |
elif getattr(ssl_obj, 'Socket', None): |
| 2004 |
ssl_socket = ssl_obj.Socket |
| 2005 |
else: |
| 2006 |
ssl_socket = ssl_obj |
| 2007 |
|
| 2008 |
|
| 2009 |
if content_type == lib.SSL3_RT_CHANGE_CIPHER_SPEC: |
| 2010 |
msg_type = lib.SSL3_MT_CHANGE_CIPHER_SPEC |
| 2011 |
elif content_type == lib.SSL3_RT_ALERT: |
| 2012 |
|
| 2013 |
|
| 2014 |
msg_type = ord(cbuf[1]); |
| 2015 |
elif content_type == lib.SSL3_RT_HANDSHAKE: |
| 2016 |
msg_type = ord(cbuf[0]) |
| 2017 |
elif content_type == lib.SSL3_RT_HEADER: |
| 2018 |
|
| 2019 |
version = ord(cbuf[1]) << 8 | ord(cbuf[2]) |
| 2020 |
msg_type = ord(cbuf[0]) |
| 2021 |
elif content_type == lib.SSL3_RT_INNER_CONTENT_TYPE: |
| 2022 |
msg_type = ord(cbuf[0]) |
| 2023 |
else: |
| 2024 |
|
| 2025 |
msg_type = -1; |
| 2026 |
res = ssl_obj.ctx._msg_cb(ssl_socket, 'write' if write_p != 0 else 'read', |
| 2027 |
version, content_type, msg_type, |
| 2028 |
bytes(ffi.buffer(cbuf, length))) |
| 2029 |
|
| 2030 |
keylog_callback_lock = threading.Lock() |
| 2031 |
|
| 2032 |
@ffi.callback("void(SSL*, const char *)") |
| 2033 |
def _keylog_callback(ssl, line): |
| 2034 |
ssl_obj = ffi.from_handle(lib.SSL_get_app_data(ssl)) |
| 2035 |
bio = ssl_obj.ctx.keylog_bio |
| 2036 |
if not bio: |
| 2037 |
return |
| 2038 |
keylog_callback_lock.acquire(True) |
| 2039 |
if isinstance(line, str): |
| 2040 |
line = line.encode() |
| 2041 |
buff = ffi.from_buffer(line) |
| 2042 |
elif isinstance(line, bytes): |
| 2043 |
buff = ffi.from_buffer(line) |
| 2044 |
else: |
| 2045 |
buff = line |
| 2046 |
fmt = ffi.from_buffer(b"%s\n") |
| 2047 |
res = lib.BIO_printf(bio, fmt, buff) |
| 2048 |
e = ffi.errno |
| 2049 |
lib.BIO_flush(bio) |
| 2050 |
keylog_callback_lock.release() |
| 2051 |
if res < 0: |
| 2052 |
raise OSError(e, ssl_obj.ctx.keylog_filename) |
| 2053 |
|
| 2054 |
class GenericCallback(object): |
| 2055 |
def __init__(self, callback, ctx): |
| 2056 |
self.callback = callback |
| 2057 |
self.ctx = ctx |
| 2058 |
|
| 2059 |
def _asn1obj2py(obj): |
| 2060 |
nid = lib.OBJ_obj2nid(obj) |
| 2061 |
if nid == lib.NID_undef: |
| 2062 |
raise ValueError("Unknown object") |
| 2063 |
sn = _str_from_buf(lib.OBJ_nid2sn(nid)) |
| 2064 |
ln = _str_from_buf(lib.OBJ_nid2ln(nid)) |
| 2065 |
buf = ffi.new("char[]", 255) |
| 2066 |
length = lib.OBJ_obj2txt(buf, len(buf), obj, 1) |
| 2067 |
if length < 0: |
| 2068 |
ssl_error(None) |
| 2069 |
if length > 0: |
| 2070 |
return (nid, sn, ln, _str_with_len(buf, length)) |
| 2071 |
else: |
| 2072 |
return (nid, sn, ln, None) |
| 2073 |
|
| 2074 |
def txt2obj(txt, name): |
| 2075 |
_bytes = _str_to_ffi_buffer(txt) |
| 2076 |
is_name = 0 if name else 1 |
| 2077 |
obj = lib.OBJ_txt2obj(_bytes, is_name) |
| 2078 |
if obj == ffi.NULL: |
| 2079 |
raise ValueError("unknown object '%s'" % txt) |
| 2080 |
result = _asn1obj2py(obj) |
| 2081 |
lib.ASN1_OBJECT_free(obj) |
| 2082 |
return result |
| 2083 |
|
| 2084 |
def nid2obj(nid): |
| 2085 |
if nid < lib.NID_undef: |
| 2086 |
raise ValueError("NID must be positive.") |
| 2087 |
obj = lib.OBJ_nid2obj(nid); |
| 2088 |
if obj == ffi.NULL: |
| 2089 |
raise ValueError("unknown NID %i" % nid) |
| 2090 |
result = _asn1obj2py(obj); |
| 2091 |
lib.ASN1_OBJECT_free(obj); |
| 2092 |
return result; |
| 2093 |
|
| 2094 |
|
| 2095 |
class MemoryBIO(object): |
| 2096 |
def __init__(self): |
| 2097 |
bio = lib.BIO_new(lib.BIO_s_mem()); |
| 2098 |
if bio == ffi.NULL: |
| 2099 |
raise ssl_error("failed to allocate BIO") |
| 2100 |
|
| 2101 |
|
| 2102 |
|
| 2103 |
|
| 2104 |
lib.BIO_set_retry_read(bio); |
| 2105 |
lib.BIO_set_mem_eof_return(bio, -1); |
| 2106 |
|
| 2107 |
self.bio = ffi.gc(bio, lib.BIO_free) |
| 2108 |
self.eof_written = False |
| 2109 |
|
| 2110 |
@property |
| 2111 |
def eof(self): |
| 2112 |
"""Whether the memory BIO is at EOF.""" |
| 2113 |
return lib.BIO_ctrl_pending(self.bio) == 0 and self.eof_written |
| 2114 |
|
| 2115 |
def write(self, strlike): |
| 2116 |
INT_MAX = 2**31-1 |
| 2117 |
if isinstance(strlike, memoryview): |
| 2118 |
if not strlike.c_contiguous: |
| 2119 |
raise BufferError("memoryview: underlying buffer is not C-contiguous") |
| 2120 |
buf = ffi.from_buffer(strlike) |
| 2121 |
if len(buf) > INT_MAX: |
| 2122 |
raise OverflowError("string longer than %d bytes", INT_MAX) |
| 2123 |
|
| 2124 |
if self.eof_written: |
| 2125 |
raise ssl_error("cannot write() after write_eof()") |
| 2126 |
nbytes = lib.BIO_write(self.bio, buf, len(buf)); |
| 2127 |
if nbytes < 0: |
| 2128 |
raise ssl_error(None) |
| 2129 |
return nbytes |
| 2130 |
|
| 2131 |
def write_eof(self): |
| 2132 |
self.eof_written = True |
| 2133 |
|
| 2134 |
|
| 2135 |
lib.BIO_clear_retry_flags(self.bio) |
| 2136 |
lib.BIO_set_mem_eof_return(self.bio, 0) |
| 2137 |
|
| 2138 |
def read(self, size=-1): |
| 2139 |
"""Read up to size bytes from the memory BIO. |
| 2140 |
|
| 2141 |
If size is not specified, read the entire buffer. |
| 2142 |
If the return value is an empty bytes instance, this means either |
| 2143 |
EOF or that no data is available. Use the "eof" property to |
| 2144 |
distinguish between the two. |
| 2145 |
""" |
| 2146 |
count = size |
| 2147 |
avail = lib.BIO_ctrl_pending(self.bio); |
| 2148 |
if count < 0 or count > avail: |
| 2149 |
count = avail; |
| 2150 |
if count == 0: |
| 2151 |
return b'' |
| 2152 |
|
| 2153 |
buf = ffi.new("char[]", count) |
| 2154 |
|
| 2155 |
nbytes = lib.BIO_read(self.bio, buf, count); |
| 2156 |
if nbytes < 0: |
| 2157 |
raise ssl_error(None) |
| 2158 |
|
| 2159 |
if nbytes < count: |
| 2160 |
pass |
| 2161 |
|
| 2162 |
|
| 2163 |
return _bytes_with_len(buf, nbytes) |
| 2164 |
|
| 2165 |
@property |
| 2166 |
def pending(self): |
| 2167 |
return lib.BIO_ctrl_pending(self.bio) |
| 2168 |
|
| 2169 |
|
| 2170 |
def RAND_status(): |
| 2171 |
return lib.RAND_status() |
| 2172 |
|
| 2173 |
def _RAND_bytes(count, pseudo): |
| 2174 |
if count < 0: |
| 2175 |
raise ValueError("num must be positive") |
| 2176 |
buf = ffi.new("unsigned char[]", count) |
| 2177 |
if pseudo: |
| 2178 |
|
| 2179 |
|
| 2180 |
ok = lib.RAND_bytes(buf, count) |
| 2181 |
if ok == 1 or ok == 0: |
| 2182 |
_bytes = _bytes_with_len(buf, count) |
| 2183 |
return (_bytes, ok == 1) |
| 2184 |
else: |
| 2185 |
ok = lib.RAND_bytes(buf, count) |
| 2186 |
if ok == 1 or (pseudo and ok == 0): |
| 2187 |
return _bytes_with_len(buf, count) |
| 2188 |
raise ssl_error(None, errcode=lib.ERR_get_error()) |
| 2189 |
|
| 2190 |
def RAND_pseudo_bytes(count): |
| 2191 |
warnings.warn("ssl.RAND_pseudo_bytes() is deprecated", DeprecationWarning) |
| 2192 |
return _RAND_bytes(count, True) |
| 2193 |
|
| 2194 |
def RAND_bytes(count): |
| 2195 |
return _RAND_bytes(count, False) |
| 2196 |
|
| 2197 |
def RAND_add(view, entropy): |
| 2198 |
buf = _str_to_ffi_buffer(view) |
| 2199 |
lib.RAND_add(buf, len(buf), entropy) |
| 2200 |
|
| 2201 |
def get_default_verify_paths(): |
| 2202 |
''' |
| 2203 |
Find a certificate store and associated values |
| 2204 |
|
| 2205 |
Returns something like |
| 2206 |
`('SSL_CERT_FILE', '/usr/lib/ssl/cert.pem', 'SSL_CERT_DIR', '/usr/lib/ssl/certs')` |
| 2207 |
on Ubuntu and windows10 |
| 2208 |
|
| 2209 |
`('SSL_CERT_FILE', '/usr/local/cert.pem', 'SSL_CERT_DIR', '/usr/local/certs')` |
| 2210 |
on CentOS |
| 2211 |
|
| 2212 |
`('SSL_CERT_FILE', '/Library/Frameworks/Python.framework/Versions/2.7/etc/openssl/cert.pem', |
| 2213 |
'SSL_CERT_DIR', '/Library/Frameworks/Python.framework/Versions/2.7/etc/openssl/certs')` |
| 2214 |
on Darwin |
| 2215 |
|
| 2216 |
For portable builds (based on CentOS, but could be running on any glibc |
| 2217 |
linux) we need to check other locations. The list of places to try was taken |
| 2218 |
from golang in Dec 2018: |
| 2219 |
https://golang.org/src/crypto/x509/root_unix.go (for the directories), |
| 2220 |
https://golang.org/src/crypto/x509/root_linux.go (for the files) |
| 2221 |
''' |
| 2222 |
certFiles = [ |
| 2223 |
"/etc/ssl/certs/ca-certificates.crt", |
| 2224 |
"/etc/pki/tls/certs/ca-bundle.crt", |
| 2225 |
"/etc/ssl/ca-bundle.pem", |
| 2226 |
"/etc/pki/tls/cacert.pem", |
| 2227 |
"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", |
| 2228 |
"/etc/ssl/cert.pem", |
| 2229 |
] |
| 2230 |
certDirectories = [ |
| 2231 |
"/etc/ssl/certs", |
| 2232 |
"/system/etc/security/cacerts", |
| 2233 |
"/usr/local/share/certs", |
| 2234 |
"/etc/pki/tls/certs", |
| 2235 |
"/etc/openssl/certs", |
| 2236 |
"/var/ssl/certs", |
| 2237 |
] |
| 2238 |
|
| 2239 |
|
| 2240 |
if getattr(get_default_verify_paths, 'retval', None): |
| 2241 |
return get_default_verify_paths.retval |
| 2242 |
|
| 2243 |
|
| 2244 |
ofile_env = _cstr_decode_fs(lib.X509_get_default_cert_file_env()) |
| 2245 |
odir_env = _cstr_decode_fs(lib.X509_get_default_cert_dir_env()) |
| 2246 |
|
| 2247 |
|
| 2248 |
ofile = _cstr_decode_fs(lib.X509_get_default_cert_file()) |
| 2249 |
odir = _cstr_decode_fs(lib.X509_get_default_cert_dir()) |
| 2250 |
|
| 2251 |
if os.path.exists(ofile) and os.path.exists(odir): |
| 2252 |
get_default_verify_paths.retval = (ofile_env, ofile, odir_env, odir) |
| 2253 |
return get_default_verify_paths.retval |
| 2254 |
|
| 2255 |
|
| 2256 |
for f in certFiles: |
| 2257 |
if os.path.exists(f): |
| 2258 |
ofile = f |
| 2259 |
for f in certDirectories: |
| 2260 |
if os.path.exists(f): |
| 2261 |
odir = f |
| 2262 |
get_default_verify_paths.retval = (ofile_env, ofile, odir_env, odir) |
| 2263 |
return get_default_verify_paths.retval |
| 2264 |
|
| 2265 |
|
| 2266 |
@ffi.callback("int(SSL*,unsigned char **,unsigned char *,const unsigned char *,unsigned int,void *)") |
| 2267 |
def select_alpn_callback(ssl, out, outlen, client_protocols, client_protocols_len, args): |
| 2268 |
ctx = ffi.from_handle(args) |
| 2269 |
return do_protocol_selection(1, out, outlen, |
| 2270 |
ffi.cast("unsigned char*",ctx.alpn_protocols), len(ctx.alpn_protocols), |
| 2271 |
client_protocols, client_protocols_len) |
| 2272 |
|
| 2273 |
if lib.OPENSSL_NPN_NEGOTIATED: |
| 2274 |
@ffi.callback("int(SSL*,unsigned char **,unsigned char *,const unsigned char *,unsigned int,void *)") |
| 2275 |
def select_npn_callback(ssl, out, outlen, server_protocols, server_protocols_len, args): |
| 2276 |
ctx = ffi.from_handle(args) |
| 2277 |
return do_protocol_selection(0, out, outlen, server_protocols, server_protocols_len, |
| 2278 |
ffi.cast("unsigned char*",ctx.npn_protocols), len(ctx.npn_protocols)) |
| 2279 |
|
| 2280 |
|
| 2281 |
@ffi.callback("int(SSL*,const unsigned char**, unsigned int*, void*)") |
| 2282 |
def advertise_npn_callback(ssl, data, length, args): |
| 2283 |
ctx = ffi.from_handle(args) |
| 2284 |
|
| 2285 |
if not ctx.npn_protocols: |
| 2286 |
data[0] = ffi.new("unsigned char*", b"") |
| 2287 |
length[0] = 0 |
| 2288 |
else: |
| 2289 |
data[0] = ffi.cast("unsigned char*",ctx.npn_protocols) |
| 2290 |
length[0] = len(ctx.npn_protocols) |
| 2291 |
|
| 2292 |
return lib.SSL_TLSEXT_ERR_OK |
| 2293 |
|
| 2294 |
|
| 2295 |
def do_protocol_selection(alpn, out, outlen, server_protocols, server_protocols_len, |
| 2296 |
client_protocols, client_protocols_len): |
| 2297 |
if client_protocols == ffi.NULL: |
| 2298 |
client_protocols = b"" |
| 2299 |
client_protocols_len = 0 |
| 2300 |
if server_protocols == ffi.NULL: |
| 2301 |
server_protocols = "" |
| 2302 |
server_protocols_len = 0 |
| 2303 |
|
| 2304 |
ret = lib.SSL_select_next_proto(out, outlen, |
| 2305 |
server_protocols, server_protocols_len, |
| 2306 |
client_protocols, client_protocols_len); |
| 2307 |
if alpn and ret != lib.OPENSSL_NPN_NEGOTIATED: |
| 2308 |
return lib.SSL_TLSEXT_ERR_NOACK |
| 2309 |
|
| 2310 |
return lib.SSL_TLSEXT_ERR_OK |
| 2311 |
|
| 2312 |
if lib.Cryptography_HAS_EGD: |
| 2313 |
def RAND_egd(path): |
| 2314 |
bytecount = lib.RAND_egd_bytes(ffi.from_buffer(path), len(path)) |
| 2315 |
if bytecount == -1: |
| 2316 |
raise SSLError("EGD connection failed or EGD did not return " |
| 2317 |
"enough data to seed the PRNG"); |
| 2318 |
return bytecount |
| 2319 |
|
| 2320 |
socket.RAND_add = RAND_add |
| 2321 |
socket.RAND_status = RAND_status |