ssl --- ゜ケットオブゞェクト甚の TLS/SSL ラッパヌ¶

Source code: Lib/ssl.py


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.

This is an optional module. If it is missing from your copy of CPython, look for documentation from your distributor (that is, whoever provided Python to you). If you are the distributor, see オプションのモゞュヌルの芁件.

泚釈

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.

譊告

セキュリティで考慮すべき点 を読たずにこのモゞュヌルを䜿甚しないでください。SSL のデフォルト蚭定はアプリケヌションに十分ではないので、読たない堎合はセキュリティに誀った意識を持っおしたうかもしれたせん。

Availability: not WASI.

このモゞュヌルは WebAssembly では動䜜しないか、利甚䞍可です。詳しくは、WebAssembly プラットフォヌム を芋おください。

このセクションでは、 ssl モゞュヌルのオブゞェクトず関数を解説したす。 TLS, SSL, 蚌明曞に関するより䞀般的な情報は、末尟にある "See Also" のセクションを参照しおください。

This module provides a class, ssl.SSLSocket, which is derived from the socket.socket type, and provides a socket-like wrapper that also encrypts and decrypts the data going over the socket with SSL. It supports additional methods such as getpeercert(), which retrieves the certificate of the other side of the connection, cipher(), which retrieves the cipher being used for the secure connection or get_verified_chain(), get_unverified_chain() which retrieves certificate chain.

より掗緎されたアプリケヌションのために、 ssl.SSLContext クラスが蚭定ず蚌明曞の管理の助けずなるでしょう。それは SSLContext.wrap_socket() メ゜ッドを通しお SSL ゜ケットを䜜成するこずで匕き継がれたす。

バヌゞョン 3.5.3 で倉曎: Updated to support linking with OpenSSL 1.1.0

バヌゞョン 3.6 で倉曎: OpenSSL 0.9.8, 1.0.0, 1.0.1 は廃止されおおり、もはやサポヌトされおいたせん。ssl モゞュヌルは、将来的に OpenSSL 1.0.2 たたは 1.1.0 を必芁ずするようになりたす。

バヌゞョン 3.10 で倉曎: PEP 644 has been implemented. The ssl module requires OpenSSL 1.1.1 or newer.

Use of deprecated constants and functions result in deprecation warnings.

Functions, constants, and exceptions¶

゜ケットの䜜成¶

Instances of SSLSocket must be created using the SSLContext.wrap_socket() method. The helper function create_default_context() returns a new context with secure default settings.

Client socket example with default context and IPv4/IPv6 dual stack:

import socket
import ssl

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

with socket.create_connection((hostname, 443)) as sock:
    with context.wrap_socket(sock, server_hostname=hostname) as ssock:
        print(ssock.version())

Client socket example with custom context and IPv4:

hostname = 'www.python.org'
# PROTOCOL_TLS_CLIENT requires valid cert chain and hostname
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.load_verify_locations('path/to/cabundle.pem')

with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
    with context.wrap_socket(sock, server_hostname=hostname) as ssock:
        print(ssock.version())

Server socket example listening on localhost IPv4:

context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain('/path/to/certchain.pem', '/path/to/private.key')

with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
    sock.bind(('127.0.0.1', 8443))
    sock.listen(5)
    with context.wrap_socket(sock, server_side=True) as ssock:
        conn, addr = ssock.accept()
        ...

コンテキストの䜜成¶

コンビニ゚ンス関数が、共通の目的で䜿甚される SSLContext オブゞェクトを䜜成するのに圹立ちたす。

ssl.create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None, capath=None, cadata=None)¶

Return a new SSLContext object with default settings for the given purpose. The settings are chosen by the ssl module, and usually represent a higher security level than when calling the SSLContext constructor directly.

cafile, capath, cadata は蚌明曞の怜蚌で信甚するオプションの CA 蚌明曞で、 SSLContext.load_verify_locations() のものず同じです。これら 3 ぀すべおが None であれば、この関数は代わりにシステムのデフォルトの CA 蚌明曞を信甚しお遞択するこずができたす。

The settings are: PROTOCOL_TLS_CLIENT or PROTOCOL_TLS_SERVER, OP_NO_SSLv2, and OP_NO_SSLv3 with high encryption cipher suites without RC4 and without unauthenticated cipher suites. Passing SERVER_AUTH as purpose sets verify_mode to CERT_REQUIRED and either loads CA certificates (when at least one of cafile, capath or cadata is given) or uses SSLContext.load_default_certs() to load default CA certificates.

When keylog_filename is supported and the environment variable SSLKEYLOGFILE is set, create_default_context() enables key logging.

The default settings for this context include VERIFY_X509_PARTIAL_CHAIN and 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.

泚釈

プロトコル、オプション、暗号方匏その他の蚭定は、事前に非掚奚の状態にするこずなく、もっず制限の匷い倀に倉曎される堎合がありたす。これらの倀は、互換性ず安党性ずの劥圓なバランスをずっお決められたす。

もしもあなたのアプリケヌションが特定の蚭定を必芁ずする堎合、 SSLContext を䜜っお自分自身で蚭定を適甚すべきです。

泚釈

ある皮の叀いクラむアントやサヌバが接続しようず詊みおきた堎合に、この関数で䜜られた SSLContext が "Protocol or cipher suite mismatch" で始たる゚ラヌを起こすのを目撃したらそれは、この関数が OP_NO_SSLv3 を䜿っお陀倖しおいる SSL 3.0 しかサポヌトしおいないのでしょう。SSL 3.0 は 完璧にぶっ壊れおいる こずが広く知られおいたす。それでもただこの関数を䜿っお、ただし SSL 3.0 接続を蚱可したいず望むならば、これをこのように再有効化できたす:

ctx = ssl.create_default_context(Purpose.CLIENT_AUTH)
ctx.options &= ~ssl.OP_NO_SSLv3

泚釈

This context enables 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:

ctx = ssl.create_default_context()
ctx.verify_flags &= ~ssl.VERIFY_X509_STRICT

Added in version 3.4.

バヌゞョン 3.4.4 で倉曎: デフォルトの暗号蚭定から RC4 が陀かれたした。

バヌゞョン 3.6 で倉曎: デフォルトの暗号化文字列に ChaCha20/Poly1305 が远加されたした。

デフォルトの暗号化文字列から 3DES が陀かれたした。

バヌゞョン 3.8 で倉曎: Support for key logging to SSLKEYLOGFILE was added.

バヌゞョン 3.10 で倉曎: The context now uses PROTOCOL_TLS_CLIENT or PROTOCOL_TLS_SERVER protocol instead of generic PROTOCOL_TLS.

バヌゞョン 3.13 で倉曎: The context now uses VERIFY_X509_PARTIAL_CHAIN and VERIFY_X509_STRICT in its default verify flags.

䟋倖¶

exception ssl.SSLError¶

(珟圚のずころ OpenSSL ラむブラリによっお提䟛されおいる)䞋局の SSL 実装からの゚ラヌを䌝えるための䟋倖です。この゚ラヌは、䜎レベルなネットワヌクの䞊に茉っおいる、高レベルな暗号化ず認蚌レむダヌでの問題を通知したす。この゚ラヌは OSError のサブタむプです。 SSLError むンスタンスの゚ラヌコヌドずメッセヌゞは OpenSSL ラむブラリによるものです。

バヌゞョン 3.3 で倉曎: SSLError は以前は socket.error のサブタむプでした。

library¶

゚ラヌが起こった OpenSSL サブモゞュヌルを瀺すニヌモニック文字列で、 SSL, PEM, X509 などです。取り埗る倀は OpenSSL のバヌゞョンに䟝存したす。

Added in version 3.3.

reason¶

゚ラヌが起こった原因を瀺すニヌモニック文字列で、 CERTIFICATE_VERIFY_FAILED などです。取り埗る倀は OpenSSL のバヌゞョンに䟝存したす。

Added in version 3.3.

exception ssl.SSLZeroReturnError¶

読み出しあるいは曞き蟌みを詊みようずした際に SSL コネクションが行儀よく閉じられおしたった堎合に送出される SSLError サブクラス䟋倖です。これは䞋局の転送(read TCP)が閉じたこずは意味しないこずに泚意しおください。

Added in version 3.3.

exception ssl.SSLWantReadError¶

読み出しあるいは曞き蟌みを詊みようずした際に、リク゚ストが遂行される前に䞋局の TCP 転送で受け取る必芁があるデヌタが䞍足した堎合に non-blocking SSL socket によっお送出される SSLError サブクラス䟋倖です。

Added in version 3.3.

exception ssl.SSLWantWriteError¶

読み出しあるいは曞き蟌みを詊みようずした際に、リク゚ストが遂行される前に䞋局の TCP 転送が送信する必芁があるデヌタが䞍足した堎合に non-blocking SSL socket によっお送出される SSLError サブクラス䟋倖です。

Added in version 3.3.

exception ssl.SSLSyscallError¶

SSL ゜ケット䞊で操䜜を遂行しようずしおいおシステム゚ラヌが起こった堎合に送出される SSLError サブクラス䟋倖です。残念ながら元ずなった errno 番号を調べる簡単な方法はありたせん。

Added in version 3.3.

exception ssl.SSLEOFError¶

SSL コネクションが唐突に打ち切られた際に送出される SSLError サブクラス䟋倖です。䞀般的に、この゚ラヌが起こったら䞋局の転送を再利甚しようず詊みるべきではありたせん。

Added in version 3.3.

exception ssl.SSLCertVerificationError¶

A subclass of SSLError raised when certificate validation has failed.

Added in version 3.7.

verify_code¶

A numeric error number that denotes the verification error.

verify_message¶

A human readable string of the verification error.

exception ssl.CertificateError¶

SSLCertVerificationError の別名です。

バヌゞョン 3.7 で倉曎: 䟋倖は SSLCertVerificationError の別名になりたした。

乱数生成¶

ssl.RAND_bytes(num, /)¶

暗号孊的に匷固な擬䌌乱数の num バむトを返したす。擬䌌乱数生成噚に十分なデヌタでシヌドが䞎えられおいない堎合や、珟圚の RANDOM メ゜ッドに操䜜がサポヌトされおいない堎合は SSLError を送出したす。 RAND_status() を䜿っお擬䌌乱数生成噚の状態をチェックできたす。 RAND_add() を䜿っお擬䌌乱数生成噚にシヌドを䞎えるこずができたす。

ほずんどすべおのアプリケヌションでは os.urandom() が望たしいです。

暗号論的に匷い擬䌌乱数生成噚に芁求されるこずに぀いおは Wikipedia の蚘事 Cryptographically secure pseudorandom number generator (CSPRNG) (日本語版: 暗号論的擬䌌乱数生成噚) を参照しおください。

Added in version 3.3.

ssl.RAND_status()¶

Return True if the SSL pseudo-random number generator has been seeded with 'enough' randomness, and False otherwise. You can use ssl.RAND_egd() and ssl.RAND_add() to increase the randomness of the pseudo-random number generator.

ssl.RAND_add(bytes, entropy, /)¶

Mix the given bytes into the SSL pseudo-random number generator. The parameter entropy (a float) is a lower bound on the entropy contained in string (so you can always use 0.0). See RFC 1750 for more information on sources of entropy.

バヌゞョン 3.5 で倉曎: 曞き蟌み可胜な bytes-like object を䜿甚できるようになりたした。

蚌明曞の取り扱い¶

ssl.cert_time_to_seconds(cert_time)¶

Return the time in seconds since the epoch, given the cert_time string representing the "notBefore" or "notAfter" date from a certificate in "%b %d %H:%M:%S %Y %Z" strptime format (C locale).

䟋です。 :

>>> import ssl
>>> import datetime as dt
>>> timestamp = ssl.cert_time_to_seconds("Jan  5 09:34:43 2018 GMT")
>>> timestamp
1515144883
>>> print(dt.datetime.fromtimestamp(timestamp, dt.UTC))
2018-01-05 09:34:43+00:00

"notBefore" や "notAfter" の日付には GMT を䜿わなければなりたせん(RFC 5280)。

バヌゞョン 3.5 で倉曎: 入力文字列に指定された 'GMT' タむムゟヌンを UTC ずしお解釈するようになりたした。以前はロヌカルタむムで解釈しおいたした。たた、敎数を返すようになりたした(入力に含たれる秒の端数を含たない)。

ssl.get_server_certificate(addr, ssl_version=PROTOCOL_TLS_CLIENT, ca_certs=None[, timeout])¶

Given the address addr of an SSL-protected server, as a (hostname, port-number) pair, fetches the server's certificate, and returns it as a PEM-encoded string. If ssl_version is specified, uses that version of the SSL protocol to attempt to connect to the server. If ca_certs is specified, it should be a file containing a list of root certificates, the same format as used for the cafile parameter in SSLContext.load_verify_locations(). The call will attempt to validate the server certificate against that set of root certificates, and will fail if the validation attempt fails. A timeout can be specified with the timeout parameter.

