"ssl" --- TLS/SSL wrapper for socket objects
********************************************

**Source code:** Lib/ssl.py

======================================================================

このモジュールは Transport Layer Security ( "Secure Sockets Layer" と
いう名前でよく知られています) 暗号化と、クライアントサイド、サーバサイ
ド両方のネットワークソケットのためのピア認証の仕組みを提供しています。
このモジュールは OpenSSL ライブラリを利用しています。 OpenSSL は、すべ
てのモダンな Unix システム、 Windows 、 macOS 、その他幾つかの OpenSSL
がインストールされているプラットフォームで利用できます。

注釈:

  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 Emscripten, not WASI.

This module does not work or is not available on WebAssembly platforms
"wasm32-emscripten" and "wasm32-wasi". See WebAssembly プラットフォー
ム for more information.

このセクションでは、 "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, and "cipher()",
which retrieves the cipher being used for the secure connection.

より洗練されたアプリケーションのために、 "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.


関数、定数、例外
================


ソケットの作成
--------------

Since Python 3.2 and 2.7.9, it is recommended to use the
"SSLContext.wrap_socket()" of an "SSLContext" instance to wrap sockets
as "SSLSocket" objects. The helper functions
"create_default_context()" returns a new context with secure default
settings. The old "wrap_socket()" function is deprecated since it is
both inefficient and has no support for server name indication (SNI)
and hostname matching.

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)

   新規の "SSLContext" オブジェクトを、与えられた *purpose* のデフォル
   ト設定で返します。設定は "ssl" モジュールで選択され、通常は
   "SSLContext" のコンストラクタを直接呼び出すよりも高いセキュリティレ
   ベルを表現します。

   *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.

   注釈:

     プロトコル、オプション、暗号方式その他の設定は、事前に非推奨の状
     態にすることなく、もっと制限の強い値に変更される場合があります。
     これらの値は、互換性と安全性との妥当なバランスをとって決められま
     す。もしもあなたのアプリケーションが特定の設定を必要とする場合、
     "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

   バージョン 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".


例外
----

exception ssl.SSLError

   (現在のところ OpenSSL ライブラリによって提供されている)下層の SSL
   実装からのエラーを伝えるための例外です。このエラーは、低レベルなネ
   ットワークの上に載っている、高レベルな暗号化と認証レイヤーでの問題
   を通知します。このエラーは "OSError" のサブタイプです。 "SSLError"
   インスタンスのエラーコードとメッセージは OpenSSL ライブラリによるも
   のです。

   バージョン 3.3 で変更: "SSLError" は以前は "socket.error" のサブタ
   イプでした。

   library

      エラーが起こった OpenSSL サブモジュールを示すニーモニック文字列
      で、 "SSL", "PEM", "X509" などです。取り得る値は OpenSSL のバー
      ジョンに依存します。

      バージョン 3.3 で追加.

   reason

      エラーが起こった原因を示すニーモニック文字列で、
      "CERTIFICATE_VERIFY_FAILED" などです。取り得る値は OpenSSL のバ
      ージョンに依存します。

      バージョン 3.3 で追加.

exception ssl.SSLZeroReturnError

   読み出しあるいは書き込みを試みようとした際に SSL コネクションが行儀
   よく閉じられてしまった場合に送出される "SSLError" サブクラス例外で
   す。これは下層の転送(read TCP)が閉じたことは意味しないことに注意し
   てください。

   バージョン 3.3 で追加.

exception ssl.SSLWantReadError

   読み出しあるいは書き込みを試みようとした際に、リクエストが遂行され
   る前に下層の TCP 転送で受け取る必要があるデータが不足した場合に
   non-blocking SSL socket によって送出される "SSLError" サブクラス例
   外です。

   バージョン 3.3 で追加.

exception ssl.SSLWantWriteError

   読み出しあるいは書き込みを試みようとした際に、リクエストが遂行され
   る前に下層の TCP 転送が送信する必要があるデータが不足した場合に
   non-blocking SSL socket によって送出される "SSLError" サブクラス例
   外です。

   バージョン 3.3 で追加.

exception ssl.SSLSyscallError

   SSL ソケット上で操作を遂行しようとしていてシステムエラーが起こった
   場合に送出される "SSLError" サブクラス例外です。残念ながら元となっ
   た errno 番号を調べる簡単な方法はありません。

   バージョン 3.3 で追加.

