You are on page 1of 18

Python OpenSSL Manual

Release 0.11

Jean-Paul Calderone
January 15, 2012

exarkuntwistedmatrix. om

Abstra t
This module is a rather thin wrapper around (a subset of ) the OpenSSL library. With thin wrapper
I mean that a lot of the obje t methods do nothing more than alling a orresponding fun tion in the
OpenSSL library.

Contents

1 Introdu tion
2 Building and Installing
3

2.1

Building the Module on a Unix System

2.2

Building the Module on a Windows System 

Python interfa e to OpenSSL

OpenSSL
3.1 rypto 

Generi ryptographi module

X509Extension obje ts
X509 obje ts

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

7

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

8

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

8

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

8

PKCS12 obje ts

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

8

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

9

X509Extension obje ts

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

9

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

10

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

10

Nets apeSPKI obje ts
Revoked obje ts

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

10

generator . . . . . . . . . . . .

11

. . . . . . . . . . . . . . . . . .

11

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

13

rand  An interfa e to the OpenSSL pseudo random number
SSL  An interfa e to the SSL-spe i parts of OpenSSL . .
Context obje ts

Conne tion obje ts

4 Internals

3

5

PKCS7 obje ts

3.3

3

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

X509Store obje ts

3.2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2

3

5

X509Req obje ts

CRL obje ts

. . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

X509Name obje ts

PKey obje ts

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2
2

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

4.1

Ex eptions

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

4.2

Callba ks

4.3

A essing So ket Methods

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

15

17

17
18
18

1 Introdu tion
The reason pyOpenSSL was reated is that the SSL support in the so ket module in Python 2.1 (the
ontemporary version of Python when the pyOpenSSL proje t was begun) was severely limited.
OpenSSL wrappers for Python at the time were also limited, though in dierent ways.

Other

Unfortunately,

1

Python's standard library SSL support has remained weak, although other pa kages (su h as M2Crypto )
have made great advan es and now equal or ex eed pyOpenSSL's fun tionality.
The reason pyOpenSSL ontinues to be maintained is that there is a signi ant user ommunity around it, as
well as a large amount of software whi h depends on it. It is a great benet to many people for pyOpenSSL
to ontinue to exist and advan e.

2 Building and Installing
These instru tions an also be found in the le

INSTALL.

I have tested this on Debian Linux systems (woody and sid), Solaris 2.6 and 2.7. Others have su essfully
ompiled it on Windows and NT.

2.1 Building the Module on a Unix System
pyOpenSSL uses distutils, so there really shouldn't be any problems. To build the library:

python setup.py build

If your OpenSSL header les aren't in

/usr/in lude, you

may need to supply the

s ript know where to look. The same goes for the libraries of ourse, use the
a ept these ags, so you have to run rst

build_ext and

then

build!

-L ag.

-I 

ag to let the setup

Note that

build won't

Example:

python setup.py build_ext -I/usr/lo al/ssl/in lude -L/usr/lo al/ssl/lib
python setup.py build

Now you should have a dire tory alled

OpenSSL that

ontains e.g.

SSL.so and __init__.py somewhere in

the build di re tory, so just:

python setup.py install

If you, for some ar ane reason, don't want the module to appear in the

--prefix option.

site-pa kages dire tory,

use the

You an, of ourse, do

python setup.py --help

to nd out more about how to use the s ript.

1 See

2

http:// handlerproje t.org/Proje ts/MeTooCrypto

2 Building and Installing

2.2 Building the Module on a Windows System
Big thanks to Itamar Shtull-Trauring and Oleg Orlov for their help with Windows build instru tions. Same
as for Unix systems, we have to separate the

build_ext and

the

build.

Building the library:

setup.py build_ext -I ...\openssl\in 32 -L ...\openssl\out32dll
setup.py build

Where

...\openssl is

of ourse the lo ation of your OpenSSL installation.

Installation is the same as for Unix systems:

setup.py install

And similarily, you an do

setup.py --help

to get more information.

3

OpenSSL 

Python interfa e to OpenSSL

This pa kage provides a high-level interfa e to the fun tions in the OpenSSL library. The following modules
are dened:

rypto
Generi ryptographi module. Note that if anything is in omplete, this module is!

rand
An interfa e to the OpenSSL pseudo random number generator.

SSL
An interfa e to the SSL-spe i parts of OpenSSL.

3.1

rypto

X509Type
See 

Generi ryptographi module

X509.

lass X509()

A lass representing X.509 erti ates.

X509NameType
See X509Name.

lass X509Name(x509name )

A lass representing X.509 Distinguished Names.
This onstru tor reates a opy of

x509name

whi h should be an instan e of

X509Name.

X509ReqType

2.2 Building the Module on a Windows System

3

See

X509Req.

lass X509Req()

A lass representing X.509 erti ate requests.

X509StoreType
A Python type obje t representing the X509Store obje t type.