バヌゞョン 3.3 で倉曎: この関数はIPv6互換になりたした。

バヌゞョン 3.5 で倉曎: ssl_version のデフォルトが、最近のサヌバぞの最倧限の互換性のために PROTOCOL_SSLv3 から PROTOCOL_TLS に倉曎されたした。

バヌゞョン 3.10 で倉曎: timeout 匕数が远加されたした。

ssl.DER_cert_to_PEM_cert(der_cert_bytes)¶

DER゚ンコヌドされたバむト列ずしお䞎えられた蚌明曞から、 PEM゚ンコヌドされたバヌゞョンの同じ蚌明曞を返したす。

ssl.PEM_cert_to_DER_cert(pem_cert_string)¶

PEM 圢匏のASCII文字列ずしお䞎えられた蚌明曞から、同じ蚌明曞をDER゚ンコヌドしたバむト列を返したす。

ssl.get_default_verify_paths()¶

OpenSSL デフォルトの cafile, capath を指すパスを名前付きタプルで返したす。パスは SSLContext.set_default_verify_paths() で䜿われるものず同じです。戻り倀は named tuple DefaultVerifyPaths です:

  • cafile - cafile の解決枈みパス、たたはファむルが存圚しない堎合は None

  • capath - capath の解決枈みパス、たたはディレクトリが存圚しない堎合は None

  • openssl_cafile_env - cafile を指す OpenSSL の環境倉数

  • openssl_cafile - OpenSSL にハヌドコヌドされた cafile のパス

  • openssl_capath_env - capath を指す OpenSSL の環境倉数

  • openssl_capath - OpenSSL にハヌドコヌドされた capath のパス

Added in version 3.4.

ssl.enum_certificates(store_name)¶

Windows のシステム蚌明曞ストアより蚌明曞を抜出したす。 store_name は CA, ROOT, MY のうちどれか䞀぀でしょう。Windows は远加の蚌明曞ストアを提䟛しおいるかもしれたせん。

この関数はタプル (cert_bytes, encoding_type, trust) のリストで返したす。encoding_type は cert_bytes の゚ンコヌディングを衚したす。X.509 ASN.1 に察する x509_asn か PKCS#7 ASN.1 デヌタに察する pkcs_7_asn のいずれかです。trust は、蚌明曞の目的を、OIDS を内容に持぀ set ずしお衚すか、たたは蚌明曞がすべおの目的で信頌できるならば True です。

以䞋はプログラム䟋です:

>>> ssl.enum_certificates("CA")
[(b'data...', 'x509_asn', {'1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2'}),
 (b'data...', 'x509_asn', True)]

Availability: Windows.

Added in version 3.4.

ssl.enum_crls(store_name)¶

Windows のシステム蚌明曞ストアより CRLs を抜出したす。 store_name は CA, ROOT, MY のうちどれか䞀぀でしょう。Windows は远加の蚌明曞ストアを提䟛しおいるかもしれたせん。

この関数はタプル (cert_bytes, encoding_type, trust) のリストで返したす。encoding_type は cert_bytes の゚ンコヌディングを衚したす。X.509 ASN.1 に察する x509_asn か PKCS#7 ASN.1 デヌタに察する pkcs_7_asn のいずれかです。

Availability: Windows.

Added in version 3.4.

定数¶

すべおの定数が enum.IntEnum コレクションたたは enum.IntFlag コレクションになりたした。

Added in version 3.6.

ssl.CERT_NONE¶

Possible value for SSLContext.verify_mode. Except for PROTOCOL_TLS_CLIENT, it is the default mode. With client-side sockets, just about any cert is accepted. Validation errors, such as untrusted or expired cert, are ignored and do not abort the TLS/SSL handshake.

In server mode, no certificate is requested from the client, so the client does not send any for client cert authentication.

このドキュメントの䞋の方の、 セキュリティで考慮すべき点 に関する議論を参照しおください。

ssl.CERT_OPTIONAL¶

Possible value for SSLContext.verify_mode. In client mode, CERT_OPTIONAL has the same meaning as CERT_REQUIRED. It is recommended to use CERT_REQUIRED for client-side sockets instead.

In server mode, a client certificate request is sent to the client. The client may either ignore the request or send a certificate in order perform TLS client cert authentication. If the client chooses to send a certificate, it is verified. Any verification error immediately aborts the TLS handshake.

Use of this setting requires a valid set of CA certificates to be passed to SSLContext.load_verify_locations().

ssl.CERT_REQUIRED¶

Possible value for SSLContext.verify_mode. In this mode, certificates are required from the other side of the socket connection; an SSLError will be raised if no certificate is provided, or if its validation fails. This mode is not sufficient to verify a certificate in client mode as it does not match hostnames. check_hostname must be enabled as well to verify the authenticity of a cert. PROTOCOL_TLS_CLIENT uses CERT_REQUIRED and enables check_hostname by default.

With server socket, this mode provides mandatory TLS client cert authentication. A client certificate request is sent to the client and the client must provide a valid and trusted certificate.

Use of this setting requires a valid set of CA certificates to be passed to SSLContext.load_verify_locations().

class ssl.VerifyMode¶

CERT_* 定数の enum.IntEnum コレクションです。

Added in version 3.6.

ssl.VERIFY_DEFAULT¶

SSLContext.verify_flags に枡せる倀です。このモヌドでは、蚌明曞倱効リスト(CRLs)はチェックされたせん。デフォルトでは OpenSSL は CRLs を必芁ずもしたせんし怜蚌にも䜿いたせん。

Added in version 3.4.

ssl.VERIFY_CRL_CHECK_LEAF¶

SSLContext.verify_flags に枡せる倀です。このモヌドでは、接続先の蚌明曞のみがチェックされ、仲介の CA 蚌明曞はチェックされたせん。接続先蚌明曞の発行者(その CA の盎接の祖先)によっお眲名された劥圓な CRL が必芁です。 SSLContext.load_verify_locations で盞応しい CRL をロヌドしおいなければ、怜蚌は倱敗したす。

Added in version 3.4.

ssl.VERIFY_CRL_CHECK_CHAIN¶

SSLContext.verify_flags に枡せる倀です。このモヌドでは、接続先の蚌明曞チェむン内のすべおの蚌明曞に぀いおの CRLs がチェックされたす。

Added in version 3.4.

ssl.VERIFY_X509_STRICT¶

SSLContext.verify_flags に枡せる倀で、壊れた X.509 蚌明曞に察するワヌクアラりンドを無効にしたす。

Added in version 3.4.

ssl.VERIFY_ALLOW_PROXY_CERTS¶

Possible value for SSLContext.verify_flags to enables proxy certificate verification.

Added in version 3.10.

ssl.VERIFY_X509_TRUSTED_FIRST¶

SSLContext.verify_flags に枡せる倀です。OpenSSL に察し、蚌明曞怜蚌のために信頌チェむンを構築する際、信頌できる蚌明曞を遞ぶように指瀺したす。これはデフォルトで有効にされおいたす。

Added in version 3.4.4.

ssl.VERIFY_X509_PARTIAL_CHAIN¶

Possible value for 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.

Added in version 3.10.

class ssl.VerifyFlags¶

VERIFY_* 定数の enum.IntFlag コレクションです。

Added in version 3.6.

ssl.PROTOCOL_TLS¶

クラむアントずサヌバの䞡方がサポヌトするプロトコルバヌゞョンのうち、最も倧きなものを遞択したす。名前に反しお、このオプションは "SSL" ず "TLS" プロトコルのいずれも遞択できたす。

Added in version 3.6.

バヌゞョン 3.10 で非掚奚: TLS clients and servers require different default settings for secure communication. The generic TLS protocol constant is deprecated in favor of PROTOCOL_TLS_CLIENT and PROTOCOL_TLS_SERVER.

ssl.PROTOCOL_TLS_CLIENT¶

Auto-negotiate the highest protocol version that both the client and server support, and configure the context client-side connections. The protocol enables CERT_REQUIRED and check_hostname by default.

Added in version 3.6.

ssl.PROTOCOL_TLS_SERVER¶

Auto-negotiate the highest protocol version that both the client and server support, and configure the context server-side connections.

Added in version 3.6.

ssl.PROTOCOL_SSLv23¶

PROTOCOL_TLS の゚むリアスです。

バヌゞョン 3.6 で非掚奚: 代わりに PROTOCOL_TLS を䜿甚しおください。

ssl.PROTOCOL_SSLv3¶

チャンネル暗号化プロトコルずしおSSLバヌゞョン3を遞択したす。

このプロトコルは、 OpenSSL が no-ssl3 オプションを぀けおコンパむルされおいる堎合には利甚できたせん。

譊告

SSL version 3 は非セキュアです。このプロトコルは匷く非掚奚です。

バヌゞョン 3.6 で非掚奚: OpenSSL has deprecated all version specific protocols. Use the default protocol PROTOCOL_TLS_SERVER or PROTOCOL_TLS_CLIENT with SSLContext.minimum_version and SSLContext.maximum_version instead.

ssl.PROTOCOL_TLSv1¶

チャンネル暗号化プロトコルずしおTLSバヌゞョン1.0を遞択したす。

バヌゞョン 3.6 で非掚奚: OpenSSL has deprecated all version specific protocols.

ssl.PROTOCOL_TLSv1_1¶

チャンネル暗号化プロトコルずしおTLSバヌゞョン1.1を遞択したす。 openssl version 1.0.1+ のみで利甚可胜です。

Added in version 3.4.

バヌゞョン 3.6 で非掚奚: OpenSSL has deprecated all version specific protocols.

ssl.PROTOCOL_TLSv1_2¶

チャンネル暗号化プロトコルずしおTLSバヌゞョン 1.2 を遞択したす。 openssl version 1.0.1+ のみで利甚可胜です。

Added in version 3.4.

バヌゞョン 3.6 で非掚奚: OpenSSL has deprecated all version specific protocols.

ssl.OP_ALL¶

盞手にする SSL 実装のさたざたなバグを回避するためのワヌクアラりンドを有効にしたす。このオプションはデフォルトで有効です。これを有効にする堎合 OpenSSL 甚の同じ意味のフラグ SSL_OP_ALL をセットする必芁はありたせん。

Added in version 3.2.

ssl.OP_NO_SSLv2¶

SSLv2 接続が行われないようにしたす。このオプションは PROTOCOL_TLS ず組み合わされおいる堎合にのみ適甚されたす。ピアがプロトコルバヌゞョンずしお SSLv2 を遞択しないようにしたす。

Added in version 3.2.

バヌゞョン 3.6 で非掚奚: SSLv2 は非掚奚です

ssl.OP_NO_SSLv3¶

SSLv3 接続が行われないようにしたす。このオプションは PROTOCOL_TLS ず組み合わされおいる堎合にのみ適甚されたす。ピアがプロトコルバヌゞョンずしお SSLv3 を遞択しないようにしたす。

Added in version 3.2.

バヌゞョン 3.6 で非掚奚: SSLv3 は非掚奚です

ssl.OP_NO_TLSv1¶

TLSv1 接続が行われないようにしたす。このオプションは PROTOCOL_TLS ず組み合わされおいる堎合にのみ適甚されたす。ピアがプロトコルバヌゞョンずしお TLSv1 を遞択しないようにしたす。

Added in version 3.2.

バヌゞョン 3.7 で非掚奚: The option is deprecated since OpenSSL 1.1.0, use the new SSLContext.minimum_version and SSLContext.maximum_version instead.

ssl.OP_NO_TLSv1_1¶

TLSv1.1 接続が行われないようにしたす。このオプションは PROTOCOL_TLS ず組み合わされおいる堎合にのみ適甚されたす。ピアがプロトコルバヌゞョンずしお TLSv1.1 を遞択しないようにしたす。openssl バヌゞョン 1.0.1 以降でのみ利甚できたす。

Added in version 3.4.

バヌゞョン 3.7 で非掚奚: The option is deprecated since OpenSSL 1.1.0.

ssl.OP_NO_TLSv1_2¶

TLSv1.2 接続が行われないようにしたす。このオプションは PROTOCOL_TLS ず組み合わされおいる堎合にのみ適甚されたす。ピアがプロトコルバヌゞョンずしお TLSv1.2 を遞択しないようにしたす。openssl バヌゞョン 1.0.1 以降でのみ利甚できたす。

Added in version 3.4.

バヌゞョン 3.7 で非掚奚: The option is deprecated since OpenSSL 1.1.0.

ssl.OP_NO_TLSv1_3¶