exception ssl.SSLEOFError

   SSL コネクションが唐突に打ち切られた際に送出される "SSLError" サブ
   クラス例外です。一般的に、このエラーが起こったら下層の転送を再利用
   しようと試みるべきではありません。

   バージョン 3.3 で追加.

exception ssl.SSLCertVerificationError

   A subclass of "SSLError" raised when certificate validation has
   failed.

   バージョン 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) (日本語版: 暗号論的擬似乱数生成器) を参照してください。

   バージョン 3.3 で追加.

ssl.RAND_pseudo_bytes(num)

   Return (bytes, is_cryptographic): bytes are *num* pseudo-random
   bytes, is_cryptographic is "True" if the bytes generated are
   cryptographically strong. Raises an "SSLError" if the operation is
   not supported by the current RAND method.

   Generated pseudo-random byte sequences will be unique if they are
   of sufficient length, but are not necessarily unpredictable. They
   can be used for non-cryptographic purposes and for certain purposes
   in cryptographic protocols, but usually not for key generation etc.

   ほとんどすべてのアプリケーションでは "os.urandom()" が望ましいです
   。

   バージョン 3.3 で追加.

   バージョン 3.6 で非推奨: OpenSSL has deprecated
   "ssl.RAND_pseudo_bytes()", use "ssl.RAND_bytes()" instead.

ssl.RAND_status()

   SSL 擬似乱数生成器が十分なランダム性(randomness)を受け取っている時
   に "True" を、それ以外の場合は *False* を返します。
   "ssl.RAND_egd()" と "ssl.RAND_add()" を使って擬似乱数生成機にランダ
   ム性を加えることができます。

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.match_hostname(cert, hostname)

   Verify that *cert* (in decoded format as returned by
   "SSLSocket.getpeercert()") matches the given *hostname*.  The rules
   applied are those for checking the identity of HTTPS servers as
   outlined in **RFC 2818**, **RFC 5280** and **RFC 6125**.  In
   addition to HTTPS, this function should be suitable for checking
   the identity of servers in various SSL-based protocols such as
   FTPS, IMAPS, POPS and others.

   "CertificateError" is raised on failure. On success, the function
   returns nothing:

      >>> cert = {'subject': ((('commonName', 'example.com'),),)}
      >>> ssl.match_hostname(cert, "example.com")
      >>> ssl.match_hostname(cert, "example.org")
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
        File "/home/py3k/Lib/ssl.py", line 130, in match_hostname
      ssl.CertificateError: hostname 'example.org' doesn't match 'example.com'

   バージョン 3.2 で追加.

   バージョン 3.3.3 で変更: The function now follows **RFC 6125**,
   section 6.4.3 and does neither match multiple wildcards (e.g.
   "*.*.com" or "*a*.example.org") nor a wildcard inside an
   internationalized domain names (IDN) fragment. IDN A-labels such as
   "www*.xn--pthon-kva.org" are still supported, but "x*.python.org"
   no longer matches "xn--tda.python.org".

   バージョン 3.5 で変更: Matching of IP addresses, when present in
   the subjectAltName field of the certificate, is now supported.

   バージョン 3.7 で変更: The function is no longer used to TLS
   connections. Hostname matching is now performed by OpenSSL.Allow
   wildcard when it is the leftmost and the only character in that
   segment. Partial wildcards like "www*.example.com" are no longer
   supported.

   バージョン 3.7 で非推奨.

ssl.cert_time_to_seconds(cert_time)

   "cert_time" として証明書内の "notBefore" や "notAfter" の ""%b %d
   %H:%M:%S %Y %Z"" strptime フォーマット (C locale) 日付を渡すと、エ
   ポックからの積算秒を返します。

   例です。 :

      >>> import ssl
      >>> timestamp = ssl.cert_time_to_seconds("Jan  5 09:34:43 2018 GMT")
      >>> timestamp  
      1515144883
      >>> from datetime import datetime
      >>> print(datetime.utcfromtimestamp(timestamp))  
      2018-01-05 09:34:43

   "notBefore" や "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 same parameter in "SSLContext.wrap_socket()".  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 のパス

   バージョン 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.

   バージョン 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.

   バージョン 3.4 で追加.