PKeyType
See

PKey.

lass PKey()

A lass representing DSA or RSA keys.

PKCS7Type
A Python type obje t representing the PKCS7 obje t type.

PKCS12Type
A Python type obje t representing the PKCS12 obje t type.

X509ExtensionType
See X509Extension.

lass X509Extension(typename, riti al, value , subje t
[

A

lass

representing

an

X.509

℄[,

issuer ℄)

v3

erti ate

extensions.

http://openssl.org/do s/apps/x509v3_ ong.html#STANDARD_EXTENSIONS
their options. Optional parameters

subje t

issuer

and

for

typename

See
strings

and

must be X509 obje ts.

Nets apeSPKIType
See Nets apeSPKI.

lass Nets apeSPKI( en )
[

A lass representing Nets ape SPKI obje ts.
If the

en

argument is present, it should be a base64-en oded string representing a Nets apeSPKI

obje t, as returned by the

lass CRL()
lass Revoked()

b64_en ode method.

A lass representing Certif ate Revo ation List obje ts.

A lass representing Revo ation obje ts of CRL.

FILETYPE_PEM
FILETYPE_ASN1
File type onstants.

TYPE_RSA
TYPE_DSA
Key type onstants.

ex eption Error

Generi ex eption used in the

rypto module.

dump_ ertifi ate(type, ert )

ert into a buer string en oded with the type type .
dump_ ertifi ate_request(type, req )
Dump the erti ate request req into a buer string en oded with the type type .
Dump the erti ate

dump_privatekey(type, pkey [, ipher, passphrase ℄)
Dump the private key

pkey

FILETYPE_PEM) en rypting

passphrase

4

into a buer string en oded with the type

it using

ipher

and

passphrase .

type ,

optionally (if

type

is

must be either a string or a allba k for providing the pass phrase.

3

OpenSSL 

Python interfa e to OpenSSL

load_ ertifi ate(type, buer )
Load a erti ate (X509) from the string

buer

en oded with the type

load_ ertifi ate_request(type, buer )
Load a erti ate request (X509Req) from the string

load_privatekey(type, buer [, passphrase ℄)
Load a private key (PKey) from the string

FILETYPE_PEM and FILETYPE_ASN1).

buer

buer

type .

en oded with the type

en oded with the type

type

type .
(must be one of

passphrase must be either a string or a allba k for providing the pass phrase.
load_ rl(type, buer )
Load Certi ate Revo ation List (CRL) data from a string buer . buer en oded with the type type .
The type type must either FILETYPE_PEM or FILETYPE_ASN1).
load_pk s7_data(type, buer )
Load pk s7 data from the string buer en oded with the type type .
load_pk s12(buer [, passphrase ℄)
Load pk s12 data from the string

buer .

If the pk s12 stru ture is en rypted, a

passphrase

must be

in luded. The MAC is always he ked and thus required.
See also the man page for the C fun tion

PKCS12_parse.

sign(key, data, digest )
Sign a data string using the given key and message digest.

key

is a

PKey instan e. data is a str instan e. digest 
sha1. New in version 0.11.

is a

str naming a supported message digest type,

for example

verify( erti ate, signature, data, digest )
Verify the signature for a data string.

erti ate is a X509 instan e orresponding to the private key whi h generated the signature. signature
is a str instan e giving the signature itself. data is a str instan e giving the data to whi h the signature
applies. digest is a str instan e naming the message digest type of the signature, for example sha1.
New in version 0.11.

X509Extension obje ts
X509Extension obje ts have the following methods:

get_short_name()
Retrieve the short des riptive name for this extension.
The result is a byte string like 

basi Constraints.

New in version 0.12.

get_data()
Retrieve the data for this extension.
The result is the ASN.1 en oded form of the extension data as a byte string.

New in version 0.12.

X509 obje ts
X509 obje ts have the following methods:

get_issuer()
Return an X509Name obje t representing the issuer of the erti ate.

get_pubkey()
Return a PKey obje t representing the publi key of the erti ate.

3.1

rypto 

Generi ryptographi module

5

get_serial_number()
Return the erti ate serial number.

get_subje t()
Return an X509Name obje t representing the subje t of the erti ate.

get_version()
Return the erti ate version.

get_notBefore()
Return a string giving the time before whi h the erti ate is not valid. The string is formatted as an
ASN1 GENERALIZEDTIME:

YYYYMMDDhhmmssZ
YYYYMMDDhhmmss+hhmm
YYYYMMDDhhmmss-hhmm
If no value exists for this eld,

None is

returned.

get_notAfter()
Return a string giving the time after whi h the erti ate is not valid. The string is formatted as an
ASN1 GENERALIZEDTIME:

YYYYMMDDhhmmssZ
YYYYMMDDhhmmss+hhmm
YYYYMMDDhhmmss-hhmm
If no value exists for this eld,

None is

returned.

set_notBefore(when )
Change the time before whi h the erti ate is not valid.

when

is a string formatted as an ASN1

GENERALIZEDTIME:

YYYYMMDDhhmmssZ
YYYYMMDDhhmmss+hhmm
YYYYMMDDhhmmss-hhmm

set_notAfter(when )
Change the time after whi h the erti ate is not valid.

when

is a string formatted as an ASN1

GENERALIZEDTIME:

YYYYMMDDhhmmssZ
YYYYMMDDhhmmss+hhmm
YYYYMMDDhhmmss-hhmm

gmtime_adj_notBefore(time )
Adjust the timestamp (in GMT) when the erti ate starts being valid.

gmtime_adj_notAfter(time )
Adjust the timestamp (in GMT) when the erti ate stops being valid.

has_expired()
Che ks the erti ate's time stamp against urrent time. Returns true if the erti ate has expired
and false otherwise.

set_issuer(issuer )
Set the issuer of the erti ate to

issuer .

set_pubkey(pkey )

6

3

OpenSSL 

Python interfa e to OpenSSL

pkey .

Set the publi key of the erti ate to

set_serial_number(serialno )

serialno .

Set the serial number of the erti ate to

set_subje t(subje t )
Set the subje t of the erti ate to

set_version(version )
Set the erti ate version to

subje t .

version .

sign(pkey, digest )
Sign the erti ate, using the key

pkey

and the message digest algorithm identied by the string

digest .

subje t_name_hash()
Return the hash of the erti ate subje t.

digest(digest_name )
Return a digest of the erti ate, using the

digest_name

method.

digest_name

must be a string

des ribing a digest algorithm supported by OpenSSL (by EVP_get_digestbyname, spe i ally). For
example,

"md5" or "sha1".

add_extensions(extensions )
Add the extensions in the sequen e

extensions

to the erti ate.

get_extension_ ount()
Return the number of extensions on this erti ate.

New in version 0.12.

get_extension(index )
Retrieve the extension on this erti ate at the given index.
Extensions on a erti ate are kept in order.

The index parameter sele ts whi h extension will be

returned. The returned obje t will be an X509Extension instan e.

New in version 0.12.

X509Name obje ts
X509Name obje ts have the following methods:

hash()
Return an integer giving the rst four bytes of the MD5 digest of the DER representation of the name.

der()
Return a string giving the DER representation of the name.

get_ omponents()
Return a list of two-tuples of strings giving the omponents of the name.
X509Name obje ts have the following members:

ountryName
The ountry of the entity.

C

may be used as an alias for

stateOrProvin eName
The state or provin e of the entity.

lo alityName
The lo ality of the entity.

L

ST

The organization name of the entity.

organizationalUnitName
The organizational unit of the entity.

3.1

rypto

may be used as an alias for

may be used as an alias for

organizationName

O

stateOrProvin eName·

lo alityName.

may be used as an alias for

OU 

Generi ryptographi module

ountryName.

organizationName.

may be used as an alias for

organizationalUnitName.

7

ommonName
The ommon name of the entity.

CN

may be used as an alias for

ommonName.

emailAddress
The e-mail address of the entity.

X509Req obje ts
X509Req obje ts have the following methods:

get_pubkey()
Return a PKey obje t representing the publi key of the erti ate request.

get_subje t()
Return an X509Name obje t representing the subje t of the erti ate.

set_pubkey(pkey )
Set the publi key of the erti ate request to

sign(pkey, digest )
Sign the erti ate request, using the key

digest .
verify(pkey )

pkey .

pkey

and the message digest algorithm identied by the

string

Verify a erti ate request using the publi key

pkey .

set_version(version )
Set the version (RFC 2459, 4.1.2.1) of the erti ate request to

version .

get_version()
Get the version (RFC 2459, 4.1.2.1) of the erti ate request.

X509Store obje ts
The X509Store obje t has urrently just one method:

add_ ert( ert )
Add the erti ate

ert

to the erti ate store.

PKey obje ts
The PKey obje t has the following methods:

bits()
Return the number of bits of the key.

generate_key(type, bits )
Generate a publi /private key pair of the type

type (one of TYPE_RSA and TYPE_DSA) with the size bits .

type()
Return the type of the key.

PKCS7 obje ts
PKCS7 obje ts have the following methods:

type_is_signed()
FIXME

8

3

OpenSSL 

Python interfa e to OpenSSL

type_is_enveloped()
FIXME

type_is_signedAndEnveloped()
FIXME

type_is_data()
FIXME

get_type_name()
Get the type name of the PKCS7.

PKCS12 obje ts
PKCS12 obje ts have the following methods:

export([passphrase=None ℄[, iter=2048 ℄[, ma iter=1 ℄)
Returns a PKCS12 obje t as a string.
The optional

passphrase

must be a string not a allba k.

See also the man page for the C fun tion

PKCS12_ reate.

get_ a_ ertifi ates()
Return CA erti ates within the PKCS12 obje t as a tuple. Returns

None

if no CA erti ates are

present.

get_ ertifi ate()
Return erti ate portion of the PKCS12 stru ture.

get_friendlyname()
Return friendlyName portion of the PKCS12 stru ture.

get_privatekey()
Return private key portion of the PKCS12 stru ture

set_ a_ ertifi ates( a erts )
Repla e or set the CA erti ates within the PKCS12 obje t with the sequen e
Set

a erts

to

None to

a erts .

remove all CA erti ates.

set_ ertifi ate( ert )
Repla e or set the erti ate portion of the PKCS12 stru ture.

set_friendlyname(name )
Repla e or set the friendlyName portion of the PKCS12 stru ture.

set_privatekey(pkey )
Repla e or set private key portion of the PKCS12 stru ture

X509Extension obje ts
X509Extension obje ts have several methods:

get_ riti al()
Return the riti al eld of the extension obje t.

get_short_name()
Return the short type name of the extension obje t.

3.1

rypto 

Generi ryptographi module

9

Nets apeSPKI obje ts
Nets apeSPKI obje ts have the following methods:

b64_en ode()
Return a base64-en oded string representation of the obje t.

get_pubkey()
Return the publi key of obje t.

set_pubkey(key )
Set the publi key of the obje t to

key .

sign(key, digest_name )
Sign the Nets apeSPKI obje t using the given

key

and

digest_name . digest_name

must be a string

des ribing a digest algorithm supported by OpenSSL (by EVP_get_digestbyname, spe i ally). For
example,

"md5" or "sha1".

verify(key )
Verify the Nets apeSPKI obje t using the given

key .

CRL obje ts
CRL obje ts have the following methods:

add_revoked(revoked )
Add a Revoked obje t to the CRL, by value not referen e.

export( ert, key [, type=FILETYPE_PEM
Use

ert

and

key

℄[,

days=100 ℄)

to sign the CRL and return the CRL as a string.

days

is the number of days before

the next CRL is due.

get_revoked()
Return a tuple of Revoked obje ts, by value not referen e.

Revoked obje ts
Revoked obje ts have the following methods:

all_reasons()
Return a list of all supported reasons.

get_reason()
Return the revo ation reason as a str. Can be None, whi h diers from "Unspe ied".

get_rev_date()
Return the revo ation date as a str. The string is formatted as an ASN1 GENERALIZEDTIME.

get_serial()
Return a str ontaining a hex number of the serial of the revoked erti ate.

set_reason(reason )
Set the revo ation reason.
ase are ignored. See

reason

must be None or a string, but the values are limited. Spa es and

all_reasons.

set_rev_date(date )
Set the revo ation date. The string is formatted as an ASN1 GENERALIZEDTIME.

set_serial(serial )

serial

10

is a string ontaining a hex number of the serial of the revoked erti ate.

3

OpenSSL 

Python interfa e to OpenSSL

3.2

rand 

An interfa e to the OpenSSL pseudo random number generator

This module handles the OpenSSL pseudo random number generator (PRNG) and de lares the following:

add(string, entropy )
Mix bytes from

string into the PRNG state. The entropy argument is (the lower bound of ) an estimate
string , measured in bytes. For more information, see e.g. RFC

of how mu h randomness is ontained in
1750.

bytes(num_bytes )
Get some random bytes from the PRNG as a string.
This is a wrapper for the C fun tion

RAND_bytes.

leanup()
Erase the memory used by the PRNG.
This is a wrapper for the C fun tion

RAND_ leanup.

egd(path [, bytes ℄)
Query the Entropy Gathering Daemon

add to

seed the PRNG. The default value of

load_file(path [, bytes ℄)
Read

2 on so ket

bytes

bytes (or all of it, if

default value of

bytes

bytes

bytes

path

for

bytes

bytes of random data and and uses

is 255.

is negative) of data from the le

path

to seed the PRNG. The

is -1.

s reen()
Add the urrent ontents of the s reen to the PRNG state. Availability: Windows.

seed(string )
This is equivalent to alling

add

with

entropy

as the length of the string.

status()
Returns true if the PRNG has been seeded with enough data, and false otherwise.

write_file(path )
Write a number of random bytes ( urrently 1024) to the le

load_file to

ex eption Error

path .

This le an then be used with

seed the PRNG again.

If the urrent RAND method supports any errors, this is raised when needed.

The default method

does not raise this when the entropy pool is depleted.
Whenever this ex eption is raised dire tly, it has a list of error messages from the OpenSSL error
queue, where ea h item is a tuple

(lib , fun tion , reason ).

strings, des ribing where and what the problem is. See

3.3

SSL

Here lib , fun tion and reason
err(3) for more information.

are all 

An interfa e to the SSL-spe i parts of OpenSSL

This module handles things spe i to SSL. There are two obje ts dened: Context, Conne tion.

SSLv2_METHOD
SSLv3_METHOD
SSLv23_METHOD
TLSv1_METHOD
These onstants represent the dierent SSL methods to use when reating a ontext obje t.

VERIFY_NONE
VERIFY_PEER
2 See

3.2

http://www.lothar. om/te h/ rypto/

rand 

An interfa e to the OpenSSL pseudo random number generator

11

VERIFY_FAIL_IF_NO_PEER_CERT
These onstants represent the veri ation mode used by the Context obje t's

FILETYPE_PEM
FILETYPE_ASN1
File type onstants used with the

use_ ertifi ate_file

and

set_verify method.

use_privatekey_file

methods of

Context obje ts.

OP_SINGLE_DH_USE
OP_EPHEMERAL_RSA
OP_NO_SSLv2
OP_NO_SSLv3
OP_NO_TLSv1

OP_SINGLE_DH_USE means to always reate a
OP_EPHEMERAL_RSA means to always use ephemeral RSA
keys when doing RSA operations. OP_NO_SSLv2, OP_NO_SSLv3 and OP_NO_TLSv1 means to disable those
spe i proto ols. This is interesting if you're using e.g. SSLv23_METHOD to get an SSLv2- ompatible
Constants used with

set_options of

Context obje ts.

new key when using ephemeral Die-Hellman.

handshake, but don't want to use SSLv2.

ContextType
See Context.

lass Context(method )

A lass representing SSL ontexts. Contexts dene the parameters of one or more SSL onne tions.

method

should be

SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD or TLSv1_METHOD.

Conne tionType
See Conne tion.

lass Conne tion( ontext, so ket )

A lass representing SSL onne tions.

ontext should be an instan e of Context and so ket should be a so ket 3 obje t. so ket may be
None ; in this ase, the Conne tion is reated with a memory BIO: see the bio_read, bio_write, and
bio_shutdown methods.

ex eption Error

This ex eption is used as a base lass for the other SSL-related ex eptions, but may also be raised
dire tly.
Whenever this ex eption is raised dire tly, it has a list of error messages from the OpenSSL error
queue, where ea h item is a tuple

(lib , fun tion , reason ).

strings, des ribing where and what the problem is. See

ex eption ZeroReturnError

This ex eption mat hes the error return ode

Here lib , fun tion and reason
err(3) for more information.

SSL_ERROR_ZERO_RETURN, and

are all

is raised when the SSL

Conne tion has been losed. In SSL 3.0 and TLS 1.0, this only o urs if a losure alert has o urred
in the proto ol, i.e. the onne tion has been losed leanly. Note that this does not ne essarily mean
that the transport layer (e.g. a so ket) has been losed.
It may seem a little strange that this is an ex eption, but it does mat h an

SSL_ERROR

ode, and is

very onvenient.

ex eption WantReadError

The operation did not omplete; the same I/O method should be alled again later, with the same
arguments. Any I/O method an lead to this sin e new handshakes an o ur at any time.

The wanted read is for

dirty

data sent over the network, not the

For a so ket based SSL onne tion,

read

lean

data inside the tunnel.

means data oming at us over the network.

Until that

3 A tually,

all that is required is an obje t that behaves like a so ket, you ould even use les, even though it'd be tri ky to
get the handshakes right!

12

3

OpenSSL 

Python interfa e to OpenSSL

OpenSSL.SSL.Conne tion.re v, OpenSSL.SSL.Conne tion.send, or
OpenSSL.SSL.Conne tion.do_handshake is prevented or in omplete. You probably want to sele t()

read su eeds, the attempted

on the so ket before trying again.

ex eption WantWriteError
WantReadError
ex eption WantX509LookupError
See

. The so ket send buer may be too full to write more data.

The operation did not omplete be ause an appli ation allba k has asked to be alled again. The I/O

method should be alled again later, with the same arguments. Note: This won't o ur in this version,
as there are no su h allba ks in this version.

ex eption SysCallError
The

SysCallError o urs when there's an I/O error and OpenSSL's error queue does not ontain any

information.

This an mean two things: An error in the transport proto ol, or an end of le that

violates the proto ol. The parameter to the ex eption is always a pair

(errnum , errstr ).

Context obje ts
Context obje ts have the following methods:

he k_privatekey()
use_privatekey[_file ℄) mat hes the erti ate
None if they mat h, raises Error otherwise.

Che k if the private key (loaded with

use_ ertifi ate[_file ℄).

Returns

get_app_data()
Retrieve appli ation data as set by

(loaded with

set_app_data.

get_ ert_store()
Retrieve the erti ate store (a X509Store obje t) that the ontext uses.
"trusted" erti ates without using the.

get_timeout()
Retrieve session timeout, as set by

This an be used to add

load_verify_lo ations() method.

set_timeout.

The default is 300 se onds.

get_verify_depth()
Retrieve the Context obje t's verify depth, as set by

get_verify_mode()
Retrieve the Context obje t's verify mode, as set by

set_verify_depth.
set_verify.

load_ lient_ a(pemle )
Read a le with PEM-formatted erti ates that will be sent to the lient when requesting a lient
erti ate.

set_ lient_ a_list( erti ate_authorities )
Repla e the urrent list of preferred erti ate signers that would be sent to the lient when requesting
a lient erti ate with the

erti ate_authorities

sequen e of

OpenSSL. rypto.X509Names.

New in version 0.10.

add_ lient_ a( erti ate_authority )
Extra t a OpenSSL. rypto.X509Name from the erti ate_authority OpenSSL. rypto.X509 erti ate
and add it to the list of preferred erti ate signers sent to the lient when requesting a lient erti ate.
New in version 0.10.

load_verify_lo ations(pemle, apath )
Spe ify where CA erti ates for veri ation purposes are lo ated. These are trusted erti ates. Note
that the erti ates have to be in PEM format. If apath is passed, it must be a dire tory prepared
using the

3.3

SSL

_rehash

tool in luded with OpenSSL. Either, but not both, of 

An interfa e to the SSL-spe i parts of OpenSSL

pemle

or

apath

may be

13

None.
set_default_verify_paths()
Spe ify that the platform provided CA erti ates are to be used for veri ation purposes. This method
may not work properly on OS X.

load_tmp_dh(dhle )
Load parameters for Ephemeral Die-Hellman from

dhle .

set_app_data(data )

data with this Context obje t. data
set_ ipher_list( iphers )
Asso iate

an be retrieved later using the

get_app_data method.

Set the list of iphers to be used in this ontext. See the OpenSSL manual for more information (e.g.
iphers(1))

set_info_ allba k( allba k )

allba k .

Set the information allba k to
handshakes.

allba k

This fun tion will be alled from time to time during SSL

should take three arguments: a Conne tion obje t and two integers. The rst

integer spe ies where in the SSL handshake the fun tion was alled, and the other the return ode
from a (possibly failed) internal fun tion all.

set_options(options )
Add SSL options. Options you have set before are not leared! This method should be used with the

OP_* onstants.

set_passwd_ b( allba k [, userdata ℄)
Set the passphrase allba k to
passphrase is loaded.

allba k

allba k .

This fun tion will be alled when a private key with a

must a ept three positional arguments.

First, an integer giving the

maximum length of the passphrase it may return. If the returned passphrase is longer than this, it
will be trun ated. Se ond, a boolean value whi h will be true if the user should be prompted for the
passphrase twi e and the allba k should verify that the two values supplied are equal.
value given as the

userdata

parameter to

set_passwd_ b.

If an error o urs,

allba k

Third, the

should return a

false value (e.g. an empty string).

set_session_id(name )
Set the ontext

name

within whi h a session an be reused for this Context obje t. This is needed

when doing session resumption, be ause there is no way for a stored session to know whi h Context
obje t it is asso iated with.

name

may be any binary data.

set_timeout(timeout )
Set the timeout for newly reated sessions for this Context obje t to

timeout . timeout

must be given

in (whole) se onds. The default value is 300 se onds. See the OpenSSL manual for more information
(e.g. SSL_CTX_set_timeout(3)).

set_verify(mode, allba k )
Set the veri ation ags for this Context obje t to
for veri ation allba ks.
used,

mode

mode

an be OR:ed with

ontrol the behaviour.

allba k

mode

and spe ify that

allba k

should be used

VERIFY_NONE and VERIFY_PEER. If VERIFY_PEER is
VERIFY_FAIL_IF_NO_PEER_CERT and VERIFY_CLIENT_ONCE to further
should be one of

should take ve arguments: A Conne tion obje t, an X509 obje t, and

three integer variables, whi h are in turn potential error number, error depth and return ode.

allba k

should return true if veri ation passes and false otherwise.

set_verify_depth(depth )
Set the maximum depth for the erti ate hain veri ation that shall be allowed for this Context
obje t.

use_ ertifi ate( ert )

ert whi h has to be a X509 obje t.
add_extra_ hain_ ert( ert )
Use the erti ate

14

3

OpenSSL 

Python interfa e to OpenSSL

Adds the erti ate

ert ,

whi h has to be a X509 obje t, to the erti ate hain presented together

with the erti ate.

use_ ertifi ate_ hain_file(le )
Load a erti ate hain from

use_privatekey(pkey )
Use the private key

pkey 

le

whi h must be PEM en oded.

whi h has to be a PKey obje t.

use_ ertifi ate_file(le [, format ℄)
Load the rst erti ate found in 

le .

The erti ate must be in the format spe ied by

FILETYPE_PEM or FILETYPE_ASN1.

is either

use_privatekey_file(le [, format ℄)
Load the rst private key found in
whi h is either 

le .

The default is

FILETYPE_PEM.

format , whi h

The private key must be in the format spe ied by

FILETYPE_PEM or FILETYPE_ASN1.

The default is

FILETYPE_PEM.

format ,

Conne tion obje ts
Conne tion obje ts have the following methods:

a ept()
Call the

a ept

method of the underlying so ket and set up SSL on the returned so ket, using the

Context obje t supplied to this Conne tion obje t at reation. Returns a pair

onn is the new Conne tion obje t reated, and address
bind(address )
Call the

lose()
Call the
all the

bind method

where

of the underlying so ket.

lose method of the underlying
shutdown method rst.

onne t(address )
Call the onne t

( onn , address ).
a ept.

is as returned by the so ket's

so ket. Note: If you want orre t SSL losure, you need to

method of the underlying so ket and set up SSL on the so ket, using the Context

obje t supplied to this Conne tion obje t at reation.

onne t_ex(address )
Call the onne t_ex method of the underlying so ket and set up SSL on the so ket, using the Context
obje t supplied to this Conne tion obje t at reation. Note that if the onne t_ex method of the
so ket doesn't return 0, SSL won't be initialized.

do_handshake()
Perform an SSL handshake (usually alled after

set_a ept_state).

renegotiate or one of set_a ept_state
send and re v.

or

This an raise the same ex eptions as

fileno()
Retrieve the le des riptor number for the underlying so ket.

listen(ba klog )
Call the listen method

of the underlying so ket.

get_app_data()
Retrieve appli ation data as set by

set_app_data.

get_ ipher_list()
Retrieve the list of iphers used by the Conne tion obje t. WARNING: This API has hanged. It used
to take an optional parameter and just return a string, but not it returns the entire list in one go.

get_ lient_ a_list()
Retrieve the list of preferred lient erti ate issuers sent by the server as

3.3

SSL 

An interfa e to the SSL-spe i parts of OpenSSL

OpenSSL. rypto.X509Name

15

obje ts.

Conne tion, the list will be empty until the onne tion with the server is established.

If this is a lient

If this is a server

Conne tion,

return the list of erti ate authorities that will be sent or has been

sent to the lient, as ontrolled by this

Conne tion's Context.

New in version 0.10.

get_ ontext()
Retrieve the Context obje t asso iated with this Conne tion.

get_peer_ ertifi ate()
Retrieve the other side's erti ate (if any)

getpeername()
Call the getpeername method

of the underlying so ket.

getso kname()
Call the getso kname method

of the underlying so ket.

getso kopt(level, optname [, buen ℄)
Call the getso kopt method of the

underlying so ket.

pending()

not the underlying transport

Retrieve the number of bytes that an be safely read from the SSL buer (
buer).

re v(bufsize )
Re eive data from the Conne tion. The return value is a string representing the data re eived. The
maximum amount of data to be re eived at on e, is spe ied by

bufsize .

bio_write(bytes )
If the Conne tion was reated with a memory BIO, this method an be used to add bytes to the read
end of that memory BIO. The Conne tion an then read the bytes (for example, in response to a all
to

re v).

renegotiate()
Renegotiate the SSL session. Call this if you wish to hange ipher suites or anything like that.

send(string )

string
bio_read(bufsize )
Send the

data to the Conne tion.

If the Conne tion was reated with a memory BIO, this method an be used to read bytes from the
write end of that memory BIO. Many Conne tion methods will add bytes whi h must be read in this
manner or the buer will eventually ll up and the Conne tion will be able to take no further a tions.

sendall(string )
Send all of the

string

data to the Conne tion. This alls

send

repeatedly until all data is sent. If an

error o urs, it's impossible to tell how mu h data has been sent.

set_a ept_state()
Set the onne tion to work in server mode. The handshake will be handled automati ally by read/write.

set_app_data(data )
Asso iate

data

with this Conne tion obje t.

data

an be retrieved later using the

get_app_data

method.

set_ onne t_state()
Set the onne tion to work in lient mode. The handshake will be handled automati ally by read/write.

setblo king(ag )
Call the setblo king method

16

of the underlying so ket.

3

OpenSSL 

Python interfa e to OpenSSL

setso kopt(level, optname, value )
Call the setso kopt method of

the underlying so ket.

shutdown()
Send the shutdown message to the Conne tion.

Returns true if the shutdown message ex hange is

ompleted and false otherwise (in whi h ase you all

re v() or send() when the onne tion be omes

readable/writeable.

get_shutdown()
Get

the

shutdown

SENT_SHUTDOWN
set_shutdown(state )

state
and

of

the

Conne tion.

Returns

RECEIVED_SHUTDOWN .

Set the shutdown state of the Conne tion.

RECEIVED_SHUTDOWN .
so k_shutdown(how )

a

bitve tor

of

either

or

both

of

state is a bitve tor of either or both of SENT_SHUTDOWN

and

Call the

shutdown method

of the underlying so ket.

bio_shutdown()
If the Conne tion was reated with a memory BIO, this method an be used to indi ate that end of 
le has been rea hed on the read end of that memory BIO.

state_string()
Retrieve a verbose string detailing the state of the Conne tion.

lient_random()
Retrieve the random value used with the lient hello message.

server_random()
Retrieve the random value used with the server hello message.

master_key()
Retrieve the value of the master key for this session.

want_read()
Che ks if more data has to be read from the transport layer to omplete an operation.

want_write()
Che ks if there is data to write to the transport layer to omplete an operation.

4 Internals
We ran into three main problems developing this: Ex eptions, allba ks and a essing so ket methods. This
is what this hapter is about.

4.1 Ex eptions
We realized early that most of the ex eptions would be raised by the I/O fun tions of OpenSSL,
so it felt natural to mimi OpenSSL's error ode system, translating them into Python ex eptions.

SSL.ZeroReturnError, SSL.WantReadError, SSL.WantWriteError,
SSL.WantX509LookupError and SSL.SysCallError.
This naturally gives us the ex eptions

For more information about this, see se tion 3.3.

17

4.2 Callba ks
There are a number of problems with allba ks. First of all, OpenSSL is written as a C library, it's not
meant to have Python allba ks, so a way around that is needed. Another problem is thread support. A lot
of the OpenSSL I/O fun tions an blo k if the so ket is in blo king mode, and then you want other Python
threads to be able to do other things. The real trouble is if you've released the global CPython interpreter
lo k to do a potentially blo king operation, and the operation alls a allba k. Then we must take the GIL
ba k, sin e alling Python APIs without holding it is not allowed.
There are two solutions to the rst problem, both of whi h are ne essary. The rst solution to use is if the C
allba k allows userdata to be passed to it (an arbitrary pointer normally). This is great! We an set our
Python fun tion obje t as the real userdata and emulate userdata for the Python fun tion in another way.
The other solution an be used if an obje t with an app_data system always is passed to the allba k. For
example, the SSL obje t in OpenSSL has app_data fun tions and in e.g. the veri ation allba ks, you an
retrieve the related SSL obje t. What we do is to set our wrapper

Conne tion obje t

as app_data for the

SSL obje t, and we an easily nd the Python allba k.
The other problem is solved using thread lo al variables. Whenever the GIL is released before alling into an

PyEval_SaveState is stored in a global thread lo al
PyThread_set_key_value). When it is ne essary to re-a quire the

OpenSSL API, the PyThreadState pointer returned by
variable (using Python's own TLS API,

GIL, either after the OpenSSL API returns or in a C allba k invoked by that OpenSSL API, the value of the

thread lo al variable is retrieved (PyThread_get_key_value) and used to re-a quire the GIL. This allows
Python threads to exe ute while OpenSSL APIs are running and allows use of any parti ular pyOpenSSL

obje t from any Python thread, sin e there is no per-thread state asso iated with any of these obje ts and
sin e OpenSSL is threadsafe (as long as properly initialized, as pyOpenSSL initializes it).

4.3 A essing So ket Methods
SSL.Conne tion lass, for an easy transition
so ket module la ks a C API, and all the methods are de lared
to have OpenSSL as a submodule to the so ket module, pla ing all the ode

We qui kly saw the benet of wrapping so ket methods in the
into using SSL. The problem here is that the
stati . One approa h would be

in `so ketmodule. ', but this is obviously not a good solution, sin e you might not want to import tonnes of
extra stu you're not going to use when importing the

so ket module.

The other approa h is to somehow

get a pointer to the method to be alled, either the C fun tion, or a allable Python obje t. This is not
really a good solution either, sin e there's a lot of lookups involved.
The way it works is that you have to supply a  so ket-like transport obje t to the

SSL.Conne tion. The
fileno() method that returns a le des riptor that's valid at
the C level (i.e. you an use the system alls read and write). If you want to use the onne t() or a ept()
methods of the SSL.Conne tion obje t, the transport obje t has to supply su h methods too. Apart from
them, any method lookups in the SSL.Conne tion obje t that fail are passed on to the underlying transport
only requirement of this obje t is that it has a

obje t.
Future hanges might be to allow Python-level transport obje ts, that instead of having
have

read() and write() methods, so more advan ed features of Python an be used.

fileno() methods,

This would probably

entail some sort of OpenSSL BIOs, but onverting Python strings ba k and forth is expensive, so this
shouldn't be used unless ne essary.

Other ni e things would be to be able to pass in dierent transport

obje ts for reading and writing, but then the

fileno()

method of

SSL.Conne tion

be omes virtually

useless. Also, should the method resolution be used on the read-transport or the write-transport?

18

4 Internals