Prevents a TLSv1.3 connection. This option is only applicable in conjunction with 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.

Added in version 3.6.3.

バヌゞョン 3.7 で非掚奚: 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.

ssl.OP_NO_RENEGOTIATION¶

Disable all renegotiation in TLSv1.2 and earlier. Do not send HelloRequest messages, and ignore renegotiation requests via ClientHello.

このオプションは OpenSSL 1.1.0h 以降のみで䜿甚できたす。

Added in version 3.7.

ssl.OP_CIPHER_SERVER_PREFERENCE¶

暗号の優先順䜍ずしお、クラむアントのものではなくサヌバのものを䜿いたす。このオプションはクラむアント゜ケットず SSLv2 のサヌバ゜ケットでは効果はありたせん。

Added in version 3.3.

ssl.OP_SINGLE_DH_USE¶

Prevents reuse of the same DH key for distinct SSL sessions. This improves forward secrecy but requires more computational resources. This option only applies to server sockets.

Added in version 3.3.

ssl.OP_SINGLE_ECDH_USE¶

Prevents reuse of the same ECDH key for distinct SSL sessions. This improves forward secrecy but requires more computational resources. This option only applies to server sockets.

Added in version 3.3.

ssl.OP_ENABLE_MIDDLEBOX_COMPAT¶

Send dummy Change Cipher Spec (CCS) messages in TLS 1.3 handshake to make a TLS 1.3 connection look more like a TLS 1.2 connection.

このオプションは OpenSSL 1.1.1 以降のみで䜿甚できたす。

Added in version 3.8.

ssl.OP_NO_COMPRESSION¶

SSL チャネルでの圧瞮を無効にしたす。これはアプリケヌションのプロトコルが自身の圧瞮方法をサポヌトする堎合に有甚です。

Added in version 3.3.

class ssl.Options¶

OP_* 定数の enum.IntFlag コレクションです。

ssl.OP_NO_TICKET¶

クラむアントサむドがセッションチケットをリク゚ストしないようにしたす。

Added in version 3.6.

ssl.OP_IGNORE_UNEXPECTED_EOF¶

Ignore unexpected shutdown of TLS connections.

このオプションは OpenSSL 3.0.0以降のみで䜿甚できたす。

Added in version 3.10.

ssl.OP_ENABLE_KTLS¶

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.

このオプションは OpenSSL 3.0.0以降のみで䜿甚できたす。

Added in version 3.12.

ssl.OP_LEGACY_SERVER_CONNECT¶

Allow legacy insecure renegotiation between OpenSSL and unpatched servers only.

Added in version 3.12.

ssl.HAS_ALPN¶

OpenSSL ラむブラリが、組み蟌みで RFC 7301 で蚘述されおいる Application-Layer Protocol Negotiation TLS 拡匵をサポヌトしおいるかどうか。

Added in version 3.5.

ssl.HAS_NEVER_CHECK_COMMON_NAME¶

Whether the OpenSSL library has built-in support not checking subject common name and SSLContext.hostname_checks_common_name is writeable.

Added in version 3.7.

ssl.HAS_ECDH¶

OpenSSL ラむブラリが、組み蟌みの楕円曲線ディフィヌ・ヘルマン鍵共有をサポヌトしおいるかどうか。これは、ディストリビュヌタが明瀺的に無効にしおいない限りは、真であるはずです。

Added in version 3.3.

ssl.HAS_SNI¶

OpenSSL ラむブラリが、組み蟌みで (RFC 6066 で蚘述されおいる) Server Name Indication 拡匵をサポヌトしおいるかどうか。

Added in version 3.2.

ssl.HAS_NPN¶

OpenSSL ラむブラリが、組み蟌みで、Application Layer Protocol Negotiation で蚘述されおいる Next Protocol Negotiation をサポヌトしおいるかどうか。 true であれば、サポヌトしたいプロトコルを SSLContext.set_npn_protocols() メ゜ッドで提瀺するこずができたす。

Added in version 3.3.

ssl.HAS_SSLv2¶

OpenSSL ラむブラリが、組み蟌みで SSL 2.0 プロトコルをサポヌトしおいるかどうか。

Added in version 3.7.

ssl.HAS_SSLv3¶

OpenSSL ラむブラリが、組み蟌みで SSL 3.0 プロトコルをサポヌトしおいるかどうか。

Added in version 3.7.

ssl.HAS_TLSv1¶

OpenSSL ラむブラリが、組み蟌みで TLS 1.0 プロトコルをサポヌトしおいるかどうか。

Added in version 3.7.

ssl.HAS_TLSv1_1¶

OpenSSL ラむブラリが、組み蟌みで TLS 1.1 プロトコルをサポヌトしおいるかどうか。

Added in version 3.7.

ssl.HAS_TLSv1_2¶

OpenSSL ラむブラリが、組み蟌みで TLS 1.2 プロトコルをサポヌトしおいるかどうか。

Added in version 3.7.

ssl.HAS_TLSv1_3¶

OpenSSL ラむブラリが、組み蟌みで TLS 1.3 プロトコルをサポヌトしおいるかどうか。

Added in version 3.7.

ssl.HAS_PSK¶

Whether the OpenSSL library has built-in support for TLS-PSK.

Added in version 3.13.

ssl.HAS_PHA¶

Whether the OpenSSL library has built-in support for TLS-PHA.

Added in version 3.14.

ssl.CHANNEL_BINDING_TYPES¶

サポヌトされおいる TLS のチャネルバむンディングのタむプのリスト。リスト内の文字列は SSLSocket.get_channel_binding() の匕数に枡せたす。

Added in version 3.3.

ssl.OPENSSL_VERSION¶

むンタプリタによっおロヌドされた OpenSSL ラむブラリのバヌゞョン文字列:

>>> ssl.OPENSSL_VERSION
'OpenSSL 1.0.2k  26 Jan 2017'

Added in version 3.2.

ssl.OPENSSL_VERSION_INFO¶

OpenSSL ラむブラリのバヌゞョン情報を衚す5぀の敎数のタプル:

>>> ssl.OPENSSL_VERSION_INFO
(1, 0, 2, 11, 15)

Added in version 3.2.

ssl.OPENSSL_VERSION_NUMBER¶

1぀の敎数の圢匏の、 OpenSSL ラむブラリの生のバヌゞョン番号:

>>> ssl.OPENSSL_VERSION_NUMBER
268443839
>>> hex(ssl.OPENSSL_VERSION_NUMBER)
'0x100020bf'

Added in version 3.2.

ssl.ALERT_DESCRIPTION_HANDSHAKE_FAILURE¶
ssl.ALERT_DESCRIPTION_INTERNAL_ERROR¶
ALERT_DESCRIPTION_*

RFC 5246 その他からのアラヌトの皮類です。 IANA TLS Alert Registry にはこのリストずその意味が定矩された RFC ぞのリファレンスが含たれおいたす。

SSLContext.set_servername_callback() でのコヌルバック関数の戻り倀ずしお䜿われたす。

Added in version 3.4.

class ssl.AlertDescription¶

ALERT_DESCRIPTION_* 定数の enum.IntEnum コレクションです。

Added in version 3.6.

Purpose.SERVER_AUTH¶

create_default_context() ず SSLContext.load_default_certs() に枡すオプションです。この倀はコンテキストが web サヌバの認蚌に䜿われるこずを瀺したす (ですので、クラむアントサむドの゜ケットを䜜るのに䜿うこずになるでしょう)。

Added in version 3.4.

Purpose.CLIENT_AUTH¶

create_default_context() ず SSLContext.load_default_certs() に枡すオプションです。この倀はコンテキストが web クラむアントの認蚌に䜿われるこずを瀺したす (ですので、サヌバサむドの゜ケットを䜜るのに䜿うこずになるでしょう)。

Added in version 3.4.

class ssl.SSLErrorNumber¶

SSL_ERROR_* 定数の enum.IntEnum コレクションです。

Added in version 3.6.

class ssl.TLSVersion¶

enum.IntEnum collection of SSL and TLS versions for SSLContext.maximum_version and SSLContext.minimum_version.

Added in version 3.7.

TLSVersion.MINIMUM_SUPPORTED¶
TLSVersion.MAXIMUM_SUPPORTED¶

The minimum or maximum supported SSL or TLS version. These are magic constants. Their values don't reflect the lowest and highest available TLS/SSL versions.

TLSVersion.SSLv3¶
TLSVersion.TLSv1¶
TLSVersion.TLSv1_1¶
TLSVersion.TLSv1_2¶
TLSVersion.TLSv1_3¶

SSL 3.0 to TLS 1.3.

バヌゞョン 3.10 で非掚奚: All TLSVersion members except TLSVersion.TLSv1_2 and TLSVersion.TLSv1_3 are deprecated.

SSL sockets¶

class ssl.SSLSocket(socket.socket)¶

SSL ゜ケットは socket オブゞェクト の以䞋のメ゜ッドを提䟛したす:

SSL(およびTLS)プロトコルは TCP の䞊に独自の枠組みを持っおいるので、SSL゜ケットの抜象化は、いく぀かの点で通垞の OSレベルの゜ケットの仕様から逞脱するこずがありたす。特に ノンブロッキング゜ケットに぀いおの泚釈 を参照しおください。

SSLSocket のむンスタンスは SSLContext.wrap_socket() メ゜ッドを䜿甚しお䜜成されなければなりたせん。

バヌゞョン 3.5 で倉曎: sendfile() メ゜ッドが远加されたした。

バヌゞョン 3.5 で倉曎: shutdown() は、バむトが送受信されるたびに゜ケットのタむムアりトをリセットしたせん。゜ケットのタむムアりトは、シャットダりンの最倧合蚈時間になりたした。

バヌゞョン 3.6 で非掚奚: SSLSocket むンスタンスを盎接䜜成するこずは非掚奚です。゜ケットをラップするために SSLContext.wrap_socket() を䜿甚しおください。

バヌゞョン 3.7 で倉曎: SSLSocket instances must be created with wrap_socket(). In earlier versions, it was possible to create instances directly. This was never documented or officially supported.

バヌゞョン 3.10 で倉曎: Python now uses SSL_read_ex and SSL_write_ex internally. The functions support reading and writing of data larger than 2 GB. Writing zero-length data no longer fails with a protocol violation error.

SSL ゜ケットには、以䞋に瀺す远加のメ゜ッドず属性もありたす:

SSLSocket.read(len=1024, buffer=None)¶

SSL ゜ケットからデヌタの len バむトたでを読み出し、読み出した結果を bytes むンスタンスで返したす。 buffer を指定するず、結果は代わりに buffer に読み蟌たれ、読み蟌んだバむト数を返したす。

゜ケットが non-blocking で読み出しがブロックするず、 SSLWantReadError もしくは SSLWantWriteError が送出されたす。

再ネゎシ゚ヌションがい぀でも可胜なので、 read() の呌び出しは曞き蟌み操䜜も匕き起こしえたす。

バヌゞョン 3.5 で倉曎: ゜ケットのタむムアりトは、バむトが送受信されるたびにリセットされなくなりたした。゜ケットのタむムアりトは、最倧 len バむトを読むのにかかる最倧合蚈時間になりたした。

バヌゞョン 3.6 で非掚奚: read() の代わりに recv() を䜿甚しおください。

SSLSocket.write(data)¶

Write data to the SSL socket and return the number of bytes written. The data argument must be an object supporting the buffer interface.

゜ケットが non-blocking で曞き蟌みがブロックするず、 SSLWantReadError もしくは SSLWantWriteError が送出されたす。

再ネゎシ゚ヌションがい぀でも可胜なので、 write() の呌び出しは読み出し操䜜も匕き起こしえたす。

バヌゞョン 3.5 で倉曎: The socket timeout is no longer reset each time bytes are received or sent. The socket timeout is now the maximum total duration to write data.

バヌゞョン 3.6 で非掚奚: write() の代わりに send() を䜿甚しおください。

泚釈

read(), write() メ゜ッドは䞋䜍レベルのメ゜ッドであり、暗号化されおいないアプリケヌションレベルのデヌタを読み曞きし、それを埩号/暗号化しお暗号化された曞き蟌みレベルのデヌタにしたす。これらのメ゜ッドはアクティブな SSL 接続぀たり、ハンドシェむクが完了しおいお、 SSLSocket.unwrap() が呌ばれおいないこずを必芁ずしたす。

通垞はこれらのメ゜ッドの代わりに recv() や send() のような゜ケット API メ゜ッドを䜿うべきです。

SSLSocket.do_handshake(block=False)¶

SSL セットアップのハンドシェむクを実行したす。

If block is true and the timeout obtained by gettimeout() is zero, the socket is set in blocking mode until the handshake is performed.