ssl.wrap_socket(sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version=PROTOCOL_TLS, ca_certs=None, do_handshake_on_connect=True, suppress_ragged_eofs=True, ciphers=None)

   Takes an instance "sock" of "socket.socket", and returns an
   instance of "ssl.SSLSocket", a subtype of "socket.socket", which
   wraps the underlying socket in an SSL context.  "sock" must be a
   "SOCK_STREAM" socket; other socket types are unsupported.

   Internally, function creates a "SSLContext" with protocol
   *ssl_version* and "SSLContext.options" set to *cert_reqs*. If
   parameters *keyfile*, *certfile*, *ca_certs* or *ciphers* are set,
   then the values are passed to "SSLContext.load_cert_chain()",
   "SSLContext.load_verify_locations()", and
   "SSLContext.set_ciphers()".

   The arguments *server_side*, *do_handshake_on_connect*, and
   *suppress_ragged_eofs* have the same meaning as
   "SSLContext.wrap_socket()".

   バージョン 3.7 で非推奨: Since Python 3.2 and 2.7.9, it is
   recommended to use the "SSLContext.wrap_socket()" instead of
   "wrap_socket()". The top-level function is limited and creates an
   insecure client socket without server name indication or hostname
   matching.


定数
----

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

   バージョン 3.6 で追加.

ssl.CERT_NONE

   Possible value for "SSLContext.verify_mode", or the "cert_reqs"
   parameter to "wrap_socket()".  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", or the "cert_reqs"
   parameter to "wrap_socket()".  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, either to "SSLContext.load_verify_locations()" or as a
   value of the "ca_certs" parameter to "wrap_socket()".

ssl.CERT_REQUIRED

   Possible value for "SSLContext.verify_mode", or the "cert_reqs"
   parameter to "wrap_socket()".  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, either to "SSLContext.load_verify_locations()" or as a
   value of the "ca_certs" parameter to "wrap_socket()".

class ssl.VerifyMode

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

   バージョン 3.6 で追加.

ssl.VERIFY_DEFAULT

   "SSLContext.verify_flags" に渡せる値です。このモードでは、証明書失
   効リスト(CRLs)はチェックされません。デフォルトでは OpenSSL は CRLs
   を必要ともしませんし検証にも使いません。

   バージョン 3.4 で追加.

ssl.VERIFY_CRL_CHECK_LEAF

   "SSLContext.verify_flags" に渡せる値です。このモードでは、接続先の
   証明書のみがチェックされ、仲介の CA 証明書はチェックされません。接
   続先証明書の発行者(その CA の直接の祖先)によって署名された妥当な
   CRL が必要です。 "SSLContext.load_verify_locations" で相応しい CRL
   をロードしていなければ、検証は失敗します。

   バージョン 3.4 で追加.

ssl.VERIFY_CRL_CHECK_CHAIN

   "SSLContext.verify_flags" に渡せる値です。このモードでは、接続先の
   証明書チェイン内のすべての証明書についての CRLs がチェックされます
   。

   バージョン 3.4 で追加.

ssl.VERIFY_X509_STRICT

   "SSLContext.verify_flags" に渡せる値で、壊れた X.509 証明書に対する
   ワークアラウンドを無効にします。

   バージョン 3.4 で追加.

ssl.VERIFY_ALLOW_PROXY_CERTS

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

   バージョン 3.10 で追加.

ssl.VERIFY_X509_TRUSTED_FIRST

   "SSLContext.verify_flags" に渡せる値です。OpenSSL に対し、証明書検
   証のために信頼チェインを構築する際、信頼できる証明書を選ぶように指
   示します。これはデフォルトで有効にされています。

   バージョン 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.

   バージョン 3.10 で追加.

class ssl.VerifyFlags

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

   バージョン 3.6 で追加.

ssl.PROTOCOL_TLS

   クライアントとサーバの両方がサポートするプロトコルバージョンのうち
   、最も大きなものを選択します。名前に反して、このオプションは "SSL"
   と "TLS" プロトコルのいずれも選択できます。

   バージョン 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.

   バージョン 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.

   バージョン 3.6 で追加.

ssl.PROTOCOL_SSLv23

   "PROTOCOL_TLS" のエイリアスです。

   バージョン 3.6 で非推奨: 代わりに "PROTOCOL_TLS" を使用してください
   。

ssl.PROTOCOL_SSLv2

   Selects SSL version 2 as the channel encryption protocol.

   This protocol is not available if OpenSSL is compiled with the "no-
   ssl2" option.

   警告:

     SSL version 2 is insecure.  Its use is highly discouraged.

   バージョン 3.6 で非推奨: OpenSSL has removed support for SSLv2.

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+ のみで利用可能です。

   バージョン 3.4 で追加.

   バージョン 3.6 で非推奨: OpenSSL has deprecated all version
   specific protocols.

