Gentoo Websites Logo
Go to: Gentoo Home Documentation Forums Lists Bugs Planet Store Wiki Get Gentoo!
View | Details | Raw Unified | Return to bug 673960 | Differences between
and this patch

Collapse All | Expand All

(-)a/Doc/library/ssl.rst (-19 / +99 lines)
Lines 179-185 instead. Link Here
179
   use.  Typically, the server chooses a particular protocol version, and the
179
   use.  Typically, the server chooses a particular protocol version, and the
180
   client must adapt to the server's choice.  Most of the versions are not
180
   client must adapt to the server's choice.  Most of the versions are not
181
   interoperable with the other versions.  If not specified, the default is
181
   interoperable with the other versions.  If not specified, the default is
182
   :data:`PROTOCOL_SSLv23`; it provides the most compatibility with other
182
   :data:`PROTOCOL_TLS`; it provides the most compatibility with other
183
   versions.
183
   versions.
184
184
185
   Here's a table showing which versions in a client (down the side) can connect
185
   Here's a table showing which versions in a client (down the side) can connect
Lines 188-198 instead. Link Here
188
     .. table::
188
     .. table::
189
189
190
       ========================  =========  =========  ==========  =========  ===========  ===========
190
       ========================  =========  =========  ==========  =========  ===========  ===========
191
        *client* / **server**    **SSLv2**  **SSLv3**  **SSLv23**  **TLSv1**  **TLSv1.1**  **TLSv1.2**
191
        *client* / **server**    **SSLv2**  **SSLv3**  **TLS**     **TLSv1**  **TLSv1.1**  **TLSv1.2**
192
       ------------------------  ---------  ---------  ----------  ---------  -----------  -----------
192
       ------------------------  ---------  ---------  ----------  ---------  -----------  -----------
193
        *SSLv2*                    yes        no         yes         no         no         no
193
        *SSLv2*                    yes        no         yes         no         no         no
194
        *SSLv3*                    no         yes        yes         no         no         no
194
        *SSLv3*                    no         yes        yes         no         no         no
195
        *SSLv23*                   no         yes        yes         yes        yes        yes
195
        *TLS* (*SSLv23*)           no         yes        yes         yes        yes        yes
196
        *TLSv1*                    no         no         yes         yes        no         no
196
        *TLSv1*                    no         no         yes         yes        no         no
197
        *TLSv1.1*                  no         no         yes         no         yes        no
197
        *TLSv1.1*                  no         no         yes         no         yes        no
198
        *TLSv1.2*                  no         no         yes         no         no         yes
198
        *TLSv1.2*                  no         no         yes         no         no         yes
Lines 245-251 purposes. Link Here
245
   :const:`None`, this function can choose to trust the system's default
245
   :const:`None`, this function can choose to trust the system's default
246
   CA certificates instead.
246
   CA certificates instead.
247
247
248
   The settings are: :data:`PROTOCOL_SSLv23`, :data:`OP_NO_SSLv2`, and
248
   The settings are: :data:`PROTOCOL_TLS`, :data:`OP_NO_SSLv2`, and
249
   :data:`OP_NO_SSLv3` with high encryption cipher suites without RC4 and
249
   :data:`OP_NO_SSLv3` with high encryption cipher suites without RC4 and
250
   without unauthenticated cipher suites. Passing :data:`~Purpose.SERVER_AUTH`
250
   without unauthenticated cipher suites. Passing :data:`~Purpose.SERVER_AUTH`
251
   as *purpose* sets :data:`~SSLContext.verify_mode` to :data:`CERT_REQUIRED`
251
   as *purpose* sets :data:`~SSLContext.verify_mode` to :data:`CERT_REQUIRED`
Lines 323-328 Random generation Link Here
323
323
324
   .. versionadded:: 3.3
324
   .. versionadded:: 3.3
325
325
326
   .. deprecated:: 3.5.3
327
328
      OpenSSL has deprecated :func:`ssl.RAND_pseudo_bytes`, use
329
      :func:`ssl.RAND_bytes` instead.
330
326
.. function:: RAND_status()
331
.. function:: RAND_status()
327
332
328
   Return ``True`` if the SSL pseudo-random number generator has been seeded
333
   Return ``True`` if the SSL pseudo-random number generator has been seeded
Lines 341-346 Random generation Link Here
341
   See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources
346
   See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources
342
   of entropy-gathering daemons.
347
   of entropy-gathering daemons.
343
348
349
   Availability: not available with LibreSSL and OpenSSL > 1.1.0
350
344
.. function:: RAND_add(bytes, entropy)
351
.. function:: RAND_add(bytes, entropy)
345
352
346
   Mix the given *bytes* into the SSL pseudo-random number generator.  The
353
   Mix the given *bytes* into the SSL pseudo-random number generator.  The
Lines 396-402 Certificate handling Link Here
396
     >>> time.ctime(ssl.cert_time_to_seconds("May  9 00:00:00 2007 GMT"))
403
     >>> time.ctime(ssl.cert_time_to_seconds("May  9 00:00:00 2007 GMT"))
397
     'Wed May  9 00:00:00 2007'
404
     'Wed May  9 00:00:00 2007'
398
405
399
.. function:: get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None)
406
.. function:: get_server_certificate(addr, ssl_version=PROTOCOL_TLS, ca_certs=None)
400
407
401
   Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
408
   Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
402
   *port-number*) pair, fetches the server's certificate, and returns it as a
409
   *port-number*) pair, fetches the server's certificate, and returns it as a
Lines 410-415 Certificate handling Link Here
410
   .. versionchanged:: 3.3
417
   .. versionchanged:: 3.3
411
      This function is now IPv6-compatible.
418
      This function is now IPv6-compatible.
412
419
420
   .. versionchanged:: 3.5 (backported)
421
      The default *ssl_version* is changed from :data:`PROTOCOL_SSLv3` to
422
      :data:`PROTOCOL_TLS` for maximum compatibility with modern servers.
423
413
.. function:: DER_cert_to_PEM_cert(DER_cert_bytes)
424
.. function:: DER_cert_to_PEM_cert(DER_cert_bytes)
414
425
415
   Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded
426
   Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded
Lines 434-439 Certificate handling Link Here
434
   * :attr:`openssl_capath_env` - OpenSSL's environment key that points to a capath,
445
   * :attr:`openssl_capath_env` - OpenSSL's environment key that points to a capath,
435
   * :attr:`openssl_capath` - hard coded path to a capath directory
446
   * :attr:`openssl_capath` - hard coded path to a capath directory
436
447
448
   Availability: LibreSSL ignores the environment vars
449
   :attr:`openssl_cafile_env` and :attr:`openssl_capath_env`
450
437
   .. versionadded:: 3.4
451
   .. versionadded:: 3.4
438
452
439
.. function:: enum_certificates(store_name)
453
.. function:: enum_certificates(store_name)
Lines 551-561 Constants Link Here
551
565
552
   .. versionadded:: 3.4.4
566
   .. versionadded:: 3.4.4
553
567
554
.. data:: PROTOCOL_SSLv23
568
.. data:: PROTOCOL_TLS
555
569
556
   Selects the highest protocol version that both the client and server support.
570
   Selects the highest protocol version that both the client and server support.
557
   Despite the name, this option can select "TLS" protocols as well as "SSL".
571
   Despite the name, this option can select "TLS" protocols as well as "SSL".
558
572
573
   .. versionadded:: 3.5.3 (backported)
574
575
.. data:: PROTOCOL_SSLv23
576
577
   Alias for data:`PROTOCOL_TLS`.
578
579
   .. deprecated:: 3.5.3
580
581
      Use data:`PROTOCOL_TLS` instead.
582
559
.. data:: PROTOCOL_SSLv2
583
.. data:: PROTOCOL_SSLv2
560
584
561
   Selects SSL version 2 as the channel encryption protocol.
585
   Selects SSL version 2 as the channel encryption protocol.
Lines 567-572 Constants Link Here
567
591
568
      SSL version 2 is insecure.  Its use is highly discouraged.
592
      SSL version 2 is insecure.  Its use is highly discouraged.
569
593
594
   .. deprecated:: 3.5.3
595
596
      OpenSSL has removed support for SSLv2.
597
570
.. data:: PROTOCOL_SSLv3
598
.. data:: PROTOCOL_SSLv3
571
599
572
   Selects SSL version 3 as the channel encryption protocol.
600
   Selects SSL version 3 as the channel encryption protocol.
Lines 578-587 Constants Link Here
578
606
579
      SSL version 3 is insecure.  Its use is highly discouraged.
607
      SSL version 3 is insecure.  Its use is highly discouraged.
580
608
609
   .. deprecated:: 3.5.3
610
611
      OpenSSL has deprecated all version specific protocols. Use the default
612
      protocol data:`PROTOCOL_TLS` with flags like data:`OP_NO_SSLv3` instead.
613
581
.. data:: PROTOCOL_TLSv1
614
.. data:: PROTOCOL_TLSv1
582
615
583
   Selects TLS version 1.0 as the channel encryption protocol.
616
   Selects TLS version 1.0 as the channel encryption protocol.
584
617
618
   .. deprecated:: 3.5.3
619
620
      OpenSSL has deprecated all version specific protocols. Use the default
621
      protocol data:`PROTOCOL_TLS` with flags like data:`OP_NO_SSLv3` instead.
622
585
.. data:: PROTOCOL_TLSv1_1
623
.. data:: PROTOCOL_TLSv1_1
586
624
587
   Selects TLS version 1.1 as the channel encryption protocol.
625
   Selects TLS version 1.1 as the channel encryption protocol.
Lines 589-594 Constants Link Here
589
627
590
   .. versionadded:: 3.4
628
   .. versionadded:: 3.4
591
629
630
   .. deprecated:: 3.5.3
631
632
      OpenSSL has deprecated all version specific protocols. Use the default
633
      protocol data:`PROTOCOL_TLS` with flags like data:`OP_NO_SSLv3` instead.
634
592
.. data:: PROTOCOL_TLSv1_2
635
.. data:: PROTOCOL_TLSv1_2
593
636
594
   Selects TLS version 1.2 as the channel encryption protocol. This is the
637
   Selects TLS version 1.2 as the channel encryption protocol. This is the
Lines 597-602 Constants Link Here
597
640
598
   .. versionadded:: 3.4
641
   .. versionadded:: 3.4
599
642
643
   .. deprecated:: 3.5.3
644
645
      OpenSSL has deprecated all version specific protocols. Use the default
646
      protocol data:`PROTOCOL_TLS` with flags like data:`OP_NO_SSLv3` instead.
647
600
.. data:: OP_ALL
648
.. data:: OP_ALL
601
649
602
   Enables workarounds for various bugs present in other SSL implementations.
650
   Enables workarounds for various bugs present in other SSL implementations.
