blob: 9b688692ed8102b48c536f99d47b473cbea91a06 [file] [log] [blame]
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001\documentclass{howto}
2
3\title{Python OpenSSL Manual}
4
5\release{0.6}
6
7\author{Martin Sjögren}
8\authoraddress{\email{martin@strakt.com}}
9
10\usepackage[english]{babel}
11\usepackage[T1]{fontenc}
12
13\begin{document}
14
15\maketitle
16
17\begin{abstract}
18\noindent
19This module is a rather thin wrapper around (a subset of) the OpenSSL library.
20With thin wrapper I mean that a lot of the object methods do nothing more than
21calling a corresponding function in the OpenSSL library.
22\end{abstract}
23
24\tableofcontents
25
26
27\section{Introduction \label{intro}}
28
29The reason this module exists at all is that the SSL support in the socket
30module in the Python 2.1 distribution (which is what we used, of course I
31cannot speak for later versions) is severely limited.
32
33When asking about SSL on the comp.lang.python newsgroup (or on
34python-list@python.org) people usually pointed you to the M2Crypto package.
35The M2Crypto.SSL module does implement a lot of OpenSSL's functionality but
36unfortunately its error handling system does not seem to be finished,
37especially for non-blocking I/O. I think that much of the reason for this
38is that M2Crypto\footnote{See \url{http://www.post1.com/home/ngps/m2/}} is
39developed using SWIG\footnote{See \url{http://swig.sourceforge.net/}}. This
40makes it awkward to create functions that e.g. can return both an integer and
41NULL since (as far as I know) you basically write C functions and SWIG makes
42wrapper functions that parses the Python argument list and calls your C
43function, and finally transforms your return value to a Python object.
44
45
46\section{Building and Installing \label{building}}
47
48These instructions can also be found in the file \verb|INSTALL|.
49
50I have tested this on Debian Linux systems (woody and sid), Solaris 2.6 and
512.7. Others have successfully compiled it on Windows and NT.
52
53\subsection{Building the Module on a Unix System \label{building-unix}}
54
55pyOpenSSL uses distutils, so there really shouldn't be any problems. To build
56the library:
57\begin{verbatim}
58python setup.py build
59\end{verbatim}
60
61If your OpenSSL header files aren't in \verb|/usr/include|, you may need to
62supply the \verb|-I| flag to let the setup script know where to look. The same
63goes for the libraries of course, use the \verb|-L| flag. Note that
64\verb|build| won't accept these flags, so you have to run first
65\verb|build_ext| and then \verb|build|! Example:
66\begin{verbatim}
67python setup.py build_ext -I/usr/local/ssl/include -L/usr/local/ssl/lib
68python setup.py build
69\end{verbatim}
70
71Now you should have a directory called \verb|OpenSSL| that contains e.g.
72\verb|SSL.so| and \verb|__init__.py| somewhere in the build dicrectory,
73so just:
74\begin{verbatim}
75python setup.py install
76\end{verbatim}
77
78If you, for some arcane reason, don't want the module to appear in the
79\verb|site-packages| directory, use the \verb|--prefix| option.
80
81You can, of course, do
82\begin{verbatim}
83python setup.py --help
84\end{verbatim}
85
86to find out more about how to use the script.
87
88\subsection{Building the Module on a Windows System \label{building-windows}}
89
90Big thanks to Itamar Shtull-Trauring and Oleg Orlov for their help with
91Windows build instructions. Same as for Unix systems, we have to separate
92the \verb|build_ext| and the \verb|build|.
93
94Building the library:
95
96\begin{verbatim}
97setup.py build_ext -I ...\openssl\inc32 -L ...\openssl\out32dll
98setup.py build
99\end{verbatim}
100
101Where \verb|...\openssl| is of course the location of your OpenSSL installation.
102
103Installation is the same as for Unix systems:
104\begin{verbatim}
105setup.py install
106\end{verbatim}
107
108And similarily, you can do
109\begin{verbatim}
110setup.py --help
111\end{verbatim}
112
113to get more information.
114
115
116\section{\module{OpenSSL} --- Python interface to OpenSSL \label{openssl}}
117
118\declaremodule{extension}{OpenSSL}
119\modulesynopsis{Python interface to OpenSSL}
120
121This package provides a high-level interface to the functions in the
122OpenSSL library. The following modules are defined:
123
124\begin{datadesc}{crypto}
125Generic cryptographic module. Note that if anything is incomplete, this module is!
126\end{datadesc}
127
128\begin{datadesc}{rand}
129An interface to the OpenSSL pseudo random number generator.
130\end{datadesc}
131
132\begin{datadesc}{SSL}
133An interface to the SSL-specific parts of OpenSSL.
134\end{datadesc}
135
136
137% % % crypto moduleOpenSSL
138
139\subsection{\module{crypto} --- Generic cryptographic module \label{openssl-crypto}}
140
141\declaremodule{extension}{crypto}
142\modulesynopsis{Generic cryptographic module}
143
144\begin{datadesc}{X509Type}
145A Python type object representing the X509 object type.
146\end{datadesc}
147
148\begin{funcdesc}{X509}{}
149Factory function that creates an X509 object.
150\end{funcdesc}
151
152\begin{datadesc}{X509NameType}
153A Python type object representing the X509Name object type.
154\end{datadesc}
155
156\begin{funcdesc}{X509Name}{x509name}
157Factory function that creates a copy of \var{x509name}.
158\end{funcdesc}
159
160\begin{datadesc}{X509ReqType}
161A Python type object representing the X509Req object type.
162\end{datadesc}
163
164\begin{funcdesc}{X509Req}{}
165Factory function that creates an X509Req object.
166\end{funcdesc}
167
168\begin{datadesc}{X509StoreType}
169A Python type object representing the X509Store object type.
170\end{datadesc}
171
172\begin{datadesc}{PKeyType}
173A Python type object representing the PKey object type.
174\end{datadesc}
175
176\begin{funcdesc}{PKey}{}
177Factory function that creates a PKey object.
178\end{funcdesc}
179
180\begin{datadesc}{PKCS7Type}
181A Python type object representing the PKCS7 object type.
182\end{datadesc}
183
184\begin{datadesc}{PKCS12Type}
185A Python type object representing the PKCS12 object type.
186\end{datadesc}
187
188\begin{datadesc}{X509ExtensionType}
189A Python type object representing the X509Extension object type.
190\end{datadesc}
191
192\begin{funcdesc}{X509Extension}{typename, critical, value}
193Factory function that creates a X509Extension object.
194\end{funcdesc}
195
196\begin{datadesc}{NetscapeSPKIType}
197A Python type object representing the NetscapeSPKI object type.
198\end{datadesc}
199
200\begin{funcdesc}{NetscapeSPKI}{\optional{enc}}
201Factory function that creates a NetscapeSPKI object. If the \var{enc} argument
202is present, it should be a base64-encoded string representing a NetscapeSPKI
203object, as returned by the \method{b64_encode} method.
204\end{funcdesc}
205
206\begin{datadesc}{FILETYPE_PEM}
207\dataline{FILETYPE_ASN1}
208File type constants.
209\end{datadesc}
210
211\begin{datadesc}{TYPE_RSA}
212\dataline{TYPE_DSA}
213Key type constants.
214\end{datadesc}
215
216\begin{excdesc}{Error}
217Generic exception used in the \module{crypto} module.
218\end{excdesc}
219
220\begin{funcdesc}{dump_certificate}{type, cert}
221Dump the certificate \var{cert} into a buffer string encoded with the type
222\var{type}.
223\end{funcdesc}
224
225\begin{funcdesc}{dump_certificate_request}{type, req}
226Dump the certificate request \var{req} into a buffer string encoded with the
227type \var{type}.
228\end{funcdesc}
229
230\begin{funcdesc}{dump_privatekey}{type, pkey\optional{, cipher, passphrase}}
231Dump the private key \var{pkey} into a buffer string encoded with the type
232\var{type}, optionally (if \var{type} is \constant{FILETYPE_PEM}) encrypting it
233using \var{cipher} and \var{passphrase}.
234
235\var{passphrase} must be either a string or a callback for providing the
236pass phrase.
237\end{funcdesc}
238
239\begin{funcdesc}{load_certificate}{type, buffer}
240Load a certificate (X509) from the string \var{buffer} encoded with the
241type \var{type}.
242\end{funcdesc}
243
244\begin{funcdesc}{load_certificate_request}{type, buffer}
245Load a certificate request (X509Req) from the string \var{buffer} encoded with
246the type \var{type}.
247\end{funcdesc}
248
249\begin{funcdesc}{load_privatekey}{type, buffer\optional{, passphrase}}
250Load a private key (PKey) from the string \var{buffer} encoded with
251the type \var{type} (must be one of \constant{FILETYPE_PEM} and
252\constant{FILETYPE_ASN1}).
253
254\var{passphrase} must be either a string or a callback for providing the
255pass phrase.
256\end{funcdesc}
257
258\begin{funcdesc}{load_pkcs7_data}{type, buffer}
259Load pkcs7 data from the string \var{buffer} encoded with the type \var{type}.
260\end{funcdesc}
261
262\begin{funcdesc}{load_pkcs12}{buffer\optional{, passphrase}}
263Load pkcs12 data from the string \var{buffer}. If the pkcs12 structure is
264encrypted, a \var{passphrase} must be included.
265\end{funcdesc}
266
267
268\subsubsection{X509 objects \label{openssl-x509}}
269
270X509 objects have the following methods:
271
272\begin{methoddesc}[X509]{get_issuer}{}
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -0500273Return an X509Name object representing the issuer of the certificate.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500274\end{methoddesc}
275
276\begin{methoddesc}[X509]{get_pubkey}{}
277Return a PKey object representing the public key of the certificate.
278\end{methoddesc}
279
280\begin{methoddesc}[X509]{get_serial_number}{}
281Return the certificate serial number.
282\end{methoddesc}
283
284\begin{methoddesc}[X509]{get_subject}{}
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -0500285Return an X509Name object representing the subject of the certificate.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500286\end{methoddesc}
287
288\begin{methoddesc}[X509]{get_version}{}
289Return the certificate version.
290\end{methoddesc}
291
292\begin{methoddesc}[X509]{gmtime_adj_notBefore}{time}
293Adjust the timestamp (in GMT) when the certificate starts being valid.
294\end{methoddesc}
295
296\begin{methoddesc}[X509]{gmtime_adj_notAfter}{time}
297Adjust the timestamp (in GMT) when the certificate stops being valid.
298\end{methoddesc}
299
300\begin{methoddesc}[X509]{has_expired}{}
301Checks the certificate's time stamp against current time. Returns true if the
302certificate has expired and false otherwise.
303\end{methoddesc}
304
305\begin{methoddesc}[X509]{set_issuer}{issuer}
306Set the issuer of the certificate to \var{issuer}.
307\end{methoddesc}
308
309\begin{methoddesc}[X509]{set_pubkey}{pkey}
310Set the public key of the certificate to \var{pkey}.
311\end{methoddesc}
312
313\begin{methoddesc}[X509]{set_serial_number}{serialno}
314Set the serial number of the certificate to \var{serialno}.
315\end{methoddesc}
316
317\begin{methoddesc}[X509]{set_subject}{subject}
318Set the subject of the certificate to \var{subject}.
319\end{methoddesc}
320
321\begin{methoddesc}[X509]{set_version}{version}
322Set the certificate version to \var{version}.
323\end{methoddesc}
324
325\begin{methoddesc}[X509]{sign}{pkey, digest}
326Sign the certificate, using the key \var{pkey} and the message digest algorithm
327identified by the string \var{digest}.
328\end{methoddesc}
329
330\begin{methoddesc}[X509]{subject_name_hash}{}
331Return the hash of the certificate subject.
332\end{methoddesc}
333
334\begin{methoddesc}[X509]{digest}{digest_name}
335Return a digest of the certificate, using the \var{digest_name} method.
336\end{methoddesc}
337
338\begin{methoddesc}[X509]{add_extensions}{extensions}
339Add the extensions in the sequence \var{extensions} to the certificate.
340\end{methoddesc}
341
342\subsubsection{X509Name objects \label{openssl-x509name}}
343
344X509Name objects have the following members:
345
346\begin{memberdesc}[X509Name]{countryName}
347The country of the entity. \code{C} may be used as an alias for
348\code{countryName}.
349\end{memberdesc}
350
351\begin{memberdesc}[X509Name]{stateOrProvinceName}
352The state or province of the entity. \code{ST} may be used as an alias for
353\code{stateOrProvinceName}·
354\end{memberdesc}
355
356\begin{memberdesc}[X509Name]{localityName}
357The locality of the entity. \code{L} may be used as an alias for
358\code{localityName}.
359\end{memberdesc}
360
361\begin{memberdesc}[X509Name]{organizationName}
362The organization name of the entity. \code{O} may be used as an alias for
363\code{organizationName}.
364\end{memberdesc}
365
366\begin{memberdesc}[X509Name]{organizationalUnitName}
367The organizational unit of the entity. \code{OU} may be used as an alias for
368\code{organizationalUnitName}.
369\end{memberdesc}
370
371\begin{memberdesc}[X509Name]{commonName}
372The common name of the entity. \code{CN} may be used as an alias for
373\code{commonName}.
374\end{memberdesc}
375
376\begin{memberdesc}[X509Name]{emailAddress}
377The e-mail address of the entity.
378\end{memberdesc}
379
380\subsubsection{X509Req objects \label{openssl-x509req}}
381
382X509Req objects have the following methods:
383
384\begin{methoddesc}[X509Req]{get_pubkey}{}
385Return a PKey object representing the public key of the certificate request.
386\end{methoddesc}
387
388\begin{methoddesc}[X509Req]{get_subject}{}
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -0500389Return an X509Name object representing the subject of the certificate.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500390\end{methoddesc}
391
392\begin{methoddesc}[X509Req]{set_pubkey}{pkey}
393Set the public key of the certificate request to \var{pkey}.
394\end{methoddesc}
395
396\begin{methoddesc}[X509Req]{sign}{pkey, digest}
397Sign the certificate request, using the key \var{pkey} and the message digest
398algorithm identified by the string \var{digest}.
399\end{methoddesc}
400
401\begin{methoddesc}[X509Req]{verify}{pkey}
402Verify a certificate request using the public key \var{pkey}.
403\end{methoddesc}
404
405\subsubsection{X509Store objects \label{openssl-x509store}}
406
407The X509Store object has currently just one method:
408
409\begin{methoddesc}[X509Store]{add_cert}{cert}
410Add the certificate \var{cert} to the certificate store.
411\end{methoddesc}
412
413\subsubsection{PKey objects \label{openssl-pkey}}
414
415The PKey object has the following methods:
416
417\begin{methoddesc}[PKey]{bits}{}
418Return the number of bits of the key.
419\end{methoddesc}
420
421\begin{methoddesc}[PKey]{generate_key}{type, bits}
422Generate a public/private key pair of the type \var{type} (one of
423\constant{TYPE_RSA} and \constant{TYPE_DSA}) with the size \var{bits}.
424\end{methoddesc}
425
426\begin{methoddesc}[PKey]{type}{}
427Return the type of the key.
428\end{methoddesc}
429
430\subsubsection{PKCS7 objects \label{openssl-pkcs7}}
431
432PKCS7 objects have the following methods:
433
434\begin{methoddesc}[PKCS7]{type_is_signed}{}
435FIXME
436\end{methoddesc}
437
438\begin{methoddesc}[PKCS7]{type_is_enveloped}{}
439FIXME
440\end{methoddesc}
441
442\begin{methoddesc}[PKCS7]{type_is_signedAndEnveloped}{}
443FIXME
444\end{methoddesc}
445
446\begin{methoddesc}[PKCS7]{type_is_data}{}
447FIXME
448\end{methoddesc}
449
450\begin{methoddesc}[PKCS7]{get_type_name}{}
451Get the type name of the PKCS7.
452\end{methoddesc}
453
454\subsubsection{PKCS12 objects \label{openssl-pkcs12}}
455
456PKCS12 objects have the following methods:
457
458\begin{methoddesc}[PKCS12]{get_certificate}{}
459Return certificate portion of the PKCS12 structure.
460\end{methoddesc}
461
462\begin{methoddesc}[PKCS12]{get_privatekey}{}
463Return private key portion of the PKCS12 structure
464\end{methoddesc}
465
466\begin{methoddesc}[PKCS12]{get_ca_certificates}{}
467Return CA certificates within the PKCS12 object as a tuple. Returns
468None if no CA certificates are present.
469\end{methoddesc}
470
471\subsubsection{X509Extension objects \label{openssl-509ext}}
472
473X509Extension objects currently only have one method:
474
475\begin{methoddesc}[X509Extension]{get_critical}{}
476Return the critical field of the extension object.
477\end{methoddesc}
478
479\subsubsection{NetscapeSPKI objects \label{openssl-netscape-spki}}
480
481NetscapeSPKI objects have the following methods:
482
483\begin{methoddesc}[NetscapeSPKI]{b64_encode}{}
484Return a base64-encoded string representation of the object.
485\end{methoddesc}
486
487\begin{methoddesc}[NetscapeSPKI]{get_pubkey}{}
488Return the public key of object.
489\end{methoddesc}
490
491\begin{methoddesc}[NetscapeSPKI]{set_pubkey}{key}
492Set the public key of the object to \var{key}.
493\end{methoddesc}
494
495\begin{methoddesc}[NetscapeSPKI]{sign}{key, digest_name}
496Sign the NetscapeSPKI object using the given \var{key} and \var{digest_name}.
497\end{methoddesc}
498
499\begin{methoddesc}[NetscapeSPKI]{verify}{key}
500Verify the NetscapeSPKI object using the given \var{key}.
501\end{methoddesc}
502
503
504% % % rand module
505
506\subsection{\module{rand} --- An interface to the OpenSSL pseudo random number generator \label{openssl-rand}}
507
508\declaremodule{extension}{rand}
509\modulesynopsis{An interface to the OpenSSL pseudo random number generator}
510
511This module handles the OpenSSL pseudo random number generator (PRNG) and
512declares the following:
513
514\begin{funcdesc}{add}{string, entropy}
515Mix bytes from \var{string} into the PRNG state. The \var{entropy} argument is
516(the lower bound of) an estimate of how much randomness is contained in
517\var{string}, measured in bytes. For more information, see e.g. \rfc{1750}.
518\end{funcdesc}
519
520\begin{funcdesc}{egd}{path\optional{, bytes}}
521Query the Entropy Gathering Daemon\footnote{See
522\url{http://www.lothar.com/tech/crypto/}} on socket \var{path} for \var{bytes}
523bytes of random data and and uses \function{add} to seed the PRNG. The default
524value of \var{bytes} is 255.
525\end{funcdesc}
526
527\begin{funcdesc}{load_file}{path\optional{, bytes}}
528Read \var{bytes} bytes (or all of it, if \var{bytes} is negative) of data from
529the file \var{path} to seed the PRNG. The default value of \var{bytes} is -1.
530\end{funcdesc}
531
532\begin{funcdesc}{screen}{}
533Add the current contents of the screen to the PRNG state.
534Availability: Windows.
535\end{funcdesc}
536
537\begin{funcdesc}{seed}{string}
538This is equivalent to calling \function{add} with \var{entropy} as the length
539of the string.
540\end{funcdesc}
541
542\begin{funcdesc}{status}{}
543Returns true if the PRNG has been seeded with enough data, and false otherwise.
544\end{funcdesc}
545
546\begin{funcdesc}{write_file}{path}
547Write a number of random bytes (currently 1024) to the file \var{path}. This
548file can then be used with \function{load_file} to seed the PRNG again.
549\end{funcdesc}
550
551
552
553% % % SSL module
554
555\subsection{\module{SSL} --- An interface to the SSL-specific parts of OpenSSL \label{openssl-ssl}}
556
557\declaremodule{extension}{SSL}
558\modulesynopsis{An interface to the SSL-specific parts of OpenSSL}
559
560This module handles things specific to SSL. There are two objects defined:
561Context, Connection.
562
563\begin{datadesc}{SSLv2_METHOD}
564\dataline{SSLv3_METHOD}
565\dataline{SSLv23_METHOD}
566\dataline{TLSv1_METHOD}
567These constants represent the different SSL methods to use when creating a
568context object.
569\end{datadesc}
570
571\begin{datadesc}{VERIFY_NONE}
572\dataline{VERIFY_PEER}
573\dataline{VERIFY_FAIL_IF_NO_PEER_CERT}
574These constants represent the verification mode used by the Context
575object's \method{set_verify} method.
576\end{datadesc}
577
578\begin{datadesc}{FILETYPE_PEM}
579\dataline{FILETYPE_ASN1}
580File type constants used with the \method{use_certificate_file} and
581\method{use_privatekey_file} methods of Context objects.
582\end{datadesc}
583
584\begin{datadesc}{OP_SINGLE_DH_USE}
585\dataline{OP_EPHEMERAL_RSA}
586\dataline{OP_NO_SSLv2}
587\dataline{OP_NO_SSLv3}
588\dataline{OP_NO_TLSv1}
589Constants used with \method{set_options} of Context objects.
590\constant{OP_SINGLE_DH_USE} means to always create a new key when using ephemeral
591Diffie-Hellman. \constant{OP_EPHEMERAL_RSA} means to always use ephemeral RSA keys
592when doing RSA operations. \constant{OP_NO_SSLv2}, \constant{OP_NO_SSLv3} and
593\constant{OP_NO_TLSv1} means to disable those specific protocols. This is
594interesting if you're using e.g. \constant{SSLv23_METHOD} to get an SSLv2-compatible
595handshake, but don't want to use SSLv2.
596\end{datadesc}
597
598\begin{datadesc}{ContextType}
599A Python type object representing the Context object type.
600\end{datadesc}
601
602\begin{funcdesc}{Context}{method}
603Factory function that creates a new Context object given an SSL method. The
604method should be \constant{SSLv2_METHOD}, \constant{SSLv3_METHOD},
605\constant{SSLv23_METHOD} or \constant{TLSv1_METHOD}.
606\end{funcdesc}
607
608\begin{datadesc}{ConnectionType}
609A Python type object representing the Connection object type.
610\end{datadesc}
611
612\begin{funcdesc}{Connection}{context, socket}
613Factory fucnction that creates a new Connection object given an SSL context and
614a socket \footnote{Actually, all that is required is an object that
615\emph{behaves} like a socket, you could even use files, even though it'd be
616tricky to get the handshakes right!} object.
617\end{funcdesc}
618
619\begin{excdesc}{Error}
620This exception is used as a base class for the other SSL-related
621exceptions, but may also be raised directly.
622
623Whenever this exception is raised directly, it has a list of error messages
624from the OpenSSL error queue, where each item is a tuple \code{(\var{lib},
625\var{function}, \var{reason})}. Here \var{lib}, \var{function} and \var{reason}
626are all strings, describing where and what the problem is. See \manpage{err}{3}
627for more information.
628\end{excdesc}
629
630\begin{excdesc}{ZeroReturnError}
631This exception matches the error return code \code{SSL_ERROR_ZERO_RETURN}, and
632is raised when the SSL Connection has been closed. In SSL 3.0 and TLS 1.0, this
633only occurs if a closure alert has occurred in the protocol, i.e. the
634connection has been closed cleanly. Note that this does not necessarily
635mean that the transport layer (e.g. a socket) has been closed.
636
637It may seem a little strange that this is an exception, but it does match an
638\code{SSL_ERROR} code, and is very convenient.
639\end{excdesc}
640
641\begin{excdesc}{WantReadError}
642The operation did not complete; the same I/O method should be called again
643later, with the same arguments. Any I/O method can lead to this since new
644handshakes can occur at any time.
645\end{excdesc}
646
647\begin{excdesc}{WantWriteError}
648See \exception{WantReadError}.
649\end{excdesc}
650
651\begin{excdesc}{WantX509LookupError}
652The operation did not complete because an application callback has asked to be
653called again. The I/O method should be called again later, with the same
654arguments. Note: This won't occur in this version, as there are no such
655callbacks in this version.
656\end{excdesc}
657
658\begin{excdesc}{SysCallError}
659The \exception{SysCallError} occurs when there's an I/O error and OpenSSL's
660error queue does not contain any information. This can mean two things: An
661error in the transport protocol, or an end of file that violates the protocol.
662The parameter to the exception is always a pair \code{(\var{errnum},
663\var{errstr})}.
664\end{excdesc}
665
666
667\subsubsection{Context objects \label{openssl-context}}
668
669Context objects have the following methods:
670
671\begin{methoddesc}[Context]{check_privatekey}{}
672Check if the private key (loaded with \method{use_privatekey\optional{_file}})
673matches the certificate (loaded with \method{use_certificate\optional{_file}}).
674Returns true if they match, false otherwise.
675\end{methoddesc}
676
677\begin{methoddesc}[Context]{get_app_data}{}
678Retrieve application data as set by \method{set_app_data}.
679\end{methoddesc}
680
681\begin{methoddesc}[Context]{get_cert_store}{}
682Retrieve the certificate store (a X509Store object) that the context uses.
683This can be used to add "trusted" certificates without using the.
684\method{load_verify_locations()} method.
685\end{methoddesc}
686
687\begin{methoddesc}[Context]{get_timeout}{}
688Retrieve session timeout, as set by \method{set_timeout}. The default is 300
689seconds.
690\end{methoddesc}
691
692\begin{methoddesc}[Context]{get_verify_depth}{}
693Retrieve the Context object's verify depth, as set by
694\method{set_verify_depth}.
695\end{methoddesc}
696
697\begin{methoddesc}[Context]{get_verify_mode}{}
698Retrieve the Context object's verify mode, as set by \method{set_verify_mode}.
699\end{methoddesc}
700
701\begin{methoddesc}[Context]{load_client_ca}{pemfile}
702Read a file with PEM-formatted certificates that will be sent to the client
703when requesting a client certificate.
704\end{methoddesc}
705
706\begin{methoddesc}[Context]{load_verify_locations}{pemfile}
707Specify where CA certificates for verification purposes are located. These are
708trusted certificates. Note that the certificates have to be in PEM format.
709\end{methoddesc}
710
711\begin{methoddesc}[Context]{load_tmp_dh}{dhfile}
712Load parameters for Ephemeral Diffie-Hellman from \var{dhfile}.
713\end{methoddesc}
714
715\begin{methoddesc}[Context]{set_app_data}{data}
716Associate \var{data} with this Context object. \var{data} can be retrieved
717later using the \method{get_app_data} method.
718\end{methoddesc}
719
720\begin{methoddesc}[Context]{set_cipher_list}{ciphers}
721Set the list of ciphers to be used in this context. See the OpenSSL manual for
722more information (e.g. ciphers(1))
723\end{methoddesc}
724
725\begin{methoddesc}[Context]{set_info_callback}{callback}
726Set the information callback to \var{callback}. This function will be called
727from time to time during SSL handshakes.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500728\var{callback} should take three arguments: a Connection object and two
729integers. The first integer specifies where in the SSL handshake the function
730was called, and the other the return code from a (possibly failed) internal
731function call.
732\end{methoddesc}
733
734\begin{methoddesc}[Context]{set_options}{options}
735Add SSL options. Options you have set before are not cleared!
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500736This method should be used with the \constant{OP_*} constants.
737\end{methoddesc}
738
739\begin{methoddesc}[Context]{set_passwd_cb}{callback\optional{, userdata}}
740Set the passphrase callback to \var{callback}. This function will be called
741when a private key with a passphrase is loaded.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500742\var{callback} should take a boolean argument \var{repeat} and an arbitrary
743argument \var{data} and return the passphrase entered by the user. If
744\var{repeat} is true then \var{callback} should ask for the passphrase twice
745and make sure that the two entries are equal. The \var{data} argument is the
746\var{userdata} variable passed to the \method{set_passwd_cb} method. If an
747error occurs, \var{callback} should return a false value (e.g. an empty
748string).
749\end{methoddesc}
750
751\begin{methoddesc}[Context]{set_session_id}{name}
752Set the context \var{name} within which a session can be reused for this
753Context object. This is needed when doing session resumption, because there is
754no way for a stored session to know which Context object it is associated with.
755\var{name} may be any binary data.
756\end{methoddesc}
757
758\begin{methoddesc}[Context]{set_timeout}{timeout}
759Set the timeout for newly created sessions for this Context object to
760\var{timeout}. \var{timeout} must be given in (whole) seconds. The default
761value is 300 seconds. See the OpenSSL manual for more information (e.g.
762SSL_CTX_set_timeout(3)).
763\end{methoddesc}
764
765\begin{methoddesc}[Context]{set_verify}{mode, callback}
766Set the verification flags for this Context object to \var{mode} and specify
767that \var{callback} should be used for verification callbacks. \var{mode}
768should be one of \constant{VERIFY_NONE} and \constant{VERIFY_PEER}. If
769\constant{VERIFY_PEER} is used, \var{mode} can be OR:ed with
770\constant{VERIFY_FAIL_IF_NO_PEER_CERT} and \constant{VERIFY_CLIENT_ONCE} to
771further control the behaviour.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500772\var{callback} should take five arguments: A Connection object, an X509 object,
773and three integer variables, which are in turn potential error number, error
774depth and return code. \var{callback} should return true if verification passes
775and false otherwise.
776\end{methoddesc}
777
778\begin{methoddesc}[Context]{set_verify_depth}{depth}
779Set the maximum depth for the certificate chain verification that shall be
780allowed for this Context object.
781\end{methoddesc}
782
783\begin{methoddesc}[Context]{use_certificate}{cert}
784Use the certificate \var{cert} which has to be a X509 object.
785\end{methoddesc}
786
Jean-Paul Calderone87b40602008-02-19 21:13:25 -0500787\begin{methoddesc}[Context]{add_extra_chain_cert}{cert}
788Adds the certificate \var{cert}, which has to be a X509 object, to the
789certificate chain presented together with the certificate.
790\end{methoddesc}
791
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500792\begin{methoddesc}[Context]{use_certificate_chain_file}{file}
793Load a certificate chain from \var{file} which must be PEM encoded.
794\end{methoddesc}
795
796\begin{methoddesc}[Context]{use_privatekey}{pkey}
797Use the private key \var{pkey} which has to be a PKey object.
798\end{methoddesc}
799
800\begin{methoddesc}[Context]{use_certificate_file}{file\optional{, format}}
801Load the first certificate found in \var{file}. The certificate must be in the
802format specified by \var{format}, which is either \constant{FILETYPE_PEM} or
803\constant{FILETYPE_ASN1}. The default is \constant{FILETYPE_PEM}.
804\end{methoddesc}
805
806\begin{methoddesc}[Context]{use_privatekey_file}{file\optional{, format}}
807Load the first private key found in \var{file}. The private key must be in the
808format specified by \var{format}, which is either \constant{FILETYPE_PEM} or
809\constant{FILETYPE_ASN1}. The default is \constant{FILETYPE_PEM}.
810\end{methoddesc}
811
812
813\subsubsection{Connection objects \label{openssl-connection}}
814
815Connection objects have the following methods:
816
817\begin{methoddesc}[Connection]{accept}{}
818Call the \method{accept} method of the underlying socket and set up SSL on the
819returned socket, using the Context object supplied to this Connection object at
820creation. Returns a pair \code{(\var{conn}, \var{address})}. where \var{conn}
821is the new Connection object created, and \var{address} is as returned by the
822socket's \method{accept}.
823\end{methoddesc}
824
825\begin{methoddesc}[Connection]{bind}{address}
826Call the \method{bind} method of the underlying socket.
827\end{methoddesc}
828
829\begin{methoddesc}[Connection]{close}{}
830Call the \method{close} method of the underlying socket. Note: If you want
831correct SSL closure, you need to call the \method{shutdown} method first.
832\end{methoddesc}
833
834\begin{methoddesc}[Connection]{connect}{address}
835Call the \method{connect} method of the underlying socket and set up SSL on the
836socket, using the Context object supplied to this Connection object at
837creation.
838\end{methoddesc}
839
840\begin{methoddesc}[Connection]{connect_ex}{address}
841Call the \method{connect_ex} method of the underlying socket and set up SSL on
842the socket, using the Context object supplied to this Connection object at
843creation. Note that if the \method{connect_ex} method of the socket doesn't
844return 0, SSL won't be initialized.
845\end{methoddesc}
846
847\begin{methoddesc}[Connection]{do_handshake}{}
848Perform an SSL handshake (usually called after \method{renegotiate} or one of
849\method{set_accept_state} or \method{set_accept_state}). This can raise the
850same exceptions as \method{send} and \method{recv}.
851\end{methoddesc}
852
853\begin{methoddesc}[Connection]{fileno}{}
854Retrieve the file descriptor number for the underlying socket.
855\end{methoddesc}
856
857\begin{methoddesc}[Connection]{listen}{backlog}
858Call the \method{listen} method of the underlying socket.
859\end{methoddesc}
860
861\begin{methoddesc}[Connection]{get_app_data}{}
862Retrieve application data as set by \method{set_app_data}.
863\end{methoddesc}
864
865\begin{methoddesc}[Connection]{get_cipher_list}{}
866Retrieve the list of ciphers used by the Connection object. WARNING: This API
867has changed. It used to take an optional parameter and just return a string,
868but not it returns the entire list in one go.
869\end{methoddesc}
870
871\begin{methoddesc}[Connection]{get_context}{}
872Retrieve the Context object associated with this Connection.
873\end{methoddesc}
874
875\begin{methoddesc}[Connection]{get_peer_certificate}{}
876Retrieve the other side's certificate (if any)
877\end{methoddesc}
878
879\begin{methoddesc}[Connection]{getpeername}{}
880Call the \method{getpeername} method of the underlying socket.
881\end{methoddesc}
882
883\begin{methoddesc}[Connection]{getsockname}{}
884Call the \method{getsockname} method of the underlying socket.
885\end{methoddesc}
886
887\begin{methoddesc}[Connection]{getsockopt}{level, optname\optional{, buflen}}
888Call the \method{getsockopt} method of the underlying socket.
889\end{methoddesc}
890
891\begin{methoddesc}[Connection]{pending}{}
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500892Retrieve the number of bytes that can be safely read from the SSL buffer
893(\emph{not} the underlying transport buffer).
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500894\end{methoddesc}
895
896\begin{methoddesc}[Connection]{recv}{bufsize}
897Receive data from the Connection. The return value is a string representing the
898data received. The maximum amount of data to be received at once, is specified
899by \var{bufsize}.
900\end{methoddesc}
901
902\begin{methoddesc}[Connection]{renegotiate}{}
903Renegotiate the SSL session. Call this if you wish to change cipher suites or
904anything like that.
905\end{methoddesc}
906
907\begin{methoddesc}[Connection]{send}{string}
908Send the \var{string} data to the Connection.
909\end{methoddesc}
910
911\begin{methoddesc}[Connection]{sendall}{string}
912Send all of the \var{string} data to the Connection. This calls \method{send}
913repeatedly until all data is sent. If an error occurs, it's impossible to tell
914how much data has been sent.
915\end{methoddesc}
916
917\begin{methoddesc}[Connection]{set_accept_state}{}
918Set the connection to work in server mode. The handshake will be handled
919automatically by read/write.
920\end{methoddesc}
921
922\begin{methoddesc}[Connection]{set_app_data}{data}
923Associate \var{data} with this Connection object. \var{data} can be retrieved
924later using the \method{get_app_data} method.
925\end{methoddesc}
926
927\begin{methoddesc}[Connection]{set_connect_state}{}
928Set the connection to work in client mode. The handshake will be handled
929automatically by read/write.
930\end{methoddesc}
931
932\begin{methoddesc}[Connection]{setblocking}{flag}
933Call the \method{setblocking} method of the underlying socket.
934\end{methoddesc}
935
936\begin{methoddesc}[Connection]{setsockopt}{level, optname, value}
937Call the \method{setsockopt} method of the underlying socket.
938\end{methoddesc}
939
940\begin{methoddesc}[Connection]{shutdown}{}
941Send the shutdown message to the Connection. Returns true if the shutdown
942message exchange is completed and false otherwise (in which case you call
943\method{recv()} or \method{send()} when the connection becomes
944readable/writeable.
945\end{methoddesc}
946
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -0500947\begin{methoddesc}[Connection]{get_shutdown}{}
948Get the shutdown state of the Connection. Returns a bitvector of either or
949both of \var{SENT_SHUTDOWN} and \var{RECEIVED_SHUTDOWN}.
950\end{methoddesc}
951
952\begin{methoddesc}[Connection]{set_shutdown}{state}
953Set the shutdown state of the Connection. \var{state} is a bitvector of
954either or both of \var{SENT_SHUTDOWN} and \var{RECEIVED_SHUTDOWN}.
955\end{methoddesc}
956
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500957\begin{methoddesc}[Connection]{sock_shutdown}{how}
958Call the \method{shutdown} method of the underlying socket.
959\end{methoddesc}
960
961\begin{methoddesc}[Connection]{state_string}{}
962Retrieve a verbose string detailing the state of the Connection.
963\end{methoddesc}
964
965\begin{methoddesc}[Connection]{want_read}{}
966Checks if more data has to be read from the transport layer to complete an
967operation.
968\end{methoddesc}
969
970\begin{methoddesc}[Connection]{want_write}{}
971Checks if there is data to write to the transport layer to complete an
972operation.
973\end{methoddesc}
974
975
976
977\section{Internals \label{internals}}
978
979We ran into three main problems developing this: Exceptions, callbacks and
980accessing socket methods. This is what this chapter is about.
981
982\subsection{Exceptions \label{exceptions}}
983
984We realized early that most of the exceptions would be raised by the I/O
985functions of OpenSSL, so it felt natural to mimic OpenSSL's error code system,
986translating them into Python exceptions. This naturally gives us the exceptions
987\exception{SSL.ZeroReturnError}, \exception{SSL.WantReadError},
988\exception{SSL.WantWriteError}, \exception{SSL.WantX509LookupError} and
989\exception{SSL.SysCallError}.
990
991For more information about this, see section \ref{openssl-ssl}.
992
993
994\subsection{Callbacks \label{callbacks}}
995
996There are a number of problems with callbacks. First of all, OpenSSL is written
997as a C library, it's not meant to have Python callbacks, so a way around that
998is needed. Another problem is thread support. A lot of the OpenSSL I/O
999functions can block if the socket is in blocking mode, and then you want other
1000Python threads to be able to do other things. The real trouble is if you've
1001released the thread lock to do a potentially blocking operation, and the
1002operation calls a callback. Then we must take the thread lock back\footnote{I'm
1003not sure why this is necessary, but otherwise I get a segmentation violation on
1004\cfunction{PyEval_CallObject}}.
1005
1006There are two solutions to the first problem, both of which are necessary. The
1007first solution to use is if the C callback allows ''userdata'' to be passed to
1008it (an arbitrary pointer normally). This is great! We can set our Python
1009function object as the real userdata and emulate userdata for the Python
1010function in another way. The other solution can be used if an object with an
1011''app_data'' system always is passed to the callback. For example, the SSL
1012object in OpenSSL has app_data functions and in e.g. the verification
1013callbacks, you can retrieve the related SSL object. What we do is to set our
1014wrapper \class{Connection} object as app_data for the SSL object, and we can
1015easily find the Python callback.
1016
1017The other problem is also partially solved by app_data. Since we're associating
1018our wrapper objects with the ''real'' objects, we can easily access data from
1019the \class{Connection} object. The solution then is to simply include a
1020\ctype{PyThreadState} variable in the \class{Connection} declaration, and write
1021macros similar to \cfunction{Py_BEGIN_ALLOW_THREADS} and
1022\cfunction{Py_END_ALLOW_THREADS} that allows specifying of the
1023\ctype{PyThreadState} variable to use. Now we can simply ''begin allow
1024threads'' before a potentially blocking operation, and ''end allow threads''
1025before calling a callback.
1026
1027
1028\subsection{Acessing Socket Methods \label{socket-methods}}
1029
1030We quickly saw the benefit of wrapping socket methods in the
1031\class{SSL.Connection} class, for an easy transition into using SSL. The
1032problem here is that the \module{socket} module lacks a C API, and all the
1033methods are declared static. One approach would be to have \module{OpenSSL} as
1034a submodule to the \module{socket} module, placing all the code in
1035\file{socketmodule.c}, but this is obviously not a good solution, since you
1036might not want to import tonnes of extra stuff you're not going to use when
1037importing the \module{socket} module. The other approach is to somehow get a
1038pointer to the method to be called, either the C function, or a callable Python
1039object. This is not really a good solution either, since there's a lot of
1040lookups involved.
1041
1042The way it works is that you have to supply a ``\class{socket}-like'' transport
1043object to the \class{SSL.Connection}. The only requirement of this object is
1044that it has a \method{fileno()} method that returns a file descriptor that's
1045valid at the C level (i.e. you can use the system calls read and write). If you
1046want to use the \method{connect()} or \method{accept()} methods of the
1047\class{SSL.Connection} object, the transport object has to supply such
1048methods too. Apart from them, any method lookups in the \class{SSL.Connection}
1049object that fail are passed on to the underlying transport object.
1050
1051Future changes might be to allow Python-level transport objects, that instead
1052of having \method{fileno()} methods, have \method{read()} and \method{write()}
1053methods, so more advanced features of Python can be used. This would probably
1054entail some sort of OpenSSL ``BIOs'', but converting Python strings back and
1055forth is expensive, so this shouldn't be used unless necessary. Other nice
1056things would be to be able to pass in different transport objects for reading
1057and writing, but then the \method{fileno()} method of \class{SSL.Connection}
1058becomes virtually useless. Also, should the method resolution be used on the
1059read-transport or the write-transport?
1060
1061
1062\end{document}