ssl.PROTOCOL_TLSv1_2

   チャンネル暗号化プロトコルとしてTLSバージョン 1.2 を選択します。
   openssl version 1.0.1+ のみで利用可能です。

   バージョン 3.4 で追加.

   バージョン 3.6 で非推奨: OpenSSL has deprecated all version
   specific protocols.

ssl.OP_ALL

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

   バージョン 3.2 で追加.

ssl.OP_NO_SSLv2

   SSLv2 接続が行われないようにします。このオプションは "PROTOCOL_TLS"
   と組み合わされている場合にのみ適用されます。ピアがプロトコルバージ
   ョンとして SSLv2 を選択しないようにします。

   バージョン 3.2 で追加.

   バージョン 3.6 で非推奨: SSLv2 は非推奨です

ssl.OP_NO_SSLv3

   SSLv3 接続が行われないようにします。このオプションは "PROTOCOL_TLS"
   と組み合わされている場合にのみ適用されます。ピアがプロトコルバージ
   ョンとして SSLv3 を選択しないようにします。

   バージョン 3.2 で追加.

   バージョン 3.6 で非推奨: SSLv3 は非推奨です

ssl.OP_NO_TLSv1

   TLSv1 接続が行われないようにします。このオプションは "PROTOCOL_TLS"
   と組み合わされている場合にのみ適用されます。ピアがプロトコルバージ
   ョンとして TLSv1 を選択しないようにします。

   バージョン 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 以降でのみ利用できます。

   バージョン 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 以降でのみ利用できます。

   バージョン 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*.

   バージョン 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 以降のみで使用できます。

   バージョン 3.7 で追加.

ssl.OP_CIPHER_SERVER_PREFERENCE

   暗号の優先順位として、クライアントのものではなくサーバのものを使い
   ます。このオプションはクライアントソケットと SSLv2 のサーバソケット
   では効果はありません。

   バージョン 3.3 で追加.

ssl.OP_SINGLE_DH_USE

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

   バージョン 3.3 で追加.

ssl.OP_SINGLE_ECDH_USE

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

   バージョン 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 以降のみで使用できます。

   バージョン 3.8 で追加.

ssl.OP_NO_COMPRESSION

   SSL チャネルでの圧縮を無効にします。これはアプリケーションのプロト
   コルが自身の圧縮方法をサポートする場合に有用です。

   バージョン 3.3 で追加.

class ssl.Options

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

ssl.OP_NO_TICKET

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

   バージョン 3.6 で追加.

ssl.OP_IGNORE_UNEXPECTED_EOF

   Ignore unexpected shutdown of TLS connections.

   このオプションは OpenSSL 3.0.0以降のみで使用できます。

   バージョン 3.10 で追加.

ssl.HAS_ALPN

   OpenSSL ライブラリが、組み込みで **RFC 7301** で記述されている
   *Application-Layer Protocol Negotiation* TLS 拡張をサポートしている
   かどうか。

   バージョン 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.

   バージョン 3.7 で追加.

ssl.HAS_ECDH

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

   バージョン 3.3 で追加.

ssl.HAS_SNI

   OpenSSL ライブラリが、組み込みで (**RFC 6066** で記述されている)
   *Server Name Indication* 拡張をサポートしているかどうか。

   バージョン 3.2 で追加.

ssl.HAS_NPN

   OpenSSL ライブラリが、組み込みで、Application Layer Protocol
   Negotiation で記述されている *Next Protocol Negotiation* をサポート
   しているかどうか。 true であれば、サポートしたいプロトコルを
   "SSLContext.set_npn_protocols()" メソッドで提示することができます。

   バージョン 3.3 で追加.

ssl.HAS_SSLv2

   OpenSSL ライブラリが、組み込みで SSL 2.0 プロトコルをサポートしてい
   るかどうか。

   バージョン 3.7 で追加.

ssl.HAS_SSLv3

   OpenSSL ライブラリが、組み込みで SSL 3.0 プロトコルをサポートしてい
   るかどうか。

   バージョン 3.7 で追加.

ssl.HAS_TLSv1

   OpenSSL ライブラリが、組み込みで TLS 1.0 プロトコルをサポートしてい
   るかどうか。

   バージョン 3.7 で追加.

ssl.HAS_TLSv1_1

   OpenSSL ライブラリが、組み込みで TLS 1.1 プロトコルをサポートしてい
   るかどうか。

   バージョン 3.7 で追加.

