Skip to content
Projeler
Gruplar
Parçacıklar
Yardım
Yükleniyor...
Oturum aç / Kaydol
Gezinmeyi değiştir
C
cpython
Proje
Proje
Ayrıntılar
Etkinlik
Cycle Analytics
Depo (repository)
Depo (repository)
Dosyalar
Kayıtlar (commit)
Dallar (branch)
Etiketler
Katkıda bulunanlar
Grafik
Karşılaştır
Grafikler
Konular (issue)
0
Konular (issue)
0
Liste
Pano
Etiketler
Kilometre Taşları
Birleştirme (merge) Talepleri
0
Birleştirme (merge) Talepleri
0
CI / CD
CI / CD
İş akışları (pipeline)
İşler
Zamanlamalar
Grafikler
Paketler
Paketler
Wiki
Wiki
Parçacıklar
Parçacıklar
Üyeler
Üyeler
Collapse sidebar
Close sidebar
Etkinlik
Grafik
Grafikler
Yeni bir konu (issue) oluştur
İşler
Kayıtlar (commit)
Konu (issue) Panoları
Kenar çubuğunu aç
Batuhan Osman TASKAYA
cpython
Commits
a50d20a5
Kaydet (Commit)
a50d20a5
authored
Eyl 16, 2009
tarafından
Georg Brandl
Dosyalara gözat
Seçenekler
Dosyalara Gözat
İndir
Eposta Yamaları
Sade Fark
Rewrap long lines.
üst
2e85f503
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
246 additions
and
257 deletions
+246
-257
ssl.rst
Doc/library/ssl.rst
+246
-257
No files found.
Doc/library/ssl.rst
Dosyayı görüntüle @
a50d20a5
:mod:`ssl` --- SSL wrapper for socket objects
:mod:`ssl` --- SSL wrapper for socket objects
=============================================
=======================
=============================================
.. module:: ssl
.. module:: ssl
:synopsis: SSL wrapper for socket objects
:synopsis: SSL wrapper for socket objects
...
@@ -16,32 +15,29 @@
...
@@ -16,32 +15,29 @@
.. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer
.. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer
This module provides access to Transport Layer Security (often known
This module provides access to Transport Layer Security (often known as "Secure
as "Secure Sockets Layer") encryption and peer authentication
Sockets Layer") encryption and peer authentication facilities for network
facilities for network sockets, both client-side and server-side.
sockets, both client-side and server-side. This module uses the OpenSSL
This module uses the OpenSSL library. It is available on all modern
library. It is available on all modern Unix systems, Windows, Mac OS X, and
Unix systems, Windows, Mac OS X, and probably additional
probably additional platforms, as long as OpenSSL is installed on that platform.
platforms, as long as OpenSSL is installed on that platform.
.. note::
.. note::
Some behavior may be platform dependent, since calls are made to the
operating
Some behavior may be platform dependent, since calls are made to the
system socket APIs. The installed version of OpenSSL may also cause
operating system socket APIs. The installed version of OpenSSL may also
variations in behavior.
cause
variations in behavior.
This section documents the objects and functions in the ``ssl`` module;
This section documents the objects and functions in the ``ssl`` module; for more
for more general information about TLS, SSL, and certificates, the
general information about TLS, SSL, and certificates, the reader is referred to
reader is referred to the documents in the "See Also" section at
the documents in the "See Also" section at the bottom.
the bottom.
This module provides a class, :class:`ssl.SSLSocket`, which is
This module provides a class, :class:`ssl.SSLSocket`, which is derived from the
derived from the :class:`socket.socket` type, and provides
:class:`socket.socket` type, and provides a socket-like wrapper that also
a socket-like wrapper that also encrypts and decrypts the data
encrypts and decrypts the data going over the socket with SSL. It supports
going over the socket with SSL. It supports additional
additional :meth:`read` and :meth:`write` methods, along with a method,
:meth:`read` and :meth:`write` methods, along with a method, :meth:`getpeercert`,
:meth:`getpeercert`, to retrieve the certificate of the other side of the
to retrieve the certificate of the other side of the connection, and
connection, and a method, :meth:`cipher`, to retrieve the cipher being used for
a method, :meth:`cipher`, to retrieve the cipher being used for the
the secure connection.
secure connection.
Functions, Constants, and Exceptions
Functions, Constants, and Exceptions
------------------------------------
------------------------------------
...
@@ -49,31 +45,33 @@ Functions, Constants, and Exceptions
...
@@ -49,31 +45,33 @@ Functions, Constants, and Exceptions
.. exception:: SSLError
.. exception:: SSLError
Raised to signal an error from the underlying SSL implementation. This
Raised to signal an error from the underlying SSL implementation. This
signifies some problem in the higher-level
signifies some problem in the higher-level
encryption and authentication
encryption and authentication layer that's superimposed on the underlying
layer that's superimposed on the underlying network connection. This error
network connection. This error is a subtype of :exc:`socket.error`, which
is a subtype of :exc:`socket.error`, which in turn is a subtype of
in turn is a subtype of
:exc:`IOError`.
:exc:`IOError`.
.. function:: wrap_socket (sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version={see docs}, ca_certs=None, do_handshake_on_connect=True, suppress_ragged_eofs=True)
.. function:: wrap_socket (sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version={see docs}, ca_certs=None, do_handshake_on_connect=True, suppress_ragged_eofs=True)
Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance of :class:`ssl.SSLSocket`, a subtype
Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance
of :class:`socket.socket`, which wraps the underlying socket in an SSL context.
of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps
For client-side sockets, the context construction is lazy; if the underlying socket isn't
the underlying socket in an SSL context. For client-side sockets, the
connected yet, the context construction will be performed after :meth:`connect` is called
context construction is lazy; if the underlying socket isn't connected yet,
on the socket. For server-side sockets, if the socket has no remote peer, it is assumed
the context construction will be performed after :meth:`connect` is called on
to be a listening socket, and the server-side SSL wrapping is automatically performed
the socket. For server-side sockets, if the socket has no remote peer, it is
on client connections accepted via the :meth:`accept` method. :func:`wrap_socket` may
assumed to be a listening socket, and the server-side SSL wrapping is
raise :exc:`SSLError`.
automatically performed on client connections accepted via the :meth:`accept`
method. :func:`wrap_socket` may raise :exc:`SSLError`.
The ``keyfile`` and ``certfile`` parameters specify optional files which contain a certificate
to be used to identify the local side of the connection. See the discussion of :ref:`ssl-certificates`
The ``keyfile`` and ``certfile`` parameters specify optional files which
for more information on how the certificate is stored in the ``certfile``.
contain a certificate to be used to identify the local side of the
connection. See the discussion of :ref:`ssl-certificates` for more
Often the private key is stored
information on how the certificate is stored in the ``certfile``.
in the same file as the certificate; in this case, only the ``certfile`` parameter need be
passed. If the private key is stored in a separate file, both parameters must be used.
Often the private key is stored in the same file as the certificate; in this
If the private key is stored in the ``certfile``, it should come before the first certificate
case, only the ``certfile`` parameter need be passed. If the private key is
in the certificate chain::
stored in a separate file, both parameters must be used. If the private key
is stored in the ``certfile``, it should come before the first certificate in
the certificate chain::
-----BEGIN RSA PRIVATE KEY-----
-----BEGIN RSA PRIVATE KEY-----
... (private key in base64 encoding) ...
... (private key in base64 encoding) ...
...
@@ -82,31 +80,33 @@ Functions, Constants, and Exceptions
...
@@ -82,31 +80,33 @@ Functions, Constants, and Exceptions
... (certificate in base64 PEM encoding) ...
... (certificate in base64 PEM encoding) ...
-----END CERTIFICATE-----
-----END CERTIFICATE-----
The parameter ``server_side`` is a boolean which identifies whether server-side or client-side
The parameter ``server_side`` is a boolean which identifies whether
behavior is desired from this socket.
server-side or client-side behavior is desired from this socket.
The parameter ``cert_reqs`` specifies whether a certificate is
The parameter ``cert_reqs`` specifies whether a certificate is required from
required from the other side of the connection, and whether it will
the other side of the connection, and whether it will be validated if
be validated if provided. It must be one of the three values
provided. It must be one of the three values :const:`CERT_NONE`
:const:`CERT_NONE` (certificates ignored), :const:`CERT_OPTIONAL` (not required,
(certificates ignored), :const:`CERT_OPTIONAL` (not required, but validated
but validated if provided), or :const:`CERT_REQUIRED` (required and
if provided), or :const:`CERT_REQUIRED` (required and validated). If the
validated). If the value of this parameter is not :const:`CERT_NONE`, then
value of this parameter is not :const:`CERT_NONE`, then the ``ca_certs``
the ``ca_certs`` parameter must point to a file of CA certificates.
parameter must point to a file of CA certificates.
The ``ca_certs`` file contains a set of concatenated "certification authority" certificates,
The ``ca_certs`` file contains a set of concatenated "certification
which are used to validate certificates passed from the other end of the connection.
authority" certificates, which are used to validate certificates passed from
See the discussion of :ref:`ssl-certificates` for more information about how to arrange
the other end of the connection. See the discussion of
the certificates in this file.
:ref:`ssl-certificates` for more information about how to arrange the
certificates in this file.
The parameter ``ssl_version`` specifies which version of the SSL protocol to use.
Typically, the server chooses a particular protocol version, and the client
The parameter ``ssl_version`` specifies which version of the SSL protocol to
must adapt to the server's choice. Most of the versions are not interoperable
use. Typically, the server chooses a particular protocol version, and the
with the other versions. If not specified, for client-side operation, the
client must adapt to the server's choice. Most of the versions are not
default SSL version is SSLv3; for server-side operation, SSLv23. These
interoperable with the other versions. If not specified, for client-side
version selections provide the most compatibility with other versions.
operation, the default SSL version is SSLv3; for server-side operation,
SSLv23. These version selections provide the most compatibility with other
Here's a table showing which versions in a client (down the side)
versions.
can connect to which versions in a server (along the top):
Here's a table showing which versions in a client (down the side) can connect
to which versions in a server (along the top):
.. table::
.. table::
...
@@ -119,51 +119,52 @@ Functions, Constants, and Exceptions
...
@@ -119,51 +119,52 @@ Functions, Constants, and Exceptions
*TLSv1* no no yes yes
*TLSv1* no no yes yes
======================== ========= ========= ========== =========
======================== ========= ========= ========== =========
In some older versions of OpenSSL (for instance, 0.9.7l on OS X 10.4),
In some older versions of OpenSSL (for instance, 0.9.7l on OS X 10.4),
an
an
SSLv2 client could not connect to an SSLv23 server.
SSLv2 client could not connect to an SSLv23 server.
The parameter ``do_handshake_on_connect`` specifies whether to do the SSL
The parameter ``do_handshake_on_connect`` specifies whether to do the SSL
handshake automatically after doing a :meth:`socket.connect`, or whether the
handshake automatically after doing a :meth:`socket.connect`, or whether the
application program will call it explicitly, by invoking the :meth:`SSLSocket.do_handshake`
application program will call it explicitly, by invoking the
method. Calling :meth:`SSLSocket.do_handshake` explicitly gives the program control over
:meth:`SSLSocket.do_handshake` method. Calling
the blocking behavior of the socket I/O involved in the handshake.
:meth:`SSLSocket.do_handshake` explicitly gives the program control over the
blocking behavior of the socket I/O involved in the handshake.
The parameter ``suppress_ragged_eofs`` specifies how the
:meth:`SSLSocket.read`
The parameter ``suppress_ragged_eofs`` specifies how the
method should signal unexpected EOF from the other end of the connection. If specifie
d
:meth:`SSLSocket.read` method should signal unexpected EOF from the other en
d
as :const:`True` (the default), it returns a normal EOF in response to unexpected
of the connection. If specified as :const:`True` (the default), it returns a
EOF errors raised from the underlying socket; if :const:`False`, it will raise
normal EOF in response to unexpected EOF errors raised from the underlying
the exceptions back to the caller.
socket; if :const:`False`, it will raise
the exceptions back to the caller.
.. function:: RAND_status()
.. function:: RAND_status()
Returns True if the SSL pseudo-random number generator has been
Returns True if the SSL pseudo-random number generator has been
seeded with
seeded with 'enough' randomness, and False otherwise. You can use
'enough' randomness, and False otherwise. You can use :func:`ssl.RAND_egd`
:func:`ssl.RAND_egd` and :func:`ssl.RAND_add` to increase the randomness
and :func:`ssl.RAND_add` to increase the randomness of the pseudo-random
of the pseudo-random
number generator.
number generator.
.. function:: RAND_egd(path)
.. function:: RAND_egd(path)
If you are running an entropy-gathering daemon (EGD) somewhere, and ``path``
If you are running an entropy-gathering daemon (EGD) somewhere, and ``path``
is the pathname of a socket connection open to it, this will read
is the pathname of a socket connection open to it, this will read
256 bytes
256 bytes of randomness from the socket, and add it to the SSL pseudo-random number generato
r
of randomness from the socket, and add it to the SSL pseudo-random numbe
r
to increase the security of generated secret keys. This is typically only
generator to increase the security of generated secret keys. This is
necessary on systems without better sources of randomness.
typically only
necessary on systems without better sources of randomness.
See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for
See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for
sources
sources
of entropy-gathering daemons.
of entropy-gathering daemons.
.. function:: RAND_add(bytes, entropy)
.. function:: RAND_add(bytes, entropy)
Mixes the given ``bytes`` into the SSL pseudo-random number generator.
Mixes the given ``bytes`` into the SSL pseudo-random number generator.
The
The parameter ``entropy`` (a float) is a lower bound on the entropy
parameter ``entropy`` (a float) is a lower bound on the entropy contained in
contained in string (so you can always use :const:`0.0`).
string (so you can always use :const:`0.0`). See :rfc:`1750` for more
See :rfc:`1750` for more
information on sources of entropy.
information on sources of entropy.
.. function:: cert_time_to_seconds(timestring)
.. function:: cert_time_to_seconds(timestring)
Returns a floating-point value containing a normal seconds-after-the-epoch
time
Returns a floating-point value containing a normal seconds-after-the-epoch
value, given the time-string representing the "notBefore" or "notAfter" date
time value, given the time-string representing the "notBefore" or "notAfter"
from a certificate.
date
from a certificate.
Here's an example::
Here's an example::
...
@@ -177,14 +178,13 @@ Functions, Constants, and Exceptions
...
@@ -177,14 +178,13 @@ Functions, Constants, and Exceptions
.. function:: get_server_certificate (addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None)
.. function:: get_server_certificate (addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None)
Given the address ``addr`` of an SSL-protected server, as a
Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
(*hostname*, *port-number*) pair, fetches the server's certificate,
*port-number*) pair, fetches the server's certificate, and returns it as a
and returns it as a PEM-encoded string. If ``ssl_version`` is
PEM-encoded string. If ``ssl_version`` is specified, uses that version of
specified, uses that version of the SSL protocol to attempt to
the SSL protocol to attempt to connect to the server. If ``ca_certs`` is
connect to the server. If ``ca_certs`` is specified, it should be
specified, it should be a file containing a list of root certificates, the
a file containing a list of root certificates, the same format as
same format as used for the same parameter in :func:`wrap_socket`. The call
used for the same parameter in :func:`wrap_socket`. The call will
will attempt to validate the server certificate against that set of root
attempt to validate the server certificate against that set of root
certificates, and will fail if the validation attempt fails.
certificates, and will fail if the validation attempt fails.
.. function:: DER_cert_to_PEM_cert (DER_cert_bytes)
.. function:: DER_cert_to_PEM_cert (DER_cert_bytes)
...
@@ -194,31 +194,29 @@ Functions, Constants, and Exceptions
...
@@ -194,31 +194,29 @@ Functions, Constants, and Exceptions
.. function:: PEM_cert_to_DER_cert (PEM_cert_string)
.. function:: PEM_cert_to_DER_cert (PEM_cert_string)
Given a certificate as an ASCII PEM string, returns a DER-encoded
Given a certificate as an ASCII PEM string, returns a DER-encoded
sequence of
sequence of
bytes for that same certificate.
bytes for that same certificate.
.. data:: CERT_NONE
.. data:: CERT_NONE
Value to pass to the ``cert_reqs`` parameter to :func:`sslobject`
Value to pass to the ``cert_reqs`` parameter to :func:`sslobject`
when no
when no certificates will be required or validated from the other
certificates will be required or validated from the other side of the socket
side of the socket
connection.
connection.
.. data:: CERT_OPTIONAL
.. data:: CERT_OPTIONAL
Value to pass to the ``cert_reqs`` parameter to :func:`sslobject`
Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when no
when no certificates will be required from the other side of the
certificates will be required from the other side of the socket connection,
socket connection, but if they are provided, will be validated.
but if they are provided, will be validated. Note that use of this setting
Note that use of this setting requires a valid certificate
requires a valid certificate validation file also be passed as a value of the
validation file also be passed as a value of the ``ca_certs``
``ca_certs`` parameter.
parameter.
.. data:: CERT_REQUIRED
.. data:: CERT_REQUIRED
Value to pass to the ``cert_reqs`` parameter to :func:`sslobject`
Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when
when certificates will be required from the other side of the
certificates will be required from the other side of the socket connection.
socket connection. Note that use of this setting requires a valid certificate
Note that use of this setting requires a valid certificate validation file
validation file also be passed as a value of the ``ca_certs``
also be passed as a value of the ``ca_certs`` parameter.
parameter.
.. data:: PROTOCOL_SSLv2
.. data:: PROTOCOL_SSLv2
...
@@ -226,22 +224,21 @@ Functions, Constants, and Exceptions
...
@@ -226,22 +224,21 @@ Functions, Constants, and Exceptions
.. data:: PROTOCOL_SSLv23
.. data:: PROTOCOL_SSLv23
Selects SSL version 2 or 3 as the channel encryption protocol.
Selects SSL version 2 or 3 as the channel encryption protocol. This is a
This is a setting to use with servers for maximum compatibility
setting to use with servers for maximum compatibility with the other end of
with the other end of an SSL connection, but it may cause the
an SSL connection, but it may cause the specific ciphers chosen for the
specific ciphers chosen for the encryption to be of fairly low
encryption to be of fairly low quality.
quality.
.. data:: PROTOCOL_SSLv3
.. data:: PROTOCOL_SSLv3
Selects SSL version 3 as the channel encryption protocol.
Selects SSL version 3 as the channel encryption protocol.
For clients, this
For clients, this
is the maximally compatible SSL variant.
is the maximally compatible SSL variant.
.. data:: PROTOCOL_TLSv1
.. data:: PROTOCOL_TLSv1
Selects TLS version 1 as the channel encryption protocol. This is
Selects TLS version 1 as the channel encryption protocol. This is
the most
the most modern version, and probably the best choice for maximum
modern version, and probably the best choice for maximum protection, if both
protection, if both
sides can speak it.
sides can speak it.
SSLSocket Objects
SSLSocket Objects
...
@@ -253,30 +250,28 @@ SSLSocket Objects
...
@@ -253,30 +250,28 @@ SSLSocket Objects
.. method:: SSLSocket.write(data)
.. method:: SSLSocket.write(data)
Writes the ``data`` to the other side of the connection, using the
Writes the ``data`` to the other side of the connection, using the
SSL
SSL
channel to encrypt. Returns the number of bytes written.
channel to encrypt. Returns the number of bytes written.
.. method:: SSLSocket.getpeercert(binary_form=False)
.. method:: SSLSocket.getpeercert(binary_form=False)
If there is no certificate for the peer on the other end of the
If there is no certificate for the peer on the other end of the connection,
connection, returns ``None``.
returns ``None``.
If the parameter ``binary_form`` is :const:`False`, and a
If the parameter ``binary_form`` is :const:`False`, and a certificate was
certificate was received from the peer, this method returns a
received from the peer, this method returns a :class:`dict` instance. If the
:class:`dict` instance. If the certificate was not validated, the
certificate was not validated, the dict is empty. If the certificate was
dict is empty. If the certificate was validated, it returns a dict
validated, it returns a dict with the keys ``subject`` (the principal for
with the keys ``subject`` (the principal for which the certificate
which the certificate was issued), and ``notAfter`` (the time after which the
was issued), and ``notAfter`` (the time after which the certificate
certificate should not be trusted). The certificate was already validated,
should not be trusted). The certificate was already validated, so
so the ``notBefore`` and ``issuer`` fields are not returned. If a
the ``notBefore`` and ``issuer`` fields are not returned. If a
certificate contains an instance of the *Subject Alternative Name* extension
certificate contains an instance of the *Subject Alternative Name*
(see :rfc:`3280`), there will also be a ``subjectAltName`` key in the
extension (see :rfc:`3280`), there will also be a
dictionary.
``subjectAltName`` key in the dictionary.
The "subject" field is a tuple containing the sequence of relative
The "subject" field is a tuple containing the sequence of relative
distinguished names (RDNs) given in the certificate's data
distinguished names (RDNs) given in the certificate's data structure for the
structure for the principal, and each RDN is a sequence of
principal, and each RDN is a sequence of name-value pairs::
name-value pairs::
{'notAfter': 'Feb 16 16:54:50 2013 GMT',
{'notAfter': 'Feb 16 16:54:50 2013 GMT',
'subject': ((('countryName', u'US'),),
'subject': ((('countryName', u'US'),),
...
@@ -286,29 +281,27 @@ SSLSocket Objects
...
@@ -286,29 +281,27 @@ SSLSocket Objects
(('organizationalUnitName', u'SSL'),),
(('organizationalUnitName', u'SSL'),),
(('commonName', u'somemachine.python.org'),))}
(('commonName', u'somemachine.python.org'),))}
If the ``binary_form`` parameter is :const:`True`, and a
If the ``binary_form`` parameter is :const:`True`, and a certificate was
certificate was provided, this method returns the DER-encoded form
provided, this method returns the DER-encoded form of the entire certificate
of the entire certificate as a sequence of bytes, or :const:`None` if the
as a sequence of bytes, or :const:`None` if the peer did not provide a
peer did not provide a certificate. This return
certificate. This return value is independent of validation; if validation
value is independent of validation; if validation was required
was required (:const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`), it will have
(:const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`), it will have
been validated, but if :const:`CERT_NONE` was used to establish the
been validated, but if :const:`CERT_NONE` was used to establish the
connection, the certificate, if present, will not have been validated.
connection, the certificate, if present, will not have been validated.
.. method:: SSLSocket.cipher()
.. method:: SSLSocket.cipher()
Returns a three-value tuple containing the name of the cipher being
Returns a three-value tuple containing the name of the cipher being used, the
used, the version of the SSL protocol that defines its use, and the
version of the SSL protocol that defines its use, and the number of secret
number of secret bits being used. If no connection has been
bits being used. If no connection has been established, returns ``None``.
established, returns ``None``.
.. method:: SSLSocket.do_handshake()
.. method:: SSLSocket.do_handshake()
Perform a TLS/SSL handshake. If this is used with a non-blocking socket,
Perform a TLS/SSL handshake. If this is used with a non-blocking socket,
it
it
may raise :exc:`SSLError` with an ``arg[0]`` of :const:`SSL_ERROR_WANT_READ`
may raise :exc:`SSLError` with an ``arg[0]`` of :const:`SSL_ERROR_WANT_READ`
or :const:`SSL_ERROR_WANT_WRITE`, in which case it must be called again until
it
or :const:`SSL_ERROR_WANT_WRITE`, in which case it must be called again until
completes successfully. For example, to simulate the behavior of a blocking socket,
it completes successfully. For example, to simulate the behavior of a
one might write::
blocking socket,
one might write::
while True:
while True:
try:
try:
...
@@ -324,13 +317,12 @@ SSLSocket Objects
...
@@ -324,13 +317,12 @@ SSLSocket Objects
.. method:: SSLSocket.unwrap()
.. method:: SSLSocket.unwrap()
Performs the SSL shutdown handshake, which removes the TLS layer
Performs the SSL shutdown handshake, which removes the TLS layer from the
from the underlying socket, and returns the underlying socket
underlying socket, and returns the underlying socket object. This can be
object. This can be used to go from encrypted operation over a
used to go from encrypted operation over a connection to unencrypted. The
connection to unencrypted. The socket instance returned should always be
socket instance returned should always be used for further communication with
used for further communication with the other side of the
the other side of the connection, rather than the original socket instance
connection, rather than the original socket instance (which may
(which may not function properly after the unwrap).
not function properly after the unwrap).
.. index:: single: certificates
.. index:: single: certificates
...
@@ -341,57 +333,54 @@ SSLSocket Objects
...
@@ -341,57 +333,54 @@ SSLSocket Objects
Certificates
Certificates
------------
------------
Certificates in general are part of a public-key / private-key system. In this system, each *principal*,
Certificates in general are part of a public-key / private-key system. In this
(which may be a machine, or a person, or an organization) is assigned a unique two-part encryption key.
system, each *principal*, (which may be a machine, or a person, or an
One part of the key is public, and is called the *public key*; the other part is kept secret, and is called
organization) is assigned a unique two-part encryption key. One part of the key
the *private key*. The two parts are related, in that if you encrypt a message with one of the parts, you can
is public, and is called the *public key*; the other part is kept secret, and is
decrypt it with the other part, and **only** with the other part.
called the *private key*. The two parts are related, in that if you encrypt a
message with one of the parts, you can decrypt it with the other part, and
A certificate contains information about two principals. It contains
**only** with the other part.
the name of a *subject*, and the subject's public key. It also
contains a statement by a second principal, the *issuer*, that the
A certificate contains information about two principals. It contains the name
subject is who he claims to be, and that this is indeed the subject's
of a *subject*, and the subject's public key. It also contains a statement by a
public key. The issuer's statement is signed with the issuer's
second principal, the *issuer*, that the subject is who he claims to be, and
private key, which only the issuer knows. However, anyone can verify
that this is indeed the subject's public key. The issuer's statement is signed
the issuer's statement by finding the issuer's public key, decrypting
with the issuer's private key, which only the issuer knows. However, anyone can
the statement with it, and comparing it to the other information in
verify the issuer's statement by finding the issuer's public key, decrypting the
the certificate. The certificate also contains information about the
statement with it, and comparing it to the other information in the certificate.
time period over which it is valid. This is expressed as two fields,
The certificate also contains information about the time period over which it is
called "notBefore" and "notAfter".
valid. This is expressed as two fields, called "notBefore" and "notAfter".
In the Python use of certificates, a client or server
In the Python use of certificates, a client or server can use a certificate to
can use a certificate to prove who they are. The other
prove who they are. The other side of a network connection can also be required
side of a network connection can also be required to produce a certificate,
to produce a certificate, and that certificate can be validated to the
and that certificate can be validated to the satisfaction
satisfaction of the client or server that requires such validation. The
of the client or server that requires such validation.
connection attempt can be set to raise an exception if the validation fails.
The connection attempt can be set to raise an exception if
Validation is done automatically, by the underlying OpenSSL framework; the
the validation fails. Validation is done
application need not concern itself with its mechanics. But the application
automatically, by the underlying OpenSSL framework; the
does usually need to provide sets of certificates to allow this process to take
application need not concern itself with its mechanics.
place.
But the application does usually need to provide
sets of certificates to allow this process to take place.
Python uses files to contain certificates. They should be formatted as "PEM"
(see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line
Python uses files to contain certificates. They should be formatted
and a footer line::
as "PEM" (see :rfc:`1422`), which is a base-64 encoded form wrapped
with a header line and a footer line::
-----BEGIN CERTIFICATE-----
-----BEGIN CERTIFICATE-----
... (certificate in base64 PEM encoding) ...
... (certificate in base64 PEM encoding) ...
-----END CERTIFICATE-----
-----END CERTIFICATE-----
The Python files which contain certificates can contain a sequence
The Python files which contain certificates can contain a sequence of
of certificates, sometimes called a *certificate chain*. This chain
certificates, sometimes called a *certificate chain*. This chain should start
should start with the specific certificate for the principal who "is"
with the specific certificate for the principal who "is" the client or server,
the client or server, and then the certificate for the issuer of that
and then the certificate for the issuer of that certificate, and then the
certificate, and then the certificate for the issuer of *that* certificate,
certificate for the issuer of *that* certificate, and so on up the chain till
and so on up the chain till you get to a certificate which is *self-signed*,
you get to a certificate which is *self-signed*, that is, a certificate which
that is, a certificate which has the same subject and issuer,
has the same subject and issuer, sometimes called a *root certificate*. The
sometimes called a *root certificate*. The certificates should just
certificates should just be concatenated together in the certificate file. For
be concatenated together in the certificate file. For example, suppose
example, suppose we had a three certificate chain, from our server certificate
we had a three certificate chain, from our server certificate to the
to the certificate of the certification authority that signed our server
certificate of the certification authority that signed our server certificate,
certificate, to the root certificate of the agency which issued the
to the root certificate of the agency which issued the certification authority's
certification authority's certificate::
certificate::
-----BEGIN CERTIFICATE-----
-----BEGIN CERTIFICATE-----
... (certificate for your server)...
... (certificate for your server)...
...
@@ -405,33 +394,30 @@ certificate::
...
@@ -405,33 +394,30 @@ certificate::
If you are going to require validation of the other side of the connection's
If you are going to require validation of the other side of the connection's
certificate, you need to provide a "CA certs" file, filled with the certificate
certificate, you need to provide a "CA certs" file, filled with the certificate
chains for each issuer you are willing to trust. Again, this file just
chains for each issuer you are willing to trust. Again, this file just
contains
contains these chains concatenated together. For validation, Python will
these chains concatenated together. For validation, Python will use the first
use the first
chain it finds in the file which matches.
chain it finds in the file which matches.
Some "standard" root certificates are available from various certification
Some "standard" root certificates are available from various certification
authorities:
authorities: `CACert.org <http://www.cacert.org/index.php?id=3>`_, `Thawte
`CACert.org <http://www.cacert.org/index.php?id=3>`_,
<http://www.thawte.com/roots/>`_, `Verisign
`Thawte <http://www.thawte.com/roots/>`_,
<http://www.verisign.com/support/roots.html>`_, `Positive SSL
`Verisign <http://www.verisign.com/support/roots.html>`_,
<http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_
`Positive SSL <http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_ (used by python.org),
(used by python.org), `Equifax and GeoTrust
`Equifax and GeoTrust <http://www.geotrust.com/resources/root_certificates/index.asp>`_.
<http://www.geotrust.com/resources/root_certificates/index.asp>`_.
In general, if you are using
In general, if you are using SSL3 or TLS1, you don't need to put the full chain
SSL3 or TLS1, you don't need to put the full chain in your "CA certs" file;
in your "CA certs" file; you only need the root certificates, and the remote
you only need the root certificates, and the remote peer is supposed to
peer is supposed to furnish the other certificates necessary to chain from its
furnish the other certificates necessary to chain from its certificate to
certificate to a root certificate. See :rfc:`4158` for more discussion of the
a root certificate.
way in which certification chains can be built.
See :rfc:`4158` for more discussion of the way in which
certification chains can be built.
If you are going to create a server that provides SSL-encrypted connection
services, you will need to acquire a certificate for that service. There are
If you are going to create a server that provides SSL-encrypted
many ways of acquiring appropriate certificates, such as buying one from a
connection services, you will need to acquire a certificate for that
certification authority. Another common practice is to generate a self-signed
service. There are many ways of acquiring appropriate certificates,
certificate. The simplest way to do this is with the OpenSSL package, using
such as buying one from a certification authority. Another common
something like the following::
practice is to generate a self-signed certificate. The simplest
way to do this is with the OpenSSL package, using something like
the following::
% openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
% openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
Generating a 1024 bit RSA private key
Generating a 1024 bit RSA private key
...
@@ -455,9 +441,9 @@ the following::
...
@@ -455,9 +441,9 @@ the following::
Email Address []:ops@myserver.mygroup.myorganization.com
Email Address []:ops@myserver.mygroup.myorganization.com
%
%
The disadvantage of a self-signed certificate is that it is its
The disadvantage of a self-signed certificate is that it is its
own root
own root certificate, and no one else will have it in their cache
certificate, and no one else will have it in their cache of known (and trusted)
of known (and trusted)
root certificates.
root certificates.
Examples
Examples
...
@@ -466,7 +452,8 @@ Examples
...
@@ -466,7 +452,8 @@ Examples
Testing for SSL support
Testing for SSL support
^^^^^^^^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^^^^^^^^
To test for the presence of SSL support in a Python installation, user code should use the following idiom::
To test for the presence of SSL support in a Python installation, user code
should use the following idiom::
try:
try:
import ssl
import ssl
...
@@ -478,8 +465,8 @@ To test for the presence of SSL support in a Python installation, user code shou
...
@@ -478,8 +465,8 @@ To test for the presence of SSL support in a Python installation, user code shou
Client-side operation
Client-side operation
^^^^^^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^^^^^^
This example connects to an SSL server, prints the server's address and
certificate,
This example connects to an SSL server, prints the server's address and
sends some bytes, and reads part of the response::
certificate,
sends some bytes, and reads part of the response::
import socket, ssl, pprint
import socket, ssl, pprint
...
@@ -507,8 +494,8 @@ sends some bytes, and reads part of the response::
...
@@ -507,8 +494,8 @@ sends some bytes, and reads part of the response::
# note that closing the SSLSocket will also close the underlying socket
# note that closing the SSLSocket will also close the underlying socket
ssl_sock.close()
ssl_sock.close()
As of September 6, 2007, the certificate printed by this program
As of September 6, 2007, the certificate printed by this program
looked like
looked like
this::
this::
{'notAfter': 'May 8 23:59:59 2009 GMT',
{'notAfter': 'May 8 23:59:59 2009 GMT',
'subject': ((('serialNumber', u'2497886'),),
'subject': ((('serialNumber', u'2497886'),),
...
@@ -531,9 +518,9 @@ which is a fairly poorly-formed ``subject`` field.
...
@@ -531,9 +518,9 @@ which is a fairly poorly-formed ``subject`` field.
Server-side operation
Server-side operation
^^^^^^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^^^^^^
For server operation, typically you'd need to have a server certificate, and
private key, each in a file.
For server operation, typically you'd need to have a server certificate, and
You'd open a socket, bind it to a port, call :meth:`listen` on it, then start waiting for clients
private key, each in a file. You'd open a socket, bind it to a port, call
to connect::
:meth:`listen` on it, then start waiting for clients
to connect::
import socket, ssl
import socket, ssl
...
@@ -541,8 +528,9 @@ to connect::
...
@@ -541,8 +528,9 @@ to connect::
bindsocket.bind(('myaddr.mydomain.com', 10023))
bindsocket.bind(('myaddr.mydomain.com', 10023))
bindsocket.listen(5)
bindsocket.listen(5)
When one did, you'd call :meth:`accept` on the socket to get the new socket from the other
When one did, you'd call :meth:`accept` on the socket to get the new socket from
end, and use :func:`wrap_socket` to create a server-side SSL context for it::
the other end, and use :func:`wrap_socket` to create a server-side SSL context
for it::
while True:
while True:
newsocket, fromaddr = bindsocket.accept()
newsocket, fromaddr = bindsocket.accept()
...
@@ -553,7 +541,8 @@ end, and use :func:`wrap_socket` to create a server-side SSL context for it::
...
@@ -553,7 +541,8 @@ end, and use :func:`wrap_socket` to create a server-side SSL context for it::
ssl_version=ssl.PROTOCOL_TLSv1)
ssl_version=ssl.PROTOCOL_TLSv1)
deal_with_client(connstream)
deal_with_client(connstream)
Then you'd read data from the ``connstream`` and do something with it till you are finished with the client (or the client is finished with you)::
Then you'd read data from the ``connstream`` and do something with it till you
are finished with the client (or the client is finished with you)::
def deal_with_client(connstream):
def deal_with_client(connstream):
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment