blob: 29c36b43be5107ddc07917cf5530bafddd06b091 [file] [log] [blame]
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -05001 Python OpenSSL Manual
2 __________________________________________________________________
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05003
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -05004 Python OpenSSL Manual
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05005
6 Martin Sjögren
7
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -05008 martin@strakt.com
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05009
10 Abstract:
11
12 This module is a rather thin wrapper around (a subset of) the OpenSSL
13 library. With thin wrapper I mean that a lot of the object methods do
14 nothing more than calling a corresponding function in the OpenSSL
15 library.
16
17Contents
18
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -050019 * 1 Introduction
20 * 2 Building and Installing
21 + 2.1 Building the Module on a Unix System
22 + 2.2 Building the Module on a Windows System
23 * 3 OpenSSL -- Python interface to OpenSSL
24 + 3.1 crypto -- Generic cryptographic module
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050025 + 3.2 rand -- An interface to the OpenSSL pseudo random number
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -050026 generator
27 + 3.3 SSL -- An interface to the SSL-specific parts of OpenSSL
28 * 4 Internals
29 + 4.1 Exceptions
30 + 4.2 Callbacks
31 + 4.3 Acessing Socket Methods
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050032
33
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -050034 1 Introduction
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050035
Jean-Paul Calderonef1b839d2008-09-01 12:06:06 -040036 The reason pyOpenSSL was created is that the SSL support in the socket
37 module in Python 2.1 (the contemporary version of Python when the
38 pyOpenSSL project was begun) was severely limited. Other OpenSSL
39 wrappers for Python at the time were also limited, though in different
40 ways. Unfortunately, Python's standard library SSL support has remained
41 weak, although other packages (such as M2Crypto^1) have made great
42 advances and now equal or exceed pyOpenSSL's functionality.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050043
Jean-Paul Calderonef1b839d2008-09-01 12:06:06 -040044 The reason pyOpenSSL continues to be maintained is that there is a
45 significant user community around it, as well as a large amount of
46 software which depends on it. It is a great benefit to many people for
47 pyOpenSSL to continue to exist and advance.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050048
49
50 2 Building and Installing
51
52 These instructions can also be found in the file INSTALL.
53
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -050054 I have tested this on Debian Linux systems (woody and sid), Solaris 2.6
55 and 2.7. Others have successfully compiled it on Windows and NT.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050056
57
582.1 Building the Module on a Unix System
59
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -050060 pyOpenSSL uses distutils, so there really shouldn't be any problems. To
61 build the library:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050062
63python setup.py build
64
65 If your OpenSSL header files aren't in /usr/include, you may need to
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -050066 supply the -I flag to let the setup script know where to look. The same
67 goes for the libraries of course, use the -L flag. Note that build
68 won't accept these flags, so you have to run first build_ext and then
69 build! Example:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050070
71python setup.py build_ext -I/usr/local/ssl/include -L/usr/local/ssl/lib
72python setup.py build
73
74 Now you should have a directory called OpenSSL that contains e.g.
75 SSL.so and __init__.py somewhere in the build dicrectory, so just:
76
77python setup.py install
78
79 If you, for some arcane reason, don't want the module to appear in the
80 site-packages directory, use the --prefix option.
81
82 You can, of course, do
83
84python setup.py --help
85
86 to find out more about how to use the script.
87
88
892.2 Building the Module on a Windows System
90
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -050091 Big thanks to Itamar Shtull-Trauring and Oleg Orlov for their help with
92 Windows build instructions. Same as for Unix systems, we have to
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050093 separate the build_ext and the build.
94
95 Building the library:
96
97setup.py build_ext -I ...\openssl\inc32 -L ...\openssl\out32dll
98setup.py build
99
100 Where ...\openssl is of course the location of your OpenSSL
101 installation.
102
103 Installation is the same as for Unix systems:
104
105setup.py install
106
107 And similarily, you can do
108
109setup.py --help
110
111 to get more information.
112
113
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500114 3 OpenSSL -- Python interface to OpenSSL
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500115
116 This package provides a high-level interface to the functions in the
117 OpenSSL library. The following modules are defined:
118
119 crypto
120 Generic cryptographic module. Note that if anything is
121 incomplete, this module is!
122
123 rand
124 An interface to the OpenSSL pseudo random number generator.
125
126 SSL
127 An interface to the SSL-specific parts of OpenSSL.
128
129
1303.1 crypto -- Generic cryptographic module
131
132 X509Type
133 A Python type object representing the X509 object type.
134
135 X509()
136 Factory function that creates an X509 object.
137
138 X509NameType
139 A Python type object representing the X509Name object type.
140
141 X509Name(x509name)
142 Factory function that creates a copy of x509name.
143
144 X509ReqType
145 A Python type object representing the X509Req object type.
146
147 X509Req()
148 Factory function that creates an X509Req object.
149
150 X509StoreType
151 A Python type object representing the X509Store object type.
152
153 PKeyType
154 A Python type object representing the PKey object type.
155
156 PKey()
157 Factory function that creates a PKey object.
158
159 PKCS7Type
160 A Python type object representing the PKCS7 object type.
161
162 PKCS12Type
163 A Python type object representing the PKCS12 object type.
164
165 X509ExtensionType
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500166 A Python type object representing the X509Extension object type.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500167
168 X509Extension(typename, critical, value)
169 Factory function that creates a X509Extension object.
170
171 NetscapeSPKIType
172 A Python type object representing the NetscapeSPKI object type.
173
174 NetscapeSPKI([enc])
175 Factory function that creates a NetscapeSPKI object. If the enc
176 argument is present, it should be a base64-encoded string
177 representing a NetscapeSPKI object, as returned by the
178 b64_encode method.
179
180 FILETYPE_PEM
181
182 FILETYPE_ASN1
183 File type constants.
184
185 TYPE_RSA
186
187 TYPE_DSA
188 Key type constants.
189
190 exception Error
191 Generic exception used in the crypto module.
192
193 dump_certificate(type, cert)
194 Dump the certificate cert into a buffer string encoded with the
195 type type.
196
197 dump_certificate_request(type, req)
198 Dump the certificate request req into a buffer string encoded
199 with the type type.
200
201 dump_privatekey(type, pkey[, cipher, passphrase])
202 Dump the private key pkey into a buffer string encoded with the
203 type type, optionally (if type is FILETYPE_PEM) encrypting it
204 using cipher and passphrase.
205
206 passphrase must be either a string or a callback for providing
207 the pass phrase.
208
209 load_certificate(type, buffer)
210 Load a certificate (X509) from the string buffer encoded with
211 the type type.
212
213 load_certificate_request(type, buffer)
214 Load a certificate request (X509Req) from the string buffer
215 encoded with the type type.
216
217 load_privatekey(type, buffer[, passphrase])
218 Load a private key (PKey) from the string buffer encoded with
219 the type type (must be one of FILETYPE_PEM and FILETYPE_ASN1).
220
221 passphrase must be either a string or a callback for providing
222 the pass phrase.
223
224 load_pkcs7_data(type, buffer)
225 Load pkcs7 data from the string buffer encoded with the type
226 type.
227
228 load_pkcs12(buffer[, passphrase])
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500229 Load pkcs12 data from the string buffer. If the pkcs12 structure
230 is encrypted, a passphrase must be included.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500231
232
233 3.1.1 X509 objects
234
235 X509 objects have the following methods:
236
237 get_issuer()
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -0500238 Return an X509Name object representing the issuer of the
239 certificate.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500240
241 get_pubkey()
242 Return a PKey object representing the public key of the
243 certificate.
244
245 get_serial_number()
246 Return the certificate serial number.
247
248 get_subject()
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -0500249 Return an X509Name object representing the subject of the
250 certificate.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500251
252 get_version()
253 Return the certificate version.
254
Jean-Paul Calderone525ef802008-03-09 20:39:42 -0400255 get_notBefore()
256 Return a string giving the time before which the certificate is
257 not valid. The string is formatted as an ASN1 GENERALIZEDTIME:
258
259 YYYYMMDDhhmmssZ
260 YYYYMMDDhhmmss+hhmm
261 YYYYMMDDhhmmss-hhmm
262
Jean-Paul Calderone24c99262008-03-09 21:48:06 -0400263 If no value exists for this field, None is returned.
264
Jean-Paul Calderone525ef802008-03-09 20:39:42 -0400265 get_notAfter()
266 Return a string giving the time after which the certificate is
267 not valid. The string is formatted as an ASN1 GENERALIZEDTIME:
268
269 YYYYMMDDhhmmssZ
270 YYYYMMDDhhmmss+hhmm
271 YYYYMMDDhhmmss-hhmm
272
Jean-Paul Calderone24c99262008-03-09 21:48:06 -0400273 If no value exists for this field, None is returned.
274
Jean-Paul Calderone525ef802008-03-09 20:39:42 -0400275 set_notBefore(when)
276 Change the time before which the certificate is not valid. when
277 is a string formatted as an ASN1 GENERALIZEDTIME:
278
279 YYYYMMDDhhmmssZ
280 YYYYMMDDhhmmss+hhmm
281 YYYYMMDDhhmmss-hhmm
282
283 set_notAfter(when)
284 Change the time after which the certificate is not valid. when
285 is a string formatted as an ASN1 GENERALIZEDTIME:
286
287 YYYYMMDDhhmmssZ
288 YYYYMMDDhhmmss+hhmm
289 YYYYMMDDhhmmss-hhmm
290
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500291 gmtime_adj_notBefore(time)
292 Adjust the timestamp (in GMT) when the certificate starts being
293 valid.
294
295 gmtime_adj_notAfter(time)
296 Adjust the timestamp (in GMT) when the certificate stops being
297 valid.
298
299 has_expired()
300 Checks the certificate's time stamp against current time.
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500301 Returns true if the certificate has expired and false otherwise.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500302
303 set_issuer(issuer)
304 Set the issuer of the certificate to issuer.
305
306 set_pubkey(pkey)
307 Set the public key of the certificate to pkey.
308
309 set_serial_number(serialno)
310 Set the serial number of the certificate to serialno.
311
312 set_subject(subject)
313 Set the subject of the certificate to subject.
314
315 set_version(version)
316 Set the certificate version to version.
317
318 sign(pkey, digest)
319 Sign the certificate, using the key pkey and the message digest
320 algorithm identified by the string digest.
321
322 subject_name_hash()
323 Return the hash of the certificate subject.
324
325 digest(digest_name)
326 Return a digest of the certificate, using the digest_name
327 method.
328
329 add_extensions(extensions)
330 Add the extensions in the sequence extensions to the
331 certificate.
332
333
334 3.1.2 X509Name objects
335
Jean-Paul Calderone2dd8ff52008-03-24 17:43:58 -0400336 X509Name objects have the following methods:
337
338 hash()
339 Return an integer giving the first four bytes of the MD5 digest
340 of the DER representation of the name.
341
Jean-Paul Calderoned2532d82008-03-25 15:20:39 -0400342 der()
343 Return a string giving the DER representation of the name.
344
Jean-Paul Calderonec54cc182008-03-26 21:11:07 -0400345 get_components()
346 Return a list of two-tuples of strings giving the components of
347 the name.
348
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500349 X509Name objects have the following members:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500350
351 countryName
352 The country of the entity. C may be used as an alias for
353 countryName.
354
355 stateOrProvinceName
356 The state or province of the entity. ST may be used as an alias
357 for stateOrProvinceName·
358
359 localityName
360 The locality of the entity. L may be used as an alias for
361 localityName.
362
363 organizationName
364 The organization name of the entity. O may be used as an alias
365 for organizationName.
366
367 organizationalUnitName
368 The organizational unit of the entity. OU may be used as an
369 alias for organizationalUnitName.
370
371 commonName
372 The common name of the entity. CN may be used as an alias for
373 commonName.
374
375 emailAddress
376 The e-mail address of the entity.
377
378
379 3.1.3 X509Req objects
380
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500381 X509Req objects have the following methods:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500382
383 get_pubkey()
384 Return a PKey object representing the public key of the
385 certificate request.
386
387 get_subject()
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -0500388 Return an X509Name object representing the subject of the
389 certificate.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500390
391 set_pubkey(pkey)
392 Set the public key of the certificate request to pkey.
393
394 sign(pkey, digest)
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500395 Sign the certificate request, using the key pkey and the message
396 digest algorithm identified by the string digest.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500397
398 verify(pkey)
399 Verify a certificate request using the public key pkey.
400
401
402 3.1.4 X509Store objects
403
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500404 The X509Store object has currently just one method:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500405
406 add_cert(cert)
407 Add the certificate cert to the certificate store.
408
409
410 3.1.5 PKey objects
411
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500412 The PKey object has the following methods:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500413
414 bits()
415 Return the number of bits of the key.
416
417 generate_key(type, bits)
418 Generate a public/private key pair of the type type (one of
419 TYPE_RSA and TYPE_DSA) with the size bits.
420
421 type()
422 Return the type of the key.
423
424
425 3.1.6 PKCS7 objects
426
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500427 PKCS7 objects have the following methods:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500428
429 type_is_signed()
430 FIXME
431
432 type_is_enveloped()
433 FIXME
434
435 type_is_signedAndEnveloped()
436 FIXME
437
438 type_is_data()
439 FIXME
440
441 get_type_name()
442 Get the type name of the PKCS7.
443
444
445 3.1.7 PKCS12 objects
446
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500447 PKCS12 objects have the following methods:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500448
449 get_certificate()
450 Return certificate portion of the PKCS12 structure.
451
452 get_privatekey()
453 Return private key portion of the PKCS12 structure
454
455 get_ca_certificates()
456 Return CA certificates within the PKCS12 object as a tuple.
457 Returns None if no CA certificates are present.
458
459
460 3.1.8 X509Extension objects
461
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500462 X509Extension objects currently only have one method:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500463
464 get_critical()
465 Return the critical field of the extension object.
466
467
468 3.1.9 NetscapeSPKI objects
469
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500470 NetscapeSPKI objects have the following methods:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500471
472 b64_encode()
473 Return a base64-encoded string representation of the object.
474
475 get_pubkey()
476 Return the public key of object.
477
478 set_pubkey(key)
479 Set the public key of the object to key.
480
481 sign(key, digest_name)
482 Sign the NetscapeSPKI object using the given key and
483 digest_name.
484
485 verify(key)
486 Verify the NetscapeSPKI object using the given key.
487
488
4893.2 rand -- An interface to the OpenSSL pseudo random number generator
490
491 This module handles the OpenSSL pseudo random number generator (PRNG)
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500492 and declares the following:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500493
494 add(string, entropy)
495 Mix bytes from string into the PRNG state. The entropy argument
496 is (the lower bound of) an estimate of how much randomness is
497 contained in string, measured in bytes. For more information,
498 see e.g. RFC 1750.
499
500 egd(path[, bytes])
Jean-Paul Calderonef1b839d2008-09-01 12:06:06 -0400501 Query the Entropy Gathering Daemon^2 on socket path for bytes
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500502 bytes of random data and and uses add to seed the PRNG. The
503 default value of bytes is 255.
504
505 load_file(path[, bytes])
506 Read bytes bytes (or all of it, if bytes is negative) of data
507 from the file path to seed the PRNG. The default value of bytes
508 is -1.
509
510 screen()
511 Add the current contents of the screen to the PRNG state.
512 Availability: Windows.
513
514 seed(string)
515 This is equivalent to calling add with entropy as the length of
516 the string.
517
518 status()
519 Returns true if the PRNG has been seeded with enough data, and
520 false otherwise.
521
522 write_file(path)
523 Write a number of random bytes (currently 1024) to the file
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500524 path. This file can then be used with load_file to seed the PRNG
525 again.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500526
527
5283.3 SSL -- An interface to the SSL-specific parts of OpenSSL
529
530 This module handles things specific to SSL. There are two objects
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500531 defined: Context, Connection.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500532
533 SSLv2_METHOD
534
535 SSLv3_METHOD
536
537 SSLv23_METHOD
538
539 TLSv1_METHOD
540 These constants represent the different SSL methods to use when
541 creating a context object.
542
543 VERIFY_NONE
544
545 VERIFY_PEER
546
547 VERIFY_FAIL_IF_NO_PEER_CERT
548 These constants represent the verification mode used by the
549 Context object's set_verify method.
550
551 FILETYPE_PEM
552
553 FILETYPE_ASN1
554 File type constants used with the use_certificate_file and
555 use_privatekey_file methods of Context objects.
556
557 OP_SINGLE_DH_USE
558
559 OP_EPHEMERAL_RSA
560
561 OP_NO_SSLv2
562
563 OP_NO_SSLv3
564
565 OP_NO_TLSv1
566 Constants used with set_options of Context objects.
567 OP_SINGLE_DH_USE means to always create a new key when using
568 ephemeral Diffie-Hellman. OP_EPHEMERAL_RSA means to always use
569 ephemeral RSA keys when doing RSA operations. OP_NO_SSLv2,
570 OP_NO_SSLv3 and OP_NO_TLSv1 means to disable those specific
571 protocols. This is interesting if you're using e.g.
572 SSLv23_METHOD to get an SSLv2-compatible handshake, but don't
573 want to use SSLv2.
574
575 ContextType
576 A Python type object representing the Context object type.
577
578 Context(method)
579 Factory function that creates a new Context object given an SSL
580 method. The method should be SSLv2_METHOD, SSLv3_METHOD,
581 SSLv23_METHOD or TLSv1_METHOD.
582
583 ConnectionType
584 A Python type object representing the Connection object type.
585
586 Connection(context, socket)
587 Factory fucnction that creates a new Connection object given an
Jean-Paul Calderonef1b839d2008-09-01 12:06:06 -0400588 SSL context and a socket ^3 object.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500589
590 exception Error
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500591 This exception is used as a base class for the other SSL-related
592 exceptions, but may also be raised directly.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500593
594 Whenever this exception is raised directly, it has a list of
595 error messages from the OpenSSL error queue, where each item is
596 a tuple (lib, function, reason). Here lib, function and reason
597 are all strings, describing where and what the problem is. See
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500598 err(3) for more information.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500599
600 exception ZeroReturnError
601 This exception matches the error return code
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500602 SSL_ERROR_ZERO_RETURN, and is raised when the SSL Connection has
603 been closed. In SSL 3.0 and TLS 1.0, this only occurs if a
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500604 closure alert has occurred in the protocol, i.e. the connection
605 has been closed cleanly. Note that this does not necessarily
606 mean that the transport layer (e.g. a socket) has been closed.
607
608 It may seem a little strange that this is an exception, but it
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500609 does match an SSL_ERROR code, and is very convenient.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500610
611 exception WantReadError
612 The operation did not complete; the same I/O method should be
613 called again later, with the same arguments. Any I/O method can
614 lead to this since new handshakes can occur at any time.
615
616 exception WantWriteError
617 See WantReadError.
618
619 exception WantX509LookupError
620 The operation did not complete because an application callback
621 has asked to be called again. The I/O method should be called
622 again later, with the same arguments. Note: This won't occur in
623 this version, as there are no such callbacks in this version.
624
625 exception SysCallError
626 The SysCallError occurs when there's an I/O error and OpenSSL's
627 error queue does not contain any information. This can mean two
628 things: An error in the transport protocol, or an end of file
629 that violates the protocol. The parameter to the exception is
630 always a pair (errnum, errstr).
631
632
633 3.3.1 Context objects
634
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500635 Context objects have the following methods:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500636
637 check_privatekey()
638 Check if the private key (loaded with use_privatekey[_file])
639 matches the certificate (loaded with use_certificate[_file]).
Jean-Paul Calderonef05fbbe2008-03-06 21:52:35 -0500640 Returns None if they match, raises Error otherwise.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500641
642 get_app_data()
643 Retrieve application data as set by set_app_data.
644
645 get_cert_store()
646 Retrieve the certificate store (a X509Store object) that the
647 context uses. This can be used to add "trusted" certificates
648 without using the. load_verify_locations() method.
649
650 get_timeout()
651 Retrieve session timeout, as set by set_timeout. The default is
652 300 seconds.
653
654 get_verify_depth()
655 Retrieve the Context object's verify depth, as set by
656 set_verify_depth.
657
658 get_verify_mode()
659 Retrieve the Context object's verify mode, as set by
660 set_verify_mode.
661
662 load_client_ca(pemfile)
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500663 Read a file with PEM-formatted certificates that will be sent to
664 the client when requesting a client certificate.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500665
666 load_verify_locations(pemfile)
667 Specify where CA certificates for verification purposes are
668 located. These are trusted certificates. Note that the
669 certificates have to be in PEM format.
670
671 load_tmp_dh(dhfile)
672 Load parameters for Ephemeral Diffie-Hellman from dhfile.
673
674 set_app_data(data)
675 Associate data with this Context object. data can be retrieved
676 later using the get_app_data method.
677
678 set_cipher_list(ciphers)
679 Set the list of ciphers to be used in this context. See the
680 OpenSSL manual for more information (e.g. ciphers(1))
681
682 set_info_callback(callback)
683 Set the information callback to callback. This function will be
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500684 called from time to time during SSL handshakes. callback should
685 take three arguments: a Connection object and two integers. The
686 first integer specifies where in the SSL handshake the function
687 was called, and the other the return code from a (possibly
688 failed) internal function call.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500689
690 set_options(options)
691 Add SSL options. Options you have set before are not cleared!
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500692 This method should be used with the OP_* constants.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500693
694 set_passwd_cb(callback[, userdata])
695 Set the passphrase callback to callback. This function will be
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500696 called when a private key with a passphrase is loaded. callback
Jean-Paul Calderone1eeb29e2008-10-19 11:50:53 -0400697 must accept three positional arguments. First, an integer giving
698 the maximum length of the passphrase it may return. If the
699 returned passphrase is longer than this, it will be truncated.
700 Second, a boolean value which will be true if the user should be
701 prompted for the passphrase twice and the callback should verify
702 that the two values supplied are equal. Third, the value given
703 as the userdata parameter to set_passwd_cb. If an error occurs,
704 callback should return a false value (e.g. an empty string).
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500705
706 set_session_id(name)
707 Set the context name within which a session can be reused for
708 this Context object. This is needed when doing session
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500709 resumption, because there is no way for a stored session to know
710 which Context object it is associated with. name may be any
711 binary data.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500712
713 set_timeout(timeout)
714 Set the timeout for newly created sessions for this Context
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500715 object to timeout. timeout must be given in (whole) seconds. The
716 default value is 300 seconds. See the OpenSSL manual for more
717 information (e.g. SSL_CTX_set_timeout(3)).
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500718
719 set_verify(mode, callback)
720 Set the verification flags for this Context object to mode and
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500721 specify that callback should be used for verification callbacks.
722 mode should be one of VERIFY_NONE and VERIFY_PEER. If
723 VERIFY_PEER is used, mode can be OR:ed with
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500724 VERIFY_FAIL_IF_NO_PEER_CERT and VERIFY_CLIENT_ONCE to further
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500725 control the behaviour. callback should take five arguments: A
726 Connection object, an X509 object, and three integer variables,
727 which are in turn potential error number, error depth and return
728 code. callback should return true if verification passes and
729 false otherwise.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500730
731 set_verify_depth(depth)
732 Set the maximum depth for the certificate chain verification
733 that shall be allowed for this Context object.
734
735 use_certificate(cert)
736 Use the certificate cert which has to be a X509 object.
737
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500738 add_extra_chain_cert(cert)
739 Adds the certificate cert, which has to be a X509 object, to the
740 certificate chain presented together with the certificate.
741
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500742 use_certificate_chain_file(file)
743 Load a certificate chain from file which must be PEM encoded.
744
745 use_privatekey(pkey)
746 Use the private key pkey which has to be a PKey object.
747
748 use_certificate_file(file[, format])
749 Load the first certificate found in file. The certificate must
750 be in the format specified by format, which is either
751 FILETYPE_PEM or FILETYPE_ASN1. The default is FILETYPE_PEM.
752
753 use_privatekey_file(file[, format])
754 Load the first private key found in file. The private key must
755 be in the format specified by format, which is either
756 FILETYPE_PEM or FILETYPE_ASN1. The default is FILETYPE_PEM.
757
758
759 3.3.2 Connection objects
760
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500761 Connection objects have the following methods:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500762
763 accept()
764 Call the accept method of the underlying socket and set up SSL
765 on the returned socket, using the Context object supplied to
766 this Connection object at creation. Returns a pair (conn,
767 address). where conn is the new Connection object created, and
768 address is as returned by the socket's accept.
769
770 bind(address)
771 Call the bind method of the underlying socket.
772
773 close()
774 Call the close method of the underlying socket. Note: If you
775 want correct SSL closure, you need to call the shutdown method
776 first.
777
778 connect(address)
779 Call the connect method of the underlying socket and set up SSL
780 on the socket, using the Context object supplied to this
781 Connection object at creation.
782
783 connect_ex(address)
784 Call the connect_ex method of the underlying socket and set up
785 SSL on the socket, using the Context object supplied to this
786 Connection object at creation. Note that if the connect_ex
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500787 method of the socket doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500788
789 do_handshake()
790 Perform an SSL handshake (usually called after renegotiate or
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500791 one of set_accept_state or set_accept_state). This can raise the
792 same exceptions as send and recv.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500793
794 fileno()
795 Retrieve the file descriptor number for the underlying socket.
796
797 listen(backlog)
798 Call the listen method of the underlying socket.
799
800 get_app_data()
801 Retrieve application data as set by set_app_data.
802
803 get_cipher_list()
804 Retrieve the list of ciphers used by the Connection object.
805 WARNING: This API has changed. It used to take an optional
806 parameter and just return a string, but not it returns the
807 entire list in one go.
808
809 get_context()
810 Retrieve the Context object associated with this Connection.
811
812 get_peer_certificate()
813 Retrieve the other side's certificate (if any)
814
815 getpeername()
816 Call the getpeername method of the underlying socket.
817
818 getsockname()
819 Call the getsockname method of the underlying socket.
820
821 getsockopt(level, optname[, buflen])
822 Call the getsockopt method of the underlying socket.
823
824 pending()
825 Retrieve the number of bytes that can be safely read from the
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500826 SSL buffer (not the underlying transport buffer).
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500827
828 recv(bufsize)
829 Receive data from the Connection. The return value is a string
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500830 representing the data received. The maximum amount of data to be
831 received at once, is specified by bufsize.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500832
833 renegotiate()
834 Renegotiate the SSL session. Call this if you wish to change
835 cipher suites or anything like that.
836
837 send(string)
838 Send the string data to the Connection.
839
840 sendall(string)
841 Send all of the string data to the Connection. This calls send
842 repeatedly until all data is sent. If an error occurs, it's
843 impossible to tell how much data has been sent.
844
845 set_accept_state()
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500846 Set the connection to work in server mode. The handshake will be
847 handled automatically by read/write.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500848
849 set_app_data(data)
850 Associate data with this Connection object. data can be
851 retrieved later using the get_app_data method.
852
853 set_connect_state()
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500854 Set the connection to work in client mode. The handshake will be
855 handled automatically by read/write.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500856
857 setblocking(flag)
858 Call the setblocking method of the underlying socket.
859
860 setsockopt(level, optname, value)
861 Call the setsockopt method of the underlying socket.
862
863 shutdown()
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500864 Send the shutdown message to the Connection. Returns true if the
865 shutdown message exchange is completed and false otherwise (in
866 which case you call recv() or send() when the connection becomes
867 readable/writeable.
868
869 get_shutdown()
870 Get the shutdown state of the Connection. Returns a bitvector of
871 either or both of SENT_SHUTDOWN and RECEIVED_SHUTDOWN.
872
873 set_shutdown(state)
874 Set the shutdown state of the Connection. state is a bitvector
875 of either or both of SENT_SHUTDOWN and RECEIVED_SHUTDOWN.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500876
877 sock_shutdown(how)
878 Call the shutdown method of the underlying socket.
879
880 state_string()
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500881 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500882
883 want_read()
884 Checks if more data has to be read from the transport layer to
885 complete an operation.
886
887 want_write()
888 Checks if there is data to write to the transport layer to
889 complete an operation.
890
891
892 4 Internals
893
894 We ran into three main problems developing this: Exceptions, callbacks
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500895 and accessing socket methods. This is what this chapter is about.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500896
897
8984.1 Exceptions
899
900 We realized early that most of the exceptions would be raised by the
901 I/O functions of OpenSSL, so it felt natural to mimic OpenSSL's error
902 code system, translating them into Python exceptions. This naturally
903 gives us the exceptions SSL.ZeroReturnError, SSL.WantReadError,
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500904 SSL.WantWriteError, SSL.WantX509LookupError and SSL.SysCallError.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500905
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500906 For more information about this, see section 3.3.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500907
908
9094.2 Callbacks
910
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500911 There are a number of problems with callbacks. First of all, OpenSSL is
912 written as a C library, it's not meant to have Python callbacks, so a
913 way around that is needed. Another problem is thread support. A lot of
914 the OpenSSL I/O functions can block if the socket is in blocking mode,
915 and then you want other Python threads to be able to do other things.
Jean-Paul Calderone657d3ec2008-09-21 18:59:46 -0400916 The real trouble is if you've released the global CPython interpreter
917 lock to do a potentially blocking operation, and the operation calls a
918 callback. Then we must take the GIL back, since calling Python APIs
919 without holding it is not allowed.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500920
921 There are two solutions to the first problem, both of which are
922 necessary. The first solution to use is if the C callback allows
923 ''userdata'' to be passed to it (an arbitrary pointer normally). This
924 is great! We can set our Python function object as the real userdata
925 and emulate userdata for the Python function in another way. The other
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500926 solution can be used if an object with an ''app_data'' system always is
927 passed to the callback. For example, the SSL object in OpenSSL has
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500928 app_data functions and in e.g. the verification callbacks, you can
929 retrieve the related SSL object. What we do is to set our wrapper
930 Connection object as app_data for the SSL object, and we can easily
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500931 find the Python callback.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500932
Jean-Paul Calderone657d3ec2008-09-21 18:59:46 -0400933 The other problem is solved using thread local variables. Whenever the
934 GIL is released before calling into an OpenSSL API, the PyThreadState
935 pointer returned by PyEval_SaveState is stored in a global thread local
936 variable (using Python's own TLS API, PyThread_set_key_value). When it
937 is necessary to re-acquire the GIL, either after the OpenSSL API
938 returns or in a C callback invoked by that OpenSSL API, the value of
939 the thread local variable is retrieved (PyThread_get_key_value) and
940 used to re-acquire the GIL. This allows Python threads to execute while
941 OpenSSL APIs are running and allows use of any particular pyOpenSSL
942 object from any Python thread, since there is no per-thread state
943 associated with any of these objects and since OpenSSL is threadsafe
944 (as long as properly initialized, as pyOpenSSL initializes it).
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500945
946
9474.3 Acessing Socket Methods
948
949 We quickly saw the benefit of wrapping socket methods in the
950 SSL.Connection class, for an easy transition into using SSL. The
951 problem here is that the socket module lacks a C API, and all the
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500952 methods are declared static. One approach would be to have OpenSSL as a
953 submodule to the socket module, placing all the code in socketmodule.c,
954 but this is obviously not a good solution, since you might not want to
955 import tonnes of extra stuff you're not going to use when importing the
956 socket module. The other approach is to somehow get a pointer to the
957 method to be called, either the C function, or a callable Python
958 object. This is not really a good solution either, since there's a lot
959 of lookups involved.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500960
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500961 The way it works is that you have to supply a ``socket-like'' transport
962 object to the SSL.Connection. The only requirement of this object is
963 that it has a fileno() method that returns a file descriptor that's
964 valid at the C level (i.e. you can use the system calls read and
965 write). If you want to use the connect() or accept() methods of the
966 SSL.Connection object, the transport object has to supply such methods
967 too. Apart from them, any method lookups in the SSL.Connection object
968 that fail are passed on to the underlying transport object.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500969
970 Future changes might be to allow Python-level transport objects, that
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500971 instead of having fileno() methods, have read() and write() methods, so
972 more advanced features of Python can be used. This would probably
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500973 entail some sort of OpenSSL ``BIOs'', but converting Python strings
974 back and forth is expensive, so this shouldn't be used unless
975 necessary. Other nice things would be to be able to pass in different
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500976 transport objects for reading and writing, but then the fileno() method
977 of SSL.Connection becomes virtually useless. Also, should the method
978 resolution be used on the read-transport or the write-transport?
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500979
980 About this document ...
981
982 Python OpenSSL Manual
983
984 This document was generated using the LaTeX2HTML translator.
985
986 LaTeX2HTML is Copyright © 1993, 1994, 1995, 1996, 1997, Nikos Drakos,
987 Computer Based Learning Unit, University of Leeds, and Copyright ©
988 1997, 1998, Ross Moore, Mathematics Department, Macquarie University,
989 Sydney.
990
991 The application of LaTeX2HTML to the Python documentation has been
992 heavily tailored by Fred L. Drake, Jr. Original navigation icons were
993 contributed by Christopher Petrilli.
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500994 __________________________________________________________________
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500995
996 Footnotes
997
998 ... M2Crypto^1
Jean-Paul Calderonef1b839d2008-09-01 12:06:06 -0400999 See http://chandlerproject.org/Projects/MeTooCrypto
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001000
Jean-Paul Calderonef1b839d2008-09-01 12:06:06 -04001001 ... Daemon^2
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001002 See http://www.lothar.com/tech/crypto/
1003
Jean-Paul Calderonef1b839d2008-09-01 12:06:06 -04001004 ... socket^3
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001005 Actually, all that is required is an object that behaves like a
1006 socket, you could even use files, even though it'd be tricky to
1007 get the handshakes right!
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -05001008 __________________________________________________________________
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001009
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -05001010 Python OpenSSL Manual
1011 __________________________________________________________________
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001012
Jean-Paul Calderonef7f0fb42008-10-19 11:55:13 -04001013 Release 0.8.