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