summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/library%2Fssl.html
blob: 0630730f663e858b5e40ba2b301dca683c9aa41b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
 <span id="ssl-tls-ssl-wrapper-for-socket-objects"></span><h1>ssl — TLS/SSL wrapper for socket objects</h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/ssl.py">Lib/ssl.py</a></p> <span class="target" id="index-0"></span> <p>This module provides access to Transport Layer Security (often known as “Secure Sockets Layer”) encryption and peer authentication facilities for network sockets, both client-side and server-side. This module uses the OpenSSL library. It is available on all modern Unix systems, Windows, macOS, and probably additional platforms, as long as OpenSSL is installed on that platform.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Some behavior may be platform dependent, since calls are made to the operating system socket APIs. The installed version of OpenSSL may also cause variations in behavior. For example, TLSv1.3 comes with OpenSSL version 1.1.1.</p> </div> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p>Don’t use this module without reading the <a class="reference internal" href="#ssl-security"><span class="std std-ref">Security considerations</span></a>. Doing so may lead to a false sense of security, as the default settings of the ssl module are not necessarily appropriate for your application.</p> </div> <div class="availability docutils container"> <p><a class="reference internal" href="https://docs.python.org/3.12/library/intro.html#availability"><span class="std std-ref">Availability</span></a>: not Emscripten, not WASI.</p> <p>This module does not work or is not available on WebAssembly platforms <code>wasm32-emscripten</code> and <code>wasm32-wasi</code>. See <a class="reference internal" href="https://docs.python.org/3.12/library/intro.html#wasm-availability"><span class="std std-ref">WebAssembly platforms</span></a> for more information.</p> </div> <p>This section documents the objects and functions in the <code>ssl</code> module; for more general information about TLS, SSL, and certificates, the reader is referred to the documents in the “See Also” section at the bottom.</p> <p>This module provides a class, <a class="reference internal" href="#ssl.SSLSocket" title="ssl.SSLSocket"><code>ssl.SSLSocket</code></a>, which is derived from the <a class="reference internal" href="socket#socket.socket" title="socket.socket"><code>socket.socket</code></a> type, and provides a socket-like wrapper that also encrypts and decrypts the data going over the socket with SSL. It supports additional methods such as <code>getpeercert()</code>, which retrieves the certificate of the other side of the connection, and <code>cipher()</code>, which retrieves the cipher being used for the secure connection.</p> <p>For more sophisticated applications, the <a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code>ssl.SSLContext</code></a> class helps manage settings and certificates, which can then be inherited by SSL sockets created through the <a class="reference internal" href="#ssl.SSLContext.wrap_socket" title="ssl.SSLContext.wrap_socket"><code>SSLContext.wrap_socket()</code></a> method.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5.3: </span>Updated to support linking with OpenSSL 1.1.0</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>OpenSSL 0.9.8, 1.0.0 and 1.0.1 are deprecated and no longer supported. In the future the ssl module will require at least OpenSSL 1.0.2 or 1.1.0.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span><span class="target" id="index-2"></span><a class="pep reference external" href="https://peps.python.org/pep-0644/"><strong>PEP 644</strong></a> has been implemented. The ssl module requires OpenSSL 1.1.1 or newer.</p> <p>Use of deprecated constants and functions result in deprecation warnings.</p> </div> <section id="functions-constants-and-exceptions"> <h2>Functions, Constants, and Exceptions</h2> <section id="socket-creation"> <h3>Socket creation</h3> <p>Instances of <a class="reference internal" href="#ssl.SSLSocket" title="ssl.SSLSocket"><code>SSLSocket</code></a> must be created using the <a class="reference internal" href="#ssl.SSLContext.wrap_socket" title="ssl.SSLContext.wrap_socket"><code>SSLContext.wrap_socket()</code></a> method. The helper function <a class="reference internal" href="#ssl.create_default_context" title="ssl.create_default_context"><code>create_default_context()</code></a> returns a new context with secure default settings.</p> <p>Client socket example with default context and IPv4/IPv6 dual stack:</p> <pre data-language="python">import socket
import ssl

hostname = 'www.python.org'
context = ssl.create_default_context()

with socket.create_connection((hostname, 443)) as sock:
    with context.wrap_socket(sock, server_hostname=hostname) as ssock:
        print(ssock.version())
</pre> <p>Client socket example with custom context and IPv4:</p> <pre data-language="python">hostname = 'www.python.org'
# PROTOCOL_TLS_CLIENT requires valid cert chain and hostname
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.load_verify_locations('path/to/cabundle.pem')

with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
    with context.wrap_socket(sock, server_hostname=hostname) as ssock:
        print(ssock.version())
</pre> <p>Server socket example listening on localhost IPv4:</p> <pre data-language="python">context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain('/path/to/certchain.pem', '/path/to/private.key')

with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
    sock.bind(('127.0.0.1', 8443))
    sock.listen(5)
    with context.wrap_socket(sock, server_side=True) as ssock:
        conn, addr = ssock.accept()
        ...
</pre> </section> <section id="context-creation"> <h3>Context creation</h3> <p>A convenience function helps create <a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code>SSLContext</code></a> objects for common purposes.</p> <dl class="py function"> <dt class="sig sig-object py" id="ssl.create_default_context">
<code>ssl.create_default_context(purpose=Purpose.SERVER_AUTH, cafile=None, capath=None, cadata=None)</code> </dt> <dd>
<p>Return a new <a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code>SSLContext</code></a> object with default settings for the given <em>purpose</em>. The settings are chosen by the <a class="reference internal" href="#module-ssl" title="ssl: TLS/SSL wrapper for socket objects"><code>ssl</code></a> module, and usually represent a higher security level than when calling the <a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code>SSLContext</code></a> constructor directly.</p> <p><em>cafile</em>, <em>capath</em>, <em>cadata</em> represent optional CA certificates to trust for certificate verification, as in <a class="reference internal" href="#ssl.SSLContext.load_verify_locations" title="ssl.SSLContext.load_verify_locations"><code>SSLContext.load_verify_locations()</code></a>. If all three are <a class="reference internal" href="constants#None" title="None"><code>None</code></a>, this function can choose to trust the system’s default CA certificates instead.</p> <p>The settings are: <a class="reference internal" href="#ssl.PROTOCOL_TLS_CLIENT" title="ssl.PROTOCOL_TLS_CLIENT"><code>PROTOCOL_TLS_CLIENT</code></a> or <a class="reference internal" href="#ssl.PROTOCOL_TLS_SERVER" title="ssl.PROTOCOL_TLS_SERVER"><code>PROTOCOL_TLS_SERVER</code></a>, <a class="reference internal" href="#ssl.OP_NO_SSLv2" title="ssl.OP_NO_SSLv2"><code>OP_NO_SSLv2</code></a>, and <a class="reference internal" href="#ssl.OP_NO_SSLv3" title="ssl.OP_NO_SSLv3"><code>OP_NO_SSLv3</code></a> with high encryption cipher suites without RC4 and without unauthenticated cipher suites. Passing <a class="reference internal" href="#ssl.Purpose.SERVER_AUTH" title="ssl.Purpose.SERVER_AUTH"><code>SERVER_AUTH</code></a> as <em>purpose</em> sets <a class="reference internal" href="#ssl.SSLContext.verify_mode" title="ssl.SSLContext.verify_mode"><code>verify_mode</code></a> to <a class="reference internal" href="#ssl.CERT_REQUIRED" title="ssl.CERT_REQUIRED"><code>CERT_REQUIRED</code></a> and either loads CA certificates (when at least one of <em>cafile</em>, <em>capath</em> or <em>cadata</em> is given) or uses <a class="reference internal" href="#ssl.SSLContext.load_default_certs" title="ssl.SSLContext.load_default_certs"><code>SSLContext.load_default_certs()</code></a> to load default CA certificates.</p> <p>When <a class="reference internal" href="#ssl.SSLContext.keylog_filename" title="ssl.SSLContext.keylog_filename"><code>keylog_filename</code></a> is supported and the environment variable <span class="target" id="index-3"></span><code>SSLKEYLOGFILE</code> is set, <a class="reference internal" href="#ssl.create_default_context" title="ssl.create_default_context"><code>create_default_context()</code></a> enables key logging.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The protocol, options, cipher and other settings may change to more restrictive values anytime without prior deprecation. The values represent a fair balance between compatibility and security.</p> <p>If your application needs specific settings, you should create a <a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code>SSLContext</code></a> and apply the settings yourself.</p> </div> <div class="admonition note"> <p class="admonition-title">Note</p> <p>If you find that when certain older clients or servers attempt to connect with a <a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code>SSLContext</code></a> created by this function that they get an error stating “Protocol or cipher suite mismatch”, it may be that they only support SSL3.0 which this function excludes using the <a class="reference internal" href="#ssl.OP_NO_SSLv3" title="ssl.OP_NO_SSLv3"><code>OP_NO_SSLv3</code></a>. SSL3.0 is widely considered to be <a class="reference external" href="https://en.wikipedia.org/wiki/POODLE">completely broken</a>. If you still wish to continue to use this function but still allow SSL 3.0 connections you can re-enable them using:</p> <pre data-language="python">ctx = ssl.create_default_context(Purpose.CLIENT_AUTH)
ctx.options &amp;= ~ssl.OP_NO_SSLv3
</pre> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4.4: </span>RC4 was dropped from the default cipher string.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>ChaCha20/Poly1305 was added to the default cipher string.</p> <p>3DES was dropped from the default cipher string.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>Support for key logging to <span class="target" id="index-4"></span><code>SSLKEYLOGFILE</code> was added.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>The context now uses <a class="reference internal" href="#ssl.PROTOCOL_TLS_CLIENT" title="ssl.PROTOCOL_TLS_CLIENT"><code>PROTOCOL_TLS_CLIENT</code></a> or <a class="reference internal" href="#ssl.PROTOCOL_TLS_SERVER" title="ssl.PROTOCOL_TLS_SERVER"><code>PROTOCOL_TLS_SERVER</code></a> protocol instead of generic <a class="reference internal" href="#ssl.PROTOCOL_TLS" title="ssl.PROTOCOL_TLS"><code>PROTOCOL_TLS</code></a>.</p> </div> </dd>
</dl> </section> <section id="exceptions"> <h3>Exceptions</h3> <dl class="py exception"> <dt class="sig sig-object py" id="ssl.SSLError">
<code>exception ssl.SSLError</code> </dt> <dd>
<p>Raised to signal an error from the underlying SSL implementation (currently provided by the OpenSSL library). This signifies some problem in the higher-level encryption and authentication layer that’s superimposed on the underlying network connection. This error is a subtype of <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a>. The error code and message of <a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code>SSLError</code></a> instances are provided by the OpenSSL library.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span><a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code>SSLError</code></a> used to be a subtype of <a class="reference internal" href="socket#socket.error" title="socket.error"><code>socket.error</code></a>.</p> </div> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLError.library">
<code>library</code> </dt> <dd>
<p>A string mnemonic designating the OpenSSL submodule in which the error occurred, such as <code>SSL</code>, <code>PEM</code> or <code>X509</code>. The range of possible values depends on the OpenSSL version.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLError.reason">
<code>reason</code> </dt> <dd>
<p>A string mnemonic designating the reason this error occurred, for example <code>CERTIFICATE_VERIFY_FAILED</code>. The range of possible values depends on the OpenSSL version.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd>
</dl> </dd>
</dl> <dl class="py exception"> <dt class="sig sig-object py" id="ssl.SSLZeroReturnError">
<code>exception ssl.SSLZeroReturnError</code> </dt> <dd>
<p>A subclass of <a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code>SSLError</code></a> raised when trying to read or write and the SSL connection has been closed cleanly. Note that this doesn’t mean that the underlying transport (read TCP) has been closed.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd>
</dl> <dl class="py exception"> <dt class="sig sig-object py" id="ssl.SSLWantReadError">
<code>exception ssl.SSLWantReadError</code> </dt> <dd>
<p>A subclass of <a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code>SSLError</code></a> raised by a <a class="reference internal" href="#ssl-nonblocking"><span class="std std-ref">non-blocking SSL socket</span></a> when trying to read or write data, but more data needs to be received on the underlying TCP transport before the request can be fulfilled.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd>
</dl> <dl class="py exception"> <dt class="sig sig-object py" id="ssl.SSLWantWriteError">
<code>exception ssl.SSLWantWriteError</code> </dt> <dd>
<p>A subclass of <a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code>SSLError</code></a> raised by a <a class="reference internal" href="#ssl-nonblocking"><span class="std std-ref">non-blocking SSL socket</span></a> when trying to read or write data, but more data needs to be sent on the underlying TCP transport before the request can be fulfilled.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd>
</dl> <dl class="py exception"> <dt class="sig sig-object py" id="ssl.SSLSyscallError">
<code>exception ssl.SSLSyscallError</code> </dt> <dd>
<p>A subclass of <a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code>SSLError</code></a> raised when a system error was encountered while trying to fulfill an operation on a SSL socket. Unfortunately, there is no easy way to inspect the original errno number.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd>
</dl> <dl class="py exception"> <dt class="sig sig-object py" id="ssl.SSLEOFError">
<code>exception ssl.SSLEOFError</code> </dt> <dd>
<p>A subclass of <a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code>SSLError</code></a> raised when the SSL connection has been terminated abruptly. Generally, you shouldn’t try to reuse the underlying transport when this error is encountered.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd>
</dl> <dl class="py exception"> <dt class="sig sig-object py" id="ssl.SSLCertVerificationError">
<code>exception ssl.SSLCertVerificationError</code> </dt> <dd>
<p>A subclass of <a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code>SSLError</code></a> raised when certificate validation has failed.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLCertVerificationError.verify_code">
<code>verify_code</code> </dt> <dd>
<p>A numeric error number that denotes the verification error.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLCertVerificationError.verify_message">
<code>verify_message</code> </dt> <dd>
<p>A human readable string of the verification error.</p> </dd>
</dl> </dd>
</dl> <dl class="py exception"> <dt class="sig sig-object py" id="ssl.CertificateError">
<code>exception ssl.CertificateError</code> </dt> <dd>
<p>An alias for <a class="reference internal" href="#ssl.SSLCertVerificationError" title="ssl.SSLCertVerificationError"><code>SSLCertVerificationError</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>The exception is now an alias for <a class="reference internal" href="#ssl.SSLCertVerificationError" title="ssl.SSLCertVerificationError"><code>SSLCertVerificationError</code></a>.</p> </div> </dd>
</dl> </section> <section id="random-generation"> <h3>Random generation</h3> <dl class="py function"> <dt class="sig sig-object py" id="ssl.RAND_bytes">
<code>ssl.RAND_bytes(num)</code> </dt> <dd>
<p>Return <em>num</em> cryptographically strong pseudo-random bytes. Raises an <a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code>SSLError</code></a> if the PRNG has not been seeded with enough data or if the operation is not supported by the current RAND method. <a class="reference internal" href="#ssl.RAND_status" title="ssl.RAND_status"><code>RAND_status()</code></a> can be used to check the status of the PRNG and <a class="reference internal" href="#ssl.RAND_add" title="ssl.RAND_add"><code>RAND_add()</code></a> can be used to seed the PRNG.</p> <p>For almost all applications <a class="reference internal" href="os#os.urandom" title="os.urandom"><code>os.urandom()</code></a> is preferable.</p> <p>Read the Wikipedia article, <a class="reference external" href="https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator">Cryptographically secure pseudorandom number generator (CSPRNG)</a>, to get the requirements of a cryptographically strong generator.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="ssl.RAND_status">
<code>ssl.RAND_status()</code> </dt> <dd>
<p>Return <code>True</code> if the SSL pseudo-random number generator has been seeded with ‘enough’ randomness, and <code>False</code> otherwise. You can use <code>ssl.RAND_egd()</code> and <a class="reference internal" href="#ssl.RAND_add" title="ssl.RAND_add"><code>ssl.RAND_add()</code></a> to increase the randomness of the pseudo-random number generator.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="ssl.RAND_add">
<code>ssl.RAND_add(bytes, entropy)</code> </dt> <dd>
<p>Mix the given <em>bytes</em> into the SSL pseudo-random number generator. The parameter <em>entropy</em> (a float) is a lower bound on the entropy contained in string (so you can always use <code>0.0</code>). See <span class="target" id="index-5"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc1750.html"><strong>RFC 1750</strong></a> for more information on sources of entropy.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>Writable <a class="reference internal" href="../glossary#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a> is now accepted.</p> </div> </dd>
</dl> </section> <section id="certificate-handling"> <h3>Certificate handling</h3> <dl class="py function"> <dt class="sig sig-object py" id="ssl.cert_time_to_seconds">
<code>ssl.cert_time_to_seconds(cert_time)</code> </dt> <dd>
<p>Return the time in seconds since the Epoch, given the <code>cert_time</code> string representing the “notBefore” or “notAfter” date from a certificate in <code>"%b %d %H:%M:%S %Y %Z"</code> strptime format (C locale).</p> <p>Here’s an example:</p> <pre data-language="pycon3">&gt;&gt;&gt; import ssl
&gt;&gt;&gt; timestamp = ssl.cert_time_to_seconds("Jan  5 09:34:43 2018 GMT")
&gt;&gt;&gt; timestamp  
1515144883
&gt;&gt;&gt; from datetime import datetime
&gt;&gt;&gt; print(datetime.utcfromtimestamp(timestamp))  
2018-01-05 09:34:43
</pre> <p>“notBefore” or “notAfter” dates must use GMT (<span class="target" id="index-6"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc5280.html"><strong>RFC 5280</strong></a>).</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>Interpret the input time as a time in UTC as specified by ‘GMT’ timezone in the input string. Local timezone was used previously. Return an integer (no fractions of a second in the input format)</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="ssl.get_server_certificate">
<code>ssl.get_server_certificate(addr, ssl_version=PROTOCOL_TLS_CLIENT, ca_certs=None[, timeout])</code> </dt> <dd>
<p>Given the address <code>addr</code> of an SSL-protected server, as a (<em>hostname</em>, <em>port-number</em>) pair, fetches the server’s certificate, and returns it as a PEM-encoded string. If <code>ssl_version</code> is specified, uses that version of the SSL protocol to attempt to connect to the server. If <em>ca_certs</em> is specified, it should be a file containing a list of root certificates, the same format as used for the <em>cafile</em> parameter in <a class="reference internal" href="#ssl.SSLContext.load_verify_locations" title="ssl.SSLContext.load_verify_locations"><code>SSLContext.load_verify_locations()</code></a>. The call will attempt to validate the server certificate against that set of root certificates, and will fail if the validation attempt fails. A timeout can be specified with the <code>timeout</code> parameter.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>This function is now IPv6-compatible.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>The default <em>ssl_version</em> is changed from <a class="reference internal" href="#ssl.PROTOCOL_SSLv3" title="ssl.PROTOCOL_SSLv3"><code>PROTOCOL_SSLv3</code></a> to <a class="reference internal" href="#ssl.PROTOCOL_TLS" title="ssl.PROTOCOL_TLS"><code>PROTOCOL_TLS</code></a> for maximum compatibility with modern servers.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>The <em>timeout</em> parameter was added.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="ssl.DER_cert_to_PEM_cert">
<code>ssl.DER_cert_to_PEM_cert(DER_cert_bytes)</code> </dt> <dd>
<p>Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded string version of the same certificate.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="ssl.PEM_cert_to_DER_cert">
<code>ssl.PEM_cert_to_DER_cert(PEM_cert_string)</code> </dt> <dd>
<p>Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of bytes for that same certificate.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="ssl.get_default_verify_paths">
<code>ssl.get_default_verify_paths()</code> </dt> <dd>
<p>Returns a named tuple with paths to OpenSSL’s default cafile and capath. The paths are the same as used by <a class="reference internal" href="#ssl.SSLContext.set_default_verify_paths" title="ssl.SSLContext.set_default_verify_paths"><code>SSLContext.set_default_verify_paths()</code></a>. The return value is a <a class="reference internal" href="../glossary#term-named-tuple"><span class="xref std std-term">named tuple</span></a> <code>DefaultVerifyPaths</code>:</p> <ul class="simple"> <li>
<code>cafile</code> - resolved path to cafile or <code>None</code> if the file doesn’t exist,</li> <li>
<code>capath</code> - resolved path to capath or <code>None</code> if the directory doesn’t exist,</li> <li>
<code>openssl_cafile_env</code> - OpenSSL’s environment key that points to a cafile,</li> <li>
<code>openssl_cafile</code> - hard coded path to a cafile,</li> <li>
<code>openssl_capath_env</code> - OpenSSL’s environment key that points to a capath,</li> <li>
<code>openssl_capath</code> - hard coded path to a capath directory</li> </ul> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="ssl.enum_certificates">
<code>ssl.enum_certificates(store_name)</code> </dt> <dd>
<p>Retrieve certificates from Windows’ system cert store. <em>store_name</em> may be one of <code>CA</code>, <code>ROOT</code> or <code>MY</code>. Windows may provide additional cert stores, too.</p> <p>The function returns a list of (cert_bytes, encoding_type, trust) tuples. The encoding_type specifies the encoding of cert_bytes. It is either <code>x509_asn</code> for X.509 ASN.1 data or <code>pkcs_7_asn</code> for PKCS#7 ASN.1 data. Trust specifies the purpose of the certificate as a set of OIDS or exactly <code>True</code> if the certificate is trustworthy for all purposes.</p> <p>Example:</p> <pre data-language="python">&gt;&gt;&gt; ssl.enum_certificates("CA")
[(b'data...', 'x509_asn', {'1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2'}),
 (b'data...', 'x509_asn', True)]
</pre> <div class="availability docutils container"> <p><a class="reference internal" href="https://docs.python.org/3.12/library/intro.html#availability"><span class="std std-ref">Availability</span></a>: Windows.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="ssl.enum_crls">
<code>ssl.enum_crls(store_name)</code> </dt> <dd>
<p>Retrieve CRLs from Windows’ system cert store. <em>store_name</em> may be one of <code>CA</code>, <code>ROOT</code> or <code>MY</code>. Windows may provide additional cert stores, too.</p> <p>The function returns a list of (cert_bytes, encoding_type, trust) tuples. The encoding_type specifies the encoding of cert_bytes. It is either <code>x509_asn</code> for X.509 ASN.1 data or <code>pkcs_7_asn</code> for PKCS#7 ASN.1 data.</p> <div class="availability docutils container"> <p><a class="reference internal" href="https://docs.python.org/3.12/library/intro.html#availability"><span class="std std-ref">Availability</span></a>: Windows.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
</dl> </section> <section id="constants"> <h3>Constants</h3>  <p>All constants are now <a class="reference internal" href="enum#enum.IntEnum" title="enum.IntEnum"><code>enum.IntEnum</code></a> or <a class="reference internal" href="enum#enum.IntFlag" title="enum.IntFlag"><code>enum.IntFlag</code></a> collections.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.</span></p> </div>  <dl class="py data"> <dt class="sig sig-object py" id="ssl.CERT_NONE">
<code>ssl.CERT_NONE</code> </dt> <dd>
<p>Possible value for <a class="reference internal" href="#ssl.SSLContext.verify_mode" title="ssl.SSLContext.verify_mode"><code>SSLContext.verify_mode</code></a>. Except for <a class="reference internal" href="#ssl.PROTOCOL_TLS_CLIENT" title="ssl.PROTOCOL_TLS_CLIENT"><code>PROTOCOL_TLS_CLIENT</code></a>, it is the default mode. With client-side sockets, just about any cert is accepted. Validation errors, such as untrusted or expired cert, are ignored and do not abort the TLS/SSL handshake.</p> <p>In server mode, no certificate is requested from the client, so the client does not send any for client cert authentication.</p> <p>See the discussion of <a class="reference internal" href="#ssl-security"><span class="std std-ref">Security considerations</span></a> below.</p> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.CERT_OPTIONAL">
<code>ssl.CERT_OPTIONAL</code> </dt> <dd>
<p>Possible value for <a class="reference internal" href="#ssl.SSLContext.verify_mode" title="ssl.SSLContext.verify_mode"><code>SSLContext.verify_mode</code></a>. In client mode, <a class="reference internal" href="#ssl.CERT_OPTIONAL" title="ssl.CERT_OPTIONAL"><code>CERT_OPTIONAL</code></a> has the same meaning as <a class="reference internal" href="#ssl.CERT_REQUIRED" title="ssl.CERT_REQUIRED"><code>CERT_REQUIRED</code></a>. It is recommended to use <a class="reference internal" href="#ssl.CERT_REQUIRED" title="ssl.CERT_REQUIRED"><code>CERT_REQUIRED</code></a> for client-side sockets instead.</p> <p>In server mode, a client certificate request is sent to the client. The client may either ignore the request or send a certificate in order perform TLS client cert authentication. If the client chooses to send a certificate, it is verified. Any verification error immediately aborts the TLS handshake.</p> <p>Use of this setting requires a valid set of CA certificates to be passed to <a class="reference internal" href="#ssl.SSLContext.load_verify_locations" title="ssl.SSLContext.load_verify_locations"><code>SSLContext.load_verify_locations()</code></a>.</p> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.CERT_REQUIRED">
<code>ssl.CERT_REQUIRED</code> </dt> <dd>
<p>Possible value for <a class="reference internal" href="#ssl.SSLContext.verify_mode" title="ssl.SSLContext.verify_mode"><code>SSLContext.verify_mode</code></a>. In this mode, certificates are required from the other side of the socket connection; an <a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code>SSLError</code></a> will be raised if no certificate is provided, or if its validation fails. This mode is <strong>not</strong> sufficient to verify a certificate in client mode as it does not match hostnames. <a class="reference internal" href="#ssl.SSLContext.check_hostname" title="ssl.SSLContext.check_hostname"><code>check_hostname</code></a> must be enabled as well to verify the authenticity of a cert. <a class="reference internal" href="#ssl.PROTOCOL_TLS_CLIENT" title="ssl.PROTOCOL_TLS_CLIENT"><code>PROTOCOL_TLS_CLIENT</code></a> uses <a class="reference internal" href="#ssl.CERT_REQUIRED" title="ssl.CERT_REQUIRED"><code>CERT_REQUIRED</code></a> and enables <a class="reference internal" href="#ssl.SSLContext.check_hostname" title="ssl.SSLContext.check_hostname"><code>check_hostname</code></a> by default.</p> <p>With server socket, this mode provides mandatory TLS client cert authentication. A client certificate request is sent to the client and the client must provide a valid and trusted certificate.</p> <p>Use of this setting requires a valid set of CA certificates to be passed to <a class="reference internal" href="#ssl.SSLContext.load_verify_locations" title="ssl.SSLContext.load_verify_locations"><code>SSLContext.load_verify_locations()</code></a>.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ssl.VerifyMode">
<code>class ssl.VerifyMode</code> </dt> <dd>
<p><a class="reference internal" href="enum#enum.IntEnum" title="enum.IntEnum"><code>enum.IntEnum</code></a> collection of CERT_* constants.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.VERIFY_DEFAULT">
<code>ssl.VERIFY_DEFAULT</code> </dt> <dd>
<p>Possible value for <a class="reference internal" href="#ssl.SSLContext.verify_flags" title="ssl.SSLContext.verify_flags"><code>SSLContext.verify_flags</code></a>. In this mode, certificate revocation lists (CRLs) are not checked. By default OpenSSL does neither require nor verify CRLs.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.VERIFY_CRL_CHECK_LEAF">
<code>ssl.VERIFY_CRL_CHECK_LEAF</code> </dt> <dd>
<p>Possible value for <a class="reference internal" href="#ssl.SSLContext.verify_flags" title="ssl.SSLContext.verify_flags"><code>SSLContext.verify_flags</code></a>. In this mode, only the peer cert is checked but none of the intermediate CA certificates. The mode requires a valid CRL that is signed by the peer cert’s issuer (its direct ancestor CA). If no proper CRL has been loaded with <a class="reference internal" href="#ssl.SSLContext.load_verify_locations" title="ssl.SSLContext.load_verify_locations"><code>SSLContext.load_verify_locations</code></a>, validation will fail.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.VERIFY_CRL_CHECK_CHAIN">
<code>ssl.VERIFY_CRL_CHECK_CHAIN</code> </dt> <dd>
<p>Possible value for <a class="reference internal" href="#ssl.SSLContext.verify_flags" title="ssl.SSLContext.verify_flags"><code>SSLContext.verify_flags</code></a>. In this mode, CRLs of all certificates in the peer cert chain are checked.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.VERIFY_X509_STRICT">
<code>ssl.VERIFY_X509_STRICT</code> </dt> <dd>
<p>Possible value for <a class="reference internal" href="#ssl.SSLContext.verify_flags" title="ssl.SSLContext.verify_flags"><code>SSLContext.verify_flags</code></a> to disable workarounds for broken X.509 certificates.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.VERIFY_ALLOW_PROXY_CERTS">
<code>ssl.VERIFY_ALLOW_PROXY_CERTS</code> </dt> <dd>
<p>Possible value for <a class="reference internal" href="#ssl.SSLContext.verify_flags" title="ssl.SSLContext.verify_flags"><code>SSLContext.verify_flags</code></a> to enables proxy certificate verification.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.VERIFY_X509_TRUSTED_FIRST">
<code>ssl.VERIFY_X509_TRUSTED_FIRST</code> </dt> <dd>
<p>Possible value for <a class="reference internal" href="#ssl.SSLContext.verify_flags" title="ssl.SSLContext.verify_flags"><code>SSLContext.verify_flags</code></a>. It instructs OpenSSL to prefer trusted certificates when building the trust chain to validate a certificate. This flag is enabled by default.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.4.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.VERIFY_X509_PARTIAL_CHAIN">
<code>ssl.VERIFY_X509_PARTIAL_CHAIN</code> </dt> <dd>
<p>Possible value for <a class="reference internal" href="#ssl.SSLContext.verify_flags" title="ssl.SSLContext.verify_flags"><code>SSLContext.verify_flags</code></a>. It instructs OpenSSL to accept intermediate CAs in the trust store to be treated as trust-anchors, in the same way as the self-signed root CA certificates. This makes it possible to trust certificates issued by an intermediate CA without having to trust its ancestor root CA.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ssl.VerifyFlags">
<code>class ssl.VerifyFlags</code> </dt> <dd>
<p><a class="reference internal" href="enum#enum.IntFlag" title="enum.IntFlag"><code>enum.IntFlag</code></a> collection of VERIFY_* constants.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.PROTOCOL_TLS">
<code>ssl.PROTOCOL_TLS</code> </dt> <dd>
<p>Selects the highest protocol version that both the client and server support. Despite the name, this option can select both “SSL” and “TLS” protocols.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.10: </span>TLS clients and servers require different default settings for secure communication. The generic TLS protocol constant is deprecated in favor of <a class="reference internal" href="#ssl.PROTOCOL_TLS_CLIENT" title="ssl.PROTOCOL_TLS_CLIENT"><code>PROTOCOL_TLS_CLIENT</code></a> and <a class="reference internal" href="#ssl.PROTOCOL_TLS_SERVER" title="ssl.PROTOCOL_TLS_SERVER"><code>PROTOCOL_TLS_SERVER</code></a>.</p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.PROTOCOL_TLS_CLIENT">
<code>ssl.PROTOCOL_TLS_CLIENT</code> </dt> <dd>
<p>Auto-negotiate the highest protocol version that both the client and server support, and configure the context client-side connections. The protocol enables <a class="reference internal" href="#ssl.CERT_REQUIRED" title="ssl.CERT_REQUIRED"><code>CERT_REQUIRED</code></a> and <a class="reference internal" href="#ssl.SSLContext.check_hostname" title="ssl.SSLContext.check_hostname"><code>check_hostname</code></a> by default.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.PROTOCOL_TLS_SERVER">
<code>ssl.PROTOCOL_TLS_SERVER</code> </dt> <dd>
<p>Auto-negotiate the highest protocol version that both the client and server support, and configure the context server-side connections.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.PROTOCOL_SSLv23">
<code>ssl.PROTOCOL_SSLv23</code> </dt> <dd>
<p>Alias for <a class="reference internal" href="#ssl.PROTOCOL_TLS" title="ssl.PROTOCOL_TLS"><code>PROTOCOL_TLS</code></a>.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.6: </span>Use <a class="reference internal" href="#ssl.PROTOCOL_TLS" title="ssl.PROTOCOL_TLS"><code>PROTOCOL_TLS</code></a> instead.</p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.PROTOCOL_SSLv3">
<code>ssl.PROTOCOL_SSLv3</code> </dt> <dd>
<p>Selects SSL version 3 as the channel encryption protocol.</p> <p>This protocol is not available if OpenSSL is compiled with the <code>no-ssl3</code> option.</p> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p>SSL version 3 is insecure. Its use is highly discouraged.</p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.6: </span>OpenSSL has deprecated all version specific protocols. Use the default protocol <a class="reference internal" href="#ssl.PROTOCOL_TLS_SERVER" title="ssl.PROTOCOL_TLS_SERVER"><code>PROTOCOL_TLS_SERVER</code></a> or <a class="reference internal" href="#ssl.PROTOCOL_TLS_CLIENT" title="ssl.PROTOCOL_TLS_CLIENT"><code>PROTOCOL_TLS_CLIENT</code></a> with <a class="reference internal" href="#ssl.SSLContext.minimum_version" title="ssl.SSLContext.minimum_version"><code>SSLContext.minimum_version</code></a> and <a class="reference internal" href="#ssl.SSLContext.maximum_version" title="ssl.SSLContext.maximum_version"><code>SSLContext.maximum_version</code></a> instead.</p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.PROTOCOL_TLSv1">
<code>ssl.PROTOCOL_TLSv1</code> </dt> <dd>
<p>Selects TLS version 1.0 as the channel encryption protocol.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.6: </span>OpenSSL has deprecated all version specific protocols.</p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.PROTOCOL_TLSv1_1">
<code>ssl.PROTOCOL_TLSv1_1</code> </dt> <dd>
<p>Selects TLS version 1.1 as the channel encryption protocol. Available only with openssl version 1.0.1+.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.6: </span>OpenSSL has deprecated all version specific protocols.</p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.PROTOCOL_TLSv1_2">
<code>ssl.PROTOCOL_TLSv1_2</code> </dt> <dd>
<p>Selects TLS version 1.2 as the channel encryption protocol. Available only with openssl version 1.0.1+.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.6: </span>OpenSSL has deprecated all version specific protocols.</p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.OP_ALL">
<code>ssl.OP_ALL</code> </dt> <dd>
<p>Enables workarounds for various bugs present in other SSL implementations. This option is set by default. It does not necessarily set the same flags as OpenSSL’s <code>SSL_OP_ALL</code> constant.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.OP_NO_SSLv2">
<code>ssl.OP_NO_SSLv2</code> </dt> <dd>
<p>Prevents an SSLv2 connection. This option is only applicable in conjunction with <a class="reference internal" href="#ssl.PROTOCOL_TLS" title="ssl.PROTOCOL_TLS"><code>PROTOCOL_TLS</code></a>. It prevents the peers from choosing SSLv2 as the protocol version.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.6: </span>SSLv2 is deprecated</p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.OP_NO_SSLv3">
<code>ssl.OP_NO_SSLv3</code> </dt> <dd>
<p>Prevents an SSLv3 connection. This option is only applicable in conjunction with <a class="reference internal" href="#ssl.PROTOCOL_TLS" title="ssl.PROTOCOL_TLS"><code>PROTOCOL_TLS</code></a>. It prevents the peers from choosing SSLv3 as the protocol version.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.6: </span>SSLv3 is deprecated</p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.OP_NO_TLSv1">
<code>ssl.OP_NO_TLSv1</code> </dt> <dd>
<p>Prevents a TLSv1 connection. This option is only applicable in conjunction with <a class="reference internal" href="#ssl.PROTOCOL_TLS" title="ssl.PROTOCOL_TLS"><code>PROTOCOL_TLS</code></a>. It prevents the peers from choosing TLSv1 as the protocol version.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.7: </span>The option is deprecated since OpenSSL 1.1.0, use the new <a class="reference internal" href="#ssl.SSLContext.minimum_version" title="ssl.SSLContext.minimum_version"><code>SSLContext.minimum_version</code></a> and <a class="reference internal" href="#ssl.SSLContext.maximum_version" title="ssl.SSLContext.maximum_version"><code>SSLContext.maximum_version</code></a> instead.</p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.OP_NO_TLSv1_1">
<code>ssl.OP_NO_TLSv1_1</code> </dt> <dd>
<p>Prevents a TLSv1.1 connection. This option is only applicable in conjunction with <a class="reference internal" href="#ssl.PROTOCOL_TLS" title="ssl.PROTOCOL_TLS"><code>PROTOCOL_TLS</code></a>. It prevents the peers from choosing TLSv1.1 as the protocol version. Available only with openssl version 1.0.1+.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.7: </span>The option is deprecated since OpenSSL 1.1.0.</p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.OP_NO_TLSv1_2">
<code>ssl.OP_NO_TLSv1_2</code> </dt> <dd>
<p>Prevents a TLSv1.2 connection. This option is only applicable in conjunction with <a class="reference internal" href="#ssl.PROTOCOL_TLS" title="ssl.PROTOCOL_TLS"><code>PROTOCOL_TLS</code></a>. It prevents the peers from choosing TLSv1.2 as the protocol version. Available only with openssl version 1.0.1+.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.7: </span>The option is deprecated since OpenSSL 1.1.0.</p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.OP_NO_TLSv1_3">
<code>ssl.OP_NO_TLSv1_3</code> </dt> <dd>
<p>Prevents a TLSv1.3 connection. This option is only applicable in conjunction with <a class="reference internal" href="#ssl.PROTOCOL_TLS" title="ssl.PROTOCOL_TLS"><code>PROTOCOL_TLS</code></a>. It prevents the peers from choosing TLSv1.3 as the protocol version. TLS 1.3 is available with OpenSSL 1.1.1 or later. When Python has been compiled against an older version of OpenSSL, the flag defaults to <em>0</em>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.7: </span>The option is deprecated since OpenSSL 1.1.0. It was added to 2.7.15, 3.6.3 and 3.7.0 for backwards compatibility with OpenSSL 1.0.2.</p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.OP_NO_RENEGOTIATION">
<code>ssl.OP_NO_RENEGOTIATION</code> </dt> <dd>
<p>Disable all renegotiation in TLSv1.2 and earlier. Do not send HelloRequest messages, and ignore renegotiation requests via ClientHello.</p> <p>This option is only available with OpenSSL 1.1.0h and later.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.OP_CIPHER_SERVER_PREFERENCE">
<code>ssl.OP_CIPHER_SERVER_PREFERENCE</code> </dt> <dd>
<p>Use the server’s cipher ordering preference, rather than the client’s. This option has no effect on client sockets and SSLv2 server sockets.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.OP_SINGLE_DH_USE">
<code>ssl.OP_SINGLE_DH_USE</code> </dt> <dd>
<p>Prevents re-use of the same DH key for distinct SSL sessions. This improves forward secrecy but requires more computational resources. This option only applies to server sockets.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.OP_SINGLE_ECDH_USE">
<code>ssl.OP_SINGLE_ECDH_USE</code> </dt> <dd>
<p>Prevents re-use of the same ECDH key for distinct SSL sessions. This improves forward secrecy but requires more computational resources. This option only applies to server sockets.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.OP_ENABLE_MIDDLEBOX_COMPAT">
<code>ssl.OP_ENABLE_MIDDLEBOX_COMPAT</code> </dt> <dd>
<p>Send dummy Change Cipher Spec (CCS) messages in TLS 1.3 handshake to make a TLS 1.3 connection look more like a TLS 1.2 connection.</p> <p>This option is only available with OpenSSL 1.1.1 and later.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.OP_NO_COMPRESSION">
<code>ssl.OP_NO_COMPRESSION</code> </dt> <dd>
<p>Disable compression on the SSL channel. This is useful if the application protocol supports its own compression scheme.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ssl.Options">
<code>class ssl.Options</code> </dt> <dd>
<p><a class="reference internal" href="enum#enum.IntFlag" title="enum.IntFlag"><code>enum.IntFlag</code></a> collection of OP_* constants.</p> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.OP_NO_TICKET">
<code>ssl.OP_NO_TICKET</code> </dt> <dd>
<p>Prevent client side from requesting a session ticket.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.OP_IGNORE_UNEXPECTED_EOF">
<code>ssl.OP_IGNORE_UNEXPECTED_EOF</code> </dt> <dd>
<p>Ignore unexpected shutdown of TLS connections.</p> <p>This option is only available with OpenSSL 3.0.0 and later.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.OP_ENABLE_KTLS">
<code>ssl.OP_ENABLE_KTLS</code> </dt> <dd>
<p>Enable the use of the kernel TLS. To benefit from the feature, OpenSSL must have been compiled with support for it, and the negotiated cipher suites and extensions must be supported by it (a list of supported ones may vary by platform and kernel version).</p> <p>Note that with enabled kernel TLS some cryptographic operations are performed by the kernel directly and not via any available OpenSSL Providers. This might be undesirable if, for example, the application requires all cryptographic operations to be performed by the FIPS provider.</p> <p>This option is only available with OpenSSL 3.0.0 and later.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.OP_LEGACY_SERVER_CONNECT">
<code>ssl.OP_LEGACY_SERVER_CONNECT</code> </dt> <dd>
<p>Allow legacy insecure renegotiation between OpenSSL and unpatched servers only.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.HAS_ALPN">
<code>ssl.HAS_ALPN</code> </dt> <dd>
<p>Whether the OpenSSL library has built-in support for the <em>Application-Layer Protocol Negotiation</em> TLS extension as described in <span class="target" id="index-7"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc7301.html"><strong>RFC 7301</strong></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.HAS_NEVER_CHECK_COMMON_NAME">
<code>ssl.HAS_NEVER_CHECK_COMMON_NAME</code> </dt> <dd>
<p>Whether the OpenSSL library has built-in support not checking subject common name and <a class="reference internal" href="#ssl.SSLContext.hostname_checks_common_name" title="ssl.SSLContext.hostname_checks_common_name"><code>SSLContext.hostname_checks_common_name</code></a> is writeable.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.HAS_ECDH">
<code>ssl.HAS_ECDH</code> </dt> <dd>
<p>Whether the OpenSSL library has built-in support for the Elliptic Curve-based Diffie-Hellman key exchange. This should be true unless the feature was explicitly disabled by the distributor.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.HAS_SNI">
<code>ssl.HAS_SNI</code> </dt> <dd>
<p>Whether the OpenSSL library has built-in support for the <em>Server Name Indication</em> extension (as defined in <span class="target" id="index-8"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc6066.html"><strong>RFC 6066</strong></a>).</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.HAS_NPN">
<code>ssl.HAS_NPN</code> </dt> <dd>
<p>Whether the OpenSSL library has built-in support for the <em>Next Protocol Negotiation</em> as described in the <a class="reference external" href="https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation">Application Layer Protocol Negotiation</a>. When true, you can use the <a class="reference internal" href="#ssl.SSLContext.set_npn_protocols" title="ssl.SSLContext.set_npn_protocols"><code>SSLContext.set_npn_protocols()</code></a> method to advertise which protocols you want to support.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.HAS_SSLv2">
<code>ssl.HAS_SSLv2</code> </dt> <dd>
<p>Whether the OpenSSL library has built-in support for the SSL 2.0 protocol.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.HAS_SSLv3">
<code>ssl.HAS_SSLv3</code> </dt> <dd>
<p>Whether the OpenSSL library has built-in support for the SSL 3.0 protocol.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.HAS_TLSv1">
<code>ssl.HAS_TLSv1</code> </dt> <dd>
<p>Whether the OpenSSL library has built-in support for the TLS 1.0 protocol.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.HAS_TLSv1_1">
<code>ssl.HAS_TLSv1_1</code> </dt> <dd>
<p>Whether the OpenSSL library has built-in support for the TLS 1.1 protocol.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.HAS_TLSv1_2">
<code>ssl.HAS_TLSv1_2</code> </dt> <dd>
<p>Whether the OpenSSL library has built-in support for the TLS 1.2 protocol.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.HAS_TLSv1_3">
<code>ssl.HAS_TLSv1_3</code> </dt> <dd>
<p>Whether the OpenSSL library has built-in support for the TLS 1.3 protocol.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.CHANNEL_BINDING_TYPES">
<code>ssl.CHANNEL_BINDING_TYPES</code> </dt> <dd>
<p>List of supported TLS channel binding types. Strings in this list can be used as arguments to <a class="reference internal" href="#ssl.SSLSocket.get_channel_binding" title="ssl.SSLSocket.get_channel_binding"><code>SSLSocket.get_channel_binding()</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.OPENSSL_VERSION">
<code>ssl.OPENSSL_VERSION</code> </dt> <dd>
<p>The version string of the OpenSSL library loaded by the interpreter:</p> <pre data-language="python">&gt;&gt;&gt; ssl.OPENSSL_VERSION
'OpenSSL 1.0.2k  26 Jan 2017'
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.OPENSSL_VERSION_INFO">
<code>ssl.OPENSSL_VERSION_INFO</code> </dt> <dd>
<p>A tuple of five integers representing version information about the OpenSSL library:</p> <pre data-language="python">&gt;&gt;&gt; ssl.OPENSSL_VERSION_INFO
(1, 0, 2, 11, 15)
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.OPENSSL_VERSION_NUMBER">
<code>ssl.OPENSSL_VERSION_NUMBER</code> </dt> <dd>
<p>The raw version number of the OpenSSL library, as a single integer:</p> <pre data-language="python">&gt;&gt;&gt; ssl.OPENSSL_VERSION_NUMBER
268443839
&gt;&gt;&gt; hex(ssl.OPENSSL_VERSION_NUMBER)
'0x100020bf'
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.ALERT_DESCRIPTION_HANDSHAKE_FAILURE">
<code>ssl.ALERT_DESCRIPTION_HANDSHAKE_FAILURE</code> </dt> <dt class="sig sig-object py" id="ssl.ALERT_DESCRIPTION_INTERNAL_ERROR">
<code>ssl.ALERT_DESCRIPTION_INTERNAL_ERROR</code> </dt> <dt class="sig sig-object py"> <span class="sig-name descname">ALERT_DESCRIPTION_*</span>
</dt> <dd>
<p>Alert Descriptions from <span class="target" id="index-9"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc5246.html"><strong>RFC 5246</strong></a> and others. The <a class="reference external" href="https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6">IANA TLS Alert Registry</a> contains this list and references to the RFCs where their meaning is defined.</p> <p>Used as the return value of the callback function in <a class="reference internal" href="#ssl.SSLContext.set_servername_callback" title="ssl.SSLContext.set_servername_callback"><code>SSLContext.set_servername_callback()</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ssl.AlertDescription">
<code>class ssl.AlertDescription</code> </dt> <dd>
<p><a class="reference internal" href="enum#enum.IntEnum" title="enum.IntEnum"><code>enum.IntEnum</code></a> collection of ALERT_DESCRIPTION_* constants.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.Purpose.SERVER_AUTH">
<code>Purpose.SERVER_AUTH</code> </dt> <dd>
<p>Option for <a class="reference internal" href="#ssl.create_default_context" title="ssl.create_default_context"><code>create_default_context()</code></a> and <a class="reference internal" href="#ssl.SSLContext.load_default_certs" title="ssl.SSLContext.load_default_certs"><code>SSLContext.load_default_certs()</code></a>. This value indicates that the context may be used to authenticate web servers (therefore, it will be used to create client-side sockets).</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
</dl> <dl class="py data"> <dt class="sig sig-object py" id="ssl.Purpose.CLIENT_AUTH">
<code>Purpose.CLIENT_AUTH</code> </dt> <dd>
<p>Option for <a class="reference internal" href="#ssl.create_default_context" title="ssl.create_default_context"><code>create_default_context()</code></a> and <a class="reference internal" href="#ssl.SSLContext.load_default_certs" title="ssl.SSLContext.load_default_certs"><code>SSLContext.load_default_certs()</code></a>. This value indicates that the context may be used to authenticate web clients (therefore, it will be used to create server-side sockets).</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ssl.SSLErrorNumber">
<code>class ssl.SSLErrorNumber</code> </dt> <dd>
<p><a class="reference internal" href="enum#enum.IntEnum" title="enum.IntEnum"><code>enum.IntEnum</code></a> collection of SSL_ERROR_* constants.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.</span></p> </div> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="ssl.TLSVersion">
<code>class ssl.TLSVersion</code> </dt> <dd>
<p><a class="reference internal" href="enum#enum.IntEnum" title="enum.IntEnum"><code>enum.IntEnum</code></a> collection of SSL and TLS versions for <a class="reference internal" href="#ssl.SSLContext.maximum_version" title="ssl.SSLContext.maximum_version"><code>SSLContext.maximum_version</code></a> and <a class="reference internal" href="#ssl.SSLContext.minimum_version" title="ssl.SSLContext.minimum_version"><code>SSLContext.minimum_version</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.TLSVersion.MINIMUM_SUPPORTED">
<code>TLSVersion.MINIMUM_SUPPORTED</code> </dt> <dd></dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.TLSVersion.MAXIMUM_SUPPORTED">
<code>TLSVersion.MAXIMUM_SUPPORTED</code> </dt> <dd>
<p>The minimum or maximum supported SSL or TLS version. These are magic constants. Their values don’t reflect the lowest and highest available TLS/SSL versions.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.TLSVersion.SSLv3">
<code>TLSVersion.SSLv3</code> </dt> <dd></dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.TLSVersion.TLSv1">
<code>TLSVersion.TLSv1</code> </dt> <dd></dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.TLSVersion.TLSv1_1">
<code>TLSVersion.TLSv1_1</code> </dt> <dd></dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.TLSVersion.TLSv1_2">
<code>TLSVersion.TLSv1_2</code> </dt> <dd></dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.TLSVersion.TLSv1_3">
<code>TLSVersion.TLSv1_3</code> </dt> <dd>
<p>SSL 3.0 to TLS 1.3.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.10: </span>All <a class="reference internal" href="#ssl.TLSVersion" title="ssl.TLSVersion"><code>TLSVersion</code></a> members except <a class="reference internal" href="#ssl.TLSVersion.TLSv1_2" title="ssl.TLSVersion.TLSv1_2"><code>TLSVersion.TLSv1_2</code></a> and <a class="reference internal" href="#ssl.TLSVersion.TLSv1_3" title="ssl.TLSVersion.TLSv1_3"><code>TLSVersion.TLSv1_3</code></a> are deprecated.</p> </div> </dd>
</dl> </section> </section> <section id="ssl-sockets"> <h2>SSL Sockets</h2> <dl class="py class"> <dt class="sig sig-object py" id="ssl.SSLSocket">
<code>class ssl.SSLSocket(socket.socket)</code> </dt> <dd>
<p>SSL sockets provide the following methods of <a class="reference internal" href="socket#socket-objects"><span class="std std-ref">Socket Objects</span></a>:</p> <ul class="simple"> <li><a class="reference internal" href="socket#socket.socket.accept" title="socket.socket.accept"><code>accept()</code></a></li> <li><a class="reference internal" href="socket#socket.socket.bind" title="socket.socket.bind"><code>bind()</code></a></li> <li><a class="reference internal" href="socket#socket.socket.close" title="socket.socket.close"><code>close()</code></a></li> <li><a class="reference internal" href="socket#socket.socket.connect" title="socket.socket.connect"><code>connect()</code></a></li> <li><a class="reference internal" href="socket#socket.socket.detach" title="socket.socket.detach"><code>detach()</code></a></li> <li><a class="reference internal" href="socket#socket.socket.fileno" title="socket.socket.fileno"><code>fileno()</code></a></li> <li>
<a class="reference internal" href="socket#socket.socket.getpeername" title="socket.socket.getpeername"><code>getpeername()</code></a>, <a class="reference internal" href="socket#socket.socket.getsockname" title="socket.socket.getsockname"><code>getsockname()</code></a>
</li> <li>
<a class="reference internal" href="socket#socket.socket.getsockopt" title="socket.socket.getsockopt"><code>getsockopt()</code></a>, <a class="reference internal" href="socket#socket.socket.setsockopt" title="socket.socket.setsockopt"><code>setsockopt()</code></a>
</li> <li>
<a class="reference internal" href="socket#socket.socket.gettimeout" title="socket.socket.gettimeout"><code>gettimeout()</code></a>, <a class="reference internal" href="socket#socket.socket.settimeout" title="socket.socket.settimeout"><code>settimeout()</code></a>, <a class="reference internal" href="socket#socket.socket.setblocking" title="socket.socket.setblocking"><code>setblocking()</code></a>
</li> <li><a class="reference internal" href="socket#socket.socket.listen" title="socket.socket.listen"><code>listen()</code></a></li> <li><a class="reference internal" href="socket#socket.socket.makefile" title="socket.socket.makefile"><code>makefile()</code></a></li> <li>
<a class="reference internal" href="socket#socket.socket.recv" title="socket.socket.recv"><code>recv()</code></a>, <a class="reference internal" href="socket#socket.socket.recv_into" title="socket.socket.recv_into"><code>recv_into()</code></a> (but passing a non-zero <code>flags</code> argument is not allowed)</li> <li>
<a class="reference internal" href="socket#socket.socket.send" title="socket.socket.send"><code>send()</code></a>, <a class="reference internal" href="socket#socket.socket.sendall" title="socket.socket.sendall"><code>sendall()</code></a> (with the same limitation)</li> <li>
<a class="reference internal" href="socket#socket.socket.sendfile" title="socket.socket.sendfile"><code>sendfile()</code></a> (but <a class="reference internal" href="os#os.sendfile" title="os.sendfile"><code>os.sendfile</code></a> will be used for plain-text sockets only, else <a class="reference internal" href="socket#socket.socket.send" title="socket.socket.send"><code>send()</code></a> will be used)</li> <li><a class="reference internal" href="socket#socket.socket.shutdown" title="socket.socket.shutdown"><code>shutdown()</code></a></li> </ul> <p>However, since the SSL (and TLS) protocol has its own framing atop of TCP, the SSL sockets abstraction can, in certain respects, diverge from the specification of normal, OS-level sockets. See especially the <a class="reference internal" href="#ssl-nonblocking"><span class="std std-ref">notes on non-blocking sockets</span></a>.</p> <p>Instances of <a class="reference internal" href="#ssl.SSLSocket" title="ssl.SSLSocket"><code>SSLSocket</code></a> must be created using the <a class="reference internal" href="#ssl.SSLContext.wrap_socket" title="ssl.SSLContext.wrap_socket"><code>SSLContext.wrap_socket()</code></a> method.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>The <code>sendfile()</code> method was added.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>The <code>shutdown()</code> does not reset the socket timeout each time bytes are received or sent. The socket timeout is now the maximum total duration of the shutdown.</p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.6: </span>It is deprecated to create a <a class="reference internal" href="#ssl.SSLSocket" title="ssl.SSLSocket"><code>SSLSocket</code></a> instance directly, use <a class="reference internal" href="#ssl.SSLContext.wrap_socket" title="ssl.SSLContext.wrap_socket"><code>SSLContext.wrap_socket()</code></a> to wrap a socket.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span><a class="reference internal" href="#ssl.SSLSocket" title="ssl.SSLSocket"><code>SSLSocket</code></a> instances must to created with <a class="reference internal" href="#ssl.SSLContext.wrap_socket" title="ssl.SSLContext.wrap_socket"><code>wrap_socket()</code></a>. In earlier versions, it was possible to create instances directly. This was never documented or officially supported.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>Python now uses <code>SSL_read_ex</code> and <code>SSL_write_ex</code> internally. The functions support reading and writing of data larger than 2 GB. Writing zero-length data no longer fails with a protocol violation error.</p> </div> </dd>
</dl> <p>SSL sockets also have the following additional methods and attributes:</p> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLSocket.read">
<code>SSLSocket.read(len=1024, buffer=None)</code> </dt> <dd>
<p>Read up to <em>len</em> bytes of data from the SSL socket and return the result as a <code>bytes</code> instance. If <em>buffer</em> is specified, then read into the buffer instead, and return the number of bytes read.</p> <p>Raise <a class="reference internal" href="#ssl.SSLWantReadError" title="ssl.SSLWantReadError"><code>SSLWantReadError</code></a> or <a class="reference internal" href="#ssl.SSLWantWriteError" title="ssl.SSLWantWriteError"><code>SSLWantWriteError</code></a> if the socket is <a class="reference internal" href="#ssl-nonblocking"><span class="std std-ref">non-blocking</span></a> and the read would block.</p> <p>As at any time a re-negotiation is possible, a call to <a class="reference internal" href="#ssl.SSLSocket.read" title="ssl.SSLSocket.read"><code>read()</code></a> can also cause write operations.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>The socket timeout is no longer reset each time bytes are received or sent. The socket timeout is now the maximum total duration to read up to <em>len</em> bytes.</p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.6: </span>Use <code>recv()</code> instead of <a class="reference internal" href="#ssl.SSLSocket.read" title="ssl.SSLSocket.read"><code>read()</code></a>.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLSocket.write">
<code>SSLSocket.write(buf)</code> </dt> <dd>
<p>Write <em>buf</em> to the SSL socket and return the number of bytes written. The <em>buf</em> argument must be an object supporting the buffer interface.</p> <p>Raise <a class="reference internal" href="#ssl.SSLWantReadError" title="ssl.SSLWantReadError"><code>SSLWantReadError</code></a> or <a class="reference internal" href="#ssl.SSLWantWriteError" title="ssl.SSLWantWriteError"><code>SSLWantWriteError</code></a> if the socket is <a class="reference internal" href="#ssl-nonblocking"><span class="std std-ref">non-blocking</span></a> and the write would block.</p> <p>As at any time a re-negotiation is possible, a call to <a class="reference internal" href="#ssl.SSLSocket.write" title="ssl.SSLSocket.write"><code>write()</code></a> can also cause read operations.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>The socket timeout is no longer reset each time bytes are received or sent. The socket timeout is now the maximum total duration to write <em>buf</em>.</p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.6: </span>Use <code>send()</code> instead of <a class="reference internal" href="#ssl.SSLSocket.write" title="ssl.SSLSocket.write"><code>write()</code></a>.</p> </div> </dd>
</dl> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The <a class="reference internal" href="#ssl.SSLSocket.read" title="ssl.SSLSocket.read"><code>read()</code></a> and <a class="reference internal" href="#ssl.SSLSocket.write" title="ssl.SSLSocket.write"><code>write()</code></a> methods are the low-level methods that read and write unencrypted, application-level data and decrypt/encrypt it to encrypted, wire-level data. These methods require an active SSL connection, i.e. the handshake was completed and <a class="reference internal" href="#ssl.SSLSocket.unwrap" title="ssl.SSLSocket.unwrap"><code>SSLSocket.unwrap()</code></a> was not called.</p> <p>Normally you should use the socket API methods like <a class="reference internal" href="socket#socket.socket.recv" title="socket.socket.recv"><code>recv()</code></a> and <a class="reference internal" href="socket#socket.socket.send" title="socket.socket.send"><code>send()</code></a> instead of these methods.</p> </div> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLSocket.do_handshake">
<code>SSLSocket.do_handshake()</code> </dt> <dd>
<p>Perform the SSL setup handshake.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>The handshake method also performs <code>match_hostname()</code> when the <a class="reference internal" href="#ssl.SSLContext.check_hostname" title="ssl.SSLContext.check_hostname"><code>check_hostname</code></a> attribute of the socket’s <a class="reference internal" href="#ssl.SSLSocket.context" title="ssl.SSLSocket.context"><code>context</code></a> is true.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>The socket timeout is no longer reset each time bytes are received or sent. The socket timeout is now the maximum total duration of the handshake.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Hostname or IP address is matched by OpenSSL during handshake. The function <code>match_hostname()</code> is no longer used. In case OpenSSL refuses a hostname or IP address, the handshake is aborted early and a TLS alert message is sent to the peer.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLSocket.getpeercert">
<code>SSLSocket.getpeercert(binary_form=False)</code> </dt> <dd>
<p>If there is no certificate for the peer on the other end of the connection, return <code>None</code>. If the SSL handshake hasn’t been done yet, raise <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a>.</p> <p>If the <code>binary_form</code> parameter is <a class="reference internal" href="constants#False" title="False"><code>False</code></a>, and a certificate was received from the peer, this method returns a <a class="reference internal" href="stdtypes#dict" title="dict"><code>dict</code></a> instance. If the certificate was not validated, the dict is empty. If the certificate was validated, it returns a dict with several keys, amongst them <code>subject</code> (the principal for which the certificate was issued) and <code>issuer</code> (the principal issuing the certificate). If a certificate contains an instance of the <em>Subject Alternative Name</em> extension (see <span class="target" id="index-10"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc3280.html"><strong>RFC 3280</strong></a>), there will also be a <code>subjectAltName</code> key in the dictionary.</p> <p>The <code>subject</code> and <code>issuer</code> fields are tuples containing the sequence of relative distinguished names (RDNs) given in the certificate’s data structure for the respective fields, and each RDN is a sequence of name-value pairs. Here is a real-world example:</p> <pre data-language="python">{'issuer': ((('countryName', 'IL'),),
            (('organizationName', 'StartCom Ltd.'),),
            (('organizationalUnitName',
              'Secure Digital Certificate Signing'),),
            (('commonName',
              'StartCom Class 2 Primary Intermediate Server CA'),)),
 'notAfter': 'Nov 22 08:15:19 2013 GMT',
 'notBefore': 'Nov 21 03:09:52 2011 GMT',
 'serialNumber': '95F0',
 'subject': ((('description', '571208-SLe257oHY9fVQ07Z'),),
             (('countryName', 'US'),),
             (('stateOrProvinceName', 'California'),),
             (('localityName', 'San Francisco'),),
             (('organizationName', 'Electronic Frontier Foundation, Inc.'),),
             (('commonName', '*.eff.org'),),
             (('emailAddress', 'hostmaster@eff.org'),)),
 'subjectAltName': (('DNS', '*.eff.org'), ('DNS', 'eff.org')),
 'version': 3}
</pre> <p>If the <code>binary_form</code> parameter is <a class="reference internal" href="constants#True" title="True"><code>True</code></a>, and a certificate was provided, this method returns the DER-encoded form of the entire certificate as a sequence of bytes, or <a class="reference internal" href="constants#None" title="None"><code>None</code></a> if the peer did not provide a certificate. Whether the peer provides a certificate depends on the SSL socket’s role:</p> <ul class="simple"> <li>for a client SSL socket, the server will always provide a certificate, regardless of whether validation was required;</li> <li>for a server SSL socket, the client will only provide a certificate when requested by the server; therefore <a class="reference internal" href="#ssl.SSLSocket.getpeercert" title="ssl.SSLSocket.getpeercert"><code>getpeercert()</code></a> will return <a class="reference internal" href="constants#None" title="None"><code>None</code></a> if you used <a class="reference internal" href="#ssl.CERT_NONE" title="ssl.CERT_NONE"><code>CERT_NONE</code></a> (rather than <a class="reference internal" href="#ssl.CERT_OPTIONAL" title="ssl.CERT_OPTIONAL"><code>CERT_OPTIONAL</code></a> or <a class="reference internal" href="#ssl.CERT_REQUIRED" title="ssl.CERT_REQUIRED"><code>CERT_REQUIRED</code></a>).</li> </ul> <p>See also <a class="reference internal" href="#ssl.SSLContext.check_hostname" title="ssl.SSLContext.check_hostname"><code>SSLContext.check_hostname</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>The returned dictionary includes additional items such as <code>issuer</code> and <code>notBefore</code>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span><a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> is raised when the handshake isn’t done. The returned dictionary includes additional X509v3 extension items such as <code>crlDistributionPoints</code>, <code>caIssuers</code> and <code>OCSP</code> URIs.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>IPv6 address strings no longer have a trailing new line.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLSocket.cipher">
<code>SSLSocket.cipher()</code> </dt> <dd>
<p>Returns a three-value tuple containing the name of the cipher being used, the version of the SSL protocol that defines its use, and the number of secret bits being used. If no connection has been established, returns <code>None</code>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLSocket.shared_ciphers">
<code>SSLSocket.shared_ciphers()</code> </dt> <dd>
<p>Return the list of ciphers available in both the client and server. Each entry of the returned list is a three-value tuple containing the name of the cipher, the version of the SSL protocol that defines its use, and the number of secret bits the cipher uses. <a class="reference internal" href="#ssl.SSLSocket.shared_ciphers" title="ssl.SSLSocket.shared_ciphers"><code>shared_ciphers()</code></a> returns <code>None</code> if no connection has been established or the socket is a client socket.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLSocket.compression">
<code>SSLSocket.compression()</code> </dt> <dd>
<p>Return the compression algorithm being used as a string, or <code>None</code> if the connection isn’t compressed.</p> <p>If the higher-level protocol supports its own compression mechanism, you can use <a class="reference internal" href="#ssl.OP_NO_COMPRESSION" title="ssl.OP_NO_COMPRESSION"><code>OP_NO_COMPRESSION</code></a> to disable SSL-level compression.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLSocket.get_channel_binding">
<code>SSLSocket.get_channel_binding(cb_type='tls-unique')</code> </dt> <dd>
<p>Get channel binding data for current connection, as a bytes object. Returns <code>None</code> if not connected or the handshake has not been completed.</p> <p>The <em>cb_type</em> parameter allow selection of the desired channel binding type. Valid channel binding types are listed in the <a class="reference internal" href="#ssl.CHANNEL_BINDING_TYPES" title="ssl.CHANNEL_BINDING_TYPES"><code>CHANNEL_BINDING_TYPES</code></a> list. Currently only the ‘tls-unique’ channel binding, defined by <span class="target" id="index-11"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc5929.html"><strong>RFC 5929</strong></a>, is supported. <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> will be raised if an unsupported channel binding type is requested.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLSocket.selected_alpn_protocol">
<code>SSLSocket.selected_alpn_protocol()</code> </dt> <dd>
<p>Return the protocol that was selected during the TLS handshake. If <a class="reference internal" href="#ssl.SSLContext.set_alpn_protocols" title="ssl.SSLContext.set_alpn_protocols"><code>SSLContext.set_alpn_protocols()</code></a> was not called, if the other party does not support ALPN, if this socket does not support any of the client’s proposed protocols, or if the handshake has not happened yet, <code>None</code> is returned.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLSocket.selected_npn_protocol">
<code>SSLSocket.selected_npn_protocol()</code> </dt> <dd>
<p>Return the higher-level protocol that was selected during the TLS/SSL handshake. If <a class="reference internal" href="#ssl.SSLContext.set_npn_protocols" title="ssl.SSLContext.set_npn_protocols"><code>SSLContext.set_npn_protocols()</code></a> was not called, or if the other party does not support NPN, or if the handshake has not yet happened, this will return <code>None</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.10: </span>NPN has been superseded by ALPN</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLSocket.unwrap">
<code>SSLSocket.unwrap()</code> </dt> <dd>
<p>Performs the SSL shutdown handshake, which removes the TLS layer from the underlying socket, and returns the underlying socket object. This can be used to go from encrypted operation over a connection to unencrypted. The returned socket should always be used for further communication with the other side of the connection, rather than the original socket.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLSocket.verify_client_post_handshake">
<code>SSLSocket.verify_client_post_handshake()</code> </dt> <dd>
<p>Requests post-handshake authentication (PHA) from a TLS 1.3 client. PHA can only be initiated for a TLS 1.3 connection from a server-side socket, after the initial TLS handshake and with PHA enabled on both sides, see <a class="reference internal" href="#ssl.SSLContext.post_handshake_auth" title="ssl.SSLContext.post_handshake_auth"><code>SSLContext.post_handshake_auth</code></a>.</p> <p>The method does not perform a cert exchange immediately. The server-side sends a CertificateRequest during the next write event and expects the client to respond with a certificate on the next read event.</p> <p>If any precondition isn’t met (e.g. not TLS 1.3, PHA not enabled), an <a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code>SSLError</code></a> is raised.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Only available with OpenSSL 1.1.1 and TLS 1.3 enabled. Without TLS 1.3 support, the method raises <a class="reference internal" href="exceptions#NotImplementedError" title="NotImplementedError"><code>NotImplementedError</code></a>.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLSocket.version">
<code>SSLSocket.version()</code> </dt> <dd>
<p>Return the actual SSL protocol version negotiated by the connection as a string, or <code>None</code> if no secure connection is established. As of this writing, possible return values include <code>"SSLv2"</code>, <code>"SSLv3"</code>, <code>"TLSv1"</code>, <code>"TLSv1.1"</code> and <code>"TLSv1.2"</code>. Recent OpenSSL versions may define more return values.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLSocket.pending">
<code>SSLSocket.pending()</code> </dt> <dd>
<p>Returns the number of already decrypted bytes available for read, pending on the connection.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLSocket.context">
<code>SSLSocket.context</code> </dt> <dd>
<p>The <a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code>SSLContext</code></a> object this SSL socket is tied to.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLSocket.server_side">
<code>SSLSocket.server_side</code> </dt> <dd>
<p>A boolean which is <code>True</code> for server-side sockets and <code>False</code> for client-side sockets.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLSocket.server_hostname">
<code>SSLSocket.server_hostname</code> </dt> <dd>
<p>Hostname of the server: <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> type, or <code>None</code> for server-side socket or if the hostname was not specified in the constructor.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>The attribute is now always ASCII text. When <code>server_hostname</code> is an internationalized domain name (IDN), this attribute now stores the A-label form (<code>"xn--pythn-mua.org"</code>), rather than the U-label form (<code>"pythön.org"</code>).</p> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLSocket.session">
<code>SSLSocket.session</code> </dt> <dd>
<p>The <a class="reference internal" href="#ssl.SSLSession" title="ssl.SSLSession"><code>SSLSession</code></a> for this SSL connection. The session is available for client and server side sockets after the TLS handshake has been performed. For client sockets the session can be set before <a class="reference internal" href="#ssl.SSLSocket.do_handshake" title="ssl.SSLSocket.do_handshake"><code>do_handshake()</code></a> has been called to reuse a session.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.</span></p> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLSocket.session_reused">
<code>SSLSocket.session_reused</code> </dt> <dd>
<div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.</span></p> </div> </dd>
</dl> </section> <section id="ssl-contexts"> <h2>SSL Contexts</h2> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> <p>An SSL context holds various data longer-lived than single SSL connections, such as SSL configuration options, certificate(s) and private key(s). It also manages a cache of SSL sessions for server-side sockets, in order to speed up repeated connections from the same clients.</p> <dl class="py class"> <dt class="sig sig-object py" id="ssl.SSLContext">
<code>class ssl.SSLContext(protocol=None)</code> </dt> <dd>
<p>Create a new SSL context. You may pass <em>protocol</em> which must be one of the <code>PROTOCOL_*</code> constants defined in this module. The parameter specifies which version of the SSL protocol to use. Typically, the server chooses a particular protocol version, and the client must adapt to the server’s choice. Most of the versions are not interoperable with the other versions. If not specified, the default is <a class="reference internal" href="#ssl.PROTOCOL_TLS" title="ssl.PROTOCOL_TLS"><code>PROTOCOL_TLS</code></a>; it provides the most compatibility with other versions.</p> <p>Here’s a table showing which versions in a client (down the side) can connect to which versions in a server (along the top):</p> <table class="docutils align-default">   <tr>
<td><p><em>client</em> / <strong>server</strong></p></td> <td><p><strong>SSLv2</strong></p></td> <td><p><strong>SSLv3</strong></p></td> <td><p><strong>TLS</strong> <a class="footnote-reference brackets" href="#id9" id="id1">3</a></p></td> <td><p><strong>TLSv1</strong></p></td> <td><p><strong>TLSv1.1</strong></p></td> <td><p><strong>TLSv1.2</strong></p></td> </tr> <tr>
<td><p><em>SSLv2</em></p></td> <td><p>yes</p></td> <td><p>no</p></td> <td><p>no <a class="footnote-reference brackets" href="#id7" id="id2">1</a></p></td> <td><p>no</p></td> <td><p>no</p></td> <td><p>no</p></td> </tr> <tr>
<td><p><em>SSLv3</em></p></td> <td><p>no</p></td> <td><p>yes</p></td> <td><p>no <a class="footnote-reference brackets" href="#id8" id="id3">2</a></p></td> <td><p>no</p></td> <td><p>no</p></td> <td><p>no</p></td> </tr> <tr>
<td><p><em>TLS</em> (<em>SSLv23</em>) <a class="footnote-reference brackets" href="#id9" id="id4">3</a></p></td> <td><p>no <a class="footnote-reference brackets" href="#id7" id="id5">1</a></p></td> <td><p>no <a class="footnote-reference brackets" href="#id8" id="id6">2</a></p></td> <td><p>yes</p></td> <td><p>yes</p></td> <td><p>yes</p></td> <td><p>yes</p></td> </tr> <tr>
<td><p><em>TLSv1</em></p></td> <td><p>no</p></td> <td><p>no</p></td> <td><p>yes</p></td> <td><p>yes</p></td> <td><p>no</p></td> <td><p>no</p></td> </tr> <tr>
<td><p><em>TLSv1.1</em></p></td> <td><p>no</p></td> <td><p>no</p></td> <td><p>yes</p></td> <td><p>no</p></td> <td><p>yes</p></td> <td><p>no</p></td> </tr> <tr>
<td><p><em>TLSv1.2</em></p></td> <td><p>no</p></td> <td><p>no</p></td> <td><p>yes</p></td> <td><p>no</p></td> <td><p>no</p></td> <td><p>yes</p></td> </tr>  </table> <h4 class="rubric">Footnotes</h4> <dl class="footnote brackets"> <dt class="label" id="id7">
<code>1(1,2)</code> </dt> <dd>
<p><a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code>SSLContext</code></a> disables SSLv2 with <a class="reference internal" href="#ssl.OP_NO_SSLv2" title="ssl.OP_NO_SSLv2"><code>OP_NO_SSLv2</code></a> by default.</p> </dd> <dt class="label" id="id8">
<code>2(1,2)</code> </dt> <dd>
<p><a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code>SSLContext</code></a> disables SSLv3 with <a class="reference internal" href="#ssl.OP_NO_SSLv3" title="ssl.OP_NO_SSLv3"><code>OP_NO_SSLv3</code></a> by default.</p> </dd> <dt class="label" id="id9">
<code>3(1,2)</code> </dt> <dd>
<p>TLS 1.3 protocol will be available with <a class="reference internal" href="#ssl.PROTOCOL_TLS" title="ssl.PROTOCOL_TLS"><code>PROTOCOL_TLS</code></a> in OpenSSL &gt;= 1.1.1. There is no dedicated PROTOCOL constant for just TLS 1.3.</p> </dd> </dl> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p><a class="reference internal" href="#ssl.create_default_context" title="ssl.create_default_context"><code>create_default_context()</code></a> lets the <a class="reference internal" href="#module-ssl" title="ssl: TLS/SSL wrapper for socket objects"><code>ssl</code></a> module choose security settings for a given purpose.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>The context is created with secure default values. The options <a class="reference internal" href="#ssl.OP_NO_COMPRESSION" title="ssl.OP_NO_COMPRESSION"><code>OP_NO_COMPRESSION</code></a>, <a class="reference internal" href="#ssl.OP_CIPHER_SERVER_PREFERENCE" title="ssl.OP_CIPHER_SERVER_PREFERENCE"><code>OP_CIPHER_SERVER_PREFERENCE</code></a>, <a class="reference internal" href="#ssl.OP_SINGLE_DH_USE" title="ssl.OP_SINGLE_DH_USE"><code>OP_SINGLE_DH_USE</code></a>, <a class="reference internal" href="#ssl.OP_SINGLE_ECDH_USE" title="ssl.OP_SINGLE_ECDH_USE"><code>OP_SINGLE_ECDH_USE</code></a>, <a class="reference internal" href="#ssl.OP_NO_SSLv2" title="ssl.OP_NO_SSLv2"><code>OP_NO_SSLv2</code></a>, and <a class="reference internal" href="#ssl.OP_NO_SSLv3" title="ssl.OP_NO_SSLv3"><code>OP_NO_SSLv3</code></a> (except for <a class="reference internal" href="#ssl.PROTOCOL_SSLv3" title="ssl.PROTOCOL_SSLv3"><code>PROTOCOL_SSLv3</code></a>) are set by default. The initial cipher suite list contains only <code>HIGH</code> ciphers, no <code>NULL</code> ciphers and no <code>MD5</code> ciphers.</p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.10: </span><a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code>SSLContext</code></a> without protocol argument is deprecated. The context class will either require <a class="reference internal" href="#ssl.PROTOCOL_TLS_CLIENT" title="ssl.PROTOCOL_TLS_CLIENT"><code>PROTOCOL_TLS_CLIENT</code></a> or <a class="reference internal" href="#ssl.PROTOCOL_TLS_SERVER" title="ssl.PROTOCOL_TLS_SERVER"><code>PROTOCOL_TLS_SERVER</code></a> protocol in the future.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>The default cipher suites now include only secure AES and ChaCha20 ciphers with forward secrecy and security level 2. RSA and DH keys with less than 2048 bits and ECC keys with less than 224 bits are prohibited. <a class="reference internal" href="#ssl.PROTOCOL_TLS" title="ssl.PROTOCOL_TLS"><code>PROTOCOL_TLS</code></a>, <a class="reference internal" href="#ssl.PROTOCOL_TLS_CLIENT" title="ssl.PROTOCOL_TLS_CLIENT"><code>PROTOCOL_TLS_CLIENT</code></a>, and <a class="reference internal" href="#ssl.PROTOCOL_TLS_SERVER" title="ssl.PROTOCOL_TLS_SERVER"><code>PROTOCOL_TLS_SERVER</code></a> use TLS 1.2 as minimum TLS version.</p> </div> </dd>
</dl> <p><a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code>SSLContext</code></a> objects have the following methods and attributes:</p> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLContext.cert_store_stats">
<code>SSLContext.cert_store_stats()</code> </dt> <dd>
<p>Get statistics about quantities of loaded X.509 certificates, count of X.509 certificates flagged as CA certificates and certificate revocation lists as dictionary.</p> <p>Example for a context with one CA cert and one other cert:</p> <pre data-language="python">&gt;&gt;&gt; context.cert_store_stats()
{'crl': 0, 'x509_ca': 1, 'x509': 2}
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLContext.load_cert_chain">
<code>SSLContext.load_cert_chain(certfile, keyfile=None, password=None)</code> </dt> <dd>
<p>Load a private key and the corresponding certificate. The <em>certfile</em> string must be the path to a single file in PEM format containing the certificate as well as any number of CA certificates needed to establish the certificate’s authenticity. The <em>keyfile</em> string, if present, must point to a file containing the private key. Otherwise the private key will be taken from <em>certfile</em> as well. See the discussion of <a class="reference internal" href="#ssl-certificates"><span class="std std-ref">Certificates</span></a> for more information on how the certificate is stored in the <em>certfile</em>.</p> <p>The <em>password</em> argument may be a function to call to get the password for decrypting the private key. It will only be called if the private key is encrypted and a password is necessary. It will be called with no arguments, and it should return a string, bytes, or bytearray. If the return value is a string it will be encoded as UTF-8 before using it to decrypt the key. Alternatively a string, bytes, or bytearray value may be supplied directly as the <em>password</em> argument. It will be ignored if the private key is not encrypted and no password is needed.</p> <p>If the <em>password</em> argument is not specified and a password is required, OpenSSL’s built-in password prompting mechanism will be used to interactively prompt the user for a password.</p> <p>An <a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code>SSLError</code></a> is raised if the private key doesn’t match with the certificate.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>New optional argument <em>password</em>.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLContext.load_default_certs">
<code>SSLContext.load_default_certs(purpose=Purpose.SERVER_AUTH)</code> </dt> <dd>
<p>Load a set of default “certification authority” (CA) certificates from default locations. On Windows it loads CA certs from the <code>CA</code> and <code>ROOT</code> system stores. On all systems it calls <a class="reference internal" href="#ssl.SSLContext.set_default_verify_paths" title="ssl.SSLContext.set_default_verify_paths"><code>SSLContext.set_default_verify_paths()</code></a>. In the future the method may load CA certificates from other locations, too.</p> <p>The <em>purpose</em> flag specifies what kind of CA certificates are loaded. The default settings <a class="reference internal" href="#ssl.Purpose.SERVER_AUTH" title="ssl.Purpose.SERVER_AUTH"><code>Purpose.SERVER_AUTH</code></a> loads certificates, that are flagged and trusted for TLS web server authentication (client side sockets). <a class="reference internal" href="#ssl.Purpose.CLIENT_AUTH" title="ssl.Purpose.CLIENT_AUTH"><code>Purpose.CLIENT_AUTH</code></a> loads CA certificates for client certificate verification on the server side.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLContext.load_verify_locations">
<code>SSLContext.load_verify_locations(cafile=None, capath=None, cadata=None)</code> </dt> <dd>
<p>Load a set of “certification authority” (CA) certificates used to validate other peers’ certificates when <a class="reference internal" href="#ssl.SSLContext.verify_mode" title="ssl.SSLContext.verify_mode"><code>verify_mode</code></a> is other than <a class="reference internal" href="#ssl.CERT_NONE" title="ssl.CERT_NONE"><code>CERT_NONE</code></a>. At least one of <em>cafile</em> or <em>capath</em> must be specified.</p> <p>This method can also load certification revocation lists (CRLs) in PEM or DER format. In order to make use of CRLs, <a class="reference internal" href="#ssl.SSLContext.verify_flags" title="ssl.SSLContext.verify_flags"><code>SSLContext.verify_flags</code></a> must be configured properly.</p> <p>The <em>cafile</em> string, if present, is the path to a file of concatenated CA certificates in PEM format. See the discussion of <a class="reference internal" href="#ssl-certificates"><span class="std std-ref">Certificates</span></a> for more information about how to arrange the certificates in this file.</p> <p>The <em>capath</em> string, if present, is the path to a directory containing several CA certificates in PEM format, following an <a class="reference external" href="https://www.openssl.org/docs/manmaster/man3/SSL_CTX_load_verify_locations.html">OpenSSL specific layout</a>.</p> <p>The <em>cadata</em> object, if present, is either an ASCII string of one or more PEM-encoded certificates or a <a class="reference internal" href="../glossary#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a> of DER-encoded certificates. Like with <em>capath</em> extra lines around PEM-encoded certificates are ignored but at least one certificate must be present.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>New optional argument <em>cadata</em></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLContext.get_ca_certs">
<code>SSLContext.get_ca_certs(binary_form=False)</code> </dt> <dd>
<p>Get a list of loaded “certification authority” (CA) certificates. If the <code>binary_form</code> parameter is <a class="reference internal" href="constants#False" title="False"><code>False</code></a> each list entry is a dict like the output of <a class="reference internal" href="#ssl.SSLSocket.getpeercert" title="ssl.SSLSocket.getpeercert"><code>SSLSocket.getpeercert()</code></a>. Otherwise the method returns a list of DER-encoded certificates. The returned list does not contain certificates from <em>capath</em> unless a certificate was requested and loaded by a SSL connection.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Certificates in a capath directory aren’t loaded unless they have been used at least once.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLContext.get_ciphers">
<code>SSLContext.get_ciphers()</code> </dt> <dd>
<p>Get a list of enabled ciphers. The list is in order of cipher priority. See <a class="reference internal" href="#ssl.SSLContext.set_ciphers" title="ssl.SSLContext.set_ciphers"><code>SSLContext.set_ciphers()</code></a>.</p> <p>Example:</p> <pre data-language="python">&gt;&gt;&gt; ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
&gt;&gt;&gt; ctx.set_ciphers('ECDHE+AESGCM:!ECDSA')
&gt;&gt;&gt; ctx.get_ciphers()
[{'aead': True,
  'alg_bits': 256,
  'auth': 'auth-rsa',
  'description': 'ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH     Au=RSA  '
                 'Enc=AESGCM(256) Mac=AEAD',
  'digest': None,
  'id': 50380848,
  'kea': 'kx-ecdhe',
  'name': 'ECDHE-RSA-AES256-GCM-SHA384',
  'protocol': 'TLSv1.2',
  'strength_bits': 256,
  'symmetric': 'aes-256-gcm'},
 {'aead': True,
  'alg_bits': 128,
  'auth': 'auth-rsa',
  'description': 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH     Au=RSA  '
                 'Enc=AESGCM(128) Mac=AEAD',
  'digest': None,
  'id': 50380847,
  'kea': 'kx-ecdhe',
  'name': 'ECDHE-RSA-AES128-GCM-SHA256',
  'protocol': 'TLSv1.2',
  'strength_bits': 128,
  'symmetric': 'aes-128-gcm'}]
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLContext.set_default_verify_paths">
<code>SSLContext.set_default_verify_paths()</code> </dt> <dd>
<p>Load a set of default “certification authority” (CA) certificates from a filesystem path defined when building the OpenSSL library. Unfortunately, there’s no easy way to know whether this method succeeds: no error is returned if no certificates are to be found. When the OpenSSL library is provided as part of the operating system, though, it is likely to be configured properly.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLContext.set_ciphers">
<code>SSLContext.set_ciphers(ciphers)</code> </dt> <dd>
<p>Set the available ciphers for sockets created with this context. It should be a string in the <a class="reference external" href="https://www.openssl.org/docs/manmaster/man1/ciphers.html">OpenSSL cipher list format</a>. If no cipher can be selected (because compile-time options or other configuration forbids use of all the specified ciphers), an <a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code>SSLError</code></a> will be raised.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>when connected, the <a class="reference internal" href="#ssl.SSLSocket.cipher" title="ssl.SSLSocket.cipher"><code>SSLSocket.cipher()</code></a> method of SSL sockets will give the currently selected cipher.</p> <p>TLS 1.3 cipher suites cannot be disabled with <a class="reference internal" href="#ssl.SSLContext.set_ciphers" title="ssl.SSLContext.set_ciphers"><code>set_ciphers()</code></a>.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLContext.set_alpn_protocols">
<code>SSLContext.set_alpn_protocols(protocols)</code> </dt> <dd>
<p>Specify which protocols the socket should advertise during the SSL/TLS handshake. It should be a list of ASCII strings, like <code>['http/1.1',
'spdy/2']</code>, ordered by preference. The selection of a protocol will happen during the handshake, and will play out according to <span class="target" id="index-12"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc7301.html"><strong>RFC 7301</strong></a>. After a successful handshake, the <a class="reference internal" href="#ssl.SSLSocket.selected_alpn_protocol" title="ssl.SSLSocket.selected_alpn_protocol"><code>SSLSocket.selected_alpn_protocol()</code></a> method will return the agreed-upon protocol.</p> <p>This method will raise <a class="reference internal" href="exceptions#NotImplementedError" title="NotImplementedError"><code>NotImplementedError</code></a> if <a class="reference internal" href="#ssl.HAS_ALPN" title="ssl.HAS_ALPN"><code>HAS_ALPN</code></a> is <code>False</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLContext.set_npn_protocols">
<code>SSLContext.set_npn_protocols(protocols)</code> </dt> <dd>
<p>Specify which protocols the socket should advertise during the SSL/TLS handshake. It should be a list of strings, like <code>['http/1.1', 'spdy/2']</code>, ordered by preference. The selection of a protocol will happen during the handshake, and will play out according to the <a class="reference external" href="https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation">Application Layer Protocol Negotiation</a>. After a successful handshake, the <a class="reference internal" href="#ssl.SSLSocket.selected_npn_protocol" title="ssl.SSLSocket.selected_npn_protocol"><code>SSLSocket.selected_npn_protocol()</code></a> method will return the agreed-upon protocol.</p> <p>This method will raise <a class="reference internal" href="exceptions#NotImplementedError" title="NotImplementedError"><code>NotImplementedError</code></a> if <a class="reference internal" href="#ssl.HAS_NPN" title="ssl.HAS_NPN"><code>HAS_NPN</code></a> is <code>False</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.10: </span>NPN has been superseded by ALPN</p> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLContext.sni_callback">
<code>SSLContext.sni_callback</code> </dt> <dd>
<p>Register a callback function that will be called after the TLS Client Hello handshake message has been received by the SSL/TLS server when the TLS client specifies a server name indication. The server name indication mechanism is specified in <span class="target" id="index-13"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc6066.html"><strong>RFC 6066</strong></a> section 3 - Server Name Indication.</p> <p>Only one callback can be set per <code>SSLContext</code>. If <em>sni_callback</em> is set to <code>None</code> then the callback is disabled. Calling this function a subsequent time will disable the previously registered callback.</p> <p>The callback function will be called with three arguments; the first being the <a class="reference internal" href="#ssl.SSLSocket" title="ssl.SSLSocket"><code>ssl.SSLSocket</code></a>, the second is a string that represents the server name that the client is intending to communicate (or <a class="reference internal" href="constants#None" title="None"><code>None</code></a> if the TLS Client Hello does not contain a server name) and the third argument is the original <a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code>SSLContext</code></a>. The server name argument is text. For internationalized domain name, the server name is an IDN A-label (<code>"xn--pythn-mua.org"</code>).</p> <p>A typical use of this callback is to change the <a class="reference internal" href="#ssl.SSLSocket" title="ssl.SSLSocket"><code>ssl.SSLSocket</code></a>’s <a class="reference internal" href="#ssl.SSLSocket.context" title="ssl.SSLSocket.context"><code>SSLSocket.context</code></a> attribute to a new object of type <a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code>SSLContext</code></a> representing a certificate chain that matches the server name.</p> <p>Due to the early negotiation phase of the TLS connection, only limited methods and attributes are usable like <a class="reference internal" href="#ssl.SSLSocket.selected_alpn_protocol" title="ssl.SSLSocket.selected_alpn_protocol"><code>SSLSocket.selected_alpn_protocol()</code></a> and <a class="reference internal" href="#ssl.SSLSocket.context" title="ssl.SSLSocket.context"><code>SSLSocket.context</code></a>. The <a class="reference internal" href="#ssl.SSLSocket.getpeercert" title="ssl.SSLSocket.getpeercert"><code>SSLSocket.getpeercert()</code></a>, <a class="reference internal" href="#ssl.SSLSocket.cipher" title="ssl.SSLSocket.cipher"><code>SSLSocket.cipher()</code></a> and <a class="reference internal" href="#ssl.SSLSocket.compression" title="ssl.SSLSocket.compression"><code>SSLSocket.compression()</code></a> methods require that the TLS connection has progressed beyond the TLS Client Hello and therefore will not return meaningful values nor can they be called safely.</p> <p>The <em>sni_callback</em> function must return <code>None</code> to allow the TLS negotiation to continue. If a TLS failure is required, a constant <a class="reference internal" href="#ssl.ALERT_DESCRIPTION_INTERNAL_ERROR" title="ssl.ALERT_DESCRIPTION_INTERNAL_ERROR"><code>ALERT_DESCRIPTION_*</code></a> can be returned. Other return values will result in a TLS fatal error with <a class="reference internal" href="#ssl.ALERT_DESCRIPTION_INTERNAL_ERROR" title="ssl.ALERT_DESCRIPTION_INTERNAL_ERROR"><code>ALERT_DESCRIPTION_INTERNAL_ERROR</code></a>.</p> <p>If an exception is raised from the <em>sni_callback</em> function the TLS connection will terminate with a fatal TLS alert message <a class="reference internal" href="#ssl.ALERT_DESCRIPTION_HANDSHAKE_FAILURE" title="ssl.ALERT_DESCRIPTION_HANDSHAKE_FAILURE"><code>ALERT_DESCRIPTION_HANDSHAKE_FAILURE</code></a>.</p> <p>This method will raise <a class="reference internal" href="exceptions#NotImplementedError" title="NotImplementedError"><code>NotImplementedError</code></a> if the OpenSSL library had OPENSSL_NO_TLSEXT defined when it was built.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLContext.set_servername_callback">
<code>SSLContext.set_servername_callback(server_name_callback)</code> </dt> <dd>
<p>This is a legacy API retained for backwards compatibility. When possible, you should use <a class="reference internal" href="#ssl.SSLContext.sni_callback" title="ssl.SSLContext.sni_callback"><code>sni_callback</code></a> instead. The given <em>server_name_callback</em> is similar to <em>sni_callback</em>, except that when the server hostname is an IDN-encoded internationalized domain name, the <em>server_name_callback</em> receives a decoded U-label (<code>"pythön.org"</code>).</p> <p>If there is an decoding error on the server name, the TLS connection will terminate with an <a class="reference internal" href="#ssl.ALERT_DESCRIPTION_INTERNAL_ERROR" title="ssl.ALERT_DESCRIPTION_INTERNAL_ERROR"><code>ALERT_DESCRIPTION_INTERNAL_ERROR</code></a> fatal TLS alert message to the client.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLContext.load_dh_params">
<code>SSLContext.load_dh_params(dhfile)</code> </dt> <dd>
<p>Load the key generation parameters for Diffie-Hellman (DH) key exchange. Using DH key exchange improves forward secrecy at the expense of computational resources (both on the server and on the client). The <em>dhfile</em> parameter should be the path to a file containing DH parameters in PEM format.</p> <p>This setting doesn’t apply to client sockets. You can also use the <a class="reference internal" href="#ssl.OP_SINGLE_DH_USE" title="ssl.OP_SINGLE_DH_USE"><code>OP_SINGLE_DH_USE</code></a> option to further improve security.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLContext.set_ecdh_curve">
<code>SSLContext.set_ecdh_curve(curve_name)</code> </dt> <dd>
<p>Set the curve name for Elliptic Curve-based Diffie-Hellman (ECDH) key exchange. ECDH is significantly faster than regular DH while arguably as secure. The <em>curve_name</em> parameter should be a string describing a well-known elliptic curve, for example <code>prime256v1</code> for a widely supported curve.</p> <p>This setting doesn’t apply to client sockets. You can also use the <a class="reference internal" href="#ssl.OP_SINGLE_ECDH_USE" title="ssl.OP_SINGLE_ECDH_USE"><code>OP_SINGLE_ECDH_USE</code></a> option to further improve security.</p> <p>This method is not available if <a class="reference internal" href="#ssl.HAS_ECDH" title="ssl.HAS_ECDH"><code>HAS_ECDH</code></a> is <code>False</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3.</span></p> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt><a class="reference external" href="https://vincent.bernat.ch/en/blog/2011-ssl-perfect-forward-secrecy">SSL/TLS &amp; Perfect Forward Secrecy</a></dt>
<dd>
<p>Vincent Bernat.</p> </dd> </dl> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLContext.wrap_socket">
<code>SSLContext.wrap_socket(sock, server_side=False, do_handshake_on_connect=True, suppress_ragged_eofs=True, server_hostname=None, session=None)</code> </dt> <dd>
<p>Wrap an existing Python socket <em>sock</em> and return an instance of <a class="reference internal" href="#ssl.SSLContext.sslsocket_class" title="ssl.SSLContext.sslsocket_class"><code>SSLContext.sslsocket_class</code></a> (default <a class="reference internal" href="#ssl.SSLSocket" title="ssl.SSLSocket"><code>SSLSocket</code></a>). The returned SSL socket is tied to the context, its settings and certificates. <em>sock</em> must be a <a class="reference internal" href="socket#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code>SOCK_STREAM</code></a> socket; other socket types are unsupported.</p> <p>The parameter <code>server_side</code> is a boolean which identifies whether server-side or client-side behavior is desired from this socket.</p> <p>For client-side sockets, the context construction is lazy; if the underlying socket isn’t connected yet, the context construction will be performed after <code>connect()</code> is called on the socket. For server-side sockets, if the socket has no remote peer, it is assumed to be a listening socket, and the server-side SSL wrapping is automatically performed on client connections accepted via the <code>accept()</code> method. The method may raise <a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code>SSLError</code></a>.</p> <p>On client connections, the optional parameter <em>server_hostname</em> specifies the hostname of the service which we are connecting to. This allows a single server to host multiple SSL-based services with distinct certificates, quite similarly to HTTP virtual hosts. Specifying <em>server_hostname</em> will raise a <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> if <em>server_side</em> is true.</p> <p>The parameter <code>do_handshake_on_connect</code> specifies whether to do the SSL handshake automatically after doing a <code>socket.connect()</code>, or whether the application program will call it explicitly, by invoking the <a class="reference internal" href="#ssl.SSLSocket.do_handshake" title="ssl.SSLSocket.do_handshake"><code>SSLSocket.do_handshake()</code></a> method. Calling <a class="reference internal" href="#ssl.SSLSocket.do_handshake" title="ssl.SSLSocket.do_handshake"><code>SSLSocket.do_handshake()</code></a> explicitly gives the program control over the blocking behavior of the socket I/O involved in the handshake.</p> <p>The parameter <code>suppress_ragged_eofs</code> specifies how the <code>SSLSocket.recv()</code> method should signal unexpected EOF from the other end of the connection. If specified as <a class="reference internal" href="constants#True" title="True"><code>True</code></a> (the default), it returns a normal EOF (an empty bytes object) in response to unexpected EOF errors raised from the underlying socket; if <a class="reference internal" href="constants#False" title="False"><code>False</code></a>, it will raise the exceptions back to the caller.</p> <p><em>session</em>, see <a class="reference internal" href="#ssl.SSLSocket.session" title="ssl.SSLSocket.session"><code>session</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>Always allow a server_hostname to be passed, even if OpenSSL does not have SNI.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span><em>session</em> argument was added.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>The method returns an instance of <a class="reference internal" href="#ssl.SSLContext.sslsocket_class" title="ssl.SSLContext.sslsocket_class"><code>SSLContext.sslsocket_class</code></a> instead of hard-coded <a class="reference internal" href="#ssl.SSLSocket" title="ssl.SSLSocket"><code>SSLSocket</code></a>.</p> </div> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLContext.sslsocket_class">
<code>SSLContext.sslsocket_class</code> </dt> <dd>
<p>The return type of <a class="reference internal" href="#ssl.SSLContext.wrap_socket" title="ssl.SSLContext.wrap_socket"><code>SSLContext.wrap_socket()</code></a>, defaults to <a class="reference internal" href="#ssl.SSLSocket" title="ssl.SSLSocket"><code>SSLSocket</code></a>. The attribute can be overridden on instance of class in order to return a custom subclass of <a class="reference internal" href="#ssl.SSLSocket" title="ssl.SSLSocket"><code>SSLSocket</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLContext.wrap_bio">
<code>SSLContext.wrap_bio(incoming, outgoing, server_side=False, server_hostname=None, session=None)</code> </dt> <dd>
<p>Wrap the BIO objects <em>incoming</em> and <em>outgoing</em> and return an instance of <a class="reference internal" href="#ssl.SSLContext.sslobject_class" title="ssl.SSLContext.sslobject_class"><code>SSLContext.sslobject_class</code></a> (default <a class="reference internal" href="#ssl.SSLObject" title="ssl.SSLObject"><code>SSLObject</code></a>). The SSL routines will read input data from the incoming BIO and write data to the outgoing BIO.</p> <p>The <em>server_side</em>, <em>server_hostname</em> and <em>session</em> parameters have the same meaning as in <a class="reference internal" href="#ssl.SSLContext.wrap_socket" title="ssl.SSLContext.wrap_socket"><code>SSLContext.wrap_socket()</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span><em>session</em> argument was added.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>The method returns an instance of <a class="reference internal" href="#ssl.SSLContext.sslobject_class" title="ssl.SSLContext.sslobject_class"><code>SSLContext.sslobject_class</code></a> instead of hard-coded <a class="reference internal" href="#ssl.SSLObject" title="ssl.SSLObject"><code>SSLObject</code></a>.</p> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLContext.sslobject_class">
<code>SSLContext.sslobject_class</code> </dt> <dd>
<p>The return type of <a class="reference internal" href="#ssl.SSLContext.wrap_bio" title="ssl.SSLContext.wrap_bio"><code>SSLContext.wrap_bio()</code></a>, defaults to <a class="reference internal" href="#ssl.SSLObject" title="ssl.SSLObject"><code>SSLObject</code></a>. The attribute can be overridden on instance of class in order to return a custom subclass of <a class="reference internal" href="#ssl.SSLObject" title="ssl.SSLObject"><code>SSLObject</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.SSLContext.session_stats">
<code>SSLContext.session_stats()</code> </dt> <dd>
<p>Get statistics about the SSL sessions created or managed by this context. A dictionary is returned which maps the names of each <a class="reference external" href="https://www.openssl.org/docs/man1.1.1/man3/SSL_CTX_sess_number.html">piece of information</a> to their numeric values. For example, here is the total number of hits and misses in the session cache since the context was created:</p> <pre data-language="python">&gt;&gt;&gt; stats = context.session_stats()
&gt;&gt;&gt; stats['hits'], stats['misses']
(0, 0)
</pre> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLContext.check_hostname">
<code>SSLContext.check_hostname</code> </dt> <dd>
<p>Whether to match the peer cert’s hostname in <a class="reference internal" href="#ssl.SSLSocket.do_handshake" title="ssl.SSLSocket.do_handshake"><code>SSLSocket.do_handshake()</code></a>. The context’s <a class="reference internal" href="#ssl.SSLContext.verify_mode" title="ssl.SSLContext.verify_mode"><code>verify_mode</code></a> must be set to <a class="reference internal" href="#ssl.CERT_OPTIONAL" title="ssl.CERT_OPTIONAL"><code>CERT_OPTIONAL</code></a> or <a class="reference internal" href="#ssl.CERT_REQUIRED" title="ssl.CERT_REQUIRED"><code>CERT_REQUIRED</code></a>, and you must pass <em>server_hostname</em> to <a class="reference internal" href="#ssl.SSLContext.wrap_socket" title="ssl.SSLContext.wrap_socket"><code>wrap_socket()</code></a> in order to match the hostname. Enabling hostname checking automatically sets <a class="reference internal" href="#ssl.SSLContext.verify_mode" title="ssl.SSLContext.verify_mode"><code>verify_mode</code></a> from <a class="reference internal" href="#ssl.CERT_NONE" title="ssl.CERT_NONE"><code>CERT_NONE</code></a> to <a class="reference internal" href="#ssl.CERT_REQUIRED" title="ssl.CERT_REQUIRED"><code>CERT_REQUIRED</code></a>. It cannot be set back to <a class="reference internal" href="#ssl.CERT_NONE" title="ssl.CERT_NONE"><code>CERT_NONE</code></a> as long as hostname checking is enabled. The <a class="reference internal" href="#ssl.PROTOCOL_TLS_CLIENT" title="ssl.PROTOCOL_TLS_CLIENT"><code>PROTOCOL_TLS_CLIENT</code></a> protocol enables hostname checking by default. With other protocols, hostname checking must be enabled explicitly.</p> <p>Example:</p> <pre data-language="python">import socket, ssl

context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
context.verify_mode = ssl.CERT_REQUIRED
context.check_hostname = True
context.load_default_certs()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = context.wrap_socket(s, server_hostname='www.verisign.com')
ssl_sock.connect(('www.verisign.com', 443))
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span><a class="reference internal" href="#ssl.SSLContext.verify_mode" title="ssl.SSLContext.verify_mode"><code>verify_mode</code></a> is now automatically changed to <a class="reference internal" href="#ssl.CERT_REQUIRED" title="ssl.CERT_REQUIRED"><code>CERT_REQUIRED</code></a> when hostname checking is enabled and <a class="reference internal" href="#ssl.SSLContext.verify_mode" title="ssl.SSLContext.verify_mode"><code>verify_mode</code></a> is <a class="reference internal" href="#ssl.CERT_NONE" title="ssl.CERT_NONE"><code>CERT_NONE</code></a>. Previously the same operation would have failed with a <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a>.</p> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLContext.keylog_filename">
<code>SSLContext.keylog_filename</code> </dt> <dd>
<p>Write TLS keys to a keylog file, whenever key material is generated or received. The keylog file is designed for debugging purposes only. The file format is specified by NSS and used by many traffic analyzers such as Wireshark. The log file is opened in append-only mode. Writes are synchronized between threads, but not between processes.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLContext.maximum_version">
<code>SSLContext.maximum_version</code> </dt> <dd>
<p>A <a class="reference internal" href="#ssl.TLSVersion" title="ssl.TLSVersion"><code>TLSVersion</code></a> enum member representing the highest supported TLS version. The value defaults to <a class="reference internal" href="#ssl.TLSVersion.MAXIMUM_SUPPORTED" title="ssl.TLSVersion.MAXIMUM_SUPPORTED"><code>TLSVersion.MAXIMUM_SUPPORTED</code></a>. The attribute is read-only for protocols other than <a class="reference internal" href="#ssl.PROTOCOL_TLS" title="ssl.PROTOCOL_TLS"><code>PROTOCOL_TLS</code></a>, <a class="reference internal" href="#ssl.PROTOCOL_TLS_CLIENT" title="ssl.PROTOCOL_TLS_CLIENT"><code>PROTOCOL_TLS_CLIENT</code></a>, and <a class="reference internal" href="#ssl.PROTOCOL_TLS_SERVER" title="ssl.PROTOCOL_TLS_SERVER"><code>PROTOCOL_TLS_SERVER</code></a>.</p> <p>The attributes <a class="reference internal" href="#ssl.SSLContext.maximum_version" title="ssl.SSLContext.maximum_version"><code>maximum_version</code></a>, <a class="reference internal" href="#ssl.SSLContext.minimum_version" title="ssl.SSLContext.minimum_version"><code>minimum_version</code></a> and <a class="reference internal" href="#ssl.SSLContext.options" title="ssl.SSLContext.options"><code>SSLContext.options</code></a> all affect the supported SSL and TLS versions of the context. The implementation does not prevent invalid combination. For example a context with <a class="reference internal" href="#ssl.OP_NO_TLSv1_2" title="ssl.OP_NO_TLSv1_2"><code>OP_NO_TLSv1_2</code></a> in <a class="reference internal" href="#ssl.SSLContext.options" title="ssl.SSLContext.options"><code>options</code></a> and <a class="reference internal" href="#ssl.SSLContext.maximum_version" title="ssl.SSLContext.maximum_version"><code>maximum_version</code></a> set to <a class="reference internal" href="#ssl.TLSVersion.TLSv1_2" title="ssl.TLSVersion.TLSv1_2"><code>TLSVersion.TLSv1_2</code></a> will not be able to establish a TLS 1.2 connection.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLContext.minimum_version">
<code>SSLContext.minimum_version</code> </dt> <dd>
<p>Like <a class="reference internal" href="#ssl.SSLContext.maximum_version" title="ssl.SSLContext.maximum_version"><code>SSLContext.maximum_version</code></a> except it is the lowest supported version or <a class="reference internal" href="#ssl.TLSVersion.MINIMUM_SUPPORTED" title="ssl.TLSVersion.MINIMUM_SUPPORTED"><code>TLSVersion.MINIMUM_SUPPORTED</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLContext.num_tickets">
<code>SSLContext.num_tickets</code> </dt> <dd>
<p>Control the number of TLS 1.3 session tickets of a <a class="reference internal" href="#ssl.PROTOCOL_TLS_SERVER" title="ssl.PROTOCOL_TLS_SERVER"><code>PROTOCOL_TLS_SERVER</code></a> context. The setting has no impact on TLS 1.0 to 1.2 connections.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLContext.options">
<code>SSLContext.options</code> </dt> <dd>
<p>An integer representing the set of SSL options enabled on this context. The default value is <a class="reference internal" href="#ssl.OP_ALL" title="ssl.OP_ALL"><code>OP_ALL</code></a>, but you can specify other options such as <a class="reference internal" href="#ssl.OP_NO_SSLv2" title="ssl.OP_NO_SSLv2"><code>OP_NO_SSLv2</code></a> by ORing them together.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span><a class="reference internal" href="#ssl.SSLContext.options" title="ssl.SSLContext.options"><code>SSLContext.options</code></a> returns <a class="reference internal" href="#ssl.Options" title="ssl.Options"><code>Options</code></a> flags:</p> <pre data-language="python">&gt;&gt;&gt; ssl.create_default_context().options  
&lt;Options.OP_ALL|OP_NO_SSLv3|OP_NO_SSLv2|OP_NO_COMPRESSION: 2197947391&gt;
</pre> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.7: </span>All <code>OP_NO_SSL*</code> and <code>OP_NO_TLS*</code> options have been deprecated since Python 3.7. Use <a class="reference internal" href="#ssl.SSLContext.minimum_version" title="ssl.SSLContext.minimum_version"><code>SSLContext.minimum_version</code></a> and <a class="reference internal" href="#ssl.SSLContext.maximum_version" title="ssl.SSLContext.maximum_version"><code>SSLContext.maximum_version</code></a> instead.</p> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLContext.post_handshake_auth">
<code>SSLContext.post_handshake_auth</code> </dt> <dd>
<p>Enable TLS 1.3 post-handshake client authentication. Post-handshake auth is disabled by default and a server can only request a TLS client certificate during the initial handshake. When enabled, a server may request a TLS client certificate at any time after the handshake.</p> <p>When enabled on client-side sockets, the client signals the server that it supports post-handshake authentication.</p> <p>When enabled on server-side sockets, <a class="reference internal" href="#ssl.SSLContext.verify_mode" title="ssl.SSLContext.verify_mode"><code>SSLContext.verify_mode</code></a> must be set to <a class="reference internal" href="#ssl.CERT_OPTIONAL" title="ssl.CERT_OPTIONAL"><code>CERT_OPTIONAL</code></a> or <a class="reference internal" href="#ssl.CERT_REQUIRED" title="ssl.CERT_REQUIRED"><code>CERT_REQUIRED</code></a>, too. The actual client cert exchange is delayed until <a class="reference internal" href="#ssl.SSLSocket.verify_client_post_handshake" title="ssl.SSLSocket.verify_client_post_handshake"><code>SSLSocket.verify_client_post_handshake()</code></a> is called and some I/O is performed.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLContext.protocol">
<code>SSLContext.protocol</code> </dt> <dd>
<p>The protocol version chosen when constructing the context. This attribute is read-only.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLContext.hostname_checks_common_name">
<code>SSLContext.hostname_checks_common_name</code> </dt> <dd>
<p>Whether <a class="reference internal" href="#ssl.SSLContext.check_hostname" title="ssl.SSLContext.check_hostname"><code>check_hostname</code></a> falls back to verify the cert’s subject common name in the absence of a subject alternative name extension (default: true).</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>The flag had no effect with OpenSSL before version 1.1.1k. Python 3.8.9, 3.9.3, and 3.10 include workarounds for previous versions.</p> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLContext.security_level">
<code>SSLContext.security_level</code> </dt> <dd>
<p>An integer representing the <a class="reference external" href="https://www.openssl.org/docs/manmaster/man3/SSL_CTX_get_security_level.html">security level</a> for the context. This attribute is read-only.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLContext.verify_flags">
<code>SSLContext.verify_flags</code> </dt> <dd>
<p>The flags for certificate verification operations. You can set flags like <a class="reference internal" href="#ssl.VERIFY_CRL_CHECK_LEAF" title="ssl.VERIFY_CRL_CHECK_LEAF"><code>VERIFY_CRL_CHECK_LEAF</code></a> by ORing them together. By default OpenSSL does neither require nor verify certificate revocation lists (CRLs).</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span><a class="reference internal" href="#ssl.SSLContext.verify_flags" title="ssl.SSLContext.verify_flags"><code>SSLContext.verify_flags</code></a> returns <a class="reference internal" href="#ssl.VerifyFlags" title="ssl.VerifyFlags"><code>VerifyFlags</code></a> flags:</p> <pre data-language="python">&gt;&gt;&gt; ssl.create_default_context().verify_flags  
&lt;VerifyFlags.VERIFY_X509_TRUSTED_FIRST: 32768&gt;
</pre> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLContext.verify_mode">
<code>SSLContext.verify_mode</code> </dt> <dd>
<p>Whether to try to verify other peers’ certificates and how to behave if verification fails. This attribute must be one of <a class="reference internal" href="#ssl.CERT_NONE" title="ssl.CERT_NONE"><code>CERT_NONE</code></a>, <a class="reference internal" href="#ssl.CERT_OPTIONAL" title="ssl.CERT_OPTIONAL"><code>CERT_OPTIONAL</code></a> or <a class="reference internal" href="#ssl.CERT_REQUIRED" title="ssl.CERT_REQUIRED"><code>CERT_REQUIRED</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span><a class="reference internal" href="#ssl.SSLContext.verify_mode" title="ssl.SSLContext.verify_mode"><code>SSLContext.verify_mode</code></a> returns <a class="reference internal" href="#ssl.VerifyMode" title="ssl.VerifyMode"><code>VerifyMode</code></a> enum:</p> <pre data-language="python">&gt;&gt;&gt; ssl.create_default_context().verify_mode  
&lt;VerifyMode.CERT_REQUIRED: 2&gt;
</pre> </div> </dd>
</dl> <span class="target" id="index-14"></span></section> <section id="certificates"> <span id="ssl-certificates"></span><span id="index-15"></span><h2>Certificates</h2> <p>Certificates in general are part of a public-key / private-key system. In this system, each <em>principal</em>, (which may be a machine, or a person, or an organization) is assigned a unique two-part encryption key. One part of the key is public, and is called the <em>public key</em>; the other part is kept secret, and is called the <em>private key</em>. The two parts are related, in that if you encrypt a message with one of the parts, you can decrypt it with the other part, and <strong>only</strong> with the other part.</p> <p>A certificate contains information about two principals. It contains the name of a <em>subject</em>, and the subject’s public key. It also contains a statement by a second principal, the <em>issuer</em>, that the subject is who they claim to be, and that this is indeed the subject’s public key. The issuer’s statement is signed with the issuer’s private key, which only the issuer knows. However, anyone can verify the issuer’s statement by finding the issuer’s public key, decrypting the statement with it, and comparing it to the other information in the certificate. The certificate also contains information about the time period over which it is valid. This is expressed as two fields, called “notBefore” and “notAfter”.</p> <p>In the Python use of certificates, a client or server can use a certificate to prove who they are. The other side of a network connection can also be required to produce a certificate, and that certificate can be validated to the satisfaction of the client or server that requires such validation. The connection attempt can be set to raise an exception if the validation fails. Validation is done automatically, by the underlying OpenSSL framework; the application need not concern itself with its mechanics. But the application does usually need to provide sets of certificates to allow this process to take place.</p> <p>Python uses files to contain certificates. They should be formatted as “PEM” (see <span class="target" id="index-16"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc1422.html"><strong>RFC 1422</strong></a>), which is a base-64 encoded form wrapped with a header line and a footer line:</p> <pre data-language="python">-----BEGIN CERTIFICATE-----
... (certificate in base64 PEM encoding) ...
-----END CERTIFICATE-----
</pre> <section id="certificate-chains"> <h3>Certificate chains</h3> <p>The Python files which contain certificates can contain a sequence of certificates, sometimes called a <em>certificate chain</em>. This chain should start with the specific certificate for the principal who “is” the client or server, and then the certificate for the issuer of that certificate, and then the certificate for the issuer of <em>that</em> certificate, and so on up the chain till you get to a certificate which is <em>self-signed</em>, that is, a certificate which has the same subject and issuer, sometimes called a <em>root certificate</em>. The certificates should just be concatenated together in the certificate file. For example, suppose we had a three certificate chain, from our server certificate to the certificate of the certification authority that signed our server certificate, to the root certificate of the agency which issued the certification authority’s certificate:</p> <pre data-language="python">-----BEGIN CERTIFICATE-----
... (certificate for your server)...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
... (the certificate for the CA)...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
... (the root certificate for the CA's issuer)...
-----END CERTIFICATE-----
</pre> </section> <section id="ca-certificates"> <h3>CA certificates</h3> <p>If you are going to require validation of the other side of the connection’s certificate, you need to provide a “CA certs” file, filled with the certificate chains for each issuer you are willing to trust. Again, this file just contains these chains concatenated together. For validation, Python will use the first chain it finds in the file which matches. The platform’s certificates file can be used by calling <a class="reference internal" href="#ssl.SSLContext.load_default_certs" title="ssl.SSLContext.load_default_certs"><code>SSLContext.load_default_certs()</code></a>, this is done automatically with <a class="reference internal" href="#ssl.create_default_context" title="ssl.create_default_context"><code>create_default_context()</code></a>.</p> </section> <section id="combined-key-and-certificate"> <h3>Combined key and certificate</h3> <p>Often the private key is stored in the same file as the certificate; in this case, only the <code>certfile</code> parameter to <a class="reference internal" href="#ssl.SSLContext.load_cert_chain" title="ssl.SSLContext.load_cert_chain"><code>SSLContext.load_cert_chain()</code></a> needs to be passed. If the private key is stored with the certificate, it should come before the first certificate in the certificate chain:</p> <pre data-language="python">-----BEGIN RSA PRIVATE KEY-----
... (private key in base64 encoding) ...
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
... (certificate in base64 PEM encoding) ...
-----END CERTIFICATE-----
</pre> </section> <section id="self-signed-certificates"> <h3>Self-signed certificates</h3> <p>If you are going to create a server that provides SSL-encrypted connection services, you will need to acquire a certificate for that service. There are many ways of acquiring appropriate certificates, such as buying one from a certification authority. Another common practice is to generate a self-signed certificate. The simplest way to do this is with the OpenSSL package, using something like the following:</p> <pre data-language="python">% openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
Generating a 1024 bit RSA private key
.......++++++
.............................++++++
writing new private key to 'cert.pem'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:MyState
Locality Name (eg, city) []:Some City
Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
Organizational Unit Name (eg, section) []:My Group
Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
Email Address []:ops@myserver.mygroup.myorganization.com
%
</pre> <p>The disadvantage of a self-signed certificate is that it is its own root certificate, and no one else will have it in their cache of known (and trusted) root certificates.</p> </section> </section> <section id="examples"> <h2>Examples</h2> <section id="testing-for-ssl-support"> <h3>Testing for SSL support</h3> <p>To test for the presence of SSL support in a Python installation, user code should use the following idiom:</p> <pre data-language="python">try:
    import ssl
except ImportError:
    pass
else:
    ...  # do something that requires SSL support
</pre> </section> <section id="client-side-operation"> <h3>Client-side operation</h3> <p>This example creates a SSL context with the recommended security settings for client sockets, including automatic certificate verification:</p> <pre data-language="python">&gt;&gt;&gt; context = ssl.create_default_context()
</pre> <p>If you prefer to tune security settings yourself, you might create a context from scratch (but beware that you might not get the settings right):</p> <pre data-language="python">&gt;&gt;&gt; context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
&gt;&gt;&gt; context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")
</pre> <p>(this snippet assumes your operating system places a bundle of all CA certificates in <code>/etc/ssl/certs/ca-bundle.crt</code>; if not, you’ll get an error and have to adjust the location)</p> <p>The <a class="reference internal" href="#ssl.PROTOCOL_TLS_CLIENT" title="ssl.PROTOCOL_TLS_CLIENT"><code>PROTOCOL_TLS_CLIENT</code></a> protocol configures the context for cert validation and hostname verification. <a class="reference internal" href="#ssl.SSLContext.verify_mode" title="ssl.SSLContext.verify_mode"><code>verify_mode</code></a> is set to <a class="reference internal" href="#ssl.CERT_REQUIRED" title="ssl.CERT_REQUIRED"><code>CERT_REQUIRED</code></a> and <a class="reference internal" href="#ssl.SSLContext.check_hostname" title="ssl.SSLContext.check_hostname"><code>check_hostname</code></a> is set to <code>True</code>. All other protocols create SSL contexts with insecure defaults.</p> <p>When you use the context to connect to a server, <a class="reference internal" href="#ssl.CERT_REQUIRED" title="ssl.CERT_REQUIRED"><code>CERT_REQUIRED</code></a> and <a class="reference internal" href="#ssl.SSLContext.check_hostname" title="ssl.SSLContext.check_hostname"><code>check_hostname</code></a> validate the server certificate: it ensures that the server certificate was signed with one of the CA certificates, checks the signature for correctness, and verifies other properties like validity and identity of the hostname:</p> <pre data-language="python">&gt;&gt;&gt; conn = context.wrap_socket(socket.socket(socket.AF_INET),
...                            server_hostname="www.python.org")
&gt;&gt;&gt; conn.connect(("www.python.org", 443))
</pre> <p>You may then fetch the certificate:</p> <pre data-language="python">&gt;&gt;&gt; cert = conn.getpeercert()
</pre> <p>Visual inspection shows that the certificate does identify the desired service (that is, the HTTPS host <code>www.python.org</code>):</p> <pre data-language="python">&gt;&gt;&gt; pprint.pprint(cert)
{'OCSP': ('http://ocsp.digicert.com',),
 'caIssuers': ('http://cacerts.digicert.com/DigiCertSHA2ExtendedValidationServerCA.crt',),
 'crlDistributionPoints': ('http://crl3.digicert.com/sha2-ev-server-g1.crl',
                           'http://crl4.digicert.com/sha2-ev-server-g1.crl'),
 'issuer': ((('countryName', 'US'),),
            (('organizationName', 'DigiCert Inc'),),
            (('organizationalUnitName', 'www.digicert.com'),),
            (('commonName', 'DigiCert SHA2 Extended Validation Server CA'),)),
 'notAfter': 'Sep  9 12:00:00 2016 GMT',
 'notBefore': 'Sep  5 00:00:00 2014 GMT',
 'serialNumber': '01BB6F00122B177F36CAB49CEA8B6B26',
 'subject': ((('businessCategory', 'Private Organization'),),
             (('1.3.6.1.4.1.311.60.2.1.3', 'US'),),
             (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),),
             (('serialNumber', '3359300'),),
             (('streetAddress', '16 Allen Rd'),),
             (('postalCode', '03894-4801'),),
             (('countryName', 'US'),),
             (('stateOrProvinceName', 'NH'),),
             (('localityName', 'Wolfeboro'),),
             (('organizationName', 'Python Software Foundation'),),
             (('commonName', 'www.python.org'),)),
 'subjectAltName': (('DNS', 'www.python.org'),
                    ('DNS', 'python.org'),
                    ('DNS', 'pypi.org'),
                    ('DNS', 'docs.python.org'),
                    ('DNS', 'testpypi.org'),
                    ('DNS', 'bugs.python.org'),
                    ('DNS', 'wiki.python.org'),
                    ('DNS', 'hg.python.org'),
                    ('DNS', 'mail.python.org'),
                    ('DNS', 'packaging.python.org'),
                    ('DNS', 'pythonhosted.org'),
                    ('DNS', 'www.pythonhosted.org'),
                    ('DNS', 'test.pythonhosted.org'),
                    ('DNS', 'us.pycon.org'),
                    ('DNS', 'id.python.org')),
 'version': 3}
</pre> <p>Now the SSL channel is established and the certificate verified, you can proceed to talk with the server:</p> <pre data-language="python">&gt;&gt;&gt; conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n")
&gt;&gt;&gt; pprint.pprint(conn.recv(1024).split(b"\r\n"))
[b'HTTP/1.1 200 OK',
 b'Date: Sat, 18 Oct 2014 18:27:20 GMT',
 b'Server: nginx',
 b'Content-Type: text/html; charset=utf-8',
 b'X-Frame-Options: SAMEORIGIN',
 b'Content-Length: 45679',
 b'Accept-Ranges: bytes',
 b'Via: 1.1 varnish',
 b'Age: 2188',
 b'X-Served-By: cache-lcy1134-LCY',
 b'X-Cache: HIT',
 b'X-Cache-Hits: 11',
 b'Vary: Cookie',
 b'Strict-Transport-Security: max-age=63072000; includeSubDomains',
 b'Connection: close',
 b'',
 b'']
</pre> <p>See the discussion of <a class="reference internal" href="#ssl-security"><span class="std std-ref">Security considerations</span></a> below.</p> </section> <section id="server-side-operation"> <h3>Server-side operation</h3> <p>For server operation, typically you’ll need to have a server certificate, and private key, each in a file. You’ll first create a context holding the key and the certificate, so that clients can check your authenticity. Then you’ll open a socket, bind it to a port, call <code>listen()</code> on it, and start waiting for clients to connect:</p> <pre data-language="python">import socket, ssl

context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile")

bindsocket = socket.socket()
bindsocket.bind(('myaddr.example.com', 10023))
bindsocket.listen(5)
</pre> <p>When a client connects, you’ll call <code>accept()</code> on the socket to get the new socket from the other end, and use the context’s <a class="reference internal" href="#ssl.SSLContext.wrap_socket" title="ssl.SSLContext.wrap_socket"><code>SSLContext.wrap_socket()</code></a> method to create a server-side SSL socket for the connection:</p> <pre data-language="python">while True:
    newsocket, fromaddr = bindsocket.accept()
    connstream = context.wrap_socket(newsocket, server_side=True)
    try:
        deal_with_client(connstream)
    finally:
        connstream.shutdown(socket.SHUT_RDWR)
        connstream.close()
</pre> <p>Then you’ll read data from the <code>connstream</code> and do something with it till you are finished with the client (or the client is finished with you):</p> <pre data-language="python">def deal_with_client(connstream):
    data = connstream.recv(1024)
    # empty data means the client is finished with us
    while data:
        if not do_something(connstream, data):
            # we'll assume do_something returns False
            # when we're finished with client
            break
        data = connstream.recv(1024)
    # finished with client
</pre> <p>And go back to listening for new client connections (of course, a real server would probably handle each client connection in a separate thread, or put the sockets in <a class="reference internal" href="#ssl-nonblocking"><span class="std std-ref">non-blocking mode</span></a> and use an event loop).</p> </section> </section> <section id="notes-on-non-blocking-sockets"> <span id="ssl-nonblocking"></span><h2>Notes on non-blocking sockets</h2> <p>SSL sockets behave slightly different than regular sockets in non-blocking mode. When working with non-blocking sockets, there are thus several things you need to be aware of:</p> <ul> <li>
<p>Most <a class="reference internal" href="#ssl.SSLSocket" title="ssl.SSLSocket"><code>SSLSocket</code></a> methods will raise either <a class="reference internal" href="#ssl.SSLWantWriteError" title="ssl.SSLWantWriteError"><code>SSLWantWriteError</code></a> or <a class="reference internal" href="#ssl.SSLWantReadError" title="ssl.SSLWantReadError"><code>SSLWantReadError</code></a> instead of <a class="reference internal" href="exceptions#BlockingIOError" title="BlockingIOError"><code>BlockingIOError</code></a> if an I/O operation would block. <a class="reference internal" href="#ssl.SSLWantReadError" title="ssl.SSLWantReadError"><code>SSLWantReadError</code></a> will be raised if a read operation on the underlying socket is necessary, and <a class="reference internal" href="#ssl.SSLWantWriteError" title="ssl.SSLWantWriteError"><code>SSLWantWriteError</code></a> for a write operation on the underlying socket. Note that attempts to <em>write</em> to an SSL socket may require <em>reading</em> from the underlying socket first, and attempts to <em>read</em> from the SSL socket may require a prior <em>write</em> to the underlying socket.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>In earlier Python versions, the <code>SSLSocket.send()</code> method returned zero instead of raising <a class="reference internal" href="#ssl.SSLWantWriteError" title="ssl.SSLWantWriteError"><code>SSLWantWriteError</code></a> or <a class="reference internal" href="#ssl.SSLWantReadError" title="ssl.SSLWantReadError"><code>SSLWantReadError</code></a>.</p> </div> </li> <li>Calling <a class="reference internal" href="select#select.select" title="select.select"><code>select()</code></a> tells you that the OS-level socket can be read from (or written to), but it does not imply that there is sufficient data at the upper SSL layer. For example, only part of an SSL frame might have arrived. Therefore, you must be ready to handle <code>SSLSocket.recv()</code> and <code>SSLSocket.send()</code> failures, and retry after another call to <a class="reference internal" href="select#select.select" title="select.select"><code>select()</code></a>.</li> <li>
<p>Conversely, since the SSL layer has its own framing, a SSL socket may still have data available for reading without <a class="reference internal" href="select#select.select" title="select.select"><code>select()</code></a> being aware of it. Therefore, you should first call <code>SSLSocket.recv()</code> to drain any potentially available data, and then only block on a <a class="reference internal" href="select#select.select" title="select.select"><code>select()</code></a> call if still necessary.</p> <p>(of course, similar provisions apply when using other primitives such as <a class="reference internal" href="select#select.poll" title="select.poll"><code>poll()</code></a>, or those in the <a class="reference internal" href="selectors#module-selectors" title="selectors: High-level I/O multiplexing."><code>selectors</code></a> module)</p> </li> <li>
<p>The SSL handshake itself will be non-blocking: the <a class="reference internal" href="#ssl.SSLSocket.do_handshake" title="ssl.SSLSocket.do_handshake"><code>SSLSocket.do_handshake()</code></a> method has to be retried until it returns successfully. Here is a synopsis using <a class="reference internal" href="select#select.select" title="select.select"><code>select()</code></a> to wait for the socket’s readiness:</p> <pre data-language="python">while True:
    try:
        sock.do_handshake()
        break
    except ssl.SSLWantReadError:
        select.select([sock], [], [])
    except ssl.SSLWantWriteError:
        select.select([], [sock], [])
</pre> </li> </ul> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p>The <a class="reference internal" href="asyncio#module-asyncio" title="asyncio: Asynchronous I/O."><code>asyncio</code></a> module supports <a class="reference internal" href="#ssl-nonblocking"><span class="std std-ref">non-blocking SSL sockets</span></a> and provides a higher level API. It polls for events using the <a class="reference internal" href="selectors#module-selectors" title="selectors: High-level I/O multiplexing."><code>selectors</code></a> module and handles <a class="reference internal" href="#ssl.SSLWantWriteError" title="ssl.SSLWantWriteError"><code>SSLWantWriteError</code></a>, <a class="reference internal" href="#ssl.SSLWantReadError" title="ssl.SSLWantReadError"><code>SSLWantReadError</code></a> and <a class="reference internal" href="exceptions#BlockingIOError" title="BlockingIOError"><code>BlockingIOError</code></a> exceptions. It runs the SSL handshake asynchronously as well.</p> </div> </section> <section id="memory-bio-support"> <h2>Memory BIO Support</h2> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> <p>Ever since the SSL module was introduced in Python 2.6, the <a class="reference internal" href="#ssl.SSLSocket" title="ssl.SSLSocket"><code>SSLSocket</code></a> class has provided two related but distinct areas of functionality:</p> <ul class="simple"> <li>SSL protocol handling</li> <li>Network IO</li> </ul> <p>The network IO API is identical to that provided by <a class="reference internal" href="socket#socket.socket" title="socket.socket"><code>socket.socket</code></a>, from which <a class="reference internal" href="#ssl.SSLSocket" title="ssl.SSLSocket"><code>SSLSocket</code></a> also inherits. This allows an SSL socket to be used as a drop-in replacement for a regular socket, making it very easy to add SSL support to an existing application.</p> <p>Combining SSL protocol handling and network IO usually works well, but there are some cases where it doesn’t. An example is async IO frameworks that want to use a different IO multiplexing model than the “select/poll on a file descriptor” (readiness based) model that is assumed by <a class="reference internal" href="socket#socket.socket" title="socket.socket"><code>socket.socket</code></a> and by the internal OpenSSL socket IO routines. This is mostly relevant for platforms like Windows where this model is not efficient. For this purpose, a reduced scope variant of <a class="reference internal" href="#ssl.SSLSocket" title="ssl.SSLSocket"><code>SSLSocket</code></a> called <a class="reference internal" href="#ssl.SSLObject" title="ssl.SSLObject"><code>SSLObject</code></a> is provided.</p> <dl class="py class"> <dt class="sig sig-object py" id="ssl.SSLObject">
<code>class ssl.SSLObject</code> </dt> <dd>
<p>A reduced-scope variant of <a class="reference internal" href="#ssl.SSLSocket" title="ssl.SSLSocket"><code>SSLSocket</code></a> representing an SSL protocol instance that does not contain any network IO methods. This class is typically used by framework authors that want to implement asynchronous IO for SSL through memory buffers.</p> <p>This class implements an interface on top of a low-level SSL object as implemented by OpenSSL. This object captures the state of an SSL connection but does not provide any network IO itself. IO needs to be performed through separate “BIO” objects which are OpenSSL’s IO abstraction layer.</p> <p>This class has no public constructor. An <a class="reference internal" href="#ssl.SSLObject" title="ssl.SSLObject"><code>SSLObject</code></a> instance must be created using the <a class="reference internal" href="#ssl.SSLContext.wrap_bio" title="ssl.SSLContext.wrap_bio"><code>wrap_bio()</code></a> method. This method will create the <a class="reference internal" href="#ssl.SSLObject" title="ssl.SSLObject"><code>SSLObject</code></a> instance and bind it to a pair of BIOs. The <em>incoming</em> BIO is used to pass data from Python to the SSL protocol instance, while the <em>outgoing</em> BIO is used to pass data the other way around.</p> <p>The following methods are available:</p> <ul class="simple"> <li><a class="reference internal" href="#ssl.SSLSocket.context" title="ssl.SSLSocket.context"><code>context</code></a></li> <li><a class="reference internal" href="#ssl.SSLSocket.server_side" title="ssl.SSLSocket.server_side"><code>server_side</code></a></li> <li><a class="reference internal" href="#ssl.SSLSocket.server_hostname" title="ssl.SSLSocket.server_hostname"><code>server_hostname</code></a></li> <li><a class="reference internal" href="#ssl.SSLSocket.session" title="ssl.SSLSocket.session"><code>session</code></a></li> <li><a class="reference internal" href="#ssl.SSLSocket.session_reused" title="ssl.SSLSocket.session_reused"><code>session_reused</code></a></li> <li><a class="reference internal" href="#ssl.SSLSocket.read" title="ssl.SSLSocket.read"><code>read()</code></a></li> <li><a class="reference internal" href="#ssl.SSLSocket.write" title="ssl.SSLSocket.write"><code>write()</code></a></li> <li><a class="reference internal" href="#ssl.SSLSocket.getpeercert" title="ssl.SSLSocket.getpeercert"><code>getpeercert()</code></a></li> <li><a class="reference internal" href="#ssl.SSLSocket.selected_alpn_protocol" title="ssl.SSLSocket.selected_alpn_protocol"><code>selected_alpn_protocol()</code></a></li> <li><a class="reference internal" href="#ssl.SSLSocket.selected_npn_protocol" title="ssl.SSLSocket.selected_npn_protocol"><code>selected_npn_protocol()</code></a></li> <li><a class="reference internal" href="#ssl.SSLSocket.cipher" title="ssl.SSLSocket.cipher"><code>cipher()</code></a></li> <li><a class="reference internal" href="#ssl.SSLSocket.shared_ciphers" title="ssl.SSLSocket.shared_ciphers"><code>shared_ciphers()</code></a></li> <li><a class="reference internal" href="#ssl.SSLSocket.compression" title="ssl.SSLSocket.compression"><code>compression()</code></a></li> <li><a class="reference internal" href="#ssl.SSLSocket.pending" title="ssl.SSLSocket.pending"><code>pending()</code></a></li> <li><a class="reference internal" href="#ssl.SSLSocket.do_handshake" title="ssl.SSLSocket.do_handshake"><code>do_handshake()</code></a></li> <li><a class="reference internal" href="#ssl.SSLSocket.verify_client_post_handshake" title="ssl.SSLSocket.verify_client_post_handshake"><code>verify_client_post_handshake()</code></a></li> <li><a class="reference internal" href="#ssl.SSLSocket.unwrap" title="ssl.SSLSocket.unwrap"><code>unwrap()</code></a></li> <li><a class="reference internal" href="#ssl.SSLSocket.get_channel_binding" title="ssl.SSLSocket.get_channel_binding"><code>get_channel_binding()</code></a></li> <li><a class="reference internal" href="#ssl.SSLSocket.version" title="ssl.SSLSocket.version"><code>version()</code></a></li> </ul> <p>When compared to <a class="reference internal" href="#ssl.SSLSocket" title="ssl.SSLSocket"><code>SSLSocket</code></a>, this object lacks the following features:</p> <ul class="simple"> <li>Any form of network IO; <code>recv()</code> and <code>send()</code> read and write only to the underlying <a class="reference internal" href="#ssl.MemoryBIO" title="ssl.MemoryBIO"><code>MemoryBIO</code></a> buffers.</li> <li>There is no <em>do_handshake_on_connect</em> machinery. You must always manually call <a class="reference internal" href="#ssl.SSLSocket.do_handshake" title="ssl.SSLSocket.do_handshake"><code>do_handshake()</code></a> to start the handshake.</li> <li>There is no handling of <em>suppress_ragged_eofs</em>. All end-of-file conditions that are in violation of the protocol are reported via the <a class="reference internal" href="#ssl.SSLEOFError" title="ssl.SSLEOFError"><code>SSLEOFError</code></a> exception.</li> <li>The method <a class="reference internal" href="#ssl.SSLSocket.unwrap" title="ssl.SSLSocket.unwrap"><code>unwrap()</code></a> call does not return anything, unlike for an SSL socket where it returns the underlying socket.</li> <li>The <em>server_name_callback</em> callback passed to <a class="reference internal" href="#ssl.SSLContext.set_servername_callback" title="ssl.SSLContext.set_servername_callback"><code>SSLContext.set_servername_callback()</code></a> will get an <a class="reference internal" href="#ssl.SSLObject" title="ssl.SSLObject"><code>SSLObject</code></a> instance instead of a <a class="reference internal" href="#ssl.SSLSocket" title="ssl.SSLSocket"><code>SSLSocket</code></a> instance as its first parameter.</li> </ul> <p>Some notes related to the use of <a class="reference internal" href="#ssl.SSLObject" title="ssl.SSLObject"><code>SSLObject</code></a>:</p> <ul class="simple"> <li>All IO on an <a class="reference internal" href="#ssl.SSLObject" title="ssl.SSLObject"><code>SSLObject</code></a> is <a class="reference internal" href="#ssl-nonblocking"><span class="std std-ref">non-blocking</span></a>. This means that for example <a class="reference internal" href="#ssl.SSLSocket.read" title="ssl.SSLSocket.read"><code>read()</code></a> will raise an <a class="reference internal" href="#ssl.SSLWantReadError" title="ssl.SSLWantReadError"><code>SSLWantReadError</code></a> if it needs more data than the incoming BIO has available.</li> <li>There is no module-level <code>wrap_bio()</code> call like there is for <a class="reference internal" href="#ssl.SSLContext.wrap_socket" title="ssl.SSLContext.wrap_socket"><code>wrap_socket()</code></a>. An <a class="reference internal" href="#ssl.SSLObject" title="ssl.SSLObject"><code>SSLObject</code></a> is always created via an <a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code>SSLContext</code></a>.</li> </ul> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span><a class="reference internal" href="#ssl.SSLObject" title="ssl.SSLObject"><code>SSLObject</code></a> instances must to created with <a class="reference internal" href="#ssl.SSLContext.wrap_bio" title="ssl.SSLContext.wrap_bio"><code>wrap_bio()</code></a>. In earlier versions, it was possible to create instances directly. This was never documented or officially supported.</p> </div> </dd>
</dl> <p>An SSLObject communicates with the outside world using memory buffers. The class <a class="reference internal" href="#ssl.MemoryBIO" title="ssl.MemoryBIO"><code>MemoryBIO</code></a> provides a memory buffer that can be used for this purpose. It wraps an OpenSSL memory BIO (Basic IO) object:</p> <dl class="py class"> <dt class="sig sig-object py" id="ssl.MemoryBIO">
<code>class ssl.MemoryBIO</code> </dt> <dd>
<p>A memory buffer that can be used to pass data between Python and an SSL protocol instance.</p> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.MemoryBIO.pending">
<code>pending</code> </dt> <dd>
<p>Return the number of bytes currently in the memory buffer.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.MemoryBIO.eof">
<code>eof</code> </dt> <dd>
<p>A boolean indicating whether the memory BIO is current at the end-of-file position.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.MemoryBIO.read">
<code>read(n=- 1)</code> </dt> <dd>
<p>Read up to <em>n</em> bytes from the memory buffer. If <em>n</em> is not specified or negative, all bytes are returned.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.MemoryBIO.write">
<code>write(buf)</code> </dt> <dd>
<p>Write the bytes from <em>buf</em> to the memory BIO. The <em>buf</em> argument must be an object supporting the buffer protocol.</p> <p>The return value is the number of bytes written, which is always equal to the length of <em>buf</em>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="ssl.MemoryBIO.write_eof">
<code>write_eof()</code> </dt> <dd>
<p>Write an EOF marker to the memory BIO. After this method has been called, it is illegal to call <a class="reference internal" href="#ssl.MemoryBIO.write" title="ssl.MemoryBIO.write"><code>write()</code></a>. The attribute <a class="reference internal" href="#ssl.MemoryBIO.eof" title="ssl.MemoryBIO.eof"><code>eof</code></a> will become true after all data currently in the buffer has been read.</p> </dd>
</dl> </dd>
</dl> </section> <section id="ssl-session"> <h2>SSL session</h2> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.</span></p> </div> <dl class="py class"> <dt class="sig sig-object py" id="ssl.SSLSession">
<code>class ssl.SSLSession</code> </dt> <dd>
<p>Session object used by <a class="reference internal" href="#ssl.SSLSocket.session" title="ssl.SSLSocket.session"><code>session</code></a>.</p> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLSession.id">
<code>id</code> </dt> <dd></dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLSession.time">
<code>time</code> </dt> <dd></dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLSession.timeout">
<code>timeout</code> </dt> <dd></dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLSession.ticket_lifetime_hint">
<code>ticket_lifetime_hint</code> </dt> <dd></dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="ssl.SSLSession.has_ticket">
<code>has_ticket</code> </dt> <dd></dd>
</dl> </dd>
</dl> </section> <section id="security-considerations"> <span id="ssl-security"></span><h2>Security considerations</h2> <section id="best-defaults"> <h3>Best defaults</h3> <p>For <strong>client use</strong>, if you don’t have any special requirements for your security policy, it is highly recommended that you use the <a class="reference internal" href="#ssl.create_default_context" title="ssl.create_default_context"><code>create_default_context()</code></a> function to create your SSL context. It will load the system’s trusted CA certificates, enable certificate validation and hostname checking, and try to choose reasonably secure protocol and cipher settings.</p> <p>For example, here is how you would use the <a class="reference internal" href="smtplib#smtplib.SMTP" title="smtplib.SMTP"><code>smtplib.SMTP</code></a> class to create a trusted, secure connection to a SMTP server:</p> <pre data-language="python">&gt;&gt;&gt; import ssl, smtplib
&gt;&gt;&gt; smtp = smtplib.SMTP("mail.python.org", port=587)
&gt;&gt;&gt; context = ssl.create_default_context()
&gt;&gt;&gt; smtp.starttls(context=context)
(220, b'2.0.0 Ready to start TLS')
</pre> <p>If a client certificate is needed for the connection, it can be added with <a class="reference internal" href="#ssl.SSLContext.load_cert_chain" title="ssl.SSLContext.load_cert_chain"><code>SSLContext.load_cert_chain()</code></a>.</p> <p>By contrast, if you create the SSL context by calling the <a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code>SSLContext</code></a> constructor yourself, it will not have certificate validation nor hostname checking enabled by default. If you do so, please read the paragraphs below to achieve a good security level.</p> </section> <section id="manual-settings"> <h3>Manual settings</h3> <section id="verifying-certificates"> <h4>Verifying certificates</h4> <p>When calling the <a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code>SSLContext</code></a> constructor directly, <a class="reference internal" href="#ssl.CERT_NONE" title="ssl.CERT_NONE"><code>CERT_NONE</code></a> is the default. Since it does not authenticate the other peer, it can be insecure, especially in client mode where most of time you would like to ensure the authenticity of the server you’re talking to. Therefore, when in client mode, it is highly recommended to use <a class="reference internal" href="#ssl.CERT_REQUIRED" title="ssl.CERT_REQUIRED"><code>CERT_REQUIRED</code></a>. However, it is in itself not sufficient; you also have to check that the server certificate, which can be obtained by calling <a class="reference internal" href="#ssl.SSLSocket.getpeercert" title="ssl.SSLSocket.getpeercert"><code>SSLSocket.getpeercert()</code></a>, matches the desired service. For many protocols and applications, the service can be identified by the hostname. This common check is automatically performed when <a class="reference internal" href="#ssl.SSLContext.check_hostname" title="ssl.SSLContext.check_hostname"><code>SSLContext.check_hostname</code></a> is enabled.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Hostname matchings is now performed by OpenSSL. Python no longer uses <code>match_hostname()</code>.</p> </div> <p>In server mode, if you want to authenticate your clients using the SSL layer (rather than using a higher-level authentication mechanism), you’ll also have to specify <a class="reference internal" href="#ssl.CERT_REQUIRED" title="ssl.CERT_REQUIRED"><code>CERT_REQUIRED</code></a> and similarly check the client certificate.</p> </section> <section id="protocol-versions"> <h4>Protocol versions</h4> <p>SSL versions 2 and 3 are considered insecure and are therefore dangerous to use. If you want maximum compatibility between clients and servers, it is recommended to use <a class="reference internal" href="#ssl.PROTOCOL_TLS_CLIENT" title="ssl.PROTOCOL_TLS_CLIENT"><code>PROTOCOL_TLS_CLIENT</code></a> or <a class="reference internal" href="#ssl.PROTOCOL_TLS_SERVER" title="ssl.PROTOCOL_TLS_SERVER"><code>PROTOCOL_TLS_SERVER</code></a> as the protocol version. SSLv2 and SSLv3 are disabled by default.</p> <pre data-language="python">&gt;&gt;&gt; client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
&gt;&gt;&gt; client_context.minimum_version = ssl.TLSVersion.TLSv1_3
&gt;&gt;&gt; client_context.maximum_version = ssl.TLSVersion.TLSv1_3
</pre> <p>The SSL context created above will only allow TLSv1.3 and later (if supported by your system) connections to a server. <a class="reference internal" href="#ssl.PROTOCOL_TLS_CLIENT" title="ssl.PROTOCOL_TLS_CLIENT"><code>PROTOCOL_TLS_CLIENT</code></a> implies certificate validation and hostname checks by default. You have to load certificates into the context.</p> </section> <section id="cipher-selection"> <h4>Cipher selection</h4> <p>If you have advanced security requirements, fine-tuning of the ciphers enabled when negotiating a SSL session is possible through the <a class="reference internal" href="#ssl.SSLContext.set_ciphers" title="ssl.SSLContext.set_ciphers"><code>SSLContext.set_ciphers()</code></a> method. Starting from Python 3.2.3, the ssl module disables certain weak ciphers by default, but you may want to further restrict the cipher choice. Be sure to read OpenSSL’s documentation about the <a class="reference external" href="https://www.openssl.org/docs/man1.1.1/man1/ciphers.html#CIPHER-LIST-FORMAT">cipher list format</a>. If you want to check which ciphers are enabled by a given cipher list, use <a class="reference internal" href="#ssl.SSLContext.get_ciphers" title="ssl.SSLContext.get_ciphers"><code>SSLContext.get_ciphers()</code></a> or the <code>openssl ciphers</code> command on your system.</p> </section> </section> <section id="multi-processing"> <h3>Multi-processing</h3> <p>If using this module as part of a multi-processed application (using, for example the <a class="reference internal" href="multiprocessing#module-multiprocessing" title="multiprocessing: Process-based parallelism."><code>multiprocessing</code></a> or <a class="reference internal" href="concurrent.futures#module-concurrent.futures" title="concurrent.futures: Execute computations concurrently using threads or processes."><code>concurrent.futures</code></a> modules), be aware that OpenSSL’s internal random number generator does not properly handle forked processes. Applications must change the PRNG state of the parent process if they use any SSL feature with <a class="reference internal" href="os#os.fork" title="os.fork"><code>os.fork()</code></a>. Any successful call of <a class="reference internal" href="#ssl.RAND_add" title="ssl.RAND_add"><code>RAND_add()</code></a> or <a class="reference internal" href="#ssl.RAND_bytes" title="ssl.RAND_bytes"><code>RAND_bytes()</code></a> is sufficient.</p> </section> </section> <section id="tls-1-3"> <span id="ssl-tlsv1-3"></span><h2>TLS 1.3</h2> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> <p>The TLS 1.3 protocol behaves slightly differently than previous version of TLS/SSL. Some new TLS 1.3 features are not yet available.</p> <ul class="simple"> <li>TLS 1.3 uses a disjunct set of cipher suites. All AES-GCM and ChaCha20 cipher suites are enabled by default. The method <a class="reference internal" href="#ssl.SSLContext.set_ciphers" title="ssl.SSLContext.set_ciphers"><code>SSLContext.set_ciphers()</code></a> cannot enable or disable any TLS 1.3 ciphers yet, but <a class="reference internal" href="#ssl.SSLContext.get_ciphers" title="ssl.SSLContext.get_ciphers"><code>SSLContext.get_ciphers()</code></a> returns them.</li> <li>Session tickets are no longer sent as part of the initial handshake and are handled differently. <a class="reference internal" href="#ssl.SSLSocket.session" title="ssl.SSLSocket.session"><code>SSLSocket.session</code></a> and <a class="reference internal" href="#ssl.SSLSession" title="ssl.SSLSession"><code>SSLSession</code></a> are not compatible with TLS 1.3.</li> <li>Client-side certificates are also no longer verified during the initial handshake. A server can request a certificate at any time. Clients process certificate requests while they send or receive application data from the server.</li> <li>TLS 1.3 features like early data, deferred TLS client cert request, signature algorithm configuration, and rekeying are not supported yet.</li> </ul> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt>
<code>Class</code> <a class="reference internal" href="socket#socket.socket" title="socket.socket"><code>socket.socket</code></a>
</dt>
<dd>
<p>Documentation of underlying <a class="reference internal" href="socket#module-socket" title="socket: Low-level networking interface."><code>socket</code></a> class</p> </dd> <dt><a class="reference external" href="https://httpd.apache.org/docs/trunk/en/ssl/ssl_intro.html">SSL/TLS Strong Encryption: An Introduction</a></dt>
<dd>
<p>Intro from the Apache HTTP Server documentation</p> </dd> <dt>
<span class="target" id="index-17"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc1422.html"><strong>RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management</strong></a>
</dt>
<dd>
<p>Steve Kent</p> </dd> <dt>
<span class="target" id="index-18"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc4086.html"><strong>RFC 4086: Randomness Requirements for Security</strong></a>
</dt>
<dd>
<p>Donald E., Jeffrey I. Schiller</p> </dd> <dt>
<span class="target" id="index-19"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc5280.html"><strong>RFC 5280: Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile</strong></a>
</dt>
<dd>
<p>D. Cooper</p> </dd> <dt>
<span class="target" id="index-20"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc5246.html"><strong>RFC 5246: The Transport Layer Security (TLS) Protocol Version 1.2</strong></a>
</dt>
<dd>
<p>T. Dierks et. al.</p> </dd> <dt>
<span class="target" id="index-21"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc6066.html"><strong>RFC 6066: Transport Layer Security (TLS) Extensions</strong></a>
</dt>
<dd>
<p>D. Eastlake</p> </dd> <dt><a class="reference external" href="https://www.iana.org/assignments/tls-parameters/tls-parameters.xml">IANA TLS: Transport Layer Security (TLS) Parameters</a></dt>
<dd>
<p>IANA</p> </dd> <dt>
<span class="target" id="index-22"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc7525.html"><strong>RFC 7525: Recommendations for Secure Use of Transport Layer Security (TLS) and Datagram Transport Layer Security (DTLS)</strong></a>
</dt>
<dd>
<p>IETF</p> </dd> <dt><a class="reference external" href="https://wiki.mozilla.org/Security/Server_Side_TLS">Mozilla’s Server Side TLS recommendations</a></dt>
<dd>
<p>Mozilla</p> </dd> </dl> </div> </section> <div class="_attribution">
  <p class="_attribution-p">
    &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
    <a href="https://docs.python.org/3.12/library/ssl.html" class="_attribution-link">https://docs.python.org/3.12/library/ssl.html</a>
  </p>
</div>