Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
allendowney
GitHub Repository: allendowney/cpython
Path: blob/main/Modules/_ssl.c
12 views
1
/* SSL socket module
2
3
SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
4
Re-worked a bit by Bill Janssen to add server-side support and
5
certificate decoding. Chris Stawarz contributed some non-blocking
6
patches.
7
8
This module is imported by ssl.py. It should *not* be used
9
directly.
10
11
XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
12
13
XXX integrate several "shutdown modes" as suggested in
14
http://bugs.python.org/issue8108#msg102867 ?
15
*/
16
17
#ifndef Py_BUILD_CORE_BUILTIN
18
# define Py_BUILD_CORE_MODULE 1
19
#endif
20
21
/* Don't warn about deprecated functions, */
22
#ifndef OPENSSL_API_COMPAT
23
// 0x10101000L == 1.1.1, 30000 == 3.0.0
24
#define OPENSSL_API_COMPAT 0x10101000L
25
#endif
26
#define OPENSSL_NO_DEPRECATED 1
27
28
#include "Python.h"
29
#include "pycore_weakref.h" // _PyWeakref_GET_REF()
30
31
/* Include symbols from _socket module */
32
#include "socketmodule.h"
33
34
#ifdef MS_WINDOWS
35
# include <wincrypt.h>
36
#endif
37
38
#include "_ssl.h"
39
40
/* Redefined below for Windows debug builds after important #includes */
41
#define _PySSL_FIX_ERRNO
42
43
#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
44
do { (save) = PyEval_SaveThread(); } while(0)
45
#define PySSL_END_ALLOW_THREADS_S(save) \
46
do { PyEval_RestoreThread(save); _PySSL_FIX_ERRNO; } while(0)
47
#define PySSL_BEGIN_ALLOW_THREADS { \
48
PyThreadState *_save = NULL; \
49
PySSL_BEGIN_ALLOW_THREADS_S(_save);
50
#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
51
52
53
#if defined(HAVE_POLL_H)
54
#include <poll.h>
55
#elif defined(HAVE_SYS_POLL_H)
56
#include <sys/poll.h>
57
#endif
58
59
/* Include OpenSSL header files */
60
#include "openssl/rsa.h"
61
#include "openssl/crypto.h"
62
#include "openssl/x509.h"
63
#include "openssl/x509v3.h"
64
#include "openssl/pem.h"
65
#include "openssl/ssl.h"
66
#include "openssl/err.h"
67
#include "openssl/rand.h"
68
#include "openssl/bio.h"
69
#include "openssl/dh.h"
70
71
#ifndef OPENSSL_THREADS
72
# error "OPENSSL_THREADS is not defined, Python requires thread-safe OpenSSL"
73
#endif
74
75
76
77
struct py_ssl_error_code {
78
const char *mnemonic;
79
int library, reason;
80
};
81
82
struct py_ssl_library_code {
83
const char *library;
84
int code;
85
};
86
87
#if defined(MS_WINDOWS) && defined(Py_DEBUG)
88
/* Debug builds on Windows rely on getting errno directly from OpenSSL.
89
* However, because it uses a different CRT, we need to transfer the
90
* value of errno from OpenSSL into our debug CRT.
91
*
92
* Don't be fooled - this is horribly ugly code. The only reasonable
93
* alternative is to do both debug and release builds of OpenSSL, which
94
* requires much uglier code to transform their automatically generated
95
* makefile. This is the lesser of all the evils.
96
*/
97
98
static void _PySSLFixErrno(void) {
99
HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
100
if (!ucrtbase) {
101
/* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
102
* have a catastrophic failure, but this function is not the
103
* place to raise it. */
104
return;
105
}
106
107
typedef int *(__stdcall *errno_func)(void);
108
errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
109
if (ssl_errno) {
110
errno = *ssl_errno();
111
*ssl_errno() = 0;
112
} else {
113
errno = ENOTRECOVERABLE;
114
}
115
}
116
117
#undef _PySSL_FIX_ERRNO
118
#define _PySSL_FIX_ERRNO _PySSLFixErrno()
119
#endif
120
121
/* Include generated data (error codes) */
122
#if (OPENSSL_VERSION_NUMBER >= 0x30100000L)
123
#include "_ssl_data_31.h"
124
#elif (OPENSSL_VERSION_NUMBER >= 0x30000000L)
125
#include "_ssl_data_300.h"
126
#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
127
#include "_ssl_data_111.h"
128
#else
129
#include "_ssl_data.h"
130
#endif
131
132
/* OpenSSL API 1.1.0+ does not include version methods */
133
#ifndef OPENSSL_NO_SSL3_METHOD
134
extern const SSL_METHOD *SSLv3_method(void);
135
#endif
136
#ifndef OPENSSL_NO_TLS1_METHOD
137
extern const SSL_METHOD *TLSv1_method(void);
138
#endif
139
#ifndef OPENSSL_NO_TLS1_1_METHOD
140
extern const SSL_METHOD *TLSv1_1_method(void);
141
#endif
142
#ifndef OPENSSL_NO_TLS1_2_METHOD
143
extern const SSL_METHOD *TLSv1_2_method(void);
144
#endif
145
146
#ifndef INVALID_SOCKET /* MS defines this */
147
#define INVALID_SOCKET (-1)
148
#endif
149
150
/* Default cipher suites */
151
#ifndef PY_SSL_DEFAULT_CIPHERS
152
#define PY_SSL_DEFAULT_CIPHERS 1
153
#endif
154
155
#if PY_SSL_DEFAULT_CIPHERS == 0
156
#ifndef PY_SSL_DEFAULT_CIPHER_STRING
157
#error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
158
#endif
159
#ifndef PY_SSL_MIN_PROTOCOL
160
#define PY_SSL_MIN_PROTOCOL TLS1_2_VERSION
161
#endif
162
#elif PY_SSL_DEFAULT_CIPHERS == 1
163
/* Python custom selection of sensible cipher suites
164
* @SECLEVEL=2: security level 2 with 112 bits minimum security (e.g. 2048 bits RSA key)
165
* ECDH+*: enable ephemeral elliptic curve Diffie-Hellman
166
* DHE+*: fallback to ephemeral finite field Diffie-Hellman
167
* encryption order: AES AEAD (GCM), ChaCha AEAD, AES CBC
168
* !aNULL:!eNULL: really no NULL ciphers
169
* !aDSS: no authentication with discrete logarithm DSA algorithm
170
* !SHA1: no weak SHA1 MAC
171
* !AESCCM: no CCM mode, it's uncommon and slow
172
*
173
* Based on Hynek's excellent blog post (update 2021-02-11)
174
* https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
175
*/
176
#define PY_SSL_DEFAULT_CIPHER_STRING "@SECLEVEL=2:ECDH+AESGCM:ECDH+CHACHA20:ECDH+AES:DHE+AES:!aNULL:!eNULL:!aDSS:!SHA1:!AESCCM"
177
#ifndef PY_SSL_MIN_PROTOCOL
178
#define PY_SSL_MIN_PROTOCOL TLS1_2_VERSION
179
#endif
180
#elif PY_SSL_DEFAULT_CIPHERS == 2
181
/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
182
#define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
183
#else
184
#error "Unsupported PY_SSL_DEFAULT_CIPHERS"
185
#endif
186
187
188
enum py_ssl_error {
189
/* these mirror ssl.h */
190
PY_SSL_ERROR_NONE,
191
PY_SSL_ERROR_SSL,
192
PY_SSL_ERROR_WANT_READ,
193
PY_SSL_ERROR_WANT_WRITE,
194
PY_SSL_ERROR_WANT_X509_LOOKUP,
195
PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
196
PY_SSL_ERROR_ZERO_RETURN,
197
PY_SSL_ERROR_WANT_CONNECT,
198
/* start of non ssl.h errorcodes */
199
PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
200
PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
201
PY_SSL_ERROR_INVALID_ERROR_CODE
202
};
203
204
enum py_ssl_server_or_client {
205
PY_SSL_CLIENT,
206
PY_SSL_SERVER
207
};
208
209
enum py_ssl_cert_requirements {
210
PY_SSL_CERT_NONE,
211
PY_SSL_CERT_OPTIONAL,
212
PY_SSL_CERT_REQUIRED
213
};
214
215
enum py_ssl_version {
216
PY_SSL_VERSION_SSL2,
217
PY_SSL_VERSION_SSL3=1,
218
PY_SSL_VERSION_TLS, /* SSLv23 */
219
PY_SSL_VERSION_TLS1,
220
PY_SSL_VERSION_TLS1_1,
221
PY_SSL_VERSION_TLS1_2,
222
PY_SSL_VERSION_TLS_CLIENT=0x10,
223
PY_SSL_VERSION_TLS_SERVER,
224
};
225
226
enum py_proto_version {
227
PY_PROTO_MINIMUM_SUPPORTED = -2,
228
PY_PROTO_SSLv3 = SSL3_VERSION,
229
PY_PROTO_TLSv1 = TLS1_VERSION,
230
PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
231
PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
232
#ifdef TLS1_3_VERSION
233
PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
234
#else
235
PY_PROTO_TLSv1_3 = 0x304,
236
#endif
237
PY_PROTO_MAXIMUM_SUPPORTED = -1,
238
239
/* OpenSSL has no dedicated API to set the minimum version to the maximum
240
* available version, and the other way around. We have to figure out the
241
* minimum and maximum available version on our own and hope for the best.
242
*/
243
#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
244
PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
245
#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
246
PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
247
#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
248
PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
249
#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
250
PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
251
#elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
252
PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
253
#else
254
#error "PY_PROTO_MINIMUM_AVAILABLE not found"
255
#endif
256
257
#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
258
PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
259
#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
260
PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
261
#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
262
PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
263
#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
264
PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
265
#elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
266
PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
267
#else
268
#error "PY_PROTO_MAXIMUM_AVAILABLE not found"
269
#endif
270
};
271
272
/* SSL socket object */
273
274
#define X509_NAME_MAXLEN 256
275
276
277
/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
278
* older SSL, but let's be safe */
279
#define PySSL_CB_MAXLEN 128
280
281
282
typedef struct {
283
PyObject_HEAD
284
SSL_CTX *ctx;
285
unsigned char *alpn_protocols;
286
unsigned int alpn_protocols_len;
287
PyObject *set_sni_cb;
288
int check_hostname;
289
/* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
290
* We have to maintain our own copy. OpenSSL's hostflags default to 0.
291
*/
292
unsigned int hostflags;
293
int protocol;
294
#ifdef TLS1_3_VERSION
295
int post_handshake_auth;
296
#endif
297
PyObject *msg_cb;
298
PyObject *keylog_filename;
299
BIO *keylog_bio;
300
/* Cached module state, also used in SSLSocket and SSLSession code. */
301
_sslmodulestate *state;
302
} PySSLContext;
303
304
typedef struct {
305
int ssl; /* last seen error from SSL */
306
int c; /* last seen error from libc */
307
#ifdef MS_WINDOWS
308
int ws; /* last seen error from winsock */
309
#endif
310
} _PySSLError;
311
312
typedef struct {
313
PyObject_HEAD
314
PyObject *Socket; /* weakref to socket on which we're layered */
315
SSL *ssl;
316
PySSLContext *ctx; /* weakref to SSL context */
317
char shutdown_seen_zero;
318
enum py_ssl_server_or_client socket_type;
319
PyObject *owner; /* Python level "owner" passed to servername callback */
320
PyObject *server_hostname;
321
_PySSLError err; /* last seen error from various sources */
322
/* Some SSL callbacks don't have error reporting. Callback wrappers
323
* store exception information on the socket. The handshake, read, write,
324
* and shutdown methods check for chained exceptions.
325
*/
326
PyObject *exc;
327
} PySSLSocket;
328
329
typedef struct {
330
PyObject_HEAD
331
BIO *bio;
332
int eof_written;
333
} PySSLMemoryBIO;
334
335
typedef struct {
336
PyObject_HEAD
337
SSL_SESSION *session;
338
PySSLContext *ctx;
339
} PySSLSession;
340
341
static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
342
{
343
_PySSLError err = { 0 };
344
if (failed) {
345
#ifdef MS_WINDOWS
346
err.ws = WSAGetLastError();
347
_PySSL_FIX_ERRNO;
348
#endif
349
err.c = errno;
350
err.ssl = SSL_get_error(ssl, retcode);
351
}
352
return err;
353
}
354
355
/*[clinic input]
356
module _ssl
357
class _ssl._SSLContext "PySSLContext *" "get_state_type(type)->PySSLContext_Type"
358
class _ssl._SSLSocket "PySSLSocket *" "get_state_type(type)->PySSLSocket_Type"
359
class _ssl.MemoryBIO "PySSLMemoryBIO *" "get_state_type(type)->PySSLMemoryBIO_Type"
360
class _ssl.SSLSession "PySSLSession *" "get_state_type(type)->PySSLSession_Type"
361
[clinic start generated code]*/
362
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=d293bed8bae240fd]*/
363
364
#include "clinic/_ssl.c.h"
365
366
static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
367
368
static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
369
static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
370
371
typedef enum {
372
SOCKET_IS_NONBLOCKING,
373
SOCKET_IS_BLOCKING,
374
SOCKET_HAS_TIMED_OUT,
375
SOCKET_HAS_BEEN_CLOSED,
376
SOCKET_TOO_LARGE_FOR_SELECT,
377
SOCKET_OPERATION_OK
378
} timeout_state;
379
380
/* Wrap error strings with filename and line # */
381
#define ERRSTR1(x,y,z) (x ":" y ": " z)
382
#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
383
384
// Get the socket from a PySSLSocket, if it has one.
385
// Return a borrowed reference.
386
static inline PySocketSockObject* GET_SOCKET(PySSLSocket *obj) {
387
if (obj->Socket) {
388
PyObject *sock = _PyWeakref_GET_REF(obj->Socket);
389
if (sock != NULL) {
390
// GET_SOCKET() returns a borrowed reference
391
Py_DECREF(sock);
392
}
393
else {
394
// dead weak reference
395
sock = Py_None;
396
}
397
return (PySocketSockObject *)sock; // borrowed reference
398
}
399
else {
400
return NULL;
401
}
402
}
403
404
/* If sock is NULL, use a timeout of 0 second */
405
#define GET_SOCKET_TIMEOUT(sock) \
406
((sock != NULL) ? (sock)->sock_timeout : 0)
407
408
#include "_ssl/debughelpers.c"
409
410
/*
411
* SSL errors.
412
*/
413
414
PyDoc_STRVAR(SSLError_doc,
415
"An error occurred in the SSL implementation.");
416
417
PyDoc_STRVAR(SSLCertVerificationError_doc,
418
"A certificate could not be verified.");
419
420
PyDoc_STRVAR(SSLZeroReturnError_doc,
421
"SSL/TLS session closed cleanly.");
422
423
PyDoc_STRVAR(SSLWantReadError_doc,
424
"Non-blocking SSL socket needs to read more data\n"
425
"before the requested operation can be completed.");
426
427
PyDoc_STRVAR(SSLWantWriteError_doc,
428
"Non-blocking SSL socket needs to write more data\n"
429
"before the requested operation can be completed.");
430
431
PyDoc_STRVAR(SSLSyscallError_doc,
432
"System error when attempting SSL operation.");
433
434
PyDoc_STRVAR(SSLEOFError_doc,
435
"SSL/TLS connection terminated abruptly.");
436
437
static PyObject *
438
SSLError_str(PyOSErrorObject *self)
439
{
440
if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
441
return Py_NewRef(self->strerror);
442
}
443
else
444
return PyObject_Str(self->args);
445
}
446
447
static PyType_Slot sslerror_type_slots[] = {
448
{Py_tp_doc, (void*)SSLError_doc},
449
{Py_tp_str, SSLError_str},
450
{0, 0},
451
};
452
453
static PyType_Spec sslerror_type_spec = {
454
.name = "ssl.SSLError",
455
.basicsize = sizeof(PyOSErrorObject),
456
.flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_IMMUTABLETYPE),
457
.slots = sslerror_type_slots
458
};
459
460
static void
461
fill_and_set_sslerror(_sslmodulestate *state,
462
PySSLSocket *sslsock, PyObject *type, int ssl_errno,
463
const char *errstr, int lineno, unsigned long errcode)
464
{
465
PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
466
PyObject *verify_obj = NULL, *verify_code_obj = NULL;
467
PyObject *init_value, *msg, *key;
468
469
if (errcode != 0) {
470
int lib, reason;
471
472
lib = ERR_GET_LIB(errcode);
473
reason = ERR_GET_REASON(errcode);
474
key = Py_BuildValue("ii", lib, reason);
475
if (key == NULL)
476
goto fail;
477
reason_obj = PyDict_GetItemWithError(state->err_codes_to_names, key);
478
Py_DECREF(key);
479
if (reason_obj == NULL && PyErr_Occurred()) {
480
goto fail;
481
}
482
key = PyLong_FromLong(lib);
483
if (key == NULL)
484
goto fail;
485
lib_obj = PyDict_GetItemWithError(state->lib_codes_to_names, key);
486
Py_DECREF(key);
487
if (lib_obj == NULL && PyErr_Occurred()) {
488
goto fail;
489
}
490
if (errstr == NULL)
491
errstr = ERR_reason_error_string(errcode);
492
}
493
if (errstr == NULL)
494
errstr = "unknown error";
495
496
/* verify code for cert validation error */
497
if ((sslsock != NULL) && (type == state->PySSLCertVerificationErrorObject)) {
498
const char *verify_str = NULL;
499
long verify_code;
500
501
verify_code = SSL_get_verify_result(sslsock->ssl);
502
verify_code_obj = PyLong_FromLong(verify_code);
503
if (verify_code_obj == NULL) {
504
goto fail;
505
}
506
507
switch (verify_code) {
508
case X509_V_ERR_HOSTNAME_MISMATCH:
509
verify_obj = PyUnicode_FromFormat(
510
"Hostname mismatch, certificate is not valid for '%S'.",
511
sslsock->server_hostname
512
);
513
break;
514
case X509_V_ERR_IP_ADDRESS_MISMATCH:
515
verify_obj = PyUnicode_FromFormat(
516
"IP address mismatch, certificate is not valid for '%S'.",
517
sslsock->server_hostname
518
);
519
break;
520
default:
521
verify_str = X509_verify_cert_error_string(verify_code);
522
if (verify_str != NULL) {
523
verify_obj = PyUnicode_FromString(verify_str);
524
} else {
525
verify_obj = Py_NewRef(Py_None);
526
}
527
break;
528
}
529
if (verify_obj == NULL) {
530
goto fail;
531
}
532
}
533
534
if (verify_obj && reason_obj && lib_obj)
535
msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
536
lib_obj, reason_obj, errstr, verify_obj,
537
lineno);
538
else if (reason_obj && lib_obj)
539
msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
540
lib_obj, reason_obj, errstr, lineno);
541
else if (lib_obj)
542
msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
543
lib_obj, errstr, lineno);
544
else
545
msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
546
if (msg == NULL)
547
goto fail;
548
549
init_value = Py_BuildValue("iN", ERR_GET_REASON(ssl_errno), msg);
550
if (init_value == NULL)
551
goto fail;
552
553
err_value = PyObject_CallObject(type, init_value);
554
Py_DECREF(init_value);
555
if (err_value == NULL)
556
goto fail;
557
558
if (reason_obj == NULL)
559
reason_obj = Py_None;
560
if (PyObject_SetAttr(err_value, state->str_reason, reason_obj))
561
goto fail;
562
563
if (lib_obj == NULL)
564
lib_obj = Py_None;
565
if (PyObject_SetAttr(err_value, state->str_library, lib_obj))
566
goto fail;
567
568
if ((sslsock != NULL) && (type == state->PySSLCertVerificationErrorObject)) {
569
/* Only set verify code / message for SSLCertVerificationError */
570
if (PyObject_SetAttr(err_value, state->str_verify_code,
571
verify_code_obj))
572
goto fail;
573
if (PyObject_SetAttr(err_value, state->str_verify_message, verify_obj))
574
goto fail;
575
}
576
577
PyErr_SetObject(type, err_value);
578
fail:
579
Py_XDECREF(err_value);
580
Py_XDECREF(verify_code_obj);
581
Py_XDECREF(verify_obj);
582
}
583
584
static int
585
PySSL_ChainExceptions(PySSLSocket *sslsock) {
586
if (sslsock->exc == NULL)
587
return 0;
588
589
_PyErr_ChainExceptions1(sslsock->exc);
590
sslsock->exc = NULL;
591
return -1;
592
}
593
594
static PyObject *
595
PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
596
{
597
PyObject *type;
598
char *errstr = NULL;
599
_PySSLError err;
600
enum py_ssl_error p = PY_SSL_ERROR_NONE;
601
unsigned long e = 0;
602
603
assert(sslsock != NULL);
604
605
_sslmodulestate *state = get_state_sock(sslsock);
606
type = state->PySSLErrorObject;
607
608
assert(ret <= 0);
609
e = ERR_peek_last_error();
610
611
if (sslsock->ssl != NULL) {
612
err = sslsock->err;
613
614
switch (err.ssl) {
615
case SSL_ERROR_ZERO_RETURN:
616
errstr = "TLS/SSL connection has been closed (EOF)";
617
type = state->PySSLZeroReturnErrorObject;
618
p = PY_SSL_ERROR_ZERO_RETURN;
619
break;
620
case SSL_ERROR_WANT_READ:
621
errstr = "The operation did not complete (read)";
622
type = state->PySSLWantReadErrorObject;
623
p = PY_SSL_ERROR_WANT_READ;
624
break;
625
case SSL_ERROR_WANT_WRITE:
626
p = PY_SSL_ERROR_WANT_WRITE;
627
type = state->PySSLWantWriteErrorObject;
628
errstr = "The operation did not complete (write)";
629
break;
630
case SSL_ERROR_WANT_X509_LOOKUP:
631
p = PY_SSL_ERROR_WANT_X509_LOOKUP;
632
errstr = "The operation did not complete (X509 lookup)";
633
break;
634
case SSL_ERROR_WANT_CONNECT:
635
p = PY_SSL_ERROR_WANT_CONNECT;
636
errstr = "The operation did not complete (connect)";
637
break;
638
case SSL_ERROR_SYSCALL:
639
{
640
if (e == 0) {
641
PySocketSockObject *s = GET_SOCKET(sslsock);
642
if (ret == 0 || (((PyObject *)s) == Py_None)) {
643
p = PY_SSL_ERROR_EOF;
644
type = state->PySSLEOFErrorObject;
645
errstr = "EOF occurred in violation of protocol";
646
} else if (s && ret == -1) {
647
/* underlying BIO reported an I/O error */
648
ERR_clear_error();
649
#ifdef MS_WINDOWS
650
if (err.ws) {
651
return PyErr_SetFromWindowsErr(err.ws);
652
}
653
#endif
654
if (err.c) {
655
errno = err.c;
656
return PyErr_SetFromErrno(PyExc_OSError);
657
}
658
else {
659
p = PY_SSL_ERROR_EOF;
660
type = state->PySSLEOFErrorObject;
661
errstr = "EOF occurred in violation of protocol";
662
}
663
} else { /* possible? */
664
p = PY_SSL_ERROR_SYSCALL;
665
type = state->PySSLSyscallErrorObject;
666
errstr = "Some I/O error occurred";
667
}
668
} else {
669
p = PY_SSL_ERROR_SYSCALL;
670
}
671
break;
672
}
673
case SSL_ERROR_SSL:
674
{
675
p = PY_SSL_ERROR_SSL;
676
if (e == 0) {
677
/* possible? */
678
errstr = "A failure in the SSL library occurred";
679
}
680
if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
681
ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
682
type = state->PySSLCertVerificationErrorObject;
683
}
684
#if defined(SSL_R_UNEXPECTED_EOF_WHILE_READING)
685
/* OpenSSL 3.0 changed transport EOF from SSL_ERROR_SYSCALL with
686
* zero return value to SSL_ERROR_SSL with a special error code. */
687
if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
688
ERR_GET_REASON(e) == SSL_R_UNEXPECTED_EOF_WHILE_READING) {
689
p = PY_SSL_ERROR_EOF;
690
type = state->PySSLEOFErrorObject;
691
errstr = "EOF occurred in violation of protocol";
692
}
693
#endif
694
break;
695
}
696
default:
697
p = PY_SSL_ERROR_INVALID_ERROR_CODE;
698
errstr = "Invalid error code";
699
}
700
}
701
fill_and_set_sslerror(state, sslsock, type, p, errstr, lineno, e);
702
ERR_clear_error();
703
PySSL_ChainExceptions(sslsock);
704
return NULL;
705
}
706
707
static PyObject *
708
_setSSLError (_sslmodulestate *state, const char *errstr, int errcode, const char *filename, int lineno)
709
{
710
if (errstr == NULL)
711
errcode = ERR_peek_last_error();
712
else
713
errcode = 0;
714
fill_and_set_sslerror(state, NULL, state->PySSLErrorObject, errcode, errstr, lineno, errcode);
715
ERR_clear_error();
716
return NULL;
717
}
718
719
static int
720
_ssl_deprecated(const char* msg, int stacklevel) {
721
return PyErr_WarnEx(
722
PyExc_DeprecationWarning, msg, stacklevel
723
);
724
}
725
726
#define PY_SSL_DEPRECATED(name, stacklevel, ret) \
727
if (_ssl_deprecated((name), (stacklevel)) == -1) return (ret)
728
729
/*
730
* SSL objects
731
*/
732
733
static int
734
_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
735
{
736
int retval = -1;
737
ASN1_OCTET_STRING *ip;
738
PyObject *hostname;
739
size_t len;
740
741
assert(server_hostname);
742
743
/* Disable OpenSSL's special mode with leading dot in hostname:
744
* When name starts with a dot (e.g ".example.com"), it will be
745
* matched by a certificate valid for any sub-domain of name.
746
*/
747
len = strlen(server_hostname);
748
if (len == 0 || *server_hostname == '.') {
749
PyErr_SetString(
750
PyExc_ValueError,
751
"server_hostname cannot be an empty string or start with a "
752
"leading dot.");
753
return retval;
754
}
755
756
/* inet_pton is not available on all platforms. */
757
ip = a2i_IPADDRESS(server_hostname);
758
if (ip == NULL) {
759
ERR_clear_error();
760
}
761
762
hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
763
if (hostname == NULL) {
764
goto error;
765
}
766
self->server_hostname = hostname;
767
768
/* Only send SNI extension for non-IP hostnames */
769
if (ip == NULL) {
770
if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
771
_setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
772
goto error;
773
}
774
}
775
if (self->ctx->check_hostname) {
776
X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
777
if (ip == NULL) {
778
if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
779
strlen(server_hostname))) {
780
_setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
781
goto error;
782
}
783
} else {
784
if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_get0_data(ip),
785
ASN1_STRING_length(ip))) {
786
_setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
787
goto error;
788
}
789
}
790
}
791
retval = 0;
792
error:
793
if (ip != NULL) {
794
ASN1_OCTET_STRING_free(ip);
795
}
796
return retval;
797
}
798
799
static PySSLSocket *
800
newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
801
enum py_ssl_server_or_client socket_type,
802
char *server_hostname,
803
PyObject *owner, PyObject *session,
804
PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
805
{
806
PySSLSocket *self;
807
SSL_CTX *ctx = sslctx->ctx;
808
_PySSLError err = { 0 };
809
810
if ((socket_type == PY_SSL_SERVER) &&
811
(sslctx->protocol == PY_SSL_VERSION_TLS_CLIENT)) {
812
_setSSLError(get_state_ctx(sslctx),
813
"Cannot create a server socket with a "
814
"PROTOCOL_TLS_CLIENT context", 0, __FILE__, __LINE__);
815
return NULL;
816
}
817
if ((socket_type == PY_SSL_CLIENT) &&
818
(sslctx->protocol == PY_SSL_VERSION_TLS_SERVER)) {
819
_setSSLError(get_state_ctx(sslctx),
820
"Cannot create a client socket with a "
821
"PROTOCOL_TLS_SERVER context", 0, __FILE__, __LINE__);
822
return NULL;
823
}
824
825
self = PyObject_GC_New(PySSLSocket,
826
get_state_ctx(sslctx)->PySSLSocket_Type);
827
if (self == NULL)
828
return NULL;
829
830
self->ssl = NULL;
831
self->Socket = NULL;
832
self->ctx = (PySSLContext*)Py_NewRef(sslctx);
833
self->shutdown_seen_zero = 0;
834
self->owner = NULL;
835
self->server_hostname = NULL;
836
self->err = err;
837
self->exc = NULL;
838
839
/* Make sure the SSL error state is initialized */
840
ERR_clear_error();
841
842
PySSL_BEGIN_ALLOW_THREADS
843
self->ssl = SSL_new(ctx);
844
PySSL_END_ALLOW_THREADS
845
if (self->ssl == NULL) {
846
Py_DECREF(self);
847
_setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
848
return NULL;
849
}
850
/* bpo43522 and OpenSSL < 1.1.1l: copy hostflags manually */
851
#if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION < 0x101010cf
852
X509_VERIFY_PARAM *ssl_params = SSL_get0_param(self->ssl);
853
X509_VERIFY_PARAM_set_hostflags(ssl_params, sslctx->hostflags);
854
#endif
855
SSL_set_app_data(self->ssl, self);
856
if (sock) {
857
SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
858
} else {
859
/* BIOs are reference counted and SSL_set_bio borrows our reference.
860
* To prevent a double free in memory_bio_dealloc() we need to take an
861
* extra reference here. */
862
BIO_up_ref(inbio->bio);
863
BIO_up_ref(outbio->bio);
864
SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
865
}
866
SSL_set_mode(self->ssl,
867
SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
868
869
#ifdef TLS1_3_VERSION
870
if (sslctx->post_handshake_auth == 1) {
871
if (socket_type == PY_SSL_SERVER) {
872
/* bpo-37428: OpenSSL does not ignore SSL_VERIFY_POST_HANDSHAKE.
873
* Set SSL_VERIFY_POST_HANDSHAKE flag only for server sockets and
874
* only in combination with SSL_VERIFY_PEER flag. */
875
int mode = SSL_get_verify_mode(self->ssl);
876
if (mode & SSL_VERIFY_PEER) {
877
int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
878
verify_cb = SSL_get_verify_callback(self->ssl);
879
mode |= SSL_VERIFY_POST_HANDSHAKE;
880
SSL_set_verify(self->ssl, mode, verify_cb);
881
}
882
} else {
883
/* client socket */
884
SSL_set_post_handshake_auth(self->ssl, 1);
885
}
886
}
887
#endif
888
889
if (server_hostname != NULL) {
890
if (_ssl_configure_hostname(self, server_hostname) < 0) {
891
Py_DECREF(self);
892
return NULL;
893
}
894
}
895
/* If the socket is in non-blocking mode or timeout mode, set the BIO
896
* to non-blocking mode (blocking is the default)
897
*/
898
if (sock && sock->sock_timeout >= 0) {
899
BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
900
BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
901
}
902
903
PySSL_BEGIN_ALLOW_THREADS
904
if (socket_type == PY_SSL_CLIENT)
905
SSL_set_connect_state(self->ssl);
906
else
907
SSL_set_accept_state(self->ssl);
908
PySSL_END_ALLOW_THREADS
909
910
self->socket_type = socket_type;
911
if (sock != NULL) {
912
self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
913
if (self->Socket == NULL) {
914
Py_DECREF(self);
915
return NULL;
916
}
917
}
918
if (owner && owner != Py_None) {
919
if (PySSL_set_owner(self, owner, NULL) == -1) {
920
Py_DECREF(self);
921
return NULL;
922
}
923
}
924
if (session && session != Py_None) {
925
if (PySSL_set_session(self, session, NULL) == -1) {
926
Py_DECREF(self);
927
return NULL;
928
}
929
}
930
931
PyObject_GC_Track(self);
932
return self;
933
}
934
935
/* SSL object methods */
936
937
/*[clinic input]
938
_ssl._SSLSocket.do_handshake
939
[clinic start generated code]*/
940
941
static PyObject *
942
_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
943
/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
944
{
945
int ret;
946
_PySSLError err;
947
int sockstate, nonblocking;
948
PySocketSockObject *sock = GET_SOCKET(self);
949
_PyTime_t timeout, deadline = 0;
950
int has_timeout;
951
952
if (sock) {
953
if (((PyObject*)sock) == Py_None) {
954
_setSSLError(get_state_sock(self),
955
"Underlying socket connection gone",
956
PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
957
return NULL;
958
}
959
Py_INCREF(sock);
960
961
/* just in case the blocking state of the socket has been changed */
962
nonblocking = (sock->sock_timeout >= 0);
963
BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
964
BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
965
}
966
967
timeout = GET_SOCKET_TIMEOUT(sock);
968
has_timeout = (timeout > 0);
969
if (has_timeout) {
970
deadline = _PyDeadline_Init(timeout);
971
}
972
973
/* Actually negotiate SSL connection */
974
/* XXX If SSL_do_handshake() returns 0, it's also a failure. */
975
do {
976
PySSL_BEGIN_ALLOW_THREADS
977
ret = SSL_do_handshake(self->ssl);
978
err = _PySSL_errno(ret < 1, self->ssl, ret);
979
PySSL_END_ALLOW_THREADS
980
self->err = err;
981
982
if (PyErr_CheckSignals())
983
goto error;
984
985
if (has_timeout)
986
timeout = _PyDeadline_Get(deadline);
987
988
if (err.ssl == SSL_ERROR_WANT_READ) {
989
sockstate = PySSL_select(sock, 0, timeout);
990
} else if (err.ssl == SSL_ERROR_WANT_WRITE) {
991
sockstate = PySSL_select(sock, 1, timeout);
992
} else {
993
sockstate = SOCKET_OPERATION_OK;
994
}
995
996
if (sockstate == SOCKET_HAS_TIMED_OUT) {
997
PyErr_SetString(PyExc_TimeoutError,
998
ERRSTR("The handshake operation timed out"));
999
goto error;
1000
} else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1001
PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
1002
ERRSTR("Underlying socket has been closed."));
1003
goto error;
1004
} else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1005
PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
1006
ERRSTR("Underlying socket too large for select()."));
1007
goto error;
1008
} else if (sockstate == SOCKET_IS_NONBLOCKING) {
1009
break;
1010
}
1011
} while (err.ssl == SSL_ERROR_WANT_READ ||
1012
err.ssl == SSL_ERROR_WANT_WRITE);
1013
Py_XDECREF(sock);
1014
if (ret < 1)
1015
return PySSL_SetError(self, ret, __FILE__, __LINE__);
1016
if (PySSL_ChainExceptions(self) < 0)
1017
return NULL;
1018
Py_RETURN_NONE;
1019
error:
1020
Py_XDECREF(sock);
1021
PySSL_ChainExceptions(self);
1022
return NULL;
1023
}
1024
1025
static PyObject *
1026
_asn1obj2py(_sslmodulestate *state, const ASN1_OBJECT *name, int no_name)
1027
{
1028
char buf[X509_NAME_MAXLEN];
1029
char *namebuf = buf;
1030
int buflen;
1031
PyObject *name_obj = NULL;
1032
1033
buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
1034
if (buflen < 0) {
1035
_setSSLError(state, NULL, 0, __FILE__, __LINE__);
1036
return NULL;
1037
}
1038
/* initial buffer is too small for oid + terminating null byte */
1039
if (buflen > X509_NAME_MAXLEN - 1) {
1040
/* make OBJ_obj2txt() calculate the required buflen */
1041
buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1042
/* allocate len + 1 for terminating NULL byte */
1043
namebuf = PyMem_Malloc(buflen + 1);
1044
if (namebuf == NULL) {
1045
PyErr_NoMemory();
1046
return NULL;
1047
}
1048
buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1049
if (buflen < 0) {
1050
_setSSLError(state, NULL, 0, __FILE__, __LINE__);
1051
goto done;
1052
}
1053
}
1054
if (!buflen && no_name) {
1055
name_obj = Py_NewRef(Py_None);
1056
}
1057
else {
1058
name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1059
}
1060
1061
done:
1062
if (buf != namebuf) {
1063
PyMem_Free(namebuf);
1064
}
1065
return name_obj;
1066
}
1067
1068
static PyObject *
1069
_create_tuple_for_attribute(_sslmodulestate *state,
1070
ASN1_OBJECT *name, ASN1_STRING *value)
1071
{
1072
Py_ssize_t buflen;
1073
PyObject *pyattr;
1074
PyObject *pyname = _asn1obj2py(state, name, 0);
1075
1076
if (pyname == NULL) {
1077
_setSSLError(state, NULL, 0, __FILE__, __LINE__);
1078
return NULL;
1079
}
1080
1081
if (ASN1_STRING_type(value) == V_ASN1_BIT_STRING) {
1082
buflen = ASN1_STRING_length(value);
1083
pyattr = Py_BuildValue("Ny#", pyname, ASN1_STRING_get0_data(value), buflen);
1084
} else {
1085
unsigned char *valuebuf = NULL;
1086
buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1087
if (buflen < 0) {
1088
_setSSLError(state, NULL, 0, __FILE__, __LINE__);
1089
Py_DECREF(pyname);
1090
return NULL;
1091
}
1092
pyattr = Py_BuildValue("Ns#", pyname, valuebuf, buflen);
1093
OPENSSL_free(valuebuf);
1094
}
1095
return pyattr;
1096
}
1097
1098
static PyObject *
1099
_create_tuple_for_X509_NAME (_sslmodulestate *state, X509_NAME *xname)
1100
{
1101
PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1102
PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1103
PyObject *rdnt;
1104
PyObject *attr = NULL; /* tuple to hold an attribute */
1105
int entry_count = X509_NAME_entry_count(xname);
1106
X509_NAME_ENTRY *entry;
1107
ASN1_OBJECT *name;
1108
ASN1_STRING *value;
1109
int index_counter;
1110
int rdn_level = -1;
1111
int retcode;
1112
1113
dn = PyList_New(0);
1114
if (dn == NULL)
1115
return NULL;
1116
/* now create another tuple to hold the top-level RDN */
1117
rdn = PyList_New(0);
1118
if (rdn == NULL)
1119
goto fail0;
1120
1121
for (index_counter = 0;
1122
index_counter < entry_count;
1123
index_counter++)
1124
{
1125
entry = X509_NAME_get_entry(xname, index_counter);
1126
1127
/* check to see if we've gotten to a new RDN */
1128
if (rdn_level >= 0) {
1129
if (rdn_level != X509_NAME_ENTRY_set(entry)) {
1130
/* yes, new RDN */
1131
/* add old RDN to DN */
1132
rdnt = PyList_AsTuple(rdn);
1133
Py_DECREF(rdn);
1134
if (rdnt == NULL)
1135
goto fail0;
1136
retcode = PyList_Append(dn, rdnt);
1137
Py_DECREF(rdnt);
1138
if (retcode < 0)
1139
goto fail0;
1140
/* create new RDN */
1141
rdn = PyList_New(0);
1142
if (rdn == NULL)
1143
goto fail0;
1144
}
1145
}
1146
rdn_level = X509_NAME_ENTRY_set(entry);
1147
1148
/* now add this attribute to the current RDN */
1149
name = X509_NAME_ENTRY_get_object(entry);
1150
value = X509_NAME_ENTRY_get_data(entry);
1151
attr = _create_tuple_for_attribute(state, name, value);
1152
/*
1153
fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1154
entry->set,
1155
PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1156
PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1157
*/
1158
if (attr == NULL)
1159
goto fail1;
1160
retcode = PyList_Append(rdn, attr);
1161
Py_DECREF(attr);
1162
if (retcode < 0)
1163
goto fail1;
1164
}
1165
/* now, there's typically a dangling RDN */
1166
if (rdn != NULL) {
1167
if (PyList_GET_SIZE(rdn) > 0) {
1168
rdnt = PyList_AsTuple(rdn);
1169
Py_DECREF(rdn);
1170
if (rdnt == NULL)
1171
goto fail0;
1172
retcode = PyList_Append(dn, rdnt);
1173
Py_DECREF(rdnt);
1174
if (retcode < 0)
1175
goto fail0;
1176
}
1177
else {
1178
Py_DECREF(rdn);
1179
}
1180
}
1181
1182
/* convert list to tuple */
1183
rdnt = PyList_AsTuple(dn);
1184
Py_DECREF(dn);
1185
if (rdnt == NULL)
1186
return NULL;
1187
return rdnt;
1188
1189
fail1:
1190
Py_XDECREF(rdn);
1191
1192
fail0:
1193
Py_XDECREF(dn);
1194
return NULL;
1195
}
1196
1197
static PyObject *
1198
_get_peer_alt_names (_sslmodulestate *state, X509 *certificate) {
1199
1200
/* this code follows the procedure outlined in
1201
OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1202
function to extract the STACK_OF(GENERAL_NAME),
1203
then iterates through the stack to add the
1204
names. */
1205
1206
int j;
1207
PyObject *peer_alt_names = Py_None;
1208
PyObject *v = NULL, *t;
1209
GENERAL_NAMES *names = NULL;
1210
GENERAL_NAME *name;
1211
BIO *biobuf = NULL;
1212
char buf[2048];
1213
char *vptr;
1214
int len;
1215
1216
if (certificate == NULL)
1217
return peer_alt_names;
1218
1219
/* get a memory buffer */
1220
biobuf = BIO_new(BIO_s_mem());
1221
if (biobuf == NULL) {
1222
PyErr_SetString(state->PySSLErrorObject, "failed to allocate BIO");
1223
return NULL;
1224
}
1225
1226
names = (GENERAL_NAMES *)X509_get_ext_d2i(
1227
certificate, NID_subject_alt_name, NULL, NULL);
1228
if (names != NULL) {
1229
if (peer_alt_names == Py_None) {
1230
peer_alt_names = PyList_New(0);
1231
if (peer_alt_names == NULL)
1232
goto fail;
1233
}
1234
1235
for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
1236
/* get a rendering of each name in the set of names */
1237
int gntype;
1238
ASN1_STRING *as = NULL;
1239
1240
name = sk_GENERAL_NAME_value(names, j);
1241
gntype = name->type;
1242
switch (gntype) {
1243
case GEN_DIRNAME:
1244
/* we special-case DirName as a tuple of
1245
tuples of attributes */
1246
1247
t = PyTuple_New(2);
1248
if (t == NULL) {
1249
goto fail;
1250
}
1251
1252
v = PyUnicode_FromString("DirName");
1253
if (v == NULL) {
1254
Py_DECREF(t);
1255
goto fail;
1256
}
1257
PyTuple_SET_ITEM(t, 0, v);
1258
1259
v = _create_tuple_for_X509_NAME(state, name->d.dirn);
1260
if (v == NULL) {
1261
Py_DECREF(t);
1262
goto fail;
1263
}
1264
PyTuple_SET_ITEM(t, 1, v);
1265
break;
1266
1267
case GEN_EMAIL:
1268
case GEN_DNS:
1269
case GEN_URI:
1270
/* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1271
correctly, CVE-2013-4238 */
1272
t = PyTuple_New(2);
1273
if (t == NULL)
1274
goto fail;
1275
switch (gntype) {
1276
case GEN_EMAIL:
1277
v = PyUnicode_FromString("email");
1278
as = name->d.rfc822Name;
1279
break;
1280
case GEN_DNS:
1281
v = PyUnicode_FromString("DNS");
1282
as = name->d.dNSName;
1283
break;
1284
case GEN_URI:
1285
v = PyUnicode_FromString("URI");
1286
as = name->d.uniformResourceIdentifier;
1287
break;
1288
}
1289
if (v == NULL) {
1290
Py_DECREF(t);
1291
goto fail;
1292
}
1293
PyTuple_SET_ITEM(t, 0, v);
1294
v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_get0_data(as),
1295
ASN1_STRING_length(as));
1296
if (v == NULL) {
1297
Py_DECREF(t);
1298
goto fail;
1299
}
1300
PyTuple_SET_ITEM(t, 1, v);
1301
break;
1302
1303
case GEN_RID:
1304
t = PyTuple_New(2);
1305
if (t == NULL)
1306
goto fail;
1307
1308
v = PyUnicode_FromString("Registered ID");
1309
if (v == NULL) {
1310
Py_DECREF(t);
1311
goto fail;
1312
}
1313
PyTuple_SET_ITEM(t, 0, v);
1314
1315
len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1316
if (len < 0) {
1317
Py_DECREF(t);
1318
_setSSLError(state, NULL, 0, __FILE__, __LINE__);
1319
goto fail;
1320
} else if (len >= (int)sizeof(buf)) {
1321
v = PyUnicode_FromString("<INVALID>");
1322
} else {
1323
v = PyUnicode_FromStringAndSize(buf, len);
1324
}
1325
if (v == NULL) {
1326
Py_DECREF(t);
1327
goto fail;
1328
}
1329
PyTuple_SET_ITEM(t, 1, v);
1330
break;
1331
1332
case GEN_IPADD:
1333
/* OpenSSL < 3.0.0 adds a trailing \n to IPv6. 3.0.0 removed
1334
* the trailing newline. Remove it in all versions
1335
*/
1336
t = PyTuple_New(2);
1337
if (t == NULL)
1338
goto fail;
1339
1340
v = PyUnicode_FromString("IP Address");
1341
if (v == NULL) {
1342
Py_DECREF(t);
1343
goto fail;
1344
}
1345
PyTuple_SET_ITEM(t, 0, v);
1346
1347
if (name->d.ip->length == 4) {
1348
unsigned char *p = name->d.ip->data;
1349
v = PyUnicode_FromFormat(
1350
"%d.%d.%d.%d",
1351
p[0], p[1], p[2], p[3]
1352
);
1353
} else if (name->d.ip->length == 16) {
1354
unsigned char *p = name->d.ip->data;
1355
v = PyUnicode_FromFormat(
1356
"%X:%X:%X:%X:%X:%X:%X:%X",
1357
p[0] << 8 | p[1],
1358
p[2] << 8 | p[3],
1359
p[4] << 8 | p[5],
1360
p[6] << 8 | p[7],
1361
p[8] << 8 | p[9],
1362
p[10] << 8 | p[11],
1363
p[12] << 8 | p[13],
1364
p[14] << 8 | p[15]
1365
);
1366
} else {
1367
v = PyUnicode_FromString("<invalid>");
1368
}
1369
1370
if (v == NULL) {
1371
Py_DECREF(t);
1372
goto fail;
1373
}
1374
PyTuple_SET_ITEM(t, 1, v);
1375
break;
1376
1377
default:
1378
/* for everything else, we use the OpenSSL print form */
1379
switch (gntype) {
1380
/* check for new general name type */
1381
case GEN_OTHERNAME:
1382
case GEN_X400:
1383
case GEN_EDIPARTY:
1384
case GEN_RID:
1385
break;
1386
default:
1387
if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1388
"Unknown general name type %d",
1389
gntype) == -1) {
1390
goto fail;
1391
}
1392
break;
1393
}
1394
(void) BIO_reset(biobuf);
1395
GENERAL_NAME_print(biobuf, name);
1396
len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1397
if (len < 0) {
1398
_setSSLError(state, NULL, 0, __FILE__, __LINE__);
1399
goto fail;
1400
}
1401
vptr = strchr(buf, ':');
1402
if (vptr == NULL) {
1403
PyErr_Format(PyExc_ValueError,
1404
"Invalid value %.200s",
1405
buf);
1406
goto fail;
1407
}
1408
t = PyTuple_New(2);
1409
if (t == NULL)
1410
goto fail;
1411
v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1412
if (v == NULL) {
1413
Py_DECREF(t);
1414
goto fail;
1415
}
1416
PyTuple_SET_ITEM(t, 0, v);
1417
v = PyUnicode_FromStringAndSize((vptr + 1),
1418
(len - (vptr - buf + 1)));
1419
if (v == NULL) {
1420
Py_DECREF(t);
1421
goto fail;
1422
}
1423
PyTuple_SET_ITEM(t, 1, v);
1424
break;
1425
}
1426
1427
/* and add that rendering to the list */
1428
1429
if (PyList_Append(peer_alt_names, t) < 0) {
1430
Py_DECREF(t);
1431
goto fail;
1432
}
1433
Py_DECREF(t);
1434
}
1435
sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
1436
}
1437
BIO_free(biobuf);
1438
if (peer_alt_names != Py_None) {
1439
v = PyList_AsTuple(peer_alt_names);
1440
Py_DECREF(peer_alt_names);
1441
return v;
1442
} else {
1443
return peer_alt_names;
1444
}
1445
1446
1447
fail:
1448
if (biobuf != NULL)
1449
BIO_free(biobuf);
1450
1451
if (peer_alt_names != Py_None) {
1452
Py_XDECREF(peer_alt_names);
1453
}
1454
1455
return NULL;
1456
}
1457
1458
static PyObject *
1459
_get_aia_uri(X509 *certificate, int nid) {
1460
PyObject *lst = NULL, *ostr = NULL;
1461
int i, result;
1462
AUTHORITY_INFO_ACCESS *info;
1463
1464
info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
1465
if (info == NULL)
1466
return Py_None;
1467
if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1468
AUTHORITY_INFO_ACCESS_free(info);
1469
return Py_None;
1470
}
1471
1472
if ((lst = PyList_New(0)) == NULL) {
1473
goto fail;
1474
}
1475
1476
for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1477
ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1478
ASN1_IA5STRING *uri;
1479
1480
if ((OBJ_obj2nid(ad->method) != nid) ||
1481
(ad->location->type != GEN_URI)) {
1482
continue;
1483
}
1484
uri = ad->location->d.uniformResourceIdentifier;
1485
ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1486
uri->length);
1487
if (ostr == NULL) {
1488
goto fail;
1489
}
1490
result = PyList_Append(lst, ostr);
1491
Py_DECREF(ostr);
1492
if (result < 0) {
1493
goto fail;
1494
}
1495
}
1496
AUTHORITY_INFO_ACCESS_free(info);
1497
1498
/* convert to tuple or None */
1499
if (PyList_Size(lst) == 0) {
1500
Py_DECREF(lst);
1501
return Py_None;
1502
} else {
1503
PyObject *tup;
1504
tup = PyList_AsTuple(lst);
1505
Py_DECREF(lst);
1506
return tup;
1507
}
1508
1509
fail:
1510
AUTHORITY_INFO_ACCESS_free(info);
1511
Py_XDECREF(lst);
1512
return NULL;
1513
}
1514
1515
static PyObject *
1516
_get_crl_dp(X509 *certificate) {
1517
STACK_OF(DIST_POINT) *dps;
1518
int i, j;
1519
PyObject *lst, *res = NULL;
1520
1521
dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
1522
1523
if (dps == NULL)
1524
return Py_None;
1525
1526
lst = PyList_New(0);
1527
if (lst == NULL)
1528
goto done;
1529
1530
for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1531
DIST_POINT *dp;
1532
STACK_OF(GENERAL_NAME) *gns;
1533
1534
dp = sk_DIST_POINT_value(dps, i);
1535
if (dp->distpoint == NULL) {
1536
/* Ignore empty DP value, CVE-2019-5010 */
1537
continue;
1538
}
1539
gns = dp->distpoint->name.fullname;
1540
1541
for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1542
GENERAL_NAME *gn;
1543
ASN1_IA5STRING *uri;
1544
PyObject *ouri;
1545
int err;
1546
1547
gn = sk_GENERAL_NAME_value(gns, j);
1548
if (gn->type != GEN_URI) {
1549
continue;
1550
}
1551
uri = gn->d.uniformResourceIdentifier;
1552
ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1553
uri->length);
1554
if (ouri == NULL)
1555
goto done;
1556
1557
err = PyList_Append(lst, ouri);
1558
Py_DECREF(ouri);
1559
if (err < 0)
1560
goto done;
1561
}
1562
}
1563
1564
/* Convert to tuple. */
1565
res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1566
1567
done:
1568
Py_XDECREF(lst);
1569
CRL_DIST_POINTS_free(dps);
1570
return res;
1571
}
1572
1573
static PyObject *
1574
_decode_certificate(_sslmodulestate *state, X509 *certificate) {
1575
1576
PyObject *retval = NULL;
1577
BIO *biobuf = NULL;
1578
PyObject *peer;
1579
PyObject *peer_alt_names = NULL;
1580
PyObject *issuer;
1581
PyObject *version;
1582
PyObject *sn_obj;
1583
PyObject *obj;
1584
ASN1_INTEGER *serialNumber;
1585
char buf[2048];
1586
int len, result;
1587
const ASN1_TIME *notBefore, *notAfter;
1588
PyObject *pnotBefore, *pnotAfter;
1589
1590
retval = PyDict_New();
1591
if (retval == NULL)
1592
return NULL;
1593
1594
peer = _create_tuple_for_X509_NAME(
1595
state,
1596
X509_get_subject_name(certificate));
1597
if (peer == NULL)
1598
goto fail0;
1599
if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1600
Py_DECREF(peer);
1601
goto fail0;
1602
}
1603
Py_DECREF(peer);
1604
1605
issuer = _create_tuple_for_X509_NAME(
1606
state,
1607
X509_get_issuer_name(certificate));
1608
if (issuer == NULL)
1609
goto fail0;
1610
if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
1611
Py_DECREF(issuer);
1612
goto fail0;
1613
}
1614
Py_DECREF(issuer);
1615
1616
version = PyLong_FromLong(X509_get_version(certificate) + 1);
1617
if (version == NULL)
1618
goto fail0;
1619
if (PyDict_SetItemString(retval, "version", version) < 0) {
1620
Py_DECREF(version);
1621
goto fail0;
1622
}
1623
Py_DECREF(version);
1624
1625
/* get a memory buffer */
1626
biobuf = BIO_new(BIO_s_mem());
1627
if (biobuf == NULL) {
1628
PyErr_SetString(state->PySSLErrorObject, "failed to allocate BIO");
1629
goto fail0;
1630
}
1631
1632
(void) BIO_reset(biobuf);
1633
serialNumber = X509_get_serialNumber(certificate);
1634
/* should not exceed 20 octets, 160 bits, so buf is big enough */
1635
i2a_ASN1_INTEGER(biobuf, serialNumber);
1636
len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1637
if (len < 0) {
1638
_setSSLError(state, NULL, 0, __FILE__, __LINE__);
1639
goto fail1;
1640
}
1641
sn_obj = PyUnicode_FromStringAndSize(buf, len);
1642
if (sn_obj == NULL)
1643
goto fail1;
1644
if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1645
Py_DECREF(sn_obj);
1646
goto fail1;
1647
}
1648
Py_DECREF(sn_obj);
1649
1650
(void) BIO_reset(biobuf);
1651
notBefore = X509_get0_notBefore(certificate);
1652
ASN1_TIME_print(biobuf, notBefore);
1653
len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1654
if (len < 0) {
1655
_setSSLError(state, NULL, 0, __FILE__, __LINE__);
1656
goto fail1;
1657
}
1658
pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1659
if (pnotBefore == NULL)
1660
goto fail1;
1661
if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1662
Py_DECREF(pnotBefore);
1663
goto fail1;
1664
}
1665
Py_DECREF(pnotBefore);
1666
1667
(void) BIO_reset(biobuf);
1668
notAfter = X509_get0_notAfter(certificate);
1669
ASN1_TIME_print(biobuf, notAfter);
1670
len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1671
if (len < 0) {
1672
_setSSLError(state, NULL, 0, __FILE__, __LINE__);
1673
goto fail1;
1674
}
1675
pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1676
if (pnotAfter == NULL)
1677
goto fail1;
1678
if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1679
Py_DECREF(pnotAfter);
1680
goto fail1;
1681
}
1682
Py_DECREF(pnotAfter);
1683
1684
/* Now look for subjectAltName */
1685
1686
peer_alt_names = _get_peer_alt_names(state, certificate);
1687
if (peer_alt_names == NULL)
1688
goto fail1;
1689
else if (peer_alt_names != Py_None) {
1690
if (PyDict_SetItemString(retval, "subjectAltName",
1691
peer_alt_names) < 0) {
1692
Py_DECREF(peer_alt_names);
1693
goto fail1;
1694
}
1695
Py_DECREF(peer_alt_names);
1696
}
1697
1698
/* Authority Information Access: OCSP URIs */
1699
obj = _get_aia_uri(certificate, NID_ad_OCSP);
1700
if (obj == NULL) {
1701
goto fail1;
1702
} else if (obj != Py_None) {
1703
result = PyDict_SetItemString(retval, "OCSP", obj);
1704
Py_DECREF(obj);
1705
if (result < 0) {
1706
goto fail1;
1707
}
1708
}
1709
1710
obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1711
if (obj == NULL) {
1712
goto fail1;
1713
} else if (obj != Py_None) {
1714
result = PyDict_SetItemString(retval, "caIssuers", obj);
1715
Py_DECREF(obj);
1716
if (result < 0) {
1717
goto fail1;
1718
}
1719
}
1720
1721
/* CDP (CRL distribution points) */
1722
obj = _get_crl_dp(certificate);
1723
if (obj == NULL) {
1724
goto fail1;
1725
} else if (obj != Py_None) {
1726
result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1727
Py_DECREF(obj);
1728
if (result < 0) {
1729
goto fail1;
1730
}
1731
}
1732
1733
BIO_free(biobuf);
1734
return retval;
1735
1736
fail1:
1737
if (biobuf != NULL)
1738
BIO_free(biobuf);
1739
fail0:
1740
Py_XDECREF(retval);
1741
return NULL;
1742
}
1743
1744
static PyObject *
1745
_certificate_to_der(_sslmodulestate *state, X509 *certificate)
1746
{
1747
unsigned char *bytes_buf = NULL;
1748
int len;
1749
PyObject *retval;
1750
1751
bytes_buf = NULL;
1752
len = i2d_X509(certificate, &bytes_buf);
1753
if (len < 0) {
1754
_setSSLError(state, NULL, 0, __FILE__, __LINE__);
1755
return NULL;
1756
}
1757
/* this is actually an immutable bytes sequence */
1758
retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1759
OPENSSL_free(bytes_buf);
1760
return retval;
1761
}
1762
1763
#include "_ssl/misc.c"
1764
#include "_ssl/cert.c"
1765
1766
/*[clinic input]
1767
_ssl._test_decode_cert
1768
path: object(converter="PyUnicode_FSConverter")
1769
/
1770
1771
[clinic start generated code]*/
1772
1773
static PyObject *
1774
_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1775
/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
1776
{
1777
PyObject *retval = NULL;
1778
X509 *x=NULL;
1779
BIO *cert;
1780
_sslmodulestate *state = get_ssl_state(module);
1781
1782
if ((cert=BIO_new(BIO_s_file())) == NULL) {
1783
PyErr_SetString(state->PySSLErrorObject,
1784
"Can't malloc memory to read file");
1785
goto fail0;
1786
}
1787
1788
if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
1789
PyErr_SetString(state->PySSLErrorObject,
1790
"Can't open file");
1791
goto fail0;
1792
}
1793
1794
x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
1795
if (x == NULL) {
1796
PyErr_SetString(state->PySSLErrorObject,
1797
"Error decoding PEM-encoded file");
1798
goto fail0;
1799
}
1800
1801
retval = _decode_certificate(state, x);
1802
X509_free(x);
1803
1804
fail0:
1805
Py_DECREF(path);
1806
if (cert != NULL) BIO_free(cert);
1807
return retval;
1808
}
1809
1810
1811
/*[clinic input]
1812
_ssl._SSLSocket.getpeercert
1813
der as binary_mode: bool = False
1814
/
1815
1816
Returns the certificate for the peer.
1817
1818
If no certificate was provided, returns None. If a certificate was
1819
provided, but not validated, returns an empty dictionary. Otherwise
1820
returns a dict containing information about the peer certificate.
1821
1822
If the optional argument is True, returns a DER-encoded copy of the
1823
peer certificate, or None if no certificate was provided. This will
1824
return the certificate even if it wasn't validated.
1825
[clinic start generated code]*/
1826
1827
static PyObject *
1828
_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1829
/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
1830
{
1831
int verification;
1832
X509 *peer_cert;
1833
PyObject *result;
1834
1835
if (!SSL_is_init_finished(self->ssl)) {
1836
PyErr_SetString(PyExc_ValueError,
1837
"handshake not done yet");
1838
return NULL;
1839
}
1840
peer_cert = SSL_get_peer_certificate(self->ssl);
1841
if (peer_cert == NULL)
1842
Py_RETURN_NONE;
1843
1844
if (binary_mode) {
1845
/* return cert in DER-encoded format */
1846
result = _certificate_to_der(get_state_sock(self), peer_cert);
1847
} else {
1848
verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
1849
if ((verification & SSL_VERIFY_PEER) == 0)
1850
result = PyDict_New();
1851
else
1852
result = _decode_certificate(get_state_sock(self), peer_cert);
1853
}
1854
X509_free(peer_cert);
1855
return result;
1856
}
1857
1858
/*[clinic input]
1859
_ssl._SSLSocket.get_verified_chain
1860
1861
[clinic start generated code]*/
1862
1863
static PyObject *
1864
_ssl__SSLSocket_get_verified_chain_impl(PySSLSocket *self)
1865
/*[clinic end generated code: output=802421163cdc3110 input=5fb0714f77e2bd51]*/
1866
{
1867
/* borrowed reference */
1868
STACK_OF(X509) *chain = SSL_get0_verified_chain(self->ssl);
1869
if (chain == NULL) {
1870
Py_RETURN_NONE;
1871
}
1872
return _PySSL_CertificateFromX509Stack(self->ctx->state, chain, 1);
1873
}
1874
1875
/*[clinic input]
1876
_ssl._SSLSocket.get_unverified_chain
1877
1878
[clinic start generated code]*/
1879
1880
static PyObject *
1881
_ssl__SSLSocket_get_unverified_chain_impl(PySSLSocket *self)
1882
/*[clinic end generated code: output=5acdae414e13f913 input=78c33c360c635cb5]*/
1883
{
1884
PyObject *retval;
1885
/* borrowed reference */
1886
/* TODO: include SSL_get_peer_certificate() for server-side sockets */
1887
STACK_OF(X509) *chain = SSL_get_peer_cert_chain(self->ssl);
1888
if (chain == NULL) {
1889
Py_RETURN_NONE;
1890
}
1891
retval = _PySSL_CertificateFromX509Stack(self->ctx->state, chain, 1);
1892
if (retval == NULL) {
1893
return NULL;
1894
}
1895
/* OpenSSL does not include peer cert for server side connections */
1896
if (self->socket_type == PY_SSL_SERVER) {
1897
PyObject *peerobj = NULL;
1898
X509 *peer = SSL_get_peer_certificate(self->ssl);
1899
1900
if (peer == NULL) {
1901
peerobj = Py_NewRef(Py_None);
1902
} else {
1903
/* consume X509 reference on success */
1904
peerobj = _PySSL_CertificateFromX509(self->ctx->state, peer, 0);
1905
if (peerobj == NULL) {
1906
X509_free(peer);
1907
Py_DECREF(retval);
1908
return NULL;
1909
}
1910
}
1911
int res = PyList_Insert(retval, 0, peerobj);
1912
Py_DECREF(peerobj);
1913
if (res < 0) {
1914
Py_DECREF(retval);
1915
return NULL;
1916
}
1917
}
1918
return retval;
1919
}
1920
1921
static PyObject *
1922
cipher_to_tuple(const SSL_CIPHER *cipher)
1923
{
1924
const char *cipher_name, *cipher_protocol;
1925
PyObject *v, *retval = PyTuple_New(3);
1926
if (retval == NULL)
1927
return NULL;
1928
1929
cipher_name = SSL_CIPHER_get_name(cipher);
1930
if (cipher_name == NULL) {
1931
PyTuple_SET_ITEM(retval, 0, Py_NewRef(Py_None));
1932
} else {
1933
v = PyUnicode_FromString(cipher_name);
1934
if (v == NULL)
1935
goto fail;
1936
PyTuple_SET_ITEM(retval, 0, v);
1937
}
1938
1939
cipher_protocol = SSL_CIPHER_get_version(cipher);
1940
if (cipher_protocol == NULL) {
1941
PyTuple_SET_ITEM(retval, 1, Py_NewRef(Py_None));
1942
} else {
1943
v = PyUnicode_FromString(cipher_protocol);
1944
if (v == NULL)
1945
goto fail;
1946
PyTuple_SET_ITEM(retval, 1, v);
1947
}
1948
1949
v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
1950
if (v == NULL)
1951
goto fail;
1952
PyTuple_SET_ITEM(retval, 2, v);
1953
1954
return retval;
1955
1956
fail:
1957
Py_DECREF(retval);
1958
return NULL;
1959
}
1960
1961
static PyObject *
1962
cipher_to_dict(const SSL_CIPHER *cipher)
1963
{
1964
const char *cipher_name, *cipher_protocol;
1965
1966
unsigned long cipher_id;
1967
int alg_bits, strength_bits, len;
1968
char buf[512] = {0};
1969
int aead, nid;
1970
const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1971
1972
/* can be NULL */
1973
cipher_name = SSL_CIPHER_get_name(cipher);
1974
cipher_protocol = SSL_CIPHER_get_version(cipher);
1975
cipher_id = SSL_CIPHER_get_id(cipher);
1976
SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
1977
/* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1978
len = (int)strlen(buf);
1979
if (len > 1 && buf[len-1] == '\n')
1980
buf[len-1] = '\0';
1981
strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1982
1983
aead = SSL_CIPHER_is_aead(cipher);
1984
nid = SSL_CIPHER_get_cipher_nid(cipher);
1985
skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1986
nid = SSL_CIPHER_get_digest_nid(cipher);
1987
digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1988
nid = SSL_CIPHER_get_kx_nid(cipher);
1989
kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1990
nid = SSL_CIPHER_get_auth_nid(cipher);
1991
auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1992
1993
return Py_BuildValue(
1994
"{sksssssssisi"
1995
"sOssssssss"
1996
"}",
1997
"id", cipher_id,
1998
"name", cipher_name,
1999
"protocol", cipher_protocol,
2000
"description", buf,
2001
"strength_bits", strength_bits,
2002
"alg_bits", alg_bits
2003
,"aead", aead ? Py_True : Py_False,
2004
"symmetric", skcipher,
2005
"digest", digest,
2006
"kea", kx,
2007
"auth", auth
2008
);
2009
}
2010
2011
/*[clinic input]
2012
_ssl._SSLSocket.shared_ciphers
2013
[clinic start generated code]*/
2014
2015
static PyObject *
2016
_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
2017
/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
2018
{
2019
STACK_OF(SSL_CIPHER) *server_ciphers;
2020
STACK_OF(SSL_CIPHER) *client_ciphers;
2021
int i, len;
2022
PyObject *res;
2023
const SSL_CIPHER* cipher;
2024
2025
/* Rather than use SSL_get_shared_ciphers, we use an equivalent algorithm because:
2026
2027
1) It returns a colon separated list of strings, in an undefined
2028
order, that we would have to post process back into tuples.
2029
2) It will return a truncated string with no indication that it has
2030
done so, if the buffer is too small.
2031
*/
2032
2033
server_ciphers = SSL_get_ciphers(self->ssl);
2034
if (!server_ciphers)
2035
Py_RETURN_NONE;
2036
client_ciphers = SSL_get_client_ciphers(self->ssl);
2037
if (!client_ciphers)
2038
Py_RETURN_NONE;
2039
2040
res = PyList_New(sk_SSL_CIPHER_num(server_ciphers));
2041
if (!res)
2042
return NULL;
2043
len = 0;
2044
for (i = 0; i < sk_SSL_CIPHER_num(server_ciphers); i++) {
2045
cipher = sk_SSL_CIPHER_value(server_ciphers, i);
2046
if (sk_SSL_CIPHER_find(client_ciphers, cipher) < 0)
2047
continue;
2048
2049
PyObject *tup = cipher_to_tuple(cipher);
2050
if (!tup) {
2051
Py_DECREF(res);
2052
return NULL;
2053
}
2054
PyList_SET_ITEM(res, len++, tup);
2055
}
2056
Py_SET_SIZE(res, len);
2057
return res;
2058
}
2059
2060
/*[clinic input]
2061
_ssl._SSLSocket.cipher
2062
[clinic start generated code]*/
2063
2064
static PyObject *
2065
_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
2066
/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
2067
{
2068
const SSL_CIPHER *current;
2069
2070
if (self->ssl == NULL)
2071
Py_RETURN_NONE;
2072
current = SSL_get_current_cipher(self->ssl);
2073
if (current == NULL)
2074
Py_RETURN_NONE;
2075
return cipher_to_tuple(current);
2076
}
2077
2078
/*[clinic input]
2079
_ssl._SSLSocket.version
2080
[clinic start generated code]*/
2081
2082
static PyObject *
2083
_ssl__SSLSocket_version_impl(PySSLSocket *self)
2084
/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
2085
{
2086
const char *version;
2087
2088
if (self->ssl == NULL)
2089
Py_RETURN_NONE;
2090
if (!SSL_is_init_finished(self->ssl)) {
2091
/* handshake not finished */
2092
Py_RETURN_NONE;
2093
}
2094
version = SSL_get_version(self->ssl);
2095
if (!strcmp(version, "unknown"))
2096
Py_RETURN_NONE;
2097
return PyUnicode_FromString(version);
2098
}
2099
2100
/*[clinic input]
2101
_ssl._SSLSocket.selected_alpn_protocol
2102
[clinic start generated code]*/
2103
2104
static PyObject *
2105
_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2106
/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2107
{
2108
const unsigned char *out;
2109
unsigned int outlen;
2110
2111
SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2112
2113
if (out == NULL)
2114
Py_RETURN_NONE;
2115
return PyUnicode_FromStringAndSize((char *)out, outlen);
2116
}
2117
2118
/*[clinic input]
2119
_ssl._SSLSocket.compression
2120
[clinic start generated code]*/
2121
2122
static PyObject *
2123
_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2124
/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2125
{
2126
#ifdef OPENSSL_NO_COMP
2127
Py_RETURN_NONE;
2128
#else
2129
const COMP_METHOD *comp_method;
2130
const char *short_name;
2131
2132
if (self->ssl == NULL)
2133
Py_RETURN_NONE;
2134
comp_method = SSL_get_current_compression(self->ssl);
2135
if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
2136
Py_RETURN_NONE;
2137
short_name = OBJ_nid2sn(COMP_get_type(comp_method));
2138
if (short_name == NULL)
2139
Py_RETURN_NONE;
2140
return PyUnicode_DecodeFSDefault(short_name);
2141
#endif
2142
}
2143
2144
static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2145
return (PySSLContext*)Py_NewRef(self->ctx);
2146
}
2147
2148
static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2149
void *closure) {
2150
2151
if (PyObject_TypeCheck(value, self->ctx->state->PySSLContext_Type)) {
2152
Py_SETREF(self->ctx, (PySSLContext *)Py_NewRef(value));
2153
SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
2154
/* Set SSL* internal msg_callback to state of new context's state */
2155
SSL_set_msg_callback(
2156
self->ssl,
2157
self->ctx->msg_cb ? _PySSL_msg_callback : NULL
2158
);
2159
} else {
2160
PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
2161
return -1;
2162
}
2163
2164
return 0;
2165
}
2166
2167
PyDoc_STRVAR(PySSL_set_context_doc,
2168
"_setter_context(ctx)\n\
2169
\
2170
This changes the context associated with the SSLSocket. This is typically\n\
2171
used from within a callback function set by the sni_callback\n\
2172
on the SSLContext to change the certificate information associated with the\n\
2173
SSLSocket before the cryptographic exchange handshake messages\n");
2174
2175
2176
static PyObject *
2177
PySSL_get_server_side(PySSLSocket *self, void *c)
2178
{
2179
return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2180
}
2181
2182
PyDoc_STRVAR(PySSL_get_server_side_doc,
2183
"Whether this is a server-side socket.");
2184
2185
static PyObject *
2186
PySSL_get_server_hostname(PySSLSocket *self, void *c)
2187
{
2188
if (self->server_hostname == NULL)
2189
Py_RETURN_NONE;
2190
return Py_NewRef(self->server_hostname);
2191
}
2192
2193
PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2194
"The currently set server hostname (for SNI).");
2195
2196
static PyObject *
2197
PySSL_get_owner(PySSLSocket *self, void *c)
2198
{
2199
if (self->owner == NULL) {
2200
Py_RETURN_NONE;
2201
}
2202
PyObject *owner = _PyWeakref_GET_REF(self->owner);
2203
if (owner == NULL) {
2204
Py_RETURN_NONE;
2205
}
2206
return owner;
2207
}
2208
2209
static int
2210
PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2211
{
2212
Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
2213
if (self->owner == NULL)
2214
return -1;
2215
return 0;
2216
}
2217
2218
PyDoc_STRVAR(PySSL_get_owner_doc,
2219
"The Python-level owner of this object.\
2220
Passed as \"self\" in servername callback.");
2221
2222
static int
2223
PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2224
{
2225
Py_VISIT(self->exc);
2226
Py_VISIT(Py_TYPE(self));
2227
return 0;
2228
}
2229
2230
static int
2231
PySSL_clear(PySSLSocket *self)
2232
{
2233
Py_CLEAR(self->exc);
2234
return 0;
2235
}
2236
2237
static void
2238
PySSL_dealloc(PySSLSocket *self)
2239
{
2240
PyTypeObject *tp = Py_TYPE(self);
2241
PyObject_GC_UnTrack(self);
2242
if (self->ssl) {
2243
SSL_free(self->ssl);
2244
}
2245
Py_XDECREF(self->Socket);
2246
Py_XDECREF(self->ctx);
2247
Py_XDECREF(self->server_hostname);
2248
Py_XDECREF(self->owner);
2249
PyObject_GC_Del(self);
2250
Py_DECREF(tp);
2251
}
2252
2253
/* If the socket has a timeout, do a select()/poll() on the socket.
2254
The argument writing indicates the direction.
2255
Returns one of the possibilities in the timeout_state enum (above).
2256
*/
2257
2258
static int
2259
PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
2260
{
2261
int rc;
2262
#ifdef HAVE_POLL
2263
struct pollfd pollfd;
2264
_PyTime_t ms;
2265
#else
2266
int nfds;
2267
fd_set fds;
2268
struct timeval tv;
2269
#endif
2270
2271
/* Nothing to do unless we're in timeout mode (not non-blocking) */
2272
if ((s == NULL) || (timeout == 0))
2273
return SOCKET_IS_NONBLOCKING;
2274
else if (timeout < 0) {
2275
if (s->sock_timeout > 0)
2276
return SOCKET_HAS_TIMED_OUT;
2277
else
2278
return SOCKET_IS_BLOCKING;
2279
}
2280
2281
/* Guard against closed socket */
2282
if (s->sock_fd == INVALID_SOCKET)
2283
return SOCKET_HAS_BEEN_CLOSED;
2284
2285
/* Prefer poll, if available, since you can poll() any fd
2286
* which can't be done with select(). */
2287
#ifdef HAVE_POLL
2288
pollfd.fd = s->sock_fd;
2289
pollfd.events = writing ? POLLOUT : POLLIN;
2290
2291
/* timeout is in seconds, poll() uses milliseconds */
2292
ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
2293
assert(ms <= INT_MAX);
2294
2295
PySSL_BEGIN_ALLOW_THREADS
2296
rc = poll(&pollfd, 1, (int)ms);
2297
PySSL_END_ALLOW_THREADS
2298
#else
2299
/* Guard against socket too large for select*/
2300
if (!_PyIsSelectable_fd(s->sock_fd))
2301
return SOCKET_TOO_LARGE_FOR_SELECT;
2302
2303
_PyTime_AsTimeval_clamp(timeout, &tv, _PyTime_ROUND_CEILING);
2304
2305
FD_ZERO(&fds);
2306
FD_SET(s->sock_fd, &fds);
2307
2308
/* Wait until the socket becomes ready */
2309
PySSL_BEGIN_ALLOW_THREADS
2310
nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
2311
if (writing)
2312
rc = select(nfds, NULL, &fds, NULL, &tv);
2313
else
2314
rc = select(nfds, &fds, NULL, NULL, &tv);
2315
PySSL_END_ALLOW_THREADS
2316
#endif
2317
2318
/* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2319
(when we are able to write or when there's something to read) */
2320
return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
2321
}
2322
2323
/*[clinic input]
2324
_ssl._SSLSocket.write
2325
b: Py_buffer
2326
/
2327
2328
Writes the bytes-like object b into the SSL object.
2329
2330
Returns the number of bytes written.
2331
[clinic start generated code]*/
2332
2333
static PyObject *
2334
_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2335
/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
2336
{
2337
size_t count = 0;
2338
int retval;
2339
int sockstate;
2340
_PySSLError err;
2341
int nonblocking;
2342
PySocketSockObject *sock = GET_SOCKET(self);
2343
_PyTime_t timeout, deadline = 0;
2344
int has_timeout;
2345
2346
if (sock != NULL) {
2347
if (((PyObject*)sock) == Py_None) {
2348
_setSSLError(get_state_sock(self),
2349
"Underlying socket connection gone",
2350
PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2351
return NULL;
2352
}
2353
Py_INCREF(sock);
2354
}
2355
2356
if (sock != NULL) {
2357
/* just in case the blocking state of the socket has been changed */
2358
nonblocking = (sock->sock_timeout >= 0);
2359
BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2360
BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2361
}
2362
2363
timeout = GET_SOCKET_TIMEOUT(sock);
2364
has_timeout = (timeout > 0);
2365
if (has_timeout) {
2366
deadline = _PyDeadline_Init(timeout);
2367
}
2368
2369
sockstate = PySSL_select(sock, 1, timeout);
2370
if (sockstate == SOCKET_HAS_TIMED_OUT) {
2371
PyErr_SetString(PyExc_TimeoutError,
2372
"The write operation timed out");
2373
goto error;
2374
} else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2375
PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
2376
"Underlying socket has been closed.");
2377
goto error;
2378
} else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2379
PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
2380
"Underlying socket too large for select().");
2381
goto error;
2382
}
2383
2384
do {
2385
PySSL_BEGIN_ALLOW_THREADS
2386
retval = SSL_write_ex(self->ssl, b->buf, (size_t)b->len, &count);
2387
err = _PySSL_errno(retval == 0, self->ssl, retval);
2388
PySSL_END_ALLOW_THREADS
2389
self->err = err;
2390
2391
if (PyErr_CheckSignals())
2392
goto error;
2393
2394
if (has_timeout) {
2395
timeout = _PyDeadline_Get(deadline);
2396
}
2397
2398
if (err.ssl == SSL_ERROR_WANT_READ) {
2399
sockstate = PySSL_select(sock, 0, timeout);
2400
} else if (err.ssl == SSL_ERROR_WANT_WRITE) {
2401
sockstate = PySSL_select(sock, 1, timeout);
2402
} else {
2403
sockstate = SOCKET_OPERATION_OK;
2404
}
2405
2406
if (sockstate == SOCKET_HAS_TIMED_OUT) {
2407
PyErr_SetString(PyExc_TimeoutError,
2408
"The write operation timed out");
2409
goto error;
2410
} else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2411
PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
2412
"Underlying socket has been closed.");
2413
goto error;
2414
} else if (sockstate == SOCKET_IS_NONBLOCKING) {
2415
break;
2416
}
2417
} while (err.ssl == SSL_ERROR_WANT_READ ||
2418
err.ssl == SSL_ERROR_WANT_WRITE);
2419
2420
Py_XDECREF(sock);
2421
if (retval == 0)
2422
return PySSL_SetError(self, retval, __FILE__, __LINE__);
2423
if (PySSL_ChainExceptions(self) < 0)
2424
return NULL;
2425
return PyLong_FromSize_t(count);
2426
error:
2427
Py_XDECREF(sock);
2428
PySSL_ChainExceptions(self);
2429
return NULL;
2430
}
2431
2432
/*[clinic input]
2433
_ssl._SSLSocket.pending
2434
2435
Returns the number of already decrypted bytes available for read, pending on the connection.
2436
[clinic start generated code]*/
2437
2438
static PyObject *
2439
_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2440
/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
2441
{
2442
int count = 0;
2443
_PySSLError err;
2444
2445
PySSL_BEGIN_ALLOW_THREADS
2446
count = SSL_pending(self->ssl);
2447
err = _PySSL_errno(count < 0, self->ssl, count);
2448
PySSL_END_ALLOW_THREADS
2449
self->err = err;
2450
2451
if (count < 0)
2452
return PySSL_SetError(self, count, __FILE__, __LINE__);
2453
else
2454
return PyLong_FromLong(count);
2455
}
2456
2457
/*[clinic input]
2458
_ssl._SSLSocket.read
2459
size as len: Py_ssize_t
2460
[
2461
buffer: Py_buffer(accept={rwbuffer})
2462
]
2463
/
2464
2465
Read up to size bytes from the SSL socket.
2466
[clinic start generated code]*/
2467
2468
static PyObject *
2469
_ssl__SSLSocket_read_impl(PySSLSocket *self, Py_ssize_t len,
2470
int group_right_1, Py_buffer *buffer)
2471
/*[clinic end generated code: output=49b16e6406023734 input=ec48bf622be1c4a1]*/
2472
{
2473
PyObject *dest = NULL;
2474
char *mem;
2475
size_t count = 0;
2476
int retval;
2477
int sockstate;
2478
_PySSLError err;
2479
int nonblocking;
2480
PySocketSockObject *sock = GET_SOCKET(self);
2481
_PyTime_t timeout, deadline = 0;
2482
int has_timeout;
2483
2484
if (!group_right_1 && len < 0) {
2485
PyErr_SetString(PyExc_ValueError, "size should not be negative");
2486
return NULL;
2487
}
2488
2489
if (sock != NULL) {
2490
if (((PyObject*)sock) == Py_None) {
2491
_setSSLError(get_state_sock(self),
2492
"Underlying socket connection gone",
2493
PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2494
return NULL;
2495
}
2496
Py_INCREF(sock);
2497
}
2498
2499
if (!group_right_1) {
2500
dest = PyBytes_FromStringAndSize(NULL, len);
2501
if (dest == NULL)
2502
goto error;
2503
if (len == 0) {
2504
Py_XDECREF(sock);
2505
return dest;
2506
}
2507
mem = PyBytes_AS_STRING(dest);
2508
}
2509
else {
2510
mem = buffer->buf;
2511
if (len <= 0 || len > buffer->len) {
2512
len = (int) buffer->len;
2513
if (buffer->len != len) {
2514
PyErr_SetString(PyExc_OverflowError,
2515
"maximum length can't fit in a C 'int'");
2516
goto error;
2517
}
2518
if (len == 0) {
2519
count = 0;
2520
goto done;
2521
}
2522
}
2523
}
2524
2525
if (sock != NULL) {
2526
/* just in case the blocking state of the socket has been changed */
2527
nonblocking = (sock->sock_timeout >= 0);
2528
BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2529
BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2530
}
2531
2532
timeout = GET_SOCKET_TIMEOUT(sock);
2533
has_timeout = (timeout > 0);
2534
if (has_timeout)
2535
deadline = _PyDeadline_Init(timeout);
2536
2537
do {
2538
PySSL_BEGIN_ALLOW_THREADS
2539
retval = SSL_read_ex(self->ssl, mem, (size_t)len, &count);
2540
err = _PySSL_errno(retval == 0, self->ssl, retval);
2541
PySSL_END_ALLOW_THREADS
2542
self->err = err;
2543
2544
if (PyErr_CheckSignals())
2545
goto error;
2546
2547
if (has_timeout) {
2548
timeout = _PyDeadline_Get(deadline);
2549
}
2550
2551
if (err.ssl == SSL_ERROR_WANT_READ) {
2552
sockstate = PySSL_select(sock, 0, timeout);
2553
} else if (err.ssl == SSL_ERROR_WANT_WRITE) {
2554
sockstate = PySSL_select(sock, 1, timeout);
2555
} else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
2556
SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
2557
{
2558
count = 0;
2559
goto done;
2560
}
2561
else
2562
sockstate = SOCKET_OPERATION_OK;
2563
2564
if (sockstate == SOCKET_HAS_TIMED_OUT) {
2565
PyErr_SetString(PyExc_TimeoutError,
2566
"The read operation timed out");
2567
goto error;
2568
} else if (sockstate == SOCKET_IS_NONBLOCKING) {
2569
break;
2570
}
2571
} while (err.ssl == SSL_ERROR_WANT_READ ||
2572
err.ssl == SSL_ERROR_WANT_WRITE);
2573
2574
if (retval == 0) {
2575
PySSL_SetError(self, retval, __FILE__, __LINE__);
2576
goto error;
2577
}
2578
if (self->exc != NULL)
2579
goto error;
2580
2581
done:
2582
Py_XDECREF(sock);
2583
if (!group_right_1) {
2584
_PyBytes_Resize(&dest, count);
2585
return dest;
2586
}
2587
else {
2588
return PyLong_FromSize_t(count);
2589
}
2590
2591
error:
2592
PySSL_ChainExceptions(self);
2593
Py_XDECREF(sock);
2594
if (!group_right_1)
2595
Py_XDECREF(dest);
2596
return NULL;
2597
}
2598
2599
/*[clinic input]
2600
_ssl._SSLSocket.shutdown
2601
2602
Does the SSL shutdown handshake with the remote end.
2603
[clinic start generated code]*/
2604
2605
static PyObject *
2606
_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2607
/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
2608
{
2609
_PySSLError err;
2610
int sockstate, nonblocking, ret;
2611
int zeros = 0;
2612
PySocketSockObject *sock = GET_SOCKET(self);
2613
_PyTime_t timeout, deadline = 0;
2614
int has_timeout;
2615
2616
if (sock != NULL) {
2617
/* Guard against closed socket */
2618
if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
2619
_setSSLError(get_state_sock(self),
2620
"Underlying socket connection gone",
2621
PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2622
return NULL;
2623
}
2624
Py_INCREF(sock);
2625
2626
/* Just in case the blocking state of the socket has been changed */
2627
nonblocking = (sock->sock_timeout >= 0);
2628
BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2629
BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2630
}
2631
2632
timeout = GET_SOCKET_TIMEOUT(sock);
2633
has_timeout = (timeout > 0);
2634
if (has_timeout) {
2635
deadline = _PyDeadline_Init(timeout);
2636
}
2637
2638
while (1) {
2639
PySSL_BEGIN_ALLOW_THREADS
2640
/* Disable read-ahead so that unwrap can work correctly.
2641
* Otherwise OpenSSL might read in too much data,
2642
* eating clear text data that happens to be
2643
* transmitted after the SSL shutdown.
2644
* Should be safe to call repeatedly every time this
2645
* function is used and the shutdown_seen_zero != 0
2646
* condition is met.
2647
*/
2648
if (self->shutdown_seen_zero)
2649
SSL_set_read_ahead(self->ssl, 0);
2650
ret = SSL_shutdown(self->ssl);
2651
err = _PySSL_errno(ret < 0, self->ssl, ret);
2652
PySSL_END_ALLOW_THREADS
2653
self->err = err;
2654
2655
/* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2656
if (ret > 0)
2657
break;
2658
if (ret == 0) {
2659
/* Don't loop endlessly; instead preserve legacy
2660
behaviour of trying SSL_shutdown() only twice.
2661
This looks necessary for OpenSSL < 0.9.8m */
2662
if (++zeros > 1)
2663
break;
2664
/* Shutdown was sent, now try receiving */
2665
self->shutdown_seen_zero = 1;
2666
continue;
2667
}
2668
2669
if (has_timeout) {
2670
timeout = _PyDeadline_Get(deadline);
2671
}
2672
2673
/* Possibly retry shutdown until timeout or failure */
2674
if (err.ssl == SSL_ERROR_WANT_READ)
2675
sockstate = PySSL_select(sock, 0, timeout);
2676
else if (err.ssl == SSL_ERROR_WANT_WRITE)
2677
sockstate = PySSL_select(sock, 1, timeout);
2678
else
2679
break;
2680
2681
if (sockstate == SOCKET_HAS_TIMED_OUT) {
2682
if (err.ssl == SSL_ERROR_WANT_READ)
2683
PyErr_SetString(PyExc_TimeoutError,
2684
"The read operation timed out");
2685
else
2686
PyErr_SetString(PyExc_TimeoutError,
2687
"The write operation timed out");
2688
goto error;
2689
}
2690
else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2691
PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
2692
"Underlying socket too large for select().");
2693
goto error;
2694
}
2695
else if (sockstate != SOCKET_OPERATION_OK)
2696
/* Retain the SSL error code */
2697
break;
2698
}
2699
if (ret < 0) {
2700
Py_XDECREF(sock);
2701
PySSL_SetError(self, ret, __FILE__, __LINE__);
2702
return NULL;
2703
}
2704
if (self->exc != NULL)
2705
goto error;
2706
if (sock)
2707
/* It's already INCREF'ed */
2708
return (PyObject *) sock;
2709
else
2710
Py_RETURN_NONE;
2711
2712
error:
2713
Py_XDECREF(sock);
2714
PySSL_ChainExceptions(self);
2715
return NULL;
2716
}
2717
2718
/*[clinic input]
2719
_ssl._SSLSocket.get_channel_binding
2720
cb_type: str = "tls-unique"
2721
2722
Get channel binding data for current connection.
2723
2724
Raise ValueError if the requested `cb_type` is not supported. Return bytes
2725
of the data or None if the data is not available (e.g. before the handshake).
2726
Only 'tls-unique' channel binding data from RFC 5929 is supported.
2727
[clinic start generated code]*/
2728
2729
static PyObject *
2730
_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2731
const char *cb_type)
2732
/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
2733
{
2734
char buf[PySSL_CB_MAXLEN];
2735
size_t len;
2736
2737
if (strcmp(cb_type, "tls-unique") == 0) {
2738
if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2739
/* if session is resumed XOR we are the client */
2740
len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2741
}
2742
else {
2743
/* if a new session XOR we are the server */
2744
len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2745
}
2746
}
2747
else {
2748
PyErr_Format(
2749
PyExc_ValueError,
2750
"'%s' channel binding type not implemented",
2751
cb_type
2752
);
2753
return NULL;
2754
}
2755
2756
/* It cannot be negative in current OpenSSL version as of July 2011 */
2757
if (len == 0)
2758
Py_RETURN_NONE;
2759
2760
return PyBytes_FromStringAndSize(buf, len);
2761
}
2762
2763
/*[clinic input]
2764
_ssl._SSLSocket.verify_client_post_handshake
2765
2766
Initiate TLS 1.3 post-handshake authentication
2767
[clinic start generated code]*/
2768
2769
static PyObject *
2770
_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2771
/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2772
{
2773
#ifdef TLS1_3_VERSION
2774
int err = SSL_verify_client_post_handshake(self->ssl);
2775
if (err == 0)
2776
return _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
2777
else
2778
Py_RETURN_NONE;
2779
#else
2780
PyErr_SetString(PyExc_NotImplementedError,
2781
"Post-handshake auth is not supported by your "
2782
"OpenSSL version.");
2783
return NULL;
2784
#endif
2785
}
2786
2787
static SSL_SESSION*
2788
_ssl_session_dup(SSL_SESSION *session) {
2789
SSL_SESSION *newsession = NULL;
2790
int slen;
2791
unsigned char *senc = NULL, *p;
2792
const unsigned char *const_p;
2793
2794
if (session == NULL) {
2795
PyErr_SetString(PyExc_ValueError, "Invalid session");
2796
goto error;
2797
}
2798
2799
/* get length */
2800
slen = i2d_SSL_SESSION(session, NULL);
2801
if (slen == 0 || slen > 0xFF00) {
2802
PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2803
goto error;
2804
}
2805
if ((senc = PyMem_Malloc(slen)) == NULL) {
2806
PyErr_NoMemory();
2807
goto error;
2808
}
2809
p = senc;
2810
if (!i2d_SSL_SESSION(session, &p)) {
2811
PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2812
goto error;
2813
}
2814
const_p = senc;
2815
newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2816
if (session == NULL) {
2817
goto error;
2818
}
2819
PyMem_Free(senc);
2820
return newsession;
2821
error:
2822
if (senc != NULL) {
2823
PyMem_Free(senc);
2824
}
2825
return NULL;
2826
}
2827
2828
static PyObject *
2829
PySSL_get_session(PySSLSocket *self, void *closure) {
2830
/* get_session can return sessions from a server-side connection,
2831
* it does not check for handshake done or client socket. */
2832
PySSLSession *pysess;
2833
SSL_SESSION *session;
2834
2835
/* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2836
* https://github.com/openssl/openssl/issues/1550 */
2837
session = SSL_get0_session(self->ssl); /* borrowed reference */
2838
if (session == NULL) {
2839
Py_RETURN_NONE;
2840
}
2841
if ((session = _ssl_session_dup(session)) == NULL) {
2842
return NULL;
2843
}
2844
session = SSL_get1_session(self->ssl);
2845
if (session == NULL) {
2846
Py_RETURN_NONE;
2847
}
2848
pysess = PyObject_GC_New(PySSLSession, self->ctx->state->PySSLSession_Type);
2849
if (pysess == NULL) {
2850
SSL_SESSION_free(session);
2851
return NULL;
2852
}
2853
2854
assert(self->ctx);
2855
pysess->ctx = (PySSLContext*)Py_NewRef(self->ctx);
2856
pysess->session = session;
2857
PyObject_GC_Track(pysess);
2858
return (PyObject *)pysess;
2859
}
2860
2861
static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2862
void *closure)
2863
{
2864
PySSLSession *pysess;
2865
SSL_SESSION *session;
2866
int result;
2867
2868
if (!Py_IS_TYPE(value, get_state_sock(self)->PySSLSession_Type)) {
2869
PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2870
return -1;
2871
}
2872
pysess = (PySSLSession *)value;
2873
2874
if (self->ctx->ctx != pysess->ctx->ctx) {
2875
PyErr_SetString(PyExc_ValueError,
2876
"Session refers to a different SSLContext.");
2877
return -1;
2878
}
2879
if (self->socket_type != PY_SSL_CLIENT) {
2880
PyErr_SetString(PyExc_ValueError,
2881
"Cannot set session for server-side SSLSocket.");
2882
return -1;
2883
}
2884
if (SSL_is_init_finished(self->ssl)) {
2885
PyErr_SetString(PyExc_ValueError,
2886
"Cannot set session after handshake.");
2887
return -1;
2888
}
2889
/* duplicate session */
2890
if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2891
return -1;
2892
}
2893
result = SSL_set_session(self->ssl, session);
2894
/* free duplicate, SSL_set_session() bumps ref count */
2895
SSL_SESSION_free(session);
2896
if (result == 0) {
2897
_setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
2898
return -1;
2899
}
2900
return 0;
2901
}
2902
2903
PyDoc_STRVAR(PySSL_set_session_doc,
2904
"_setter_session(session)\n\
2905
\
2906
Get / set SSLSession.");
2907
2908
static PyObject *
2909
PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2910
if (SSL_session_reused(self->ssl)) {
2911
Py_RETURN_TRUE;
2912
} else {
2913
Py_RETURN_FALSE;
2914
}
2915
}
2916
2917
PyDoc_STRVAR(PySSL_get_session_reused_doc,
2918
"Was the client session reused during handshake?");
2919
2920
static PyGetSetDef ssl_getsetlist[] = {
2921
{"context", (getter) PySSL_get_context,
2922
(setter) PySSL_set_context, PySSL_set_context_doc},
2923
{"server_side", (getter) PySSL_get_server_side, NULL,
2924
PySSL_get_server_side_doc},
2925
{"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2926
PySSL_get_server_hostname_doc},
2927
{"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2928
PySSL_get_owner_doc},
2929
{"session", (getter) PySSL_get_session,
2930
(setter) PySSL_set_session, PySSL_set_session_doc},
2931
{"session_reused", (getter) PySSL_get_session_reused, NULL,
2932
PySSL_get_session_reused_doc},
2933
{NULL}, /* sentinel */
2934
};
2935
2936
static PyMethodDef PySSLMethods[] = {
2937
_SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2938
_SSL__SSLSOCKET_WRITE_METHODDEF
2939
_SSL__SSLSOCKET_READ_METHODDEF
2940
_SSL__SSLSOCKET_PENDING_METHODDEF
2941
_SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2942
_SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
2943
_SSL__SSLSOCKET_CIPHER_METHODDEF
2944
_SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2945
_SSL__SSLSOCKET_VERSION_METHODDEF
2946
_SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2947
_SSL__SSLSOCKET_COMPRESSION_METHODDEF
2948
_SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2949
_SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
2950
_SSL__SSLSOCKET_GET_UNVERIFIED_CHAIN_METHODDEF
2951
_SSL__SSLSOCKET_GET_VERIFIED_CHAIN_METHODDEF
2952
{NULL, NULL}
2953
};
2954
2955
static PyType_Slot PySSLSocket_slots[] = {
2956
{Py_tp_methods, PySSLMethods},
2957
{Py_tp_getset, ssl_getsetlist},
2958
{Py_tp_dealloc, PySSL_dealloc},
2959
{Py_tp_traverse, PySSL_traverse},
2960
{Py_tp_clear, PySSL_clear},
2961
{0, 0},
2962
};
2963
2964
static PyType_Spec PySSLSocket_spec = {
2965
.name = "_ssl._SSLSocket",
2966
.basicsize = sizeof(PySSLSocket),
2967
.flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
2968
Py_TPFLAGS_HAVE_GC),
2969
.slots = PySSLSocket_slots,
2970
};
2971
2972
/*
2973
* _SSLContext objects
2974
*/
2975
2976
static int
2977
_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
2978
{
2979
int mode;
2980
int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2981
2982
switch(n) {
2983
case PY_SSL_CERT_NONE:
2984
mode = SSL_VERIFY_NONE;
2985
break;
2986
case PY_SSL_CERT_OPTIONAL:
2987
mode = SSL_VERIFY_PEER;
2988
break;
2989
case PY_SSL_CERT_REQUIRED:
2990
mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2991
break;
2992
default:
2993
PyErr_SetString(PyExc_ValueError,
2994
"invalid value for verify_mode");
2995
return -1;
2996
}
2997
2998
/* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
2999
* server sockets and SSL_set_post_handshake_auth() for client. */
3000
3001
/* keep current verify cb */
3002
verify_cb = SSL_CTX_get_verify_callback(self->ctx);
3003
SSL_CTX_set_verify(self->ctx, mode, verify_cb);
3004
return 0;
3005
}
3006
3007
/*[clinic input]
3008
@classmethod
3009
_ssl._SSLContext.__new__
3010
protocol as proto_version: int
3011
/
3012
[clinic start generated code]*/
3013
3014
static PyObject *
3015
_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
3016
/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
3017
{
3018
PySSLContext *self;
3019
long options;
3020
const SSL_METHOD *method = NULL;
3021
SSL_CTX *ctx = NULL;
3022
X509_VERIFY_PARAM *params;
3023
int result;
3024
3025
/* slower approach, walk MRO and get borrowed reference to module.
3026
* PyType_GetModuleByDef is required for SSLContext subclasses */
3027
PyObject *module = PyType_GetModuleByDef(type, &_sslmodule_def);
3028
if (module == NULL) {
3029
PyErr_SetString(PyExc_RuntimeError,
3030
"Cannot find internal module state");
3031
return NULL;
3032
}
3033
3034
switch(proto_version) {
3035
#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
3036
case PY_SSL_VERSION_SSL3:
3037
PY_SSL_DEPRECATED("ssl.PROTOCOL_SSLv3 is deprecated", 2, NULL);
3038
method = SSLv3_method();
3039
break;
3040
#endif
3041
#if (defined(TLS1_VERSION) && \
3042
!defined(OPENSSL_NO_TLS1) && \
3043
!defined(OPENSSL_NO_TLS1_METHOD))
3044
case PY_SSL_VERSION_TLS1:
3045
PY_SSL_DEPRECATED("ssl.PROTOCOL_TLSv1 is deprecated", 2, NULL);
3046
method = TLSv1_method();
3047
break;
3048
#endif
3049
#if (defined(TLS1_1_VERSION) && \
3050
!defined(OPENSSL_NO_TLS1_1) && \
3051
!defined(OPENSSL_NO_TLS1_1_METHOD))
3052
case PY_SSL_VERSION_TLS1_1:
3053
PY_SSL_DEPRECATED("ssl.PROTOCOL_TLSv1_1 is deprecated", 2, NULL);
3054
method = TLSv1_1_method();
3055
break;
3056
#endif
3057
#if (defined(TLS1_2_VERSION) && \
3058
!defined(OPENSSL_NO_TLS1_2) && \
3059
!defined(OPENSSL_NO_TLS1_2_METHOD))
3060
case PY_SSL_VERSION_TLS1_2:
3061
PY_SSL_DEPRECATED("ssl.PROTOCOL_TLSv1_2 is deprecated", 2, NULL);
3062
method = TLSv1_2_method();
3063
break;
3064
#endif
3065
case PY_SSL_VERSION_TLS:
3066
PY_SSL_DEPRECATED("ssl.PROTOCOL_TLS is deprecated", 2, NULL);
3067
method = TLS_method();
3068
break;
3069
case PY_SSL_VERSION_TLS_CLIENT:
3070
method = TLS_client_method();
3071
break;
3072
case PY_SSL_VERSION_TLS_SERVER:
3073
method = TLS_server_method();
3074
break;
3075
default:
3076
method = NULL;
3077
}
3078
3079
if (method == NULL) {
3080
PyErr_Format(PyExc_ValueError,
3081
"invalid or unsupported protocol version %i",
3082
proto_version);
3083
return NULL;
3084
}
3085
3086
PySSL_BEGIN_ALLOW_THREADS
3087
ctx = SSL_CTX_new(method);
3088
PySSL_END_ALLOW_THREADS
3089
3090
if (ctx == NULL) {
3091
_setSSLError(get_ssl_state(module), NULL, 0, __FILE__, __LINE__);
3092
return NULL;
3093
}
3094
3095
assert(type != NULL && type->tp_alloc != NULL);
3096
self = (PySSLContext *) type->tp_alloc(type, 0);
3097
if (self == NULL) {
3098
SSL_CTX_free(ctx);
3099
return NULL;
3100
}
3101
self->ctx = ctx;
3102
self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
3103
self->protocol = proto_version;
3104
self->msg_cb = NULL;
3105
self->keylog_filename = NULL;
3106
self->keylog_bio = NULL;
3107
self->alpn_protocols = NULL;
3108
self->set_sni_cb = NULL;
3109
self->state = get_ssl_state(module);
3110
3111
/* Don't check host name by default */
3112
if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3113
self->check_hostname = 1;
3114
if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
3115
Py_DECREF(self);
3116
return NULL;
3117
}
3118
} else {
3119
self->check_hostname = 0;
3120
if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
3121
Py_DECREF(self);
3122
return NULL;
3123
}
3124
}
3125
/* Defaults */
3126
options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3127
if (proto_version != PY_SSL_VERSION_SSL2)
3128
options |= SSL_OP_NO_SSLv2;
3129
if (proto_version != PY_SSL_VERSION_SSL3)
3130
options |= SSL_OP_NO_SSLv3;
3131
/* Minimal security flags for server and client side context.
3132
* Client sockets ignore server-side parameters. */
3133
#ifdef SSL_OP_NO_COMPRESSION
3134
options |= SSL_OP_NO_COMPRESSION;
3135
#endif
3136
#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3137
options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3138
#endif
3139
#ifdef SSL_OP_SINGLE_DH_USE
3140
options |= SSL_OP_SINGLE_DH_USE;
3141
#endif
3142
#ifdef SSL_OP_SINGLE_ECDH_USE
3143
options |= SSL_OP_SINGLE_ECDH_USE;
3144
#endif
3145
SSL_CTX_set_options(self->ctx, options);
3146
3147
/* A bare minimum cipher list without completely broken cipher suites.
3148
* It's far from perfect but gives users a better head start. */
3149
if (proto_version != PY_SSL_VERSION_SSL2) {
3150
#if PY_SSL_DEFAULT_CIPHERS == 2
3151
/* stick to OpenSSL's default settings */
3152
result = 1;
3153
#else
3154
result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3155
#endif
3156
} else {
3157
/* SSLv2 needs MD5 */
3158
result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3159
}
3160
if (result == 0) {
3161
Py_DECREF(self);
3162
ERR_clear_error();
3163
PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
3164
"No cipher can be selected.");
3165
goto error;
3166
}
3167
#ifdef PY_SSL_MIN_PROTOCOL
3168
switch(proto_version) {
3169
case PY_SSL_VERSION_TLS:
3170
case PY_SSL_VERSION_TLS_CLIENT:
3171
case PY_SSL_VERSION_TLS_SERVER:
3172
result = SSL_CTX_set_min_proto_version(ctx, PY_SSL_MIN_PROTOCOL);
3173
if (result == 0) {
3174
PyErr_Format(PyExc_ValueError,
3175
"Failed to set minimum protocol 0x%x",
3176
PY_SSL_MIN_PROTOCOL);
3177
goto error;
3178
}
3179
break;
3180
default:
3181
break;
3182
}
3183
#endif
3184
3185
/* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3186
usage for no cost at all. */
3187
SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3188
3189
#define SID_CTX "Python"
3190
SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3191
sizeof(SID_CTX));
3192
#undef SID_CTX
3193
3194
params = SSL_CTX_get0_param(self->ctx);
3195
/* Improve trust chain building when cross-signed intermediate
3196
certificates are present. See https://bugs.python.org/issue23476. */
3197
X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
3198
X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
3199
3200
#ifdef TLS1_3_VERSION
3201
self->post_handshake_auth = 0;
3202
SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3203
#endif
3204
3205
return (PyObject *)self;
3206
error:
3207
Py_XDECREF(self);
3208
ERR_clear_error();
3209
return NULL;
3210
}
3211
3212
static int
3213
context_traverse(PySSLContext *self, visitproc visit, void *arg)
3214
{
3215
Py_VISIT(self->set_sni_cb);
3216
Py_VISIT(self->msg_cb);
3217
Py_VISIT(Py_TYPE(self));
3218
return 0;
3219
}
3220
3221
static int
3222
context_clear(PySSLContext *self)
3223
{
3224
Py_CLEAR(self->set_sni_cb);
3225
Py_CLEAR(self->msg_cb);
3226
Py_CLEAR(self->keylog_filename);
3227
if (self->keylog_bio != NULL) {
3228
PySSL_BEGIN_ALLOW_THREADS
3229
BIO_free_all(self->keylog_bio);
3230
PySSL_END_ALLOW_THREADS
3231
self->keylog_bio = NULL;
3232
}
3233
return 0;
3234
}
3235
3236
static void
3237
context_dealloc(PySSLContext *self)
3238
{
3239
PyTypeObject *tp = Py_TYPE(self);
3240
/* bpo-31095: UnTrack is needed before calling any callbacks */
3241
PyObject_GC_UnTrack(self);
3242
context_clear(self);
3243
SSL_CTX_free(self->ctx);
3244
PyMem_FREE(self->alpn_protocols);
3245
Py_TYPE(self)->tp_free(self);
3246
Py_DECREF(tp);
3247
}
3248
3249
/*[clinic input]
3250
_ssl._SSLContext.set_ciphers
3251
cipherlist: str
3252
/
3253
[clinic start generated code]*/
3254
3255
static PyObject *
3256
_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3257
/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3258
{
3259
int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
3260
if (ret == 0) {
3261
/* Clearing the error queue is necessary on some OpenSSL versions,
3262
otherwise the error will be reported again when another SSL call
3263
is done. */
3264
ERR_clear_error();
3265
PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
3266
"No cipher can be selected.");
3267
return NULL;
3268
}
3269
Py_RETURN_NONE;
3270
}
3271
3272
/*[clinic input]
3273
_ssl._SSLContext.get_ciphers
3274
[clinic start generated code]*/
3275
3276
static PyObject *
3277
_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3278
/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3279
{
3280
SSL *ssl = NULL;
3281
STACK_OF(SSL_CIPHER) *sk = NULL;
3282
const SSL_CIPHER *cipher;
3283
int i=0;
3284
PyObject *result = NULL, *dct;
3285
3286
ssl = SSL_new(self->ctx);
3287
if (ssl == NULL) {
3288
_setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
3289
goto exit;
3290
}
3291
sk = SSL_get_ciphers(ssl);
3292
3293
result = PyList_New(sk_SSL_CIPHER_num(sk));
3294
if (result == NULL) {
3295
goto exit;
3296
}
3297
3298
for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3299
cipher = sk_SSL_CIPHER_value(sk, i);
3300
dct = cipher_to_dict(cipher);
3301
if (dct == NULL) {
3302
Py_CLEAR(result);
3303
goto exit;
3304
}
3305
PyList_SET_ITEM(result, i, dct);
3306
}
3307
3308
exit:
3309
if (ssl != NULL)
3310
SSL_free(ssl);
3311
return result;
3312
3313
}
3314
3315
3316
static int
3317
do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3318
const unsigned char *server_protocols, unsigned int server_protocols_len,
3319
const unsigned char *client_protocols, unsigned int client_protocols_len)
3320
{
3321
int ret;
3322
if (client_protocols == NULL) {
3323
client_protocols = (unsigned char *)"";
3324
client_protocols_len = 0;
3325
}
3326
if (server_protocols == NULL) {
3327
server_protocols = (unsigned char *)"";
3328
server_protocols_len = 0;
3329
}
3330
3331
ret = SSL_select_next_proto(out, outlen,
3332
server_protocols, server_protocols_len,
3333
client_protocols, client_protocols_len);
3334
if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3335
return SSL_TLSEXT_ERR_NOACK;
3336
3337
return SSL_TLSEXT_ERR_OK;
3338
}
3339
3340
static int
3341
_selectALPN_cb(SSL *s,
3342
const unsigned char **out, unsigned char *outlen,
3343
const unsigned char *client_protocols, unsigned int client_protocols_len,
3344
void *args)
3345
{
3346
PySSLContext *ctx = (PySSLContext *)args;
3347
return do_protocol_selection(1, (unsigned char **)out, outlen,
3348
ctx->alpn_protocols, ctx->alpn_protocols_len,
3349
client_protocols, client_protocols_len);
3350
}
3351
3352
/*[clinic input]
3353
_ssl._SSLContext._set_alpn_protocols
3354
protos: Py_buffer
3355
/
3356
[clinic start generated code]*/
3357
3358
static PyObject *
3359
_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3360
Py_buffer *protos)
3361
/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
3362
{
3363
if ((size_t)protos->len > UINT_MAX) {
3364
PyErr_Format(PyExc_OverflowError,
3365
"protocols longer than %u bytes", UINT_MAX);
3366
return NULL;
3367
}
3368
3369
PyMem_Free(self->alpn_protocols);
3370
self->alpn_protocols = PyMem_Malloc(protos->len);
3371
if (!self->alpn_protocols)
3372
return PyErr_NoMemory();
3373
memcpy(self->alpn_protocols, protos->buf, protos->len);
3374
self->alpn_protocols_len = (unsigned int)protos->len;
3375
3376
if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3377
return PyErr_NoMemory();
3378
SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3379
3380
Py_RETURN_NONE;
3381
}
3382
3383
static PyObject *
3384
get_verify_mode(PySSLContext *self, void *c)
3385
{
3386
/* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3387
int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3388
SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3389
switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
3390
case SSL_VERIFY_NONE:
3391
return PyLong_FromLong(PY_SSL_CERT_NONE);
3392
case SSL_VERIFY_PEER:
3393
return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3394
case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3395
return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3396
}
3397
PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
3398
"invalid return value from SSL_CTX_get_verify_mode");
3399
return NULL;
3400
}
3401
3402
static int
3403
set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3404
{
3405
int n;
3406
if (!PyArg_Parse(arg, "i", &n))
3407
return -1;
3408
if (n == PY_SSL_CERT_NONE && self->check_hostname) {
3409
PyErr_SetString(PyExc_ValueError,
3410
"Cannot set verify_mode to CERT_NONE when "
3411
"check_hostname is enabled.");
3412
return -1;
3413
}
3414
return _set_verify_mode(self, n);
3415
}
3416
3417
static PyObject *
3418
get_verify_flags(PySSLContext *self, void *c)
3419
{
3420
X509_VERIFY_PARAM *param;
3421
unsigned long flags;
3422
3423
param = SSL_CTX_get0_param(self->ctx);
3424
flags = X509_VERIFY_PARAM_get_flags(param);
3425
return PyLong_FromUnsignedLong(flags);
3426
}
3427
3428
static int
3429
set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3430
{
3431
X509_VERIFY_PARAM *param;
3432
unsigned long new_flags, flags, set, clear;
3433
3434
if (!PyArg_Parse(arg, "k", &new_flags))
3435
return -1;
3436
param = SSL_CTX_get0_param(self->ctx);
3437
flags = X509_VERIFY_PARAM_get_flags(param);
3438
clear = flags & ~new_flags;
3439
set = ~flags & new_flags;
3440
if (clear) {
3441
if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
3442
_setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
3443
return -1;
3444
}
3445
}
3446
if (set) {
3447
if (!X509_VERIFY_PARAM_set_flags(param, set)) {
3448
_setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
3449
return -1;
3450
}
3451
}
3452
return 0;
3453
}
3454
3455
/* Getter and setter for protocol version */
3456
static int
3457
set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3458
{
3459
long v;
3460
int result;
3461
3462
if (!PyArg_Parse(arg, "l", &v))
3463
return -1;
3464
if (v > INT_MAX) {
3465
PyErr_SetString(PyExc_OverflowError, "Option is too long");
3466
return -1;
3467
}
3468
3469
switch(self->protocol) {
3470
case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3471
case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3472
case PY_SSL_VERSION_TLS:
3473
break;
3474
default:
3475
PyErr_SetString(
3476
PyExc_ValueError,
3477
"The context's protocol doesn't support modification of "
3478
"highest and lowest version."
3479
);
3480
return -1;
3481
}
3482
3483
/* check for deprecations and supported values */
3484
switch(v) {
3485
case PY_PROTO_SSLv3:
3486
PY_SSL_DEPRECATED("ssl.TLSVersion.SSLv3 is deprecated", 2, -1);
3487
break;
3488
case PY_PROTO_TLSv1:
3489
PY_SSL_DEPRECATED("ssl.TLSVersion.TLSv1 is deprecated", 2, -1);
3490
break;
3491
case PY_PROTO_TLSv1_1:
3492
PY_SSL_DEPRECATED("ssl.TLSVersion.TLSv1_1 is deprecated", 2, -1);
3493
break;
3494
case PY_PROTO_MINIMUM_SUPPORTED:
3495
case PY_PROTO_MAXIMUM_SUPPORTED:
3496
case PY_PROTO_TLSv1_2:
3497
case PY_PROTO_TLSv1_3:
3498
/* ok */
3499
break;
3500
default:
3501
PyErr_Format(PyExc_ValueError,
3502
"Unsupported TLS/SSL version 0x%x", v);
3503
return -1;
3504
}
3505
3506
if (what == 0) {
3507
switch(v) {
3508
case PY_PROTO_MINIMUM_SUPPORTED:
3509
v = 0;
3510
break;
3511
case PY_PROTO_MAXIMUM_SUPPORTED:
3512
/* Emulate max for set_min_proto_version */
3513
v = PY_PROTO_MAXIMUM_AVAILABLE;
3514
break;
3515
default:
3516
break;
3517
}
3518
result = SSL_CTX_set_min_proto_version(self->ctx, v);
3519
}
3520
else {
3521
switch(v) {
3522
case PY_PROTO_MAXIMUM_SUPPORTED:
3523
v = 0;
3524
break;
3525
case PY_PROTO_MINIMUM_SUPPORTED:
3526
/* Emulate max for set_min_proto_version */
3527
v = PY_PROTO_MINIMUM_AVAILABLE;
3528
break;
3529
default:
3530
break;
3531
}
3532
result = SSL_CTX_set_max_proto_version(self->ctx, v);
3533
}
3534
if (result == 0) {
3535
PyErr_Format(PyExc_ValueError,
3536
"Unsupported protocol version 0x%x", v);
3537
return -1;
3538
}
3539
return 0;
3540
}
3541
3542
static PyObject *
3543
get_minimum_version(PySSLContext *self, void *c)
3544
{
3545
int v = SSL_CTX_get_min_proto_version(self->ctx);
3546
if (v == 0) {
3547
v = PY_PROTO_MINIMUM_SUPPORTED;
3548
}
3549
return PyLong_FromLong(v);
3550
}
3551
3552
static int
3553
set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3554
{
3555
return set_min_max_proto_version(self, arg, 0);
3556
}
3557
3558
static PyObject *
3559
get_maximum_version(PySSLContext *self, void *c)
3560
{
3561
int v = SSL_CTX_get_max_proto_version(self->ctx);
3562
if (v == 0) {
3563
v = PY_PROTO_MAXIMUM_SUPPORTED;
3564
}
3565
return PyLong_FromLong(v);
3566
}
3567
3568
static int
3569
set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3570
{
3571
return set_min_max_proto_version(self, arg, 1);
3572
}
3573
3574
#ifdef TLS1_3_VERSION
3575
static PyObject *
3576
get_num_tickets(PySSLContext *self, void *c)
3577
{
3578
return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
3579
}
3580
3581
static int
3582
set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3583
{
3584
long num;
3585
if (!PyArg_Parse(arg, "l", &num))
3586
return -1;
3587
if (num < 0) {
3588
PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3589
return -1;
3590
}
3591
if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3592
PyErr_SetString(PyExc_ValueError,
3593
"SSLContext is not a server context.");
3594
return -1;
3595
}
3596
if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3597
PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3598
return -1;
3599
}
3600
return 0;
3601
}
3602
3603
PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3604
"Control the number of TLSv1.3 session tickets");
3605
#endif /* TLS1_3_VERSION */
3606
3607
static PyObject *
3608
get_security_level(PySSLContext *self, void *c)
3609
{
3610
return PyLong_FromLong(SSL_CTX_get_security_level(self->ctx));
3611
}
3612
PyDoc_STRVAR(PySSLContext_security_level_doc, "The current security level");
3613
3614
static PyObject *
3615
get_options(PySSLContext *self, void *c)
3616
{
3617
return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3618
}
3619
3620
static int
3621
set_options(PySSLContext *self, PyObject *arg, void *c)
3622
{
3623
long new_opts, opts, set, clear;
3624
long opt_no = (
3625
SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 |
3626
SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2 | SSL_OP_NO_TLSv1_3
3627
);
3628
3629
if (!PyArg_Parse(arg, "l", &new_opts))
3630
return -1;
3631
opts = SSL_CTX_get_options(self->ctx);
3632
clear = opts & ~new_opts;
3633
set = ~opts & new_opts;
3634
3635
if ((set & opt_no) != 0) {
3636
if (_ssl_deprecated("ssl.OP_NO_SSL*/ssl.OP_NO_TLS* options are "
3637
"deprecated", 2) < 0) {
3638
return -1;
3639
}
3640
}
3641
if (clear) {
3642
SSL_CTX_clear_options(self->ctx, clear);
3643
}
3644
if (set)
3645
SSL_CTX_set_options(self->ctx, set);
3646
return 0;
3647
}
3648
3649
static PyObject *
3650
get_host_flags(PySSLContext *self, void *c)
3651
{
3652
return PyLong_FromUnsignedLong(self->hostflags);
3653
}
3654
3655
static int
3656
set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3657
{
3658
X509_VERIFY_PARAM *param;
3659
unsigned int new_flags = 0;
3660
3661
if (!PyArg_Parse(arg, "I", &new_flags))
3662
return -1;
3663
3664
param = SSL_CTX_get0_param(self->ctx);
3665
self->hostflags = new_flags;
3666
X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3667
return 0;
3668
}
3669
3670
static PyObject *
3671
get_check_hostname(PySSLContext *self, void *c)
3672
{
3673
return PyBool_FromLong(self->check_hostname);
3674
}
3675
3676
static int
3677
set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3678
{
3679
int check_hostname;
3680
if (!PyArg_Parse(arg, "p", &check_hostname))
3681
return -1;
3682
if (check_hostname &&
3683
SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
3684
/* check_hostname = True sets verify_mode = CERT_REQUIRED */
3685
if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
3686
return -1;
3687
}
3688
}
3689
self->check_hostname = check_hostname;
3690
return 0;
3691
}
3692
3693
static PyObject *
3694
get_post_handshake_auth(PySSLContext *self, void *c) {
3695
#if TLS1_3_VERSION
3696
return PyBool_FromLong(self->post_handshake_auth);
3697
#else
3698
Py_RETURN_NONE;
3699
#endif
3700
}
3701
3702
#if TLS1_3_VERSION
3703
static int
3704
set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
3705
if (arg == NULL) {
3706
PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3707
return -1;
3708
}
3709
int pha = PyObject_IsTrue(arg);
3710
3711
if (pha == -1) {
3712
return -1;
3713
}
3714
self->post_handshake_auth = pha;
3715
3716
/* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3717
* server sockets and SSL_set_post_handshake_auth() for client. */
3718
3719
return 0;
3720
}
3721
#endif
3722
3723
static PyObject *
3724
get_protocol(PySSLContext *self, void *c) {
3725
return PyLong_FromLong(self->protocol);
3726
}
3727
3728
typedef struct {
3729
PyThreadState *thread_state;
3730
PyObject *callable;
3731
char *password;
3732
int size;
3733
int error;
3734
} _PySSLPasswordInfo;
3735
3736
static int
3737
_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3738
const char *bad_type_error)
3739
{
3740
/* Set the password and size fields of a _PySSLPasswordInfo struct
3741
from a unicode, bytes, or byte array object.
3742
The password field will be dynamically allocated and must be freed
3743
by the caller */
3744
PyObject *password_bytes = NULL;
3745
const char *data = NULL;
3746
Py_ssize_t size;
3747
3748
if (PyUnicode_Check(password)) {
3749
password_bytes = PyUnicode_AsUTF8String(password);
3750
if (!password_bytes) {
3751
goto error;
3752
}
3753
data = PyBytes_AS_STRING(password_bytes);
3754
size = PyBytes_GET_SIZE(password_bytes);
3755
} else if (PyBytes_Check(password)) {
3756
data = PyBytes_AS_STRING(password);
3757
size = PyBytes_GET_SIZE(password);
3758
} else if (PyByteArray_Check(password)) {
3759
data = PyByteArray_AS_STRING(password);
3760
size = PyByteArray_GET_SIZE(password);
3761
} else {
3762
PyErr_SetString(PyExc_TypeError, bad_type_error);
3763
goto error;
3764
}
3765
3766
if (size > (Py_ssize_t)INT_MAX) {
3767
PyErr_Format(PyExc_ValueError,
3768
"password cannot be longer than %d bytes", INT_MAX);
3769
goto error;
3770
}
3771
3772
PyMem_Free(pw_info->password);
3773
pw_info->password = PyMem_Malloc(size);
3774
if (!pw_info->password) {
3775
PyErr_SetString(PyExc_MemoryError,
3776
"unable to allocate password buffer");
3777
goto error;
3778
}
3779
memcpy(pw_info->password, data, size);
3780
pw_info->size = (int)size;
3781
3782
Py_XDECREF(password_bytes);
3783
return 1;
3784
3785
error:
3786
Py_XDECREF(password_bytes);
3787
return 0;
3788
}
3789
3790
static int
3791
_password_callback(char *buf, int size, int rwflag, void *userdata)
3792
{
3793
_PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3794
PyObject *fn_ret = NULL;
3795
3796
PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3797
3798
if (pw_info->error) {
3799
/* already failed previously. OpenSSL 3.0.0-alpha14 invokes the
3800
* callback multiple times which can lead to fatal Python error in
3801
* exception check. */
3802
goto error;
3803
}
3804
3805
if (pw_info->callable) {
3806
fn_ret = PyObject_CallNoArgs(pw_info->callable);
3807
if (!fn_ret) {
3808
/* TODO: It would be nice to move _ctypes_add_traceback() into the
3809
core python API, so we could use it to add a frame here */
3810
goto error;
3811
}
3812
3813
if (!_pwinfo_set(pw_info, fn_ret,
3814
"password callback must return a string")) {
3815
goto error;
3816
}
3817
Py_CLEAR(fn_ret);
3818
}
3819
3820
if (pw_info->size > size) {
3821
PyErr_Format(PyExc_ValueError,
3822
"password cannot be longer than %d bytes", size);
3823
goto error;
3824
}
3825
3826
PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3827
memcpy(buf, pw_info->password, pw_info->size);
3828
return pw_info->size;
3829
3830
error:
3831
Py_XDECREF(fn_ret);
3832
PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3833
pw_info->error = 1;
3834
return -1;
3835
}
3836
3837
/*[clinic input]
3838
_ssl._SSLContext.load_cert_chain
3839
certfile: object
3840
keyfile: object = None
3841
password: object = None
3842
3843
[clinic start generated code]*/
3844
3845
static PyObject *
3846
_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3847
PyObject *keyfile, PyObject *password)
3848
/*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
3849
{
3850
PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
3851
pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3852
void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
3853
_PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
3854
int r;
3855
3856
errno = 0;
3857
ERR_clear_error();
3858
if (keyfile == Py_None)
3859
keyfile = NULL;
3860
if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3861
if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3862
PyErr_SetString(PyExc_TypeError,
3863
"certfile should be a valid filesystem path");
3864
}
3865
return NULL;
3866
}
3867
if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3868
if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3869
PyErr_SetString(PyExc_TypeError,
3870
"keyfile should be a valid filesystem path");
3871
}
3872
goto error;
3873
}
3874
if (password != Py_None) {
3875
if (PyCallable_Check(password)) {
3876
pw_info.callable = password;
3877
} else if (!_pwinfo_set(&pw_info, password,
3878
"password should be a string or callable")) {
3879
goto error;
3880
}
3881
SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3882
SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3883
}
3884
PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
3885
r = SSL_CTX_use_certificate_chain_file(self->ctx,
3886
PyBytes_AS_STRING(certfile_bytes));
3887
PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3888
if (r != 1) {
3889
if (pw_info.error) {
3890
ERR_clear_error();
3891
/* the password callback has already set the error information */
3892
}
3893
else if (errno != 0) {
3894
ERR_clear_error();
3895
PyErr_SetFromErrno(PyExc_OSError);
3896
}
3897
else {
3898
_setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
3899
}
3900
goto error;
3901
}
3902
PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
3903
r = SSL_CTX_use_PrivateKey_file(self->ctx,
3904
PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3905
SSL_FILETYPE_PEM);
3906
PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3907
Py_CLEAR(keyfile_bytes);
3908
Py_CLEAR(certfile_bytes);
3909
if (r != 1) {
3910
if (pw_info.error) {
3911
ERR_clear_error();
3912
/* the password callback has already set the error information */
3913
}
3914
else if (errno != 0) {
3915
ERR_clear_error();
3916
PyErr_SetFromErrno(PyExc_OSError);
3917
}
3918
else {
3919
_setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
3920
}
3921
goto error;
3922
}
3923
PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
3924
r = SSL_CTX_check_private_key(self->ctx);
3925
PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3926
if (r != 1) {
3927
_setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
3928
goto error;
3929
}
3930
SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3931
SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
3932
PyMem_Free(pw_info.password);
3933
Py_RETURN_NONE;
3934
3935
error:
3936
SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3937
SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
3938
PyMem_Free(pw_info.password);
3939
Py_XDECREF(keyfile_bytes);
3940
Py_XDECREF(certfile_bytes);
3941
return NULL;
3942
}
3943
3944
/* internal helper function, returns -1 on error
3945
*/
3946
static int
3947
_add_ca_certs(PySSLContext *self, const void *data, Py_ssize_t len,
3948
int filetype)
3949
{
3950
BIO *biobuf = NULL;
3951
X509_STORE *store;
3952
int retval = -1, err, loaded = 0, was_bio_eof = 0;
3953
3954
assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3955
3956
if (len <= 0) {
3957
PyErr_SetString(PyExc_ValueError,
3958
"Empty certificate data");
3959
return -1;
3960
} else if (len > INT_MAX) {
3961
PyErr_SetString(PyExc_OverflowError,
3962
"Certificate data is too long.");
3963
return -1;
3964
}
3965
3966
biobuf = BIO_new_mem_buf(data, (int)len);
3967
if (biobuf == NULL) {
3968
_setSSLError(get_state_ctx(self), "Can't allocate buffer", 0, __FILE__, __LINE__);
3969
return -1;
3970
}
3971
3972
store = SSL_CTX_get_cert_store(self->ctx);
3973
assert(store != NULL);
3974
3975
while (1) {
3976
X509 *cert = NULL;
3977
int r;
3978
3979
if (filetype == SSL_FILETYPE_ASN1) {
3980
if (BIO_eof(biobuf)) {
3981
was_bio_eof = 1;
3982
break;
3983
}
3984
cert = d2i_X509_bio(biobuf, NULL);
3985
} else {
3986
cert = PEM_read_bio_X509(biobuf, NULL,
3987
SSL_CTX_get_default_passwd_cb(self->ctx),
3988
SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3989
);
3990
}
3991
if (cert == NULL) {
3992
break;
3993
}
3994
r = X509_STORE_add_cert(store, cert);
3995
X509_free(cert);
3996
if (!r) {
3997
err = ERR_peek_last_error();
3998
if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3999
(ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
4000
/* cert already in hash table, not an error */
4001
ERR_clear_error();
4002
} else {
4003
break;
4004
}
4005
}
4006
loaded++;
4007
}
4008
4009
err = ERR_peek_last_error();
4010
if (loaded == 0) {
4011
const char *msg = NULL;
4012
if (filetype == SSL_FILETYPE_PEM) {
4013
msg = "no start line: cadata does not contain a certificate";
4014
} else {
4015
msg = "not enough data: cadata does not contain a certificate";
4016
}
4017
_setSSLError(get_state_ctx(self), msg, 0, __FILE__, __LINE__);
4018
retval = -1;
4019
} else if ((filetype == SSL_FILETYPE_ASN1) && was_bio_eof) {
4020
/* EOF ASN1 file, not an error */
4021
ERR_clear_error();
4022
retval = 0;
4023
} else if ((filetype == SSL_FILETYPE_PEM) &&
4024
(ERR_GET_LIB(err) == ERR_LIB_PEM) &&
4025
(ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
4026
/* EOF PEM file, not an error */
4027
ERR_clear_error();
4028
retval = 0;
4029
} else if (err != 0) {
4030
_setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
4031
retval = -1;
4032
} else {
4033
retval = 0;
4034
}
4035
4036
BIO_free(biobuf);
4037
return retval;
4038
}
4039
4040
4041
/*[clinic input]
4042
_ssl._SSLContext.load_verify_locations
4043
cafile: object = None
4044
capath: object = None
4045
cadata: object = None
4046
4047
[clinic start generated code]*/
4048
4049
static PyObject *
4050
_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
4051
PyObject *cafile,
4052
PyObject *capath,
4053
PyObject *cadata)
4054
/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
4055
{
4056
PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
4057
const char *cafile_buf = NULL, *capath_buf = NULL;
4058
int r = 0, ok = 1;
4059
4060
errno = 0;
4061
if (cafile == Py_None)
4062
cafile = NULL;
4063
if (capath == Py_None)
4064
capath = NULL;
4065
if (cadata == Py_None)
4066
cadata = NULL;
4067
4068
if (cafile == NULL && capath == NULL && cadata == NULL) {
4069
PyErr_SetString(PyExc_TypeError,
4070
"cafile, capath and cadata cannot be all omitted");
4071
goto error;
4072
}
4073
if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
4074
if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4075
PyErr_SetString(PyExc_TypeError,
4076
"cafile should be a valid filesystem path");
4077
}
4078
goto error;
4079
}
4080
if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
4081
if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4082
PyErr_SetString(PyExc_TypeError,
4083
"capath should be a valid filesystem path");
4084
}
4085
goto error;
4086
}
4087
4088
/* validate cadata type and load cadata */
4089
if (cadata) {
4090
if (PyUnicode_Check(cadata)) {
4091
PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
4092
if (cadata_ascii == NULL) {
4093
if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4094
goto invalid_cadata;
4095
}
4096
goto error;
4097
}
4098
r = _add_ca_certs(self,
4099
PyBytes_AS_STRING(cadata_ascii),
4100
PyBytes_GET_SIZE(cadata_ascii),
4101
SSL_FILETYPE_PEM);
4102
Py_DECREF(cadata_ascii);
4103
if (r == -1) {
4104
goto error;
4105
}
4106
}
4107
else if (PyObject_CheckBuffer(cadata)) {
4108
Py_buffer buf;
4109
if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
4110
goto error;
4111
}
4112
if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4113
PyBuffer_Release(&buf);
4114
PyErr_SetString(PyExc_TypeError,
4115
"cadata should be a contiguous buffer with "
4116
"a single dimension");
4117
goto error;
4118
}
4119
r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4120
PyBuffer_Release(&buf);
4121
if (r == -1) {
4122
goto error;
4123
}
4124
}
4125
else {
4126
invalid_cadata:
4127
PyErr_SetString(PyExc_TypeError,
4128
"cadata should be an ASCII string or a "
4129
"bytes-like object");
4130
goto error;
4131
}
4132
}
4133
4134
/* load cafile or capath */
4135
if (cafile || capath) {
4136
if (cafile)
4137
cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4138
if (capath)
4139
capath_buf = PyBytes_AS_STRING(capath_bytes);
4140
PySSL_BEGIN_ALLOW_THREADS
4141
r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4142
PySSL_END_ALLOW_THREADS
4143
if (r != 1) {
4144
if (errno != 0) {
4145
ERR_clear_error();
4146
PyErr_SetFromErrno(PyExc_OSError);
4147
}
4148
else {
4149
_setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
4150
}
4151
goto error;
4152
}
4153
}
4154
goto end;
4155
4156
error:
4157
ok = 0;
4158
end:
4159
Py_XDECREF(cafile_bytes);
4160
Py_XDECREF(capath_bytes);
4161
if (ok) {
4162
Py_RETURN_NONE;
4163
} else {
4164
return NULL;
4165
}
4166
}
4167
4168
/*[clinic input]
4169
_ssl._SSLContext.load_dh_params
4170
path as filepath: object
4171
/
4172
4173
[clinic start generated code]*/
4174
4175
static PyObject *
4176
_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4177
/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
4178
{
4179
FILE *f;
4180
DH *dh;
4181
4182
f = _Py_fopen_obj(filepath, "rb");
4183
if (f == NULL)
4184
return NULL;
4185
4186
errno = 0;
4187
PySSL_BEGIN_ALLOW_THREADS
4188
dh = PEM_read_DHparams(f, NULL, NULL, NULL);
4189
fclose(f);
4190
PySSL_END_ALLOW_THREADS
4191
if (dh == NULL) {
4192
if (errno != 0) {
4193
ERR_clear_error();
4194
PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4195
}
4196
else {
4197
_setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
4198
}
4199
return NULL;
4200
}
4201
if (!SSL_CTX_set_tmp_dh(self->ctx, dh)) {
4202
DH_free(dh);
4203
return _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
4204
}
4205
DH_free(dh);
4206
Py_RETURN_NONE;
4207
}
4208
4209
/*[clinic input]
4210
_ssl._SSLContext._wrap_socket
4211
sock: object(subclass_of="get_state_ctx(self)->Sock_Type")
4212
server_side: bool
4213
server_hostname as hostname_obj: object = None
4214
*
4215
owner: object = None
4216
session: object = None
4217
4218
[clinic start generated code]*/
4219
4220
static PyObject *
4221
_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
4222
int server_side, PyObject *hostname_obj,
4223
PyObject *owner, PyObject *session)
4224
/*[clinic end generated code: output=f103f238633940b4 input=700ca8fedff53994]*/
4225
{
4226
char *hostname = NULL;
4227
PyObject *res;
4228
4229
/* server_hostname is either None (or absent), or to be encoded
4230
as IDN A-label (ASCII str) without NULL bytes. */
4231
if (hostname_obj != Py_None) {
4232
if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
4233
return NULL;
4234
}
4235
4236
res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4237
server_side, hostname,
4238
owner, session,
4239
NULL, NULL);
4240
if (hostname != NULL)
4241
PyMem_Free(hostname);
4242
return res;
4243
}
4244
4245
/*[clinic input]
4246
_ssl._SSLContext._wrap_bio
4247
incoming: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4248
outgoing: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4249
server_side: bool
4250
server_hostname as hostname_obj: object = None
4251
*
4252
owner: object = None
4253
session: object = None
4254
4255
[clinic start generated code]*/
4256
4257
static PyObject *
4258
_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4259
PySSLMemoryBIO *outgoing, int server_side,
4260
PyObject *hostname_obj, PyObject *owner,
4261
PyObject *session)
4262
/*[clinic end generated code: output=5c5d6d9b41f99332 input=a9205d097fd45a82]*/
4263
{
4264
char *hostname = NULL;
4265
PyObject *res;
4266
4267
/* server_hostname is either None (or absent), or to be encoded
4268
as IDN A-label (ASCII str) without NULL bytes. */
4269
if (hostname_obj != Py_None) {
4270
if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
4271
return NULL;
4272
}
4273
4274
res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
4275
owner, session,
4276
incoming, outgoing);
4277
4278
PyMem_Free(hostname);
4279
return res;
4280
}
4281
4282
/*[clinic input]
4283
_ssl._SSLContext.session_stats
4284
[clinic start generated code]*/
4285
4286
static PyObject *
4287
_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4288
/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
4289
{
4290
int r;
4291
PyObject *value, *stats = PyDict_New();
4292
if (!stats)
4293
return NULL;
4294
4295
#define ADD_STATS(SSL_NAME, KEY_NAME) \
4296
value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4297
if (value == NULL) \
4298
goto error; \
4299
r = PyDict_SetItemString(stats, KEY_NAME, value); \
4300
Py_DECREF(value); \
4301
if (r < 0) \
4302
goto error;
4303
4304
ADD_STATS(number, "number");
4305
ADD_STATS(connect, "connect");
4306
ADD_STATS(connect_good, "connect_good");
4307
ADD_STATS(connect_renegotiate, "connect_renegotiate");
4308
ADD_STATS(accept, "accept");
4309
ADD_STATS(accept_good, "accept_good");
4310
ADD_STATS(accept_renegotiate, "accept_renegotiate");
4311
ADD_STATS(accept, "accept");
4312
ADD_STATS(hits, "hits");
4313
ADD_STATS(misses, "misses");
4314
ADD_STATS(timeouts, "timeouts");
4315
ADD_STATS(cache_full, "cache_full");
4316
4317
#undef ADD_STATS
4318
4319
return stats;
4320
4321
error:
4322
Py_DECREF(stats);
4323
return NULL;
4324
}
4325
4326
/*[clinic input]
4327
_ssl._SSLContext.set_default_verify_paths
4328
[clinic start generated code]*/
4329
4330
static PyObject *
4331
_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4332
/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
4333
{
4334
int rc;
4335
Py_BEGIN_ALLOW_THREADS
4336
rc = SSL_CTX_set_default_verify_paths(self->ctx);
4337
Py_END_ALLOW_THREADS
4338
if (!rc) {
4339
_setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
4340
return NULL;
4341
}
4342
Py_RETURN_NONE;
4343
}
4344
4345
/*[clinic input]
4346
_ssl._SSLContext.set_ecdh_curve
4347
name: object
4348
/
4349
4350
[clinic start generated code]*/
4351
4352
static PyObject *
4353
_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4354
/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
4355
{
4356
PyObject *name_bytes;
4357
int nid;
4358
if (!PyUnicode_FSConverter(name, &name_bytes))
4359
return NULL;
4360
assert(PyBytes_Check(name_bytes));
4361
nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4362
Py_DECREF(name_bytes);
4363
if (nid == 0) {
4364
PyErr_Format(PyExc_ValueError,
4365
"unknown elliptic curve name %R", name);
4366
return NULL;
4367
}
4368
#if OPENSSL_VERSION_MAJOR < 3
4369
EC_KEY *key = EC_KEY_new_by_curve_name(nid);
4370
if (key == NULL) {
4371
_setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
4372
return NULL;
4373
}
4374
SSL_CTX_set_tmp_ecdh(self->ctx, key);
4375
EC_KEY_free(key);
4376
#else
4377
if (!SSL_CTX_set1_groups(self->ctx, &nid, 1)) {
4378
_setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
4379
return NULL;
4380
}
4381
#endif
4382
Py_RETURN_NONE;
4383
}
4384
4385
static int
4386
_servername_callback(SSL *s, int *al, void *args)
4387
{
4388
int ret;
4389
PySSLContext *sslctx = (PySSLContext *) args;
4390
PySSLSocket *ssl;
4391
PyObject *result;
4392
/* The high-level ssl.SSLSocket object */
4393
PyObject *ssl_socket;
4394
const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
4395
PyGILState_STATE gstate = PyGILState_Ensure();
4396
4397
if (sslctx->set_sni_cb == NULL) {
4398
/* remove race condition in this the call back while if removing the
4399
* callback is in progress */
4400
PyGILState_Release(gstate);
4401
return SSL_TLSEXT_ERR_OK;
4402
}
4403
4404
ssl = SSL_get_app_data(s);
4405
assert(Py_IS_TYPE(ssl, get_state_ctx(sslctx)->PySSLSocket_Type));
4406
4407
/* The servername callback expects an argument that represents the current
4408
* SSL connection and that has a .context attribute that can be changed to
4409
* identify the requested hostname. Since the official API is the Python
4410
* level API we want to pass the callback a Python level object rather than
4411
* a _ssl.SSLSocket instance. If there's an "owner" (typically an
4412
* SSLObject) that will be passed. Otherwise if there's a socket then that
4413
* will be passed. If both do not exist only then the C-level object is
4414
* passed. */
4415
if (ssl->owner)
4416
ssl_socket = _PyWeakref_GET_REF(ssl->owner);
4417
else if (ssl->Socket)
4418
ssl_socket = _PyWeakref_GET_REF(ssl->Socket);
4419
else
4420
ssl_socket = Py_NewRef(ssl);
4421
4422
if (ssl_socket == NULL)
4423
goto error;
4424
4425
if (servername == NULL) {
4426
result = PyObject_CallFunctionObjArgs(sslctx->set_sni_cb, ssl_socket,
4427
Py_None, sslctx, NULL);
4428
}
4429
else {
4430
PyObject *servername_bytes;
4431
PyObject *servername_str;
4432
4433
servername_bytes = PyBytes_FromString(servername);
4434
if (servername_bytes == NULL) {
4435
PyErr_WriteUnraisable((PyObject *) sslctx);
4436
goto error;
4437
}
4438
/* server_hostname was encoded to an A-label by our caller; put it
4439
* back into a str object, but still as an A-label (bpo-28414)
4440
*/
4441
servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4442
if (servername_str == NULL) {
4443
PyErr_WriteUnraisable(servername_bytes);
4444
Py_DECREF(servername_bytes);
4445
goto error;
4446
}
4447
Py_DECREF(servername_bytes);
4448
result = PyObject_CallFunctionObjArgs(
4449
sslctx->set_sni_cb, ssl_socket, servername_str,
4450
sslctx, NULL);
4451
Py_DECREF(servername_str);
4452
}
4453
Py_DECREF(ssl_socket);
4454
4455
if (result == NULL) {
4456
PyErr_WriteUnraisable(sslctx->set_sni_cb);
4457
*al = SSL_AD_HANDSHAKE_FAILURE;
4458
ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4459
}
4460
else {
4461
/* Result may be None, a SSLContext or an integer
4462
* None and SSLContext are OK, integer or other values are an error.
4463
*/
4464
if (result == Py_None) {
4465
ret = SSL_TLSEXT_ERR_OK;
4466
} else {
4467
*al = (int) PyLong_AsLong(result);
4468
if (PyErr_Occurred()) {
4469
PyErr_WriteUnraisable(result);
4470
*al = SSL_AD_INTERNAL_ERROR;
4471
}
4472
ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4473
}
4474
Py_DECREF(result);
4475
}
4476
4477
PyGILState_Release(gstate);
4478
return ret;
4479
4480
error:
4481
Py_DECREF(ssl_socket);
4482
*al = SSL_AD_INTERNAL_ERROR;
4483
ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4484
PyGILState_Release(gstate);
4485
return ret;
4486
}
4487
4488
static PyObject *
4489
get_sni_callback(PySSLContext *self, void *c)
4490
{
4491
PyObject *cb = self->set_sni_cb;
4492
if (cb == NULL) {
4493
Py_RETURN_NONE;
4494
}
4495
return Py_NewRef(cb);
4496
}
4497
4498
static int
4499
set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4500
{
4501
if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4502
PyErr_SetString(PyExc_ValueError,
4503
"sni_callback cannot be set on TLS_CLIENT context");
4504
return -1;
4505
}
4506
Py_CLEAR(self->set_sni_cb);
4507
if (arg == Py_None) {
4508
SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4509
}
4510
else {
4511
if (!PyCallable_Check(arg)) {
4512
SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4513
PyErr_SetString(PyExc_TypeError,
4514
"not a callable object");
4515
return -1;
4516
}
4517
self->set_sni_cb = Py_NewRef(arg);
4518
SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4519
SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4520
}
4521
return 0;
4522
}
4523
4524
PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4525
"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4526
\n\
4527
If the argument is None then the callback is disabled. The method is called\n\
4528
with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4529
See RFC 6066 for details of the SNI extension.");
4530
4531
/*[clinic input]
4532
_ssl._SSLContext.cert_store_stats
4533
4534
Returns quantities of loaded X.509 certificates.
4535
4536
X.509 certificates with a CA extension and certificate revocation lists
4537
inside the context's cert store.
4538
4539
NOTE: Certificates in a capath directory aren't loaded unless they have
4540
been used at least once.
4541
[clinic start generated code]*/
4542
4543
static PyObject *
4544
_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4545
/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
4546
{
4547
X509_STORE *store;
4548
STACK_OF(X509_OBJECT) *objs;
4549
X509_OBJECT *obj;
4550
int x509 = 0, crl = 0, ca = 0, i;
4551
4552
store = SSL_CTX_get_cert_store(self->ctx);
4553
objs = X509_STORE_get0_objects(store);
4554
for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4555
obj = sk_X509_OBJECT_value(objs, i);
4556
switch (X509_OBJECT_get_type(obj)) {
4557
case X509_LU_X509:
4558
x509++;
4559
if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
4560
ca++;
4561
}
4562
break;
4563
case X509_LU_CRL:
4564
crl++;
4565
break;
4566
default:
4567
/* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4568
* As far as I can tell they are internal states and never
4569
* stored in a cert store */
4570
break;
4571
}
4572
}
4573
return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4574
"x509_ca", ca);
4575
}
4576
4577
/*[clinic input]
4578
_ssl._SSLContext.get_ca_certs
4579
binary_form: bool = False
4580
4581
Returns a list of dicts with information of loaded CA certs.
4582
4583
If the optional argument is True, returns a DER-encoded copy of the CA
4584
certificate.
4585
4586
NOTE: Certificates in a capath directory aren't loaded unless they have
4587
been used at least once.
4588
[clinic start generated code]*/
4589
4590
static PyObject *
4591
_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4592
/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
4593
{
4594
X509_STORE *store;
4595
STACK_OF(X509_OBJECT) *objs;
4596
PyObject *ci = NULL, *rlist = NULL;
4597
int i;
4598
4599
if ((rlist = PyList_New(0)) == NULL) {
4600
return NULL;
4601
}
4602
4603
store = SSL_CTX_get_cert_store(self->ctx);
4604
objs = X509_STORE_get0_objects(store);
4605
for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4606
X509_OBJECT *obj;
4607
X509 *cert;
4608
4609
obj = sk_X509_OBJECT_value(objs, i);
4610
if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
4611
/* not a x509 cert */
4612
continue;
4613
}
4614
/* CA for any purpose */
4615
cert = X509_OBJECT_get0_X509(obj);
4616
if (!X509_check_ca(cert)) {
4617
continue;
4618
}
4619
if (binary_form) {
4620
ci = _certificate_to_der(get_state_ctx(self), cert);
4621
} else {
4622
ci = _decode_certificate(get_state_ctx(self), cert);
4623
}
4624
if (ci == NULL) {
4625
goto error;
4626
}
4627
if (PyList_Append(rlist, ci) == -1) {
4628
goto error;
4629
}
4630
Py_CLEAR(ci);
4631
}
4632
return rlist;
4633
4634
error:
4635
Py_XDECREF(ci);
4636
Py_XDECREF(rlist);
4637
return NULL;
4638
}
4639
4640
4641
static PyGetSetDef context_getsetlist[] = {
4642
{"check_hostname", (getter) get_check_hostname,
4643
(setter) set_check_hostname, NULL},
4644
{"_host_flags", (getter) get_host_flags,
4645
(setter) set_host_flags, NULL},
4646
{"minimum_version", (getter) get_minimum_version,
4647
(setter) set_minimum_version, NULL},
4648
{"maximum_version", (getter) get_maximum_version,
4649
(setter) set_maximum_version, NULL},
4650
{"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4651
(setter) _PySSLContext_set_keylog_filename, NULL},
4652
{"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4653
(setter) _PySSLContext_set_msg_callback, NULL},
4654
{"sni_callback", (getter) get_sni_callback,
4655
(setter) set_sni_callback, PySSLContext_sni_callback_doc},
4656
#ifdef TLS1_3_VERSION
4657
{"num_tickets", (getter) get_num_tickets,
4658
(setter) set_num_tickets, PySSLContext_num_tickets_doc},
4659
#endif
4660
{"options", (getter) get_options,
4661
(setter) set_options, NULL},
4662
{"post_handshake_auth", (getter) get_post_handshake_auth,
4663
#ifdef TLS1_3_VERSION
4664
(setter) set_post_handshake_auth,
4665
#else
4666
NULL,
4667
#endif
4668
NULL},
4669
{"protocol", (getter) get_protocol,
4670
NULL, NULL},
4671
{"verify_flags", (getter) get_verify_flags,
4672
(setter) set_verify_flags, NULL},
4673
{"verify_mode", (getter) get_verify_mode,
4674
(setter) set_verify_mode, NULL},
4675
{"security_level", (getter) get_security_level,
4676
NULL, PySSLContext_security_level_doc},
4677
{NULL}, /* sentinel */
4678
};
4679
4680
static struct PyMethodDef context_methods[] = {
4681
_SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4682
_SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4683
_SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4684
_SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4685
_SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4686
_SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4687
_SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4688
_SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4689
_SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4690
_SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
4691
_SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4692
_SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
4693
_SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
4694
{NULL, NULL} /* sentinel */
4695
};
4696
4697
static PyType_Slot PySSLContext_slots[] = {
4698
{Py_tp_methods, context_methods},
4699
{Py_tp_getset, context_getsetlist},
4700
{Py_tp_new, _ssl__SSLContext},
4701
{Py_tp_dealloc, context_dealloc},
4702
{Py_tp_traverse, context_traverse},
4703
{Py_tp_clear, context_clear},
4704
{0, 0},
4705
};
4706
4707
static PyType_Spec PySSLContext_spec = {
4708
.name = "_ssl._SSLContext",
4709
.basicsize = sizeof(PySSLContext),
4710
.flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
4711
Py_TPFLAGS_IMMUTABLETYPE),
4712
.slots = PySSLContext_slots,
4713
};
4714
4715
4716
/*
4717
* MemoryBIO objects
4718
*/
4719
4720
/*[clinic input]
4721
@classmethod
4722
_ssl.MemoryBIO.__new__
4723
4724
[clinic start generated code]*/
4725
4726
static PyObject *
4727
_ssl_MemoryBIO_impl(PyTypeObject *type)
4728
/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
4729
{
4730
BIO *bio;
4731
PySSLMemoryBIO *self;
4732
4733
bio = BIO_new(BIO_s_mem());
4734
if (bio == NULL) {
4735
PyErr_SetString(PyExc_MemoryError, "failed to allocate BIO");
4736
return NULL;
4737
}
4738
/* Since our BIO is non-blocking an empty read() does not indicate EOF,
4739
* just that no data is currently available. The SSL routines should retry
4740
* the read, which we can achieve by calling BIO_set_retry_read(). */
4741
BIO_set_retry_read(bio);
4742
BIO_set_mem_eof_return(bio, -1);
4743
4744
assert(type != NULL && type->tp_alloc != NULL);
4745
self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4746
if (self == NULL) {
4747
BIO_free(bio);
4748
return NULL;
4749
}
4750
self->bio = bio;
4751
self->eof_written = 0;
4752
4753
return (PyObject *) self;
4754
}
4755
4756
static int
4757
memory_bio_traverse(PySSLMemoryBIO *self, visitproc visit, void *arg)
4758
{
4759
Py_VISIT(Py_TYPE(self));
4760
return 0;
4761
}
4762
4763
static void
4764
memory_bio_dealloc(PySSLMemoryBIO *self)
4765
{
4766
PyTypeObject *tp = Py_TYPE(self);
4767
PyObject_GC_UnTrack(self);
4768
BIO_free(self->bio);
4769
Py_TYPE(self)->tp_free(self);
4770
Py_DECREF(tp);
4771
}
4772
4773
static PyObject *
4774
memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4775
{
4776
return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
4777
}
4778
4779
PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4780
"The number of bytes pending in the memory BIO.");
4781
4782
static PyObject *
4783
memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4784
{
4785
return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4786
&& self->eof_written);
4787
}
4788
4789
PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4790
"Whether the memory BIO is at EOF.");
4791
4792
/*[clinic input]
4793
_ssl.MemoryBIO.read
4794
size as len: int = -1
4795
/
4796
4797
Read up to size bytes from the memory BIO.
4798
4799
If size is not specified, read the entire buffer.
4800
If the return value is an empty bytes instance, this means either
4801
EOF or that no data is available. Use the "eof" property to
4802
distinguish between the two.
4803
[clinic start generated code]*/
4804
4805
static PyObject *
4806
_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4807
/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4808
{
4809
int avail, nbytes;
4810
PyObject *result;
4811
4812
avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
4813
if ((len < 0) || (len > avail))
4814
len = avail;
4815
4816
result = PyBytes_FromStringAndSize(NULL, len);
4817
if ((result == NULL) || (len == 0))
4818
return result;
4819
4820
nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4821
if (nbytes < 0) {
4822
_sslmodulestate *state = get_state_mbio(self);
4823
Py_DECREF(result);
4824
_setSSLError(state, NULL, 0, __FILE__, __LINE__);
4825
return NULL;
4826
}
4827
4828
/* There should never be any short reads but check anyway. */
4829
if (nbytes < len) {
4830
_PyBytes_Resize(&result, nbytes);
4831
}
4832
4833
return result;
4834
}
4835
4836
/*[clinic input]
4837
_ssl.MemoryBIO.write
4838
b: Py_buffer
4839
/
4840
4841
Writes the bytes b into the memory BIO.
4842
4843
Returns the number of bytes written.
4844
[clinic start generated code]*/
4845
4846
static PyObject *
4847
_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4848
/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
4849
{
4850
int nbytes;
4851
4852
if (b->len > INT_MAX) {
4853
PyErr_Format(PyExc_OverflowError,
4854
"string longer than %d bytes", INT_MAX);
4855
return NULL;
4856
}
4857
4858
if (self->eof_written) {
4859
PyObject *module = PyType_GetModule(Py_TYPE(self));
4860
if (module == NULL)
4861
return NULL;
4862
PyErr_SetString(get_ssl_state(module)->PySSLErrorObject,
4863
"cannot write() after write_eof()");
4864
return NULL;
4865
}
4866
4867
nbytes = BIO_write(self->bio, b->buf, (int)b->len);
4868
if (nbytes < 0) {
4869
_sslmodulestate *state = get_state_mbio(self);
4870
_setSSLError(state, NULL, 0, __FILE__, __LINE__);
4871
return NULL;
4872
}
4873
4874
return PyLong_FromLong(nbytes);
4875
}
4876
4877
/*[clinic input]
4878
_ssl.MemoryBIO.write_eof
4879
4880
Write an EOF marker to the memory BIO.
4881
4882
When all data has been read, the "eof" property will be True.
4883
[clinic start generated code]*/
4884
4885
static PyObject *
4886
_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4887
/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
4888
{
4889
self->eof_written = 1;
4890
/* After an EOF is written, a zero return from read() should be a real EOF
4891
* i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4892
BIO_clear_retry_flags(self->bio);
4893
BIO_set_mem_eof_return(self->bio, 0);
4894
4895
Py_RETURN_NONE;
4896
}
4897
4898
static PyGetSetDef memory_bio_getsetlist[] = {
4899
{"pending", (getter) memory_bio_get_pending, NULL,
4900
PySSL_memory_bio_pending_doc},
4901
{"eof", (getter) memory_bio_get_eof, NULL,
4902
PySSL_memory_bio_eof_doc},
4903
{NULL}, /* sentinel */
4904
};
4905
4906
static struct PyMethodDef memory_bio_methods[] = {
4907
_SSL_MEMORYBIO_READ_METHODDEF
4908
_SSL_MEMORYBIO_WRITE_METHODDEF
4909
_SSL_MEMORYBIO_WRITE_EOF_METHODDEF
4910
{NULL, NULL} /* sentinel */
4911
};
4912
4913
static PyType_Slot PySSLMemoryBIO_slots[] = {
4914
{Py_tp_methods, memory_bio_methods},
4915
{Py_tp_getset, memory_bio_getsetlist},
4916
{Py_tp_new, _ssl_MemoryBIO},
4917
{Py_tp_dealloc, memory_bio_dealloc},
4918
{Py_tp_traverse, memory_bio_traverse},
4919
{0, 0},
4920
};
4921
4922
static PyType_Spec PySSLMemoryBIO_spec = {
4923
.name = "_ssl.MemoryBIO",
4924
.basicsize = sizeof(PySSLMemoryBIO),
4925
.flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
4926
Py_TPFLAGS_HAVE_GC),
4927
.slots = PySSLMemoryBIO_slots,
4928
};
4929
4930
/*
4931
* SSL Session object
4932
*/
4933
4934
static void
4935
PySSLSession_dealloc(PySSLSession *self)
4936
{
4937
PyTypeObject *tp = Py_TYPE(self);
4938
/* bpo-31095: UnTrack is needed before calling any callbacks */
4939
PyObject_GC_UnTrack(self);
4940
Py_XDECREF(self->ctx);
4941
if (self->session != NULL) {
4942
SSL_SESSION_free(self->session);
4943
}
4944
PyObject_GC_Del(self);
4945
Py_DECREF(tp);
4946
}
4947
4948
static PyObject *
4949
PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4950
{
4951
int result;
4952
PyTypeObject *sesstype = ((PySSLSession*)left)->ctx->state->PySSLSession_Type;
4953
4954
if (left == NULL || right == NULL) {
4955
PyErr_BadInternalCall();
4956
return NULL;
4957
}
4958
4959
if (!Py_IS_TYPE(left, sesstype) || !Py_IS_TYPE(right, sesstype)) {
4960
Py_RETURN_NOTIMPLEMENTED;
4961
}
4962
4963
if (left == right) {
4964
result = 0;
4965
} else {
4966
const unsigned char *left_id, *right_id;
4967
unsigned int left_len, right_len;
4968
left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4969
&left_len);
4970
right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4971
&right_len);
4972
if (left_len == right_len) {
4973
result = memcmp(left_id, right_id, left_len);
4974
} else {
4975
result = 1;
4976
}
4977
}
4978
4979
switch (op) {
4980
case Py_EQ:
4981
if (result == 0) {
4982
Py_RETURN_TRUE;
4983
} else {
4984
Py_RETURN_FALSE;
4985
}
4986
break;
4987
case Py_NE:
4988
if (result != 0) {
4989
Py_RETURN_TRUE;
4990
} else {
4991
Py_RETURN_FALSE;
4992
}
4993
break;
4994
case Py_LT:
4995
case Py_LE:
4996
case Py_GT:
4997
case Py_GE:
4998
Py_RETURN_NOTIMPLEMENTED;
4999
break;
5000
default:
5001
PyErr_BadArgument();
5002
return NULL;
5003
}
5004
}
5005
5006
static int
5007
PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
5008
{
5009
Py_VISIT(self->ctx);
5010
Py_VISIT(Py_TYPE(self));
5011
return 0;
5012
}
5013
5014
static int
5015
PySSLSession_clear(PySSLSession *self)
5016
{
5017
Py_CLEAR(self->ctx);
5018
return 0;
5019
}
5020
5021
5022
static PyObject *
5023
PySSLSession_get_time(PySSLSession *self, void *closure) {
5024
return PyLong_FromLong(SSL_SESSION_get_time(self->session));
5025
}
5026
5027
PyDoc_STRVAR(PySSLSession_get_time_doc,
5028
"Session creation time (seconds since epoch).");
5029
5030
5031
static PyObject *
5032
PySSLSession_get_timeout(PySSLSession *self, void *closure) {
5033
return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
5034
}
5035
5036
PyDoc_STRVAR(PySSLSession_get_timeout_doc,
5037
"Session timeout (delta in seconds).");
5038
5039
5040
static PyObject *
5041
PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
5042
unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
5043
return PyLong_FromUnsignedLong(hint);
5044
}
5045
5046
PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
5047
"Ticket life time hint.");
5048
5049
5050
static PyObject *
5051
PySSLSession_get_session_id(PySSLSession *self, void *closure) {
5052
const unsigned char *id;
5053
unsigned int len;
5054
id = SSL_SESSION_get_id(self->session, &len);
5055
return PyBytes_FromStringAndSize((const char *)id, len);
5056
}
5057
5058
PyDoc_STRVAR(PySSLSession_get_session_id_doc,
5059
"Session id");
5060
5061
5062
static PyObject *
5063
PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
5064
if (SSL_SESSION_has_ticket(self->session)) {
5065
Py_RETURN_TRUE;
5066
} else {
5067
Py_RETURN_FALSE;
5068
}
5069
}
5070
5071
PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
5072
"Does the session contain a ticket?");
5073
5074
5075
static PyGetSetDef PySSLSession_getsetlist[] = {
5076
{"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5077
PySSLSession_get_has_ticket_doc},
5078
{"id", (getter) PySSLSession_get_session_id, NULL,
5079
PySSLSession_get_session_id_doc},
5080
{"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5081
NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5082
{"time", (getter) PySSLSession_get_time, NULL,
5083
PySSLSession_get_time_doc},
5084
{"timeout", (getter) PySSLSession_get_timeout, NULL,
5085
PySSLSession_get_timeout_doc},
5086
{NULL}, /* sentinel */
5087
};
5088
5089
static PyType_Slot PySSLSession_slots[] = {
5090
{Py_tp_getset,PySSLSession_getsetlist},
5091
{Py_tp_richcompare, PySSLSession_richcompare},
5092
{Py_tp_dealloc, PySSLSession_dealloc},
5093
{Py_tp_traverse, PySSLSession_traverse},
5094
{Py_tp_clear, PySSLSession_clear},
5095
{0, 0},
5096
};
5097
5098
static PyType_Spec PySSLSession_spec = {
5099
.name = "_ssl.SSLSession",
5100
.basicsize = sizeof(PySSLSession),
5101
.flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5102
Py_TPFLAGS_IMMUTABLETYPE |
5103
Py_TPFLAGS_DISALLOW_INSTANTIATION),
5104
.slots = PySSLSession_slots,
5105
};
5106
5107
5108
/* helper routines for seeding the SSL PRNG */
5109
/*[clinic input]
5110
_ssl.RAND_add
5111
string as view: Py_buffer(accept={str, buffer})
5112
entropy: double
5113
/
5114
5115
Mix string into the OpenSSL PRNG state.
5116
5117
entropy (a float) is a lower bound on the entropy contained in
5118
string. See RFC 4086.
5119
[clinic start generated code]*/
5120
5121
static PyObject *
5122
_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
5123
/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
5124
{
5125
const char *buf;
5126
Py_ssize_t len, written;
5127
5128
buf = (const char *)view->buf;
5129
len = view->len;
5130
do {
5131
written = Py_MIN(len, INT_MAX);
5132
RAND_add(buf, (int)written, entropy);
5133
buf += written;
5134
len -= written;
5135
} while (len);
5136
Py_RETURN_NONE;
5137
}
5138
5139
static PyObject *
5140
PySSL_RAND(PyObject *module, int len, int pseudo)
5141
{
5142
int ok;
5143
PyObject *bytes;
5144
unsigned long err;
5145
const char *errstr;
5146
PyObject *v;
5147
5148
if (len < 0) {
5149
PyErr_SetString(PyExc_ValueError, "num must be positive");
5150
return NULL;
5151
}
5152
5153
bytes = PyBytes_FromStringAndSize(NULL, len);
5154
if (bytes == NULL)
5155
return NULL;
5156
if (pseudo) {
5157
ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5158
if (ok == 0 || ok == 1)
5159
return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5160
}
5161
else {
5162
ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5163
if (ok == 1)
5164
return bytes;
5165
}
5166
Py_DECREF(bytes);
5167
5168
err = ERR_get_error();
5169
errstr = ERR_reason_error_string(err);
5170
v = Py_BuildValue("(ks)", err, errstr);
5171
if (v != NULL) {
5172
PyErr_SetObject(get_ssl_state(module)->PySSLErrorObject, v);
5173
Py_DECREF(v);
5174
}
5175
return NULL;
5176
}
5177
5178
/*[clinic input]
5179
_ssl.RAND_bytes
5180
n: int
5181
/
5182
5183
Generate n cryptographically strong pseudo-random bytes.
5184
[clinic start generated code]*/
5185
5186
static PyObject *
5187
_ssl_RAND_bytes_impl(PyObject *module, int n)
5188
/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
5189
{
5190
return PySSL_RAND(module, n, 0);
5191
}
5192
5193
5194
/*[clinic input]
5195
_ssl.RAND_status
5196
5197
Returns True if the OpenSSL PRNG has been seeded with enough data and False if not.
5198
5199
It is necessary to seed the PRNG with RAND_add() on some platforms before
5200
using the ssl() function.
5201
[clinic start generated code]*/
5202
5203
static PyObject *
5204
_ssl_RAND_status_impl(PyObject *module)
5205
/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=d5ae5aea52f36e01]*/
5206
{
5207
return PyBool_FromLong(RAND_status());
5208
}
5209
5210
/*[clinic input]
5211
_ssl.get_default_verify_paths
5212
5213
Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5214
5215
The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5216
[clinic start generated code]*/
5217
5218
static PyObject *
5219
_ssl_get_default_verify_paths_impl(PyObject *module)
5220
/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
5221
{
5222
PyObject *ofile_env = NULL;
5223
PyObject *ofile = NULL;
5224
PyObject *odir_env = NULL;
5225
PyObject *odir = NULL;
5226
5227
#define CONVERT(info, target) { \
5228
const char *tmp = (info); \
5229
target = NULL; \
5230
if (!tmp) { target = Py_NewRef(Py_None); } \
5231
else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5232
target = PyBytes_FromString(tmp); } \
5233
if (!target) goto error; \
5234
}
5235
5236
CONVERT(X509_get_default_cert_file_env(), ofile_env);
5237
CONVERT(X509_get_default_cert_file(), ofile);
5238
CONVERT(X509_get_default_cert_dir_env(), odir_env);
5239
CONVERT(X509_get_default_cert_dir(), odir);
5240
#undef CONVERT
5241
5242
return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
5243
5244
error:
5245
Py_XDECREF(ofile_env);
5246
Py_XDECREF(ofile);
5247
Py_XDECREF(odir_env);
5248
Py_XDECREF(odir);
5249
return NULL;
5250
}
5251
5252
static PyObject*
5253
asn1obj2py(_sslmodulestate *state, ASN1_OBJECT *obj)
5254
{
5255
int nid;
5256
const char *ln, *sn;
5257
5258
nid = OBJ_obj2nid(obj);
5259
if (nid == NID_undef) {
5260
PyErr_Format(PyExc_ValueError, "Unknown object");
5261
return NULL;
5262
}
5263
sn = OBJ_nid2sn(nid);
5264
ln = OBJ_nid2ln(nid);
5265
return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(state, obj, 1));
5266
}
5267
5268
/*[clinic input]
5269
_ssl.txt2obj
5270
txt: str
5271
name: bool = False
5272
5273
Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5274
5275
By default objects are looked up by OID. With name=True short and
5276
long name are also matched.
5277
[clinic start generated code]*/
5278
5279
static PyObject *
5280
_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5281
/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
5282
{
5283
PyObject *result = NULL;
5284
ASN1_OBJECT *obj;
5285
5286
obj = OBJ_txt2obj(txt, name ? 0 : 1);
5287
if (obj == NULL) {
5288
PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
5289
return NULL;
5290
}
5291
result = asn1obj2py(get_ssl_state(module), obj);
5292
ASN1_OBJECT_free(obj);
5293
return result;
5294
}
5295
5296
/*[clinic input]
5297
_ssl.nid2obj
5298
nid: int
5299
/
5300
5301
Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5302
[clinic start generated code]*/
5303
5304
static PyObject *
5305
_ssl_nid2obj_impl(PyObject *module, int nid)
5306
/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
5307
{
5308
PyObject *result = NULL;
5309
ASN1_OBJECT *obj;
5310
5311
if (nid < NID_undef) {
5312
PyErr_SetString(PyExc_ValueError, "NID must be positive.");
5313
return NULL;
5314
}
5315
obj = OBJ_nid2obj(nid);
5316
if (obj == NULL) {
5317
PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
5318
return NULL;
5319
}
5320
result = asn1obj2py(get_ssl_state(module), obj);
5321
ASN1_OBJECT_free(obj);
5322
return result;
5323
}
5324
5325
#ifdef _MSC_VER
5326
5327
static PyObject*
5328
certEncodingType(DWORD encodingType)
5329
{
5330
static PyObject *x509_asn = NULL;
5331
static PyObject *pkcs_7_asn = NULL;
5332
5333
if (x509_asn == NULL) {
5334
x509_asn = PyUnicode_InternFromString("x509_asn");
5335
if (x509_asn == NULL)
5336
return NULL;
5337
}
5338
if (pkcs_7_asn == NULL) {
5339
pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5340
if (pkcs_7_asn == NULL)
5341
return NULL;
5342
}
5343
switch(encodingType) {
5344
case X509_ASN_ENCODING:
5345
return Py_NewRef(x509_asn);
5346
case PKCS_7_ASN_ENCODING:
5347
return Py_NewRef(pkcs_7_asn);
5348
default:
5349
return PyLong_FromLong(encodingType);
5350
}
5351
}
5352
5353
static PyObject*
5354
parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5355
{
5356
CERT_ENHKEY_USAGE *usage;
5357
DWORD size, error, i;
5358
PyObject *retval;
5359
5360
if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5361
error = GetLastError();
5362
if (error == CRYPT_E_NOT_FOUND) {
5363
Py_RETURN_TRUE;
5364
}
5365
return PyErr_SetFromWindowsErr(error);
5366
}
5367
5368
usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5369
if (usage == NULL) {
5370
return PyErr_NoMemory();
5371
}
5372
5373
/* Now get the actual enhanced usage property */
5374
if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5375
PyMem_Free(usage);
5376
error = GetLastError();
5377
if (error == CRYPT_E_NOT_FOUND) {
5378
Py_RETURN_TRUE;
5379
}
5380
return PyErr_SetFromWindowsErr(error);
5381
}
5382
retval = PyFrozenSet_New(NULL);
5383
if (retval == NULL) {
5384
goto error;
5385
}
5386
for (i = 0; i < usage->cUsageIdentifier; ++i) {
5387
if (usage->rgpszUsageIdentifier[i]) {
5388
PyObject *oid;
5389
int err;
5390
oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5391
if (oid == NULL) {
5392
Py_CLEAR(retval);
5393
goto error;
5394
}
5395
err = PySet_Add(retval, oid);
5396
Py_DECREF(oid);
5397
if (err == -1) {
5398
Py_CLEAR(retval);
5399
goto error;
5400
}
5401
}
5402
}
5403
error:
5404
PyMem_Free(usage);
5405
return retval;
5406
}
5407
5408
static HCERTSTORE
5409
ssl_collect_certificates(const char *store_name)
5410
{
5411
/* this function collects the system certificate stores listed in
5412
* system_stores into a collection certificate store for being
5413
* enumerated. The store must be readable to be added to the
5414
* store collection.
5415
*/
5416
5417
HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5418
static DWORD system_stores[] = {
5419
CERT_SYSTEM_STORE_LOCAL_MACHINE,
5420
CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5421
CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5422
CERT_SYSTEM_STORE_CURRENT_USER,
5423
CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5424
CERT_SYSTEM_STORE_SERVICES,
5425
CERT_SYSTEM_STORE_USERS};
5426
size_t i, storesAdded;
5427
BOOL result;
5428
5429
hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5430
(HCRYPTPROV)NULL, 0, NULL);
5431
if (!hCollectionStore) {
5432
return NULL;
5433
}
5434
storesAdded = 0;
5435
for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5436
hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5437
(HCRYPTPROV)NULL,
5438
CERT_STORE_READONLY_FLAG |
5439
system_stores[i], store_name);
5440
if (hSystemStore) {
5441
result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5442
CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5443
if (result) {
5444
++storesAdded;
5445
}
5446
CertCloseStore(hSystemStore, 0); /* flag must be 0 */
5447
}
5448
}
5449
if (storesAdded == 0) {
5450
CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5451
return NULL;
5452
}
5453
5454
return hCollectionStore;
5455
}
5456
5457
/*[clinic input]
5458
_ssl.enum_certificates
5459
store_name: str
5460
5461
Retrieve certificates from Windows' cert store.
5462
5463
store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5464
more cert storages, too. The function returns a list of (bytes,
5465
encoding_type, trust) tuples. The encoding_type flag can be interpreted
5466
with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5467
a set of OIDs or the boolean True.
5468
[clinic start generated code]*/
5469
5470
static PyObject *
5471
_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5472
/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
5473
{
5474
HCERTSTORE hCollectionStore = NULL;
5475
PCCERT_CONTEXT pCertCtx = NULL;
5476
PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
5477
PyObject *result = NULL;
5478
5479
result = PySet_New(NULL);
5480
if (result == NULL) {
5481
return NULL;
5482
}
5483
hCollectionStore = ssl_collect_certificates(store_name);
5484
if (hCollectionStore == NULL) {
5485
Py_DECREF(result);
5486
return PyErr_SetFromWindowsErr(GetLastError());
5487
}
5488
5489
while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
5490
cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5491
pCertCtx->cbCertEncoded);
5492
if (!cert) {
5493
Py_CLEAR(result);
5494
break;
5495
}
5496
if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5497
Py_CLEAR(result);
5498
break;
5499
}
5500
keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5501
if (keyusage == Py_True) {
5502
Py_DECREF(keyusage);
5503
keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
5504
}
5505
if (keyusage == NULL) {
5506
Py_CLEAR(result);
5507
break;
5508
}
5509
if ((tup = PyTuple_New(3)) == NULL) {
5510
Py_CLEAR(result);
5511
break;
5512
}
5513
PyTuple_SET_ITEM(tup, 0, cert);
5514
cert = NULL;
5515
PyTuple_SET_ITEM(tup, 1, enc);
5516
enc = NULL;
5517
PyTuple_SET_ITEM(tup, 2, keyusage);
5518
keyusage = NULL;
5519
if (PySet_Add(result, tup) == -1) {
5520
Py_CLEAR(result);
5521
Py_CLEAR(tup);
5522
break;
5523
}
5524
Py_CLEAR(tup);
5525
}
5526
if (pCertCtx) {
5527
/* loop ended with an error, need to clean up context manually */
5528
CertFreeCertificateContext(pCertCtx);
5529
}
5530
5531
/* In error cases cert, enc and tup may not be NULL */
5532
Py_XDECREF(cert);
5533
Py_XDECREF(enc);
5534
Py_XDECREF(keyusage);
5535
Py_XDECREF(tup);
5536
5537
/* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5538
associated with the store, in this case our collection store and the
5539
associated system stores. */
5540
if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
5541
/* This error case might shadow another exception.*/
5542
Py_XDECREF(result);
5543
return PyErr_SetFromWindowsErr(GetLastError());
5544
}
5545
5546
/* convert set to list */
5547
if (result == NULL) {
5548
return NULL;
5549
} else {
5550
PyObject *lst = PySequence_List(result);
5551
Py_DECREF(result);
5552
return lst;
5553
}
5554
}
5555
5556
/*[clinic input]
5557
_ssl.enum_crls
5558
store_name: str
5559
5560
Retrieve CRLs from Windows' cert store.
5561
5562
store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5563
more cert storages, too. The function returns a list of (bytes,
5564
encoding_type) tuples. The encoding_type flag can be interpreted with
5565
X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5566
[clinic start generated code]*/
5567
5568
static PyObject *
5569
_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5570
/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
5571
{
5572
HCERTSTORE hCollectionStore = NULL;
5573
PCCRL_CONTEXT pCrlCtx = NULL;
5574
PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5575
PyObject *result = NULL;
5576
5577
result = PySet_New(NULL);
5578
if (result == NULL) {
5579
return NULL;
5580
}
5581
hCollectionStore = ssl_collect_certificates(store_name);
5582
if (hCollectionStore == NULL) {
5583
Py_DECREF(result);
5584
return PyErr_SetFromWindowsErr(GetLastError());
5585
}
5586
5587
while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
5588
crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5589
pCrlCtx->cbCrlEncoded);
5590
if (!crl) {
5591
Py_CLEAR(result);
5592
break;
5593
}
5594
if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5595
Py_CLEAR(result);
5596
break;
5597
}
5598
if ((tup = PyTuple_New(2)) == NULL) {
5599
Py_CLEAR(result);
5600
break;
5601
}
5602
PyTuple_SET_ITEM(tup, 0, crl);
5603
crl = NULL;
5604
PyTuple_SET_ITEM(tup, 1, enc);
5605
enc = NULL;
5606
5607
if (PySet_Add(result, tup) == -1) {
5608
Py_CLEAR(result);
5609
Py_CLEAR(tup);
5610
break;
5611
}
5612
Py_CLEAR(tup);
5613
}
5614
if (pCrlCtx) {
5615
/* loop ended with an error, need to clean up context manually */
5616
CertFreeCRLContext(pCrlCtx);
5617
}
5618
5619
/* In error cases cert, enc and tup may not be NULL */
5620
Py_XDECREF(crl);
5621
Py_XDECREF(enc);
5622
Py_XDECREF(tup);
5623
5624
/* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5625
associated with the store, in this case our collection store and the
5626
associated system stores. */
5627
if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
5628
/* This error case might shadow another exception.*/
5629
Py_XDECREF(result);
5630
return PyErr_SetFromWindowsErr(GetLastError());
5631
}
5632
/* convert set to list */
5633
if (result == NULL) {
5634
return NULL;
5635
} else {
5636
PyObject *lst = PySequence_List(result);
5637
Py_DECREF(result);
5638
return lst;
5639
}
5640
}
5641
5642
#endif /* _MSC_VER */
5643
5644
/* List of functions exported by this module. */
5645
static PyMethodDef PySSL_methods[] = {
5646
_SSL__TEST_DECODE_CERT_METHODDEF
5647
_SSL_RAND_ADD_METHODDEF
5648
_SSL_RAND_BYTES_METHODDEF
5649
_SSL_RAND_STATUS_METHODDEF
5650
_SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5651
_SSL_ENUM_CERTIFICATES_METHODDEF
5652
_SSL_ENUM_CRLS_METHODDEF
5653
_SSL_TXT2OBJ_METHODDEF
5654
_SSL_NID2OBJ_METHODDEF
5655
{NULL, NULL} /* Sentinel */
5656
};
5657
5658
5659
PyDoc_STRVAR(module_doc,
5660
"Implementation module for SSL socket operations. See the socket module\n\
5661
for documentation.");
5662
5663
static int
5664
sslmodule_init_exceptions(PyObject *module)
5665
{
5666
_sslmodulestate *state = get_ssl_state(module);
5667
PyObject *bases = NULL;
5668
5669
#define add_exception(exc, name, doc, base) \
5670
do { \
5671
(exc) = PyErr_NewExceptionWithDoc("ssl." name, (doc), (base), NULL); \
5672
if ((state) == NULL) goto error; \
5673
if (PyModule_AddObjectRef(module, name, exc) < 0) goto error; \
5674
} while(0)
5675
5676
state->PySSLErrorObject = PyType_FromSpecWithBases(
5677
&sslerror_type_spec, PyExc_OSError);
5678
if (state->PySSLErrorObject == NULL) {
5679
goto error;
5680
}
5681
if (PyModule_AddObjectRef(module, "SSLError", state->PySSLErrorObject) < 0) {
5682
goto error;
5683
}
5684
5685
/* ssl.CertificateError used to be a subclass of ValueError */
5686
bases = PyTuple_Pack(2, state->PySSLErrorObject, PyExc_ValueError);
5687
if (bases == NULL) {
5688
goto error;
5689
}
5690
add_exception(
5691
state->PySSLCertVerificationErrorObject,
5692
"SSLCertVerificationError",
5693
SSLCertVerificationError_doc,
5694
bases
5695
);
5696
Py_CLEAR(bases);
5697
5698
add_exception(
5699
state->PySSLZeroReturnErrorObject,
5700
"SSLZeroReturnError",
5701
SSLZeroReturnError_doc,
5702
state->PySSLErrorObject
5703
);
5704
5705
add_exception(
5706
state->PySSLWantWriteErrorObject,
5707
"SSLWantWriteError",
5708
SSLWantWriteError_doc,
5709
state->PySSLErrorObject
5710
);
5711
5712
add_exception(
5713
state->PySSLWantReadErrorObject,
5714
"SSLWantReadError",
5715
SSLWantReadError_doc,
5716
state->PySSLErrorObject
5717
);
5718
5719
add_exception(
5720
state->PySSLSyscallErrorObject,
5721
"SSLSyscallError",
5722
SSLSyscallError_doc,
5723
state->PySSLErrorObject
5724
);
5725
5726
add_exception(
5727
state->PySSLEOFErrorObject,
5728
"SSLEOFError",
5729
SSLEOFError_doc,
5730
state->PySSLErrorObject
5731
);
5732
#undef add_exception
5733
5734
return 0;
5735
error:
5736
Py_XDECREF(bases);
5737
return -1;
5738
}
5739
5740
static int
5741
sslmodule_init_socketapi(PyObject *module)
5742
{
5743
_sslmodulestate *state = get_ssl_state(module);
5744
PySocketModule_APIObject *sockmod = PySocketModule_ImportModuleAndAPI();
5745
5746
if ((sockmod == NULL) || (sockmod->Sock_Type == NULL)) {
5747
return -1;
5748
}
5749
state->Sock_Type = (PyTypeObject*)Py_NewRef(sockmod->Sock_Type);
5750
return 0;
5751
}
5752
5753
static int
5754
sslmodule_init_constants(PyObject *m)
5755
{
5756
5757
PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5758
PY_SSL_DEFAULT_CIPHER_STRING);
5759
5760
PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5761
PY_SSL_ERROR_ZERO_RETURN);
5762
PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5763
PY_SSL_ERROR_WANT_READ);
5764
PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5765
PY_SSL_ERROR_WANT_WRITE);
5766
PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5767
PY_SSL_ERROR_WANT_X509_LOOKUP);
5768
PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5769
PY_SSL_ERROR_SYSCALL);
5770
PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5771
PY_SSL_ERROR_SSL);
5772
PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5773
PY_SSL_ERROR_WANT_CONNECT);
5774
/* non ssl.h errorcodes */
5775
PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5776
PY_SSL_ERROR_EOF);
5777
PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5778
PY_SSL_ERROR_INVALID_ERROR_CODE);
5779
/* cert requirements */
5780
PyModule_AddIntConstant(m, "CERT_NONE",
5781
PY_SSL_CERT_NONE);
5782
PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5783
PY_SSL_CERT_OPTIONAL);
5784
PyModule_AddIntConstant(m, "CERT_REQUIRED",
5785
PY_SSL_CERT_REQUIRED);
5786
/* CRL verification for verification_flags */
5787
PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5788
0);
5789
PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5790
X509_V_FLAG_CRL_CHECK);
5791
PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5792
X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5793
PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5794
X509_V_FLAG_X509_STRICT);
5795
PyModule_AddIntConstant(m, "VERIFY_ALLOW_PROXY_CERTS",
5796
X509_V_FLAG_ALLOW_PROXY_CERTS);
5797
PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5798
X509_V_FLAG_TRUSTED_FIRST);
5799
5800
#ifdef X509_V_FLAG_PARTIAL_CHAIN
5801
PyModule_AddIntConstant(m, "VERIFY_X509_PARTIAL_CHAIN",
5802
X509_V_FLAG_PARTIAL_CHAIN);
5803
#endif
5804
5805
/* Alert Descriptions from ssl.h */
5806
/* note RESERVED constants no longer intended for use have been removed */
5807
/* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5808
5809
#define ADD_AD_CONSTANT(s) \
5810
PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5811
SSL_AD_##s)
5812
5813
ADD_AD_CONSTANT(CLOSE_NOTIFY);
5814
ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5815
ADD_AD_CONSTANT(BAD_RECORD_MAC);
5816
ADD_AD_CONSTANT(RECORD_OVERFLOW);
5817
ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5818
ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5819
ADD_AD_CONSTANT(BAD_CERTIFICATE);
5820
ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5821
ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5822
ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5823
ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5824
ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5825
ADD_AD_CONSTANT(UNKNOWN_CA);
5826
ADD_AD_CONSTANT(ACCESS_DENIED);
5827
ADD_AD_CONSTANT(DECODE_ERROR);
5828
ADD_AD_CONSTANT(DECRYPT_ERROR);
5829
ADD_AD_CONSTANT(PROTOCOL_VERSION);
5830
ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5831
ADD_AD_CONSTANT(INTERNAL_ERROR);
5832
ADD_AD_CONSTANT(USER_CANCELLED);
5833
ADD_AD_CONSTANT(NO_RENEGOTIATION);
5834
/* Not all constants are in old OpenSSL versions */
5835
#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5836
ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5837
#endif
5838
#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5839
ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5840
#endif
5841
#ifdef SSL_AD_UNRECOGNIZED_NAME
5842
ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5843
#endif
5844
#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5845
ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5846
#endif
5847
#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5848
ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5849
#endif
5850
#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5851
ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5852
#endif
5853
5854
#undef ADD_AD_CONSTANT
5855
5856
/* protocol versions */
5857
#ifndef OPENSSL_NO_SSL3
5858
PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5859
PY_SSL_VERSION_SSL3);
5860
#endif
5861
PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
5862
PY_SSL_VERSION_TLS);
5863
PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5864
PY_SSL_VERSION_TLS);
5865
PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5866
PY_SSL_VERSION_TLS_CLIENT);
5867
PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5868
PY_SSL_VERSION_TLS_SERVER);
5869
PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5870
PY_SSL_VERSION_TLS1);
5871
PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5872
PY_SSL_VERSION_TLS1_1);
5873
PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5874
PY_SSL_VERSION_TLS1_2);
5875
5876
/* protocol options */
5877
PyModule_AddIntConstant(m, "OP_ALL",
5878
SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
5879
PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5880
PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5881
PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
5882
PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5883
PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5884
#ifdef SSL_OP_NO_TLSv1_3
5885
PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5886
#else
5887
PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5888
#endif
5889
PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5890
SSL_OP_CIPHER_SERVER_PREFERENCE);
5891
PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
5892
PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
5893
PyModule_AddIntConstant(m, "OP_LEGACY_SERVER_CONNECT",
5894
SSL_OP_LEGACY_SERVER_CONNECT);
5895
#ifdef SSL_OP_SINGLE_ECDH_USE
5896
PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
5897
#endif
5898
#ifdef SSL_OP_NO_COMPRESSION
5899
PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5900
SSL_OP_NO_COMPRESSION);
5901
#endif
5902
#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5903
PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5904
SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5905
#endif
5906
#ifdef SSL_OP_NO_RENEGOTIATION
5907
PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
5908
SSL_OP_NO_RENEGOTIATION);
5909
#endif
5910
#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
5911
PyModule_AddIntConstant(m, "OP_IGNORE_UNEXPECTED_EOF",
5912
SSL_OP_IGNORE_UNEXPECTED_EOF);
5913
#endif
5914
#ifdef SSL_OP_ENABLE_KTLS
5915
PyModule_AddIntConstant(m, "OP_ENABLE_KTLS", SSL_OP_ENABLE_KTLS);
5916
#endif
5917
5918
#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5919
PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5920
X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5921
#endif
5922
#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5923
PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5924
X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5925
#endif
5926
#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5927
PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5928
X509_CHECK_FLAG_NO_WILDCARDS);
5929
#endif
5930
#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5931
PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5932
X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5933
#endif
5934
#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5935
PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5936
X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5937
#endif
5938
#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5939
PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5940
X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5941
#endif
5942
5943
/* file types */
5944
PyModule_AddIntConstant(m, "ENCODING_PEM", PY_SSL_ENCODING_PEM);
5945
PyModule_AddIntConstant(m, "ENCODING_DER", PY_SSL_ENCODING_DER);
5946
5947
/* protocol versions */
5948
PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5949
PY_PROTO_MINIMUM_SUPPORTED);
5950
PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5951
PY_PROTO_MAXIMUM_SUPPORTED);
5952
PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5953
PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
5954
PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
5955
PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
5956
PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
5957
5958
#define addbool(m, key, value) \
5959
do { \
5960
PyObject *bool_obj = (value) ? Py_True : Py_False; \
5961
PyModule_AddObject((m), (key), Py_NewRef(bool_obj)); \
5962
} while (0)
5963
5964
addbool(m, "HAS_SNI", 1);
5965
addbool(m, "HAS_TLS_UNIQUE", 1);
5966
addbool(m, "HAS_ECDH", 1);
5967
addbool(m, "HAS_NPN", 0);
5968
addbool(m, "HAS_ALPN", 1);
5969
5970
addbool(m, "HAS_SSLv2", 0);
5971
5972
#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
5973
addbool(m, "HAS_SSLv3", 1);
5974
#else
5975
addbool(m, "HAS_SSLv3", 0);
5976
#endif
5977
5978
#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
5979
addbool(m, "HAS_TLSv1", 1);
5980
#else
5981
addbool(m, "HAS_TLSv1", 0);
5982
#endif
5983
5984
#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
5985
addbool(m, "HAS_TLSv1_1", 1);
5986
#else
5987
addbool(m, "HAS_TLSv1_1", 0);
5988
#endif
5989
5990
#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
5991
addbool(m, "HAS_TLSv1_2", 1);
5992
#else
5993
addbool(m, "HAS_TLSv1_2", 0);
5994
#endif
5995
5996
#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
5997
addbool(m, "HAS_TLSv1_3", 1);
5998
#else
5999
addbool(m, "HAS_TLSv1_3", 0);
6000
#endif
6001
6002
return 0;
6003
}
6004
6005
static int
6006
sslmodule_init_errorcodes(PyObject *module)
6007
{
6008
_sslmodulestate *state = get_ssl_state(module);
6009
6010
struct py_ssl_error_code *errcode;
6011
struct py_ssl_library_code *libcode;
6012
6013
/* Mappings for error codes */
6014
state->err_codes_to_names = PyDict_New();
6015
if (state->err_codes_to_names == NULL)
6016
return -1;
6017
state->lib_codes_to_names = PyDict_New();
6018
if (state->lib_codes_to_names == NULL)
6019
return -1;
6020
6021
errcode = error_codes;
6022
while (errcode->mnemonic != NULL) {
6023
PyObject *mnemo = PyUnicode_FromString(errcode->mnemonic);
6024
if (mnemo == NULL) {
6025
return -1;
6026
}
6027
PyObject *key = Py_BuildValue("ii", errcode->library, errcode->reason);
6028
if (key == NULL) {
6029
Py_DECREF(mnemo);
6030
return -1;
6031
}
6032
int rc = PyDict_SetItem(state->err_codes_to_names, key, mnemo);
6033
Py_DECREF(key);
6034
Py_DECREF(mnemo);
6035
if (rc < 0) {
6036
return -1;
6037
}
6038
errcode++;
6039
}
6040
6041
libcode = library_codes;
6042
while (libcode->library != NULL) {
6043
PyObject *mnemo, *key;
6044
key = PyLong_FromLong(libcode->code);
6045
mnemo = PyUnicode_FromString(libcode->library);
6046
if (key == NULL || mnemo == NULL)
6047
return -1;
6048
if (PyDict_SetItem(state->lib_codes_to_names, key, mnemo))
6049
return -1;
6050
Py_DECREF(key);
6051
Py_DECREF(mnemo);
6052
libcode++;
6053
}
6054
6055
return 0;
6056
}
6057
6058
static void
6059
parse_openssl_version(unsigned long libver,
6060
unsigned int *major, unsigned int *minor,
6061
unsigned int *fix, unsigned int *patch,
6062
unsigned int *status)
6063
{
6064
*status = libver & 0xF;
6065
libver >>= 4;
6066
*patch = libver & 0xFF;
6067
libver >>= 8;
6068
*fix = libver & 0xFF;
6069
libver >>= 8;
6070
*minor = libver & 0xFF;
6071
libver >>= 8;
6072
*major = libver & 0xFF;
6073
}
6074
6075
static int
6076
sslmodule_init_versioninfo(PyObject *m)
6077
{
6078
PyObject *r;
6079
unsigned long libver;
6080
unsigned int major, minor, fix, patch, status;
6081
6082
/* OpenSSL version */
6083
/* SSLeay() gives us the version of the library linked against,
6084
which could be different from the headers version.
6085
*/
6086
libver = OpenSSL_version_num();
6087
r = PyLong_FromUnsignedLong(libver);
6088
if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6089
return -1;
6090
6091
parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6092
r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6093
if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6094
return -1;
6095
6096
r = PyUnicode_FromString(OpenSSL_version(OPENSSL_VERSION));
6097
if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6098
return -1;
6099
6100
libver = OPENSSL_VERSION_NUMBER;
6101
parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6102
r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6103
if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6104
return -1;
6105
6106
return 0;
6107
}
6108
6109
static int
6110
sslmodule_init_types(PyObject *module)
6111
{
6112
_sslmodulestate *state = get_ssl_state(module);
6113
6114
state->PySSLContext_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6115
module, &PySSLContext_spec, NULL
6116
);
6117
if (state->PySSLContext_Type == NULL)
6118
return -1;
6119
6120
state->PySSLSocket_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6121
module, &PySSLSocket_spec, NULL
6122
);
6123
if (state->PySSLSocket_Type == NULL)
6124
return -1;
6125
6126
state->PySSLMemoryBIO_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6127
module, &PySSLMemoryBIO_spec, NULL
6128
);
6129
if (state->PySSLMemoryBIO_Type == NULL)
6130
return -1;
6131
6132
state->PySSLSession_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6133
module, &PySSLSession_spec, NULL
6134
);
6135
if (state->PySSLSession_Type == NULL)
6136
return -1;
6137
6138
state->PySSLCertificate_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6139
module, &PySSLCertificate_spec, NULL
6140
);
6141
if (state->PySSLCertificate_Type == NULL)
6142
return -1;
6143
6144
if (PyModule_AddType(module, state->PySSLContext_Type))
6145
return -1;
6146
if (PyModule_AddType(module, state->PySSLSocket_Type))
6147
return -1;
6148
if (PyModule_AddType(module, state->PySSLMemoryBIO_Type))
6149
return -1;
6150
if (PyModule_AddType(module, state->PySSLSession_Type))
6151
return -1;
6152
if (PyModule_AddType(module, state->PySSLCertificate_Type))
6153
return -1;
6154
return 0;
6155
}
6156
6157
static int
6158
sslmodule_init_strings(PyObject *module)
6159
{
6160
_sslmodulestate *state = get_ssl_state(module);
6161
state->str_library = PyUnicode_InternFromString("library");
6162
if (state->str_library == NULL) {
6163
return -1;
6164
}
6165
state->str_reason = PyUnicode_InternFromString("reason");
6166
if (state->str_reason == NULL) {
6167
return -1;
6168
}
6169
state->str_verify_message = PyUnicode_InternFromString("verify_message");
6170
if (state->str_verify_message == NULL) {
6171
return -1;
6172
}
6173
state->str_verify_code = PyUnicode_InternFromString("verify_code");
6174
if (state->str_verify_code == NULL) {
6175
return -1;
6176
}
6177
return 0;
6178
}
6179
6180
static int
6181
sslmodule_init_lock(PyObject *module)
6182
{
6183
_sslmodulestate *state = get_ssl_state(module);
6184
state->keylog_lock = PyThread_allocate_lock();
6185
if (state->keylog_lock == NULL) {
6186
PyErr_NoMemory();
6187
return -1;
6188
}
6189
return 0;
6190
}
6191
6192
static PyModuleDef_Slot sslmodule_slots[] = {
6193
{Py_mod_exec, sslmodule_init_types},
6194
{Py_mod_exec, sslmodule_init_exceptions},
6195
{Py_mod_exec, sslmodule_init_socketapi},
6196
{Py_mod_exec, sslmodule_init_errorcodes},
6197
{Py_mod_exec, sslmodule_init_constants},
6198
{Py_mod_exec, sslmodule_init_versioninfo},
6199
{Py_mod_exec, sslmodule_init_strings},
6200
{Py_mod_exec, sslmodule_init_lock},
6201
{Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
6202
{0, NULL}
6203
};
6204
6205
static int
6206
sslmodule_traverse(PyObject *m, visitproc visit, void *arg)
6207
{
6208
_sslmodulestate *state = get_ssl_state(m);
6209
6210
Py_VISIT(state->PySSLContext_Type);
6211
Py_VISIT(state->PySSLSocket_Type);
6212
Py_VISIT(state->PySSLMemoryBIO_Type);
6213
Py_VISIT(state->PySSLSession_Type);
6214
Py_VISIT(state->PySSLCertificate_Type);
6215
Py_VISIT(state->PySSLErrorObject);
6216
Py_VISIT(state->PySSLCertVerificationErrorObject);
6217
Py_VISIT(state->PySSLZeroReturnErrorObject);
6218
Py_VISIT(state->PySSLWantReadErrorObject);
6219
Py_VISIT(state->PySSLWantWriteErrorObject);
6220
Py_VISIT(state->PySSLSyscallErrorObject);
6221
Py_VISIT(state->PySSLEOFErrorObject);
6222
Py_VISIT(state->err_codes_to_names);
6223
Py_VISIT(state->lib_codes_to_names);
6224
Py_VISIT(state->Sock_Type);
6225
6226
return 0;
6227
}
6228
6229
static int
6230
sslmodule_clear(PyObject *m)
6231
{
6232
_sslmodulestate *state = get_ssl_state(m);
6233
6234
Py_CLEAR(state->PySSLContext_Type);
6235
Py_CLEAR(state->PySSLSocket_Type);
6236
Py_CLEAR(state->PySSLMemoryBIO_Type);
6237
Py_CLEAR(state->PySSLSession_Type);
6238
Py_CLEAR(state->PySSLCertificate_Type);
6239
Py_CLEAR(state->PySSLErrorObject);
6240
Py_CLEAR(state->PySSLCertVerificationErrorObject);
6241
Py_CLEAR(state->PySSLZeroReturnErrorObject);
6242
Py_CLEAR(state->PySSLWantReadErrorObject);
6243
Py_CLEAR(state->PySSLWantWriteErrorObject);
6244
Py_CLEAR(state->PySSLSyscallErrorObject);
6245
Py_CLEAR(state->PySSLEOFErrorObject);
6246
Py_CLEAR(state->err_codes_to_names);
6247
Py_CLEAR(state->lib_codes_to_names);
6248
Py_CLEAR(state->Sock_Type);
6249
Py_CLEAR(state->str_library);
6250
Py_CLEAR(state->str_reason);
6251
Py_CLEAR(state->str_verify_code);
6252
Py_CLEAR(state->str_verify_message);
6253
return 0;
6254
}
6255
6256
static void
6257
sslmodule_free(void *m)
6258
{
6259
sslmodule_clear((PyObject *)m);
6260
_sslmodulestate *state = get_ssl_state(m);
6261
PyThread_free_lock(state->keylog_lock);
6262
}
6263
6264
static struct PyModuleDef _sslmodule_def = {
6265
PyModuleDef_HEAD_INIT,
6266
.m_name = "_ssl",
6267
.m_doc = module_doc,
6268
.m_size = sizeof(_sslmodulestate),
6269
.m_methods = PySSL_methods,
6270
.m_slots = sslmodule_slots,
6271
.m_traverse = sslmodule_traverse,
6272
.m_clear = sslmodule_clear,
6273
.m_free = sslmodule_free
6274
};
6275
6276
PyMODINIT_FUNC
6277
PyInit__ssl(void)
6278
{
6279
return PyModuleDef_Init(&_sslmodule_def);
6280
}
6281
6282