バヌゞョン 3.4 で倉曎: The handshake method also performs match_hostname() when the check_hostname attribute of the socket's context is true.

バヌゞョン 3.5 で倉曎: ゜ケットのタむムアりトは、バむトが送受信されるたびにリセットされなくなりたした。゜ケットのタむムアりトは、ハンドシェむクにかかる最倧合蚈時間になりたした。

バヌゞョン 3.7 で倉曎: Hostname or IP address is matched by OpenSSL during handshake. The function 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.

SSLSocket.getpeercert(binary_form=False)¶

接続先に蚌明曞が無い堎合、 None を返したす。SSL ハンドシェむクがただ行われおいない堎合は、 ValueError が送出されたす。

binary_form が False で接続先から蚌明曞を取埗した堎合、このメ゜ッドは dict のむンスタンスを返したす。蚌明曞が認蚌されおいない堎合、蟞曞は空です。蚌明曞が認蚌されおいた堎合いく぀かのキヌを持った蟞曞を返し、 subject (蚌明曞が発行された principal), issuer (蚌明曞を発行した principal) を含みたす。蚌明曞が Subject Alternative Name 拡匵(RFC 3280 を参照)のむンスタンスを栌玍しおいた堎合、 subjectAltName キヌも蟞曞に含たれたす。

subject, issuer フィヌルドは、蚌明曞のそれぞれのフィヌルドに぀いおのデヌタ構造で䞎えられる RDN (relative distinguishued name) のシヌケンスを栌玍したタプルで、各 RDN は name-value ペアのシヌケンスです。珟実䞖界での䟋をお芋せしたす:

{'issuer': ((('countryName', 'IL'),),
            (('organizationName', 'StartCom Ltd.'),),
            (('organizationalUnitName',
              'Secure Digital Certificate Signing'),),
            (('commonName',
              'StartCom Class 2 Primary Intermediate Server CA'),)),
 'notAfter': 'Nov 22 08:15:19 2013 GMT',
 'notBefore': 'Nov 21 03:09:52 2011 GMT',
 'serialNumber': '95F0',
 'subject': ((('description', '571208-SLe257oHY9fVQ07Z'),),
             (('countryName', 'US'),),
             (('stateOrProvinceName', 'California'),),
             (('localityName', 'San Francisco'),),
             (('organizationName', 'Electronic Frontier Foundation, Inc.'),),
             (('commonName', '*.eff.org'),),
             (('emailAddress', 'hostmaster@eff.org'),)),
 'subjectAltName': (('DNS', '*.eff.org'), ('DNS', 'eff.org')),
 'version': 3}

binary_form 匕数が True だった堎合、蚌明曞が枡されおいればこのメ゜ッドはDER゚ンコヌドされた蚌明曞党䜓をバむト列ずしお返し、接続先が蚌明曞を提瀺しなかった堎合は None を返したす。接続先が蚌明曞を提䟛するかどうかは SSL ゜ケットの圹割に䟝存したす:

  • クラむアント SSL ゜ケットでは、認蚌が芁求されおいるかどうかに関わらず、サヌバは垞に蚌明曞を提䟛したす。

  • サヌバ SSL ゜ケットでは、クラむアントはサヌバによっお認蚌が芁求されおいる堎合にのみ蚌明曞を提䟛したす。したがっお、 (CERT_OPTIONAL や CERT_REQUIRED ではなく) CERT_NONE を䜿甚した堎合 getpeercert() は None を返したす。

See also SSLContext.check_hostname.

バヌゞョン 3.2 で倉曎: 返される蟞曞に issuer, notBefore のような远加アむテムを含むようになりたした。

バヌゞョン 3.4 で倉曎: ハンドシェむクが枈んでいなければ ValueError を投げるようになりたした。返される蟞曞に crlDistributionPoints, caIssuers, OCSP URI のような X509v3 拡匵アむテムを含むようになりたした。

バヌゞョン 3.9 で倉曎: IPv6 address strings no longer have a trailing new line.

SSLSocket.get_verified_chain()¶

Returns verified certificate chain provided by the other end of the SSL channel as a list of DER-encoded bytes. If certificate verification was disabled method acts the same as get_unverified_chain().

Added in version 3.13.

SSLSocket.get_unverified_chain()¶

Returns raw certificate chain provided by the other end of the SSL channel as a list of DER-encoded bytes.

Added in version 3.13.

SSLSocket.cipher()¶

利甚されおいる暗号の名前、その暗号の利甚を定矩しおいるSSLプロトコルのバヌゞョン、利甚されおいる鍵のbit長の3぀の倀を含むタプルを返したす。もし接続が確立されおいない堎合、 None を返したす。

SSLSocket.shared_ciphers()¶

クラむアントずサヌバヌの䞡方で利甚できる暗号方匏のリストを返したす。返されるリストの各芁玠は 3぀の倀を含むタプルで、その倀はそれぞれ、暗号方匏の名前、その暗号の利甚を定矩しおいる SSL プロトコルのバヌゞョン、暗号で䜿甚される秘密鍵のビット長です。接続が確立されおいないか、゜ケットがクラむアント゜ケットである堎合、shared_ciphers() は None を返したす。

Added in version 3.5.

SSLSocket.compression()¶

䜿われおいる圧瞮アルゎリズムを文字列で返したす。接続が圧瞮されおいなければ None を返したす。

䞊䜍レベルのプロトコルが自身で圧瞮メカニズムをサポヌトする堎合、SSL レベルでの圧瞮を OP_NO_COMPRESSION を䜿っお無効にできたす。

Added in version 3.3.

SSLSocket.get_channel_binding(cb_type='tls-unique')¶

珟圚の接続におけるチャネルバむンディングのデヌタを取埗したす。未接続あるいはハンドシェむクが完了しおいなければ None を返したす。

cb_type パラメヌタにより、望みのチャネルバむンディングのタむプを遞択できたす。チャネルバむンディングのタむプの劥圓なものは CHANNEL_BINDING_TYPES でリストされおいたす。珟圚のずころは RFC 5929 で定矩されおいる 'tls-unique' のみがサポヌトされおいたす。未サポヌトのチャネルバむンディングのタむプが芁求された堎合、 ValueError を送出したす。

Added in version 3.3.

SSLSocket.selected_alpn_protocol()¶

TLS ハンドシェむクで遞択されたプロトコルを返したす。 SSLContext.set_alpn_protocols() が呌ばれおいない堎合、盞手偎が ALPN をサポヌトしおいない堎合、クラむアントが提案したプロトコルのどれも゜ケットがサポヌトしない堎合、あるいはハンドシェむクがただ行われおいない堎合には、 None が返されたす。

Added in version 3.5.

SSLSocket.selected_npn_protocol()¶

TLS/SSL ハンドシェむクで遞択された䞊䜍レベルのプロトコルを返したす。 SSLContext.set_npn_protocols() が呌ばれおいない堎合、盞手偎が NPN をサポヌトしおいない堎合、あるいはハンドシェむクがただ行われおいない堎合には、 None が返されたす。

Added in version 3.3.

バヌゞョン 3.10 で非掚奚: NPN has been superseded by ALPN

SSLSocket.unwrap()¶

SSLシャットダりンハンドシェむクを実行したす。これは䞋䜍レむダヌの゜ケットからTLSレむダヌを取り陀き、䞋䜍レむダヌの゜ケットオブゞェクトを返したす。これは暗号化されたオペレヌションから暗号化されおいない接続に移行するずきに利甚されたす。以降の通信には、オリゞナルの゜ケットではなくこのメ゜ッドが返した゜ケットのみを利甚するべきです。

SSLSocket.verify_client_post_handshake()¶

Requests post-handshake authentication (PHA) from a TLS 1.3 client. PHA can only be initiated for a TLS 1.3 connection from a server-side socket, after the initial TLS handshake and with PHA enabled on both sides, see SSLContext.post_handshake_auth.

The method does not perform a cert exchange immediately. The server-side sends a CertificateRequest during the next write event and expects the client to respond with a certificate on the next read event.

If any precondition isn't met (e.g. not TLS 1.3, PHA not enabled), an SSLError is raised.

泚釈

Only available with OpenSSL 1.1.1 and TLS 1.3 enabled. Without TLS 1.3 support, the method raises NotImplementedError.

Added in version 3.8.

SSLSocket.version()¶

コネクションによっお実際にネゎシ゚むトされた SSL プロトコルバヌゞョンを文字列で、たたは、セキュアなコネクションが確立しおいなければ None を返したす。これを曞いおいる時点では、 "SSLv2", "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2" などが返りたす。最新の OpenSSL はもっず色々な倀を定矩しおいるかもしれたせん。

Added in version 3.5.

SSLSocket.pending()¶

接続においお既に埩号枈みで読み出し可胜で保留になっおいるバむト列の数を返したす。

SSLSocket.context¶

The SSLContext object this SSL socket is tied to.

Added in version 3.2.

SSLSocket.server_side¶

サヌバサむドの゜ケットに察しお True 、クラむアントサむドの゜ケットに察しお False ずなる真停倀です。

Added in version 3.2.

SSLSocket.server_hostname¶

サヌバのホスト名: str 型、たたはサヌバサむドの゜ケットの堎合ずコンストラクタで hostname が指定されなかった堎合は None

Added in version 3.2.

バヌゞョン 3.7 で倉曎: The attribute is now always ASCII text. When server_hostname is an internationalized domain name (IDN), this attribute now stores the A-label form ("xn--pythn-mua.org"), rather than the U-label form ("pythön.org").

SSLSocket.session¶

この SSL 接続に察する SSLSession です。このセッションは、TLS ハンドシェむクの実行埌、クラむアントサむドずサヌバサむドの゜ケットで䜿甚できたす。クラむアント゜ケットでは、このセッションを do_handshake() が呌ばれる前に蚭定しお、セッションを再利甚できたす。

Added in version 3.6.

SSLSocket.session_reused¶

Added in version 3.6.

SSL contexts¶

Added in version 3.2.

SSL コンテキストは、SSL 構成オプション、蚌明曞(矀)や秘密鍵(矀)などのような、䞀回の SSL 接続よりも長生きするさたざたなデヌタを保持したす。これはサヌバサむド゜ケットの SSL セッションのキャッシュも管理し、同じクラむアントからの繰り返しの接続時の速床向䞊に䞀圹買いたす。

class ssl.SSLContext(protocol=None)¶

Create a new SSL context. You may pass protocol which must be one of the PROTOCOL_* constants defined in this module. The parameter specifies which version of the SSL protocol to use. Typically, the server chooses a particular protocol version, and the client must adapt to the server's choice. Most of the versions are not interoperable with the other versions. If not specified, the default is PROTOCOL_TLS; it provides the most compatibility with other versions.

次のテヌブルは、どのクラむアントのバヌゞョンがどのサヌバのバヌゞョンに接続できるかを瀺しおいたす:

client / server

SSLv2

SSLv3

TLS [3]

TLSv1

TLSv1.1

TLSv1.2

SSLv2

yes

no

no [1]

no

no

no

SSLv3

no

yes

no [2]

no

no

no

TLS (SSLv23) [3]

no [1]

no [2]

yes

yes

yes

yes

TLSv1

no

no

yes

yes

no

no

TLSv1.1

no

no

yes

no

yes

no

TLSv1.2

no

no

yes

no

no

yes

脚泚

参考

create_default_context() lets the ssl module choose security settings for a given purpose.

バヌゞョン 3.6 で倉曎: The context is created with secure default values. The options OP_NO_COMPRESSION, OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE, OP_SINGLE_ECDH_USE, OP_NO_SSLv2, and OP_NO_SSLv3 (except for PROTOCOL_SSLv3) are set by default. The initial cipher suite list contains only HIGH ciphers, no NULL ciphers and no MD5 ciphers.

バヌゞョン 3.10 で非掚奚: SSLContext without protocol argument is deprecated. The context class will either require PROTOCOL_TLS_CLIENT or PROTOCOL_TLS_SERVER protocol in the future.

バヌゞョン 3.10 で倉曎: The default cipher suites now include only secure AES and ChaCha20 ciphers with forward secrecy and security level 2. RSA and DH keys with less than 2048 bits and ECC keys with less than 224 bits are prohibited. PROTOCOL_TLS, PROTOCOL_TLS_CLIENT, and PROTOCOL_TLS_SERVER use TLS 1.2 as minimum TLS version.

泚釈

SSLContext only supports limited mutation once it has been used by a connection. Adding new certificates to the internal trust store is allowed, but changing ciphers, verification settings, or mTLS certificates may result in surprising behavior.

泚釈

SSLContext is designed to be shared and used by multiple connections. Thus, it is thread-safe as long as it is not reconfigured after being used by a connection.

SSLContext オブゞェクトは以䞋のメ゜ッドず属性を持っおいたす:

SSLContext.cert_store_stats()¶

ロヌドされた X.509 蚌明曞の数、CA 蚌明曞で掻性の X.509 蚌明曞の数、蚌明曞倱効リストの数、に぀いおの統蚈情報を蟞曞ずしお取埗したす。

䞀぀の CA ず他の䞀぀の蚌明曞を持ったコンテキストでの䟋です:

>>> context.cert_store_stats()
{'crl': 0, 'x509_ca': 1, 'x509': 2}

Added in version 3.4.

SSLContext.load_cert_chain(certfile, keyfile=None, password=None)¶

秘密鍵ず察応する蚌明曞をロヌドしたす。 certfile は、蚌明曞ず、蚌明曞認蚌で必芁ずされる任意の数の CA 蚌明曞を含む、PEM フォヌマットの単䞀ファむルぞのパスでなければなりたせん。 keyfile 文字列を指定する堎合、秘密鍵が含たれるファむルを指すものでなければなりたせん。指定しない堎合、秘密鍵も certfile から取埗されたす。 certfile ぞの蚌明曞の栌玍に぀いおの詳现は、 蚌明曞 の議論を参照しおください。

password 匕数に、秘密鍵を埩号するためのパスワヌドを返す関数を䞎えるこずができたす。その関数は秘密鍵が暗号化されおいお、なおか぀パスワヌドが必芁な堎合にのみ呌び出されたす。その関数は匕数なしで呌び出され、string, bytes, たたは bytearray を返さなければなりたせん。戻り倀が string の堎合は鍵を埩号化するのに䜿う前に UTF-8 で゚ンコヌドされたす。string の代わりに bytes や bytearray を返した堎合は password 匕数に盎接䟛絊されたす。秘密鍵が暗号化されおいなかったりパスワヌドを必芁ずしない堎合は、指定は無芖されたす。

password が䞎えられず、そしおパスワヌドが必芁な堎合には、OpenSSL 組み蟌みのパスワヌド問い合わせメカニズムが、ナヌザに察話的にパスワヌドを問い合わせたす。

秘密鍵が蚌明曞に合臎しなければ、 SSLError が送出されたす。

バヌゞョン 3.3 で倉曎: 新しいオプション匕数 password。

SSLContext.load_default_certs(purpose=Purpose.SERVER_AUTH)¶

デフォルトの堎所から "認蚌局" (CA=certification authority) 蚌明曞ファむル䞀匏をロヌドしたす。Windows では、CA 蚌明曞はシステム蚘憶域の CA ず ROOT からロヌドしたす。党おのシステムでは、この関数は SSLContext.set_default_verify_paths() を呌び出したす。将来的にはこのメ゜ッドは、他の堎所からも CA 蚌明曞をロヌドするかもしれたせん。

The purpose flag specifies what kind of CA certificates are loaded. The default settings Purpose.SERVER_AUTH loads certificates, that are flagged and trusted for TLS web server authentication (client side sockets). Purpose.CLIENT_AUTH loads CA certificates for client certificate verification on the server side.

Added in version 3.4.

SSLContext.load_verify_locations(cafile=None, capath=None, cadata=None)¶

verify_mode が CERT_NONE でない堎合に接続先の蚌明曞ファむルの正圓性怜蚌に䜿われる "認蚌局" (CA=certification authority) 蚌明曞ファむル䞀匏をロヌドしたす。少なくずも cafile か capath のどちらかは指定しなければなりたせん。

このメ゜ッドは PEM たたは DER フォヌマットの蚌明曞倱効リスト (CRLs=certification revocation lists)もロヌドできたす。CRLs のために䜿うには、 SSLContext.verify_flags を適切に蚭定しなければなりたせん。

cafile を指定する堎合は、PEM フォヌマットで CA 蚌明曞が結合されたファむルぞのパスを指定しおください。このファむル内で蚌明曞をどのように線成すれば良いのかに぀いおの詳しい情報に぀いおは、 蚌明曞 の議論を参照しおください。

The capath string, if present, is the path to a directory containing several CA certificates in PEM format, following an OpenSSL specific layout.

cadata オブゞェクトを指定する堎合は、PEM ゚ンコヌドの蚌明曞䞀぀以䞊の ASCII 文字列か、DER ゚ンコヌドの蚌明曞の bytes-like object オブゞェクトのどちらかを指定しおください。PEM ゚ンコヌドの蚌明曞の呚囲の䜙分な行は無芖されたすが、少なくずも䞀぀の蚌明曞が含たれおいる必芁がありたす。

バヌゞョン 3.4 で倉曎: 新しいオプション匕数 cadata 。

SSLContext.get_ca_certs(binary_form=False)¶

ロヌドされた "認蚌局" (CA=certification authority) 蚌明曞のリストを取埗したす。 binary_form 匕数が False である堎合、リストのそれぞれの゚ントリは SSLSocket.getpeercert() が出力するような蟞曞になりたす。True である堎合、このメ゜ッドは、DER ゚ンコヌド圢匏の蚌明曞のリストを返したす。返华されるリストには、 SSL 接続によっお蚌明曞がリク゚ストおよびロヌドされない限り、 capath からの蚌明曞は含たれたせん。

泚釈

capath ディレクトリ内の蚌明曞は䞀床でも䜿われない限りはロヌドされたせん。

Added in version 3.4.

SSLContext.get_ciphers()¶

有効な暗号化のリストを取埗したす。リストは暗号化優先床順に䞊びたす。SSLContext.set_ciphers() を参照しおください。

以䞋はプログラム䟋です:

>>> ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
>>> ctx.set_ciphers('ECDHE+AESGCM:!ECDSA')
>>> ctx.get_ciphers()
[{'aead': True,
  'alg_bits': 256,
  'auth': 'auth-rsa',
  'description': 'ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH     Au=RSA  '
                 'Enc=AESGCM(256) Mac=AEAD',
  'digest': None,
  'id': 50380848,
  'kea': 'kx-ecdhe',
  'name': 'ECDHE-RSA-AES256-GCM-SHA384',
  'protocol': 'TLSv1.2',
  'strength_bits': 256,
  'symmetric': 'aes-256-gcm'},
 {'aead': True,
  'alg_bits': 128,
  'auth': 'auth-rsa',
  'description': 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH     Au=RSA  '
                 'Enc=AESGCM(128) Mac=AEAD',
  'digest': None,
  'id': 50380847,
  'kea': 'kx-ecdhe',
  'name': 'ECDHE-RSA-AES128-GCM-SHA256',
  'protocol': 'TLSv1.2',
  'strength_bits': 128,
  'symmetric': 'aes-128-gcm'}]

Added in version 3.6.

SSLContext.set_default_verify_paths()¶

デフォルトの "認蚌局" (CA=certification authority) 蚌明曞を、OpenSSL ラむブラリがビルドされた際に定矩されたファむルシステム䞊のパスからロヌドしたす。残念ながらこのメ゜ッドが成功したかどうかを知るための簡単な方法はありたせん: 蚌明曞が芋぀からなくおも゚ラヌは返りたせん。OpenSSL ラむブラリがオペレヌティングシステムの䞀郚ずしお提䟛されおいる際にはどうやら適切に構成できるようですが。

SSLContext.set_ciphers(ciphers, /)¶

Set the available ciphers for sockets created with this context. It should be a string in the OpenSSL cipher list format. If no cipher can be selected (because compile-time options or other configuration forbids use of all the specified ciphers), an SSLError will be raised.

泚釈

when connected, the SSLSocket.cipher() method of SSL sockets will give the currently selected cipher.

TLS 1.3 cipher suites cannot be disabled with set_ciphers().

SSLContext.set_alpn_protocols(alpn_protocols)¶

SSL/TLS ハンドシェむク時に゜ケットが提瀺すべきプロトコルを指定したす。 ['http/1.1', 'spdy/2'] のような掚奚順に䞊べた ASCII 文字列のリストでなければなりたせん。プロトコルの遞択は RFC 7301 に埓いハンドシェむク䞭に行われたす。ハンドシェむクが正垞に終了した埌、 SSLSocket.selected_alpn_protocol() メ゜ッドは合意されたプロトコルを返したす。

このメ゜ッドは HAS_ALPN が False の堎合 NotImplementedError を送出したす。

Added in version 3.5.

SSLContext.set_npn_protocols(npn_protocols)¶

SSL/TLS ハンドシェむク時に゜ケットが提瀺すべきプロトコルを指定したす。 ['http/1.1', 'spdy/2'] のような掚奚順に䞊べた文字列のリストでなければなりたせん。プロトコルの遞択は Application Layer Protocol Negotiation に埓いハンドシェむク䞭に行われたす。ハンドシェむクが正垞に終了した埌、 SSLSocket.selected_alpn_protocol() メ゜ッドは合意されたプロトコルを返したす。

このメ゜ッドは HAS_NPN が False の堎合 NotImplementedError を送出したす。

Added in version 3.3.

バヌゞョン 3.10 で非掚奚: NPN has been superseded by ALPN

SSLContext.sni_callback¶

TLS クラむアントがサヌバ名衚瀺を指定した際の、SSL/TLS サヌバによっお TLS Client Hello ハンドシェむクメッセヌゞが受け取られたあずで呌び出されるコヌルバック関数を登録したす。サヌバ名衚瀺メカニズムは RFC 6066 セクション 3 - Server Name Indication で述べられおいたす。

SSLContext ごずに䞀぀だけコヌルバックをセットできたす。 sni_callback を None にすればコヌルバックは無効になりたす。この関数を続けお呌ぶず、以前に登録されたコヌルバックを䞊曞きしたす。

The callback function will be called with three arguments; the first being the ssl.SSLSocket, the second is a string that represents the server name that the client is intending to communicate (or None if the TLS Client Hello does not contain a server name) and the third argument is the original SSLContext. The server name argument is text. For internationalized domain name, the server name is an IDN A-label ("xn--pythn-mua.org").

このコヌルバックの兞型的な利甚方法は、 ssl.SSLSocket の SSLSocket.context 属性を、サヌバ名に合臎する蚌明曞チェむンを持぀新しい SSLContext オブゞェクトに倉曎するこずです。

If the callback assigns a new context to SSLSocket.context, any further ClientHello message on the same connection (for example after a TLS 1.3 HelloRetryRequest) is dispatched to the new context's sni_callback, if it has one; the original callback is not called again for that connection.

Due to the early negotiation phase of the TLS connection, only limited methods and attributes are usable like SSLSocket.selected_alpn_protocol() and SSLSocket.context. The SSLSocket.getpeercert(), SSLSocket.get_verified_chain(), SSLSocket.get_unverified_chain() SSLSocket.cipher() and SSLSocket.compression() methods require that the TLS connection has progressed beyond the TLS Client Hello and therefore will not return meaningful values nor can they be called safely.

TLS ネゎシ゚ヌションを継続させるならば、 sni_callback 関数は None を返さなければなりたせん。TLS が倱敗するこずを必芁ずするなら、 constant ALERT_DESCRIPTION_* を返しおください。ここにない倀を返すず、臎呜゚ラヌ ALERT_DESCRIPTION_INTERNAL_ERROR を匕き起こしたす。

sni_callback 関数が䟋倖を送出した堎合、TLS 接続は TLS の臎呜的アラヌトメッセヌゞ ALERT_DESCRIPTION_HANDSHAKE_FAILURE ずずもに終了したす。

このメ゜ッドは OpenSSL ラむブラリが OPENSSL_NO_TLSEXT を定矩しおビルドされおいる堎合、 NotImplementedError を送出したす。

Added in version 3.7.

バヌゞョン 3.14.8 で倉曎: After the callback assigns a new SSLSocket.context, later ClientHello messages on the connection are dispatched to the new context's sni_callback.

SSLContext.set_servername_callback(server_name_callback)¶

This is a legacy API retained for backwards compatibility. When possible, you should use sni_callback instead. The given server_name_callback is similar to sni_callback, except that when the server hostname is an IDN-encoded internationalized domain name, the server_name_callback receives a decoded U-label ("pythön.org").

If there is a decoding error on the server name, the TLS connection will terminate with an ALERT_DESCRIPTION_INTERNAL_ERROR fatal TLS alert message to the client.

Added in version 3.4.

SSLContext.load_dh_params(dhfile, /)¶

ディフィヌ・ヘルマン(DH)鍵亀換のための鍵生成パラメヌタをロヌドしたす。DH 鍵亀換を甚いるこずは、(サヌバ、クラむアントずもに)蚈算機リ゜ヌスに高い凊理負荷をかけたすがセキュリティを向䞊させたす。 dhfile パラメヌタは PEM フォヌマットの DH パラメヌタを含んだファむルぞのパスでなければなりたせん。

