Teks sumber — English
Terjemahan — Bahasa Indonesia
This module provides access to Transport Layer Security (often known as "Secure Sockets Layer") encryption and peer authentication facilities for network sockets, both client-side and server-side. This module uses the OpenSSL library.
Some behavior may be platform dependent, since calls are made to the operating system socket APIs. The installed version of OpenSSL may also cause variations in behavior. For example, TLSv1.3 comes with OpenSSL version 1.1.1.
Updated to support linking with OpenSSL 1.1.0
OpenSSL 0.9.8, 1.0.0 and 1.0.1 are deprecated and no longer supported. In the future the ssl module will require at least OpenSSL 1.0.2 or 1.1.0.
:pep:`644` has been implemented. The ssl module requires OpenSSL 1.1.1 or newer.
The default settings for this context include :data:`VERIFY_X509_PARTIAL_CHAIN` and :data:`VERIFY_X509_STRICT`. These make the underlying OpenSSL implementation behave more like a conforming implementation of :rfc:`5280`, in exchange for a small amount of incompatibility with older X.509 certificates.
This context enables :data:`VERIFY_X509_STRICT` by default, which may reject pre-:rfc:`5280` or malformed certificates that the underlying OpenSSL implementation otherwise would accept. While disabling this is not recommended, you can do so using::
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:`OSError`. The error code and message of :exc:`SSLError` instances are provided by the OpenSSL 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.
A string mnemonic designating the reason this error occurred, for example ``CERTIFICATE_VERIFY_FAILED``. The range of possible values depends on the OpenSSL version.
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:`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
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.
Possible value for :attr:`SSLContext.verify_flags`. It instructs OpenSSL to prefer trusted certificates when building the trust chain to validate a certificate. This flag is enabled by default.
Possible value for :attr:`SSLContext.verify_flags`. It instructs OpenSSL to accept intermediate CAs in the trust store to be treated as trust-anchors, in the same way as the self-signed root CA certificates. This makes it possible to trust certificates issued by an intermediate CA without having to trust its ancestor root CA.
This protocol is not available if OpenSSL is compiled with the ``no-ssl3`` option.
OpenSSL has deprecated all version specific protocols. Use the default protocol :data:`PROTOCOL_TLS_SERVER` or :data:`PROTOCOL_TLS_CLIENT` with :attr:`SSLContext.minimum_version` and :attr:`SSLContext.maximum_version` instead.
OpenSSL has deprecated all version specific protocols.
Selects TLS version 1.1 as the channel encryption protocol. Available only with openssl version 1.0.1+.
Selects TLS version 1.2 as the channel encryption protocol. Available only with openssl version 1.0.1+.
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.
The option is deprecated since OpenSSL 1.1.0, use the new :attr:`SSLContext.minimum_version` and :attr:`SSLContext.maximum_version` instead.
Prevents a TLSv1.1 connection. This option is only applicable in conjunction with :const:`PROTOCOL_TLS`. It prevents the peers from choosing TLSv1.1 as the protocol version. Available only with openssl version 1.0.1+.
The option is deprecated since OpenSSL 1.1.0.
Prevents a TLSv1.2 connection. This option is only applicable in conjunction with :const:`PROTOCOL_TLS`. It prevents the peers from choosing TLSv1.2 as the protocol version. Available only with openssl version 1.0.1+.
Prevents a TLSv1.3 connection. This option is only applicable in conjunction with :const:`PROTOCOL_TLS`. It prevents the peers from choosing TLSv1.3 as the protocol version. TLS 1.3 is available with OpenSSL 1.1.1 or later. When Python has been compiled against an older version of OpenSSL, the flag defaults to *0*.
The option is deprecated since OpenSSL 1.1.0. It was added to 2.7.15 and 3.6.3 for backwards compatibility with OpenSSL 1.0.2.
This option is only available with OpenSSL 1.1.0h and later.
This option is only available with OpenSSL 1.1.1 and later.
This option is only available with OpenSSL 3.0.0 and later.
Enable the use of the kernel TLS. To benefit from the feature, OpenSSL must have been compiled with support for it, and the negotiated cipher suites and extensions must be supported by it (a list of supported ones may vary by platform and kernel version).
Note that with enabled kernel TLS some cryptographic operations are performed by the kernel directly and not via any available OpenSSL Providers. This might be undesirable if, for example, the application requires all cryptographic operations to be performed by the FIPS provider.
Allow legacy insecure renegotiation between OpenSSL and unpatched servers only.
Whether the OpenSSL library has built-in support for the *Application-Layer Protocol Negotiation* TLS extension as described in :rfc:`7301`.
Whether the OpenSSL library has built-in support not checking subject common name and :attr:`SSLContext.hostname_checks_common_name` is writeable.
Whether the OpenSSL library has built-in support for the Elliptic Curve-based Diffie-Hellman key exchange. This should be true unless the feature was explicitly disabled by the distributor.
Whether the OpenSSL library has built-in support for the *Server Name Indication* extension (as defined in :rfc:`6066`).
Whether the OpenSSL library has built-in support for the *Next Protocol Negotiation* as described in the `Application Layer Protocol Negotiation <https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation>`_. When true, you can use the :meth:`SSLContext.set_npn_protocols` method to advertise which protocols you want to support.
Whether the OpenSSL library has built-in support for the SSL 2.0 protocol.
Whether the OpenSSL library has built-in support for the SSL 3.0 protocol.
Whether the OpenSSL library has built-in support for the TLS 1.0 protocol.
Whether the OpenSSL library has built-in support for the TLS 1.1 protocol.
Whether the OpenSSL library has built-in support for the TLS 1.2 protocol.
Whether the OpenSSL library has built-in support for the TLS 1.3 protocol.
Whether the OpenSSL library has built-in support for TLS-PSK.
Whether the OpenSSL library has built-in support for External PSKs in TLS 1.3 as described in :rfc:`9258`.
Whether the OpenSSL library has built-in support for TLS-PHA.
The version string of the OpenSSL library loaded by the interpreter::
>>> ssl.OPENSSL_VERSION
'OpenSSL 1.0.2k 26 Jan 2017'
A tuple of five integers representing version information about the OpenSSL library::
>>> ssl.OPENSSL_VERSION_INFO
(1, 0, 2, 11, 15)
The raw version number of the OpenSSL library, as a single integer::
>>> ssl.OPENSSL_VERSION_NUMBER
268443839
>>> hex(ssl.OPENSSL_VERSION_NUMBER)
'0x100020bf'
Hostname or IP address is matched by OpenSSL during handshake. The function :func:`!match_hostname` is no longer used. In case OpenSSL refuses a hostname or IP address, the handshake is aborted early and a TLS alert message is sent to the peer.
Only available with OpenSSL 1.1.1 and TLS 1.3 enabled. Without TLS 1.3 support, the method raises :exc:`NotImplementedError`.
Return the actual SSL protocol version negotiated by the connection as a string, or ``None`` if no secure connection is established. As of this writing, possible return values include ``"SSLv2"``, ``"SSLv3"``, ``"TLSv1"``, ``"TLSv1.1"`` and ``"TLSv1.2"``. Recent OpenSSL versions may define more return values.
TLS 1.3 protocol will be available with :data:`PROTOCOL_TLS` in OpenSSL >= 1.1.1. There is no dedicated PROTOCOL constant for just TLS 1.3.
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.
The *capath* string, if present, is the path to a directory containing several CA certificates in PEM format, following an `OpenSSL specific layout <https://docs.openssl.org/master/man3/SSL_CTX_load_verify_locations/>`_.
By default, this method returns only the preferred IANA names for the available groups. However, if the ``include_aliases`` parameter is set to :const:`True` this method will also return any associated aliases such as the ECDH curve names supported in older versions of OpenSSL.
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.
Set the allowed ciphers for sockets created with this context when connecting using TLS 1.2 and earlier. The *ciphers* argument should be a string in the `OpenSSL cipher list format <https://docs.openssl.org/master/man1/openssl-ciphers/#cipher-list-format>`_. To set allowed TLS 1.3 ciphers, use :meth:`SSLContext.set_ciphersuites`.
Set the groups allowed for key agreement for sockets created with this context. It should be a string in the `OpenSSL group list format <https://docs.openssl.org/master/man3/SSL_CTX_set1_groups_list/>`_.
Set the signature algorithms allowed for certificate-based client authentication. It should be a string in the `OpenSSL client sigalgs list format <https://docs.openssl.org/master/man3/SSL_CTX_set1_client_sigalgs_list/>`_.
Set the signature algorithms allowed for the server to complete the TLS handshake. It should be a string in the `OpenSSL sigalgs list format <https://docs.openssl.org/master/man3/SSL_CTX_set1_sigalgs_list/>`_.
This method will raise :exc:`NotImplementedError` if the OpenSSL library had OPENSSL_NO_TLSEXT defined when it was built.
Always allow a server_hostname to be passed, even if OpenSSL does not have SNI.
Get statistics about the SSL sessions created or managed by this context. A dictionary is returned which maps the names of each `piece of information <https://docs.openssl.org/1.1.1/man3/SSL_CTX_sess_number/>`_ to their numeric values. For example, here is the total number of hits and misses in the session cache since the context was created::
The flag had no effect with OpenSSL before version 1.1.1l. Python 3.8.9, 3.9.3, and 3.10 include workarounds for previous versions.
An integer representing the `security level <https://docs.openssl.org/master/man3/SSL_CTX_get_security_level/>`_ for the context. This attribute is read-only.
The flags for certificate verification operations. You can set flags like :data:`VERIFY_CRL_CHECK_LEAF` by ORing them together. By default OpenSSL does neither require nor verify certificate revocation lists (CRLs).
the PSK can only be accepted with a cipher suite that uses SHA-256. When a certificate is loaded, OpenSSL's default TLS 1.3 cipher suite order selects a SHA-384 suite instead, so the PSK is declined even if it matches.
In the Python use of certificates, a client or server can use a certificate to prove who they are. The other side of a network connection can also be required to produce a certificate, and that certificate can be validated to the satisfaction of the client or server that requires such validation. The connection attempt can be set to raise an exception if the validation fails. Validation is done automatically, by the underlying OpenSSL framework; the application need not concern itself with its mechanics. But the application does usually need to provide sets of certificates to allow this process to take place.
If you are going to create a server that provides SSL-encrypted connection services, you will need to acquire a certificate for that service. There are many ways of acquiring appropriate certificates, such as buying one from a certification authority. Another common practice is to generate a self-signed certificate. The simplest way to do this is with the OpenSSL package, using something like the following::
% openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
Generating a 1024 bit RSA private key
.......++++++
.............................++++++
writing new private key to 'cert.pem'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:MyState
Locality Name (eg, city) []:Some City
Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
Organizational Unit Name (eg, section) []:My Group
Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
Email Address []:ops@myserver.mygroup.myorganization.com
%
Combining SSL protocol handling and network IO usually works well, but there are some cases where it doesn't. An example is async IO frameworks that want to use a different IO multiplexing model than the "select/poll on a file descriptor" (readiness based) model that is assumed by :class:`socket.socket` and by the internal OpenSSL socket IO routines. This is mostly relevant for platforms like Windows where this model is not efficient. For this purpose, a reduced scope variant of :class:`SSLSocket` called :class:`SSLObject` is provided.
This class implements an interface on top of a low-level SSL object as implemented by OpenSSL. This object captures the state of an SSL connection but does not provide any network IO itself. IO needs to be performed through separate "BIO" objects which are OpenSSL's IO abstraction layer.
An SSLObject communicates with the outside world using memory buffers. The class :class:`MemoryBIO` provides a memory buffer that can be used for this purpose. It wraps an OpenSSL memory BIO (Basic IO) object:
Hostname matchings is now performed by OpenSSL. Python no longer uses :func:`!match_hostname`.
If you have advanced security requirements, fine-tuning of the ciphers enabled when negotiating a SSL session is possible through the :meth:`SSLContext.set_ciphers` method. Starting from Python 3.2.3, the ssl module disables certain weak ciphers by default, but you may want to further restrict the cipher choice. Be sure to read OpenSSL's documentation about the `cipher list format <https://docs.openssl.org/1.1.1/man1/ciphers/#cipher-list-format>`_. If you want to check which ciphers are enabled by a given cipher list, use :meth:`SSLContext.get_ciphers` or the ``openssl ciphers`` command on your system.
If using this module as part of a multi-processed application (using, for example the :mod:`multiprocessing` or :mod:`concurrent.futures` modules), be aware that OpenSSL's internal random number generator does not properly handle forked processes. Applications must change the PRNG state of the parent process if they use any SSL feature with :func:`os.fork`. Any successful call of :func:`~ssl.RAND_add` or :func:`~ssl.RAND_bytes` is sufficient.
OpenSSL
OpenSSL