Package nss :: Module ssl :: Class SSLSocket
[hide private]
[frames] | no frames]

type SSLSocket

object --+    
         |    
 io.Socket --+
             |
            SSLSocket

SSLSocket(family=PR_AF_INET, type=PR_DESC_SOCKET_TCP)

Create a new NSPR SSL socket:

Instance Methods [hide private]
 
__init__(family=PR_AF_INET, type=PR_DESC_SOCKET_TCP)
x.__init__(...) initializes x; see help(type(x)) for signature
a new object with type S, a subtype of T
__new__(T, S, ...)
(Socket, NetworkAddress)
accept(timeout=PR_INTERVAL_NO_TIMEOUT)
The socket is a rendezvous socket that has been bound to an address with Socket.bind() and is listening for connections after a call to Socket.listen().
 
config_secure_server(cert, key, kea)
Configures a listen socket with the information needed to handshake as an SSL server.
string)
connection_info_format(level=0, indent=' ')
This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.
[(level, string),...]
connection_info_format_lines(level=0)
Formats the object into a sequence of lines with indent level information.
str
connection_info_str()
Returns a string describing the properties of the SSL connection.
 
data_pending()
Returns the number of bytes waiting in internal SSL buffers to be read by the local application from the SSL socket.
 
force_handshake()
Drives a handshake for a specified SSLSocket to completion on a socket that has already been prepared to do a handshake or is in the middle of doing a handshake.
 
force_handshake_timeout(timeout)
See the documentation for SSLSocket.force\_handshake().
Certficate
get_certificate()
Returns the certificate associated with the socket or None if not previously set.
enabled
get_cipher_pref(cipher)
Returns the preference for the specified SSL2, SSL3, or TLS cipher on the socket.
 
get_hostname()
SSLSocket.get\_hostname() is used by certificate authentication callback function to obtain the domain name of the desired SSL server for the purpose of comparing it with the domain name in the certificate presented by the server actually contacted.
string
get_negotiated_host()
Returns SNI negotiated host name.
Certficate
get_peer_certificate()
SSLSocket.get\_peer\_certificate() is used by certificate authentication and bad-certificate callback functions to obtain the certificate under scrutiny.
 
get_pkcs11_pin_arg()
Returns a tuple of arguments or None if not previously set with SSLSocket.set\_pkcs11\_pin\_arg()
on, cipher, key_size, secret_key_size, issuer, subject
get_security_status()
Gets information about the security parameters of the current connection.
id
get_session_id()
Returns the SSL session ID as a SecItem.
SSLChannelInfo
get_ssl_channel_info()
Returns a ssl.SSLChannelInfo describing the parameters of the connection.
value
get_ssl_option(value)
Retrieves the value of a specified SSL option.
(min_version, max_version)
get_ssl_version_range(repr_kind=AsEnum)
Returns the range of SSL3/TLS versions enabled for the socket.
 
invalidate_session()
After you call SSLSSocket.invalidate_session(), the existing connection using the session can continue, but no new connections can resume this SSL session.
 
rehandshake(flush_cache)
Causes SSL to begin a new SSL 3.0 handshake on a connection that has already completed one handshake.
 
rehandshake_timeout(flush_cache, timeout)
See the documentation for SSLSocket.rehandshake().
 
reset_handshake(as_server)
Calling SSLSocket.reset\_handshake() causes the SSL handshake protocol to start from the beginning on the next I/O operation.
 
set_auth_certificate_callback(...)
set_auth_certificate_callback(callback, [user_data1, ...])
 
set_certificate_db(certdb)
Sets the Certificate Database on a specific SSLSocket.
 
set_cipher_pref(cipher, enabled)
Sets preference for the specified SSL2, SSL3, or TLS cipher on the socket.
 
set_client_auth_data_callback(...)
set_client_auth_data_callback(callback, [user_data1, ...])
 
set_handshake_callback(...)
set_handshake_callback(callback, [user_data1, ...])
 
set_hostname(url)
The client application's certificate authentication callback function needs to compare the domain name in the server's certificate against the domain name of the server the client was attempting to contact.
 
set_pkcs11_pin_arg(user_dataN=..., ...)
 