Lines 608-630 Constants Link Here
608
.. data:: OP_NO_SSLv2
656
.. data:: OP_NO_SSLv2
609
657
610
   Prevents an SSLv2 connection.  This option is only applicable in
658
   Prevents an SSLv2 connection.  This option is only applicable in
611
   conjunction with :const:`PROTOCOL_SSLv23`.  It prevents the peers from
659
   conjunction with :const:`PROTOCOL_TLS`.  It prevents the peers from
612
   choosing SSLv2 as the protocol version.
660
   choosing SSLv2 as the protocol version.
613
661
614
   .. versionadded:: 3.2
662
   .. versionadded:: 3.2
615
663
664
   .. deprecated:: 3.5.3
665
666
      SSLv2 is deprecated
667
668
616
.. data:: OP_NO_SSLv3
669
.. data:: OP_NO_SSLv3
617
670
618
   Prevents an SSLv3 connection.  This option is only applicable in
671
   Prevents an SSLv3 connection.  This option is only applicable in
619
   conjunction with :const:`PROTOCOL_SSLv23`.  It prevents the peers from
672
   conjunction with :const:`PROTOCOL_TLS`.  It prevents the peers from
620
   choosing SSLv3 as the protocol version.
673
   choosing SSLv3 as the protocol version.
621
674
622
   .. versionadded:: 3.2
675
   .. versionadded:: 3.2
623
676
677
   .. deprecated:: 3.5.3
678
679
      SSLv3 is deprecated
680
624
.. data:: OP_NO_TLSv1
681
.. data:: OP_NO_TLSv1
625
682
626
   Prevents a TLSv1 connection.  This option is only applicable in
683
   Prevents a TLSv1 connection.  This option is only applicable in
627
   conjunction with :const:`PROTOCOL_SSLv23`.  It prevents the peers from
684
   conjunction with :const:`PROTOCOL_TLS`.  It prevents the peers from
628
   choosing TLSv1 as the protocol version.
685
   choosing TLSv1 as the protocol version.
629
686
630
   .. versionadded:: 3.2
687
   .. versionadded:: 3.2
Lines 632-638 Constants Link Here
632
.. data:: OP_NO_TLSv1_1
689
.. data:: OP_NO_TLSv1_1
633
690
634
   Prevents a TLSv1.1 connection. This option is only applicable in conjunction
691
   Prevents a TLSv1.1 connection. This option is only applicable in conjunction
635
   with :const:`PROTOCOL_SSLv23`. It prevents the peers from choosing TLSv1.1 as
692
   with :const:`PROTOCOL_TLS`. It prevents the peers from choosing TLSv1.1 as
636
   the protocol version. Available only with openssl version 1.0.1+.
693
   the protocol version. Available only with openssl version 1.0.1+.
637
694
638
   .. versionadded:: 3.4
695
   .. versionadded:: 3.4
Lines 640-646 Constants Link Here
640
.. data:: OP_NO_TLSv1_2
697
.. data:: OP_NO_TLSv1_2
641
698
642
   Prevents a TLSv1.2 connection. This option is only applicable in conjunction
699
   Prevents a TLSv1.2 connection. This option is only applicable in conjunction
643
   with :const:`PROTOCOL_SSLv23`. It prevents the peers from choosing TLSv1.2 as
700
   with :const:`PROTOCOL_TLS`. It prevents the peers from choosing TLSv1.2 as
644
   the protocol version. Available only with openssl version 1.0.1+.
701
   the protocol version. Available only with openssl version 1.0.1+.
645
702
646
   .. versionadded:: 3.4
703
   .. versionadded:: 3.4
Lines 1002-1018 such as SSL configuration options, certificate(s) and private key(s). Link Here
1002
It also manages a cache of SSL sessions for server-side sockets, in order
1059
It also manages a cache of SSL sessions for server-side sockets, in order
1003
to speed up repeated connections from the same clients.
1060
to speed up repeated connections from the same clients.
1004
1061
1005
.. class:: SSLContext(protocol)
1062
.. class:: SSLContext(protocol=PROTOCOL_TLS)
1006
1063
1007
   Create a new SSL context.  You must pass *protocol* which must be one
1064
   Create a new SSL context.  You may pass *protocol* which must be one
1008
   of the ``PROTOCOL_*`` constants defined in this module.
1065
   of the ``PROTOCOL_*`` constants defined in this module.
1009
   :data:`PROTOCOL_SSLv23` is currently recommended for maximum
1066
   :data:`PROTOCOL_TLS` is currently recommended for maximum
1010
   interoperability.
1067
   interoperability and default value.
1011
1068
1012
   .. seealso::
1069
   .. seealso::
1013
      :func:`create_default_context` lets the :mod:`ssl` module choose
1070
      :func:`create_default_context` lets the :mod:`ssl` module choose
1014
      security settings for a given purpose.
1071
      security settings for a given purpose.
1015
1072
1073
   .. versionchanged:: 3.5.3 (backported)
1074
1075
      :data:`PROTOCOL_TLS` is the default value.
1076
1016
1077
1017
:class:`SSLContext` objects have the following methods and attributes:
1078
:class:`SSLContext` objects have the following methods and attributes:
1018
1079
Lines 1141-1146 to speed up repeated connections from the same clients. Link Here
1141
      when connected, the :meth:`SSLSocket.cipher` method of SSL sockets will
1202
      when connected, the :meth:`SSLSocket.cipher` method of SSL sockets will
1142
      give the currently selected cipher.
1203
      give the currently selected cipher.
1143
1204
1205
.. method:: SSLContext.set_alpn_protocols(protocols)
1206
1207
   Specify which protocols the socket should advertise during the SSL/TLS
1208
   handshake. It should be a list of ASCII strings, like ``['http/1.1',
1209
   'spdy/2']``, ordered by preference. The selection of a protocol will happen
1210
   during the handshake, and will play out according to :rfc:`7301`. After a
1211
   successful handshake, the :meth:`SSLSocket.selected_alpn_protocol` method will
1212
   return the agreed-upon protocol.
1213
1214
   This method will raise :exc:`NotImplementedError` if :data:`HAS_ALPN` is
1215
   False.
1216
1217
   OpenSSL 1.1.0+ will abort the handshake and raise :exc:`SSLError` when
1218
   both sides support ALPN but cannot agree on a protocol.
1219
1220
   .. versionadded:: 3.5 (backported)
1221
1144
.. method:: SSLContext.set_npn_protocols(protocols)
1222
.. method:: SSLContext.set_npn_protocols(protocols)
1145
1223
1146
   Specify which protocols the socket should advertise during the SSL/TLS
1224
   Specify which protocols the socket should advertise during the SSL/TLS
Lines 1495-1501 If you prefer to tune security settings yourself, you might create Link Here
1495
a context from scratch (but beware that you might not get the settings
1573
a context from scratch (but beware that you might not get the settings
1496
right)::
1574
right)::
1497
1575
1498
   >>> context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
1576
   >>> context = ssl.SSLContext(ssl.PROTOCOL_TLS)
1499
   >>> context.verify_mode = ssl.CERT_REQUIRED
1577
   >>> context.verify_mode = ssl.CERT_REQUIRED
1500
   >>> context.check_hostname = True
1578
   >>> context.check_hostname = True
1501
   >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")
1579
   >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")
Lines 1760-1774 Protocol versions Link Here
1760
1838
1761
SSL versions 2 and 3 are considered insecure and are therefore dangerous to
1839
SSL versions 2 and 3 are considered insecure and are therefore dangerous to
1762
use.  If you want maximum compatibility between clients and servers, it is
1840
use.  If you want maximum compatibility between clients and servers, it is
1763
recommended to use :const:`PROTOCOL_SSLv23` as the protocol version and then
1841
recommended to use :const:`PROTOCOL_TLS` as the protocol version and then
1764
disable SSLv2 and SSLv3 explicitly using the :data:`SSLContext.options`
1842
disable SSLv2 and SSLv3 explicitly using the :data:`SSLContext.options`
1765
attribute::
1843
attribute::
1766
1844
1767
   context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
1845
   context = ssl.SSLContext(ssl.PROTOCOL_TLS)
1768
   context.options |= ssl.OP_NO_SSLv2
1846
   context.options |= ssl.OP_NO_SSLv2
1769
   context.options |= ssl.OP_NO_SSLv3
1847
   context.options |= ssl.OP_NO_SSLv3
1848
   context.options |= ssl.OP_NO_TLSv1
1849
   context.options |= ssl.OP_NO_TLSv1_1
1770
1850
1771
The SSL context created above will only allow TLSv1 and later (if
1851
The SSL context created above will only allow TLSv1.2 and later (if
1772
supported by your system) connections.
1852
supported by your system) connections.
1773
1853
1774
Cipher selection
1854
Cipher selection
(-)a/Lib/ssl.py (-21 / +17 lines)
Lines 51-56 The following constants identify various SSL protocol variants: Link Here
51
PROTOCOL_SSLv2
51
PROTOCOL_SSLv2
52
PROTOCOL_SSLv3
52
PROTOCOL_SSLv3
53
PROTOCOL_SSLv23
53
PROTOCOL_SSLv23
54
PROTOCOL_TLS
54
PROTOCOL_TLSv1
55
PROTOCOL_TLSv1
55
PROTOCOL_TLSv1_1
56
PROTOCOL_TLSv1_1
56
PROTOCOL_TLSv1_2
57
PROTOCOL_TLSv1_2
Lines 92-98 import re Link Here
92
import sys
93
import sys
93
import os
94
import os
94
from collections import namedtuple
95
from collections import namedtuple
95
from enum import Enum as _Enum
96
from enum import Enum as _Enum, IntEnum as _IntEnum
96
97
97
import _ssl             # if we can't import it, let the error propagate
98
import _ssl             # if we can't import it, let the error propagate
98
99
Lines 126-148 from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN Link Here
126
127
127
from _ssl import _OPENSSL_API_VERSION
128
from _ssl import _OPENSSL_API_VERSION
128
129
130
_IntEnum._convert(
131
        '_SSLMethod', __name__,
132
        lambda name: name.startswith('PROTOCOL_') and name != 'PROTOCOL_SSLv23',
133
        source=_ssl)
134
135
PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_TLS
136
_PROTOCOL_NAMES = {value: name for name, value in _SSLMethod.__members__.items()}
129
137
130
_PROTOCOL_NAMES = {value: name for name, value in globals().items() if name.startswith('PROTOCOL_')}
131
try:
138
try:
132
    from _ssl import PROTOCOL_SSLv2
133
    _SSLv2_IF_EXISTS = PROTOCOL_SSLv2
139
    _SSLv2_IF_EXISTS = PROTOCOL_SSLv2
134
except ImportError:
140
except NameError:
135
    _SSLv2_IF_EXISTS = None
141
    _SSLv2_IF_EXISTS = None
136
else:
137
    _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2"