ssl.HAS_TLSv1_2

   OpenSSL ライブラリが、組み込みで TLS 1.2 プロトコルをサポートしてい
   るかどうか。

   バージョン 3.7 で追加.

ssl.HAS_TLSv1_3

   OpenSSL ライブラリが、組み込みで TLS 1.3 プロトコルをサポートしてい
   るかどうか。

   バージョン 3.7 で追加.

ssl.CHANNEL_BINDING_TYPES

   サポートされている TLS のチャネルバインディングのタイプのリスト。リ
   スト内の文字列は "SSLSocket.get_channel_binding()" の引数に渡せます
   。

   バージョン 3.3 で追加.

ssl.OPENSSL_VERSION

   インタプリタによってロードされた OpenSSL ライブラリのバージョン文字
   列:

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

   バージョン 3.2 で追加.

ssl.OPENSSL_VERSION_INFO

   OpenSSL ライブラリのバージョン情報を表す5つの整数のタプル:

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

   バージョン 3.2 で追加.

ssl.OPENSSL_VERSION_NUMBER

   1つの整数の形式の、 OpenSSL ライブラリの生のバージョン番号:

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

   バージョン 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()" でのコールバック関数の戻り値
   として使われます。

   バージョン 3.4 で追加.

class ssl.AlertDescription

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

   バージョン 3.6 で追加.

Purpose.SERVER_AUTH

   "create_default_context()" と "SSLContext.load_default_certs()" に
   渡すオプションです。この値はコンテキストが web サーバの認証に使われ
   ることを示します (ですので、クライアントサイドのソケットを作るのに
   使うことになるでしょう)。

   バージョン 3.4 で追加.

Purpose.CLIENT_AUTH

   "create_default_context()" と "SSLContext.load_default_certs()" に
   渡すオプションです。この値はコンテキストが web クライアントの認証に
   使われることを示します (ですので、サーバサイドのソケットを作るのに
   使うことになるでしょう)。

   バージョン 3.4 で追加.

class ssl.SSLErrorNumber

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

   バージョン 3.6 で追加.

class ssl.TLSVersion

   "enum.IntEnum" collection of SSL and TLS versions for
   "SSLContext.maximum_version" and "SSLContext.minimum_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 ソケット
============

class ssl.SSLSocket(socket.socket)

   SSL ソケットは socket オブジェクト の以下のメソッドを提供します:

   * "accept()"

   * "bind()"

   * "close()"

   * "connect()"

   * "detach()"

   * "fileno()"

   * "getpeername()", "getsockname()"

   * "getsockopt()", "setsockopt()"

   * "gettimeout()", "settimeout()", "setblocking()"

   * "listen()"

   * "makefile()"

   * "recv()", "recv_into()" (but passing a non-zero "flags" argument
     is not allowed)

   * "send()", "sendall()" (with the same limitation)

   * "sendfile()" (but "os.sendfile" will be used for plain-text
     sockets only, else "send()" will be used)

   * "shutdown()"

   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 to 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(buf)

   *buf* を SSL ソケットに書き込み、書き込んだバイト数を返します。
   *buf* 引数はバッファインターフェイスをサポートするオブジェクトでな
   ければなりません。

   ソケットが non-blocking で書き込みがブロックすると、
   "SSLWantReadError" もしくは "SSLWantWriteError" が送出されます。

   再ネゴシエーションがいつでも可能なので、 "write()"  の呼び出しは読
   み出し操作も引き起こしえます。

   バージョン 3.5 で変更: ソケットのタイムアウトは、バイトが送受信され
   るたびにリセットされなくなりました。ソケットのタイムアウトは、*buf*
   を書き込むのにかかる最大合計時間になりました。

   バージョン 3.6 で非推奨: "write()" の代わりに "send()" を使用してく
   ださい。

注釈:

  "read()", "write()" メソッドは下位レベルのメソッドであり、暗号化され
  ていないアプリケーションレベルのデータを読み書きし、それを復号/暗号
  化して暗号化された書き込みレベルのデータにします。これらのメソッドは
  アクティブな SSL 接続つまり、ハンドシェイクが完了していて、
  "SSLSocket.unwrap()" が呼ばれていないことを必要とします。通常はこれ
  らのメソッドの代わりに "recv()" や "send()" のようなソケット API メ
  ソッドを使うべきです。

SSLSocket.do_handshake()

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

   バージョン 3.4 で変更: ソケットの "context" の属性 "check_hostname"
   が真の場合に、ハンドシェイクメソッドが "match_hostname()" を実行す
   るようになりました。

   バージョン 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}

   注釈:

     To validate a certificate for a particular service, you can use
     the "match_hostname()" function.

   "binary_form" 引数が "True" だった場合、証明書が渡されていればこの
   メソッドはDERエンコードされた証明書全体をバイト列として返し、接続先
   が証明書を提示しなかった場合は "None" を返します。接続先が証明書を
   提供するかどうかは SSL ソケットの役割に依存します:

   * クライアント SSL ソケットでは、認証が要求されているかどうかに関わ
     らず、サーバは常に証明書を提供します。

   * サーバ SSL ソケットでは、クライアントはサーバによって認証が要求さ
     れている場合にのみ証明書を提供します。したがって、
     ("CERT_OPTIONAL" や "CERT_REQUIRED" ではなく) "CERT_NONE" を使用
     した場合 "getpeercert()" は "None" を返します。

   バージョン 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.cipher()

   利用されている暗号の名前、その暗号の利用を定義しているSSLプロトコル
   のバージョン、利用されている鍵のbit長の3つの値を含むタプルを返しま
   す。もし接続が確立されていない場合、 "None" を返します。

SSLSocket.shared_ciphers()

   クライアントとサーバーの両方で利用できる暗号方式のリストを返します
   。返されるリストの各要素は 3つの値を含むタプルで、その値はそれぞれ
   、暗号方式の名前、その暗号の利用を定義している SSL プロトコルのバー
   ジョン、暗号で使用される秘密鍵のビット長です。接続が確立されていな
   いか、ソケットがクライアントソケットである場合、"shared_ciphers()"
   は "None" を返します。

   バージョン 3.5 で追加.

SSLSocket.compression()

   使われている圧縮アルゴリズムを文字列で返します。接続が圧縮されてい
   なければ "None" を返します。

   上位レベルのプロトコルが自身で圧縮メカニズムをサポートする場合、SSL
   レベルでの圧縮を "OP_NO_COMPRESSION" を使って無効にできます。

   バージョン 3.3 で追加.

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

   現在の接続におけるチャネルバインディングのデータを取得します。未接
   続あるいはハンドシェイクが完了していなければ "None" を返します。

   *cb_type* パラメータにより、望みのチャネルバインディングのタイプを
   選択できます。チャネルバインディングのタイプの妥当なものは
   "CHANNEL_BINDING_TYPES" でリストされています。現在のところは **RFC
   5929** で定義されている 'tls-unique' のみがサポートされています。未
   サポートのチャネルバインディングのタイプが要求された場合、
   "ValueError" を送出します。

   バージョン 3.3 で追加.

SSLSocket.selected_alpn_protocol()

   TLS ハンドシェイクで選択されたプロトコルを返します。
   "SSLContext.set_alpn_protocols()" が呼ばれていない場合、相手側が
   ALPN をサポートしていない場合、クライアントが提案したプロトコルのど
   れもソケットがサポートしない場合、あるいはハンドシェイクがまだ行わ
   れていない場合には、 "None" が返されます。

   バージョン 3.5 で追加.

SSLSocket.selected_npn_protocol()

   TLS/SSL ハンドシェイクで選択された上位レベルのプロトコルを返します
   。 "SSLContext.set_npn_protocols()" が呼ばれていない場合、相手側が
   NPN をサポートしていない場合、あるいはハンドシェイクがまだ行われて
   いない場合には、 "None" が返されます。

   バージョン 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".

   バージョン 3.8 で追加.

SSLSocket.version()

   コネクションによって実際にネゴシエイトされた SSL プロトコルバージョ
   ンを文字列で、または、セキュアなコネクションが確立していなければ
   "None" を返します。これを書いている時点では、 ""SSLv2"", ""SSLv3"",
   ""TLSv1"", ""TLSv1.1"", ""TLSv1.2"" などが返ります。最新の OpenSSL
   はもっと色々な値を定義しているかもしれません。

   バージョン 3.5 で追加.

SSLSocket.pending()

   接続において既に復号済みで読み出し可能で保留になっているバイト列の
   数を返します。

SSLSocket.context

   The "SSLContext" object this SSL socket is tied to.  If the SSL
   socket was created using the deprecated "wrap_socket()" function
   (rather than "SSLContext.wrap_socket()"), this is a custom context
   object created for this SSL socket.

   バージョン 3.2 で追加.