set_sock_peer_id(id)
Associates a peer ID with a socket to facilitate looking up the SSL session when it is tunneling through a proxy.
 
set_ssl_option(option, value)
Sets a single configuration parameter on this socket.
 
set_ssl_version_range(min_version, max_version)
Sets the range of enabled SSL3/TLS versions for this socket.

Inherited from io.Socket: __iter__, __str__, accept_read, bind, close, connect, fileno, get_peer_name, get_sock_name, get_socket_option, listen, makefile, next, read, readline, readlines, recv, recv_from, send, send_to, sendall, set_socket_option, shutdown

Static Methods [hide private]
Socket
import_tcp_socket(osfd)
Returns a Socket object that uses the specified socket file descriptor for communication.

Inherited from io.Socket: new_tcp_pair, poll

Properties [hide private]

Inherited from io.Socket: desc_type, family, netaddr

Method Details [hide private]

__init__(family=PR_AF_INET, type=PR_DESC_SOCKET_TCP)
(Constructor)

 
x.__init__(...) initializes x; see help(type(x)) for signature
Parameters:
  • family (integer) -
    one of:
    • PR_AF_INET
    • PR_AF_INET6
    • PR_AF_LOCAL
  • type (integer) -
    one of:
    • PR_DESC_SOCKET_TCP
    • PR_DESC_SOCKET_UDP
Overrides: io.Socket.__init__

__new__(T, S, ...)

 
Returns: a new object with type S, a subtype of T
Overrides: io.Socket.__new__

accept(timeout=PR_INTERVAL_NO_TIMEOUT)

 

The socket is a rendezvous socket that has been bound to an address with Socket.bind() and is listening for connections after a call to Socket.listen(). Socket.accept() accepts the first connection from the queue of pending connections and creates a new socket for the newly accepted connection. The rendezvous socket can still be used to accept more connections.

Socket.accept() blocks the calling thread until either a new connection is successfully accepted or an error occurs. If the timeout parameter is not PR_INTERVAL_NO_TIMEOUT and no pending connection can be accepted before the time limit, Socket.accept() raises a nss.error.NSPRError exception with the error code PR_IO_TIMEOUT_ERROR.

Socket.accept() returns a tuple containing a new Socket object and Networkaddress object for the peer.

Parameters:
  • timeout (integer) - optional timeout value expressed as a NSPR interval
Returns: (Socket, NetworkAddress)
Overrides: io.Socket.accept

config_secure_server(cert, key, kea)

 
Configures a listen socket with the information needed to handshake as an SSL server. SSLSocket.config\_secure\_server() requires the certificate for the server and the server's private key.
Parameters:
  • cert (Certificate object) - Server's certificate as a Certificate object
  • key (PrivateKey object) - Server's private key as a PrivateKey object
  • kea (integer) - Key exchange type (e.g. ssl_kea_rsa, ssl_kea_dh, etc.)

connection_info_format(level=0, indent=' ')

 
This is equivalent to: indented_format(obj.format_lines()) on an object providing a format_lines() method.
Parameters:
  • level (integer) - Initial indentation level, all subsequent indents are relative to this starting level.
  • indent (string) - string replicated once for each indent level then prepended to output line
Returns: string)

connection_info_format_lines(level=0)

 

Formats the object into a sequence of lines with indent level information. The return value is a list where each list item is a tuple. The first item in the tuple is an integer representing the indentation level for that line. Any remaining items in the tuple are strings to be output on that line.

The output of this function can be formatted into a single string by calling nss.nss.indented\_format(), e.g.:

print indented_format(obj.format_lines())

The reason this function returns a tuple as opposed to an single indented string is to support other text formatting systems such as GUI's with indentation controls. See nss.nss.indented\_format() for a complete explanation.

Parameters:
  • level (integer) - Initial indentation level, all subsequent indents are relative to this starting level.
Returns: [(level, string),...]

data_pending()

 

Returns the number of bytes waiting in internal SSL buffers to be read by the local application from the SSL socket.

If SSL_SECURITY has not been enabled with a call to ssl.set\_ssl\_default\_option() or SSLSocket.set\_ssl\_option(), the function returns zero.

force_handshake()

 

Drives a handshake for a specified SSLSocket to completion on a socket that has already been prepared to do a handshake or is in the middle of doing a handshake.

