Initial import to Tizen
[profile/ivi/python-pyOpenSSL.git] / doc / pyOpenSSL.tex
1 \documentclass{howto}
2
3 \title{Python OpenSSL Manual}
4
5 \release{0.11}
6
7 \author{Jean-Paul Calderone}
8 \authoraddress{\email{exarkun@twistedmatrix.com}}
9
10 \usepackage[english]{babel}
11 \usepackage[T1]{fontenc}
12
13 \begin{document}
14
15 \maketitle
16
17 \begin{abstract}
18 \noindent
19 This module is a rather thin wrapper around (a subset of) the OpenSSL library.
20 With thin wrapper I mean that a lot of the object methods do nothing more than
21 calling a corresponding function in the OpenSSL library.
22 \end{abstract}
23
24 \tableofcontents
25
26
27 \section{Introduction \label{intro}}
28
29 The reason pyOpenSSL was created is that the SSL support in the socket module
30 in Python 2.1 (the contemporary version of Python when the pyOpenSSL project
31 was begun) was severely limited.  Other OpenSSL wrappers for Python at the time
32 were also limited, though in different ways.  Unfortunately, Python's standard
33 library SSL support has remained weak, although other packages (such as
34 M2Crypto\footnote{See \url{http://chandlerproject.org/Projects/MeTooCrypto}})
35 have made great advances and now equal or exceed pyOpenSSL's functionality.
36
37 The reason pyOpenSSL continues to be maintained is that there is a significant
38 user community around it, as well as a large amount of software which depends
39 on it.  It is a great benefit to many people for pyOpenSSL to continue to exist
40 and advance.
41
42 \section{Building and Installing \label{building}}
43
44 These instructions can also be found in the file \verb|INSTALL|.
45
46 I have tested this on Debian Linux systems (woody and sid), Solaris 2.6 and
47 2.7. Others have successfully compiled it on Windows and NT.
48
49 \subsection{Building the Module on a Unix System \label{building-unix}}
50
51 pyOpenSSL uses distutils, so there really shouldn't be any problems. To build
52 the library:
53 \begin{verbatim}
54 python setup.py build
55 \end{verbatim}
56
57 If your OpenSSL header files aren't in \verb|/usr/include|, you may need to
58 supply the \verb|-I| flag to let the setup script know where to look. The same
59 goes for the libraries of course, use the \verb|-L| flag. Note that
60 \verb|build| won't accept these flags, so you have to run first
61 \verb|build_ext| and then \verb|build|! Example:
62 \begin{verbatim}
63 python setup.py build_ext -I/usr/local/ssl/include -L/usr/local/ssl/lib
64 python setup.py build
65 \end{verbatim}
66
67 Now you should have a directory called \verb|OpenSSL| that contains e.g.
68 \verb|SSL.so| and \verb|__init__.py| somewhere in the build dicrectory,
69 so just:
70 \begin{verbatim}
71 python setup.py install
72 \end{verbatim}
73
74 If you, for some arcane reason, don't want the module to appear in the
75 \verb|site-packages| directory, use the \verb|--prefix| option.
76
77 You can, of course, do
78 \begin{verbatim}
79 python setup.py --help
80 \end{verbatim}
81
82 to find out more about how to use the script.
83
84 \subsection{Building the Module on a Windows System \label{building-windows}}
85
86 Big thanks to Itamar Shtull-Trauring and Oleg Orlov for their help with
87 Windows build instructions.  Same as for Unix systems, we have to separate
88 the \verb|build_ext| and the \verb|build|.
89
90 Building the library:
91
92 \begin{verbatim}
93 setup.py build_ext -I ...\openssl\inc32 -L ...\openssl\out32dll
94 setup.py build
95 \end{verbatim}
96
97 Where \verb|...\openssl| is of course the location of your OpenSSL installation.
98
99 Installation is the same as for Unix systems:
100 \begin{verbatim}
101 setup.py install
102 \end{verbatim}
103
104 And similarily, you can do
105 \begin{verbatim}
106 setup.py --help
107 \end{verbatim}
108
109 to get more information.
110
111
112 \section{\module{OpenSSL} --- Python interface to OpenSSL \label{openssl}}
113
114 \declaremodule{extension}{OpenSSL}
115 \modulesynopsis{Python interface to OpenSSL}
116
117 This package provides a high-level interface to the functions in the
118 OpenSSL library. The following modules are defined:
119
120 \begin{datadesc}{crypto}
121 Generic cryptographic module. Note that if anything is incomplete, this module is!
122 \end{datadesc}
123
124 \begin{datadesc}{rand}
125 An interface to the OpenSSL pseudo random number generator.
126 \end{datadesc}
127
128 \begin{datadesc}{SSL}
129 An interface to the SSL-specific parts of OpenSSL.
130 \end{datadesc}
131
132
133 % % % crypto moduleOpenSSL
134
135 \subsection{\module{crypto} --- Generic cryptographic module \label{openssl-crypto}}
136
137 \declaremodule{extension}{crypto}
138 \modulesynopsis{Generic cryptographic module}
139
140 \begin{datadesc}{X509Type}
141 See \class{X509}.
142 \end{datadesc}
143
144 \begin{classdesc}{X509}{}
145 A class representing X.509 certificates.
146 \end{classdesc}
147
148 \begin{datadesc}{X509NameType}
149 See \class{X509Name}.
150 \end{datadesc}
151
152 \begin{classdesc}{X509Name}{x509name}
153 A class representing X.509 Distinguished Names.
154
155 This constructor creates a copy of \var{x509name} which should be an
156 instance of \class{X509Name}.
157 \end{classdesc}
158
159 \begin{datadesc}{X509ReqType}
160 See \class{X509Req}.
161 \end{datadesc}
162
163 \begin{classdesc}{X509Req}{}
164 A class representing X.509 certificate requests.
165 \end{classdesc}
166
167 \begin{datadesc}{X509StoreType}
168 A Python type object representing the X509Store object type.
169 \end{datadesc}
170
171 \begin{datadesc}{PKeyType}
172 See \class{PKey}.
173 \end{datadesc}
174
175 \begin{classdesc}{PKey}{}
176 A class representing DSA or RSA keys.
177 \end{classdesc}
178
179 \begin{datadesc}{PKCS7Type}
180 A Python type object representing the PKCS7 object type.
181 \end{datadesc}
182
183 \begin{datadesc}{PKCS12Type}
184 A Python type object representing the PKCS12 object type.
185 \end{datadesc}
186
187 \begin{datadesc}{X509ExtensionType}
188 See \class{X509Extension}.
189 \end{datadesc}
190
191 \begin{classdesc}{X509Extension}{typename, critical, value\optional{, subject}\optional{, issuer}}
192 A class representing an X.509 v3 certificate extensions.
193 See \url{http://openssl.org/docs/apps/x509v3_config.html\#STANDARD_EXTENSIONS}
194 for \var{typename} strings and their options.
195 Optional parameters \var{subject} and \var{issuer} must be X509 objects.
196 \end{classdesc}
197
198 \begin{datadesc}{NetscapeSPKIType}
199 See \class{NetscapeSPKI}.
200 \end{datadesc}
201
202 \begin{classdesc}{NetscapeSPKI}{\optional{enc}}
203 A class representing Netscape SPKI objects.
204
205 If the \var{enc} argument is present, it should be a base64-encoded string
206 representing a NetscapeSPKI object, as returned by the \method{b64_encode}
207 method.
208 \end{classdesc}
209
210 \begin{classdesc}{CRL}{}
211 A class representing Certifcate Revocation List objects.
212 \end{classdesc}
213
214 \begin{classdesc}{Revoked}{}
215 A class representing Revocation objects of CRL.
216 \end{classdesc}
217
218 \begin{datadesc}{FILETYPE_PEM}
219 \dataline{FILETYPE_ASN1}
220 File type constants.
221 \end{datadesc}
222
223 \begin{datadesc}{TYPE_RSA}
224 \dataline{TYPE_DSA}
225 Key type constants.
226 \end{datadesc}
227
228 \begin{excdesc}{Error}
229 Generic exception used in the \module{crypto} module.
230 \end{excdesc}
231
232 \begin{funcdesc}{dump_certificate}{type, cert}
233 Dump the certificate \var{cert} into a buffer string encoded with the type
234 \var{type}.
235 \end{funcdesc}
236
237 \begin{funcdesc}{dump_certificate_request}{type, req}
238 Dump the certificate request \var{req} into a buffer string encoded with the
239 type \var{type}.
240 \end{funcdesc}
241
242 \begin{funcdesc}{dump_privatekey}{type, pkey\optional{, cipher, passphrase}}
243 Dump the private key \var{pkey} into a buffer string encoded with the type
244 \var{type}, optionally (if \var{type} is \constant{FILETYPE_PEM}) encrypting it
245 using \var{cipher} and \var{passphrase}.
246
247 \var{passphrase} must be either a string or a callback for providing the
248 pass phrase.
249 \end{funcdesc}
250
251 \begin{funcdesc}{load_certificate}{type, buffer}
252 Load a certificate (X509) from the string \var{buffer} encoded with the
253 type \var{type}.
254 \end{funcdesc}
255
256 \begin{funcdesc}{load_certificate_request}{type, buffer}
257 Load a certificate request (X509Req) from the string \var{buffer} encoded with
258 the type \var{type}.
259 \end{funcdesc}
260
261 \begin{funcdesc}{load_privatekey}{type, buffer\optional{, passphrase}}
262 Load a private key (PKey) from the string \var{buffer} encoded with
263 the type \var{type} (must be one of \constant{FILETYPE_PEM} and
264 \constant{FILETYPE_ASN1}).
265
266 \var{passphrase} must be either a string or a callback for providing the
267 pass phrase.
268 \end{funcdesc}
269
270 \begin{funcdesc}{load_crl}{type, buffer}
271 Load Certificate Revocation List (CRL) data from a string \var{buffer}.
272 \var{buffer} encoded with the type \var{type}.  The type \var{type}
273 must either \constant{FILETYPE_PEM} or \constant{FILETYPE_ASN1}).
274 \end{funcdesc}
275
276 \begin{funcdesc}{load_pkcs7_data}{type, buffer}
277 Load pkcs7 data from the string \var{buffer} encoded with the type \var{type}.
278 \end{funcdesc}
279
280 \begin{funcdesc}{load_pkcs12}{buffer\optional{, passphrase}}
281 Load pkcs12 data from the string \var{buffer}. If the pkcs12 structure is
282 encrypted, a \var{passphrase} must be included.  The MAC is always
283 checked and thus required.
284
285 See also the man page for the C function \function{PKCS12_parse}.
286 \end{funcdesc}
287
288 \begin{funcdesc}{sign}{key, data, digest}
289 Sign a data string using the given key and message digest.
290
291 \var{key} is a \code{PKey} instance.  \var{data} is a \code{str} instance.
292 \var{digest} is a \code{str} naming a supported message digest type, for example
293 \code{``sha1''}.
294 \versionadded{0.11}
295 \end{funcdesc}
296
297 \begin{funcdesc}{verify}{certificate, signature, data, digest}
298 Verify the signature for a data string.
299
300 \var{certificate} is a \code{X509} instance corresponding to the private key
301 which generated the signature.  \var{signature} is a \var{str} instance giving
302 the signature itself.  \var{data} is a \var{str} instance giving the data to
303 which the signature applies.  \var{digest} is a \var{str} instance naming the
304 message digest type of the signature, for example \code{``sha1''}.
305 \versionadded{0.11}
306 \end{funcdesc}
307
308 \subsubsection{X509Extension objects \label{openssl-x509ext}}
309
310 X509Extension objects have the following methods:
311
312 \begin{methoddesc}[X509Extension]{get_short_name}{}
313 Retrieve the short descriptive name for this extension.
314
315 The result is a byte string like \code{``basicConstraints''}.
316 \versionadded{0.12}
317 \end{methoddesc}
318
319 \begin{methoddesc}[X509Extension]{get_data}{}
320 Retrieve the data for this extension.
321
322 The result is the ASN.1 encoded form of the extension data as a byte string.
323 \versionadded{0.12}
324 \end{methoddesc}
325
326 \subsubsection{X509 objects \label{openssl-x509}}
327
328 X509 objects have the following methods:
329
330 \begin{methoddesc}[X509]{get_issuer}{}
331 Return an X509Name object representing the issuer of the certificate.
332 \end{methoddesc}
333
334 \begin{methoddesc}[X509]{get_pubkey}{}
335 Return a PKey object representing the public key of the certificate.
336 \end{methoddesc}
337
338 \begin{methoddesc}[X509]{get_serial_number}{}
339 Return the certificate serial number.
340 \end{methoddesc}
341
342 \begin{methoddesc}[X509]{get_subject}{}
343 Return an X509Name object representing the subject of the certificate.
344 \end{methoddesc}
345
346 \begin{methoddesc}[X509]{get_version}{}
347 Return the certificate version.
348 \end{methoddesc}
349
350 \begin{methoddesc}[X509]{get_notBefore}{}
351 Return a string giving the time before which the certificate is not valid.  The
352 string is formatted as an ASN1 GENERALIZEDTIME:
353 \begin{verbatim}
354                  YYYYMMDDhhmmssZ
355                  YYYYMMDDhhmmss+hhmm
356                  YYYYMMDDhhmmss-hhmm
357 \end{verbatim}
358 If no value exists for this field, \code{None} is returned.
359 \end{methoddesc}
360
361 \begin{methoddesc}[X509]{get_notAfter}{}
362 Return a string giving the time after which the certificate is not valid.  The
363 string is formatted as an ASN1 GENERALIZEDTIME:
364 \begin{verbatim}
365                  YYYYMMDDhhmmssZ
366                  YYYYMMDDhhmmss+hhmm
367                  YYYYMMDDhhmmss-hhmm
368 \end{verbatim}
369 If no value exists for this field, \code{None} is returned.
370 \end{methoddesc}
371
372 \begin{methoddesc}[X509]{set_notBefore}{when}
373 Change the time before which the certificate is not valid.  \var{when} is a
374 string formatted as an ASN1 GENERALIZEDTIME:
375 \begin{verbatim}
376                  YYYYMMDDhhmmssZ
377                  YYYYMMDDhhmmss+hhmm
378                  YYYYMMDDhhmmss-hhmm
379 \end{verbatim}
380 \end{methoddesc}
381
382 \begin{methoddesc}[X509]{set_notAfter}{when}
383 Change the time after which the certificate is not valid.  \var{when} is a
384 string formatted as an ASN1 GENERALIZEDTIME:
385 \begin{verbatim}
386                  YYYYMMDDhhmmssZ
387                  YYYYMMDDhhmmss+hhmm
388                  YYYYMMDDhhmmss-hhmm
389 \end{verbatim}
390 \end{methoddesc}
391
392 \begin{methoddesc}[X509]{gmtime_adj_notBefore}{time}
393 Adjust the timestamp (in GMT) when the certificate starts being valid.
394 \end{methoddesc}
395
396 \begin{methoddesc}[X509]{gmtime_adj_notAfter}{time}
397 Adjust the timestamp (in GMT) when the certificate stops being valid.
398 \end{methoddesc}
399
400 \begin{methoddesc}[X509]{has_expired}{}
401 Checks the certificate's time stamp against current time. Returns true if the
402 certificate has expired and false otherwise.
403 \end{methoddesc}
404
405 \begin{methoddesc}[X509]{set_issuer}{issuer}
406 Set the issuer of the certificate to \var{issuer}.
407 \end{methoddesc}
408
409 \begin{methoddesc}[X509]{set_pubkey}{pkey}
410 Set the public key of the certificate to \var{pkey}.
411 \end{methoddesc}
412
413 \begin{methoddesc}[X509]{set_serial_number}{serialno}
414 Set the serial number of the certificate to \var{serialno}.
415 \end{methoddesc}
416
417 \begin{methoddesc}[X509]{set_subject}{subject}
418 Set the subject of the certificate to \var{subject}.
419 \end{methoddesc}
420
421 \begin{methoddesc}[X509]{set_version}{version}
422 Set the certificate version to \var{version}.
423 \end{methoddesc}
424
425 \begin{methoddesc}[X509]{sign}{pkey, digest}
426 Sign the certificate, using the key \var{pkey} and the message digest algorithm
427 identified by the string \var{digest}.
428 \end{methoddesc}
429
430 \begin{methoddesc}[X509]{subject_name_hash}{}
431 Return the hash of the certificate subject.
432 \end{methoddesc}
433
434 \begin{methoddesc}[X509]{digest}{digest_name}
435 Return a digest of the certificate, using the \var{digest_name} method.
436 \var{digest_name} must be a string describing a digest algorithm supported
437 by OpenSSL (by EVP_get_digestbyname, specifically).  For example,
438 \constant{"md5"} or \constant{"sha1"}.
439 \end{methoddesc}
440
441 \begin{methoddesc}[X509]{add_extensions}{extensions}
442 Add the extensions in the sequence \var{extensions} to the certificate.
443 \end{methoddesc}
444
445 \begin{methoddesc}[X509]{get_extension_count}{}
446 Return the number of extensions on this certificate.
447 \versionadded{0.12}
448 \end{methoddesc}
449
450 \begin{methoddesc}[X509]{get_extension}{index}
451 Retrieve the extension on this certificate at the given index.
452
453 Extensions on a certificate are kept in order.  The index parameter selects
454 which extension will be returned.  The returned object will be an X509Extension
455 instance.
456 \versionadded{0.12}
457 \end{methoddesc}
458
459 \subsubsection{X509Name objects \label{openssl-x509name}}
460
461 X509Name objects have the following methods:
462
463 \begin{methoddesc}[X509Name]{hash}{}
464 Return an integer giving the first four bytes of the MD5 digest of the DER
465 representation of the name.
466 \end{methoddesc}
467
468 \begin{methoddesc}[X509Name]{der}{}
469 Return a string giving the DER representation of the name.
470 \end{methoddesc}
471
472 \begin{methoddesc}[X509Name]{get_components}{}
473 Return a list of two-tuples of strings giving the components of the name.
474 \end{methoddesc}
475
476 X509Name objects have the following members:
477
478 \begin{memberdesc}[X509Name]{countryName}
479 The country of the entity. \code{C} may be used as an alias for
480 \code{countryName}.
481 \end{memberdesc}
482
483 \begin{memberdesc}[X509Name]{stateOrProvinceName}
484 The state or province of the entity. \code{ST} may be used as an alias for
485 \code{stateOrProvinceName}·
486 \end{memberdesc}
487
488 \begin{memberdesc}[X509Name]{localityName}
489 The locality of the entity. \code{L} may be used as an alias for
490 \code{localityName}.
491 \end{memberdesc}
492
493 \begin{memberdesc}[X509Name]{organizationName}
494 The organization name of the entity. \code{O} may be used as an alias for
495 \code{organizationName}.
496 \end{memberdesc}
497
498 \begin{memberdesc}[X509Name]{organizationalUnitName}
499 The organizational unit of the entity. \code{OU} may be used as an alias for
500 \code{organizationalUnitName}.
501 \end{memberdesc}
502
503 \begin{memberdesc}[X509Name]{commonName}
504 The common name of the entity. \code{CN} may be used as an alias for
505 \code{commonName}.
506 \end{memberdesc}
507
508 \begin{memberdesc}[X509Name]{emailAddress}
509 The e-mail address of the entity.
510 \end{memberdesc}
511
512 \subsubsection{X509Req objects \label{openssl-x509req}}
513
514 X509Req objects have the following methods:
515
516 \begin{methoddesc}[X509Req]{get_pubkey}{}
517 Return a PKey object representing the public key of the certificate request.
518 \end{methoddesc}
519
520 \begin{methoddesc}[X509Req]{get_subject}{}
521 Return an X509Name object representing the subject of the certificate.
522 \end{methoddesc}
523
524 \begin{methoddesc}[X509Req]{set_pubkey}{pkey}
525 Set the public key of the certificate request to \var{pkey}.
526 \end{methoddesc}
527
528 \begin{methoddesc}[X509Req]{sign}{pkey, digest}
529 Sign the certificate request, using the key \var{pkey} and the message digest
530 algorithm identified by the string \var{digest}.
531 \end{methoddesc}
532
533 \begin{methoddesc}[X509Req]{verify}{pkey}
534 Verify a certificate request using the public key \var{pkey}.
535 \end{methoddesc}
536
537 \begin{methoddesc}[X509Req]{set_version}{version}
538 Set the version (RFC 2459, 4.1.2.1) of the certificate request to
539 \var{version}.
540 \end{methoddesc}
541
542 \begin{methoddesc}[X509Req]{get_version}{}
543 Get the version (RFC 2459, 4.1.2.1) of the certificate request.
544 \end{methoddesc}
545
546 \subsubsection{X509Store objects \label{openssl-x509store}}
547
548 The X509Store object has currently just one method:
549
550 \begin{methoddesc}[X509Store]{add_cert}{cert}
551 Add the certificate \var{cert} to the certificate store.
552 \end{methoddesc}
553
554 \subsubsection{PKey objects \label{openssl-pkey}}
555
556 The PKey object has the following methods:
557
558 \begin{methoddesc}[PKey]{bits}{}
559 Return the number of bits of the key.
560 \end{methoddesc}
561
562 \begin{methoddesc}[PKey]{generate_key}{type, bits}
563 Generate a public/private key pair of the type \var{type} (one of
564 \constant{TYPE_RSA} and \constant{TYPE_DSA}) with the size \var{bits}.
565 \end{methoddesc}
566
567 \begin{methoddesc}[PKey]{type}{}
568 Return the type of the key.
569 \end{methoddesc}
570
571 \subsubsection{PKCS7 objects \label{openssl-pkcs7}}
572
573 PKCS7 objects have the following methods:
574
575 \begin{methoddesc}[PKCS7]{type_is_signed}{}
576 FIXME
577 \end{methoddesc}
578
579 \begin{methoddesc}[PKCS7]{type_is_enveloped}{}
580 FIXME
581 \end{methoddesc}
582
583 \begin{methoddesc}[PKCS7]{type_is_signedAndEnveloped}{}
584 FIXME
585 \end{methoddesc}
586
587 \begin{methoddesc}[PKCS7]{type_is_data}{}
588 FIXME
589 \end{methoddesc}
590
591 \begin{methoddesc}[PKCS7]{get_type_name}{}
592 Get the type name of the PKCS7.
593 \end{methoddesc}
594
595 \subsubsection{PKCS12 objects \label{openssl-pkcs12}}
596
597 PKCS12 objects have the following methods:
598
599 \begin{methoddesc}[PKCS12]{export}{\optional{passphrase=None}\optional{, iter=2048}\optional{, maciter=1}}
600 Returns a PKCS12 object as a string.
601
602 The optional \var{passphrase} must be a string not a callback.
603
604 See also the man page for the C function \function{PKCS12_create}.
605 \end{methoddesc}
606
607 \begin{methoddesc}[PKCS12]{get_ca_certificates}{}
608 Return CA certificates within the PKCS12 object as a tuple. Returns
609 \constant{None} if no CA certificates are present.
610 \end{methoddesc}
611
612 \begin{methoddesc}[PKCS12]{get_certificate}{}
613 Return certificate portion of the PKCS12 structure.
614 \end{methoddesc}
615
616 \begin{methoddesc}[PKCS12]{get_friendlyname}{}
617 Return friendlyName portion of the PKCS12 structure.
618 \end{methoddesc}
619
620 \begin{methoddesc}[PKCS12]{get_privatekey}{}
621 Return private key portion of the PKCS12 structure
622 \end{methoddesc}
623
624 \begin{methoddesc}[PKCS12]{set_ca_certificates}{cacerts}
625 Replace or set the CA certificates within the PKCS12 object with the sequence \var{cacerts}.
626
627 Set \var{cacerts} to \constant{None} to remove all CA certificates.
628 \end{methoddesc}
629
630 \begin{methoddesc}[PKCS12]{set_certificate}{cert}
631 Replace or set the certificate portion of the PKCS12 structure.
632 \end{methoddesc}
633
634 \begin{methoddesc}[PKCS12]{set_friendlyname}{name}
635 Replace or set the friendlyName portion of the PKCS12 structure.
636 \end{methoddesc}
637
638 \begin{methoddesc}[PKCS12]{set_privatekey}{pkey}
639 Replace or set private key portion of the PKCS12 structure
640 \end{methoddesc}
641
642 \subsubsection{X509Extension objects \label{openssl-509ext}}
643
644 X509Extension objects have several methods:
645
646 \begin{methoddesc}[X509Extension]{get_critical}{}
647 Return the critical field of the extension object.
648 \end{methoddesc}
649
650 \begin{methoddesc}[X509Extension]{get_short_name}{}
651 Return the short type name of the extension object.
652 \end{methoddesc}
653
654 \subsubsection{NetscapeSPKI objects \label{openssl-netscape-spki}}
655
656 NetscapeSPKI objects have the following methods:
657
658 \begin{methoddesc}[NetscapeSPKI]{b64_encode}{}
659 Return a base64-encoded string representation of the object.
660 \end{methoddesc}
661
662 \begin{methoddesc}[NetscapeSPKI]{get_pubkey}{}
663 Return the public key of object.
664 \end{methoddesc}
665
666 \begin{methoddesc}[NetscapeSPKI]{set_pubkey}{key}
667 Set the public key of the object to \var{key}.
668 \end{methoddesc}
669
670 \begin{methoddesc}[NetscapeSPKI]{sign}{key, digest_name}
671 Sign the NetscapeSPKI object using the given \var{key} and
672 \var{digest_name}.  \var{digest_name} must be a string describing a digest
673 algorithm supported by OpenSSL (by EVP_get_digestbyname, specifically).  For
674 example, \constant{"md5"} or \constant{"sha1"}.
675 \end{methoddesc}
676
677 \begin{methoddesc}[NetscapeSPKI]{verify}{key}
678 Verify the NetscapeSPKI object using the given \var{key}.
679 \end{methoddesc}
680
681 \subsubsection{CRL objects \label{crl}}
682
683 CRL objects have the following methods:
684
685 \begin{methoddesc}[CRL]{add_revoked}{revoked}
686 Add a Revoked object to the CRL, by value not reference.
687 \end{methoddesc}
688
689 \begin{methoddesc}[CRL]{export}{cert, key\optional{, type=FILETYPE_PEM}\optional{, days=100}}
690 Use \var{cert} and \var{key} to sign the CRL and return the CRL as a string.
691 \var{days} is the number of days before the next CRL is due.
692 \end{methoddesc}
693
694 \begin{methoddesc}[CRL]{get_revoked}{}
695 Return a tuple of Revoked objects, by value not reference.
696 \end{methoddesc}
697
698 \subsubsection{Revoked objects \label{revoked}}
699
700 Revoked objects have the following methods:
701
702 \begin{methoddesc}[Revoked]{all_reasons}{}
703 Return a list of all supported reasons.
704 \end{methoddesc}
705
706 \begin{methoddesc}[Revoked]{get_reason}{}
707 Return the revocation reason as a str.  Can be
708 None, which differs from "Unspecified".
709 \end{methoddesc}
710
711 \begin{methoddesc}[Revoked]{get_rev_date}{}
712 Return the revocation date as a str.
713 The string is formatted as an ASN1 GENERALIZEDTIME.
714 \end{methoddesc}
715
716 \begin{methoddesc}[Revoked]{get_serial}{}
717 Return a str containing a hex number of the serial of the revoked certificate.
718 \end{methoddesc}
719
720 \begin{methoddesc}[Revoked]{set_reason}{reason}
721 Set the revocation reason.  \var{reason} must
722 be None or a string, but the values are limited.  
723 Spaces and case are ignored.  See \method{all_reasons}.
724 \end{methoddesc}
725
726 \begin{methoddesc}[Revoked]{set_rev_date}{date}
727 Set the revocation date.
728 The string is formatted as an ASN1 GENERALIZEDTIME.
729 \end{methoddesc}
730
731 \begin{methoddesc}[Revoked]{set_serial}{serial}
732 \var{serial} is a string containing a hex number of the serial of the revoked certificate.
733 \end{methoddesc}
734
735
736 % % % rand module
737
738 \subsection{\module{rand} --- An interface to the OpenSSL pseudo random number generator \label{openssl-rand}}
739
740 \declaremodule{extension}{rand}
741 \modulesynopsis{An interface to the OpenSSL pseudo random number generator}
742
743 This module handles the OpenSSL pseudo random number generator (PRNG) and
744 declares the following:
745
746 \begin{funcdesc}{add}{string, entropy}
747 Mix bytes from \var{string} into the PRNG state. The \var{entropy} argument is
748 (the lower bound of) an estimate of how much randomness is contained in
749 \var{string}, measured in bytes. For more information, see e.g. \rfc{1750}.
750 \end{funcdesc}
751
752 \begin{funcdesc}{bytes}{num_bytes}
753 Get some random bytes from the PRNG as a string.
754
755 This is a wrapper for the C function \function{RAND_bytes}.
756 \end{funcdesc}
757
758 \begin{funcdesc}{cleanup}{}
759 Erase the memory used by the PRNG.
760
761 This is a wrapper for the C function \function{RAND_cleanup}.
762 \end{funcdesc}
763
764 \begin{funcdesc}{egd}{path\optional{, bytes}}
765 Query the Entropy Gathering Daemon\footnote{See
766 \url{http://www.lothar.com/tech/crypto/}} on socket \var{path} for \var{bytes}
767 bytes of random data and and uses \function{add} to seed the PRNG. The default
768 value of \var{bytes} is 255.
769 \end{funcdesc}
770
771 \begin{funcdesc}{load_file}{path\optional{, bytes}}
772 Read \var{bytes} bytes (or all of it, if \var{bytes} is negative) of data from
773 the file \var{path} to seed the PRNG. The default value of \var{bytes} is -1.
774 \end{funcdesc}
775
776 \begin{funcdesc}{screen}{}
777 Add the current contents of the screen to the PRNG state.
778 Availability: Windows.
779 \end{funcdesc}
780
781 \begin{funcdesc}{seed}{string}
782 This is equivalent to calling \function{add} with \var{entropy} as the length
783 of the string.
784 \end{funcdesc}
785
786 \begin{funcdesc}{status}{}
787 Returns true if the PRNG has been seeded with enough data, and false otherwise.
788 \end{funcdesc}
789
790 \begin{funcdesc}{write_file}{path}
791 Write a number of random bytes (currently 1024) to the file \var{path}. This
792 file can then be used with \function{load_file} to seed the PRNG again.
793 \end{funcdesc}
794
795 \begin{excdesc}{Error}
796 If the current RAND method supports any errors, this is raised when needed.
797 The default method does not raise this when the entropy pool is depleted.
798
799 Whenever this exception is raised directly, it has a list of error messages
800 from the OpenSSL error queue, where each item is a tuple \code{(\var{lib},
801 \var{function}, \var{reason})}. Here \var{lib}, \var{function} and \var{reason}
802 are all strings, describing where and what the problem is. See \manpage{err}{3}
803 for more information.
804 \end{excdesc}
805
806
807 % % % SSL module
808
809 \subsection{\module{SSL} --- An interface to the SSL-specific parts of OpenSSL \label{openssl-ssl}}
810
811 \declaremodule{extension}{SSL}
812 \modulesynopsis{An interface to the SSL-specific parts of OpenSSL}
813
814 This module handles things specific to SSL. There are two objects defined:
815 Context, Connection.
816
817 \begin{datadesc}{SSLv2_METHOD}
818 \dataline{SSLv3_METHOD}
819 \dataline{SSLv23_METHOD}
820 \dataline{TLSv1_METHOD}
821 These constants represent the different SSL methods to use when creating a
822 context object.
823 \end{datadesc}
824
825 \begin{datadesc}{VERIFY_NONE}
826 \dataline{VERIFY_PEER}
827 \dataline{VERIFY_FAIL_IF_NO_PEER_CERT}
828 These constants represent the verification mode used by the Context
829 object's \method{set_verify} method.
830 \end{datadesc}
831
832 \begin{datadesc}{FILETYPE_PEM}
833 \dataline{FILETYPE_ASN1}
834 File type constants used with the \method{use_certificate_file} and
835 \method{use_privatekey_file} methods of Context objects.
836 \end{datadesc}
837
838 \begin{datadesc}{OP_SINGLE_DH_USE}
839 \dataline{OP_EPHEMERAL_RSA}
840 \dataline{OP_NO_SSLv2}
841 \dataline{OP_NO_SSLv3}
842 \dataline{OP_NO_TLSv1}
843 Constants used with \method{set_options} of Context objects.
844 \constant{OP_SINGLE_DH_USE} means to always create a new key when using ephemeral
845 Diffie-Hellman. \constant{OP_EPHEMERAL_RSA} means to always use ephemeral RSA keys
846 when doing RSA operations. \constant{OP_NO_SSLv2}, \constant{OP_NO_SSLv3} and
847 \constant{OP_NO_TLSv1} means to disable those specific protocols. This is
848 interesting if you're using e.g. \constant{SSLv23_METHOD} to get an SSLv2-compatible
849 handshake, but don't want to use SSLv2.
850 \end{datadesc}
851
852 \begin{datadesc}{ContextType}
853 See \class{Context}.
854 \end{datadesc}
855
856 \begin{classdesc}{Context}{method}
857 A class representing SSL contexts.  Contexts define the parameters of one or
858 more SSL connections.
859
860 \var{method} should be \constant{SSLv2_METHOD}, \constant{SSLv3_METHOD},
861 \constant{SSLv23_METHOD} or \constant{TLSv1_METHOD}.
862 \end{classdesc}
863
864 \begin{datadesc}{ConnectionType}
865 See \class{Connection}.
866 \end{datadesc}
867
868 \begin{classdesc}{Connection}{context, socket}
869 A class representing SSL connections.
870
871 \var{context} should be an instance of \class{Context} and \var{socket}
872 should be a socket \footnote{Actually, all that is required is an object
873 that \emph{behaves} like a socket, you could even use files, even though
874 it'd be tricky to get the handshakes right!} object.  \var{socket} may be
875 \var{None}; in this case, the Connection is created with a memory BIO: see
876 the \method{bio_read}, \method{bio_write}, and \method{bio_shutdown}
877 methods.
878 \end{classdesc}
879
880 \begin{excdesc}{Error}
881 This exception is used as a base class for the other SSL-related
882 exceptions, but may also be raised directly.
883
884 Whenever this exception is raised directly, it has a list of error messages
885 from the OpenSSL error queue, where each item is a tuple \code{(\var{lib},
886 \var{function}, \var{reason})}. Here \var{lib}, \var{function} and \var{reason}
887 are all strings, describing where and what the problem is. See \manpage{err}{3}
888 for more information.
889 \end{excdesc}
890
891 \begin{excdesc}{ZeroReturnError}
892 This exception matches the error return code \code{SSL_ERROR_ZERO_RETURN}, and
893 is raised when the SSL Connection has been closed. In SSL 3.0 and TLS 1.0, this
894 only occurs if a closure alert has occurred in the protocol, i.e. the
895 connection has been closed cleanly. Note that this does not necessarily
896 mean that the transport layer (e.g. a socket) has been closed.
897
898 It may seem a little strange that this is an exception, but it does match an
899 \code{SSL_ERROR} code, and is very convenient.
900 \end{excdesc}
901
902 \begin{excdesc}{WantReadError}
903 The operation did not complete; the same I/O method should be called again
904 later, with the same arguments. Any I/O method can lead to this since new
905 handshakes can occur at any time.
906
907 The wanted read is for \emph{dirty} data sent over the network, not the
908 \emph{clean} data inside the tunnel.  For a socket based SSL connection,
909 \emph{read} means data coming at us over the network.  Until that read
910 succeeds, the attempted \method{OpenSSL.SSL.Connection.recv},
911 \method{OpenSSL.SSL.Connection.send}, or
912 \method{OpenSSL.SSL.Connection.do_handshake} is prevented or incomplete. You
913 probably want to \method{select()} on the socket before trying again.
914 \end{excdesc}
915
916 \begin{excdesc}{WantWriteError}
917 See \exception{WantReadError}.  The socket send buffer may be too full to
918 write more data.
919 \end{excdesc}
920
921 \begin{excdesc}{WantX509LookupError}
922 The operation did not complete because an application callback has asked to be
923 called again. The I/O method should be called again later, with the same
924 arguments. Note: This won't occur in this version, as there are no such
925 callbacks in this version.
926 \end{excdesc}
927
928 \begin{excdesc}{SysCallError}
929 The \exception{SysCallError} occurs when there's an I/O error and OpenSSL's
930 error queue does not contain any information. This can mean two things: An
931 error in the transport protocol, or an end of file that violates the protocol.
932 The parameter to the exception is always a pair \code{(\var{errnum},
933 \var{errstr})}.
934 \end{excdesc}
935
936
937 \subsubsection{Context objects \label{openssl-context}}
938
939 Context objects have the following methods:
940
941 \begin{methoddesc}[Context]{check_privatekey}{}
942 Check if the private key (loaded with \method{use_privatekey\optional{_file}})
943 matches the certificate (loaded with \method{use_certificate\optional{_file}}).
944 Returns \code{None} if they match, raises \exception{Error} otherwise.
945 \end{methoddesc}
946
947 \begin{methoddesc}[Context]{get_app_data}{}
948 Retrieve application data as set by \method{set_app_data}.
949 \end{methoddesc}
950
951 \begin{methoddesc}[Context]{get_cert_store}{}
952 Retrieve the certificate store (a X509Store object) that the context uses.
953 This can be used to add "trusted" certificates without using the.
954 \method{load_verify_locations()} method.
955 \end{methoddesc}
956
957 \begin{methoddesc}[Context]{get_timeout}{}
958 Retrieve session timeout, as set by \method{set_timeout}. The default is 300
959 seconds.
960 \end{methoddesc}
961
962 \begin{methoddesc}[Context]{get_verify_depth}{}
963 Retrieve the Context object's verify depth, as set by
964 \method{set_verify_depth}.
965 \end{methoddesc}
966
967 \begin{methoddesc}[Context]{get_verify_mode}{}
968 Retrieve the Context object's verify mode, as set by \method{set_verify}.
969 \end{methoddesc}
970
971 \begin{methoddesc}[Context]{load_client_ca}{pemfile}
972 Read a file with PEM-formatted certificates that will be sent to the client
973 when requesting a client certificate.
974 \end{methoddesc}
975
976 \begin{methoddesc}[Context]{set_client_ca_list}{certificate_authorities}
977 Replace the current list of preferred certificate signers that would be
978 sent to the client when requesting a client certificate with the
979 \var{certificate_authorities} sequence of \class{OpenSSL.crypto.X509Name}s.
980
981 \versionadded{0.10}
982 \end{methoddesc}
983
984 \begin{methoddesc}[Context]{add_client_ca}{certificate_authority}
985 Extract a \class{OpenSSL.crypto.X509Name} from the \var{certificate_authority}
986 \class{OpenSSL.crypto.X509} certificate and add it to the list of preferred
987 certificate signers sent to the client when requesting a client certificate.
988
989 \versionadded{0.10}
990 \end{methoddesc}
991
992 \begin{methoddesc}[Context]{load_verify_locations}{pemfile, capath}
993 Specify where CA certificates for verification purposes are located. These
994 are trusted certificates. Note that the certificates have to be in PEM
995 format.  If capath is passed, it must be a directory prepared using the
996 \code{c_rehash} tool included with OpenSSL.  Either, but not both, of
997 \var{pemfile} or \var{capath} may be \code{None}.
998 \end{methoddesc}
999
1000 \begin{methoddesc}[Context]{set_default_verify_paths}{}
1001 Specify that the platform provided CA certificates are to be used for
1002 verification purposes.  This method may not work properly on OS X.
1003 \end{methoddesc}
1004
1005 \begin{methoddesc}[Context]{load_tmp_dh}{dhfile}
1006 Load parameters for Ephemeral Diffie-Hellman from \var{dhfile}.
1007 \end{methoddesc}
1008
1009 \begin{methoddesc}[Context]{set_app_data}{data}
1010 Associate \var{data} with this Context object. \var{data} can be retrieved
1011 later using the \method{get_app_data} method.
1012 \end{methoddesc}
1013
1014 \begin{methoddesc}[Context]{set_cipher_list}{ciphers}
1015 Set the list of ciphers to be used in this context. See the OpenSSL manual for
1016 more information (e.g. ciphers(1))
1017 \end{methoddesc}
1018
1019 \begin{methoddesc}[Context]{set_info_callback}{callback}
1020 Set the information callback to \var{callback}. This function will be called
1021 from time to time during SSL handshakes.
1022 \var{callback} should take three arguments: a Connection object and two
1023 integers. The first integer specifies where in the SSL handshake the function
1024 was called, and the other the return code from a (possibly failed) internal
1025 function call.
1026 \end{methoddesc}
1027
1028 \begin{methoddesc}[Context]{set_options}{options}
1029 Add SSL options. Options you have set before are not cleared!
1030 This method should be used with the \constant{OP_*} constants.
1031 \end{methoddesc}
1032
1033 \begin{methoddesc}[Context]{set_passwd_cb}{callback\optional{, userdata}}
1034 Set the passphrase callback to \var{callback}. This function will be called
1035 when a private key with a passphrase is loaded. \var{callback} must accept
1036 three positional arguments.  First, an integer giving the maximum length of
1037 the passphrase it may return.  If the returned passphrase is longer than
1038 this, it will be truncated.  Second, a boolean value which will be true if
1039 the user should be prompted for the passphrase twice and the callback should
1040 verify that the two values supplied are equal. Third, the value given as the
1041 \var{userdata} parameter to \method{set_passwd_cb}.  If an error occurs,
1042 \var{callback} should return a false value (e.g. an empty string).
1043 \end{methoddesc}
1044
1045 \begin{methoddesc}[Context]{set_session_id}{name}
1046 Set the context \var{name} within which a session can be reused for this
1047 Context object. This is needed when doing session resumption, because there is
1048 no way for a stored session to know which Context object it is associated with.
1049 \var{name} may be any binary data.
1050 \end{methoddesc}
1051
1052 \begin{methoddesc}[Context]{set_timeout}{timeout}
1053 Set the timeout for newly created sessions for this Context object to
1054 \var{timeout}. \var{timeout} must be given in (whole) seconds. The default
1055 value is 300 seconds. See the OpenSSL manual for more information (e.g.
1056 SSL_CTX_set_timeout(3)).
1057 \end{methoddesc}
1058
1059 \begin{methoddesc}[Context]{set_verify}{mode, callback}
1060 Set the verification flags for this Context object to \var{mode} and specify
1061 that \var{callback} should be used for verification callbacks. \var{mode}
1062 should be one of \constant{VERIFY_NONE} and \constant{VERIFY_PEER}. If
1063 \constant{VERIFY_PEER} is used, \var{mode} can be OR:ed with
1064 \constant{VERIFY_FAIL_IF_NO_PEER_CERT} and \constant{VERIFY_CLIENT_ONCE} to
1065 further control the behaviour.
1066 \var{callback} should take five arguments: A Connection object, an X509 object,
1067 and three integer variables, which are in turn potential error number, error
1068 depth and return code. \var{callback} should return true if verification passes
1069 and false otherwise.
1070 \end{methoddesc}
1071
1072 \begin{methoddesc}[Context]{set_verify_depth}{depth}
1073 Set the maximum depth for the certificate chain verification that shall be
1074 allowed for this Context object.
1075 \end{methoddesc}
1076
1077 \begin{methoddesc}[Context]{use_certificate}{cert}
1078 Use the certificate \var{cert} which has to be a X509 object.
1079 \end{methoddesc}
1080
1081 \begin{methoddesc}[Context]{add_extra_chain_cert}{cert}
1082 Adds the certificate \var{cert}, which has to be a X509 object, to the
1083 certificate chain presented together with the certificate.
1084 \end{methoddesc}
1085
1086 \begin{methoddesc}[Context]{use_certificate_chain_file}{file}
1087 Load a certificate chain from \var{file} which must be PEM encoded.
1088 \end{methoddesc}
1089
1090 \begin{methoddesc}[Context]{use_privatekey}{pkey}
1091 Use the private key \var{pkey} which has to be a PKey object.
1092 \end{methoddesc}
1093
1094 \begin{methoddesc}[Context]{use_certificate_file}{file\optional{, format}}
1095 Load the first certificate found in \var{file}. The certificate must be in the
1096 format specified by \var{format}, which is either \constant{FILETYPE_PEM} or
1097 \constant{FILETYPE_ASN1}. The default is \constant{FILETYPE_PEM}.
1098 \end{methoddesc}
1099
1100 \begin{methoddesc}[Context]{use_privatekey_file}{file\optional{, format}}
1101 Load the first private key found in \var{file}. The private key must be in the
1102 format specified by \var{format}, which is either \constant{FILETYPE_PEM} or
1103 \constant{FILETYPE_ASN1}. The default is \constant{FILETYPE_PEM}.
1104 \end{methoddesc}
1105
1106
1107 \subsubsection{Connection objects \label{openssl-connection}}
1108
1109 Connection objects have the following methods:
1110
1111 \begin{methoddesc}[Connection]{accept}{}
1112 Call the \method{accept} method of the underlying socket and set up SSL on the
1113 returned socket, using the Context object supplied to this Connection object at
1114 creation. Returns a pair \code{(\var{conn}, \var{address})}. where \var{conn}
1115 is the new Connection object created, and \var{address} is as returned by the
1116 socket's \method{accept}.
1117 \end{methoddesc}
1118
1119 \begin{methoddesc}[Connection]{bind}{address}
1120 Call the \method{bind} method of the underlying socket.
1121 \end{methoddesc}
1122
1123 \begin{methoddesc}[Connection]{close}{}
1124 Call the \method{close} method of the underlying socket. Note: If you want
1125 correct SSL closure, you need to call the \method{shutdown} method first.
1126 \end{methoddesc}
1127
1128 \begin{methoddesc}[Connection]{connect}{address}
1129 Call the \method{connect} method of the underlying socket and set up SSL on the
1130 socket, using the Context object supplied to this Connection object at
1131 creation.
1132 \end{methoddesc}
1133
1134 \begin{methoddesc}[Connection]{connect_ex}{address}
1135 Call the \method{connect_ex} method of the underlying socket and set up SSL on
1136 the socket, using the Context object supplied to this Connection object at
1137 creation. Note that if the \method{connect_ex} method of the socket doesn't
1138 return 0, SSL won't be initialized.
1139 \end{methoddesc}
1140
1141 \begin{methoddesc}[Connection]{do_handshake}{}
1142 Perform an SSL handshake (usually called after \method{renegotiate} or one of
1143 \method{set_accept_state} or \method{set_accept_state}). This can raise the
1144 same exceptions as \method{send} and \method{recv}.
1145 \end{methoddesc}
1146
1147 \begin{methoddesc}[Connection]{fileno}{}
1148 Retrieve the file descriptor number for the underlying socket.
1149 \end{methoddesc}
1150
1151 \begin{methoddesc}[Connection]{listen}{backlog}
1152 Call the \method{listen} method of the underlying socket.
1153 \end{methoddesc}
1154
1155 \begin{methoddesc}[Connection]{get_app_data}{}
1156 Retrieve application data as set by \method{set_app_data}.
1157 \end{methoddesc}
1158
1159 \begin{methoddesc}[Connection]{get_cipher_list}{}
1160 Retrieve the list of ciphers used by the Connection object. WARNING: This API
1161 has changed. It used to take an optional parameter and just return a string,
1162 but not it returns the entire list in one go.
1163 \end{methoddesc}
1164
1165 \begin{methoddesc}[Connection]{get_client_ca_list}{}
1166 Retrieve the list of preferred client certificate issuers sent by the server
1167 as \class{OpenSSL.crypto.X509Name} objects.
1168
1169 If this is a client \class{Connection}, the list will be empty until the
1170 connection with the server is established.
1171
1172 If this is a server \class{Connection}, return the list of certificate
1173 authorities that will be sent or has been sent to the client, as controlled
1174 by this \class{Connection}'s \class{Context}.
1175
1176 \versionadded{0.10}
1177 \end{methoddesc}
1178
1179 \begin{methoddesc}[Connection]{get_context}{}
1180 Retrieve the Context object associated with this Connection.
1181 \end{methoddesc}
1182
1183 \begin{methoddesc}[Connection]{get_peer_certificate}{}
1184 Retrieve the other side's certificate (if any)
1185 \end{methoddesc}
1186
1187 \begin{methoddesc}[Connection]{getpeername}{}
1188 Call the \method{getpeername} method of the underlying socket.
1189 \end{methoddesc}
1190
1191 \begin{methoddesc}[Connection]{getsockname}{}
1192 Call the \method{getsockname} method of the underlying socket.
1193 \end{methoddesc}
1194
1195 \begin{methoddesc}[Connection]{getsockopt}{level, optname\optional{, buflen}}
1196 Call the \method{getsockopt} method of the underlying socket.
1197 \end{methoddesc}
1198
1199 \begin{methoddesc}[Connection]{pending}{}
1200 Retrieve the number of bytes that can be safely read from the SSL buffer
1201 (\emph{not} the underlying transport buffer).
1202 \end{methoddesc}
1203
1204 \begin{methoddesc}[Connection]{recv}{bufsize}
1205 Receive data from the Connection. The return value is a string representing the
1206 data received. The maximum amount of data to be received at once, is specified
1207 by \var{bufsize}.
1208 \end{methoddesc}
1209
1210 \begin{methoddesc}[Connection]{bio_write}{bytes}
1211 If the Connection was created with a memory BIO, this method can be used to add
1212 bytes to the read end of that memory BIO.  The Connection can then read the
1213 bytes (for example, in response to a call to \method{recv}).
1214 \end{methoddesc}
1215
1216 \begin{methoddesc}[Connection]{renegotiate}{}
1217 Renegotiate the SSL session. Call this if you wish to change cipher suites or
1218 anything like that.
1219 \end{methoddesc}
1220
1221 \begin{methoddesc}[Connection]{send}{string}
1222 Send the \var{string} data to the Connection.
1223 \end{methoddesc}
1224
1225 \begin{methoddesc}[Connection]{bio_read}{bufsize}
1226 If the Connection was created with a memory BIO, this method can be used to
1227 read bytes from the write end of that memory BIO.  Many Connection methods will
1228 add bytes which must be read in this manner or the buffer will eventually fill
1229 up and the Connection will be able to take no further actions.
1230 \end{methoddesc}
1231
1232 \begin{methoddesc}[Connection]{sendall}{string}
1233 Send all of the \var{string} data to the Connection. This calls \method{send}
1234 repeatedly until all data is sent. If an error occurs, it's impossible to tell
1235 how much data has been sent.
1236 \end{methoddesc}
1237
1238 \begin{methoddesc}[Connection]{set_accept_state}{}
1239 Set the connection to work in server mode. The handshake will be handled
1240 automatically by read/write.
1241 \end{methoddesc}
1242
1243 \begin{methoddesc}[Connection]{set_app_data}{data}
1244 Associate \var{data} with this Connection object. \var{data} can be retrieved
1245 later using the \method{get_app_data} method.
1246 \end{methoddesc}
1247
1248 \begin{methoddesc}[Connection]{set_connect_state}{}
1249 Set the connection to work in client mode. The handshake will be handled
1250 automatically by read/write.
1251 \end{methoddesc}
1252
1253 \begin{methoddesc}[Connection]{setblocking}{flag}
1254 Call the \method{setblocking} method of the underlying socket.
1255 \end{methoddesc}
1256
1257 \begin{methoddesc}[Connection]{setsockopt}{level, optname, value}
1258 Call the \method{setsockopt} method of the underlying socket.
1259 \end{methoddesc}
1260
1261 \begin{methoddesc}[Connection]{shutdown}{}
1262 Send the shutdown message to the Connection. Returns true if the shutdown
1263 message exchange is completed and false otherwise (in which case you call
1264 \method{recv()} or \method{send()} when the connection becomes
1265 readable/writeable.
1266 \end{methoddesc}
1267
1268 \begin{methoddesc}[Connection]{get_shutdown}{}
1269 Get the shutdown state of the Connection.  Returns a bitvector of either or
1270 both of \var{SENT_SHUTDOWN} and \var{RECEIVED_SHUTDOWN}.
1271 \end{methoddesc}
1272
1273 \begin{methoddesc}[Connection]{set_shutdown}{state}
1274 Set the shutdown state of the Connection.  \var{state} is a bitvector of
1275 either or both of \var{SENT_SHUTDOWN} and \var{RECEIVED_SHUTDOWN}.
1276 \end{methoddesc}
1277
1278 \begin{methoddesc}[Connection]{sock_shutdown}{how}
1279 Call the \method{shutdown} method of the underlying socket.
1280 \end{methoddesc}
1281
1282 \begin{methoddesc}[Connection]{bio_shutdown}{}
1283 If the Connection was created with a memory BIO, this method can be used to
1284 indicate that ``end of file'' has been reached on the read end of that memory
1285 BIO.
1286 \end{methoddesc}
1287
1288 \begin{methoddesc}[Connection]{state_string}{}
1289 Retrieve a verbose string detailing the state of the Connection.
1290 \end{methoddesc}
1291
1292 \begin{methoddesc}[Connection]{client_random}{}
1293 Retrieve the random value used with the client hello message.
1294 \end{methoddesc}
1295
1296 \begin{methoddesc}[Connection]{server_random}{}
1297 Retrieve the random value used with the server hello message.
1298 \end{methoddesc}
1299
1300 \begin{methoddesc}[Connection]{master_key}{}
1301 Retrieve the value of the master key for this session.
1302 \end{methoddesc}
1303
1304 \begin{methoddesc}[Connection]{want_read}{}
1305 Checks if more data has to be read from the transport layer to complete an
1306 operation.
1307 \end{methoddesc}
1308
1309 \begin{methoddesc}[Connection]{want_write}{}
1310 Checks if there is data to write to the transport layer to complete an
1311 operation.
1312 \end{methoddesc}
1313
1314
1315
1316 \section{Internals \label{internals}}
1317
1318 We ran into three main problems developing this: Exceptions, callbacks and
1319 accessing socket methods. This is what this chapter is about.
1320
1321 \subsection{Exceptions \label{exceptions}}
1322
1323 We realized early that most of the exceptions would be raised by the I/O
1324 functions of OpenSSL, so it felt natural to mimic OpenSSL's error code system,
1325 translating them into Python exceptions. This naturally gives us the exceptions
1326 \exception{SSL.ZeroReturnError}, \exception{SSL.WantReadError},
1327 \exception{SSL.WantWriteError}, \exception{SSL.WantX509LookupError} and
1328 \exception{SSL.SysCallError}.
1329
1330 For more information about this, see section \ref{openssl-ssl}.
1331
1332
1333 \subsection{Callbacks \label{callbacks}}
1334
1335 There are a number of problems with callbacks. First of all, OpenSSL is written
1336 as a C library, it's not meant to have Python callbacks, so a way around that
1337 is needed. Another problem is thread support. A lot of the OpenSSL I/O
1338 functions can block if the socket is in blocking mode, and then you want other
1339 Python threads to be able to do other things. The real trouble is if you've
1340 released the global CPython interpreter lock to do a potentially blocking
1341 operation, and the operation calls a callback. Then we must take the GIL back,
1342 since calling Python APIs without holding it is not allowed.
1343
1344 There are two solutions to the first problem, both of which are necessary. The
1345 first solution to use is if the C callback allows ''userdata'' to be passed to
1346 it (an arbitrary pointer normally). This is great! We can set our Python
1347 function object as the real userdata and emulate userdata for the Python
1348 function in another way. The other solution can be used if an object with an
1349 ''app_data'' system always is passed to the callback. For example, the SSL
1350 object in OpenSSL has app_data functions and in e.g. the verification
1351 callbacks, you can retrieve the related SSL object. What we do is to set our
1352 wrapper \class{Connection} object as app_data for the SSL object, and we can
1353 easily find the Python callback.
1354
1355 The other problem is solved using thread local variables.  Whenever the GIL is
1356 released before calling into an OpenSSL API, the PyThreadState pointer returned
1357 by \cfunction{PyEval_SaveState} is stored in a global thread local variable
1358 (using Python's own TLS API, \cfunction{PyThread_set_key_value}).  When it is
1359 necessary to re-acquire the GIL, either after the OpenSSL API returns or in a C
1360 callback invoked by that OpenSSL API, the value of the thread local variable is
1361 retrieved (\cfunction{PyThread_get_key_value}) and used to re-acquire the GIL.
1362 This allows Python threads to execute while OpenSSL APIs are running and allows
1363 use of any particular pyOpenSSL object from any Python thread, since there is
1364 no per-thread state associated with any of these objects and since OpenSSL is
1365 threadsafe (as long as properly initialized, as pyOpenSSL initializes it).
1366
1367
1368 \subsection{Acessing Socket Methods \label{socket-methods}}
1369
1370 We quickly saw the benefit of wrapping socket methods in the
1371 \class{SSL.Connection} class, for an easy transition into using SSL. The
1372 problem here is that the \module{socket} module lacks a C API, and all the
1373 methods are declared static. One approach would be to have \module{OpenSSL} as
1374 a submodule to the \module{socket} module, placing all the code in
1375 \file{socketmodule.c}, but this is obviously not a good solution, since you
1376 might not want to import tonnes of extra stuff you're not going to use when
1377 importing the \module{socket} module. The other approach is to somehow get a
1378 pointer to the method to be called, either the C function, or a callable Python
1379 object. This is not really a good solution either, since there's a lot of
1380 lookups involved.
1381
1382 The way it works is that you have to supply a ``\class{socket}-like'' transport
1383 object to the \class{SSL.Connection}. The only requirement of this object is
1384 that it has a \method{fileno()} method that returns a file descriptor that's
1385 valid at the C level (i.e. you can use the system calls read and write). If you
1386 want to use the \method{connect()} or \method{accept()} methods of the
1387 \class{SSL.Connection} object, the transport object has to supply such
1388 methods too. Apart from them, any method lookups in the \class{SSL.Connection}
1389 object that fail are passed on to the underlying transport object.
1390
1391 Future changes might be to allow Python-level transport objects, that instead
1392 of having \method{fileno()} methods, have \method{read()} and \method{write()}
1393 methods, so more advanced features of Python can be used. This would probably
1394 entail some sort of OpenSSL ``BIOs'', but converting Python strings back and
1395 forth is expensive, so this shouldn't be used unless necessary. Other nice
1396 things would be to be able to pass in different transport objects for reading
1397 and writing, but then the \method{fileno()} method of \class{SSL.Connection}
1398 becomes virtually useless. Also, should the method resolution be used on the
1399 read-transport or the write-transport?
1400
1401
1402 \end{document}