SSLSocket.server_side

   サーバサイドのソケットに対して "True" 、クライアントサイドのソケッ
   トに対して "False" となる真偽値です。

   バージョン 3.2 で追加.

SSLSocket.server_hostname

   サーバのホスト名: "str" 型、またはサーバサイドのソケットの場合とコ
   ンストラクタで hostname が指定されなかった場合は "None"

   バージョン 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()" が呼ばれる前に設定して、セッションを再利用できます
   。

   バージョン 3.6 で追加.

SSLSocket.session_reused

   バージョン 3.6 で追加.


SSL コンテキスト
================

バージョン 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         |
   +--------------------------+--------------+--------------+---------------+-----------+-------------+-------------+

   -[ 脚注 ]-

   [1] "SSLContext" では、デフォルトで "OP_NO_SSLv2" によりSSLv2 が無
       効になっています。

   [2] "SSLContext" では、デフォルトで "OP_NO_SSLv3" により SSLv3 が無
       効になっています。

   [3] TLS 1.3 protocol will be available with "PROTOCOL_TLS" in
       OpenSSL >= 1.1.1. There is no dedicated PROTOCOL constant for
       just TLS 1.3.

   参考: "create_default_context()" は "ssl" モジュールに、目的に合ったセ
       キュリティ設定を選ばせます。

   バージョン 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" (except for "PROTOCOL_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 (except for "PROTOCOL_SSLv2").

   バージョン 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" オブジェクトは以下のメソッドと属性を持っています:

SSLContext.cert_store_stats()

   ロードされた X.509 証明書の数、CA 証明書で活性の X.509 証明書の数、
   証明書失効リストの数、についての統計情報を辞書として取得します。

   一つの CA と他の一つの証明書を持ったコンテキストでの例です:

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

   バージョン 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.

   バージョン 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 ディレクトリ内の証明書は一度でも使われない限りはロードされ
     ません。

   バージョン 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'}]

   バージョン 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.

   注釈:

     接続時に SSL ソケットの "SSLSocket.cipher()" メソッドが、現在選択
     されているその暗号を使います。TLS 1.3 cipher suites cannot be
     disabled with "set_ciphers()".

SSLContext.set_alpn_protocols(protocols)

   SSL/TLS ハンドシェイク時にソケットが提示すべきプロトコルを指定しま
   す。 "['http/1.1', 'spdy/2']" のような推奨順に並べた ASCII 文字列の
   リストでなければなりません。プロトコルの選択は **RFC 7301** に従い
   ハンドシェイク中に行われます。ハンドシェイクが正常に終了した後、
   "SSLSocket.selected_alpn_protocol()" メソッドは合意されたプロトコル
   を返します。

   このメソッドは "HAS_ALPN" が "False" の場合 "NotImplementedError"
   を送出します。

   バージョン 3.5 で追加.

SSLContext.set_npn_protocols(protocols)

   SSL/TLS ハンドシェイク時にソケットが提示すべきプロトコルを指定しま
   す。 "['http/1.1', 'spdy/2']" のような推奨順に並べた文字列のリスト
   でなければなりません。プロトコルの選択は Application Layer Protocol
   Negotiation に従いハンドシェイク中に行われます。ハンドシェイクが正
   常に終了した後、 "SSLSocket.selected_alpn_protocol()" メソッドは合
   意されたプロトコルを返します。

   このメソッドは "HAS_NPN" が "False" の場合 "NotImplementedError" を
   送出します。

   バージョン 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" オブジェクトに変更することです。

   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.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" を送出します。

   バージョン 3.7 で追加.

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 an decoding error on the server name, the TLS
   connection will terminate with an
   "ALERT_DESCRIPTION_INTERNAL_ERROR" fatal TLS alert message to the
   client.

   バージョン 3.4 で追加.

SSLContext.load_dh_params(dhfile)

   ディフィー・ヘルマン(DH)鍵交換のための鍵生成パラメータをロードしま
   す。DH 鍵交換を用いることは、(サーバ、クライアントともに)計算機リソ
   ースに高い処理負荷をかけますがセキュリティを向上させます。 *dhfile*
   パラメータは PEM フォーマットの DH パラメータを含んだファイルへのパ
   スでなければなりません。

   この設定はクライアントソケットには適用されません。さらにセキュリテ
   ィを改善するのに "OP_SINGLE_DH_USE" オプションも利用できます。

   バージョン 3.3 で追加.