When you are forcing the initial handshake on a blocking socket, this function returns when the handshake is complete. For subsequent handshakes, the function can return either because the handshake is complete, or because application data has been received on the connection that must be processed (that is, the application must read it) before the handshake can continue. You can use SSLSocket.force\_handshake() when a handshake is desired but neither end has anything to say immediately. This occurs, for example, when an HTTPS server has received a request and determines that before it can answer the request, it needs to request an authentication certificate from the client. At the HTTP protocol level, nothing more is being said (that is, no HTTP request or response is being sent), so the server uses SSLSocket.force\_handshake() to make the handshake occur. SSLSocket.force\_handshake() does not prepare a socket to do a handshake by itself. The following functions prepare a socket to do a handshake:

A call to SSLSocket.force\_handshake() will almost always be preceded by one of those functions. In versions prior to NSS 1.2, you cannot force a subsequent handshake. If you use this function after the initial handshake, it returns immediately without forcing a handshake.

force_handshake_timeout(timeout)

 
See the documentation for SSLSocket.force\_handshake(). This function adds a timeout interval.
Parameters:
  • timeout (integer) - timeout value expressed as a NSPR interval

get_cipher_pref(cipher)

 
Returns the preference for the specified SSL2, SSL3, or TLS cipher on the socket.
Parameters:
  • cipher (integer) - The cipher suite enumeration (e.g. SSL_RSA_WITH_NULL_MD5, etc.)
Returns: enabled

get_peer_certificate()

 
SSLSocket.get\_peer\_certificate() is used by certificate authentication and bad-certificate callback functions to obtain the certificate under scrutiny. If the client calls SSLSocket.get\_peer\_certificate(), it always returns the server's certificate. If the server calls SSLSocket.get\_peer\_certificate(), it may return None if client authentication is not enabled or if the client had no certificate when asked.
Returns: Certficate

get_security_status()

 

Gets information about the security parameters of the current connection. Returns the tuple (on, cipher, key_size, secret_key_size, issuer, subject)

The interpretation of each value is:
on
An integer, will be one of these values:
  • SSL_SECURITY_STATUS_OFF
  • SSL_SECURITY_STATUS_ON_HIGH
  • SSL_SECURITY_STATUS_ON_LOW
cipher
A string specifying the name of the cipher.
  • For SSL v2, the string is one of the following:
    • RC4
    • RC4-Export
    • RC2-CBC
    • RC2-CBC-Export
    • DES-CBC,
    • DES-EDE3-CBC
  • For SSL v3, the string is one of the following:
    • RC4
    • RC4-40
    • RC2-CBC
    • RC2-CBC-40
    • DES-CBC
    • 3DES-EDE-CBC
    • DES-CBC-40
keySize
An integer, the session key size used, in bits.
secret_key_size
An integer. indicates the size, in bits, of the secret portion of the session key used (also known as the 'effective key size'). The secret key size is never greater than the session key size.
issuer
A string specifying the DN of the issuer of the certificate at the other end of the connection, in RFC1485 format. If no certificate is supplied, the string is 'no certificate'
subject
A string specifying the distinguished name of the certificate at the other end of the connection, in RFC1485 format. If no certificate is supplied, the string is 'no certificate'
Returns: on, cipher, key_size, secret_key_size, issuer, subject

get_ssl_option(value)

 
Retrieves the value of a specified SSL option. Refer to the documentation for SSLSocket.set\_ssl\_option() for an explanation of the possible values.
Parameters:
  • value (integer) - a constant value identifying which option to query
Returns: value

get_ssl_version_range(repr_kind=AsEnum)

 
Returns the range of SSL3/TLS versions enabled for the socket. The result is a tuple whose contents are dictated by repr_kind.
Parameters:
  • repr_kind (RepresentationKind constant) - Specifies what format the contents of the returned tuple will be in. May be one of:

    AsEnum
    The enumerated constant as an integer value.
    AsEnumName
    The name of the enumerated constant as a string.
    AsString
    A short friendly name for the enumerated constant.
Returns: (min_version, max_version)

import_tcp_socket(osfd)
Static Method

 
Returns a Socket object that uses the specified socket file descriptor for communication.
Parameters:
  • osfd (integer) - file descriptor of the SOCK_STREAM socket to import