138
139
try:
140
    from _ssl import PROTOCOL_TLSv1_1, PROTOCOL_TLSv1_2
141
except ImportError:
142
    pass
143
else:
144
    _PROTOCOL_NAMES[PROTOCOL_TLSv1_1] = "TLSv1.1"
145
    _PROTOCOL_NAMES[PROTOCOL_TLSv1_2] = "TLSv1.2"
146
142
147
if sys.platform == "win32":
143
if sys.platform == "win32":
148
    from _ssl import enum_certificates, enum_crls
144
    from _ssl import enum_certificates, enum_crls
Lines 348-360 class SSLContext(_SSLContext): Link Here
348
    __slots__ = ('protocol', '__weakref__')
344
    __slots__ = ('protocol', '__weakref__')
349
    _windows_cert_stores = ("CA", "ROOT")
345
    _windows_cert_stores = ("CA", "ROOT")
350
346
351
    def __new__(cls, protocol, *args, **kwargs):
347
    def __new__(cls, protocol=PROTOCOL_TLS, *args, **kwargs):
352
        self = _SSLContext.__new__(cls, protocol)
348
        self = _SSLContext.__new__(cls, protocol)
353
        if protocol != _SSLv2_IF_EXISTS:
349
        if protocol != _SSLv2_IF_EXISTS:
354
            self.set_ciphers(_DEFAULT_CIPHERS)
350
            self.set_ciphers(_DEFAULT_CIPHERS)
355
        return self
351
        return self
356
352
357
    def __init__(self, protocol):
353
    def __init__(self, protocol=PROTOCOL_TLS):
358
        self.protocol = protocol
354
        self.protocol = protocol
