blob: cd89173318d87522788f7efb64048b1fbd5bbcbc [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
36 The reason this module exists at all is that the SSL support in the
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -050037 socket module in the Python 2.1 distribution (which is what we used, of
38 course I cannot speak for later versions) is severely limited.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050039
40 When asking about SSL on the comp.lang.python newsgroup (or on
41 python-list@python.org) people usually pointed you to the M2Crypto
42 package. The M2Crypto.SSL module does implement a lot of OpenSSL's
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -050043 functionality but unfortunately its error handling system does not seem
44 to be finished, especially for non-blocking I/O. I think that much of
45 the reason for this is that M2Crypto^1 is developed using SWIG^2. This
46 makes it awkward to create functions that e.g. can return both an
47 integer and NULL since (as far as I know) you basically write C
48 functions and SWIG makes wrapper functions that parses the Python
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050049 argument list and calls your C function, and finally transforms your
50 return value to a Python object.
51
52
53 2 Building and Installing
54
55 These instructions can also be found in the file INSTALL.
56
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -050057 I have tested this on Debian Linux systems (woody and sid), Solaris 2.6
58 and 2.7. Others have successfully compiled it on Windows and NT.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050059
60
612.1 Building the Module on a Unix System
62
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -050063 pyOpenSSL uses distutils, so there really shouldn't be any problems. To
64 build the library:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050065
66python setup.py build
67
68 If your OpenSSL header files aren't in /usr/include, you may need to
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -050069 supply the -I flag to let the setup script know where to look. The same
70 goes for the libraries of course, use the -L flag. Note that build
71 won't accept these flags, so you have to run first build_ext and then
72 build! Example:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050073
74python setup.py build_ext -I/usr/local/ssl/include -L/usr/local/ssl/lib
75python setup.py build
76
77 Now you should have a directory called OpenSSL that contains e.g.
78 SSL.so and __init__.py somewhere in the build dicrectory, so just:
79
80python setup.py install
81
82 If you, for some arcane reason, don't want the module to appear in the
83 site-packages directory, use the --prefix option.
84
85 You can, of course, do
86
87python setup.py --help
88
89 to find out more about how to use the script.
90
91
922.2 Building the Module on a Windows System
93
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -050094 Big thanks to Itamar Shtull-Trauring and Oleg Orlov for their help with
95 Windows build instructions. Same as for Unix systems, we have to
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050096 separate the build_ext and the build.
97
98 Building the library:
99
100setup.py build_ext -I ...\openssl\inc32 -L ...\openssl\out32dll
101setup.py build
102
103 Where ...\openssl is of course the location of your OpenSSL
104 installation.
105
106 Installation is the same as for Unix systems:
107
108setup.py install
109
110 And similarily, you can do
111
112setup.py --help
113
114 to get more information.
115
116
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500117 3 OpenSSL -- Python interface to OpenSSL
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500118
119 This package provides a high-level interface to the functions in the
120 OpenSSL library. The following modules are defined:
121
122 crypto
123 Generic cryptographic module. Note that if anything is
124 incomplete, this module is!
125
126 rand
127 An interface to the OpenSSL pseudo random number generator.
128
129 SSL
130 An interface to the SSL-specific parts of OpenSSL.
131
132
1333.1 crypto -- Generic cryptographic module
134
135 X509Type
136 A Python type object representing the X509 object type.
137
138 X509()
139 Factory function that creates an X509 object.
140
141 X509NameType
142 A Python type object representing the X509Name object type.
143
144 X509Name(x509name)
145 Factory function that creates a copy of x509name.
146
147 X509ReqType
148 A Python type object representing the X509Req object type.
149
150 X509Req()
151 Factory function that creates an X509Req object.
152
153 X509StoreType
154 A Python type object representing the X509Store object type.
155
156 PKeyType
157 A Python type object representing the PKey object type.
158
159 PKey()
160 Factory function that creates a PKey object.
161
162 PKCS7Type
163 A Python type object representing the PKCS7 object type.
164
165 PKCS12Type
166 A Python type object representing the PKCS12 object type.
167
168 X509ExtensionType
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500169 A Python type object representing the X509Extension object type.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500170
171 X509Extension(typename, critical, value)
172 Factory function that creates a X509Extension object.
173
174 NetscapeSPKIType
175 A Python type object representing the NetscapeSPKI object type.
176
177 NetscapeSPKI([enc])
178 Factory function that creates a NetscapeSPKI object. If the enc
179 argument is present, it should be a base64-encoded string
180 representing a NetscapeSPKI object, as returned by the
181 b64_encode method.
182
183 FILETYPE_PEM
184
185 FILETYPE_ASN1
186 File type constants.
187
188 TYPE_RSA
189
190 TYPE_DSA
191 Key type constants.
192
193 exception Error
194 Generic exception used in the crypto module.
195
196 dump_certificate(type, cert)
197 Dump the certificate cert into a buffer string encoded with the
198 type type.
199
200 dump_certificate_request(type, req)
201 Dump the certificate request req into a buffer string encoded
202 with the type type.
203
204 dump_privatekey(type, pkey[, cipher, passphrase])
205 Dump the private key pkey into a buffer string encoded with the
206 type type, optionally (if type is FILETYPE_PEM) encrypting it
207 using cipher and passphrase.
208
209 passphrase must be either a string or a callback for providing
210 the pass phrase.
211
212 load_certificate(type, buffer)
213 Load a certificate (X509) from the string buffer encoded with
214 the type type.
215
216 load_certificate_request(type, buffer)
217 Load a certificate request (X509Req) from the string buffer
218 encoded with the type type.
219
220 load_privatekey(type, buffer[, passphrase])
221 Load a private key (PKey) from the string buffer encoded with
222 the type type (must be one of FILETYPE_PEM and FILETYPE_ASN1).
223
224 passphrase must be either a string or a callback for providing
225 the pass phrase.
226
227 load_pkcs7_data(type, buffer)
228 Load pkcs7 data from the string buffer encoded with the type
229 type.
230
231 load_pkcs12(buffer[, passphrase])
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500232 Load pkcs12 data from the string buffer. If the pkcs12 structure
233 is encrypted, a passphrase must be included.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500234
235
236 3.1.1 X509 objects
237
238 X509 objects have the following methods:
239
240 get_issuer()
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -0500241 Return an X509Name object representing the issuer of the
242 certificate.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500243
244 get_pubkey()
245 Return a PKey object representing the public key of the
246 certificate.
247
248 get_serial_number()
249 Return the certificate serial number.
250
251 get_subject()
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -0500252 Return an X509Name object representing the subject of the
253 certificate.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500254
255 get_version()
256 Return the certificate version.
257
Jean-Paul Calderone525ef802008-03-09 20:39:42 -0400258 get_notBefore()
259 Return a string giving the time before which the certificate is
260 not valid. The string is formatted as an ASN1 GENERALIZEDTIME:
261
262 YYYYMMDDhhmmssZ
263 YYYYMMDDhhmmss+hhmm
264 YYYYMMDDhhmmss-hhmm
265
266 get_notAfter()
267 Return a string giving the time after which the certificate is
268 not valid. The string is formatted as an ASN1 GENERALIZEDTIME:
269
270 YYYYMMDDhhmmssZ
271 YYYYMMDDhhmmss+hhmm
272 YYYYMMDDhhmmss-hhmm
273
274 set_notBefore(when)
275 Change the time before which the certificate is not valid. when
276 is a string formatted as an ASN1 GENERALIZEDTIME:
277
278 YYYYMMDDhhmmssZ
279 YYYYMMDDhhmmss+hhmm
280 YYYYMMDDhhmmss-hhmm
281
282 set_notAfter(when)
283 Change the time after which the certificate is not valid. when
284 is a string formatted as an ASN1 GENERALIZEDTIME:
285
286 YYYYMMDDhhmmssZ
287 YYYYMMDDhhmmss+hhmm
288 YYYYMMDDhhmmss-hhmm
289
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500290 gmtime_adj_notBefore(time)
291 Adjust the timestamp (in GMT) when the certificate starts being
292 valid.
293
294 gmtime_adj_notAfter(time)
295 Adjust the timestamp (in GMT) when the certificate stops being
296 valid.
297
298 has_expired()
299 Checks the certificate's time stamp against current time.
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500300 Returns true if the certificate has expired and false otherwise.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500301
302 set_issuer(issuer)
303 Set the issuer of the certificate to issuer.
304
305 set_pubkey(pkey)
306 Set the public key of the certificate to pkey.
307
308 set_serial_number(serialno)
309 Set the serial number of the certificate to serialno.
310
311 set_subject(subject)
312 Set the subject of the certificate to subject.
313
314 set_version(version)
315 Set the certificate version to version.
316
317 sign(pkey, digest)
318 Sign the certificate, using the key pkey and the message digest
319 algorithm identified by the string digest.
320
321 subject_name_hash()
322 Return the hash of the certificate subject.
323
324 digest(digest_name)
325 Return a digest of the certificate, using the digest_name
326 method.
327
328 add_extensions(extensions)
329 Add the extensions in the sequence extensions to the
330 certificate.
331
332
333 3.1.2 X509Name objects
334
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500335 X509Name objects have the following members:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500336
337 countryName
338 The country of the entity. C may be used as an alias for
339 countryName.
340
341 stateOrProvinceName
342 The state or province of the entity. ST may be used as an alias
343 for stateOrProvinceName·
344
345 localityName
346 The locality of the entity. L may be used as an alias for
347 localityName.
348
349 organizationName
350 The organization name of the entity. O may be used as an alias
351 for organizationName.
352
353 organizationalUnitName
354 The organizational unit of the entity. OU may be used as an
355 alias for organizationalUnitName.
356
357 commonName
358 The common name of the entity. CN may be used as an alias for
359 commonName.
360
361 emailAddress
362 The e-mail address of the entity.
363
364
365 3.1.3 X509Req objects
366
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500367 X509Req objects have the following methods:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500368
369 get_pubkey()
370 Return a PKey object representing the public key of the
371 certificate request.
372
373 get_subject()
Jean-Paul Calderone2aa2b332008-03-06 21:43:14 -0500374 Return an X509Name object representing the subject of the
375 certificate.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500376
377 set_pubkey(pkey)
378 Set the public key of the certificate request to pkey.
379
380 sign(pkey, digest)
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500381 Sign the certificate request, using the key pkey and the message
382 digest algorithm identified by the string digest.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500383
384 verify(pkey)
385 Verify a certificate request using the public key pkey.
386
387
388 3.1.4 X509Store objects
389
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500390 The X509Store object has currently just one method:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500391
392 add_cert(cert)
393 Add the certificate cert to the certificate store.
394
395
396 3.1.5 PKey objects
397
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500398 The PKey object has the following methods:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500399
400 bits()
401 Return the number of bits of the key.
402
403 generate_key(type, bits)
404 Generate a public/private key pair of the type type (one of
405 TYPE_RSA and TYPE_DSA) with the size bits.
406
407 type()
408 Return the type of the key.
409
410
411 3.1.6 PKCS7 objects
412
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500413 PKCS7 objects have the following methods:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500414
415 type_is_signed()
416 FIXME
417
418 type_is_enveloped()
419 FIXME
420
421 type_is_signedAndEnveloped()
422 FIXME
423
424 type_is_data()
425 FIXME
426
427 get_type_name()
428 Get the type name of the PKCS7.
429
430
431 3.1.7 PKCS12 objects
432
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500433 PKCS12 objects have the following methods:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500434
435 get_certificate()
436 Return certificate portion of the PKCS12 structure.
437
438 get_privatekey()
439 Return private key portion of the PKCS12 structure
440
441 get_ca_certificates()
442 Return CA certificates within the PKCS12 object as a tuple.
443 Returns None if no CA certificates are present.
444
445
446 3.1.8 X509Extension objects
447
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500448 X509Extension objects currently only have one method:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500449
450 get_critical()
451 Return the critical field of the extension object.
452
453
454 3.1.9 NetscapeSPKI objects
455
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500456 NetscapeSPKI objects have the following methods:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500457
458 b64_encode()
459 Return a base64-encoded string representation of the object.
460
461 get_pubkey()
462 Return the public key of object.
463
464 set_pubkey(key)
465 Set the public key of the object to key.
466
467 sign(key, digest_name)
468 Sign the NetscapeSPKI object using the given key and
469 digest_name.
470
471 verify(key)
472 Verify the NetscapeSPKI object using the given key.
473
474
4753.2 rand -- An interface to the OpenSSL pseudo random number generator
476
477 This module handles the OpenSSL pseudo random number generator (PRNG)
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500478 and declares the following:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500479
480 add(string, entropy)
481 Mix bytes from string into the PRNG state. The entropy argument
482 is (the lower bound of) an estimate of how much randomness is
483 contained in string, measured in bytes. For more information,
484 see e.g. RFC 1750.
485
486 egd(path[, bytes])
487 Query the Entropy Gathering Daemon^3 on socket path for bytes
488 bytes of random data and and uses add to seed the PRNG. The
489 default value of bytes is 255.
490
491 load_file(path[, bytes])
492 Read bytes bytes (or all of it, if bytes is negative) of data
493 from the file path to seed the PRNG. The default value of bytes
494 is -1.
495
496 screen()
497 Add the current contents of the screen to the PRNG state.
498 Availability: Windows.
499
500 seed(string)
501 This is equivalent to calling add with entropy as the length of
502 the string.
503
504 status()
505 Returns true if the PRNG has been seeded with enough data, and
506 false otherwise.
507
508 write_file(path)
509 Write a number of random bytes (currently 1024) to the file
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500510 path. This file can then be used with load_file to seed the PRNG
511 again.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500512
513
5143.3 SSL -- An interface to the SSL-specific parts of OpenSSL
515
516 This module handles things specific to SSL. There are two objects
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500517 defined: Context, Connection.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500518
519 SSLv2_METHOD
520
521 SSLv3_METHOD
522
523 SSLv23_METHOD
524
525 TLSv1_METHOD
526 These constants represent the different SSL methods to use when
527 creating a context object.
528
529 VERIFY_NONE
530
531 VERIFY_PEER
532
533 VERIFY_FAIL_IF_NO_PEER_CERT
534 These constants represent the verification mode used by the
535 Context object's set_verify method.
536
537 FILETYPE_PEM
538
539 FILETYPE_ASN1
540 File type constants used with the use_certificate_file and
541 use_privatekey_file methods of Context objects.
542
543 OP_SINGLE_DH_USE
544
545 OP_EPHEMERAL_RSA
546
547 OP_NO_SSLv2
548
549 OP_NO_SSLv3
550
551 OP_NO_TLSv1
552 Constants used with set_options of Context objects.
553 OP_SINGLE_DH_USE means to always create a new key when using
554 ephemeral Diffie-Hellman. OP_EPHEMERAL_RSA means to always use
555 ephemeral RSA keys when doing RSA operations. OP_NO_SSLv2,
556 OP_NO_SSLv3 and OP_NO_TLSv1 means to disable those specific
557 protocols. This is interesting if you're using e.g.
558 SSLv23_METHOD to get an SSLv2-compatible handshake, but don't
559 want to use SSLv2.
560
561 ContextType
562 A Python type object representing the Context object type.
563
564 Context(method)
565 Factory function that creates a new Context object given an SSL
566 method. The method should be SSLv2_METHOD, SSLv3_METHOD,
567 SSLv23_METHOD or TLSv1_METHOD.
568
569 ConnectionType
570 A Python type object representing the Connection object type.
571
572 Connection(context, socket)
573 Factory fucnction that creates a new Connection object given an
574 SSL context and a socket ^4 object.
575
576 exception Error
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500577 This exception is used as a base class for the other SSL-related
578 exceptions, but may also be raised directly.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500579
580 Whenever this exception is raised directly, it has a list of
581 error messages from the OpenSSL error queue, where each item is
582 a tuple (lib, function, reason). Here lib, function and reason
583 are all strings, describing where and what the problem is. See
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500584 err(3) for more information.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500585
586 exception ZeroReturnError
587 This exception matches the error return code
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500588 SSL_ERROR_ZERO_RETURN, and is raised when the SSL Connection has
589 been closed. In SSL 3.0 and TLS 1.0, this only occurs if a
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500590 closure alert has occurred in the protocol, i.e. the connection
591 has been closed cleanly. Note that this does not necessarily
592 mean that the transport layer (e.g. a socket) has been closed.
593
594 It may seem a little strange that this is an exception, but it
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500595 does match an SSL_ERROR code, and is very convenient.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500596
597 exception WantReadError
598 The operation did not complete; the same I/O method should be
599 called again later, with the same arguments. Any I/O method can
600 lead to this since new handshakes can occur at any time.
601
602 exception WantWriteError
603 See WantReadError.
604
605 exception WantX509LookupError
606 The operation did not complete because an application callback
607 has asked to be called again. The I/O method should be called
608 again later, with the same arguments. Note: This won't occur in
609 this version, as there are no such callbacks in this version.
610
611 exception SysCallError
612 The SysCallError occurs when there's an I/O error and OpenSSL's
613 error queue does not contain any information. This can mean two
614 things: An error in the transport protocol, or an end of file
615 that violates the protocol. The parameter to the exception is
616 always a pair (errnum, errstr).
617
618
619 3.3.1 Context objects
620
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500621 Context objects have the following methods:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500622
623 check_privatekey()
624 Check if the private key (loaded with use_privatekey[_file])
625 matches the certificate (loaded with use_certificate[_file]).
Jean-Paul Calderonef05fbbe2008-03-06 21:52:35 -0500626 Returns None if they match, raises Error otherwise.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500627
628 get_app_data()
629 Retrieve application data as set by set_app_data.
630
631 get_cert_store()
632 Retrieve the certificate store (a X509Store object) that the
633 context uses. This can be used to add "trusted" certificates
634 without using the. load_verify_locations() method.
635
636 get_timeout()
637 Retrieve session timeout, as set by set_timeout. The default is
638 300 seconds.
639
640 get_verify_depth()
641 Retrieve the Context object's verify depth, as set by
642 set_verify_depth.
643
644 get_verify_mode()
645 Retrieve the Context object's verify mode, as set by
646 set_verify_mode.
647
648 load_client_ca(pemfile)
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500649 Read a file with PEM-formatted certificates that will be sent to
650 the client when requesting a client certificate.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500651
652 load_verify_locations(pemfile)
653 Specify where CA certificates for verification purposes are
654 located. These are trusted certificates. Note that the
655 certificates have to be in PEM format.
656
657 load_tmp_dh(dhfile)
658 Load parameters for Ephemeral Diffie-Hellman from dhfile.
659
660 set_app_data(data)
661 Associate data with this Context object. data can be retrieved
662 later using the get_app_data method.
663
664 set_cipher_list(ciphers)
665 Set the list of ciphers to be used in this context. See the
666 OpenSSL manual for more information (e.g. ciphers(1))
667
668 set_info_callback(callback)
669 Set the information callback to callback. This function will be
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500670 called from time to time during SSL handshakes. callback should
671 take three arguments: a Connection object and two integers. The
672 first integer specifies where in the SSL handshake the function
673 was called, and the other the return code from a (possibly
674 failed) internal function call.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500675
676 set_options(options)
677 Add SSL options. Options you have set before are not cleared!
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500678 This method should be used with the OP_* constants.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500679
680 set_passwd_cb(callback[, userdata])
681 Set the passphrase callback to callback. This function will be
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500682 called when a private key with a passphrase is loaded. callback
683 should take a boolean argument repeat and an arbitrary argument
684 data and return the passphrase entered by the user. If repeat is
685 true then callback should ask for the passphrase twice and make
686 sure that the two entries are equal. The data argument is the
687 userdata variable passed to the set_passwd_cb method. If an
688 error occurs, callback should return a false value (e.g. an
689 empty string).
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500690
691 set_session_id(name)
692 Set the context name within which a session can be reused for
693 this Context object. This is needed when doing session
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500694 resumption, because there is no way for a stored session to know
695 which Context object it is associated with. name may be any
696 binary data.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500697
698 set_timeout(timeout)
699 Set the timeout for newly created sessions for this Context
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500700 object to timeout. timeout must be given in (whole) seconds. The
701 default value is 300 seconds. See the OpenSSL manual for more
702 information (e.g. SSL_CTX_set_timeout(3)).
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500703
704 set_verify(mode, callback)
705 Set the verification flags for this Context object to mode and
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500706 specify that callback should be used for verification callbacks.
707 mode should be one of VERIFY_NONE and VERIFY_PEER. If
708 VERIFY_PEER is used, mode can be OR:ed with
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500709 VERIFY_FAIL_IF_NO_PEER_CERT and VERIFY_CLIENT_ONCE to further
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500710 control the behaviour. callback should take five arguments: A
711 Connection object, an X509 object, and three integer variables,
712 which are in turn potential error number, error depth and return
713 code. callback should return true if verification passes and
714 false otherwise.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500715
716 set_verify_depth(depth)
717 Set the maximum depth for the certificate chain verification
718 that shall be allowed for this Context object.
719
720 use_certificate(cert)
721 Use the certificate cert which has to be a X509 object.
722
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500723 add_extra_chain_cert(cert)
724 Adds the certificate cert, which has to be a X509 object, to the
725 certificate chain presented together with the certificate.
726
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500727 use_certificate_chain_file(file)
728 Load a certificate chain from file which must be PEM encoded.
729
730 use_privatekey(pkey)
731 Use the private key pkey which has to be a PKey object.
732
733 use_certificate_file(file[, format])
734 Load the first certificate found in file. The certificate must
735 be in the format specified by format, which is either
736 FILETYPE_PEM or FILETYPE_ASN1. The default is FILETYPE_PEM.
737
738 use_privatekey_file(file[, format])
739 Load the first private key found in file. The private key must
740 be in the format specified by format, which is either
741 FILETYPE_PEM or FILETYPE_ASN1. The default is FILETYPE_PEM.
742
743
744 3.3.2 Connection objects
745
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500746 Connection objects have the following methods:
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500747
748 accept()
749 Call the accept method of the underlying socket and set up SSL
750 on the returned socket, using the Context object supplied to
751 this Connection object at creation. Returns a pair (conn,
752 address). where conn is the new Connection object created, and
753 address is as returned by the socket's accept.
754
755 bind(address)
756 Call the bind method of the underlying socket.
757
758 close()
759 Call the close method of the underlying socket. Note: If you
760 want correct SSL closure, you need to call the shutdown method
761 first.
762
763 connect(address)
764 Call the connect method of the underlying socket and set up SSL
765 on the socket, using the Context object supplied to this
766 Connection object at creation.
767
768 connect_ex(address)
769 Call the connect_ex method of the underlying socket and set up
770 SSL on the socket, using the Context object supplied to this
771 Connection object at creation. Note that if the connect_ex
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500772 method of the socket doesn't return 0, SSL won't be initialized.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500773
774 do_handshake()
775 Perform an SSL handshake (usually called after renegotiate or
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500776 one of set_accept_state or set_accept_state). This can raise the
777 same exceptions as send and recv.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500778
779 fileno()
780 Retrieve the file descriptor number for the underlying socket.
781
782 listen(backlog)
783 Call the listen method of the underlying socket.
784
785 get_app_data()
786 Retrieve application data as set by set_app_data.
787
788 get_cipher_list()
789 Retrieve the list of ciphers used by the Connection object.
790 WARNING: This API has changed. It used to take an optional
791 parameter and just return a string, but not it returns the
792 entire list in one go.
793
794 get_context()
795 Retrieve the Context object associated with this Connection.
796
797 get_peer_certificate()
798 Retrieve the other side's certificate (if any)
799
800 getpeername()
801 Call the getpeername method of the underlying socket.
802
803 getsockname()
804 Call the getsockname method of the underlying socket.
805
806 getsockopt(level, optname[, buflen])
807 Call the getsockopt method of the underlying socket.
808
809 pending()
810 Retrieve the number of bytes that can be safely read from the
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500811 SSL buffer (not the underlying transport buffer).
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500812
813 recv(bufsize)
814 Receive data from the Connection. The return value is a string
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500815 representing the data received. The maximum amount of data to be
816 received at once, is specified by bufsize.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500817
818 renegotiate()
819 Renegotiate the SSL session. Call this if you wish to change
820 cipher suites or anything like that.
821
822 send(string)
823 Send the string data to the Connection.
824
825 sendall(string)
826 Send all of the string data to the Connection. This calls send
827 repeatedly until all data is sent. If an error occurs, it's
828 impossible to tell how much data has been sent.
829
830 set_accept_state()
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500831 Set the connection to work in server mode. The handshake will be
832 handled automatically by read/write.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500833
834 set_app_data(data)
835 Associate data with this Connection object. data can be
836 retrieved later using the get_app_data method.
837
838 set_connect_state()
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500839 Set the connection to work in client mode. The handshake will be
840 handled automatically by read/write.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500841
842 setblocking(flag)
843 Call the setblocking method of the underlying socket.
844
845 setsockopt(level, optname, value)
846 Call the setsockopt method of the underlying socket.
847
848 shutdown()
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500849 Send the shutdown message to the Connection. Returns true if the
850 shutdown message exchange is completed and false otherwise (in
851 which case you call recv() or send() when the connection becomes
852 readable/writeable.
853
854 get_shutdown()
855 Get the shutdown state of the Connection. Returns a bitvector of
856 either or both of SENT_SHUTDOWN and RECEIVED_SHUTDOWN.
857
858 set_shutdown(state)
859 Set the shutdown state of the Connection. state is a bitvector
860 of either or both of SENT_SHUTDOWN and RECEIVED_SHUTDOWN.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500861
862 sock_shutdown(how)
863 Call the shutdown method of the underlying socket.
864
865 state_string()
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500866 Retrieve a verbose string detailing the state of the Connection.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500867
868 want_read()
869 Checks if more data has to be read from the transport layer to
870 complete an operation.
871
872 want_write()
873 Checks if there is data to write to the transport layer to
874 complete an operation.
875
876
877 4 Internals
878
879 We ran into three main problems developing this: Exceptions, callbacks
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500880 and accessing socket methods. This is what this chapter is about.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500881
882
8834.1 Exceptions
884
885 We realized early that most of the exceptions would be raised by the
886 I/O functions of OpenSSL, so it felt natural to mimic OpenSSL's error
887 code system, translating them into Python exceptions. This naturally
888 gives us the exceptions SSL.ZeroReturnError, SSL.WantReadError,
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500889 SSL.WantWriteError, SSL.WantX509LookupError and SSL.SysCallError.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500890
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500891 For more information about this, see section 3.3.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500892
893
8944.2 Callbacks
895
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500896 There are a number of problems with callbacks. First of all, OpenSSL is
897 written as a C library, it's not meant to have Python callbacks, so a
898 way around that is needed. Another problem is thread support. A lot of
899 the OpenSSL I/O functions can block if the socket is in blocking mode,
900 and then you want other Python threads to be able to do other things.
901 The real trouble is if you've released the thread lock to do a
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500902 potentially blocking operation, and the operation calls a callback.
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500903 Then we must take the thread lock back^5.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500904
905 There are two solutions to the first problem, both of which are
906 necessary. The first solution to use is if the C callback allows
907 ''userdata'' to be passed to it (an arbitrary pointer normally). This
908 is great! We can set our Python function object as the real userdata
909 and emulate userdata for the Python function in another way. The other
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500910 solution can be used if an object with an ''app_data'' system always is
911 passed to the callback. For example, the SSL object in OpenSSL has
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500912 app_data functions and in e.g. the verification callbacks, you can
913 retrieve the related SSL object. What we do is to set our wrapper
914 Connection object as app_data for the SSL object, and we can easily
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500915 find the Python callback.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500916
917 The other problem is also partially solved by app_data. Since we're
918 associating our wrapper objects with the ''real'' objects, we can
919 easily access data from the Connection object. The solution then is to
920 simply include a PyThreadState variable in the Connection declaration,
921 and write macros similar to Py_BEGIN_ALLOW_THREADS and
922 Py_END_ALLOW_THREADS that allows specifying of the PyThreadState
923 variable to use. Now we can simply ''begin allow threads'' before a
924 potentially blocking operation, and ''end allow threads'' before
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500925 calling a callback.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500926
927
9284.3 Acessing Socket Methods
929
930 We quickly saw the benefit of wrapping socket methods in the
931 SSL.Connection class, for an easy transition into using SSL. The
932 problem here is that the socket module lacks a C API, and all the
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500933 methods are declared static. One approach would be to have OpenSSL as a
934 submodule to the socket module, placing all the code in socketmodule.c,
935 but this is obviously not a good solution, since you might not want to
936 import tonnes of extra stuff you're not going to use when importing the
937 socket module. The other approach is to somehow get a pointer to the
938 method to be called, either the C function, or a callable Python
939 object. This is not really a good solution either, since there's a lot
940 of lookups involved.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500941
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500942 The way it works is that you have to supply a ``socket-like'' transport
943 object to the SSL.Connection. The only requirement of this object is
944 that it has a fileno() method that returns a file descriptor that's
945 valid at the C level (i.e. you can use the system calls read and
946 write). If you want to use the connect() or accept() methods of the
947 SSL.Connection object, the transport object has to supply such methods
948 too. Apart from them, any method lookups in the SSL.Connection object
949 that fail are passed on to the underlying transport object.
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500950
951 Future changes might be to allow Python-level transport objects, that
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500952 instead of having fileno() methods, have read() and write() methods, so
953 more advanced features of Python can be used. This would probably
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500954 entail some sort of OpenSSL ``BIOs'', but converting Python strings
955 back and forth is expensive, so this shouldn't be used unless
956 necessary. Other nice things would be to be able to pass in different
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500957 transport objects for reading and writing, but then the fileno() method
958 of SSL.Connection becomes virtually useless. Also, should the method
959 resolution be used on the read-transport or the write-transport?
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500960
961 About this document ...
962
963 Python OpenSSL Manual
964
965 This document was generated using the LaTeX2HTML translator.
966
967 LaTeX2HTML is Copyright © 1993, 1994, 1995, 1996, 1997, Nikos Drakos,
968 Computer Based Learning Unit, University of Leeds, and Copyright ©
969 1997, 1998, Ross Moore, Mathematics Department, Macquarie University,
970 Sydney.
971
972 The application of LaTeX2HTML to the Python documentation has been
973 heavily tailored by Fred L. Drake, Jr. Original navigation icons were
974 contributed by Christopher Petrilli.
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500975 __________________________________________________________________
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500976
977 Footnotes
978
979 ... M2Crypto^1
980 See http://www.post1.com/home/ngps/m2/
981
982 ... SWIG^2
983 See http://swig.sourceforge.net/
984
985 ... Daemon^3
986 See http://www.lothar.com/tech/crypto/
987
988 ... socket^4
989 Actually, all that is required is an object that behaves like a
990 socket, you could even use files, even though it'd be tricky to
991 get the handshakes right!
992
993 ... back^5
994 I'm not sure why this is necessary, but otherwise I get a
995 segmentation violation on PyEval_CallObject
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500996 __________________________________________________________________
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500997
Jean-Paul Calderoneb6f57be2008-03-06 21:22:16 -0500998 Python OpenSSL Manual
999 __________________________________________________________________
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001000
1001 Release 0.6.