SSLContext.set_ecdh_curve(curve_name)

   楕円曲線ディフィー・ヘルマン(ECDH)鍵交換の曲線名を指定します。ECDH
   はもとの DH に較べて、ほぼ間違いなく同程度に安全である一方で、顕著
   に高速です。 *curve_name* パラメータは既知の楕円曲線を表す文字列で
   なければなりません。例えば "prime256v1" が広くサポートされている曲
   線です。

   この設定はクライアントソケットには適用されません。さらにセキュリテ
   ィを改善するのに "OP_SINGLE_ECDH_USE" オプションも利用できます。

   このメソッドは "HAS_ECDH" が "False" の場合は利用できません。

   バージョン 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 overridden on instance of class
   in order to return a custom subclass of "SSLSocket".

   バージョン 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.

   *server_side*、 *server_hostname* 、 *session* 引数は、
   "SSLContext.wrap_socket()" での意味と同じ意味を持ちます。

   バージョン 3.6 で変更: *session* 引数が追加されました。

   バージョン 3.7 で変更: The method returns an instance of
   "SSLContext.sslobject_class" instead of hard-coded "SSLObject".

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".

   バージョン 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))

   バージョン 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.

   バージョン 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
   combination. 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.

   バージョン 3.7 で追加.

SSLContext.minimum_version

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

   バージョン 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.

   バージョン 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.

   バージョン 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).

   バージョン 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.

   バージョン 3.10 で追加.

SSLContext.verify_flags

   証明書の検証操作のためのフラグです。 "VERIFY_CRL_CHECK_LEAF" などの
   フラグをビット OR 演算でセットできます。デフォルトでは OpenSSL は証
   明書失効リスト (CRLs) を必要としませんし検証にも使いません。

   バージョン 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>


証明書
======

証明書を大まかに説明すると、公開鍵/秘密鍵システムの一種です。このシス
テムでは、各 *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()" and "wrap_socket()" 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 API. It polls for events using the "selectors" module
  and handles "SSLWantWriteError", "SSLWantReadError" and
  "BlockingIOError" exceptions. It runs the SSL handshake
  asynchronously as well.


メモリ BIO サポート
===================

バージョン 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 は、データを反対向
   きに渡すために使用されます。

   次のメソッドがサポートされています:

   * "context"

   * "server_side"

   * "server_hostname"

   * "session"

   * "session_reused"

   * "read()"

   * "write()"

   * "getpeercert()"

   * "selected_alpn_protocol()"

   * "selected_npn_protocol()"

   * "cipher()"

   * "shared_ciphers()"

   * "compression()"

   * "pending()"

   * "do_handshake()"

   * "verify_client_post_handshake()"

   * "unwrap()"

   * "get_channel_binding()"

   * "version()"

   "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" を送出します。

   * There is no module-level "wrap_bio()" call like there is for
     "wrap_socket()". An "SSLObject" is always created via an
     "SSLContext".

   バージョン 3.7 で変更: "SSLObject" instances must to 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 セッション
==============

バージョン 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 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; in this case, the "match_hostname()" function can be used.
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_3
   >>> client_context.maximum_version = ssl.TLSVersion.TLSv1_3

The SSL context created above will only allow TLSv1.3 and later (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()", "RAND_bytes()" or
"RAND_pseudo_bytes()" is sufficient.


TLS 1.3
=======

バージョン 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.

参考:

  "socket.socket" クラス
     下位レイヤーの "socket" クラスのドキュメント

  SSL/TLS Strong Encryption: An Introduction
     Apache HTTPサーバのドキュメンテーションのイントロ

  **RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part
  II: Certificate-Based Key Management**
     Steve Kent

  **RFC 4086: Randomness Requirements for Security**
     Donald E., Jeffrey I. Schiller

  **RFC 5280: Internet X.509 Public Key Infrastructure Certificate and
  Certificate Revocation List (CRL) Profile**
     D. Cooper

  **RFC 5246: The Transport Layer Security (TLS) Protocol Version
  1.2**
     T. Dierks et. al.

  **RFC 6066: Transport Layer Security (TLS) Extensions**
     D. Eastlake

  IANA TLS: Transport Layer Security (TLS) Parameters
     IANA

  **RFC 7525: Recommendations for Secure Use of Transport Layer
  Security (TLS) and Datagram Transport Layer Security (DTLS)**
     IETF

  Mozilla's Server Side TLS recommendations
     Mozilla