Returns: Socket
Overrides: io.Socket.import_tcp_socket

rehandshake(flush_cache)

 

Causes SSL to begin a new SSL 3.0 handshake on a connection that has already completed one handshake.

If flush_cache is True, the SSLSocket.rehandshake() function invalidates the current SSL session associated with the specified SSLSocket from the session cache and starts another full SSL 3.0 handshake. It is for use with SSL 3.0 only. You can call this function to redo the handshake if you have changed one of the socket's configuration parameters (for example, if you are going to request client authentication). Setting flush_cache to False can be useful, for example, if you are using export ciphers and want to keep changing the symmetric keys to foil potential attackers. SSLSocket.rehandshake() only initiates the new handshake by sending the first message of that handshake. To drive the new handshake to completion, you must either call SSLSocket.force\_handshake() or do another I/O operation (read or write) on the socket. A call to SSLSocket.rehandshake() is typically followed by a call to SSLSocket.force\_handshake().

Parameters:
  • flush_cache (bool) -
    • If flush_cache is True, the SSL3 cache entry will be flushed first, ensuring that a full SSL handshake from scratch will occur.
    • If flush_cache is False, and an SSL connection is established, it will do the much faster session restart handshake. This will regenerate the symmetric session keys without doing another private key operation.

rehandshake_timeout(flush_cache, timeout)

 
See the documentation for SSLSocket.rehandshake(). This function adds a timeout interval.
Parameters:
  • flush_cache (bool) - cache flush flag
  • timeout (integer) - timeout value expressed as a NSPR interval

reset_handshake(as_server)

 
Calling SSLSocket.reset\_handshake() causes the SSL handshake protocol to start from the beginning on the next I/O operation. That is, the handshake starts with no cipher suite already in use, just as it does on the first handshake on a new socket. When an application imports a socket into SSL after the TCP connection on that socket has already been established, it must call SSLSocket.reset\_handshake() to determine whether SSL should behave like an SSL client or an SSL server. Note that this step would not be necessary if the socket weren't already connected. For an SSL socket that is configured before it is connected, SSL figures this out when the application calls SSLSocket.connect() or SSLSocket.accept(). If the socket is already connected before SSL gets involved, you must provide this extra hint.
Parameters:
  • as_server (bool) -
    • True means the socket will attempt to handshake as a server the next time it tries, and
    • False means the socket will attempt to handshake as a client the next time it tries.

set_auth_certificate_callback(...)

 

set_auth_certificate_callback(callback, [user_data1, ...])

The callback has the following signature:

callback(socket, check_sig, is_server, [user_data1, ...]) -> bool
socket
the SSLSocket object
check_sig
boolean, True means signatures are to be checked and the certificate chain is to be validated. False means they are not to be checked. (The value is normally True.)
is_server
boolean, True means the callback function should evaluate the certificate as a server does, treating the remote end as a client. False means the callback function should evaluate the certificate as a client does, treating the remote end as a server.
user_dataN
zero or more caller supplied optional parameters

The callback function should return True if authentication is successful, False otherwise. If authentication is not successful the callback should indicate the reason for the failure (if possible) by calling nss.set_error() with the appropriate error code.

The callback function obtains the certificate to be authenticated by calling ssl.get_peer_certificate(). If is_server is false, the callback should also check that the domain name in the remote server's certificate matches the desired domain name specified in a previous call to ssl.set_hostname(). To obtain that domain name, the callback calls ssl.get_hostname().

The callback may need to call one or more PK11 functions to obtain the services of a PKCS 11 module. Some of the PK11 functions require a PIN argument (see ssl.set_pkcs11_pin_arg() for details). To obtain the value that was set with ssl.set_pkcs11_pin_arg(), the callback calls ssl.get_pkcs11_pin_arg().

If the callback returns False, the SSL connection is terminated immediately unless the application has supplied a bad-certificate callback function by having previously called ssl.set_bad_cert_callback(). A bad-certificate callback function gives the application the opportunity to choose to accept the certificate as authentic and authorized even though it failed the check performed by the certificate authentication callback function.

Example:

def auth_certificate_callback(sock, check_sig, is_server, certdb):
    cert_is_valid = False

    cert = sock.get_peer_certificate()
    pin_args = sock.get_pkcs11_pin_arg()
    if pin_args is None:
        pin_args = ()

    # Define how the cert is being used based upon the is_server flag.  This may
    # seem backwards, but isn't. If we're a server we're trying to validate a
    # client cert. If we're a client we're trying to validate a server cert.
    if is_server:
        intended_usage = nss.certificateUsageSSLClient
    else:
        intended_usage = nss.certificateUsageSSLServer

    try:
        # If the cert fails validation it will raise an exception, the errno attribute
        # will be set to the error code matching the reason why the validation failed
        # and the strerror attribute will contain a string describing the reason.
        approved_usage = cert.verify_now(certdb, check_sig, intended_usage, *pin_args)
    except Exception, e:
        cert_is_valid = False
        return cert_is_valid

    # Is the intended usage a proper subset of the approved usage
    if approved_usage & intended_usage:
        cert_is_valid = True
    else:
        cert_is_valid = False

    # If this is a server, we're finished
    if is_server or not cert_is_valid:
        return cert_is_valid

    # Certificate is OK.  Since this is the client side of an SSL
    # connection, we need to verify that the name field in the cert
    # matches the desired hostname.  This is our defense against
    # man-in-the-middle attacks.

    hostname = sock.get_hostname()
    try:
        # If the cert fails validation it will raise an exception
        cert_is_valid = cert.verify_hostname(hostname)
    except Exception, e:
        cert_is_valid = False
        return cert_is_valid

    return cert_is_valid
Parameters:
  • callback (function pointer) - callback to invoke
  • user_dataN, - zero or more caller supplied parameters which will be passed to the callback

set_certificate_db(certdb)

 
Sets the Certificate Database on a specific SSLSocket.
Parameters:
  • certdb (CertDB object) - The certification database as a CertDB object

set_cipher_pref(cipher, enabled)

 

Sets preference for the specified SSL2, SSL3, or TLS cipher on the socket. A cipher suite is used only if the policy allows it and the preference for it is set to True.

This function must be called once for each cipher you want to enable or disable by default.

Note, which cipher suites are permitted or disallowed are modified by previous calls to one or more of the SSL Export Policy Functions.

Parameters:
  • cipher (integer) - The cipher suite enumeration (e.g. SSL_RSA_WITH_NULL_MD5, etc.)
  • enabled (bool or int) - True enables, False disables

set_client_auth_data_callback(...)

 

set_client_auth_data_callback(callback, [user_data1, ...])

The callback has the following signature:

callback(ca_names, [user_data1, ...]) -> (Certificate, PrivateKey)
ca_names
Sequence of CA distinguished names that the server accepts. Each item in the sequence must be a SecItem object containing a distinguished name.
user_dataN
zero or more caller supplied optional parameters

The callback returns Certificate and PrivateKey if successful, or None if the callback failed.

Defines a callback function for SSL to use in a client application when a server asks for client authentication information. This callback function is required if your client application is going to support client authentication.

The callback function set with SSLSocket.set\_client\_auth\_data\_callback() is used to get information from a client application when authentication is requested by the server. The callback function retrieves the client's private key and certificate. SSL provides an implementation of this callback function; see NSS_GetClientAuthData for details. Unlike SSL_AuthCertificate, NSS_GetClientAuthData is not a default callback function. You must set it explicitly with SSLSocket.set\_client\_auth\_data\_callback() if you want to use it.

Example:

def client_auth_data_callback(ca_names, chosen_nickname, password, certdb):
    cert = None
    if chosen_nickname:
        try:
            cert = nss.find_cert_from_nickname(chosen_nickname, password)
            priv_key = nss.find_key_by_any_cert(cert, password)
            return cert, priv_key
        except NSPRError, e:
            return False
    else:
        nicknames = nss.get_cert_nicknames(certdb, nss.SEC_CERT_NICKNAMES_USER)
        for nickname in nicknames:
            try:
                cert = nss.find_cert_from_nickname(nickname, password)
                if cert.check_valid_times():
                    if cert.has_signer_in_ca_names(ca_names):
                        priv_key = nss.find_key_by_any_cert(cert, password)
                        return cert, priv_key
            except NSPRError, e:
                pass
        return False

sock = ssl.SSLSocket(net_addr.family)
sock.set_client_auth_data_callback(client_auth_data_callback, nickname, password, nss.get_default_certdb())
Parameters:
  • callback (function pointer) - callback to invoke
  • user_dataN, - zero or more caller supplied parameters which will be passed to the callback

set_handshake_callback(...)

 

set_handshake_callback(callback, [user_data1, ...])

The callback has the following signature:

callback(socket, [user_data1, ...])
socket
the SSL socket the handshake has completed on
user_dataN
zero or more caller supplied optional parameters

Sets up a callback function used by SSL to inform either a client application or a server application when the handshake is completed.

Example:

def handshake_callback(sock):
    print 'handshake complete, peer = %s' % (sock.get_peer_name())

sock = ssl.SSLSocket(net_addr.family)
sock.set_handshake_callback(handshake_callback)
Parameters:
  • callback (function pointer) - callback to invoke
  • user_dataN, - zero or more caller supplied parameters which will be passed to the callback

set_hostname(url)

 
The client application's certificate authentication callback function needs to compare the domain name in the server's certificate against the domain name of the server the client was attempting to contact. This step is vital because it is the client's only protection against a man-in-the-middle attack. The client application uses SSLSocket.set\_hostname() to set the domain name of the desired server before performing the first SSL handshake. The client application's certificate authentication callback function gets this string by calling SSLSocket.get\_hostname().
Parameters:
  • url (string) - A string specifying the desired server's domain name.

set_pkcs11_pin_arg(user_dataN=..., ...)

 
Parameters:
  • user_dataN (object ...) - zero or more caller supplied parameters which will be passed to the pk11.password_callback()

set_sock_peer_id(id)

 

Associates a peer ID with a socket to facilitate looking up the SSL session when it is tunneling through a proxy.

SSL peers frequently reconnect after a relatively short time has passed. To avoid the overhead of repeating the full SSL handshake in situations like this, the SSL protocol supports the use of a session cache, which retains information about each connection for some predetermined length of time.

For example, a client session cache includes the hostname and port number of each server the client connects with, plus additional information such as the master secret generated during the SSL handshake. For a direct connection with a server, the hostname and port number are sufficient for the client to identify the server as one for which it has an entry in its session cache. However, the situation is more complicated if the client is on an intranet and is connecting to a server on the Internet through a proxy. In this case, the client first connects to the proxy, and the client and proxy exchange messages specified by the proxy protocol that allow the proxy, in turn, to connect to the requested server on behalf of the client. This arrangement is known as SSL tunneling.

Client session cache entries for SSL connections that tunnel through a particular proxy all have the same hostname and port number--that is, the hostname and port number of the proxy. To determine whether a particular server with which the client is attempting to connect has an entry in the session cache, the session cache needs some additional information that identifies that server. This additional identifying information is known as a peer ID. The peer ID is associated with a socket, and must be set before the SSL handshake occurs--that is, before the SSL handshake is initiated by a call to a function such as SSLSocket.read() or SSLSocket.force\_handshake(). To set the peer ID, you use SSLSocket.set\_sock\_peer\_id().

In summary, SSL uses three pieces of information to identify a server's entry in the client session cache: the hostname, port number, and peer ID. In the case of a client that is tunneling through a proxy, the hostname and port number identify the proxy, and the peer ID identifies the desired server. It is recommended that the client set the peer ID to a string that consists of the server's hostname and port number, like this:'www.hostname.com:387'. This convention guarantees that each server has a unique entry in the client session cache.

Parameters:
  • id (integer) - An ID number assigned by the application to keep track of the SSL session associated with the peer.

set_ssl_option(option, value)

 

Sets a single configuration parameter on this socket. Call once for each parameter you want to change. The configuration parameters are listed below.