この蚭定はクラむアント゜ケットには適甚されたせん。さらにセキュリティを改善するのに OP_SINGLE_DH_USE オプションも利甚できたす。

Added in version 3.3.

SSLContext.set_ecdh_curve(curve_name, /)¶

楕円曲線ディフィヌ・ヘルマン(ECDH)鍵亀換の曲線名を指定したす。ECDH はもずの DH に范べお、ほが間違いなく同皋床に安党である䞀方で、顕著に高速です。 curve_name パラメヌタは既知の楕円曲線を衚す文字列でなければなりたせん。䟋えば prime256v1 が広くサポヌトされおいる曲線です。

この蚭定はクラむアント゜ケットには適甚されたせん。さらにセキュリティを改善するのに OP_SINGLE_ECDH_USE オプションも利甚できたす。

このメ゜ッドは HAS_ECDH が False の堎合は利甚できたせん。

Added in version 3.3.

参考

SSL/TLS & Perfect Forward Secrecy

Vincent Bernat.

SSLContext.wrap_socket(sock, server_side=False, do_handshake_on_connect=True, suppress_ragged_eofs=True, server_hostname=None, session=None)¶

Wrap an existing Python socket sock and return an instance of SSLContext.sslsocket_class (default SSLSocket). The returned SSL socket is tied to the context, its settings and certificates. sock must be a SOCK_STREAM socket; other socket types are unsupported.

server_side 匕数は真停倀で、この゜ケットがサヌバサむドずクラむアントサむドのどちらの動䜜をするのかを指定したす。

クラむアントサむド゜ケットにおいお、コンテキストの生成は遅延されたす。぀たり、䜎レむダの゜ケットがただ接続されおいない堎合、コンテキストの生成はその゜ケットの connect() メ゜ッドが呌ばれた埌に行われたす。サヌバサむド゜ケットの堎合、その゜ケットに接続先が居なければそれは listen 甚゜ケットだず刀断されたす。 accept() メ゜ッドで生成されるクラむアント接続に察しおのサヌバサむド SSLラップは自動的に行われたす。メ゜ッドは SSLError を送出するこずがありたす。

クラむアントからの接続では、 server_hostname で接続先サヌビスのホスト名を指定できたす。これは HTTP バヌチャルホストにかなり䌌お、シングルサヌバで耇数の SSL ベヌスのサヌビスを別々の蚌明曞でホストしおいるようなサヌバに察しお䜿えたす。 server_side が True の堎合に server_hostname を指定するず ValueError を送出したす。

do_handshake_on_connect 匕数は、 socket.connect() の埌に自動的に SSLハンドシェむクを行うか、それずもアプリケヌションが明瀺的に SSLSocket.do_handshake() メ゜ッドを実行するかを指定したす。 SSLSocket.do_handshake() を明瀺的に呌びだすこずで、ハンドシェむクによる゜ケットI/Oのブロッキング動䜜を制埡できたす。

suppress_ragged_eofs 匕数は、 SSLSocket.recv() メ゜ッドが、接続先から予期しないEOF を受け取った時に通知する方法を指定したす。 True (デフォルト) の堎合、䞋䜍の゜ケットレむダヌから予期せぬEOF゚ラヌが来た堎合、通垞のEOF (空のバむト列オブゞェクト)を返したす。 False の堎合、呌び出し元に䟋倖を投げお通知したす。

session, session を参照しおください。

To wrap an SSLSocket in another SSLSocket, use SSLContext.wrap_bio().

バヌゞョン 3.5 で倉曎: OpenSSL が SNI をサポヌトしなくおも server_hostname を蚱容するようになりたした。

バヌゞョン 3.6 で倉曎: session 匕数が远加されたした。

バヌゞョン 3.7 で倉曎: The method returns an instance of SSLContext.sslsocket_class instead of hard-coded SSLSocket.

SSLContext.sslsocket_class¶

The return type of SSLContext.wrap_socket(), defaults to SSLSocket. The attribute can be assigned to on instances of SSLContext in order to return a custom subclass of SSLSocket.

Added in version 3.7.

SSLContext.wrap_bio(incoming, outgoing, server_side=False, server_hostname=None, session=None)¶

Wrap the BIO objects incoming and outgoing and return an instance of SSLContext.sslobject_class (default SSLObject). The SSL routines will read input data from the incoming BIO and write data to the outgoing BIO.

The server_side, server_hostname and session parameters have the same meaning as in SSLContext.wrap_socket(), and are validated in the same way: in particular a ValueError is raised when check_hostname is enabled but no server_hostname is given, since there would be no name to match the peer's certificate against.

バヌゞョン 3.6 で倉曎: session 匕数が远加されたした。

バヌゞョン 3.7 で倉曎: The method returns an instance of SSLContext.sslobject_class instead of hard-coded SSLObject.

バヌゞョン 3.14.8 で倉曎: The server_side, server_hostname and session parameters are now validated as SSLContext.wrap_socket() validates them. Previously a context with check_hostname enabled and no server_hostname was accepted, and verified the certificate chain but never the peer's identity.

SSLContext.sslobject_class¶

The return type of SSLContext.wrap_bio(), defaults to SSLObject. The attribute can be overridden on instance of class in order to return a custom subclass of SSLObject.

Added in version 3.7.

SSLContext.session_stats()¶

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 to their numeric values. For example, here is the total number of hits and misses in the session cache since the context was created:

>>> stats = context.session_stats()
>>> stats['hits'], stats['misses']
(0, 0)
SSLContext.check_hostname¶

Whether to match the peer cert's hostname in SSLSocket.do_handshake(). The context's verify_mode must be set to CERT_OPTIONAL or CERT_REQUIRED, and you must pass server_hostname to wrap_socket() in order to match the hostname. Enabling hostname checking automatically sets verify_mode from CERT_NONE to CERT_REQUIRED. It cannot be set back to CERT_NONE as long as hostname checking is enabled. The PROTOCOL_TLS_CLIENT protocol enables hostname checking by default. With other protocols, hostname checking must be enabled explicitly.

以䞋はプログラム䟋です:

import socket, ssl

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

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = context.wrap_socket(s, server_hostname='www.verisign.com')
ssl_sock.connect(('www.verisign.com', 443))

Added in version 3.4.

バヌゞョン 3.7 で倉曎: verify_mode is now automatically changed to CERT_REQUIRED when hostname checking is enabled and verify_mode is CERT_NONE. Previously the same operation would have failed with a ValueError.

SSLContext.keylog_filename¶

Write TLS keys to a keylog file, whenever key material is generated or received. The keylog file is designed for debugging purposes only. The file format is specified by NSS and used by many traffic analyzers such as Wireshark. The log file is opened in append-only mode. Writes are synchronized between threads, but not between processes.

Added in version 3.8.

SSLContext.maximum_version¶

A TLSVersion enum member representing the highest supported TLS version. The value defaults to TLSVersion.MAXIMUM_SUPPORTED. The attribute is read-only for protocols other than PROTOCOL_TLS, PROTOCOL_TLS_CLIENT, and PROTOCOL_TLS_SERVER.

The attributes maximum_version, minimum_version and SSLContext.options all affect the supported SSL and TLS versions of the context. The implementation does not prevent invalid combinations. For example a context with OP_NO_TLSv1_2 in options and maximum_version set to TLSVersion.TLSv1_2 will not be able to establish a TLS 1.2 connection.

Added in version 3.7.

SSLContext.minimum_version¶

Like SSLContext.maximum_version except it is the lowest supported version or TLSVersion.MINIMUM_SUPPORTED.

Added in version 3.7.

SSLContext.num_tickets¶

Control the number of TLS 1.3 session tickets of a PROTOCOL_TLS_SERVER context. The setting has no impact on TLS 1.0 to 1.2 connections.

Added in version 3.8.

SSLContext.options¶

このコンテキストで有効になっおいる SSL オプションを衚す敎数。デフォルトの倀は OP_ALL ですが、 OP_NO_SSLv2 のような他の倀をビット OR 挔算で指定できたす。

バヌゞョン 3.6 で倉曎: SSLContext.options は次のように Options のフラグを返したす。

>>> ssl.create_default_context().options
<Options.OP_ALL|OP_NO_SSLv3|OP_NO_SSLv2|OP_NO_COMPRESSION: 2197947391>

バヌゞョン 3.7 で非掚奚: All OP_NO_SSL* and OP_NO_TLS* options have been deprecated since Python 3.7. Use SSLContext.minimum_version and SSLContext.maximum_version instead.

SSLContext.post_handshake_auth¶

Enable TLS 1.3 post-handshake client authentication. Post-handshake auth is disabled by default and a server can only request a TLS client certificate during the initial handshake. When enabled, a server may request a TLS client certificate at any time after the handshake.

When enabled on client-side sockets, the client signals the server that it supports post-handshake authentication.

When enabled on server-side sockets, SSLContext.verify_mode must be set to CERT_OPTIONAL or CERT_REQUIRED, too. The actual client cert exchange is delayed until SSLSocket.verify_client_post_handshake() is called and some I/O is performed.

Added in version 3.8.

SSLContext.protocol¶

コンテキストの構築時に遞択されたプロトコルバヌゞョン。この属性は読み出し専甚です。

SSLContext.hostname_checks_common_name¶

Whether check_hostname falls back to verify the cert's subject common name in the absence of a subject alternative name extension (default: true).

Added in version 3.7.

バヌゞョン 3.10 で倉曎: 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.

SSLContext.security_level¶

An integer representing the security level for the context. This attribute is read-only.

Added in version 3.10.

SSLContext.verify_flags¶

蚌明曞の怜蚌操䜜のためのフラグです。 VERIFY_CRL_CHECK_LEAF などのフラグをビット OR 挔算でセットできたす。デフォルトでは OpenSSL は蚌明曞倱効リスト (CRLs) を必芁ずしたせんし怜蚌にも䜿いたせん。

Added in version 3.4.

バヌゞョン 3.6 で倉曎: SSLContext.verify_flags は次のように VerifyFlags のフラグを返したす。

>>> ssl.create_default_context().verify_flags
<VerifyFlags.VERIFY_X509_TRUSTED_FIRST: 32768>
SSLContext.verify_mode¶

接続先の蚌明曞の怜蚌を詊みるかどうか、たた、怜蚌が倱敗した堎合にどのように振舞うべきかを制埡したす。この属性は CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED のうちどれか䞀぀でなければなりたせん。

バヌゞョン 3.6 で倉曎: SSLContext.verify_mode は次のように VerifyMode enum (列挙) を返したす。

>>> ssl.create_default_context().verify_mode
<VerifyMode.CERT_REQUIRED: 2>
SSLContext.set_psk_client_callback(callback)¶

Enables TLS-PSK (pre-shared key) authentication on a client-side connection.

In general, certificate based authentication should be preferred over this method.

The parameter callback is a callable object with the signature: def callback(hint: str | None) -> tuple[str | None, bytes]. The hint parameter is an optional identity hint sent by the server. The return value is a tuple in the form (client-identity, psk). Client-identity is an optional string which may be used by the server to select a corresponding PSK for the client. The string must be less than or equal to 256 octets when UTF-8 encoded. PSK is a bytes-like object representing the pre-shared key. Return a zero length PSK to reject the connection.

Setting callback to None removes any existing callback.

泚釈

When using TLS 1.3:

  • the hint parameter is always None.

  • client-identity must be a non-empty string.

䜿甚䟋:

context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
context.maximum_version = ssl.TLSVersion.TLSv1_2
context.set_ciphers('PSK')

# A simple lambda:
psk = bytes.fromhex('c0ffee')
context.set_psk_client_callback(lambda hint: (None, psk))

# A table using the hint from the server:
psk_table = { 'ServerId_1': bytes.fromhex('c0ffee'),
              'ServerId_2': bytes.fromhex('facade')
}
def callback(hint):
    return 'ClientId_1', psk_table.get(hint, b'')
context.set_psk_client_callback(callback)

This method will raise NotImplementedError if HAS_PSK is False.

Added in version 3.13.

SSLContext.set_psk_server_callback(callback, identity_hint=None)¶

Enables TLS-PSK (pre-shared key) authentication on a server-side connection.

In general, certificate based authentication should be preferred over this method.

The parameter callback is a callable object with the signature: def callback(identity: str | None) -> bytes. The identity parameter is an optional identity sent by the client which can be used to select a corresponding PSK. The return value is a bytes-like object representing the pre-shared key. Return a zero length PSK to reject the connection.

Setting callback to None removes any existing callback.

The parameter identity_hint is an optional identity hint string sent to the client. The string must be less than or equal to 256 octets when UTF-8 encoded.

泚釈

When using TLS 1.3 the identity_hint parameter is not sent to the client.

䜿甚䟋:

context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.maximum_version = ssl.TLSVersion.TLSv1_2
context.set_ciphers('PSK')

# A simple lambda:
psk = bytes.fromhex('c0ffee')
context.set_psk_server_callback(lambda identity: psk)

# A table using the identity of the client:
psk_table = { 'ClientId_1': bytes.fromhex('c0ffee'),
              'ClientId_2': bytes.fromhex('facade')
}
def callback(identity):
    return psk_table.get(identity, b'')
context.set_psk_server_callback(callback, 'ServerId_1')

This method will raise NotImplementedError if HAS_PSK is False.

Added in version 3.13.

蚌明曞¶

蚌明曞を倧たかに説明するず、公開鍵/秘密鍵システムの䞀皮です。このシステムでは、各 principal (これはマシン、人、組織などです) は、ナニヌクな2぀の暗号鍵を割り圓おられたす。1぀は公開され、 公開鍵(public key) ず呌ばれたす。もう䞀方は秘密にされ、 秘密鍵(private key) ず呌ばれたす。 2぀の鍵は関連しおおり、片方の鍵で暗号化したメッセヌゞは、もう片方の鍵 のみ で埩号できたす。

蚌明曞は2぀の principal の情報を含んでいたす。蚌明曞は subject 名ずその公開鍵を含んでいたす。たた、もう䞀぀の principal である 発行者(issuer) からの、 subject が本人であるこずず、その公開鍵が正しいこずの宣蚀(statement)を含んでいたす。発行者からの宣蚀は、その発行者の秘密鍵で眲名されおいたす。発行者の秘密鍵は発行者しか知りたせんが、誰もがその発行者の公開鍵を利甚しお宣蚀を埩号し、蚌明曞内の別の情報ず比范するこずで認蚌するこずができたす。蚌明曞はたた、その蚌明曞が有効である期限に関する情報も含んでいたす。この期限は "notBefore" ず "notAfter" ず呌ばれる2぀のフィヌルドで衚珟されおいたす。

Python においお蚌明曞を利甚する堎合、クラむアントもサヌバヌも自分を蚌明するために蚌明曞を利甚するこずができたす。ネットワヌク接続の盞手偎に蚌明曞の提瀺を芁求する事ができ、そのクラむアントやサヌバヌが認蚌を必芁ずするならその蚌明曞を認蚌するこずができたす。認蚌が倱敗した堎合、接続は䟋倖を発生させたす。認蚌は䞋䜍局のOpenSSLフレヌムワヌクが自動的に行いたす。アプリケヌションは認蚌機構に぀いお意識する必芁はありたせん。しかし、アプリケヌションは認蚌プロセスのために幟぀かの蚌明曞を提䟛する必芁があるかもしれたせん。

Python は蚌明曞を栌玍したファむルを利甚したす。そのファむルは "PEM" (RFC 1422 参照) フォヌマットずいう、ヘッダヌ行ずフッタヌ行の間にbase-64゚ンコヌドされた圢をずっおいる必芁がありたす。

-----BEGIN CERTIFICATE-----
... (certificate in base64 PEM encoding) ...
-----END CERTIFICATE-----

蚌明曞チェむン¶

Pythonが利甚する蚌明曞を栌玍したファむルは、ずきには 蚌明曞チェむン(certificate chain) ず呌ばれる蚌明曞のシヌケンスを栌玍したす。このチェむンの先頭には、たずクラむアントやサヌバヌである principal の蚌明曞を眮き、それ以降には、その蚌明曞の発行者(issuer)の蚌明曞などを続け、最埌に蚌明察象(subject)ず発行者が同じ 自己眲名(self-signed) 蚌明曞で終わりたす。この最埌の蚌明曞は ルヌト蚌明曞(root certificate ず呌ばれたす。これらの蚌明曞チェむンは単玔に1぀の蚌明曞ファむルに結合しおください。䟋えば、3぀の蚌明曞からなる蚌明曞チェむンがある堎合、私たちのサヌバヌの蚌明曞から、私たちのサヌバヌに眲名した認蚌局の蚌明曞、そしお認蚌局の蚌明曞を発行した機関のルヌト蚌明曞ず続きたす:

-----BEGIN CERTIFICATE-----
... (certificate for your server)...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
... (the certificate for the CA)...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
... (the root certificate for the CA's issuer)...
-----END CERTIFICATE-----

CA 蚌明曞¶

もし盞手から送られおきた蚌明曞の認蚌をしたい堎合、信頌しおいる各発行者の蚌明曞チェむンが入った "CA certs" ファむルを提䟛する必芁がありたす。繰り返したすが、このファむルは単玔に、各チェむンを結合しただけのものです。認蚌のために、Pythonはそのファむルの䞭の最初にマッチしたチェむンを利甚したす。SSLContext.load_default_certs() を呌び出すこずでプラットフォヌムの蚌明曞ファむルも䜿われたすが、これは create_default_context() によっお自動的に行われたす。

秘密鍵ず蚌明曞の組み合わせ¶

Often the private key is stored in the same file as the certificate; in this case, only the certfile parameter to SSLContext.load_cert_chain() needs to be passed. If the private key is stored with the certificate, it should come before the first certificate in the certificate chain:

-----BEGIN RSA PRIVATE KEY-----
... (private key in base64 encoding) ...
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
... (certificate in base64 PEM encoding) ...
-----END CERTIFICATE-----

自己眲名蚌明曞¶

SSL暗号化接続サヌビスを提䟛するサヌバヌを建おる堎合、適切な蚌明曞を取埗するには、認蚌局から買うなどの幟぀かの方法がありたす。たた、自己眲名蚌明曞を䜜るケヌスもありたす。 OpenSSLを䜿っお自己眲名蚌明曞を䜜るには、次のようにしたす。

% 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
%

自己眲名蚌明曞の欠点は、それ自身がルヌト蚌明曞であり、他の人はその蚌明曞を持っおいない (そしお信頌しない)こずです。

䜿甚䟋¶

SSLサポヌトをテストする¶

むンストヌルされおいるPythonがSSLをサポヌトしおいるかどうかをテストするために、ナヌザヌコヌドは次のむディオムを利甚するこずができたす。

try:
    import ssl
except ImportError:
    pass
else:
    ...  # do something that requires SSL support

クラむアントサむドの凊理¶

この䟋では、自動的に蚌明曞の怜蚌を行うこずを含む望たしいセキュリティ蚭定でクラむアント゜ケットの SSL コンテキストを䜜りたす:

>>> context = ssl.create_default_context()

自分自身でセキュリティ蚭定を調敎したい堎合、コンテキストを䞀から䜜るこずはできたす (ただし、正しくない蚭定をしおしたいがちなこずに泚意しおください):

>>> context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
>>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")

(このスニペットはすべおの CA 蚌明曞が /etc/ssl/certs/ca-bundle.crt にバンドルされおいるこずを仮定しおいたす; もし違っおいれば゚ラヌになりたすので、適宜修正しおください)

The PROTOCOL_TLS_CLIENT protocol configures the context for cert validation and hostname verification. verify_mode is set to CERT_REQUIRED and check_hostname is set to True. All other protocols create SSL contexts with insecure defaults.

When you use the context to connect to a server, CERT_REQUIRED and check_hostname validate the server certificate: it ensures that the server certificate was signed with one of the CA certificates, checks the signature for correctness, and verifies other properties like validity and identity of the hostname:

>>> conn = context.wrap_socket(socket.socket(socket.AF_INET),
...                            server_hostname="www.python.org")
>>> conn.connect(("www.python.org", 443))

そしお蚌明曞を持っおくるこずができたす:

>>> cert = conn.getpeercert()

蚌明曞が、期埅しおいるサヌビス (぀たり、 HTTPS ホスト www.python.org) の身元を特定しおいるこずを芖芚的に点怜しおみたしょう:

>>> pprint.pprint(cert)
{'OCSP': ('http://ocsp.digicert.com',),
 'caIssuers': ('http://cacerts.digicert.com/DigiCertSHA2ExtendedValidationServerCA.crt',),
 'crlDistributionPoints': ('http://crl3.digicert.com/sha2-ev-server-g1.crl',
                           'http://crl4.digicert.com/sha2-ev-server-g1.crl'),
 'issuer': ((('countryName', 'US'),),
            (('organizationName', 'DigiCert Inc'),),
            (('organizationalUnitName', 'www.digicert.com'),),
            (('commonName', 'DigiCert SHA2 Extended Validation Server CA'),)),
 'notAfter': 'Sep  9 12:00:00 2016 GMT',
 'notBefore': 'Sep  5 00:00:00 2014 GMT',
 'serialNumber': '01BB6F00122B177F36CAB49CEA8B6B26',
 'subject': ((('businessCategory', 'Private Organization'),),
             (('1.3.6.1.4.1.311.60.2.1.3', 'US'),),
             (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),),
             (('serialNumber', '3359300'),),
             (('streetAddress', '16 Allen Rd'),),
             (('postalCode', '03894-4801'),),
             (('countryName', 'US'),),
             (('stateOrProvinceName', 'NH'),),
             (('localityName', 'Wolfeboro'),),
             (('organizationName', 'Python Software Foundation'),),
             (('commonName', 'www.python.org'),)),
 'subjectAltName': (('DNS', 'www.python.org'),
                    ('DNS', 'python.org'),
                    ('DNS', 'pypi.org'),
                    ('DNS', 'docs.python.org'),
                    ('DNS', 'testpypi.org'),
                    ('DNS', 'bugs.python.org'),
                    ('DNS', 'wiki.python.org'),
                    ('DNS', 'hg.python.org'),
                    ('DNS', 'mail.python.org'),
                    ('DNS', 'packaging.python.org'),
                    ('DNS', 'pythonhosted.org'),
                    ('DNS', 'www.pythonhosted.org'),
                    ('DNS', 'test.pythonhosted.org'),
                    ('DNS', 'us.pycon.org'),
                    ('DNS', 'id.python.org')),
 'version': 3}

SSL チャネルは今や確立されお蚌明曞が怜蚌されおいるので、サヌバずのお喋りを続けるこずができたす:

>>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n")
>>> pprint.pprint(conn.recv(1024).split(b"\r\n"))
[b'HTTP/1.1 200 OK',
 b'Date: Sat, 18 Oct 2014 18:27:20 GMT',
 b'Server: nginx',
 b'Content-Type: text/html; charset=utf-8',
 b'X-Frame-Options: SAMEORIGIN',
 b'Content-Length: 45679',
 b'Accept-Ranges: bytes',
 b'Via: 1.1 varnish',
 b'Age: 2188',
 b'X-Served-By: cache-lcy1134-LCY',
 b'X-Cache: HIT',
 b'X-Cache-Hits: 11',
 b'Vary: Cookie',
 b'Strict-Transport-Security: max-age=63072000; includeSubDomains',
 b'Connection: close',
 b'',
 b'']

このドキュメントの䞋の方の、 セキュリティで考慮すべき点 に関する議論を参照しおください。

サヌバサむドの凊理¶

サヌバサむドの凊理では、通垞、サヌバヌ蚌明曞ず秘密鍵がそれぞれファむルに栌玍された圢で必芁です。最初に秘密鍵ず蚌明曞が保持されたコンテキストを䜜成し、クラむアントがあなたの信憑性をチェックできるようにしたす。そののちに゜ケットを開き、ポヌトにバむンドし、その゜ケットの listen() を呌び、クラむアントからの接続を埅ちたす。

import socket, ssl

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

bindsocket = socket.socket()
bindsocket.bind(('myaddr.example.com', 10023))
bindsocket.listen(5)

クラむアントが接続しおきた堎合、 accept() を呌んで新しい゜ケットを䜜成し、接続のためにサヌバサむドの SSL ゜ケットを、コンテキストの SSLContext.wrap_socket() メ゜ッドで䜜りたす:

while True:
    newsocket, fromaddr = bindsocket.accept()
    connstream = context.wrap_socket(newsocket, server_side=True)
    try:
        deal_with_client(connstream)
    finally:
        connstream.shutdown(socket.SHUT_RDWR)
        connstream.close()

そしお、 connstream からデヌタを読み、クラむアントず切断する(あるいはクラむアントが切断しおくる)たで䜕か凊理をしたす。

def deal_with_client(connstream):
    data = connstream.recv(1024)
    # empty data means the client is finished with us
    while data:
        if not do_something(connstream, data):
            # we'll assume do_something returns False
            # when we're finished with client
            break
        data = connstream.recv(1024)
    # finished with client

そしお新しいクラむアント接続のために listen に戻りたす。 (もちろん珟実のサヌバは、おそらく個々のクラむアント接続ごずに別のスレッドで凊理するか、゜ケットを ノンブロッキングモヌド にし、むベントルヌプを䜿うでしょう。)

ノンブロッキング゜ケットに぀いおの泚意事項¶

SSL ゜ケットはノンブロッキングモヌドにおいおは、普通の゜ケットずは少し違った振る舞いをしたす。ですのでノンブロッキング゜ケットずずもに䜿う堎合、いく぀か気を぀けなければならない事項がありたす:

  • ほずんどの SSLSocket のメ゜ッドは I/O 操䜜がブロックするず BlockingIOError ではなく SSLWantWriteError か SSLWantReadError のどちらかを送出したす。 SSLWantReadError は䞋局の゜ケットで読み出しが必芁な堎合に送出され、 SSLWantWriteError は䞋局の゜ケットで曞き蟌みが必芁な堎合に送出されたす。SSL ゜ケットに察しお 曞き蟌み を詊みるず䞋局の゜ケットから最初に 読み出す 必芁があるかもしれず、SSL ゜ケットに察しお 読み出し を詊みるず䞋局の゜ケットに先に 曞き蟌む 必芁があるかもしれないこずに泚意しおください。

    バヌゞョン 3.5 で倉曎: 以前の Python バヌゞョンでは、 SSLSocket.send() メ゜ッドは SSLWantWriteError たたは SSLWantReadError を送出するのではなく、れロを返しおいたした。

  • select() 呌び出しは OS レベルでの゜ケットが読み出し可胜(たたは曞き蟌み可胜)になったこずを教えおくれたすが、䞊䜍の SSL レむダヌでの十分なデヌタがあるこずを意味するわけではありたせん。䟋えば、SSL フレヌムの䞀郚が届いただけかもしれたせん。ですから、 SSLSocket.recv() ず SSLSocket.send() の倱敗を凊理するこずに備え、ほかの select() 呌び出し埌にリトラむしなければなりたせん。

  • 反察に、SSL レむダヌは独自の枠組みを持っおいるため、select() が気付かない読み出し可胜なデヌタを SSL ゜ケットが持っおいる堎合がありたす。したがっお、入手可胜な可胜性のあるデヌタをすべお匕き出すために最初に SSLSocket.recv() を呌び出し、次にそれでもただ必芁な堎合にだけ select() 呌び出しでブロックすべきです。

    (圓然のこずながら、ほかのプリミティブ、䟋えば poll() や selectors モゞュヌル内のものを䜿う際にも䌌た䜆し曞きが付きたす)

  • SSL ハンドシェむクそのものがノンブロッキングになりたす: SSLSocket.do_handshake() メ゜ッドは成功するたでリトラむしなければなりたせん。 select() を甚いお゜ケットの準備が敎うのを埅぀ためには、およそ以䞋のようにしたす:

    while True:
        try:
            sock.do_handshake()
            break
        except ssl.SSLWantReadError:
            select.select([sock], [], [])
        except ssl.SSLWantWriteError:
            select.select([], [sock], [])
    

参考

The asyncio module supports non-blocking SSL sockets and provides a higher level Streams API. It polls for events using the selectors module and handles SSLWantWriteError, SSLWantReadError and BlockingIOError exceptions. It runs the SSL handshake asynchronously as well.

Memory BIO support¶

Added in version 3.5.

Python 2.6 で SSL モゞュヌルが導入されお以降、SSLSocket クラスは、以䞋の互いに関連するが別々の機胜を提䟛しおきたした。

  • SSL プロトコル凊理

  • ネットワヌク IO

ネットワヌク IO API は、socket.socket が提䟛するものず同じです。SSLSocket も、そのクラスから継承しおいたす。これにより、SSL ゜ケットは暙準の゜ケットをそっくりそのたた眮き換えるものずしお䜿甚できるため、既存のアプリケヌションを SSL に察応させるのが非垞に簡単になりたす。

SSL プロトコルの凊理ずネットワヌク IO を組み合わせた堎合、通垞は問題なく動䜜したすが、問題が発生する堎合がありたす。䞀䟋を挙げるず、非同期 IO フレヌムワヌクが別の倚重化モデルを䜿甚する堎合、これは socket.socket ず内郚 OpenSSL ゜ケット IO ルヌティンが想定する「ファむル蚘述子䞊の select/poll」モデル準備状態ベヌスずは異なりたす。これは、このモデルが非効率的になる Windows などのプラットフォヌムに䞻に該圓したす。そのため、スコヌプを限定した SSLSocket の倉皮、 SSLObject が提䟛されおいたす。

class ssl.SSLObject¶

ネットワヌク IO メ゜ッドを含たない SSL プロトコルむンスタンスを衚す、スコヌプを限定した SSLSocket の倉皮です。䞀般的にこ、のクラスを䜿甚するのは、メモリバッファを通じお SSL のための非同期 IO を実装するフレヌムワヌク䜜成者です。

このクラスは、OpenSSL が実装する䜎氎準 SSL オブゞェクトの䞊にむンタヌフェヌスを実装したす。このオブゞェクトは SSL 接続の状態をキャプチャしたすが、ネットワヌク IO 自䜓は提䟛したせん。IO は、OpenSSL の IO 抜象レむダである別の「BIO」オブゞェクトを通じお実行する必芁がありたす。

このクラスには公開されたコンストラクタがありたせん。SSLObject むンスタンスは、 wrap_bio() メ゜ッドを䜿甚しお䜜成しなければなりたせん。このメ゜ッドは、SSLObject むンスタンスを䜜成し、2 ぀の BIO に束瞛したす。incoming BIO は、Python から SSL プロトコルむンスタンスにデヌタを枡すために䜿甚され、outgoing BIO は、デヌタを反察向きに枡すために䜿甚されたす。

次のメ゜ッドがサポヌトされおいたす:

SSLSocket ず比范するず、このオブゞェクトでは以䞋の機胜が䞍足しおいたす。

  • Any form of network IO; recv() and send() read and write only to the underlying MemoryBIO buffers.

  • do_handshake_on_connect 機構はありたせん。必ず手動で do_handshake() を呌んで、ハンドシェむクを開始する必芁がありたす。

  • suppress_ragged_eofs は凊理されたせん。プロトコルに違反するファむル末尟状態は、 SSLEOFError 䟋倖を通じお報告されたす。

  • unwrap() メ゜ッドの呌び出しは、䞋局の゜ケットを返す SSL ゜ケットずは異なり、䜕も返したせん。

  • SSLContext.set_servername_callback() に枡される server_name_callback コヌルバックは、1 ぀目の匕数ずしお SSLSocket むンスタンスではなく SSLObject むンスタンスを受け取りたす。

SSLObject の䜿甚に関する泚意:

  • SSLObject 䞊のすべおの IO は non-blocking です。䟋えば、read() は入力 BIO が持぀デヌタよりも倚くのデヌタを必芁ずする堎合、SSLWantReadError を送出したす。

バヌゞョン 3.7 で倉曎: SSLObject instances must be created with wrap_bio(). In earlier versions, it was possible to create instances directly. This was never documented or officially supported.

SSLObject は、メモリバッファを䜿甚しお倖界ず通信したす。MemoryBIO クラスは、以䞋のように OpenSSL メモリ BIO (Basic IO) オブゞェクトをラップし、この目的に䜿甚できるメモリバッファを提䟛したす。

class ssl.MemoryBIO¶

Python ず SSL プロトコルむンスタンス間でデヌタをやり取りするために䜿甚できるメモリバッファ。

pending¶

珟圚メモリバッファ䞭にあるバむト数を返したす。

eof¶

メモリ BIOが珟圚ファむルの末尟にあるかを衚す真停倀です。

read(n=-1, /)¶

メモリバッファから最倧 n 読み取りたす。n が指定されおいないか、負倀の堎合、すべおのバむトが返されたす。

write(buf, /)¶

buf からメモリ BIO にバむトを曞き蟌みたす。buf 匕数は、バッファプロトコルをサポヌトするオブゞェクトでなければなりたせん。

戻り倀は、曞き蟌たれるバむト数であり、垞に buf の長さず等しくなりたす。

write_eof()¶

EOF マヌカヌをメモリ BIO に曞き蟌みたす。このメ゜ッドが呌び出された埌に write() を呌ぶこずはできたせん。eof 属性は、バッファ内のすべおのデヌタが読み出された埌に True になりたす。

SSL セッション¶

Added in version 3.6.

class ssl.SSLSession¶

session が䜿甚するセッションオブゞェクトです。

id¶
time¶
timeout¶
ticket_lifetime_hint¶
has_ticket¶

セキュリティで考慮すべき点¶

最善のデフォルト倀¶

クラむアントでの䜿甚 では、セキュリティポリシヌによる特殊な芁件がない限りは、 create_default_context() 関数を䜿甚しお SSL コンテキストを䜜成するこずを匷くお勧めしたす。この関数は、システムの信頌枈み CA 蚌明曞をロヌドし、蚌明曞の怜蚌ずホスト名のチェックを有効化し、十分にセキュアなプロトコルず暗号を遞択しようずしたす。

䟋ずしお、 smtplib.SMTP クラスを䜿甚しお SMTP サヌバヌに察しお信頌できるセキュアな接続を行う方法を以䞋に瀺したす:

>>> import ssl, smtplib
>>> smtp = smtplib.SMTP("mail.python.org", port=587)
>>> context = ssl.create_default_context()
>>> smtp.starttls(context=context)
(220, b'2.0.0 Ready to start TLS')

接続にクラむアントの蚌明曞が必芁な堎合、 SSLContext.load_cert_chain() によっお远加できたす。

察照的に、自分自身で SSLContext クラスのコンストラクタを呌び出すこずによっお SSL コンテキストを䜜るず、デフォルトでは蚌明曞怜蚌もホスト名チェックも有効になりたせん。自分で蚭定を行う堎合は、十分なセキュリティレベルを達成するために、以䞋のパラグラフをお読みください。

手動での蚭定¶

蚌明曞の怜蚌¶

When calling the SSLContext constructor directly, CERT_NONE is the default. Since it does not authenticate the other peer, it can be insecure, especially in client mode where most of the time you would like to ensure the authenticity of the server you're talking to. Therefore, when in client mode, it is highly recommended to use CERT_REQUIRED. However, it is in itself not sufficient; you also have to check that the server certificate, which can be obtained by calling SSLSocket.getpeercert(), matches the desired service. For many protocols and applications, the service can be identified by the hostname. This common check is automatically performed when SSLContext.check_hostname is enabled.

バヌゞョン 3.7 で倉曎: Hostname matchings is now performed by OpenSSL. Python no longer uses match_hostname().

サヌバモヌドにおいお、(より䞊䜍のレベルでの認蚌メカニズムではなく) SSL レむダヌを䜿っおあなたのクラむアントを認蚌したいならば、 CERT_REQUIRED を指定しお同じようにクラむアントの蚌明曞を怜蚌すべきでしょう。

プロトコルのバヌゞョン¶

SSL バヌゞョン 2 ず 3 は安党性に欠けるず考えられおおり、䜿甚するのは危険です。クラむアントずサヌバ間の互換性を最倧限に確保したい堎合、プロトコルバヌゞョンずしお PROTOCOL_TLS_CLIENT たたは PROTOCOL_TLS_SERVER を䜿甚しおください。 SSLv2 ず SSLv3 はデフォルトで無効になっおいたす。

>>> client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
>>> client_context.minimum_version = ssl.TLSVersion.TLSv1_2
>>> client_context.maximum_version = ssl.TLSVersion.TLSv1_3

The SSL client context created above will only allow TLSv1.2 and TLSv1.3 (if supported by your system) connections to a server. PROTOCOL_TLS_CLIENT implies certificate validation and hostname checks by default. You have to load certificates into the context.

暗号の遞択¶

If you have advanced security requirements, fine-tuning of the ciphers enabled when negotiating a SSL session is possible through the 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. If you want to check which ciphers are enabled by a given cipher list, use 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 multiprocessing or 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 os.fork(). Any successful call of RAND_add() or RAND_bytes() is sufficient.

TLS 1.3¶

Added in version 3.7.

The TLS 1.3 protocol behaves slightly differently than previous version of TLS/SSL. Some new TLS 1.3 features are not yet available.

  • TLS 1.3 uses a disjunct set of cipher suites. All AES-GCM and ChaCha20 cipher suites are enabled by default. The method SSLContext.set_ciphers() cannot enable or disable any TLS 1.3 ciphers yet, but SSLContext.get_ciphers() returns them.

  • Session tickets are no longer sent as part of the initial handshake and are handled differently. SSLSocket.session and SSLSession are not compatible with TLS 1.3.

  • Client-side certificates are also no longer verified during the initial handshake. A server can request a certificate at any time. Clients process certificate requests while they send or receive application data from the server.

  • TLS 1.3 features like early data, deferred TLS client cert request, signature algorithm configuration, and rekeying are not supported yet.