359
355
360
    def wrap_socket(self, sock, server_side=False,
356
    def wrap_socket(self, sock, server_side=False,
Lines 408-414 def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None, Link Here
408
    if not isinstance(purpose, _ASN1Object):
404
    if not isinstance(purpose, _ASN1Object):
409
        raise TypeError(purpose)
405
        raise TypeError(purpose)
410
406
411
    context = SSLContext(PROTOCOL_SSLv23)
407
    context = SSLContext(PROTOCOL_TLS)
412
408
413
    # SSLv2 considered harmful.
409
    # SSLv2 considered harmful.
414
    context.options |= OP_NO_SSLv2
410
    context.options |= OP_NO_SSLv2
Lines 445-451 def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None, Link Here
445
        context.load_default_certs(purpose)
441
        context.load_default_certs(purpose)
446
    return context
442
    return context
447
443
448
def _create_unverified_context(protocol=PROTOCOL_SSLv23, *, cert_reqs=None,
444
def _create_unverified_context(protocol=PROTOCOL_TLS, *, cert_reqs=None,
449
                           check_hostname=False, purpose=Purpose.SERVER_AUTH,
445
                           check_hostname=False, purpose=Purpose.SERVER_AUTH,
450
                           certfile=None, keyfile=None,
446
                           certfile=None, keyfile=None,
451
                           cafile=None, capath=None, cadata=None):
447
                           cafile=None, capath=None, cadata=None):
Lines 501-507 class SSLSocket(socket): Link Here
501
497
502
    def __init__(self, sock=None, keyfile=None, certfile=None,
498
    def __init__(self, sock=None, keyfile=None, certfile=None,
503
                 server_side=False, cert_reqs=CERT_NONE,
499
                 server_side=False, cert_reqs=CERT_NONE,
504
                 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
500
                 ssl_version=PROTOCOL_TLS, ca_certs=None,
505
                 do_handshake_on_connect=True,
501
                 do_handshake_on_connect=True,
506
                 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
502
                 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
507
                 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
503
                 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
Lines 883-889 class SSLSocket(socket): Link Here
883
879
884
def wrap_socket(sock, keyfile=None, certfile=None,
880
def wrap_socket(sock, keyfile=None, certfile=None,
885
                server_side=False, cert_reqs=CERT_NONE,
881
                server_side=False, cert_reqs=CERT_NONE,
886
                ssl_version=PROTOCOL_SSLv23, ca_certs=None,
882
                ssl_version=PROTOCOL_TLS, ca_certs=None,
887
                do_handshake_on_connect=True,
883
                do_handshake_on_connect=True,
888
                suppress_ragged_eofs=True,
884
                suppress_ragged_eofs=True,
889
                ciphers=None):
885
                ciphers=None):
Lines 930-936 def PEM_cert_to_DER_cert(pem_cert_string): Link Here
930
    d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
926
    d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
931
    return base64.decodebytes(d.encode('ASCII', 'strict'))
927
    return base64.decodebytes(d.encode('ASCII', 'strict'))
932
928
933
def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
929
def get_server_certificate(addr, ssl_version=PROTOCOL_TLS, ca_certs=None):
934
    """Retrieve the certificate from the server at the specified address,
930
    """Retrieve the certificate from the server at the specified address,
935
    and return it as a PEM-encoded string.
931
    and return it as a PEM-encoded string.
936
    If 'ca_certs' is specified, validate the server cert against it.
932
    If 'ca_certs' is specified, validate the server cert against it.
(-)a/Lib/test/test_ssl.py (-11 / +212 lines)
Lines 23-28 ssl = support.import_module("ssl") Link Here
23
23
24
PROTOCOLS = sorted(ssl._PROTOCOL_NAMES)
24
PROTOCOLS = sorted(ssl._PROTOCOL_NAMES)
25
HOST = support.HOST
25
HOST = support.HOST
26
IS_LIBRESSL = ssl.OPENSSL_VERSION.startswith('LibreSSL')
27
IS_OPENSSL_1_1 = not IS_LIBRESSL and ssl.OPENSSL_VERSION_INFO >= (1, 1, 0)
28
26
29
27
def data_file(*name):
30
def data_file(*name):
28
    return os.path.join(os.path.dirname(__file__), *name)
31
    return os.path.join(os.path.dirname(__file__), *name)
Lines 134-139 class BasicSocketTests(unittest.TestCase): Link Here
134
        self.assertIn(ssl.HAS_SNI, {True, False})
137
        self.assertIn(ssl.HAS_SNI, {True, False})
135
        self.assertIn(ssl.HAS_ECDH, {True, False})
138
        self.assertIn(ssl.HAS_ECDH, {True, False})
136
139
140
    def test_str_for_enums(self):
141
        # Make sure that the PROTOCOL_* constants have enum-like string
142
        # reprs.
143
        proto = ssl.PROTOCOL_TLS
144
        self.assertEqual(str(proto), '_SSLMethod.PROTOCOL_TLS')
145
        ctx = ssl.SSLContext(proto)
146
        self.assertIs(ctx.protocol, proto)
147
137
    def test_random(self):
148
    def test_random(self):
138
        v = ssl.RAND_status()
149
        v = ssl.RAND_status()
139
        if support.verbose:
150
        if support.verbose:
Lines 296-304 class BasicSocketTests(unittest.TestCase): Link Here
296
        self.assertGreaterEqual(status, 0)
307
        self.assertGreaterEqual(status, 0)
297
        self.assertLessEqual(status, 15)
308
        self.assertLessEqual(status, 15)
298
        # Version string as returned by {Open,Libre}SSL, the format might change
309
        # Version string as returned by {Open,Libre}SSL, the format might change
299
        if "LibreSSL" in s:
310
        if IS_LIBRESSL:
300
            self.assertTrue(s.startswith("LibreSSL {:d}.{:d}".format(major, minor)),
311
            self.assertTrue(s.startswith("LibreSSL {:d}".format(major)),
301
                            (s, t))
312
                            (s, t, hex(n)))
302
        else:
313
        else:
303
            self.assertTrue(s.startswith("OpenSSL {:d}.{:d}.{:d}".format(major, minor, fix)),
314
            self.assertTrue(s.startswith("OpenSSL {:d}.{:d}.{:d}".format(major, minor, fix)),
304
                            (s, t))
315
                            (s, t))
Lines 655-661 class ContextTests(unittest.TestCase): Link Here
655
    def test_constructor(self):
666
    def test_constructor(self):
656
        for protocol in PROTOCOLS:
667
        for protocol in PROTOCOLS:
657
            ssl.SSLContext(protocol)
668
            ssl.SSLContext(protocol)
658
        self.assertRaises(TypeError, ssl.SSLContext)
669
        ctx = ssl.SSLContext()
670
        self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLS)
659
        self.assertRaises(ValueError, ssl.SSLContext, -1)
671
        self.assertRaises(ValueError, ssl.SSLContext, -1)
660
        self.assertRaises(ValueError, ssl.SSLContext, 42)
672
        self.assertRaises(ValueError, ssl.SSLContext, 42)
661
673
Lines 676-690 class ContextTests(unittest.TestCase): Link Here
676
    def test_options(self):
688
    def test_options(self):
677
        ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
689
        ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
678
        # OP_ALL | OP_NO_SSLv2 | OP_NO_SSLv3 is the default value
690
        # OP_ALL | OP_NO_SSLv2 | OP_NO_SSLv3 is the default value
679
        self.assertEqual(ssl.OP_ALL | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3,
691
        default = (ssl.OP_ALL | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3)
680
                         ctx.options)
692
        if not IS_LIBRESSL and ssl.OPENSSL_VERSION_INFO >= (1, 1, 0):
693
            default |= ssl.OP_NO_COMPRESSION
694
        self.assertEqual(default, ctx.options)
681
        ctx.options |= ssl.OP_NO_TLSv1
695
        ctx.options |= ssl.OP_NO_TLSv1
682
        self.assertEqual(ssl.OP_ALL | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO_TLSv1,
696
        self.assertEqual(default | ssl.OP_NO_TLSv1, ctx.options)
683
                         ctx.options)
684
        if can_clear_options():
697
        if can_clear_options():
685
            ctx.options = (ctx.options & ~ssl.OP_NO_SSLv2) | ssl.OP_NO_TLSv1
698
            ctx.options = (ctx.options & ~ssl.OP_NO_TLSv1)
686
            self.assertEqual(ssl.OP_ALL | ssl.OP_NO_TLSv1 | ssl.OP_NO_SSLv3,
699
            self.assertEqual(default, ctx.options)
687
                             ctx.options)
688
            ctx.options = 0
700
            ctx.options = 0
689
            # Ubuntu has OP_NO_SSLv3 forced on by default
701
            # Ubuntu has OP_NO_SSLv3 forced on by default
690
            self.assertEqual(0, ctx.options & ~ssl.OP_NO_SSLv3)
702
            self.assertEqual(0, ctx.options & ~ssl.OP_NO_SSLv3)
Lines 1020-1025 class ContextTests(unittest.TestCase): Link Here
1020
        self.assertRaises(TypeError, ctx.load_default_certs, 'SERVER_AUTH')
1032
        self.assertRaises(TypeError, ctx.load_default_certs, 'SERVER_AUTH')
1021
1033
1022
    @unittest.skipIf(sys.platform == "win32", "not-Windows specific")
1034
    @unittest.skipIf(sys.platform == "win32", "not-Windows specific")
1035
    @unittest.skipIf(IS_LIBRESSL, "LibreSSL doesn't support env vars")
1023
    def test_load_default_certs_env(self):
1036
    def test_load_default_certs_env(self):
1024
        ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1037
        ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1025
        with support.EnvironmentVarGuard() as env:
1038
        with support.EnvironmentVarGuard() as env:
Lines 1505-1510 class NetworkedTests(unittest.TestCase): Link Here
1505
                self.assertIs(ss.context, ctx2)
1518
                self.assertIs(ss.context, ctx2)
1506
                self.assertIs(ss._sslobj.context, ctx2)
1519
                self.assertIs(ss._sslobj.context, ctx2)
1507
1520
1521
1522
class NetworkedBIOTests(unittest.TestCase):
1523
1524
    def ssl_io_loop(self, sock, incoming, outgoing, func, *args, **kwargs):
1525
        # A simple IO loop. Call func(*args) depending on the error we get
1526
        # (WANT_READ or WANT_WRITE) move data between the socket and the BIOs.
1527
        timeout = kwargs.get('timeout', 10)
1528
        count = 0
1529
        while True:
1530
            errno = None
1531
            count += 1
1532
            try:
1533
                ret = func(*args)
1534
            except ssl.SSLError as e:
1535
                if e.errno not in (ssl.SSL_ERROR_WANT_READ,
1536
                                   ssl.SSL_ERROR_WANT_WRITE):
1537
                    raise
1538
                errno = e.errno
1539
            # Get any data from the outgoing BIO irrespective of any error, and
1540
            # send it to the socket.
1541
            buf = outgoing.read()
1542
            sock.sendall(buf)
1543
            # If there's no error, we're done. For WANT_READ, we need to get
1544
            # data from the socket and put it in the incoming BIO.
1545
            if errno is None:
1546
                break
1547
            elif errno == ssl.SSL_ERROR_WANT_READ:
1548
                buf = sock.recv(32768)
1549
                if buf:
1550
                    incoming.write(buf)
1551
                else:
1552
                    incoming.write_eof()
1553
        if support.verbose:
1554
            sys.stdout.write("Needed %d calls to complete %s().\n"
1555
                             % (count, func.__name__))
1556
        return ret
1557
1558
    def test_handshake(self):
1559
        with support.transient_internet(REMOTE_HOST):
1560
            sock = socket.socket(socket.AF_INET)
1561
            sock.connect((REMOTE_HOST, 443))
1562
            incoming = ssl.MemoryBIO()
1563
            outgoing = ssl.MemoryBIO()
1564
            ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
1565
            ctx.verify_mode = ssl.CERT_REQUIRED
1566
            ctx.load_verify_locations(REMOTE_ROOT_CERT)
1567
            ctx.check_hostname = True
1568
            sslobj = ctx.wrap_bio(incoming, outgoing, False, REMOTE_HOST)
1569
            self.assertIs(sslobj._sslobj.owner, sslobj)
1570
            self.assertIsNone(sslobj.cipher())
1571
            self.assertIsNotNone(sslobj.shared_ciphers())
1572
            self.assertRaises(ValueError, sslobj.getpeercert)
1573
            if 'tls-unique' in ssl.CHANNEL_BINDING_TYPES:
1574
                self.assertIsNone(sslobj.get_channel_binding('tls-unique'))
1575
            self.ssl_io_loop(sock, incoming, outgoing, sslobj.do_handshake)
1576
            self.assertTrue(sslobj.cipher())
1577
            self.assertIsNotNone(sslobj.shared_ciphers())
1578
            self.assertTrue(sslobj.getpeercert())
1579
            if 'tls-unique' in ssl.CHANNEL_BINDING_TYPES:
1580
                self.assertTrue(sslobj.get_channel_binding('tls-unique'))
1581
            try:
1582
                self.ssl_io_loop(sock, incoming, outgoing, sslobj.unwrap)
1583
            except ssl.SSLSyscallError:
1584
                # self-signed.pythontest.net probably shuts down the TCP
1585
                # connection without sending a secure shutdown message, and
1586
                # this is reported as SSL_ERROR_SYSCALL
1587
                pass
1588
            self.assertRaises(ssl.SSLError, sslobj.write, b'foo')
1589
            sock.close()
1590
1591
    def test_read_write_data(self):
1592
        with support.transient_internet(REMOTE_HOST):
1593
            sock = socket.socket(socket.AF_INET)
1594
            sock.connect((REMOTE_HOST, 443))
1595
            incoming = ssl.MemoryBIO()
1596
            outgoing = ssl.MemoryBIO()
1597
            ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
1598
            ctx.verify_mode = ssl.CERT_NONE
1599
            sslobj = ctx.wrap_bio(incoming, outgoing, False)
1600
            self.ssl_io_loop(sock, incoming, outgoing, sslobj.do_handshake)
1601
            req = b'GET / HTTP/1.0\r\n\r\n'
1602
            self.ssl_io_loop(sock, incoming, outgoing, sslobj.write, req)
1603
            buf = self.ssl_io_loop(sock, incoming, outgoing, sslobj.read, 1024)
1604
            self.assertEqual(buf[:5], b'HTTP/')
1605
            self.ssl_io_loop(sock, incoming, outgoing, sslobj.unwrap)
1606
            sock.close()
1607
1608
1508
try:
1609
try:
1509
    import threading
1610
    import threading
1510
except ImportError:
1611
except ImportError:
Lines 2629-2634 else: Link Here
2629
                        s.connect((HOST, server.port))
2730
                        s.connect((HOST, server.port))
2630
            self.assertIn("no shared cipher", str(server.conn_errors[0]))
2731
            self.assertIn("no shared cipher", str(server.conn_errors[0]))
2631
2732
2733
        def test_version_basic(self):
2734
            """
2735
            Basic tests for SSLSocket.version().
2736
            More tests are done in the test_protocol_*() methods.
2737
            """
2738
            context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
2739
            with ThreadedEchoServer(CERTFILE,
2740
                                    ssl_version=ssl.PROTOCOL_TLSv1,
2741
                                    chatty=False) as server:
2742
                with context.wrap_socket(socket.socket()) as s:
2743
                    self.assertIs(s.version(), None)
2744
                    s.connect((HOST, server.port))
2745
                    self.assertEqual(s.version(), 'TLSv1')
2746
                self.assertIs(s.version(), None)
2747
2632
        @unittest.skipUnless(ssl.HAS_ECDH, "test requires ECDH-enabled OpenSSL")
2748
        @unittest.skipUnless(ssl.HAS_ECDH, "test requires ECDH-enabled OpenSSL")
2633
        def test_default_ecdh_curve(self):
2749
        def test_default_ecdh_curve(self):
2634
            # Issue #21015: elliptic curve-based Diffie Hellman key exchange
2750
            # Issue #21015: elliptic curve-based Diffie Hellman key exchange
Lines 2738-2743 else: Link Here
2738
            if "ADH" not in parts and "EDH" not in parts and "DHE" not in parts:
2854
            if "ADH" not in parts and "EDH" not in parts and "DHE" not in parts:
2739
                self.fail("Non-DH cipher: " + cipher[0])
2855
                self.fail("Non-DH cipher: " + cipher[0])
2740
2856
2857
        def test_selected_alpn_protocol(self):
2858
            # selected_alpn_protocol() is None unless ALPN is used.
2859
            context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
2860
            context.load_cert_chain(CERTFILE)
2861
            stats = server_params_test(context, context,
2862
                                       chatty=True, connectionchatty=True)
2863
            self.assertIs(stats['client_alpn_protocol'], None)
2864
2865
        @unittest.skipUnless(ssl.HAS_ALPN, "ALPN support required")
2866
        def test_selected_alpn_protocol_if_server_uses_alpn(self):
2867
            # selected_alpn_protocol() is None unless ALPN is used by the client.
2868
            client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
2869
            client_context.load_verify_locations(CERTFILE)
2870
            server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
2871
            server_context.load_cert_chain(CERTFILE)
2872
            server_context.set_alpn_protocols(['foo', 'bar'])
2873
            stats = server_params_test(client_context, server_context,
2874
                                       chatty=True, connectionchatty=True)
2875
            self.assertIs(stats['client_alpn_protocol'], None)
2876
2877
        @unittest.skipUnless(ssl.HAS_ALPN, "ALPN support needed for this test")
2878
        def test_alpn_protocols(self):
2879
            server_protocols = ['foo', 'bar', 'milkshake']
2880
            protocol_tests = [
2881
                (['foo', 'bar'], 'foo'),
2882
                (['bar', 'foo'], 'foo'),
2883
                (['milkshake'], 'milkshake'),
2884
                (['http/3.0', 'http/4.0'], None)
2885
            ]
2886
            for client_protocols, expected in protocol_tests:
2887
                server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
2888
                server_context.load_cert_chain(CERTFILE)
2889
                server_context.set_alpn_protocols(server_protocols)
2890
                client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
2891
                client_context.load_cert_chain(CERTFILE)
2892
                client_context.set_alpn_protocols(client_protocols)
2893
2894
                try:
2895
                    stats = server_params_test(client_context,
2896
                                               server_context,
2897
                                               chatty=True,
2898
                                               connectionchatty=True)
2899
                except ssl.SSLError as e:
2900
                    stats = e
2901
2902
                if expected is None and IS_OPENSSL_1_1:
2903
                    # OpenSSL 1.1.0 raises handshake error
2904
                    self.assertIsInstance(stats, ssl.SSLError)
2905
                else:
2906
                    msg = "failed trying %s (s) and %s (c).\n" \
2907
                        "was expecting %s, but got %%s from the %%s" \
2908
                            % (str(server_protocols), str(client_protocols),
2909
                                str(expected))
2910
                    client_result = stats['client_alpn_protocol']
2911
                    self.assertEqual(client_result, expected,
2912
                                     msg % (client_result, "client"))
2913
                    server_result = stats['server_alpn_protocols'][-1] \
2914
                        if len(stats['server_alpn_protocols']) else 'nothing'
2915
                    self.assertEqual(server_result, expected,
2916
                                     msg % (server_result, "server"))
2917
2741
        def test_selected_npn_protocol(self):
2918
        def test_selected_npn_protocol(self):
2742
            # selected_npn_protocol() is None unless NPN is used
2919
            # selected_npn_protocol() is None unless NPN is used
2743
            context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
2920
            context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
Lines 2878-2883 else: Link Here
2878
            self.assertEqual(cm.exception.reason, 'TLSV1_ALERT_INTERNAL_ERROR')
3055
            self.assertEqual(cm.exception.reason, 'TLSV1_ALERT_INTERNAL_ERROR')
2879
            self.assertIn("TypeError", stderr.getvalue())
3056
            self.assertIn("TypeError", stderr.getvalue())
2880
3057
3058
        def test_shared_ciphers(self):
3059
            server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3060
            server_context.load_cert_chain(SIGNED_CERTFILE)
3061
            client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
3062
            client_context.verify_mode = ssl.CERT_REQUIRED
3063
            client_context.load_verify_locations(SIGNING_CA)
3064
            if ssl.OPENSSL_VERSION_INFO >= (1, 0, 2):
3065
                client_context.set_ciphers("AES128:AES256")
3066
                server_context.set_ciphers("AES256")
3067
                alg1 = "AES256"
3068
                alg2 = "AES-256"
3069
            else:
3070
                client_context.set_ciphers("AES:3DES")
3071
                server_context.set_ciphers("3DES")
3072
                alg1 = "3DES"
3073
                alg2 = "DES-CBC3"
3074
3075
            stats = server_params_test(client_context, server_context)
3076
            ciphers = stats['server_shared_ciphers'][0]
3077
            self.assertGreater(len(ciphers), 0)
3078
            for name, tls_version, bits in ciphers:
3079
                if not alg1 in name.split("-") and alg2 not in name:
3080
                    self.fail(name)
3081
2881
        def test_read_write_after_close_raises_valuerror(self):
3082
        def test_read_write_after_close_raises_valuerror(self):
2882
            context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
3083
            context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
2883
            context.verify_mode = ssl.CERT_REQUIRED
3084
            context.verify_mode = ssl.CERT_REQUIRED
(-)a/Modules/_hashopenssl.c (-62 / +104 lines)
Lines 20-26 Link Here
20
20
21
/* EVP is the preferred interface to hashing in OpenSSL */
21
/* EVP is the preferred interface to hashing in OpenSSL */
22
#include <openssl/evp.h>
22
#include <openssl/evp.h>
23
#include <openssl/hmac.h>
24
/* We use the object interface to discover what hashes OpenSSL supports. */
23
/* We use the object interface to discover what hashes OpenSSL supports. */
25
#include <openssl/objects.h>
24
#include <openssl/objects.h>
26
#include "openssl/err.h"
25
#include "openssl/err.h"
Lines 31-45 Link Here
31
#define HASH_OBJ_CONSTRUCTOR 0
30
#define HASH_OBJ_CONSTRUCTOR 0
32
#endif
31
#endif
33
32
34
/* Minimum OpenSSL version needed to support sha224 and higher. */
33
#if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER)
35
#if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x00908000)
34
/* OpenSSL < 1.1.0 */
36
#define _OPENSSL_SUPPORTS_SHA2
35
#define EVP_MD_CTX_new EVP_MD_CTX_create
36
#define EVP_MD_CTX_free EVP_MD_CTX_destroy
37
#define HAS_FAST_PKCS5_PBKDF2_HMAC 0
38
#include <openssl/hmac.h>
39
#else
40
/* OpenSSL >= 1.1.0 */
41
#define HAS_FAST_PKCS5_PBKDF2_HMAC 1
37
#endif
42
#endif
38
43
39
typedef struct {
44
typedef struct {
40
    PyObject_HEAD
45
    PyObject_HEAD
41
    PyObject            *name;  /* name of this hash algorithm */
46
    PyObject            *name;  /* name of this hash algorithm */
42
    EVP_MD_CTX           ctx;   /* OpenSSL message digest context */
47
    EVP_MD_CTX          *ctx;   /* OpenSSL message digest context */
43
#ifdef WITH_THREAD
48
#ifdef WITH_THREAD
44
    PyThread_type_lock   lock;  /* OpenSSL context lock */
49
    PyThread_type_lock   lock;  /* OpenSSL context lock */
45
#endif
50
#endif
Lines 51-57 static PyTypeObject EVPtype; Link Here
51
56
52
#define DEFINE_CONSTS_FOR_NEW(Name)  \
57
#define DEFINE_CONSTS_FOR_NEW(Name)  \
53
    static PyObject *CONST_ ## Name ## _name_obj = NULL; \
58
    static PyObject *CONST_ ## Name ## _name_obj = NULL; \
54
    static EVP_MD_CTX CONST_new_ ## Name ## _ctx; \
55
    static EVP_MD_CTX *CONST_new_ ## Name ## _ctx_p = NULL;
59
    static EVP_MD_CTX *CONST_new_ ## Name ## _ctx_p = NULL;
56
60
57
DEFINE_CONSTS_FOR_NEW(md5)
61
DEFINE_CONSTS_FOR_NEW(md5)
Lines 64-82 DEFINE_CONSTS_FOR_NEW(sha512) Link Here
64
#endif
68
#endif
65
69
66
70
71
/* LCOV_EXCL_START */
72
static PyObject *
73
_setException(PyObject *exc)
74
{
75
    unsigned long errcode;
76
    const char *lib, *func, *reason;
77
78
    errcode = ERR_peek_last_error();
79
    if (!errcode) {
80
        PyErr_SetString(exc, "unknown reasons");
81
        return NULL;
82
    }
83
    ERR_clear_error();
84
85
    lib = ERR_lib_error_string(errcode);
86
    func = ERR_func_error_string(errcode);
87
    reason = ERR_reason_error_string(errcode);
88
89
    if (lib && func) {
90
        PyErr_Format(exc, "[%s: %s] %s", lib, func, reason);
91
    }
92
    else if (lib) {
93
        PyErr_Format(exc, "[%s] %s", lib, reason);
94
    }
95
    else {
96
        PyErr_SetString(exc, reason);
97
    }
98
    return NULL;
99
}
100
/* LCOV_EXCL_STOP */
101
67
static EVPobject *
102
static EVPobject *
68
newEVPobject(PyObject *name)
103
newEVPobject(PyObject *name)
69
{
104
{
70
    EVPobject *retval = (EVPobject *)PyObject_New(EVPobject, &EVPtype);
105
    EVPobject *retval = (EVPobject *)PyObject_New(EVPobject, &EVPtype);
106
    if (retval == NULL) {
107
        return NULL;
108
    }
109
110
    retval->ctx = EVP_MD_CTX_new();
111
    if (retval->ctx == NULL) {
112
        PyErr_NoMemory();
113
        return NULL;
114
    }
71
115
72
    /* save the name for .name to return */
116
    /* save the name for .name to return */
73
    if (retval != NULL) {
117
    Py_INCREF(name);
74
        Py_INCREF(name);
118
    retval->name = name;
75
        retval->name = name;
76
#ifdef WITH_THREAD
119
#ifdef WITH_THREAD
77
        retval->lock = NULL;
120
    retval->lock = NULL;
78
#endif
121
#endif
79
    }
80
122
81
    return retval;
123
    return retval;
82
}
124
}
Lines 91-97 EVP_hash(EVPobject *self, const void *vp, Py_ssize_t len) Link Here
91
            process = MUNCH_SIZE;
133
            process = MUNCH_SIZE;
92
        else
134
        else
93
            process = Py_SAFE_DOWNCAST(len, Py_ssize_t, unsigned int);
135
            process = Py_SAFE_DOWNCAST(len, Py_ssize_t, unsigned int);
94
        EVP_DigestUpdate(&self->ctx, (const void*)cp, process);
136
        EVP_DigestUpdate(self->ctx, (const void*)cp, process);
95
        len -= process;
137
        len -= process;
96
        cp += process;
138
        cp += process;
97
    }
139
    }
Lines 106-121 EVP_dealloc(EVPobject *self) Link Here
106
    if (self->lock != NULL)
148
    if (self->lock != NULL)
107
        PyThread_free_lock(self->lock);
149
        PyThread_free_lock(self->lock);
108
#endif
150
#endif
109
    EVP_MD_CTX_cleanup(&self->ctx);
151
    EVP_MD_CTX_free(self->ctx);
110
    Py_XDECREF(self->name);
152
    Py_XDECREF(self->name);
111
    PyObject_Del(self);
153
    PyObject_Del(self);
112
}
154
}
113
155
114
static void locked_EVP_MD_CTX_copy(EVP_MD_CTX *new_ctx_p, EVPobject *self)
156
static int
157
locked_EVP_MD_CTX_copy(EVP_MD_CTX *new_ctx_p, EVPobject *self)
115
{
158
{
159
    int result;
116
    ENTER_HASHLIB(self);
160
    ENTER_HASHLIB(self);
117
    EVP_MD_CTX_copy(new_ctx_p, &self->ctx);
161
    result = EVP_MD_CTX_copy(new_ctx_p, self->ctx);
118
    LEAVE_HASHLIB(self);
162
    LEAVE_HASHLIB(self);
163
    return result;
119
}
164
}
120
165
121
/* External methods for a hash object */
166
/* External methods for a hash object */
Lines 131-137 EVP_copy(EVPobject *self, PyObject *unused) Link Here
131
    if ( (newobj = newEVPobject(self->name))==NULL)
176
    if ( (newobj = newEVPobject(self->name))==NULL)
132
        return NULL;
177
        return NULL;
133
178
134
    locked_EVP_MD_CTX_copy(&newobj->ctx, self);
179
    if (!locked_EVP_MD_CTX_copy(newobj->ctx, self)) {
180
        return _setException(PyExc_ValueError);
181
    }
135
    return (PyObject *)newobj;
182
    return (PyObject *)newobj;
136
}
183
}
137
184
Lines 142-157 static PyObject * Link Here
142
EVP_digest(EVPobject *self, PyObject *unused)
189
EVP_digest(EVPobject *self, PyObject *unused)
143
{
190
{
144
    unsigned char digest[EVP_MAX_MD_SIZE];
191
    unsigned char digest[EVP_MAX_MD_SIZE];
145
    EVP_MD_CTX temp_ctx;
192
    EVP_MD_CTX *temp_ctx;
146
    PyObject *retval;
193
    PyObject *retval;
147
    unsigned int digest_size;
194
    unsigned int digest_size;
148
195
149
    locked_EVP_MD_CTX_copy(&temp_ctx, self);
196
    temp_ctx = EVP_MD_CTX_new();
150
    digest_size = EVP_MD_CTX_size(&temp_ctx);
197
    if (temp_ctx == NULL) {
151
    EVP_DigestFinal(&temp_ctx, digest, NULL);
198
        PyErr_NoMemory();
199
        return NULL;
200
    }
201
202
    if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
203
        return _setException(PyExc_ValueError);
204
    }
205
    digest_size = EVP_MD_CTX_size(temp_ctx);
206
    EVP_DigestFinal(temp_ctx, digest, NULL);
152
207
153
    retval = PyBytes_FromStringAndSize((const char *)digest, digest_size);
208
    retval = PyBytes_FromStringAndSize((const char *)digest, digest_size);
154
    EVP_MD_CTX_cleanup(&temp_ctx);
209
    EVP_MD_CTX_free(temp_ctx);
155
    return retval;
210
    return retval;
156
}
211
}
157
212
Lines 162-178 static PyObject * Link Here
162
EVP_hexdigest(EVPobject *self, PyObject *unused)
217
EVP_hexdigest(EVPobject *self, PyObject *unused)
163
{
218
{
164
    unsigned char digest[EVP_MAX_MD_SIZE];
219
    unsigned char digest[EVP_MAX_MD_SIZE];
165
    EVP_MD_CTX temp_ctx;
220
    EVP_MD_CTX *temp_ctx;
166
    PyObject *retval;
221
    PyObject *retval;
167
    char *hex_digest;
222
    char *hex_digest;
168
    unsigned int i, j, digest_size;
223
    unsigned int i, j, digest_size;
169
224
225
    temp_ctx = EVP_MD_CTX_new();
226
    if (temp_ctx == NULL) {
227
        PyErr_NoMemory();
228
        return NULL;
229
    }
230
170
    /* Get the raw (binary) digest value */
231
    /* Get the raw (binary) digest value */
171
    locked_EVP_MD_CTX_copy(&temp_ctx, self);
232
    if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
172
    digest_size = EVP_MD_CTX_size(&temp_ctx);
233
        return _setException(PyExc_ValueError);
173
    EVP_DigestFinal(&temp_ctx, digest, NULL);
234
    }
235
    digest_size = EVP_MD_CTX_size(temp_ctx);
236
    EVP_DigestFinal(temp_ctx, digest, NULL);
174
237
175
    EVP_MD_CTX_cleanup(&temp_ctx);
238
    EVP_MD_CTX_free(temp_ctx);
176
239
177
    /* Allocate a new buffer */
240
    /* Allocate a new buffer */
178
    hex_digest = PyMem_Malloc(digest_size * 2 + 1);
241
    hex_digest = PyMem_Malloc(digest_size * 2 + 1);
Lines 241-247 static PyObject * Link Here
241
EVP_get_block_size(EVPobject *self, void *closure)
304
EVP_get_block_size(EVPobject *self, void *closure)
242
{
305
{
243
    long block_size;
306
    long block_size;
244
    block_size = EVP_MD_CTX_block_size(&self->ctx);
307
    block_size = EVP_MD_CTX_block_size(self->ctx);
245
    return PyLong_FromLong(block_size);
308
    return PyLong_FromLong(block_size);
246
}
309
}
247
310
Lines 249-255 static PyObject * Link Here
249
EVP_get_digest_size(EVPobject *self, void *closure)
312
EVP_get_digest_size(EVPobject *self, void *closure)
250
{
313
{
251
    long size;
314
    long size;
252
    size = EVP_MD_CTX_size(&self->ctx);
315
    size = EVP_MD_CTX_size(self->ctx);
253
    return PyLong_FromLong(size);
316
    return PyLong_FromLong(size);
254
}
317
}
255
318
Lines 310-316 EVP_tp_init(EVPobject *self, PyObject *args, PyObject *kwds) Link Here
310
            PyBuffer_Release(&view);
373
            PyBuffer_Release(&view);
311
        return -1;
374
        return -1;
312
    }
375
    }
313
    EVP_DigestInit(&self->ctx, digest);
376
    EVP_DigestInit(self->ctx, digest);
314
377
315
    self->name = name_obj;
378
    self->name = name_obj;
316
    Py_INCREF(self->name);
379
    Py_INCREF(self->name);
Lines 407-415 EVPnew(PyObject *name_obj, Link Here
407
        return NULL;
470
        return NULL;
408
471
409
    if (initial_ctx) {
472
    if (initial_ctx) {
410
        EVP_MD_CTX_copy(&self->ctx, initial_ctx);
473
        EVP_MD_CTX_copy(self->ctx, initial_ctx);
411
    } else {
474
    } else {
412
        EVP_DigestInit(&self->ctx, digest);
475
        EVP_DigestInit(self->ctx, digest);
413
    }
476
    }
414
477
415
    if (cp && len) {
478
    if (cp && len) {
Lines 475-480 EVP_new(PyObject *self, PyObject *args, PyObject *kwdict) Link Here
475
538
476
#define PY_PBKDF2_HMAC 1
539
#define PY_PBKDF2_HMAC 1
477
540
541
#if !HAS_FAST_PKCS5_PBKDF2_HMAC
478
/* Improved implementation of PKCS5_PBKDF2_HMAC()
542
/* Improved implementation of PKCS5_PBKDF2_HMAC()
479
 *
543
 *
480
 * PKCS5_PBKDF2_HMAC_fast() hashes the password exactly one time instead of
544
 * PKCS5_PBKDF2_HMAC_fast() hashes the password exactly one time instead of
Lines 556-592 PKCS5_PBKDF2_HMAC_fast(const char *pass, int passlen, Link Here
556
    HMAC_CTX_cleanup(&hctx_tpl);
620
    HMAC_CTX_cleanup(&hctx_tpl);
557
    return 1;
621
    return 1;
558
}
622
}
623
#endif
559
624
560
/* LCOV_EXCL_START */
561
static PyObject *
562
_setException(PyObject *exc)
563
{
564
    unsigned long errcode;
565
    const char *lib, *func, *reason;
566
567
    errcode = ERR_peek_last_error();
568
    if (!errcode) {
569
        PyErr_SetString(exc, "unknown reasons");
570
        return NULL;
571
    }
572
    ERR_clear_error();
573
574
    lib = ERR_lib_error_string(errcode);
575
    func = ERR_func_error_string(errcode);
576
    reason = ERR_reason_error_string(errcode);
577
578
    if (lib && func) {
579
        PyErr_Format(exc, "[%s: %s] %s", lib, func, reason);
580
    }
581
    else if (lib) {
582
        PyErr_Format(exc, "[%s] %s", lib, reason);
583
    }
584
    else {
585
        PyErr_SetString(exc, reason);
586
    }
587
    return NULL;
588
}
589
/* LCOV_EXCL_STOP */
590
625
591
PyDoc_STRVAR(pbkdf2_hmac__doc__,
626
PyDoc_STRVAR(pbkdf2_hmac__doc__,
592
"pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None) -> key\n\
627
"pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None) -> key\n\
Lines 668-677 pbkdf2_hmac(PyObject *self, PyObject *args, PyObject *kwdict) Link Here
668
    key = PyBytes_AS_STRING(key_obj);
703
    key = PyBytes_AS_STRING(key_obj);
669
704
670
    Py_BEGIN_ALLOW_THREADS
705
    Py_BEGIN_ALLOW_THREADS
706
#if HAS_FAST_PKCS5_PBKDF2_HMAC
707
    retval = PKCS5_PBKDF2_HMAC((char*)password.buf, (int)password.len,
708
                               (unsigned char *)salt.buf, (int)salt.len,
709
                               iterations, digest, dklen,
710
                               (unsigned char *)key);
711
#else
671
    retval = PKCS5_PBKDF2_HMAC_fast((char*)password.buf, (int)password.len,
712
    retval = PKCS5_PBKDF2_HMAC_fast((char*)password.buf, (int)password.len,
672
                                    (unsigned char *)salt.buf, (int)salt.len,
713
                                    (unsigned char *)salt.buf, (int)salt.len,
673
                                    iterations, digest, dklen,
714
                                    iterations, digest, dklen,
674
                                    (unsigned char *)key);
715
                                    (unsigned char *)key);
716
#endif
675
    Py_END_ALLOW_THREADS
717
    Py_END_ALLOW_THREADS
676
718
677
    if (!retval) {
719
    if (!retval) {
Lines 790-796 generate_hash_name_list(void) Link Here
790
    if (CONST_ ## NAME ## _name_obj == NULL) { \
832
    if (CONST_ ## NAME ## _name_obj == NULL) { \
791
        CONST_ ## NAME ## _name_obj = PyUnicode_FromString(#NAME); \
833
        CONST_ ## NAME ## _name_obj = PyUnicode_FromString(#NAME); \
792
        if (EVP_get_digestbyname(#NAME)) { \
834
        if (EVP_get_digestbyname(#NAME)) { \
793
            CONST_new_ ## NAME ## _ctx_p = &CONST_new_ ## NAME ## _ctx; \
835
            CONST_new_ ## NAME ## _ctx_p = EVP_MD_CTX_new(); \
794
            EVP_DigestInit(CONST_new_ ## NAME ## _ctx_p, EVP_get_digestbyname(#NAME)); \
836
            EVP_DigestInit(CONST_new_ ## NAME ## _ctx_p, EVP_get_digestbyname(#NAME)); \
795
        } \
837
        } \
796
    } \
838
    } \
(-)a/Modules/_ssl.c (-42 / +207 lines)
Lines 55-60 static PySocketModule_APIObject PySocketModule; Link Here
55
#include <sys/poll.h>
55
#include <sys/poll.h>
56
#endif
56
#endif
57
57
58
/* Don't warn about deprecated functions */
59
#ifdef __GNUC__
60
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
61
#endif
62
#ifdef __clang__
63
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
64
#endif
65
58
/* Include OpenSSL header files */
66
/* Include OpenSSL header files */
59
#include "openssl/rsa.h"
67
#include "openssl/rsa.h"
60
#include "openssl/crypto.h"
68
#include "openssl/crypto.h"
Lines 90-95 struct py_ssl_library_code { Link Here
90
/* Include generated data (error codes) */
98
/* Include generated data (error codes) */
91
#include "_ssl_data.h"
99
#include "_ssl_data.h"
92
100
101
#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
102
#  define OPENSSL_VERSION_1_1 1
103
#endif
104
93
/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
105
/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
94
    http://www.openssl.org/news/changelog.html
106
    http://www.openssl.org/news/changelog.html
95
 */
107
 */
Lines 108-113 struct py_ssl_library_code { Link Here
108
# define HAVE_SNI 0
120
# define HAVE_SNI 0
109
#endif
121
#endif
110
122
123
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
124
# define HAVE_ALPN
125
#endif
126
127
#ifndef INVALID_SOCKET /* MS defines this */
128
#define INVALID_SOCKET (-1)
129
#endif
130
131
#ifdef OPENSSL_VERSION_1_1
132
/* OpenSSL 1.1.0+ */
133
#ifndef OPENSSL_NO_SSL2
134
#define OPENSSL_NO_SSL2
135
#endif
136
#else /* OpenSSL < 1.1.0 */
137
#if defined(WITH_THREAD)
138
#define HAVE_OPENSSL_CRYPTO_LOCK
139
#endif
140
141
#define TLS_method SSLv23_method
142
143
static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
144
{
145
    return ne->set;
146
}
147
148
#ifndef OPENSSL_NO_COMP
149
static int COMP_get_type(const COMP_METHOD *meth)
150
{
151
    return meth->type;
152
}
153
154
static const char *COMP_get_name(const COMP_METHOD *meth)
155
{
156
    return meth->name;
157
}
158
#endif
159
160
static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
161
{
162
    return ctx->default_passwd_callback;
163
}
164
165
static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
166
{
167
    return ctx->default_passwd_callback_userdata;
168
}
169
170
static int X509_OBJECT_get_type(X509_OBJECT *x)
171
{
172
    return x->type;
173
}
174
175
static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
176
{
177
    return x->data.x509;
178
}
179
180
static int BIO_up_ref(BIO *b)
181
{
182
    CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
183
    return 1;
184
}
185
186
static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
187
    return store->objs;
188
}
189
190
static X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *store)
191
{
192
    return store->param;
193
}
194
#endif /* OpenSSL < 1.1.0 or LibreSSL */
195
196
111
enum py_ssl_error {
197
enum py_ssl_error {
112
    /* these mirror ssl.h */
198
    /* these mirror ssl.h */
113
    PY_SSL_ERROR_NONE,
199
    PY_SSL_ERROR_NONE,
Lines 138-144 enum py_ssl_cert_requirements { Link Here
138
enum py_ssl_version {
224
enum py_ssl_version {
139
    PY_SSL_VERSION_SSL2,
225
    PY_SSL_VERSION_SSL2,
140
    PY_SSL_VERSION_SSL3=1,
226
    PY_SSL_VERSION_SSL3=1,
141
    PY_SSL_VERSION_SSL23,
227
    PY_SSL_VERSION_TLS,
142
#if HAVE_TLSv1_2
228
#if HAVE_TLSv1_2
143
    PY_SSL_VERSION_TLS1,
229
    PY_SSL_VERSION_TLS1,
144
    PY_SSL_VERSION_TLS1_1,
230
    PY_SSL_VERSION_TLS1_1,
Lines 504-510 newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock, Link Here
504
    PySSL_BEGIN_ALLOW_THREADS
590
    PySSL_BEGIN_ALLOW_THREADS
505
    self->ssl = SSL_new(ctx);
591
    self->ssl = SSL_new(ctx);
506
    PySSL_END_ALLOW_THREADS
592
    PySSL_END_ALLOW_THREADS
507
    SSL_set_app_data(self->ssl,self);
593
    SSL_set_app_data(self->ssl, self);
508
    SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
594
    SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
509
    mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
595
    mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
510
#ifdef SSL_MODE_AUTO_RETRY
596
#ifdef SSL_MODE_AUTO_RETRY
Lines 691-697 _create_tuple_for_X509_NAME (X509_NAME *xname) Link Here
691
777
692
        /* check to see if we've gotten to a new RDN */
778
        /* check to see if we've gotten to a new RDN */
693
        if (rdn_level >= 0) {
779
        if (rdn_level >= 0) {
694
            if (rdn_level != entry->set) {
780
            if (rdn_level != X509_NAME_ENTRY_set(entry)) {
695
                /* yes, new RDN */
781
                /* yes, new RDN */
696
                /* add old RDN to DN */
782
                /* add old RDN to DN */
697
                rdnt = PyList_AsTuple(rdn);
783
                rdnt = PyList_AsTuple(rdn);
Lines 708-714 _create_tuple_for_X509_NAME (X509_NAME *xname) Link Here
708
                    goto fail0;
794
                    goto fail0;
709
            }
795
            }
710
        }
796
        }
711
        rdn_level = entry->set;
797
        rdn_level = X509_NAME_ENTRY_set(entry);
712
798
713
        /* now add this attribute to the current RDN */
799
        /* now add this attribute to the current RDN */
714
        name = X509_NAME_ENTRY_get_object(entry);
800
        name = X509_NAME_ENTRY_get_object(entry);
Lines 811-828 _get_peer_alt_names (X509 *certificate) { Link Here
811
            goto fail;
897
            goto fail;
812
        }
898
        }
813
899
814
        p = ext->value->data;
900
        p = X509_EXTENSION_get_data(ext)->data;
815
        if (method->it)
901
        if (method->it)
816
            names = (GENERAL_NAMES*)
902
            names = (GENERAL_NAMES*)
817
              (ASN1_item_d2i(NULL,
903
              (ASN1_item_d2i(NULL,
818
                             &p,
904
                             &p,
819
                             ext->value->length,
905
                             X509_EXTENSION_get_data(ext)->length,
820
                             ASN1_ITEM_ptr(method->it)));
906
                             ASN1_ITEM_ptr(method->it)));
821
        else
907
        else
822
            names = (GENERAL_NAMES*)
908
            names = (GENERAL_NAMES*)
823
              (method->d2i(NULL,
909
              (method->d2i(NULL,
824
                           &p,
910
                           &p,
825
                           ext->value->length));
911
                           X509_EXTENSION_get_data(ext)->length));
826
912
827
        for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
913
        for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
828
            /* get a rendering of each name in the set of names */
914
            /* get a rendering of each name in the set of names */
Lines 1033-1045 _get_crl_dp(X509 *certificate) { Link Here
1033
    int i, j;
1119
    int i, j;
1034
    PyObject *lst, *res = NULL;
1120
    PyObject *lst, *res = NULL;
1035
1121
1036
#if OPENSSL_VERSION_NUMBER < 0x10001000L
1122
#if OPENSSL_VERSION_NUMBER >= 0x10001000L
1037
    dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
1038
#else
1039
    /* Calls x509v3_cache_extensions and sets up crldp */
1123
    /* Calls x509v3_cache_extensions and sets up crldp */
1040
    X509_check_ca(certificate);
1124
    X509_check_ca(certificate);
1041
    dps = certificate->crldp;
1042
#endif
1125
#endif
1126
    dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
1043
1127
1044
    if (dps == NULL)
1128
    if (dps == NULL)
1045
        return Py_None;
1129
        return Py_None;
Lines 1403-1408 static PyObject *PySSL_cipher (PySSLSocket *self) { Link Here
1403
    return NULL;
1487
    return NULL;
1404
}
1488
}
1405
1489
1490
/*[clinic input]
1491
_ssl._SSLSocket.shared_ciphers
1492
[clinic start generated code]*/
1493
1494
static PyObject *
1495
_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1496
/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
1497
{
1498
    STACK_OF(SSL_CIPHER) *ciphers;
1499
    int i;
1500
    PyObject *res;
1501
1502
    ciphers = SSL_get_ciphers(self->ssl);
1503
    if (!ciphers)
1504
        Py_RETURN_NONE;
1505
    res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1506
    if (!res)
1507
        return NULL;
1508
    for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1509
        PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1510
        if (!tup) {
1511
            Py_DECREF(res);
1512
            return NULL;
1513
        }
1514
        PyList_SET_ITEM(res, i, tup);
1515
    }
1516
    return res;
1517
}
1518
1519
/*[clinic input]
1520
_ssl._SSLSocket.cipher
1521
[clinic start generated code]*/
1522
1523
static PyObject *
1524
_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1525
/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
1526
{
1527
    const SSL_CIPHER *current;
1528
1529
    if (self->ssl == NULL)
1530
        Py_RETURN_NONE;
1531
    current = SSL_get_current_cipher(self->ssl);
1532
    if (current == NULL)
1533
        Py_RETURN_NONE;
1534
    return cipher_to_tuple(current);
1535
}
1536
1537
/*[clinic input]
1538
_ssl._SSLSocket.version
1539
[clinic start generated code]*/
1540
1541
static PyObject *
1542
_ssl__SSLSocket_version_impl(PySSLSocket *self)
1543
/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
1544
{
1545
    const char *version;
1546
1547
    if (self->ssl == NULL)
1548
        Py_RETURN_NONE;
1549
    version = SSL_get_version(self->ssl);
1550
    if (!strcmp(version, "unknown"))
1551
        Py_RETURN_NONE;
1552
    return PyUnicode_FromString(version);
1553
}
1554
1406
#ifdef OPENSSL_NPN_NEGOTIATED
1555
#ifdef OPENSSL_NPN_NEGOTIATED
1407
static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1556
static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1408
    const unsigned char *out;
1557
    const unsigned char *out;
Lines 1427-1435 static PyObject *PySSL_compression(PySSLSocket *self) { Link Here
1427
    if (self->ssl == NULL)
1576
    if (self->ssl == NULL)
1428
        Py_RETURN_NONE;
1577
        Py_RETURN_NONE;
1429
    comp_method = SSL_get_current_compression(self->ssl);
1578
    comp_method = SSL_get_current_compression(self->ssl);
1430
    if (comp_method == NULL || comp_method->type == NID_undef)
1579
    if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
1431
        Py_RETURN_NONE;
1580
        Py_RETURN_NONE;
1432
    short_name = OBJ_nid2sn(comp_method->type);
1581
    short_name = COMP_get_name(comp_method);
1433
    if (short_name == NULL)
1582
    if (short_name == NULL)
1434
        Py_RETURN_NONE;
1583
        Py_RETURN_NONE;
1435
    return PyUnicode_DecodeFSDefault(short_name);
1584
    return PyUnicode_DecodeFSDefault(short_name);
Lines 1977-1983 context_new(PyTypeObject *type, PyObject *args, PyObject *kwds) Link Here
1977
{
2126
{
1978
    char *kwlist[] = {"protocol", NULL};
2127
    char *kwlist[] = {"protocol", NULL};
1979
    PySSLContext *self;
2128
    PySSLContext *self;
1980
    int proto_version = PY_SSL_VERSION_SSL23;
2129
    int proto_version = PY_SSL_VERSION_TLS;
1981
    long options;
2130
    long options;
1982
    SSL_CTX *ctx = NULL;
2131
    SSL_CTX *ctx = NULL;
1983
2132
Lines 2003-2010 context_new(PyTypeObject *type, PyObject *args, PyObject *kwds) Link Here
2003
    else if (proto_version == PY_SSL_VERSION_SSL2)
2152
    else if (proto_version == PY_SSL_VERSION_SSL2)
2004
        ctx = SSL_CTX_new(SSLv2_method());
2153
        ctx = SSL_CTX_new(SSLv2_method());
2005
#endif
2154
#endif
2006
    else if (proto_version == PY_SSL_VERSION_SSL23)
2155
    else if (proto_version == PY_SSL_VERSION_TLS)
2007
        ctx = SSL_CTX_new(SSLv23_method());
2156
        ctx = SSL_CTX_new(TLS_method());
2008
    else
2157
    else
2009
        proto_version = -1;
2158
        proto_version = -1;
2010
    PySSL_END_ALLOW_THREADS
2159
    PySSL_END_ALLOW_THREADS
Lines 2047-2054 context_new(PyTypeObject *type, PyObject *args, PyObject *kwds) Link Here
2047
#ifndef OPENSSL_NO_ECDH
2196
#ifndef OPENSSL_NO_ECDH
2048
    /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2197
    /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2049
       prime256v1 by default.  This is Apache mod_ssl's initialization
2198
       prime256v1 by default.  This is Apache mod_ssl's initialization
2050
       policy, so we should be safe. */
2199
       policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2051
#if defined(SSL_CTX_set_ecdh_auto)
2200
     */
2201
#if defined(SSL_CTX_set_ecdh_auto) && !defined(OPENSSL_VERSION_1_1)
2052
    SSL_CTX_set_ecdh_auto(self->ctx, 1);
2202
    SSL_CTX_set_ecdh_auto(self->ctx, 1);
2053
#else
2203
#else
2054
    {
2204
    {
Lines 2259-2268 static PyObject * Link Here
2259
get_verify_flags(PySSLContext *self, void *c)
2409
get_verify_flags(PySSLContext *self, void *c)
2260
{
2410
{
2261
    X509_STORE *store;
2411
    X509_STORE *store;
2412
    X509_VERIFY_PARAM *param;
2262
    unsigned long flags;
2413
    unsigned long flags;
2263
2414
2264
    store = SSL_CTX_get_cert_store(self->ctx);
2415
    store = SSL_CTX_get_cert_store(self->ctx);
2265
    flags = X509_VERIFY_PARAM_get_flags(store->param);
2416
    param = X509_STORE_get0_param(store);
2417
    flags = X509_VERIFY_PARAM_get_flags(param);
2266
    return PyLong_FromUnsignedLong(flags);
2418
    return PyLong_FromUnsignedLong(flags);
2267
}
2419
}
2268
2420
Lines 2270-2291 static int Link Here
2270
set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2422
set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2271
{
2423
{
2272
    X509_STORE *store;
2424
    X509_STORE *store;
2425
    X509_VERIFY_PARAM *param;
2273
    unsigned long new_flags, flags, set, clear;
2426
    unsigned long new_flags, flags, set, clear;
2274
2427
2275
    if (!PyArg_Parse(arg, "k", &new_flags))
2428
    if (!PyArg_Parse(arg, "k", &new_flags))
2276
        return -1;
2429
        return -1;
2277
    store = SSL_CTX_get_cert_store(self->ctx);
2430
    store = SSL_CTX_get_cert_store(self->ctx);
2278
    flags = X509_VERIFY_PARAM_get_flags(store->param);
2431
    param = X509_STORE_get0_param(store);
2432
    flags = X509_VERIFY_PARAM_get_flags(param);
2279
    clear = flags & ~new_flags;
2433
    clear = flags & ~new_flags;
2280
    set = ~flags & new_flags;
2434
    set = ~flags & new_flags;
2281
    if (clear) {
2435
    if (clear) {
2282
        if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2436
        if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
2283
            _setSSLError(NULL, 0, __FILE__, __LINE__);
2437
            _setSSLError(NULL, 0, __FILE__, __LINE__);
2284
            return -1;
2438
            return -1;
2285
        }
2439
        }
2286
    }
2440
    }
2287
    if (set) {
2441
    if (set) {
2288
        if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2442
        if (!X509_VERIFY_PARAM_set_flags(param, set)) {
2289
            _setSSLError(NULL, 0, __FILE__, __LINE__);
2443
            _setSSLError(NULL, 0, __FILE__, __LINE__);
2290
            return -1;
2444
            return -1;
2291
        }
2445
        }
Lines 2455-2462 load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds) Link Here
2455
    char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2609
    char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2456
    PyObject *certfile, *keyfile = NULL, *password = NULL;
2610
    PyObject *certfile, *keyfile = NULL, *password = NULL;
2457
    PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
2611
    PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
2458
    pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2612
    pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
2459
    void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2613
    void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
2460
    _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
2614
    _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
2461
    int r;
2615
    int r;
2462
2616
Lines 2587-2594 _add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len, Link Here
2587
            cert = d2i_X509_bio(biobuf, NULL);
2741
            cert = d2i_X509_bio(biobuf, NULL);
2588
        } else {
2742
        } else {
2589
            cert = PEM_read_bio_X509(biobuf, NULL,
2743
            cert = PEM_read_bio_X509(biobuf, NULL,
2590
                                     self->ctx->default_passwd_callback,
2744
                                     SSL_CTX_get_default_passwd_cb(self->ctx),
2591
                                     self->ctx->default_passwd_callback_userdata);
2745
                                     SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
2746
                                    );
2592
        }
2747
        }
2593
        if (cert == NULL) {
2748
        if (cert == NULL) {
2594
            break;
2749
            break;
Lines 3036-3060 static PyObject * Link Here
3036
cert_store_stats(PySSLContext *self)
3191
cert_store_stats(PySSLContext *self)
3037
{
3192
{
3038
    X509_STORE *store;
3193
    X509_STORE *store;
3194
    STACK_OF(X509_OBJECT) *objs;
3039
    X509_OBJECT *obj;
3195
    X509_OBJECT *obj;
3040
    int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3196
    int x509 = 0, crl = 0, ca = 0, i;
3041
3197
3042
    store = SSL_CTX_get_cert_store(self->ctx);
3198
    store = SSL_CTX_get_cert_store(self->ctx);
3043
    for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3199
    objs = X509_STORE_get0_objects(store);
3044
        obj = sk_X509_OBJECT_value(store->objs, i);
3200
    for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3045
        switch (obj->type) {
3201
        obj = sk_X509_OBJECT_value(objs, i);
3202
        switch (X509_OBJECT_get_type(obj)) {
3046
            case X509_LU_X509:
3203
            case X509_LU_X509:
3047
                x509++;
3204
                x509++;
3048
                if (X509_check_ca(obj->data.x509)) {
3205
                if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
3049
                    ca++;
3206
                    ca++;
3050
                }
3207
                }
3051
                break;
3208
                break;
3052
            case X509_LU_CRL:
3209
            case X509_LU_CRL:
3053
                crl++;
3210
                crl++;
3054
                break;
3211
                break;
3055
            case X509_LU_PKEY:
3056
                pkey++;
3057
                break;
3058
            default:
3212
            default:
3059
                /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3213
                /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3060
                 * As far as I can tell they are internal states and never
3214
                 * As far as I can tell they are internal states and never
Lines 3079-3084 get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds) Link Here
3079
{
3233
{
3080
    char *kwlist[] = {"binary_form", NULL};
3234
    char *kwlist[] = {"binary_form", NULL};
3081
    X509_STORE *store;
3235
    X509_STORE *store;
3236
    STACK_OF(X509_OBJECT) *objs;
3082
    PyObject *ci = NULL, *rlist = NULL;
3237
    PyObject *ci = NULL, *rlist = NULL;
3083
    int i;
3238
    int i;
3084
    int binary_mode = 0;
3239
    int binary_mode = 0;
Lines 3093-3109 get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds) Link Here
3093
    }
3248
    }
3094
3249
3095
    store = SSL_CTX_get_cert_store(self->ctx);
3250
    store = SSL_CTX_get_cert_store(self->ctx);
3096
    for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3251
    objs = X509_STORE_get0_objects(store);
3252
    for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3097
        X509_OBJECT *obj;
3253
        X509_OBJECT *obj;
3098
        X509 *cert;
3254
        X509 *cert;
3099
3255
3100
        obj = sk_X509_OBJECT_value(store->objs, i);
3256
        obj = sk_X509_OBJECT_value(objs, i);
3101
        if (obj->type != X509_LU_X509) {
3257
        if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
3102
            /* not a x509 cert */
3258
            /* not a x509 cert */
3103
            continue;
3259
            continue;
3104
        }
3260
        }
3105
        /* CA for any purpose */
3261
        /* CA for any purpose */
3106
        cert = obj->data.x509;
3262
        cert = X509_OBJECT_get0_X509(obj);
3107
        if (!X509_check_ca(cert)) {
3263
        if (!X509_check_ca(cert)) {
3108
            continue;
3264
            continue;
3109
        }
3265
        }
Lines 3776-3785 static PyMethodDef PySSL_methods[] = { Link Here
3776
};
3932
};
3777
3933
3778
3934
3779
#ifdef WITH_THREAD
3935
#ifdef HAVE_OPENSSL_CRYPTO_LOCK
3780
3936
3781
/* an implementation of OpenSSL threading operations in terms
3937
/* an implementation of OpenSSL threading operations in terms
3782
   of the Python C thread library */
3938
 * of the Python C thread library
3939
 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
3940
 */
3783
3941
3784
static PyThread_type_lock *_ssl_locks = NULL;
3942
static PyThread_type_lock *_ssl_locks = NULL;
3785
3943
Lines 3860-3866 static int _setup_ssl_threads(void) { Link Here
3860
    return 1;
4018
    return 1;
3861
}
4019
}
3862
4020
3863
#endif  /* def HAVE_THREAD */
4021
#endif  /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
3864
4022
3865
PyDoc_STRVAR(module_doc,
4023
PyDoc_STRVAR(module_doc,
3866
"Implementation module for SSL socket operations.  See the socket module\n\
4024
"Implementation module for SSL socket operations.  See the socket module\n\
Lines 3927-3937 PyInit__ssl(void) Link Here
3927
    SSL_load_error_strings();
4085
    SSL_load_error_strings();
3928
    SSL_library_init();
4086
    SSL_library_init();
3929
#ifdef WITH_THREAD
4087
#ifdef WITH_THREAD
4088
#ifdef HAVE_OPENSSL_CRYPTO_LOCK
3930
    /* note that this will start threading if not already started */
4089
    /* note that this will start threading if not already started */
3931
    if (!_setup_ssl_threads()) {
4090
    if (!_setup_ssl_threads()) {
3932
        return NULL;
4091
        return NULL;
3933
    }
4092
    }
4093
#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
4094
    /* OpenSSL 1.1.0 builtin thread support is enabled */
4095
    _ssl_locks_count++;
3934
#endif
4096
#endif
4097
#endif  /* WITH_THREAD */
3935
    OpenSSL_add_all_algorithms();
4098
    OpenSSL_add_all_algorithms();
3936
4099
3937
    /* Add symbols to module dict */
4100
    /* Add symbols to module dict */
Lines 4075-4081 PyInit__ssl(void) Link Here
4075
                            PY_SSL_VERSION_SSL3);
4238
                            PY_SSL_VERSION_SSL3);
4076
#endif
4239
#endif
4077
    PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4240
    PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4078
                            PY_SSL_VERSION_SSL23);
4241
                            PY_SSL_VERSION_TLS);
4242
    PyModule_AddIntConstant(m, "PROTOCOL_TLS",
4243
                            PY_SSL_VERSION_TLS);
4079
    PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4244
    PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4080
                            PY_SSL_VERSION_TLS1);
4245
                            PY_SSL_VERSION_TLS1);
4081
#if HAVE_TLSv1_2
4246
#if HAVE_TLSv1_2

Return to bug 673960