-
Notifications
You must be signed in to change notification settings - Fork 1
/
ssl-backport.diff
12963 lines (12634 loc) · 507 KB
/
ssl-backport.diff
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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
diff --git a/Doc/library/ssl.rst b/Doc/library/ssl.rst
index c115976..84dd332 100644
--- a/Doc/library/ssl.rst
+++ b/Doc/library/ssl.rst
@@ -28,19 +28,14 @@ probably additional platforms, as long as OpenSSL is installed on that platform.
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.
+ cause variations in behavior. For example, TLSv1.1 and TLSv1.2 come with
+ openssl version 1.0.1.
.. warning::
- The ssl module won't validate certificates by default. When used in
- client mode, this means you are vulnerable to man-in-the-middle attacks.
+ Don't use this module without reading the :ref:`ssl-security`. 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.
-.. warning::
-
- OpenSSL's internal random number generator does not properly handle fork.
- Applications must change the PRNG state of the parent process if they use
- any SSL feature with :func:`os.fork`. Any successful call of
- :func:`~ssl.RAND_add`, :func:`~ssl.RAND_bytes` or
- :func:`~ssl.RAND_pseudo_bytes` is sufficient.
This section documents the objects and functions in the ``ssl`` module; for more
general information about TLS, SSL, and certificates, the reader is referred to
@@ -49,23 +44,101 @@ the documents in the "See Also" section at the bottom.
This module provides a class, :class:`ssl.SSLSocket`, which is derived from the
:class:`socket.socket` type, and provides a socket-like wrapper that also
encrypts and decrypts the data going over the socket with SSL. It supports
-additional :meth:`read` and :meth:`write` methods, along with a method,
-:meth:`getpeercert`, to retrieve the certificate of the other side of the
-connection, and a method, :meth:`cipher`, to retrieve the cipher being used for
-the secure connection.
+additional methods such as :meth:`getpeercert`, which retrieves the
+certificate of the other side of the connection, and :meth:`cipher`,which
+retrieves the cipher being used for the secure connection.
+
+For more sophisticated applications, the :class:`ssl.SSLContext` class
+helps manage settings and certificates, which can then be inherited
+by SSL sockets created through the :meth:`SSLContext.wrap_socket` method.
+
Functions, Constants, and Exceptions
------------------------------------
.. exception:: SSLError
- Raised to signal an error from the underlying SSL implementation. 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 :exc:`socket.error`, which in turn is a subtype of
- :exc:`IOError`.
+ 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
+ :exc:`socket.error`, which in turn is a subtype of :exc:`IOError`. The
+ error code and message of :exc:`SSLError` instances are provided by the
+ OpenSSL library.
+
+ .. attribute:: library
+
+ A string mnemonic designating the OpenSSL submodule in which the error
+ occurred, such as ``SSL``, ``PEM`` or ``X509``. The range of possible
+ values depends on the OpenSSL version.
+
+ .. versionadded:: 2.7.9
+
+ .. attribute:: reason
+
+ A string mnemonic designating the reason this error occurred, for
+ example ``CERTIFICATE_VERIFY_FAILED``. The range of possible
+ values depends on the OpenSSL version.
+
+ .. versionadded:: 2.7.9
+
+.. exception:: SSLZeroReturnError
+
+ A subclass of :exc:`SSLError` 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.
+
+ .. versionadded:: 2.7.9
+
+.. exception:: SSLWantReadError
+
+ A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket
+ <ssl-nonblocking>` 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.
+
+ .. versionadded:: 2.7.9
+
+.. exception:: SSLWantWriteError
+
+ A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket
+ <ssl-nonblocking>` 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.
-.. function:: wrap_socket (sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version={see docs}, ca_certs=None, do_handshake_on_connect=True, suppress_ragged_eofs=True, ciphers=None)
+ .. versionadded:: 2.7.9
+
+.. exception:: SSLSyscallError
+
+ A subclass of :exc:`SSLError` 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.
+
+ .. versionadded:: 2.7.9
+
+.. exception:: SSLEOFError
+
+ A subclass of :exc:`SSLError` raised when the SSL connection has been
+ terminated abruptly. Generally, you shouldn't try to reuse the underlying
+ transport when this error is encountered.
+
+ .. versionadded:: 2.7.9
+
+.. exception:: CertificateError
+
+ Raised to signal an error with a certificate (such as mismatching
+ hostname). Certificate errors detected by OpenSSL, though, raise
+ an :exc:`SSLError`.
+
+
+Socket creation
+^^^^^^^^^^^^^^^
+
+The following function allows for standalone socket creation. Starting from
+Python 2.7.9, it can be more flexible to use :meth:`SSLContext.wrap_socket`
+instead.
+
+.. function:: wrap_socket(sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version={see docs}, ca_certs=None, do_handshake_on_connect=True, suppress_ragged_eofs=True, ciphers=None)
Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance
of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps
@@ -85,19 +158,6 @@ Functions, Constants, and Exceptions
connection. See the discussion of :ref:`ssl-certificates` for more
information on how the certificate is stored in the ``certfile``.
- Often the private key is stored in the same file as the certificate; in this
- case, only the ``certfile`` parameter need be passed. If the private key is
- stored in a separate file, both parameters must be used. If the private key
- is stored in the ``certfile``, it should come before the first certificate in
- the certificate chain::
-
- -----BEGIN RSA PRIVATE KEY-----
- ... (private key in base64 encoding) ...
- -----END RSA PRIVATE KEY-----
- -----BEGIN CERTIFICATE-----
- ... (certificate in base64 PEM encoding) ...
- -----END CERTIFICATE-----
-
The parameter ``server_side`` is a boolean which identifies whether
server-side or client-side behavior is desired from this socket.
@@ -127,14 +187,16 @@ Functions, Constants, and Exceptions
.. table::
- ======================== ========= ========= ========== =========
- *client* / **server** **SSLv2** **SSLv3** **SSLv23** **TLSv1**
- ------------------------ --------- --------- ---------- ---------
- *SSLv2* yes no yes no
- *SSLv3* no yes yes no
- *SSLv23* yes no yes no
- *TLSv1* no no yes yes
- ======================== ========= ========= ========== =========
+ ======================== ========= ========= ========== ========= =========== ===========
+ *client* / **server** **SSLv2** **SSLv3** **SSLv23** **TLSv1** **TLSv1.1** **TLSv1.2**
+ ------------------------ --------- --------- ---------- --------- ----------- -----------
+ *SSLv2* yes no yes no no no
+ *SSLv3* no yes yes no no no
+ *SSLv23* yes no yes no no no
+ *TLSv1* no no yes yes no no
+ *TLSv1.1* no no yes no yes no
+ *TLSv1.2* no no yes no no yes
+ ======================== ========= ========= ========== ========= =========== ===========
.. note::
@@ -161,22 +223,79 @@ Functions, Constants, and Exceptions
The parameter ``suppress_ragged_eofs`` specifies how the
:meth:`SSLSocket.read` method should signal unexpected EOF from the other end
of the connection. If specified as :const:`True` (the default), it returns a
- normal EOF in response to unexpected EOF errors raised from the underlying
- socket; if :const:`False`, it will raise the exceptions back to the caller.
+ normal EOF (an empty bytes object) in response to unexpected EOF errors
+ raised from the underlying socket; if :const:`False`, it will raise the
+ exceptions back to the caller.
.. versionchanged:: 2.7
New optional argument *ciphers*.
+
+Context creation
+^^^^^^^^^^^^^^^^
+
+A convenience function helps create :class:`SSLContext` objects for common
+purposes.
+
+.. function:: create_default_context(purpose=Purpose.SERVER_AUTH, cafile=None, capath=None, cadata=None)
+
+ Return a new :class:`SSLContext` object with default settings for
+ the given *purpose*. The settings are chosen by the :mod:`ssl` module,
+ and usually represent a higher security level than when calling the
+ :class:`SSLContext` constructor directly.
+
+ *cafile*, *capath*, *cadata* represent optional CA certificates to
+ trust for certificate verification, as in
+ :meth:`SSLContext.load_verify_locations`. If all three are
+ :const:`None`, this function can choose to trust the system's default
+ CA certificates instead.
+
+ The settings in Python 2.7.9 are: :data:`PROTOCOL_SSLv23`,
+ :data:`OP_NO_SSLv2`, and :data:`OP_NO_SSLv3` with high encryption cipher
+ suites without RC4 and without unauthenticated cipher suites. Passing
+ :data:`~Purpose.SERVER_AUTH` as *purpose* sets
+ :data:`~SSLContext.verify_mode` to :data:`CERT_REQUIRED` and either loads CA
+ certificates (when at least one of *cafile*, *capath* or *cadata* is given)
+ or uses :meth:`SSLContext.load_default_certs` to load default CA
+ certificates.
+
+ .. note::
+ 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.
+
+ If your application needs specific settings, you should create a
+ :class:`SSLContext` and apply the settings yourself.
+
+ .. note::
+ If you find that when certain older clients or servers attempt to connect
+ with a :class:`SSLContext` 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
+ :data:`OP_NO_SSLv3`. SSL3.0 has problematic security due to a number of
+ poor implementations and it's reliance on MD5 within the protocol. If you
+ wish to continue to use this function but still allow SSL 3.0 connections
+ you can re-enable them using::
+
+ ctx = ssl.create_default_context(Purpose.CLIENT_AUTH)
+ ctx.options &= ~ssl.OP_NO_SSLv3
+
+ .. versionadded:: 2.7.9
+
+
+Random generation
+^^^^^^^^^^^^^^^^^
+
.. function:: RAND_status()
Returns ``True`` if the SSL pseudo-random number generator has been seeded with
- 'enough' randomness, and False otherwise. You can use :func:`ssl.RAND_egd`
+ 'enough' randomness, and ``False`` otherwise. You can use :func:`ssl.RAND_egd`
and :func:`ssl.RAND_add` to increase the randomness of the pseudo-random
number generator.
.. function:: RAND_egd(path)
- If you are running an entropy-gathering daemon (EGD) somewhere, and ``path``
+ If you are running an entropy-gathering daemon (EGD) somewhere, and *path*
is the pathname of a socket connection open to it, this will read 256 bytes
of randomness from the socket, and add it to the SSL pseudo-random number
generator to increase the security of generated secret keys. This is
@@ -187,28 +306,66 @@ Functions, Constants, and Exceptions
.. function:: RAND_add(bytes, entropy)
- Mixes the given ``bytes`` into the SSL pseudo-random number generator. The
- parameter ``entropy`` (a float) is a lower bound on the entropy contained in
+ Mixes the given *bytes* into the SSL pseudo-random number generator. The
+ parameter *entropy* (a float) is a lower bound on the entropy contained in
string (so you can always use :const:`0.0`). See :rfc:`1750` for more
information on sources of entropy.
-.. function:: cert_time_to_seconds(timestring)
+Certificate handling
+^^^^^^^^^^^^^^^^^^^^
+
+.. function:: match_hostname(cert, hostname)
+
+ Verify that *cert* (in decoded format as returned by
+ :meth:`SSLSocket.getpeercert`) matches the given *hostname*. The rules
+ applied are those for checking the identity of HTTPS servers as outlined
+ in :rfc:`2818` and :rfc:`6125`, except that IP addresses are not currently
+ supported. In addition to HTTPS, this function should be suitable for
+ checking the identity of servers in various SSL-based protocols such as
+ FTPS, IMAPS, POPS and others.
+
+ :exc:`CertificateError` is raised on failure. On success, the function
+ returns nothing::
- Returns a floating-point value containing a normal seconds-after-the-epoch
- time value, given the time-string representing the "notBefore" or "notAfter"
- date from a certificate.
+ >>> cert = {'subject': ((('commonName', 'example.com'),),)}
+ >>> ssl.match_hostname(cert, "example.com")
+ >>> ssl.match_hostname(cert, "example.org")
+ Traceback (most recent call last):
+ File "<stdin>", line 1, in <module>
+ File "/home/py3k/Lib/ssl.py", line 130, in match_hostname
+ ssl.CertificateError: hostname 'example.org' doesn't match 'example.com'
- Here's an example::
+ .. versionadded:: 2.7.9
- >>> import ssl
- >>> ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT")
- 1178694000.0
- >>> import time
- >>> time.ctime(ssl.cert_time_to_seconds("May 9 00:00:00 2007 GMT"))
- 'Wed May 9 00:00:00 2007'
- >>>
-.. function:: get_server_certificate (addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None)
+.. function:: cert_time_to_seconds(cert_time)
+
+ Return the time in seconds since the Epoch, given the ``cert_time``
+ string representing the "notBefore" or "notAfter" date from a
+ certificate in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C
+ locale).
+
+ Here's an example:
+
+ .. doctest:: newcontext
+
+ >>> import ssl
+ >>> timestamp = ssl.cert_time_to_seconds("Jan 5 09:34:43 2018 GMT")
+ >>> timestamp
+ 1515144883
+ >>> from datetime import datetime
+ >>> print(datetime.utcfromtimestamp(timestamp))
+ 2018-01-05 09:34:43
+
+ "notBefore" or "notAfter" dates must use GMT (:rfc:`5280`).
+
+ .. versionchanged:: 2.7.9
+ 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)
+
+.. function:: get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None)
Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
*port-number*) pair, fetches the server's certificate, and returns it as a
@@ -219,36 +376,144 @@ Functions, Constants, and Exceptions
will attempt to validate the server certificate against that set of root
certificates, and will fail if the validation attempt fails.
-.. function:: DER_cert_to_PEM_cert (DER_cert_bytes)
+ .. versionchanged:: 2.7.9
+
+ This function is now IPv6-compatible, and the default *ssl_version* is
+ changed from :data:`PROTOCOL_SSLv3` to :data:`PROTOCOL_SSLv23` for
+ maximum compatibility with modern servers.
+
+.. function:: DER_cert_to_PEM_cert(DER_cert_bytes)
Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded
string version of the same certificate.
-.. function:: PEM_cert_to_DER_cert (PEM_cert_string)
+.. function:: PEM_cert_to_DER_cert(PEM_cert_string)
Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of
bytes for that same certificate.
+.. function:: get_default_verify_paths()
+
+ Returns a named tuple with paths to OpenSSL's default cafile and capath.
+ The paths are the same as used by
+ :meth:`SSLContext.set_default_verify_paths`. The return value is a
+ :term:`named tuple` ``DefaultVerifyPaths``:
+
+ * :attr:`cafile` - resolved path to cafile or None if the file doesn't exist,
+ * :attr:`capath` - resolved path to capath or None if the directory doesn't exist,
+ * :attr:`openssl_cafile_env` - OpenSSL's environment key that points to a cafile,
+ * :attr:`openssl_cafile` - hard coded path to a cafile,
+ * :attr:`openssl_capath_env` - OpenSSL's environment key that points to a capath,
+ * :attr:`openssl_capath` - hard coded path to a capath directory
+
+ .. versionadded:: 2.7.9
+
+.. function:: enum_certificates(store_name)
+
+ Retrieve certificates from Windows' system cert store. *store_name* may be
+ one of ``CA``, ``ROOT`` or ``MY``. Windows may provide additional cert
+ stores, too.
+
+ The function returns a list of (cert_bytes, encoding_type, trust) tuples.
+ The encoding_type specifies the encoding of cert_bytes. It is either
+ :const:`x509_asn` for X.509 ASN.1 data or :const:`pkcs_7_asn` for
+ PKCS#7 ASN.1 data. Trust specifies the purpose of the certificate as a set
+ of OIDS or exactly ``True`` if the certificate is trustworthy for all
+ purposes.
+
+ Example::
+
+ >>> 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)]
+
+ Availability: Windows.
+
+ .. versionadded:: 2.7.9
+
+.. function:: enum_crls(store_name)
+
+ Retrieve CRLs from Windows' system cert store. *store_name* may be
+ one of ``CA``, ``ROOT`` or ``MY``. Windows may provide additional cert
+ stores, too.
+
+ The function returns a list of (cert_bytes, encoding_type, trust) tuples.
+ The encoding_type specifies the encoding of cert_bytes. It is either
+ :const:`x509_asn` for X.509 ASN.1 data or :const:`pkcs_7_asn` for
+ PKCS#7 ASN.1 data.
+
+ Availability: Windows.
+
+ .. versionadded:: 2.7.9
+
+
+Constants
+^^^^^^^^^
+
.. data:: CERT_NONE
- Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when no
- certificates will be required or validated from the other side of the socket
- connection.
+ Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
+ parameter to :func:`wrap_socket`. In this mode (the default), no
+ certificates will be required from the other side of the socket connection.
+ If a certificate is received from the other end, no attempt to validate it
+ is made.
+
+ See the discussion of :ref:`ssl-security` below.
.. data:: CERT_OPTIONAL
- Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when no
- certificates will be required from the other side of the socket connection,
- but if they are provided, will be validated. Note that use of this setting
- requires a valid certificate validation file also be passed as a value of the
- ``ca_certs`` parameter.
+ Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
+ parameter to :func:`wrap_socket`. In this mode no certificates will be
+ required from the other side of the socket connection; but if they
+ are provided, validation will be attempted and an :class:`SSLError`
+ will be raised on failure.
+
+ Use of this setting requires a valid set of CA certificates to
+ be passed, either to :meth:`SSLContext.load_verify_locations` or as a
+ value of the ``ca_certs`` parameter to :func:`wrap_socket`.
.. data:: CERT_REQUIRED
- Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when
- certificates will be required from the other side of the socket connection.
- Note that use of this setting requires a valid certificate validation file
- also be passed as a value of the ``ca_certs`` parameter.
+ Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
+ parameter to :func:`wrap_socket`. In this mode, certificates are
+ required from the other side of the socket connection; an :class:`SSLError`
+ will be raised if no certificate is provided, or if its validation fails.
+
+ Use of this setting requires a valid set of CA certificates to
+ be passed, either to :meth:`SSLContext.load_verify_locations` or as a
+ value of the ``ca_certs`` parameter to :func:`wrap_socket`.
+
+.. data:: VERIFY_DEFAULT
+
+ Possible value for :attr:`SSLContext.verify_flags`. In this mode,
+ certificate revocation lists (CRLs) are not checked. By default OpenSSL
+ does neither require nor verify CRLs.
+
+ .. versionadded:: 2.7.9
+
+.. data:: VERIFY_CRL_CHECK_LEAF
+
+ Possible value for :attr:`SSLContext.verify_flags`. In this mode, only the
+ peer cert is check but non 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 has been loaded
+ :attr:`SSLContext.load_verify_locations`, validation will fail.
+
+ .. versionadded:: 2.7.9
+
+.. data:: VERIFY_CRL_CHECK_CHAIN
+
+ Possible value for :attr:`SSLContext.verify_flags`. In this mode, CRLs of
+ all certificates in the peer cert chain are checked.
+
+ .. versionadded:: 2.7.9
+
+.. data:: VERIFY_X509_STRICT
+
+ Possible value for :attr:`SSLContext.verify_flags` to disable workarounds
+ for broken X.509 certificates.
+
+ .. versionadded:: 2.7.9
.. data:: PROTOCOL_SSLv2
@@ -275,9 +540,136 @@ Functions, Constants, and Exceptions
.. data:: PROTOCOL_TLSv1
- Selects TLS version 1 as the channel encryption protocol. This is the most
+ Selects TLS version 1.0 as the channel encryption protocol.
+
+.. data:: PROTOCOL_TLSv1_1
+
+ Selects TLS version 1.1 as the channel encryption protocol.
+ Available only with openssl version 1.0.1+.
+
+ .. versionadded:: 2.7.9
+
+.. data:: PROTOCOL_TLSv1_2
+
+ Selects TLS version 1.2 as the channel encryption protocol. This is the most
modern version, and probably the best choice for maximum protection, if both
- sides can speak it.
+ sides can speak it. Available only with openssl version 1.0.1+.
+
+ .. versionadded:: 2.7.9
+
+.. data:: OP_ALL
+
+ 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 ``SSL_OP_ALL`` constant.
+
+ .. versionadded:: 2.7.9
+
+.. data:: OP_NO_SSLv2
+
+ Prevents an SSLv2 connection. This option is only applicable in
+ conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
+ choosing SSLv2 as the protocol version.
+
+ .. versionadded:: 2.7.9
+
+.. data:: OP_NO_SSLv3
+
+ Prevents an SSLv3 connection. This option is only applicable in
+ conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
+ choosing SSLv3 as the protocol version.
+
+ .. versionadded:: 2.7.9
+
+.. data:: OP_NO_TLSv1
+
+ Prevents a TLSv1 connection. This option is only applicable in
+ conjunction with :const:`PROTOCOL_SSLv23`. It prevents the peers from
+ choosing TLSv1 as the protocol version.
+
+ .. versionadded:: 2.7.9
+
+.. data:: OP_NO_TLSv1_1
+
+ Prevents a TLSv1.1 connection. This option is only applicable in conjunction
+ with :const:`PROTOCOL_SSLv23`. It prevents the peers from choosing TLSv1.1 as
+ the protocol version. Available only with openssl version 1.0.1+.
+
+ .. versionadded:: 2.7.9
+
+.. data:: OP_NO_TLSv1_2
+
+ Prevents a TLSv1.2 connection. This option is only applicable in conjunction
+ with :const:`PROTOCOL_SSLv23`. It prevents the peers from choosing TLSv1.2 as
+ the protocol version. Available only with openssl version 1.0.1+.
+
+ .. versionadded:: 2.7.9
+
+.. data:: OP_CIPHER_SERVER_PREFERENCE
+
+ Use the server's cipher ordering preference, rather than the client's.
+ This option has no effect on client sockets and SSLv2 server sockets.
+
+ .. versionadded:: 2.7.9
+
+.. data:: OP_SINGLE_DH_USE
+
+ 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.
+
+ .. versionadded:: 2.7.9
+
+.. data:: OP_SINGLE_ECDH_USE
+
+ 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.
+
+ .. versionadded:: 2.7.9
+
+.. data:: OP_NO_COMPRESSION
+
+ Disable compression on the SSL channel. This is useful if the application
+ protocol supports its own compression scheme.
+
+ This option is only available with OpenSSL 1.0.0 and later.
+
+ .. versionadded:: 2.7.9
+
+.. data:: HAS_ECDH
+
+ Whether the OpenSSL library has built-in support for Elliptic Curve-based
+ Diffie-Hellman key exchange. This should be true unless the feature was
+ explicitly disabled by the distributor.
+
+ .. versionadded:: 2.7.9
+
+.. data:: HAS_SNI
+
+ Whether the OpenSSL library has built-in support for the *Server Name
+ Indication* extension to the SSLv3 and TLSv1 protocols (as defined in
+ :rfc:`4366`). When true, you can use the *server_hostname* argument to
+ :meth:`SSLContext.wrap_socket`.
+
+ .. versionadded:: 2.7.9
+
+.. data:: HAS_NPN
+
+ Whether the OpenSSL library has built-in support for *Next Protocol
+ Negotiation* as described in the `NPN draft specification
+ <http://tools.ietf.org/html/draft-agl-tls-nextprotoneg>`_. When true,
+ you can use the :meth:`SSLContext.set_npn_protocols` method to advertise
+ which protocols you want to support.
+
+ .. versionadded:: 2.7.9
+
+.. data:: CHANNEL_BINDING_TYPES
+
+ List of supported TLS channel binding types. Strings in this list
+ can be used as arguments to :meth:`SSLSocket.get_channel_binding`.
+
+ .. versionadded:: 2.7.9
.. data:: OPENSSL_VERSION
@@ -309,9 +701,40 @@ Functions, Constants, and Exceptions
.. versionadded:: 2.7
+.. data:: ALERT_DESCRIPTION_HANDSHAKE_FAILURE
+ ALERT_DESCRIPTION_INTERNAL_ERROR
+ ALERT_DESCRIPTION_*
+
+ Alert Descriptions from :rfc:`5246` and others. The `IANA TLS Alert Registry
+ <http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6>`_
+ contains this list and references to the RFCs where their meaning is defined.
+
+ Used as the return value of the callback function in
+ :meth:`SSLContext.set_servername_callback`.
+
+ .. versionadded:: 2.7.9
+
+.. data:: Purpose.SERVER_AUTH
+
+ Option for :func:`create_default_context` and
+ :meth:`SSLContext.load_default_certs`. This value indicates that the
+ context may be used to authenticate Web servers (therefore, it will
+ be used to create client-side sockets).
+
+ .. versionadded:: 2.7.9
-SSLSocket Objects
------------------
+.. data:: Purpose.CLIENT_AUTH
+
+ Option for :func:`create_default_context` and
+ :meth:`SSLContext.load_default_certs`. This value indicates that the
+ context may be used to authenticate Web clients (therefore, it will
+ be used to create server-side sockets).
+
+ .. versionadded:: 2.7.9
+
+
+SSL Sockets
+-----------
SSL sockets provide the following methods of :ref:`socket-objects`:
@@ -334,37 +757,64 @@ SSL sockets provide the following methods of :ref:`socket-objects`:
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.
+the specification of normal, OS-level sockets. See especially the
+:ref:`notes on non-blocking sockets <ssl-nonblocking>`.
SSL sockets also have the following additional methods and attributes:
+.. method:: SSLSocket.do_handshake()
+
+ Perform the SSL setup handshake.
+
+ .. versionchanged:: 2.7.9
+
+ The handshake method also performs :func:`match_hostname` when the
+ :attr:`~SSLContext.check_hostname` attribute of the socket's
+ :attr:`~SSLSocket.context` is true.
+
.. method:: SSLSocket.getpeercert(binary_form=False)
If there is no certificate for the peer on the other end of the connection,
- returns ``None``.
+ return ``None``. If the SSL handshake hasn't been done yet, raise
+ :exc:`ValueError`.
If the ``binary_form`` parameter is :const:`False`, and a certificate was
received from the peer, this method returns a :class:`dict` instance. If the
certificate was not validated, the dict is empty. If the certificate was
- validated, it returns a dict with the keys ``subject`` (the principal for
- which the certificate was issued), and ``notAfter`` (the time after which the
- certificate should not be trusted). The certificate was already validated,
- so the ``notBefore`` and ``issuer`` fields are not returned. If a
- certificate contains an instance of the *Subject Alternative Name* extension
- (see :rfc:`3280`), there will also be a ``subjectAltName`` key in the
- dictionary.
-
- The "subject" field is a tuple containing the sequence of relative
- distinguished names (RDNs) given in the certificate's data structure for the
- principal, and each RDN is a sequence of name-value pairs::
-
- {'notAfter': 'Feb 16 16:54:50 2013 GMT',
- 'subject': ((('countryName', u'US'),),
- (('stateOrProvinceName', u'Delaware'),),
- (('localityName', u'Wilmington'),),
- (('organizationName', u'Python Software Foundation'),),
- (('organizationalUnitName', u'SSL'),),
- (('commonName', u'somemachine.python.org'),))}
+ validated, it returns a dict with several keys, amongst them ``subject``
+ (the principal for which the certificate was issued) and ``issuer``
+ (the principal issuing the certificate). If a certificate contains an
+ instance of the *Subject Alternative Name* extension (see :rfc:`3280`),
+ there will also be a ``subjectAltName`` key in the dictionary.
+
+ The ``subject`` and ``issuer`` 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::
+
+ {'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', '[email protected]'),)),
+ 'subjectAltName': (('DNS', '*.eff.org'), ('DNS', 'eff.org')),
+ 'version': 3}
+
+ .. note::
+
+ To validate a certificate for a particular service, you can use the
+ :func:`match_hostname` function.
If the ``binary_form`` parameter is :const:`True`, and a certificate was
provided, this method returns the DER-encoded form of the entire certificate
@@ -380,40 +830,388 @@ SSL sockets also have the following additional methods and attributes:
:const:`None` if you used :const:`CERT_NONE` (rather than
:const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`).
+ .. versionchanged:: 2.7.9
+ The returned dictionary includes additional items such as ``issuer`` and
+ ``notBefore``. Additionall :exc:`ValueError` is raised when the handshake
+ isn't done. The returned dictionary includes additional X509v3 extension
+ items such as ``crlDistributionPoints``, ``caIssuers`` and ``OCSP`` URIs.
+
.. method:: SSLSocket.cipher()
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 ``None``.
-.. method:: SSLSocket.do_handshake()
+.. method:: SSLSocket.compression()
+
+ Return the compression algorithm being used as a string, or ``None``
+ if the connection isn't compressed.
+
+ If the higher-level protocol supports its own compression mechanism,
+ you can use :data:`OP_NO_COMPRESSION` to disable SSL-level compression.
+
+ .. versionadded:: 2.7.9
+
+.. method:: SSLSocket.get_channel_binding(cb_type="tls-unique")
- Perform a TLS/SSL handshake. If this is used with a non-blocking socket, it
- may raise :exc:`SSLError` with an ``arg[0]`` of :const:`SSL_ERROR_WANT_READ`
- or :const:`SSL_ERROR_WANT_WRITE`, in which case it must be called again until
- it completes successfully. For example, to simulate the behavior of a
- blocking socket, one might write::
-
- while True:
- try:
- s.do_handshake()
- break
- except ssl.SSLError as err:
- if err.args[0] == ssl.SSL_ERROR_WANT_READ:
- select.select([s], [], [])
- elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:
- select.select([], [s], [])
- else:
- raise
+ Get channel binding data for current connection, as a bytes object. Returns
+ ``None`` if not connected or the handshake has not been completed.
+
+ The *cb_type* parameter allow selection of the desired channel binding
+ type. Valid channel binding types are listed in the
+ :data:`CHANNEL_BINDING_TYPES` list. Currently only the 'tls-unique' channel
+ binding, defined by :rfc:`5929`, is supported. :exc:`ValueError` will be
+ raised if an unsupported channel binding type is requested.
+
+ .. versionadded:: 2.7.9
+
+.. method:: SSLSocket.selected_npn_protocol()
+
+ Returns the protocol that was selected during the TLS/SSL handshake. If
+ :meth:`SSLContext.set_npn_protocols` was not called, or if the other party
+ does not support NPN, or if the handshake has not yet happened, this will
+ return ``None``.
+
+ .. versionadded:: 2.7.9
.. method:: SSLSocket.unwrap()
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
- socket instance returned should always be used for further communication with
- the other side of the connection, rather than the original socket instance
- (which may not function properly after the unwrap).
+ returned socket should always be used for further communication with the
+ other side of the connection, rather than the original socket.
+
+.. attribute:: SSLSocket.context
+
+ The :class:`SSLContext` object this SSL socket is tied to. If the SSL
+ socket was created using the top-level :func:`wrap_socket` function
+ (rather than :meth:`SSLContext.wrap_socket`), this is a custom context
+ object created for this SSL socket.
+
+ .. versionadded:: 2.7.9
+
+
+SSL Contexts
+------------
+
+.. versionadded:: 2.7.9
+
+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.
+
+.. class:: SSLContext(protocol)
+
+ Create a new SSL context. You must pass *protocol* which must be one
+ of the ``PROTOCOL_*`` constants defined in this module.
+ :data:`PROTOCOL_SSLv23` is currently recommended for maximum
+ interoperability.
+
+ .. seealso::
+ :func:`create_default_context` lets the :mod:`ssl` module choose
+ security settings for a given purpose.
+
+
+:class:`SSLContext` objects have the following methods and attributes:
+
+.. method:: SSLContext.cert_store_stats()
+
+ Get statistics about quantities of loaded X.509 certificates, count of
+ X.509 certificates flagged as CA certificates and certificate revocation
+ lists as dictionary.
+
+ Example for a context with one CA cert and one other cert::
+
+ >>> context.cert_store_stats()
+ {'crl': 0, 'x509_ca': 1, 'x509': 2}
+
+
+.. method:: SSLContext.load_cert_chain(certfile, keyfile=None, password=None)
+
+ Load a private key and the corresponding certificate. The *certfile*
+ 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 *keyfile* string, if present, must
+ point to a file containing the private key in. Otherwise the private
+ key will be taken from *certfile* as well. See the discussion of
+ :ref:`ssl-certificates` for more information on how the certificate
+ is stored in the *certfile*.
+
+ The *password* 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 *password* argument. It will be ignored if the private key is not
+ encrypted and no password is needed.
+
+ If the *password* 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.
+
+ An :class:`SSLError` is raised if the private key doesn't
+ match with the certificate.
+
+.. method:: SSLContext.load_default_certs(purpose=Purpose.SERVER_AUTH)
+
+ Load a set of default "certification authority" (CA) certificates from
+ default locations. On Windows it loads CA certs from the ``CA`` and
+ ``ROOT`` system stores. On other systems it calls
+ :meth:`SSLContext.set_default_verify_paths`. In the future the method may
+ load CA certificates from other locations, too.
+
+ The *purpose* flag specifies what kind of CA certificates are loaded. The
+ default settings :data:`Purpose.SERVER_AUTH` loads certificates, that are
+ flagged and trusted for TLS web server authentication (client side
+ sockets). :data:`Purpose.CLIENT_AUTH` loads CA certificates for client
+ certificate verification on the server side.
+
+.. method:: SSLContext.load_verify_locations(cafile=None, capath=None, cadata=None)
+
+ Load a set of "certification authority" (CA) certificates used to validate
+ other peers' certificates when :data:`verify_mode` is other than
+ :data:`CERT_NONE`. At least one of *cafile* or *capath* must be specified.
+
+ This method can also load certification revocation lists (CRLs) in PEM or
+ DER format. In order to make use of CRLs, :attr:`SSLContext.verify_flags`
+ must be configured properly.
+
+ The *cafile* string, if present, is the path to a file of concatenated
+ CA certificates in PEM format. See the discussion of
+ :ref:`ssl-certificates` for more information about how to arrange the
+ certificates in this file.
+
+ The *capath* string, if present, is
+ the path to a directory containing several CA certificates in PEM format,
+ following an `OpenSSL specific layout
+ <http://www.openssl.org/docs/ssl/SSL_CTX_load_verify_locations.html>`_.
+
+ The *cadata* object, if present, is either an ASCII string of one or more
+ PEM-encoded certificates or a bytes-like object of DER-encoded
+ certificates. Like with *capath* extra lines around PEM-encoded
+ certificates are ignored but at least one certificate must be present.
+
+.. method:: SSLContext.get_ca_certs(binary_form=False)
+
+ Get a list of loaded "certification authority" (CA) certificates. If the
+ ``binary_form`` parameter is :const:`False` each list
+ entry is a dict like the output of :meth:`SSLSocket.getpeercert`. Otherwise
+ the method returns a list of DER-encoded certificates. The returned list
+ does not contain certificates from *capath* unless a certificate was
+ requested and loaded by a SSL connection.
+
+.. method:: SSLContext.set_default_verify_paths()
+
+ 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.
+
+.. method:: SSLContext.set_ciphers(ciphers)
+
+ Set the available ciphers for sockets created with this context.
+ It should be a string in the `OpenSSL cipher list format
+ <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`_.
+ If no cipher can be selected (because compile-time options or other
+ configuration forbids use of all the specified ciphers), an
+ :class:`SSLError` will be raised.
+
+ .. note::
+ when connected, the :meth:`SSLSocket.cipher` method of SSL sockets will
+ give the currently selected cipher.
+
+.. method:: SSLContext.set_npn_protocols(protocols)