blob: 9fe700199055681f35df8fd5dbaf0c743d4bfe3d [file] [log] [blame]
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001from sys import platform
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05002from functools import wraps, partial
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08003from itertools import count
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08004from weakref import WeakValueDictionary
5from errno import errorcode
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -08006
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05007from six import text_type as _text_type
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -08008from six import integer_types as integer_types
Jean-Paul Calderone63eab692014-01-18 10:19:56 -05009
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050010from OpenSSL._util import (
11 ffi as _ffi,
12 lib as _lib,
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050013 exception_from_error_queue as _exception_from_error_queue,
14 native as _native)
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080015
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080016from OpenSSL.crypto import (
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050017 FILETYPE_PEM, _PassphraseHelper, PKey, X509Name, X509, X509Store)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -080018
19_unspecified = object()
20
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -050021try:
22 _memoryview = memoryview
23except NameError:
24 class _memoryview(object):
25 pass
26
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050027OPENSSL_VERSION_NUMBER = _lib.OPENSSL_VERSION_NUMBER
28SSLEAY_VERSION = _lib.SSLEAY_VERSION
29SSLEAY_CFLAGS = _lib.SSLEAY_CFLAGS
30SSLEAY_PLATFORM = _lib.SSLEAY_PLATFORM
31SSLEAY_DIR = _lib.SSLEAY_DIR
32SSLEAY_BUILT_ON = _lib.SSLEAY_BUILT_ON
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080033
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050034SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
35RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080036
37SSLv2_METHOD = 1
38SSLv3_METHOD = 2
39SSLv23_METHOD = 3
40TLSv1_METHOD = 4
Jean-Paul Calderone56bff942013-11-03 11:30:43 -050041TLSv1_1_METHOD = 5
42TLSv1_2_METHOD = 6
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080043
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050044OP_NO_SSLv2 = _lib.SSL_OP_NO_SSLv2
45OP_NO_SSLv3 = _lib.SSL_OP_NO_SSLv3
46OP_NO_TLSv1 = _lib.SSL_OP_NO_TLSv1
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -050047
48OP_NO_TLSv1_1 = getattr(_lib, "SSL_OP_NO_TLSv1_1", 0)
49OP_NO_TLSv1_2 = getattr(_lib, "SSL_OP_NO_TLSv1_2", 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080050
Jean-Paul Calderone0d7e8a12014-01-08 16:54:13 -050051try:
52 MODE_RELEASE_BUFFERS = _lib.SSL_MODE_RELEASE_BUFFERS
53except AttributeError:
54 pass
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080055
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050056OP_SINGLE_DH_USE = _lib.SSL_OP_SINGLE_DH_USE
57OP_EPHEMERAL_RSA = _lib.SSL_OP_EPHEMERAL_RSA
58OP_MICROSOFT_SESS_ID_BUG = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
59OP_NETSCAPE_CHALLENGE_BUG = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
60OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = _lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
61OP_SSLREF2_REUSE_CERT_TYPE_BUG = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
62OP_MICROSOFT_BIG_SSLV3_BUFFER = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Jean-Paul Calderone0d7e8a12014-01-08 16:54:13 -050063try:
64 OP_MSIE_SSLV2_RSA_PADDING = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
65except AttributeError:
66 pass
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050067OP_SSLEAY_080_CLIENT_DH_BUG = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
68OP_TLS_D5_BUG = _lib.SSL_OP_TLS_D5_BUG
69OP_TLS_BLOCK_PADDING_BUG = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
70OP_DONT_INSERT_EMPTY_FRAGMENTS = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
71OP_CIPHER_SERVER_PREFERENCE = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
72OP_TLS_ROLLBACK_BUG = _lib.SSL_OP_TLS_ROLLBACK_BUG
73OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
74OP_PKCS1_CHECK_2 = _lib.SSL_OP_PKCS1_CHECK_2
75OP_NETSCAPE_CA_DN_BUG = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
76OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG= _lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
Jean-Paul Calderonec1780342014-01-08 16:59:03 -050077try:
78 OP_NO_COMPRESSION = _lib.SSL_OP_NO_COMPRESSION
79except AttributeError:
80 pass
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080081
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050082OP_NO_QUERY_MTU = _lib.SSL_OP_NO_QUERY_MTU
83OP_COOKIE_EXCHANGE = _lib.SSL_OP_COOKIE_EXCHANGE
84OP_NO_TICKET = _lib.SSL_OP_NO_TICKET
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -080085
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050086OP_ALL = _lib.SSL_OP_ALL
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080087
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050088VERIFY_PEER = _lib.SSL_VERIFY_PEER
89VERIFY_FAIL_IF_NO_PEER_CERT = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
90VERIFY_CLIENT_ONCE = _lib.SSL_VERIFY_CLIENT_ONCE
91VERIFY_NONE = _lib.SSL_VERIFY_NONE
Jean-Paul Calderone935d2da2013-03-04 08:11:19 -080092
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050093SESS_CACHE_OFF = _lib.SSL_SESS_CACHE_OFF
94SESS_CACHE_CLIENT = _lib.SSL_SESS_CACHE_CLIENT
95SESS_CACHE_SERVER = _lib.SSL_SESS_CACHE_SERVER
96SESS_CACHE_BOTH = _lib.SSL_SESS_CACHE_BOTH
97SESS_CACHE_NO_AUTO_CLEAR = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
98SESS_CACHE_NO_INTERNAL_LOOKUP = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
99SESS_CACHE_NO_INTERNAL_STORE = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
100SESS_CACHE_NO_INTERNAL = _lib.SSL_SESS_CACHE_NO_INTERNAL
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800101
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500102SSL_ST_CONNECT = _lib.SSL_ST_CONNECT
103SSL_ST_ACCEPT = _lib.SSL_ST_ACCEPT
104SSL_ST_MASK = _lib.SSL_ST_MASK
105SSL_ST_INIT = _lib.SSL_ST_INIT
106SSL_ST_BEFORE = _lib.SSL_ST_BEFORE
107SSL_ST_OK = _lib.SSL_ST_OK
108SSL_ST_RENEGOTIATE = _lib.SSL_ST_RENEGOTIATE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800109
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500110SSL_CB_LOOP = _lib.SSL_CB_LOOP
111SSL_CB_EXIT = _lib.SSL_CB_EXIT
112SSL_CB_READ = _lib.SSL_CB_READ
113SSL_CB_WRITE = _lib.SSL_CB_WRITE
114SSL_CB_ALERT = _lib.SSL_CB_ALERT
115SSL_CB_READ_ALERT = _lib.SSL_CB_READ_ALERT
116SSL_CB_WRITE_ALERT = _lib.SSL_CB_WRITE_ALERT
117SSL_CB_ACCEPT_LOOP = _lib.SSL_CB_ACCEPT_LOOP
118SSL_CB_ACCEPT_EXIT = _lib.SSL_CB_ACCEPT_EXIT
119SSL_CB_CONNECT_LOOP = _lib.SSL_CB_CONNECT_LOOP
120SSL_CB_CONNECT_EXIT = _lib.SSL_CB_CONNECT_EXIT
121SSL_CB_HANDSHAKE_START = _lib.SSL_CB_HANDSHAKE_START
122SSL_CB_HANDSHAKE_DONE = _lib.SSL_CB_HANDSHAKE_DONE
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800123
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800124
Andy Lutomirskib4e5c8d2014-03-05 12:54:15 -0800125NID_X9_62_c2pnb163v1 = _lib.NID_X9_62_c2pnb163v1
126SN_X9_62_c2pnb163v1 = _ffi.string(_lib.SN_X9_62_c2pnb163v1)
127NID_X9_62_c2pnb163v2 = _lib.NID_X9_62_c2pnb163v2
128SN_X9_62_c2pnb163v2 = _ffi.string(_lib.SN_X9_62_c2pnb163v2)
129NID_X9_62_c2pnb163v3 = _lib.NID_X9_62_c2pnb163v3
130SN_X9_62_c2pnb163v3 = _ffi.string(_lib.SN_X9_62_c2pnb163v3)
131NID_X9_62_c2pnb176v1 = _lib.NID_X9_62_c2pnb176v1
132SN_X9_62_c2pnb176v1 = _ffi.string(_lib.SN_X9_62_c2pnb176v1)
133NID_X9_62_c2tnb191v1 = _lib.NID_X9_62_c2tnb191v1
134SN_X9_62_c2tnb191v1 = _ffi.string(_lib.SN_X9_62_c2tnb191v1)
135NID_X9_62_c2tnb191v2 = _lib.NID_X9_62_c2tnb191v2
136SN_X9_62_c2tnb191v2 = _ffi.string(_lib.SN_X9_62_c2tnb191v2)
137NID_X9_62_c2tnb191v3 = _lib.NID_X9_62_c2tnb191v3
138SN_X9_62_c2tnb191v3 = _ffi.string(_lib.SN_X9_62_c2tnb191v3)
139NID_X9_62_c2onb191v4 = _lib.NID_X9_62_c2onb191v4
140SN_X9_62_c2onb191v4 = _ffi.string(_lib.SN_X9_62_c2onb191v4)
141NID_X9_62_c2onb191v5 = _lib.NID_X9_62_c2onb191v5
142SN_X9_62_c2onb191v5 = _ffi.string(_lib.SN_X9_62_c2onb191v5)
143NID_X9_62_c2pnb208w1 = _lib.NID_X9_62_c2pnb208w1
144SN_X9_62_c2pnb208w1 = _ffi.string(_lib.SN_X9_62_c2pnb208w1)
145NID_X9_62_c2tnb239v1 = _lib.NID_X9_62_c2tnb239v1
146SN_X9_62_c2tnb239v1 = _ffi.string(_lib.SN_X9_62_c2tnb239v1)
147NID_X9_62_c2tnb239v2 = _lib.NID_X9_62_c2tnb239v2
148SN_X9_62_c2tnb239v2 = _ffi.string(_lib.SN_X9_62_c2tnb239v2)
149NID_X9_62_c2tnb239v3 = _lib.NID_X9_62_c2tnb239v3
150SN_X9_62_c2tnb239v3 = _ffi.string(_lib.SN_X9_62_c2tnb239v3)
151NID_X9_62_c2onb239v4 = _lib.NID_X9_62_c2onb239v4
152SN_X9_62_c2onb239v4 = _ffi.string(_lib.SN_X9_62_c2onb239v4)
153NID_X9_62_c2onb239v5 = _lib.NID_X9_62_c2onb239v5
154SN_X9_62_c2onb239v5 = _ffi.string(_lib.SN_X9_62_c2onb239v5)
155NID_X9_62_c2pnb272w1 = _lib.NID_X9_62_c2pnb272w1
156SN_X9_62_c2pnb272w1 = _ffi.string(_lib.SN_X9_62_c2pnb272w1)
157NID_X9_62_c2pnb304w1 = _lib.NID_X9_62_c2pnb304w1
158SN_X9_62_c2pnb304w1 = _ffi.string(_lib.SN_X9_62_c2pnb304w1)
159NID_X9_62_c2tnb359v1 = _lib.NID_X9_62_c2tnb359v1
160SN_X9_62_c2tnb359v1 = _ffi.string(_lib.SN_X9_62_c2tnb359v1)
161NID_X9_62_c2pnb368w1 = _lib.NID_X9_62_c2pnb368w1
162SN_X9_62_c2pnb368w1 = _ffi.string(_lib.SN_X9_62_c2pnb368w1)
163NID_X9_62_c2tnb431r1 = _lib.NID_X9_62_c2tnb431r1
164SN_X9_62_c2tnb431r1 = _ffi.string(_lib.SN_X9_62_c2tnb431r1)
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600165NID_X9_62_prime192v1 = _lib.NID_X9_62_prime192v1
Andy Lutomirskib4e5c8d2014-03-05 12:54:15 -0800166SN_X9_62_prime192v1 = _ffi.string(_lib.SN_X9_62_prime192v1)
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600167NID_X9_62_prime192v2 = _lib.NID_X9_62_prime192v2
Andy Lutomirskib4e5c8d2014-03-05 12:54:15 -0800168SN_X9_62_prime192v2 = _ffi.string(_lib.SN_X9_62_prime192v2)
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600169NID_X9_62_prime192v3 = _lib.NID_X9_62_prime192v3
Andy Lutomirskib4e5c8d2014-03-05 12:54:15 -0800170SN_X9_62_prime192v3 = _ffi.string(_lib.SN_X9_62_prime192v3)
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600171NID_X9_62_prime239v1 = _lib.NID_X9_62_prime239v1
Andy Lutomirskib4e5c8d2014-03-05 12:54:15 -0800172SN_X9_62_prime239v1 = _ffi.string(_lib.SN_X9_62_prime239v1)
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600173NID_X9_62_prime239v2 = _lib.NID_X9_62_prime239v2
Andy Lutomirskib4e5c8d2014-03-05 12:54:15 -0800174SN_X9_62_prime239v2 = _ffi.string(_lib.SN_X9_62_prime239v2)
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600175NID_X9_62_prime239v3 = _lib.NID_X9_62_prime239v3
Andy Lutomirskib4e5c8d2014-03-05 12:54:15 -0800176SN_X9_62_prime239v3 = _ffi.string(_lib.SN_X9_62_prime239v3)
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600177NID_X9_62_prime256v1 = _lib.NID_X9_62_prime256v1
Andy Lutomirskib4e5c8d2014-03-05 12:54:15 -0800178SN_X9_62_prime256v1 = _ffi.string(_lib.SN_X9_62_prime256v1)
179NID_secp112r1 = _lib.NID_secp112r1
180SN_secp112r1 = _ffi.string(_lib.SN_secp112r1)
181NID_secp112r2 = _lib.NID_secp112r2
182SN_secp112r2 = _ffi.string(_lib.SN_secp112r2)
183NID_secp128r1 = _lib.NID_secp128r1
184SN_secp128r1 = _ffi.string(_lib.SN_secp128r1)
185NID_secp128r2 = _lib.NID_secp128r2
186SN_secp128r2 = _ffi.string(_lib.SN_secp128r2)
187NID_secp160k1 = _lib.NID_secp160k1
188SN_secp160k1 = _ffi.string(_lib.SN_secp160k1)
189NID_secp160r1 = _lib.NID_secp160r1
190SN_secp160r1 = _ffi.string(_lib.SN_secp160r1)
191NID_secp160r2 = _lib.NID_secp160r2
192SN_secp160r2 = _ffi.string(_lib.SN_secp160r2)
193NID_sect163k1 = _lib.NID_sect163k1
194SN_sect163k1 = _ffi.string(_lib.SN_sect163k1)
195NID_sect163r1 = _lib.NID_sect163r1
196SN_sect163r1 = _ffi.string(_lib.SN_sect163r1)
197NID_sect163r2 = _lib.NID_sect163r2
198SN_sect163r2 = _ffi.string(_lib.SN_sect163r2)
199NID_secp192k1 = _lib.NID_secp192k1
200SN_secp192k1 = _ffi.string(_lib.SN_secp192k1)
201NID_secp224k1 = _lib.NID_secp224k1
202SN_secp224k1 = _ffi.string(_lib.SN_secp224k1)
203NID_secp224r1 = _lib.NID_secp224r1
204SN_secp224r1 = _ffi.string(_lib.SN_secp224r1)
205NID_secp256k1 = _lib.NID_secp256k1
206SN_secp256k1 = _ffi.string(_lib.SN_secp256k1)
207NID_secp384r1 = _lib.NID_secp384r1
208SN_secp384r1 = _ffi.string(_lib.SN_secp384r1)
209NID_secp521r1 = _lib.NID_secp521r1
210SN_secp521r1 = _ffi.string(_lib.SN_secp521r1)
211NID_sect113r1 = _lib.NID_sect113r1
212SN_sect113r1 = _ffi.string(_lib.SN_sect113r1)
213NID_sect113r2 = _lib.NID_sect113r2
214SN_sect113r2 = _ffi.string(_lib.SN_sect113r2)
215NID_sect131r1 = _lib.NID_sect131r1
216SN_sect131r1 = _ffi.string(_lib.SN_sect131r1)
217NID_sect131r2 = _lib.NID_sect131r2
218SN_sect131r2 = _ffi.string(_lib.SN_sect131r2)
219NID_sect193r1 = _lib.NID_sect193r1
220SN_sect193r1 = _ffi.string(_lib.SN_sect193r1)
221NID_sect193r2 = _lib.NID_sect193r2
222SN_sect193r2 = _ffi.string(_lib.SN_sect193r2)
223NID_sect233k1 = _lib.NID_sect233k1
224SN_sect233k1 = _ffi.string(_lib.SN_sect233k1)
225NID_sect233r1 = _lib.NID_sect233r1
226SN_sect233r1 = _ffi.string(_lib.SN_sect233r1)
227NID_sect239k1 = _lib.NID_sect239k1
228SN_sect239k1 = _ffi.string(_lib.SN_sect239k1)
229NID_sect283k1 = _lib.NID_sect283k1
230SN_sect283k1 = _ffi.string(_lib.SN_sect283k1)
231NID_sect283r1 = _lib.NID_sect283r1
232SN_sect283r1 = _ffi.string(_lib.SN_sect283r1)
233NID_sect409k1 = _lib.NID_sect409k1
234SN_sect409k1 = _ffi.string(_lib.SN_sect409k1)
235NID_sect409r1 = _lib.NID_sect409r1
236SN_sect409r1 = _ffi.string(_lib.SN_sect409r1)
237NID_sect571k1 = _lib.NID_sect571k1
238SN_sect571k1 = _ffi.string(_lib.SN_sect571k1)
239NID_sect571r1 = _lib.NID_sect571r1
240SN_sect571r1 = _ffi.string(_lib.SN_sect571r1)
241NID_wap_wsg_idm_ecid_wtls1 = _lib.NID_wap_wsg_idm_ecid_wtls1
242SN_wap_wsg_idm_ecid_wtls1 = _ffi.string(_lib.SN_wap_wsg_idm_ecid_wtls1)
243NID_wap_wsg_idm_ecid_wtls3 = _lib.NID_wap_wsg_idm_ecid_wtls3
244SN_wap_wsg_idm_ecid_wtls3 = _ffi.string(_lib.SN_wap_wsg_idm_ecid_wtls3)
245NID_wap_wsg_idm_ecid_wtls4 = _lib.NID_wap_wsg_idm_ecid_wtls4
246SN_wap_wsg_idm_ecid_wtls4 = _ffi.string(_lib.SN_wap_wsg_idm_ecid_wtls4)
247NID_wap_wsg_idm_ecid_wtls5 = _lib.NID_wap_wsg_idm_ecid_wtls5
248SN_wap_wsg_idm_ecid_wtls5 = _ffi.string(_lib.SN_wap_wsg_idm_ecid_wtls5)
249NID_wap_wsg_idm_ecid_wtls6 = _lib.NID_wap_wsg_idm_ecid_wtls6
250SN_wap_wsg_idm_ecid_wtls6 = _ffi.string(_lib.SN_wap_wsg_idm_ecid_wtls6)
251NID_wap_wsg_idm_ecid_wtls7 = _lib.NID_wap_wsg_idm_ecid_wtls7
252SN_wap_wsg_idm_ecid_wtls7 = _ffi.string(_lib.SN_wap_wsg_idm_ecid_wtls7)
253NID_wap_wsg_idm_ecid_wtls8 = _lib.NID_wap_wsg_idm_ecid_wtls8
254SN_wap_wsg_idm_ecid_wtls8 = _ffi.string(_lib.SN_wap_wsg_idm_ecid_wtls8)
255NID_wap_wsg_idm_ecid_wtls9 = _lib.NID_wap_wsg_idm_ecid_wtls9
256SN_wap_wsg_idm_ecid_wtls9 = _ffi.string(_lib.SN_wap_wsg_idm_ecid_wtls9)
257NID_wap_wsg_idm_ecid_wtls10 = _lib.NID_wap_wsg_idm_ecid_wtls10
258SN_wap_wsg_idm_ecid_wtls10 = _ffi.string(_lib.SN_wap_wsg_idm_ecid_wtls10)
259NID_wap_wsg_idm_ecid_wtls11 = _lib.NID_wap_wsg_idm_ecid_wtls11
260SN_wap_wsg_idm_ecid_wtls11 = _ffi.string(_lib.SN_wap_wsg_idm_ecid_wtls11)
261NID_wap_wsg_idm_ecid_wtls12 = _lib.NID_wap_wsg_idm_ecid_wtls12
262SN_wap_wsg_idm_ecid_wtls12 = _ffi.string(_lib.SN_wap_wsg_idm_ecid_wtls12)
263NID_ipsec3 = _lib.NID_ipsec3
264SN_ipsec3 = _ffi.string(_lib.SN_ipsec3)
265NID_ipsec4 = _lib.NID_ipsec4
266SN_ipsec4 = _ffi.string(_lib.SN_ipsec4)
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600267
Alex Gaynor807853c2014-01-17 13:03:27 -0600268_Cryptography_HAS_EC = _lib.Cryptography_HAS_EC
Andy Lutomirski9bca0ed2014-03-05 14:41:41 -0800269ELLIPTIC_CURVE_DESCRIPTIONS = {} # In case there's no EC support
270if _Cryptography_HAS_EC:
271 _num_curves = _lib.EC_get_builtin_curves(_ffi.NULL, 0)
272 _curves = _ffi.new('EC_builtin_curve[]', _num_curves)
273 if _lib.EC_get_builtin_curves(_curves, _num_curves) == _num_curves:
274 ELLIPTIC_CURVE_DESCRIPTIONS = {c.nid : _ffi.string(c.comment)
275 for c in _curves}
276 del _num_curves
277 del _curves
Alex Gaynor12dc0842014-01-17 12:51:31 -0600278
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600279
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500280class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500281 """
282 An error occurred in an `OpenSSL.SSL` API.
283 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500284
285
286
287_raise_current_error = partial(_exception_from_error_queue, Error)
288
289
290class WantReadError(Error):
291 pass
292
293
294
295class WantWriteError(Error):
296 pass
297
298
299
300class WantX509LookupError(Error):
301 pass
302
303
304
305class ZeroReturnError(Error):
306 pass
307
308
309
310class SysCallError(Error):
311 pass
312
313
314
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800315class _VerifyHelper(object):
316 def __init__(self, connection, callback):
317 self._problems = []
318
319 @wraps(callback)
320 def wrapper(ok, store_ctx):
321 cert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500322 cert._x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
323 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
324 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800325
326 try:
327 result = callback(connection, cert, error_number, error_depth, ok)
328 except Exception as e:
329 self._problems.append(e)
330 return 0
331 else:
332 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500333 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800334 return 1
335 else:
336 return 0
337
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500338 self.callback = _ffi.callback(
339 "int (*)(int, X509_STORE_CTX *)", wrapper)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800340
341
342 def raise_if_problem(self):
343 if self._problems:
344 try:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500345 _raise_current_error()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800346 except Error:
347 pass
348 raise self._problems.pop(0)
349
350
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800351
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800352def _asFileDescriptor(obj):
353 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800354 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800355 meth = getattr(obj, "fileno", None)
356 if meth is not None:
357 obj = meth()
358
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800359 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800360 fd = obj
361
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800362 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800363 raise TypeError("argument must be an int, or have a fileno() method.")
364 elif fd < 0:
365 raise ValueError(
366 "file descriptor cannot be a negative integer (%i)" % (fd,))
367
368 return fd
369
370
371
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800372def SSLeay_version(type):
373 """
374 Return a string describing the version of OpenSSL in use.
375
376 :param type: One of the SSLEAY_ constants defined in this module.
377 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500378 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800379
380
381
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800382class Session(object):
383 pass
384
385
386
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800387class Context(object):
388 """
389 :py:obj:`OpenSSL.SSL.Context` instances define the parameters for setting up
390 new SSL connections.
391 """
392 _methods = {
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500393 SSLv3_METHOD: "SSLv3_method",
394 SSLv23_METHOD: "SSLv23_method",
395 TLSv1_METHOD: "TLSv1_method",
396 TLSv1_1_METHOD: "TLSv1_1_method",
397 TLSv1_2_METHOD: "TLSv1_2_method",
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800398 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500399 _methods = dict(
400 (identifier, getattr(_lib, name))
401 for (identifier, name) in _methods.items()
402 if getattr(_lib, name, None) is not None)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800403
Jean-Paul Calderone63157872013-03-20 16:43:38 -0700404
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800405 def __init__(self, method):
406 """
407 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
408 TLSv1_METHOD.
409 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500410 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800411 raise TypeError("method must be an integer")
412
413 try:
414 method_func = self._methods[method]
415 except KeyError:
416 raise ValueError("No such protocol")
417
418 method_obj = method_func()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500419 if method_obj == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500420 # TODO: This is untested.
421 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800422
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500423 context = _lib.SSL_CTX_new(method_obj)
424 if context == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500425 # TODO: This is untested.
426 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500427 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800428
429 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800430 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800431 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800432 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800433 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800434 self._verify_callback = None
435 self._info_callback = None
436 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800437 self._app_data = None
438
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -0800439 # SSL_CTX_set_app_data(self->ctx, self);
440 # SSL_CTX_set_mode(self->ctx, SSL_MODE_ENABLE_PARTIAL_WRITE |
441 # SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
442 # SSL_MODE_AUTO_RETRY);
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500443 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800444
445
446 def load_verify_locations(self, cafile, capath=None):
447 """
448 Let SSL know where we can find trusted certificates for the certificate
449 chain
450
451 :param cafile: In which file we can find the certificates
452 :param capath: In which directory we can find the certificates
453 :return: None
454 """
455 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500456 cafile = _ffi.NULL
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800457 elif not isinstance(cafile, bytes):
458 raise TypeError("cafile must be None or a byte string")
459
460 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500461 capath = _ffi.NULL
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800462 elif not isinstance(capath, bytes):
463 raise TypeError("capath must be None or a byte string")
464
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500465 load_result = _lib.SSL_CTX_load_verify_locations(self._context, cafile, capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800466 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500467 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800468
469
470 def _wrap_callback(self, callback):
471 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800472 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800473 return callback(size, verify, self._passphrase_userdata)
474 return _PassphraseHelper(
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800475 FILETYPE_PEM, wrapper, more_args=True, truncate=True)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800476
477
478 def set_passwd_cb(self, callback, userdata=None):
479 """
480 Set the passphrase callback
481
482 :param callback: The Python callback to use
483 :param userdata: (optional) A Python object which will be given as
484 argument to the callback
485 :return: None
486 """
487 if not callable(callback):
488 raise TypeError("callback must be callable")
489
490 self._passphrase_helper = self._wrap_callback(callback)
491 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500492 _lib.SSL_CTX_set_default_passwd_cb(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800493 self._context, self._passphrase_callback)
494 self._passphrase_userdata = userdata
495
496
497 def set_default_verify_paths(self):
498 """
499 Use the platform-specific CA certificate locations
500
501 :return: None
502 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500503 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800504 if not set_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500505 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500506 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800507
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800508
509 def use_certificate_chain_file(self, certfile):
510 """
511 Load a certificate chain from a file
512
513 :param certfile: The name of the certificate chain file
514 :return: None
515 """
Jean-Paul Calderoned8607982014-01-18 10:30:55 -0500516 if isinstance(certfile, _text_type):
517 # Perhaps sys.getfilesystemencoding() could be better?
518 certfile = certfile.encode("utf-8")
519
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800520 if not isinstance(certfile, bytes):
Jean-Paul Calderoned8607982014-01-18 10:30:55 -0500521 raise TypeError("certfile must be bytes or unicode")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800522
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500523 result = _lib.SSL_CTX_use_certificate_chain_file(self._context, certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800524 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500525 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800526
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800527
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800528 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800529 """
530 Load a certificate from a file
531
532 :param certfile: The name of the certificate file
533 :param filetype: (optional) The encoding of the file, default is PEM
534 :return: None
535 """
Jean-Paul Calderone684baf52014-01-18 10:31:19 -0500536 if isinstance(certfile, _text_type):
537 # Perhaps sys.getfilesystemencoding() could be better?
538 certfile = certfile.encode("utf-8")
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800539 if not isinstance(certfile, bytes):
Jean-Paul Calderone684baf52014-01-18 10:31:19 -0500540 raise TypeError("certfile must be bytes or unicode")
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500541 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800542 raise TypeError("filetype must be an integer")
543
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500544 use_result = _lib.SSL_CTX_use_certificate_file(self._context, certfile, filetype)
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800545 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500546 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800547
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800548
549 def use_certificate(self, cert):
550 """
551 Load a certificate from a X509 object
552
553 :param cert: The X509 object
554 :return: None
555 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800556 if not isinstance(cert, X509):
557 raise TypeError("cert must be an X509 instance")
558
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500559 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800560 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500561 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800562
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800563
564 def add_extra_chain_cert(self, certobj):
565 """
566 Add certificate to chain
567
568 :param certobj: The X509 certificate object to add to the chain
569 :return: None
570 """
571 if not isinstance(certobj, X509):
572 raise TypeError("certobj must be an X509 instance")
573
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500574 copy = _lib.X509_dup(certobj._x509)
575 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800576 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500577 # TODO: This is untested.
578 _lib.X509_free(copy)
579 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800580
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800581
582 def _raise_passphrase_exception(self):
583 if self._passphrase_helper is None:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500584 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800585 exception = self._passphrase_helper.raise_if_problem(Error)
586 if exception is not None:
587 raise exception
588
589
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800590 def use_privatekey_file(self, keyfile, filetype=_unspecified):
591 """
592 Load a private key from a file
593
594 :param keyfile: The name of the key file
595 :param filetype: (optional) The encoding of the file, default is PEM
596 :return: None
597 """
Jean-Paul Calderone87e525a2014-01-18 10:31:51 -0500598 if isinstance(keyfile, _text_type):
599 # Perhaps sys.getfilesystemencoding() could be better?
600 keyfile = keyfile.encode("utf-8")
601
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800602 if not isinstance(keyfile, bytes):
603 raise TypeError("keyfile must be a byte string")
604
605 if filetype is _unspecified:
606 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500607 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800608 raise TypeError("filetype must be an integer")
609
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500610 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800611 self._context, keyfile, filetype)
612 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800613 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800614
615
616 def use_privatekey(self, pkey):
617 """
618 Load a private key from a PKey object
619
620 :param pkey: The PKey object
621 :return: None
622 """
623 if not isinstance(pkey, PKey):
624 raise TypeError("pkey must be a PKey instance")
625
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500626 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800627 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800628 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800629
630
631 def check_privatekey(self):
632 """
633 Check that the private key and certificate match up
634
635 :return: None (raises an exception if something's wrong)
636 """
637
638 def load_client_ca(self, cafile):
639 """
640 Load the trusted certificates that will be sent to the client (basically
641 telling the client "These are the guys I trust"). Does not actually
642 imply any of the certificates are trusted; that must be configured
643 separately.
644
645 :param cafile: The name of the certificates file
646 :return: None
647 """
648
649 def set_session_id(self, buf):
650 """
651 Set the session identifier. This is needed if you want to do session
652 resumption.
653
654 :param buf: A Python object that can be safely converted to a string
655 :returns: None
656 """
657
658 def set_session_cache_mode(self, mode):
659 """
660 Enable/disable session caching and specify the mode used.
661
662 :param mode: One or more of the SESS_CACHE_* flags (combine using
663 bitwise or)
664 :returns: The previously set caching mode.
665 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500666 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800667 raise TypeError("mode must be an integer")
668
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500669 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800670
671
672 def get_session_cache_mode(self):
673 """
674 :returns: The currently used cache mode.
675 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500676 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800677
678
679 def set_verify(self, mode, callback):
680 """
681 Set the verify mode and verify callback
682
683 :param mode: The verify mode, this is either VERIFY_NONE or
684 VERIFY_PEER combined with possible other flags
685 :param callback: The Python callback to use
686 :return: None
687
688 See SSL_CTX_set_verify(3SSL) for further details.
689 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500690 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800691 raise TypeError("mode must be an integer")
692
693 if not callable(callback):
694 raise TypeError("callback must be callable")
695
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800696 self._verify_helper = _VerifyHelper(self, callback)
697 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500698 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800699
700
701 def set_verify_depth(self, depth):
702 """
703 Set the verify depth
704
705 :param depth: An integer specifying the verify depth
706 :return: None
707 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500708 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800709 raise TypeError("depth must be an integer")
710
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500711 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800712
713
714 def get_verify_mode(self):
715 """
716 Get the verify mode
717
718 :return: The verify mode
719 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500720 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800721
722
723 def get_verify_depth(self):
724 """
725 Get the verify depth
726
727 :return: The verify depth
728 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500729 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800730
731
732 def load_tmp_dh(self, dhfile):
733 """
734 Load parameters for Ephemeral Diffie-Hellman
735
736 :param dhfile: The file to load EDH parameters from
737 :return: None
738 """
739 if not isinstance(dhfile, bytes):
740 raise TypeError("dhfile must be a byte string")
741
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500742 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500743 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500744 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500745 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800746
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500747 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
748 dh = _ffi.gc(dh, _lib.DH_free)
749 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800750
751
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600752 def set_tmp_ecdh_by_curve_name(self, curve_name):
753 """
754 Configure this connection to people to use Elliptical Curve
755 Diffie-Hellman key exchanges.
756
Alex Gaynora683fc02014-01-17 12:45:56 -0600757 :param curve_name: One of the named curve constants.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600758 :return: None
759 """
760 if _lib.Cryptography_HAS_EC:
761 ecdh = _lib.EC_KEY_new_by_curve_name(curve_name)
762 if ecdh == _ffi.NULL:
763 raise ValueError(
764 "OpenSSL could not load the requested elliptic curve"
765 )
766 _lib.SSL_CTX_set_tmp_ecdh(self._context, ecdh)
767 _lib.EC_KEY_free(ecdh)
768 else:
769 raise ValueError("OpenSSL is compiled without ECDH support")
770
771
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800772 def set_cipher_list(self, cipher_list):
773 """
774 Change the cipher list
775
776 :param cipher_list: A cipher list, see ciphers(1)
777 :return: None
778 """
Jean-Paul Calderone63eab692014-01-18 10:19:56 -0500779 if isinstance(cipher_list, _text_type):
780 cipher_list = cipher_list.encode("ascii")
781
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800782 if not isinstance(cipher_list, bytes):
Jean-Paul Calderone63eab692014-01-18 10:19:56 -0500783 raise TypeError("cipher_list must be bytes or unicode")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800784
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500785 result = _lib.SSL_CTX_set_cipher_list(self._context, cipher_list)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800786 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500787 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800788
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800789
790 def set_client_ca_list(self, certificate_authorities):
791 """
792 Set the list of preferred client certificate signers for this server context.
793
794 This list of certificate authorities will be sent to the client when the
795 server requests a client certificate.
796
797 :param certificate_authorities: a sequence of X509Names.
798 :return: None
799 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500800 name_stack = _lib.sk_X509_NAME_new_null()
801 if name_stack == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500802 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500803 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800804
805 try:
806 for ca_name in certificate_authorities:
807 if not isinstance(ca_name, X509Name):
808 raise TypeError(
809 "client CAs must be X509Name objects, not %s objects" % (
810 type(ca_name).__name__,))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500811 copy = _lib.X509_NAME_dup(ca_name._name)
812 if copy == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500813 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500814 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500815 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800816 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500817 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500818 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800819 except:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500820 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800821 raise
822
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500823 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800824
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800825
826 def add_client_ca(self, certificate_authority):
827 """
828 Add the CA certificate to the list of preferred signers for this context.
829
830 The list of certificate authorities will be sent to the client when the
831 server requests a client certificate.
832
833 :param certificate_authority: certificate authority's X509 certificate.
834 :return: None
835 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800836 if not isinstance(certificate_authority, X509):
837 raise TypeError("certificate_authority must be an X509 instance")
838
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500839 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800840 self._context, certificate_authority._x509)
841 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500842 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500843 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800844
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800845
846 def set_timeout(self, timeout):
847 """
848 Set session timeout
849
850 :param timeout: The timeout in seconds
851 :return: The previous session timeout
852 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500853 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800854 raise TypeError("timeout must be an integer")
855
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500856 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800857
858
859 def get_timeout(self):
860 """
861 Get the session timeout
862
863 :return: The session timeout
864 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500865 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800866
867
868 def set_info_callback(self, callback):
869 """
870 Set the info callback
871
872 :param callback: The Python callback to use
873 :return: None
874 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800875 @wraps(callback)
876 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -0500877 callback(Connection._reverse_mapping[ssl], where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500878 self._info_callback = _ffi.callback(
879 "void (*)(const SSL *, int, int)", wrapper)
880 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800881
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800882
883 def get_app_data(self):
884 """
885 Get the application data (supplied via set_app_data())
886
887 :return: The application data
888 """
889 return self._app_data
890
891
892 def set_app_data(self, data):
893 """
894 Set the application data (will be returned from get_app_data())
895
896 :param data: Any Python object
897 :return: None
898 """
899 self._app_data = data
900
901
902 def get_cert_store(self):
903 """
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500904 Get the certificate store for the context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800905
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500906 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800907 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500908 store = _lib.SSL_CTX_get_cert_store(self._context)
909 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500910 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800911 return None
912
913 pystore = X509Store.__new__(X509Store)
914 pystore._store = store
915 return pystore
916
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800917
918 def set_options(self, options):
919 """
920 Add options. Options set before are not cleared!
921
922 :param options: The options to add.
923 :return: The new option bitmask.
924 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500925 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800926 raise TypeError("options must be an integer")
927
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500928 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800929
930
931 def set_mode(self, mode):
932 """
933 Add modes via bitmask. Modes set before are not cleared!
934
935 :param mode: The mode to add.
936 :return: The new mode bitmask.
937 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500938 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800939 raise TypeError("mode must be an integer")
940
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500941 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800942
943
944 def set_tlsext_servername_callback(self, callback):
945 """
946 Specify a callback function to be called when clients specify a server name.
947
948 :param callback: The callback function. It will be invoked with one
949 argument, the Connection instance.
950 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800951 @wraps(callback)
952 def wrapper(ssl, alert, arg):
953 callback(Connection._reverse_mapping[ssl])
954 return 0
955
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500956 self._tlsext_servername_callback = _ffi.callback(
957 "int (*)(const SSL *, int *, void *)", wrapper)
958 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800959 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800960
961ContextType = Context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800962
963
964
965class Connection(object):
966 """
967 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800968 _reverse_mapping = WeakValueDictionary()
969
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800970 def __init__(self, context, socket=None):
971 """
972 Create a new Connection object, using the given OpenSSL.SSL.Context
973 instance and socket.
974
975 :param context: An SSL Context to use for this connection
976 :param socket: The socket to use for transport layer
977 """
978 if not isinstance(context, Context):
979 raise TypeError("context must be a Context instance")
980
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500981 ssl = _lib.SSL_new(context._context)
982 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800983 self._context = context
984
985 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800986
987 if socket is None:
988 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -0800989 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500990 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
991 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800992
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500993 if self._into_ssl == _ffi.NULL or self._from_ssl == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500994 # TODO: This is untested.
995 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800996
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500997 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800998 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800999 self._into_ssl = None
1000 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001001 self._socket = socket
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001002 set_result = _lib.SSL_set_fd(self._ssl, _asFileDescriptor(self._socket))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001003 if not set_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001004 # TODO: This is untested.
1005 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001006
1007
1008 def __getattr__(self, name):
1009 """
1010 Look up attributes on the wrapped socket object if they are not found on
1011 the Connection object.
1012 """
1013 return getattr(self._socket, name)
1014
1015
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001016 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001017 if self._context._verify_helper is not None:
1018 self._context._verify_helper.raise_if_problem()
1019
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001020 error = _lib.SSL_get_error(ssl, result)
1021 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001022 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001023 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001024 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001025 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001026 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001027 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001028 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001029 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001030 elif error == _lib.SSL_ERROR_SYSCALL:
1031 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001032 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001033 if platform == "win32":
1034 errno = _ffi.getwinerror()[0]
1035 else:
1036 errno = _ffi.errno
1037 raise SysCallError(errno, errorcode[errno])
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001038 else:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001039 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001040 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001041 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001042 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001043 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001044 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001045 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001046 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001047
1048
1049 def get_context(self):
1050 """
1051 Get session context
1052 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001053 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001054
1055
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001056 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001057 """
1058 Switch this connection to a new session context
1059
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001060 :param context: A :py:class:`Context` instance giving the new session
1061 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001062 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001063 if not isinstance(context, Context):
1064 raise TypeError("context must be a Context instance")
1065
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001066 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001067 self._context = context
1068
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001069
1070 def get_servername(self):
1071 """
1072 Retrieve the servername extension value if provided in the client hello
1073 message, or None if there wasn't one.
1074
1075 :return: A byte string giving the server name or :py:data:`None`.
1076 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001077 name = _lib.SSL_get_servername(self._ssl, _lib.TLSEXT_NAMETYPE_host_name)
1078 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001079 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001080
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001081 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001082
1083
1084 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001085 """
1086 Set the value of the servername extension to send in the client hello.
1087
1088 :param name: A byte string giving the name.
1089 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001090 if not isinstance(name, bytes):
1091 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001092 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001093 raise TypeError("name must not contain NUL byte")
1094
1095 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001096 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001097
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001098
1099 def pending(self):
1100 """
1101 Get the number of bytes that can be safely read from the connection
1102
1103 :return: The number of bytes available in the receive buffer.
1104 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001105 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001106
1107
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001108 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001109 """
1110 Send data on the connection. NOTE: If you get one of the WantRead,
1111 WantWrite or WantX509Lookup exceptions on this, you have to call the
1112 method again with the SAME buffer.
1113
1114 :param buf: The string to send
1115 :param flags: (optional) Included for compatibility with the socket
1116 API, the value is ignored
1117 :return: The number of bytes written
1118 """
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001119 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001120 buf = buf.tobytes()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001121 if not isinstance(buf, bytes):
1122 raise TypeError("data must be a byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001123
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001124 result = _lib.SSL_write(self._ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001125 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001126 return result
1127 write = send
1128
1129
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001130 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001131 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001132 Send "all" data on the connection. This calls send() repeatedly until
1133 all data is sent. If an error occurs, it's impossible to tell how much
1134 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001135
1136 :param buf: The string to send
1137 :param flags: (optional) Included for compatibility with the socket
1138 API, the value is ignored
1139 :return: The number of bytes written
1140 """
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001141 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001142 buf = buf.tobytes()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001143 if not isinstance(buf, bytes):
1144 raise TypeError("buf must be a byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001145
1146 left_to_send = len(buf)
1147 total_sent = 0
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001148 data = _ffi.new("char[]", buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001149
1150 while left_to_send:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001151 result = _lib.SSL_write(self._ssl, data + total_sent, left_to_send)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001152 self._raise_ssl_error(self._ssl, result)
1153 total_sent += result
1154 left_to_send -= result
1155
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001156
1157 def recv(self, bufsiz, flags=None):
1158 """
1159 Receive data on the connection. NOTE: If you get one of the WantRead,
1160 WantWrite or WantX509Lookup exceptions on this, you have to call the
1161 method again with the SAME buffer.
1162
1163 :param bufsiz: The maximum number of bytes to read
1164 :param flags: (optional) Included for compatibility with the socket
1165 API, the value is ignored
1166 :return: The string read from the Connection
1167 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001168 buf = _ffi.new("char[]", bufsiz)
1169 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001170 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001171 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001172 read = recv
1173
1174
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001175 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001176 if _lib.BIO_should_retry(bio):
1177 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001178 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001179 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001180 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001181 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001182 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001183 # TODO: This is untested. I think io_special means the socket
1184 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001185 raise ValueError("BIO_should_io_special")
1186 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001187 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001188 raise ValueError("unknown bio failure")
1189 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001190 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001191 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001192
1193
1194 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001195 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001196 When using non-socket connections this function reads the "dirty" data
1197 that would have traveled away on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001198
1199 :param bufsiz: The maximum number of bytes to read
1200 :return: The string read.
1201 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001202 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001203 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001204
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001205 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001206 raise TypeError("bufsiz must be an integer")
1207
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001208 buf = _ffi.new("char[]", bufsiz)
1209 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001210 if result <= 0:
1211 self._handle_bio_errors(self._from_ssl, result)
1212
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001213 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001214
1215
1216 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001217 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001218 When using non-socket connections this function sends "dirty" data that
1219 would have traveled in on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001220
1221 :param buf: The string to put into the memory BIO.
1222 :return: The number of bytes written
1223 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001224 if self._into_ssl is None:
1225 raise TypeError("Connection sock was not None")
1226
1227 if not isinstance(buf, bytes):
1228 raise TypeError("buf must be a byte string")
1229
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001230 result = _lib.BIO_write(self._into_ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001231 if result <= 0:
1232 self._handle_bio_errors(self._into_ssl, result)
1233 return result
1234
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001235
1236 def renegotiate(self):
1237 """
1238 Renegotiate the session
1239
1240 :return: True if the renegotiation can be started, false otherwise
1241 """
1242
1243 def do_handshake(self):
1244 """
1245 Perform an SSL handshake (usually called after renegotiate() or one of
1246 set_*_state()). This can raise the same exceptions as send and recv.
1247
1248 :return: None.
1249 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001250 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001251 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001252
1253
1254 def renegotiate_pending(self):
1255 """
1256 Check if there's a renegotiation in progress, it will return false once
1257 a renegotiation is finished.
1258
1259 :return: Whether there's a renegotiation in progress
1260 """
1261
1262 def total_renegotiations(self):
1263 """
1264 Find out the total number of renegotiations.
1265
1266 :return: The number of renegotiations.
1267 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001268 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001269
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001270
1271 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001272 """
1273 Connect to remote host and set up client-side SSL
1274
1275 :param addr: A remote address
1276 :return: What the socket's connect method returns
1277 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001278 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001279 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001280
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001281
1282 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001283 """
1284 Connect to remote host and set up client-side SSL. Note that if the socket's
1285 connect_ex method doesn't return 0, SSL won't be initialized.
1286
1287 :param addr: A remove address
1288 :return: What the socket's connect_ex method returns
1289 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001290 connect_ex = self._socket.connect_ex
1291 self.set_connect_state()
1292 return connect_ex(addr)
1293
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001294
1295 def accept(self):
1296 """
1297 Accept incoming connection and set up SSL on it
1298
1299 :return: A (conn,addr) pair where conn is a Connection and addr is an
1300 address
1301 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001302 client, addr = self._socket.accept()
1303 conn = Connection(self._context, client)
1304 conn.set_accept_state()
1305 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001306
1307
1308 def bio_shutdown(self):
1309 """
1310 When using non-socket connections this function signals end of
1311 data on the input for this connection.
1312
1313 :return: None
1314 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001315 if self._from_ssl is None:
1316 raise TypeError("Connection sock was not None")
1317
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001318 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001319
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001320
1321 def shutdown(self):
1322 """
1323 Send closure alert
1324
1325 :return: True if the shutdown completed successfully (i.e. both sides
1326 have sent closure alerts), false otherwise (i.e. you have to
1327 wait for a ZeroReturnError on a recv() method call
1328 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001329 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001330 if result < 0:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001331 # TODO: This is untested.
1332 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001333 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001334 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001335 else:
1336 return False
1337
1338
1339 def get_cipher_list(self):
1340 """
1341 Get the session cipher list
1342
1343 :return: A list of cipher strings
1344 """
1345 ciphers = []
1346 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001347 result = _lib.SSL_get_cipher_list(self._ssl, i)
1348 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001349 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001350 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001351 return ciphers
1352
1353
1354 def get_client_ca_list(self):
1355 """
1356 Get CAs whose certificates are suggested for client authentication.
1357
1358 :return: If this is a server connection, a list of X509Names representing
1359 the acceptable CAs as set by :py:meth:`OpenSSL.SSL.Context.set_client_ca_list` or
1360 :py:meth:`OpenSSL.SSL.Context.add_client_ca`. If this is a client connection,
1361 the list of such X509Names sent by the server, or an empty list if that
1362 has not yet happened.
1363 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001364 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1365 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001366 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001367 return []
1368
1369 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001370 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1371 name = _lib.sk_X509_NAME_value(ca_names, i)
1372 copy = _lib.X509_NAME_dup(name)
1373 if copy == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001374 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001375 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001376
1377 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001378 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001379 result.append(pyname)
1380 return result
1381
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001382
1383 def makefile(self):
1384 """
1385 The makefile() method is not implemented, since there is no dup semantics
1386 for SSL connections
1387
1388 :raise NotImplementedError
1389 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001390 raise NotImplementedError("Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001391
1392
1393 def get_app_data(self):
1394 """
1395 Get application data
1396
1397 :return: The application data
1398 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001399 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001400
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001401
1402 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001403 """
1404 Set application data
1405
1406 :param data - The application data
1407 :return: None
1408 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001409 self._app_data = data
1410
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001411
1412 def get_shutdown(self):
1413 """
1414 Get shutdown state
1415
1416 :return: The shutdown state, a bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
1417 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001418 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001419
1420
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001421 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001422 """
1423 Set shutdown state
1424
1425 :param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
1426 :return: None
1427 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05001428 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001429 raise TypeError("state must be an integer")
1430
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001431 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001432
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001433
1434 def state_string(self):
1435 """
1436 Get a verbose state description
1437
1438 :return: A string representing the state
1439 """
1440
1441 def server_random(self):
1442 """
1443 Get a copy of the server hello nonce.
1444
1445 :return: A string representing the state
1446 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001447 if self._ssl.session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001448 return None
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001449 return _ffi.buffer(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001450 self._ssl.s3.server_random,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001451 _lib.SSL3_RANDOM_SIZE)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001452
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001453
1454 def client_random(self):
1455 """
1456 Get a copy of the client hello nonce.
1457
1458 :return: A string representing the state
1459 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001460 if self._ssl.session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001461 return None
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001462 return _ffi.buffer(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001463 self._ssl.s3.client_random,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001464 _lib.SSL3_RANDOM_SIZE)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001465
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001466
1467 def master_key(self):
1468 """
1469 Get a copy of the master key.
1470
1471 :return: A string representing the state
1472 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001473 if self._ssl.session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001474 return None
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001475 return _ffi.buffer(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001476 self._ssl.session.master_key,
1477 self._ssl.session.master_key_length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001478
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001479
1480 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001481 """
1482 See shutdown(2)
1483
1484 :return: What the socket's shutdown() method returns
1485 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001486 return self._socket.shutdown(*args, **kwargs)
1487
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001488
1489 def get_peer_certificate(self):
1490 """
1491 Retrieve the other side's certificate (if any)
1492
1493 :return: The peer's certificate
1494 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001495 cert = _lib.SSL_get_peer_certificate(self._ssl)
1496 if cert != _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001497 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001498 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001499 return pycert
1500 return None
1501
1502
1503 def get_peer_cert_chain(self):
1504 """
1505 Retrieve the other side's certificate (if any)
1506
1507 :return: A list of X509 instances giving the peer's certificate chain,
1508 or None if it does not have one.
1509 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001510 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
1511 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001512 return None
1513
1514 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001515 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001516 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001517 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001518 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001519 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001520 result.append(pycert)
1521 return result
1522
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001523
1524 def want_read(self):
1525 """
1526 Checks if more data has to be read from the transport layer to complete an
1527 operation.
1528
1529 :return: True iff more data has to be read
1530 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001531 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001532
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001533
1534 def want_write(self):
1535 """
1536 Checks if there is data to write to the transport layer to complete an
1537 operation.
1538
1539 :return: True iff there is data to write
1540 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001541 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001542
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001543
1544 def set_accept_state(self):
1545 """
1546 Set the connection to work in server mode. The handshake will be handled
1547 automatically by read/write.
1548
1549 :return: None
1550 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001551 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001552
1553
1554 def set_connect_state(self):
1555 """
1556 Set the connection to work in client mode. The handshake will be handled
1557 automatically by read/write.
1558
1559 :return: None
1560 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001561 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001562
1563
1564 def get_session(self):
1565 """
1566 Returns the Session currently used.
1567
1568 @return: An instance of :py:class:`OpenSSL.SSL.Session` or :py:obj:`None` if
1569 no session exists.
1570 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001571 session = _lib.SSL_get1_session(self._ssl)
1572 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001573 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001574
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001575 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001576 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001577 return pysession
1578
1579
1580 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001581 """
1582 Set the session to be used when the TLS/SSL connection is established.
1583
1584 :param session: A Session instance representing the session to use.
1585 :returns: None
1586 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001587 if not isinstance(session, Session):
1588 raise TypeError("session must be a Session instance")
1589
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001590 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001591 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001592 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001593
1594ConnectionType = Connection
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05001595
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05001596# This is similar to the initialization calls at the end of OpenSSL/crypto.py
1597# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05001598_lib.SSL_library_init()