SSL_SECURITY (default=True)
Enables use of security protocol. WARNING: If you turn this option off, the session will not be an SSL session and will not have certificate-based authentication, tamper detection, or encryption.
SSL_REQUEST_CERTIFICATE: (default=False)
Is a server option that requests a client to authenticate itself.
SSL_REQUIRE_CERTIFICATE: (default=SSL_REQUIRE_FIRST_HANDSHAKE)
Is a server option that requires a client to authenticate itself (only if SSL_REQUEST_CERTIFICATE is also on). If client does not provide certificate, the connection terminates.
SSL_HANDSHAKE_AS_CLIENT: (default=False)
Controls the behavior of SSLSocket.accept(),. If this option is off, the SSLSocket.accept() configures the SSL socket to handshake as a server. If it is on, then SSLSocket.accept() configures the SSL socket to handshake as a client, even though it accepted the connection as a TCP server.
SSL_HANDSHAKE_AS_SERVER: (default=False)
Controls the behavior of SSLSocket.connect(). If this option is off, then SSLSocket.connect() configures the SSL socket to handshake as a client. If it is on, then SSLSocket.connect() configures the SSL socket to handshake as a server, even though it connected as a TCP client.
SSL_ENABLE_FDX: (default=False)

Tells the SSL library whether the application will have two threads, one reading and one writing, or just one thread doing reads and writes alternately. The factory setting for this option (which is the default, unless the application changes the default) is off, which means that the application will not do simultaneous reads and writes. An application that needs to do simultaneous reads and writes should set this to True.

In NSS 2.8, the SSL_ENABLE_FDX option only affects the behavior of nonblocking SSL sockets. See the description below for more information on this option.

SSL_ENABLE_SSL3: (default=True)
Enables the application to communicate with SSL v3. If you turn this option off, an attempt to establish a connection with a peer that understands only SSL v3 will fail. [1]
SSL_ENABLE_SSL2: (default=True)
Enables the application to communicate with SSL v2. If you turn this option off, an attempt to establish a connection with a peer that understands only SSL v2 will fail. [1]
SSL_ENABLE_TLS: (default=True)
Is a peer of the SSL_ENABLE_SSL2 and SSL_ENABLE_SSL3 options. The IETF standard Transport Layer Security (TLS) protocol, RFC 2246, is a modified version of SSL3. It uses the SSL version number 3.1, appearing to be a 'minor' revision of SSL3.0. NSS 2.8 supports TLS in addition to SSL2 and SSL3. You can think of it as 'SSL_ENABLE_SSL3.1.' See the description below for more information about this option. [1]
SSL_V2_COMPATIBLE_HELLO: (default=True)
Tells the SSL library whether or not to send SSL3 client hello messages in SSL2-compatible format. If set to True, it will; otherwise, it will not. See the description below for more information on this option.
SSL_NO_CACHE: (default=False)
Disallows use of the session cache. Factory setting is off. If you turn this option on, this socket will be unable to resume a session begun by another socket. When this socket's session is finished, no other socket will be able to resume the session begun by this socket.
SSL_ROLLBACK_DETECTION: (default=True)
Disables detection of a rollback attack. Factory setting is on. You must turn this option off to interoperate with TLS clients ( such as certain versions of Microsoft Internet Explorer) that do not conform to the TLS specification regarding rollback attacks. Important: turning this option off means that your code will not comply with the TLS 3.1 and SSL 3.0 specifications regarding rollback attack and will therefore be vulnerable to this form of attack.

Keep the following in mind when deciding on the operating parameters you want to use with a particular socket.

Turning on SSL_REQUIRE_CERTIFICATE will have no effect unless SSL_REQUEST_CERTIFICATE is also turned on. If you enable SSL_REQUEST_CERTIFICATE, then you should explicitly enable or disable SSL_REQUIRE_CERTIFICATE rather than allowing it to default. Enabling the SSL_REQUIRE_CERTIFICATE option is not recommended. If the client has no certificate and this option is enabled, the client's connection terminates with an error. The user is likely to think something is wrong with either the client or the server, and is unlikely to realize that the problem is the lack of a certificate. It is better to allow the SSL handshake to complete and then return an error message to the client that informs the user of the need for a certificate.

The SSL protocol is defined to be able to handle simultaneous two-way communication between applications at each end of an SSL connection. Two-way simultaneous communication is also known as'Full Duplex', abbreviated FDX. However, most application protocols that use SSL are not two-way simultaneous, but two-way alternate, also known as 'Half Dupled'; that is, each end takes turns sending, and each end is either sending, or receiving, but not both at the same time. For an application to do full duplex, it would have two threads sharing the socket; one doing all the reading and the other doing all the writing.

The SSL_ENABLE_FDX option tells the SSL library whether the application will have two threads, one reading and one writing, or just one thread doing reads and writes alternately.

If an SSL3 client hello message is sent to a server that only understands SSL2 and not SSL3, then the server will interpret the SSL3 client hello as a very large message, and the connection will usually seem to 'hang' while the SSL2 server expects more data that will never arrive. For this reason, the SSL3 spec allows SSL3 client hellos to be sent in SSL2 format, and it recommends that SSL3 servers all accept SSL3 client hellos in SSL2 format. When an SSL2-only server receives an SSL3 client hello in SSL2 format, it can (and probably will) negotiate the protocol version correctly, not causing a 'hang'.

Some applications may wish to force SSL3 client hellos to be sent in SSL3 format, not in SSL2-compatible format. They might wish to do this if they knew, somehow, that the server does not understand SSL2-compatible client hello messages.

SSL_V2_COMPATIBLE_HELLO tells the SSL library whether or not to send SSL3 client hello messages in SSL2-compatible format. Note that calling SSLSocket.set\_ssl\_option() to set SSL_V2_COMPATIBLE_HELLO to False implicitly also sets the SSL_ENABLE_SSL2 option to False for that SSL socket. Calling SSL_EnableDefault to change the application default setting for SSL_V2_COMPATIBLE_HELLO to False implicitly also sets the default value for SSL_ENABLE_SSL2 option to False for that application.

The options SSL_ENABLE_SSL2, SSL_ENABLE_SSL3, and SSL_ENABLE_TLS can each be set to True or False independently of each other. NSS 2.8 and later versions will negotiate the highest protocol version with the peer application from among the set of protocols that are commonly enabled in both applications. [1]

Note that SSL3 and TLS share the same set of cipher suites. When both SSL3 and TLS are enabled, all SSL3/TLS cipher suites that are enabled are enabled for both SSL3 and TLS.

When an application imports a socket into SSL after the TCP connection on that socket has already been established, it must call SSLSocket.reset\_handshake() to indicate whether the socket is for a client or server. At first glance this may seem unnecessary, since SSLSocket.set\_ssl\_option() can set SSL_HANDSHAKE_AS_CLIENT or SSL_HANDSHAKE_AS_SERVER. However, these settings control the behavior of SSLSocket.connect() and SSLSocket.accept() only; if you don't call one of those functions after importing a non-SSL socket with SSL_Import (as in the case of an already established TCP connection), SSL still needs to know whether the application is functioning as a client or server.

If a socket file descriptor is imported as an SSL socket before it is connected, it is implicitly configured to handshake as a client or handshake as a server when the connection is made. If the application calls SSLSocket.connect() (connecting as a TCP client), then the SSL socket is (by default) configured to handshake as an SSL client. If the application calls SSLSocket.accept() (connecting the socket as a TCP server) then the SSL socket is (by default) configured to handshake as an SSL server. SSL_HANDSHAKE_AS_CLIENT and SSL_HANDSHAKE_AS_SERVER control this implicit configuration. Both SSL_HANDSHAKE_AS_CLIENT and SSL_HANDSHAKE_AS_SERVER are initially set to off--that is, the process default for both values is False when the process begins. The process default can be changed from the initial values by using SSL_EnableDefault, and the value for a particular socket can be changed by using SSLSocket.set\_ssl\_option().

If a socket that is already connected gets imported into SSL after it has been connected (that is, after SSLSocket.accept() or SSLSocket.connect() has returned), then no implicit SSL handshake configuration as a client or server will have been done by SSLSocket.connect() or SSLSocket.accept() on that socket. In this case, a call to SSLSocket.reset\_handshake() is required to explicitly configure the socket to handshake as a client or as a server. If SSLSocket.reset\_handshake() is not called to explicitly configure the socket handshake, a crash is likely to occur when the first I/O operation is done on the socket after it is imported into SSL.

[1](1, 2, 3, 4) See the "SSL Version Range API" section in the module documentation for updated recomendations on protocol selection.

set_ssl_version_range(min_version, max_version)

 
Sets the range of enabled SSL3/TLS versions for this socket.
Parameters: