blob: a3e4cd01791c7229f810f795c3b84216744b9c12 [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
Alex Gaynor12dc0842014-01-17 12:51:31 -0600269
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600270
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500271class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -0500272 """
273 An error occurred in an `OpenSSL.SSL` API.
274 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500275
276
277
278_raise_current_error = partial(_exception_from_error_queue, Error)
279
280
281class WantReadError(Error):
282 pass
283
284
285
286class WantWriteError(Error):
287 pass
288
289
290
291class WantX509LookupError(Error):
292 pass
293
294
295
296class ZeroReturnError(Error):
297 pass
298
299
300
301class SysCallError(Error):
302 pass
303
304
305
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800306class _VerifyHelper(object):
307 def __init__(self, connection, callback):
308 self._problems = []
309
310 @wraps(callback)
311 def wrapper(ok, store_ctx):
312 cert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500313 cert._x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
314 error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
315 error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800316
317 try:
318 result = callback(connection, cert, error_number, error_depth, ok)
319 except Exception as e:
320 self._problems.append(e)
321 return 0
322 else:
323 if result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500324 _lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800325 return 1
326 else:
327 return 0
328
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500329 self.callback = _ffi.callback(
330 "int (*)(int, X509_STORE_CTX *)", wrapper)
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800331
332
333 def raise_if_problem(self):
334 if self._problems:
335 try:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500336 _raise_current_error()
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800337 except Error:
338 pass
339 raise self._problems.pop(0)
340
341
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800342
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800343def _asFileDescriptor(obj):
344 fd = None
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800345 if not isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800346 meth = getattr(obj, "fileno", None)
347 if meth is not None:
348 obj = meth()
349
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800350 if isinstance(obj, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800351 fd = obj
352
Konstantinos Koukopoulosc8b13ea2014-01-28 00:21:50 -0800353 if not isinstance(fd, integer_types):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800354 raise TypeError("argument must be an int, or have a fileno() method.")
355 elif fd < 0:
356 raise ValueError(
357 "file descriptor cannot be a negative integer (%i)" % (fd,))
358
359 return fd
360
361
362
Jean-Paul Calderoned39a3f62013-03-04 12:23:51 -0800363def SSLeay_version(type):
364 """
365 Return a string describing the version of OpenSSL in use.
366
367 :param type: One of the SSLEAY_ constants defined in this module.
368 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500369 return _ffi.string(_lib.SSLeay_version(type))
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800370
371
372
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800373class Session(object):
374 pass
375
376
377
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800378class Context(object):
379 """
380 :py:obj:`OpenSSL.SSL.Context` instances define the parameters for setting up
381 new SSL connections.
382 """
383 _methods = {
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500384 SSLv3_METHOD: "SSLv3_method",
385 SSLv23_METHOD: "SSLv23_method",
386 TLSv1_METHOD: "TLSv1_method",
387 TLSv1_1_METHOD: "TLSv1_1_method",
388 TLSv1_2_METHOD: "TLSv1_2_method",
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800389 }
Jean-Paul Calderonebe2bb422013-12-29 07:34:08 -0500390 _methods = dict(
391 (identifier, getattr(_lib, name))
392 for (identifier, name) in _methods.items()
393 if getattr(_lib, name, None) is not None)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800394
Jean-Paul Calderone63157872013-03-20 16:43:38 -0700395
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800396 def __init__(self, method):
397 """
398 :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, or
399 TLSv1_METHOD.
400 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500401 if not isinstance(method, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800402 raise TypeError("method must be an integer")
403
404 try:
405 method_func = self._methods[method]
406 except KeyError:
407 raise ValueError("No such protocol")
408
409 method_obj = method_func()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500410 if method_obj == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500411 # TODO: This is untested.
412 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800413
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500414 context = _lib.SSL_CTX_new(method_obj)
415 if context == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500416 # TODO: This is untested.
417 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500418 context = _ffi.gc(context, _lib.SSL_CTX_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800419
420 self._context = context
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800421 self._passphrase_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800422 self._passphrase_callback = None
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800423 self._passphrase_userdata = None
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800424 self._verify_helper = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800425 self._verify_callback = None
426 self._info_callback = None
427 self._tlsext_servername_callback = None
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800428 self._app_data = None
429
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -0800430 # SSL_CTX_set_app_data(self->ctx, self);
431 # SSL_CTX_set_mode(self->ctx, SSL_MODE_ENABLE_PARTIAL_WRITE |
432 # SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
433 # SSL_MODE_AUTO_RETRY);
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500434 self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800435
436
437 def load_verify_locations(self, cafile, capath=None):
438 """
439 Let SSL know where we can find trusted certificates for the certificate
440 chain
441
442 :param cafile: In which file we can find the certificates
443 :param capath: In which directory we can find the certificates
444 :return: None
445 """
446 if cafile is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500447 cafile = _ffi.NULL
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800448 elif not isinstance(cafile, bytes):
449 raise TypeError("cafile must be None or a byte string")
450
451 if capath is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500452 capath = _ffi.NULL
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800453 elif not isinstance(capath, bytes):
454 raise TypeError("capath must be None or a byte string")
455
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500456 load_result = _lib.SSL_CTX_load_verify_locations(self._context, cafile, capath)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800457 if not load_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500458 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800459
460
461 def _wrap_callback(self, callback):
462 @wraps(callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800463 def wrapper(size, verify, userdata):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800464 return callback(size, verify, self._passphrase_userdata)
465 return _PassphraseHelper(
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800466 FILETYPE_PEM, wrapper, more_args=True, truncate=True)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800467
468
469 def set_passwd_cb(self, callback, userdata=None):
470 """
471 Set the passphrase callback
472
473 :param callback: The Python callback to use
474 :param userdata: (optional) A Python object which will be given as
475 argument to the callback
476 :return: None
477 """
478 if not callable(callback):
479 raise TypeError("callback must be callable")
480
481 self._passphrase_helper = self._wrap_callback(callback)
482 self._passphrase_callback = self._passphrase_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500483 _lib.SSL_CTX_set_default_passwd_cb(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800484 self._context, self._passphrase_callback)
485 self._passphrase_userdata = userdata
486
487
488 def set_default_verify_paths(self):
489 """
490 Use the platform-specific CA certificate locations
491
492 :return: None
493 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500494 set_result = _lib.SSL_CTX_set_default_verify_paths(self._context)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800495 if not set_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500496 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500497 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800498
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800499
500 def use_certificate_chain_file(self, certfile):
501 """
502 Load a certificate chain from a file
503
504 :param certfile: The name of the certificate chain file
505 :return: None
506 """
Jean-Paul Calderoned8607982014-01-18 10:30:55 -0500507 if isinstance(certfile, _text_type):
508 # Perhaps sys.getfilesystemencoding() could be better?
509 certfile = certfile.encode("utf-8")
510
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800511 if not isinstance(certfile, bytes):
Jean-Paul Calderoned8607982014-01-18 10:30:55 -0500512 raise TypeError("certfile must be bytes or unicode")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800513
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500514 result = _lib.SSL_CTX_use_certificate_chain_file(self._context, certfile)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800515 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500516 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800517
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800518
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800519 def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800520 """
521 Load a certificate from a file
522
523 :param certfile: The name of the certificate file
524 :param filetype: (optional) The encoding of the file, default is PEM
525 :return: None
526 """
Jean-Paul Calderone684baf52014-01-18 10:31:19 -0500527 if isinstance(certfile, _text_type):
528 # Perhaps sys.getfilesystemencoding() could be better?
529 certfile = certfile.encode("utf-8")
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800530 if not isinstance(certfile, bytes):
Jean-Paul Calderone684baf52014-01-18 10:31:19 -0500531 raise TypeError("certfile must be bytes or unicode")
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500532 if not isinstance(filetype, integer_types):
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800533 raise TypeError("filetype must be an integer")
534
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500535 use_result = _lib.SSL_CTX_use_certificate_file(self._context, certfile, filetype)
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800536 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500537 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800538
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800539
540 def use_certificate(self, cert):
541 """
542 Load a certificate from a X509 object
543
544 :param cert: The X509 object
545 :return: None
546 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800547 if not isinstance(cert, X509):
548 raise TypeError("cert must be an X509 instance")
549
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500550 use_result = _lib.SSL_CTX_use_certificate(self._context, cert._x509)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800551 if not use_result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500552 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800553
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800554
555 def add_extra_chain_cert(self, certobj):
556 """
557 Add certificate to chain
558
559 :param certobj: The X509 certificate object to add to the chain
560 :return: None
561 """
562 if not isinstance(certobj, X509):
563 raise TypeError("certobj must be an X509 instance")
564
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500565 copy = _lib.X509_dup(certobj._x509)
566 add_result = _lib.SSL_CTX_add_extra_chain_cert(self._context, copy)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800567 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500568 # TODO: This is untested.
569 _lib.X509_free(copy)
570 _raise_current_error()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800571
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800572
573 def _raise_passphrase_exception(self):
574 if self._passphrase_helper is None:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500575 _raise_current_error()
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800576 exception = self._passphrase_helper.raise_if_problem(Error)
577 if exception is not None:
578 raise exception
579
580
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800581 def use_privatekey_file(self, keyfile, filetype=_unspecified):
582 """
583 Load a private key from a file
584
585 :param keyfile: The name of the key file
586 :param filetype: (optional) The encoding of the file, default is PEM
587 :return: None
588 """
Jean-Paul Calderone87e525a2014-01-18 10:31:51 -0500589 if isinstance(keyfile, _text_type):
590 # Perhaps sys.getfilesystemencoding() could be better?
591 keyfile = keyfile.encode("utf-8")
592
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800593 if not isinstance(keyfile, bytes):
594 raise TypeError("keyfile must be a byte string")
595
596 if filetype is _unspecified:
597 filetype = FILETYPE_PEM
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -0500598 elif not isinstance(filetype, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800599 raise TypeError("filetype must be an integer")
600
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500601 use_result = _lib.SSL_CTX_use_PrivateKey_file(
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800602 self._context, keyfile, filetype)
603 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800604 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800605
606
607 def use_privatekey(self, pkey):
608 """
609 Load a private key from a PKey object
610
611 :param pkey: The PKey object
612 :return: None
613 """
614 if not isinstance(pkey, PKey):
615 raise TypeError("pkey must be a PKey instance")
616
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500617 use_result = _lib.SSL_CTX_use_PrivateKey(self._context, pkey._pkey)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800618 if not use_result:
Jean-Paul Calderone173cff92013-03-06 10:29:21 -0800619 self._raise_passphrase_exception()
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800620
621
622 def check_privatekey(self):
623 """
624 Check that the private key and certificate match up
625
626 :return: None (raises an exception if something's wrong)
627 """
628
629 def load_client_ca(self, cafile):
630 """
631 Load the trusted certificates that will be sent to the client (basically
632 telling the client "These are the guys I trust"). Does not actually
633 imply any of the certificates are trusted; that must be configured
634 separately.
635
636 :param cafile: The name of the certificates file
637 :return: None
638 """
639
640 def set_session_id(self, buf):
641 """
642 Set the session identifier. This is needed if you want to do session
643 resumption.
644
645 :param buf: A Python object that can be safely converted to a string
646 :returns: None
647 """
648
649 def set_session_cache_mode(self, mode):
650 """
651 Enable/disable session caching and specify the mode used.
652
653 :param mode: One or more of the SESS_CACHE_* flags (combine using
654 bitwise or)
655 :returns: The previously set caching mode.
656 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500657 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800658 raise TypeError("mode must be an integer")
659
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500660 return _lib.SSL_CTX_set_session_cache_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800661
662
663 def get_session_cache_mode(self):
664 """
665 :returns: The currently used cache mode.
666 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500667 return _lib.SSL_CTX_get_session_cache_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800668
669
670 def set_verify(self, mode, callback):
671 """
672 Set the verify mode and verify callback
673
674 :param mode: The verify mode, this is either VERIFY_NONE or
675 VERIFY_PEER combined with possible other flags
676 :param callback: The Python callback to use
677 :return: None
678
679 See SSL_CTX_set_verify(3SSL) for further details.
680 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500681 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800682 raise TypeError("mode must be an integer")
683
684 if not callable(callback):
685 raise TypeError("callback must be callable")
686
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -0800687 self._verify_helper = _VerifyHelper(self, callback)
688 self._verify_callback = self._verify_helper.callback
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500689 _lib.SSL_CTX_set_verify(self._context, mode, self._verify_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800690
691
692 def set_verify_depth(self, depth):
693 """
694 Set the verify depth
695
696 :param depth: An integer specifying the verify depth
697 :return: None
698 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500699 if not isinstance(depth, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800700 raise TypeError("depth must be an integer")
701
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500702 _lib.SSL_CTX_set_verify_depth(self._context, depth)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800703
704
705 def get_verify_mode(self):
706 """
707 Get the verify mode
708
709 :return: The verify mode
710 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500711 return _lib.SSL_CTX_get_verify_mode(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800712
713
714 def get_verify_depth(self):
715 """
716 Get the verify depth
717
718 :return: The verify depth
719 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500720 return _lib.SSL_CTX_get_verify_depth(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800721
722
723 def load_tmp_dh(self, dhfile):
724 """
725 Load parameters for Ephemeral Diffie-Hellman
726
727 :param dhfile: The file to load EDH parameters from
728 :return: None
729 """
730 if not isinstance(dhfile, bytes):
731 raise TypeError("dhfile must be a byte string")
732
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500733 bio = _lib.BIO_new_file(dhfile, b"r")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500734 if bio == _ffi.NULL:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500735 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500736 bio = _ffi.gc(bio, _lib.BIO_free)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800737
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500738 dh = _lib.PEM_read_bio_DHparams(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
739 dh = _ffi.gc(dh, _lib.DH_free)
740 _lib.SSL_CTX_set_tmp_dh(self._context, dh)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800741
742
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600743 def set_tmp_ecdh_by_curve_name(self, curve_name):
744 """
745 Configure this connection to people to use Elliptical Curve
746 Diffie-Hellman key exchanges.
747
Alex Gaynora683fc02014-01-17 12:45:56 -0600748 :param curve_name: One of the named curve constants.
Alex Gaynor7b8d57a2014-01-17 12:08:54 -0600749 :return: None
750 """
751 if _lib.Cryptography_HAS_EC:
752 ecdh = _lib.EC_KEY_new_by_curve_name(curve_name)
753 if ecdh == _ffi.NULL:
754 raise ValueError(
755 "OpenSSL could not load the requested elliptic curve"
756 )
757 _lib.SSL_CTX_set_tmp_ecdh(self._context, ecdh)
758 _lib.EC_KEY_free(ecdh)
759 else:
760 raise ValueError("OpenSSL is compiled without ECDH support")
761
762
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800763 def set_cipher_list(self, cipher_list):
764 """
765 Change the cipher list
766
767 :param cipher_list: A cipher list, see ciphers(1)
768 :return: None
769 """
Jean-Paul Calderone63eab692014-01-18 10:19:56 -0500770 if isinstance(cipher_list, _text_type):
771 cipher_list = cipher_list.encode("ascii")
772
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800773 if not isinstance(cipher_list, bytes):
Jean-Paul Calderone63eab692014-01-18 10:19:56 -0500774 raise TypeError("cipher_list must be bytes or unicode")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800775
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500776 result = _lib.SSL_CTX_set_cipher_list(self._context, cipher_list)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800777 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500778 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800779
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800780
781 def set_client_ca_list(self, certificate_authorities):
782 """
783 Set the list of preferred client certificate signers for this server context.
784
785 This list of certificate authorities will be sent to the client when the
786 server requests a client certificate.
787
788 :param certificate_authorities: a sequence of X509Names.
789 :return: None
790 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500791 name_stack = _lib.sk_X509_NAME_new_null()
792 if name_stack == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500793 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500794 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800795
796 try:
797 for ca_name in certificate_authorities:
798 if not isinstance(ca_name, X509Name):
799 raise TypeError(
800 "client CAs must be X509Name objects, not %s objects" % (
801 type(ca_name).__name__,))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500802 copy = _lib.X509_NAME_dup(ca_name._name)
803 if copy == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500804 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500805 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500806 push_result = _lib.sk_X509_NAME_push(name_stack, copy)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800807 if not push_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500808 _lib.X509_NAME_free(copy)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500809 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800810 except:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500811 _lib.sk_X509_NAME_free(name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800812 raise
813
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500814 _lib.SSL_CTX_set_client_CA_list(self._context, name_stack)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800815
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800816
817 def add_client_ca(self, certificate_authority):
818 """
819 Add the CA certificate to the list of preferred signers for this context.
820
821 The list of certificate authorities will be sent to the client when the
822 server requests a client certificate.
823
824 :param certificate_authority: certificate authority's X509 certificate.
825 :return: None
826 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800827 if not isinstance(certificate_authority, X509):
828 raise TypeError("certificate_authority must be an X509 instance")
829
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500830 add_result = _lib.SSL_CTX_add_client_CA(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800831 self._context, certificate_authority._x509)
832 if not add_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500833 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500834 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800835
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800836
837 def set_timeout(self, timeout):
838 """
839 Set session timeout
840
841 :param timeout: The timeout in seconds
842 :return: The previous session timeout
843 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500844 if not isinstance(timeout, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800845 raise TypeError("timeout must be an integer")
846
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500847 return _lib.SSL_CTX_set_timeout(self._context, timeout)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800848
849
850 def get_timeout(self):
851 """
852 Get the session timeout
853
854 :return: The session timeout
855 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500856 return _lib.SSL_CTX_get_timeout(self._context)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800857
858
859 def set_info_callback(self, callback):
860 """
861 Set the info callback
862
863 :param callback: The Python callback to use
864 :return: None
865 """
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800866 @wraps(callback)
867 def wrapper(ssl, where, return_code):
Jean-Paul Calderonef2bbc9c2014-02-02 10:59:14 -0500868 callback(Connection._reverse_mapping[ssl], where, return_code)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500869 self._info_callback = _ffi.callback(
870 "void (*)(const SSL *, int, int)", wrapper)
871 _lib.SSL_CTX_set_info_callback(self._context, self._info_callback)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800872
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800873
874 def get_app_data(self):
875 """
876 Get the application data (supplied via set_app_data())
877
878 :return: The application data
879 """
880 return self._app_data
881
882
883 def set_app_data(self, data):
884 """
885 Set the application data (will be returned from get_app_data())
886
887 :param data: Any Python object
888 :return: None
889 """
890 self._app_data = data
891
892
893 def get_cert_store(self):
894 """
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500895 Get the certificate store for the context.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800896
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500897 :return: A X509Store object or None if it does not have one.
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800898 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500899 store = _lib.SSL_CTX_get_cert_store(self._context)
900 if store == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500901 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800902 return None
903
904 pystore = X509Store.__new__(X509Store)
905 pystore._store = store
906 return pystore
907
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800908
909 def set_options(self, options):
910 """
911 Add options. Options set before are not cleared!
912
913 :param options: The options to add.
914 :return: The new option bitmask.
915 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500916 if not isinstance(options, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800917 raise TypeError("options must be an integer")
918
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500919 return _lib.SSL_CTX_set_options(self._context, options)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800920
921
922 def set_mode(self, mode):
923 """
924 Add modes via bitmask. Modes set before are not cleared!
925
926 :param mode: The mode to add.
927 :return: The new mode bitmask.
928 """
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -0500929 if not isinstance(mode, integer_types):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800930 raise TypeError("mode must be an integer")
931
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500932 return _lib.SSL_CTX_set_mode(self._context, mode)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800933
934
935 def set_tlsext_servername_callback(self, callback):
936 """
937 Specify a callback function to be called when clients specify a server name.
938
939 :param callback: The callback function. It will be invoked with one
940 argument, the Connection instance.
941 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800942 @wraps(callback)
943 def wrapper(ssl, alert, arg):
944 callback(Connection._reverse_mapping[ssl])
945 return 0
946
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500947 self._tlsext_servername_callback = _ffi.callback(
948 "int (*)(const SSL *, int *, void *)", wrapper)
949 _lib.SSL_CTX_set_tlsext_servername_callback(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800950 self._context, self._tlsext_servername_callback)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -0800951
952ContextType = Context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800953
954
955
956class Connection(object):
957 """
958 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800959 _reverse_mapping = WeakValueDictionary()
960
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800961 def __init__(self, context, socket=None):
962 """
963 Create a new Connection object, using the given OpenSSL.SSL.Context
964 instance and socket.
965
966 :param context: An SSL Context to use for this connection
967 :param socket: The socket to use for transport layer
968 """
969 if not isinstance(context, Context):
970 raise TypeError("context must be a Context instance")
971
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500972 ssl = _lib.SSL_new(context._context)
973 self._ssl = _ffi.gc(ssl, _lib.SSL_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800974 self._context = context
975
976 self._reverse_mapping[self._ssl] = self
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800977
978 if socket is None:
979 self._socket = None
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -0800980 # Don't set up any gc for these, SSL_free will take care of them.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500981 self._into_ssl = _lib.BIO_new(_lib.BIO_s_mem())
982 self._from_ssl = _lib.BIO_new(_lib.BIO_s_mem())
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800983
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500984 if self._into_ssl == _ffi.NULL or self._from_ssl == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500985 # TODO: This is untested.
986 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800987
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500988 _lib.SSL_set_bio(self._ssl, self._into_ssl, self._from_ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800989 else:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800990 self._into_ssl = None
991 self._from_ssl = None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800992 self._socket = socket
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500993 set_result = _lib.SSL_set_fd(self._ssl, _asFileDescriptor(self._socket))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800994 if not set_result:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -0500995 # TODO: This is untested.
996 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -0800997
998
999 def __getattr__(self, name):
1000 """
1001 Look up attributes on the wrapped socket object if they are not found on
1002 the Connection object.
1003 """
1004 return getattr(self._socket, name)
1005
1006
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001007 def _raise_ssl_error(self, ssl, result):
Jean-Paul Calderone7e166fe2013-03-06 20:54:38 -08001008 if self._context._verify_helper is not None:
1009 self._context._verify_helper.raise_if_problem()
1010
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001011 error = _lib.SSL_get_error(ssl, result)
1012 if error == _lib.SSL_ERROR_WANT_READ:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001013 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001014 elif error == _lib.SSL_ERROR_WANT_WRITE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001015 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001016 elif error == _lib.SSL_ERROR_ZERO_RETURN:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001017 raise ZeroReturnError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001018 elif error == _lib.SSL_ERROR_WANT_X509_LOOKUP:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001019 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001020 raise WantX509LookupError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001021 elif error == _lib.SSL_ERROR_SYSCALL:
1022 if _lib.ERR_peek_error() == 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001023 if result < 0:
Konstantinos Koukopoulos541150d2014-01-31 01:00:19 +02001024 if platform == "win32":
1025 errno = _ffi.getwinerror()[0]
1026 else:
1027 errno = _ffi.errno
1028 raise SysCallError(errno, errorcode[errno])
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001029 else:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001030 raise SysCallError(-1, "Unexpected EOF")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001031 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001032 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001033 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001034 elif error == _lib.SSL_ERROR_NONE:
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001035 pass
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001036 else:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001037 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001038
1039
1040 def get_context(self):
1041 """
1042 Get session context
1043 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001044 return self._context
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001045
1046
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001047 def set_context(self, context):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001048 """
1049 Switch this connection to a new session context
1050
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001051 :param context: A :py:class:`Context` instance giving the new session
1052 context to use.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001053 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001054 if not isinstance(context, Context):
1055 raise TypeError("context must be a Context instance")
1056
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001057 _lib.SSL_set_SSL_CTX(self._ssl, context._context)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001058 self._context = context
1059
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001060
1061 def get_servername(self):
1062 """
1063 Retrieve the servername extension value if provided in the client hello
1064 message, or None if there wasn't one.
1065
1066 :return: A byte string giving the server name or :py:data:`None`.
1067 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001068 name = _lib.SSL_get_servername(self._ssl, _lib.TLSEXT_NAMETYPE_host_name)
1069 if name == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001070 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001071
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001072 return _ffi.string(name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001073
1074
1075 def set_tlsext_host_name(self, name):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001076 """
1077 Set the value of the servername extension to send in the client hello.
1078
1079 :param name: A byte string giving the name.
1080 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001081 if not isinstance(name, bytes):
1082 raise TypeError("name must be a byte string")
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001083 elif b"\0" in name:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001084 raise TypeError("name must not contain NUL byte")
1085
1086 # XXX I guess this can fail sometimes?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001087 _lib.SSL_set_tlsext_host_name(self._ssl, name)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001088
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001089
1090 def pending(self):
1091 """
1092 Get the number of bytes that can be safely read from the connection
1093
1094 :return: The number of bytes available in the receive buffer.
1095 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001096 return _lib.SSL_pending(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001097
1098
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001099 def send(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001100 """
1101 Send data on the connection. NOTE: If you get one of the WantRead,
1102 WantWrite or WantX509Lookup exceptions on this, you have to call the
1103 method again with the SAME buffer.
1104
1105 :param buf: The string to send
1106 :param flags: (optional) Included for compatibility with the socket
1107 API, the value is ignored
1108 :return: The number of bytes written
1109 """
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001110 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001111 buf = buf.tobytes()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001112 if not isinstance(buf, bytes):
1113 raise TypeError("data must be a byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001114
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001115 result = _lib.SSL_write(self._ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001116 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001117 return result
1118 write = send
1119
1120
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001121 def sendall(self, buf, flags=0):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001122 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001123 Send "all" data on the connection. This calls send() repeatedly until
1124 all data is sent. If an error occurs, it's impossible to tell how much
1125 data has been sent.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001126
1127 :param buf: The string to send
1128 :param flags: (optional) Included for compatibility with the socket
1129 API, the value is ignored
1130 :return: The number of bytes written
1131 """
Jean-Paul Calderone8fb53182013-12-30 08:35:49 -05001132 if isinstance(buf, _memoryview):
Jean-Paul Calderone1aba4162013-03-05 18:50:00 -08001133 buf = buf.tobytes()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001134 if not isinstance(buf, bytes):
1135 raise TypeError("buf must be a byte string")
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001136
1137 left_to_send = len(buf)
1138 total_sent = 0
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001139 data = _ffi.new("char[]", buf)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001140
1141 while left_to_send:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001142 result = _lib.SSL_write(self._ssl, data + total_sent, left_to_send)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001143 self._raise_ssl_error(self._ssl, result)
1144 total_sent += result
1145 left_to_send -= result
1146
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001147
1148 def recv(self, bufsiz, flags=None):
1149 """
1150 Receive data on the connection. NOTE: If you get one of the WantRead,
1151 WantWrite or WantX509Lookup exceptions on this, you have to call the
1152 method again with the SAME buffer.
1153
1154 :param bufsiz: The maximum number of bytes to read
1155 :param flags: (optional) Included for compatibility with the socket
1156 API, the value is ignored
1157 :return: The string read from the Connection
1158 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001159 buf = _ffi.new("char[]", bufsiz)
1160 result = _lib.SSL_read(self._ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001161 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001162 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001163 read = recv
1164
1165
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001166 def _handle_bio_errors(self, bio, result):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001167 if _lib.BIO_should_retry(bio):
1168 if _lib.BIO_should_read(bio):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001169 raise WantReadError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001170 elif _lib.BIO_should_write(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001171 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001172 raise WantWriteError()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001173 elif _lib.BIO_should_io_special(bio):
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001174 # TODO: This is untested. I think io_special means the socket
1175 # BIO has a not-yet connected socket.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001176 raise ValueError("BIO_should_io_special")
1177 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001178 # TODO: This is untested.
Jean-Paul Calderoned899af02013-03-19 22:10:37 -07001179 raise ValueError("unknown bio failure")
1180 else:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001181 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001182 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001183
1184
1185 def bio_read(self, bufsiz):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001186 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001187 When using non-socket connections this function reads the "dirty" data
1188 that would have traveled away on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001189
1190 :param bufsiz: The maximum number of bytes to read
1191 :return: The string read.
1192 """
Jean-Paul Calderone97e041d2013-03-05 21:03:12 -08001193 if self._from_ssl is None:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001194 raise TypeError("Connection sock was not None")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001195
Jean-Paul Calderonebef4f4c2014-02-02 18:13:31 -05001196 if not isinstance(bufsiz, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001197 raise TypeError("bufsiz must be an integer")
1198
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001199 buf = _ffi.new("char[]", bufsiz)
1200 result = _lib.BIO_read(self._from_ssl, buf, bufsiz)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001201 if result <= 0:
1202 self._handle_bio_errors(self._from_ssl, result)
1203
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001204 return _ffi.buffer(buf, result)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001205
1206
1207 def bio_write(self, buf):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001208 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001209 When using non-socket connections this function sends "dirty" data that
1210 would have traveled in on the network.
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001211
1212 :param buf: The string to put into the memory BIO.
1213 :return: The number of bytes written
1214 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001215 if self._into_ssl is None:
1216 raise TypeError("Connection sock was not None")
1217
1218 if not isinstance(buf, bytes):
1219 raise TypeError("buf must be a byte string")
1220
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001221 result = _lib.BIO_write(self._into_ssl, buf, len(buf))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001222 if result <= 0:
1223 self._handle_bio_errors(self._into_ssl, result)
1224 return result
1225
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001226
1227 def renegotiate(self):
1228 """
1229 Renegotiate the session
1230
1231 :return: True if the renegotiation can be started, false otherwise
1232 """
1233
1234 def do_handshake(self):
1235 """
1236 Perform an SSL handshake (usually called after renegotiate() or one of
1237 set_*_state()). This can raise the same exceptions as send and recv.
1238
1239 :return: None.
1240 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001241 result = _lib.SSL_do_handshake(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001242 self._raise_ssl_error(self._ssl, result)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001243
1244
1245 def renegotiate_pending(self):
1246 """
1247 Check if there's a renegotiation in progress, it will return false once
1248 a renegotiation is finished.
1249
1250 :return: Whether there's a renegotiation in progress
1251 """
1252
1253 def total_renegotiations(self):
1254 """
1255 Find out the total number of renegotiations.
1256
1257 :return: The number of renegotiations.
1258 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001259 return _lib.SSL_total_renegotiations(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001260
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001261
1262 def connect(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001263 """
1264 Connect to remote host and set up client-side SSL
1265
1266 :param addr: A remote address
1267 :return: What the socket's connect method returns
1268 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001269 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001270 return self._socket.connect(addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001271
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001272
1273 def connect_ex(self, addr):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001274 """
1275 Connect to remote host and set up client-side SSL. Note that if the socket's
1276 connect_ex method doesn't return 0, SSL won't be initialized.
1277
1278 :param addr: A remove address
1279 :return: What the socket's connect_ex method returns
1280 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001281 connect_ex = self._socket.connect_ex
1282 self.set_connect_state()
1283 return connect_ex(addr)
1284
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001285
1286 def accept(self):
1287 """
1288 Accept incoming connection and set up SSL on it
1289
1290 :return: A (conn,addr) pair where conn is a Connection and addr is an
1291 address
1292 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001293 client, addr = self._socket.accept()
1294 conn = Connection(self._context, client)
1295 conn.set_accept_state()
1296 return (conn, addr)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001297
1298
1299 def bio_shutdown(self):
1300 """
1301 When using non-socket connections this function signals end of
1302 data on the input for this connection.
1303
1304 :return: None
1305 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001306 if self._from_ssl is None:
1307 raise TypeError("Connection sock was not None")
1308
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001309 _lib.BIO_set_mem_eof_return(self._into_ssl, 0)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001310
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001311
1312 def shutdown(self):
1313 """
1314 Send closure alert
1315
1316 :return: True if the shutdown completed successfully (i.e. both sides
1317 have sent closure alerts), false otherwise (i.e. you have to
1318 wait for a ZeroReturnError on a recv() method call
1319 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001320 result = _lib.SSL_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001321 if result < 0:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001322 # TODO: This is untested.
1323 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001324 elif result > 0:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001325 return True
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001326 else:
1327 return False
1328
1329
1330 def get_cipher_list(self):
1331 """
1332 Get the session cipher list
1333
1334 :return: A list of cipher strings
1335 """
1336 ciphers = []
1337 for i in count():
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001338 result = _lib.SSL_get_cipher_list(self._ssl, i)
1339 if result == _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001340 break
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001341 ciphers.append(_native(_ffi.string(result)))
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001342 return ciphers
1343
1344
1345 def get_client_ca_list(self):
1346 """
1347 Get CAs whose certificates are suggested for client authentication.
1348
1349 :return: If this is a server connection, a list of X509Names representing
1350 the acceptable CAs as set by :py:meth:`OpenSSL.SSL.Context.set_client_ca_list` or
1351 :py:meth:`OpenSSL.SSL.Context.add_client_ca`. If this is a client connection,
1352 the list of such X509Names sent by the server, or an empty list if that
1353 has not yet happened.
1354 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001355 ca_names = _lib.SSL_get_client_CA_list(self._ssl)
1356 if ca_names == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001357 # TODO: This is untested.
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001358 return []
1359
1360 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001361 for i in range(_lib.sk_X509_NAME_num(ca_names)):
1362 name = _lib.sk_X509_NAME_value(ca_names, i)
1363 copy = _lib.X509_NAME_dup(name)
1364 if copy == _ffi.NULL:
Jean-Paul Calderonea9f84ad2013-12-29 17:06:11 -05001365 # TODO: This is untested.
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001366 _raise_current_error()
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001367
1368 pyname = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001369 pyname._name = _ffi.gc(copy, _lib.X509_NAME_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001370 result.append(pyname)
1371 return result
1372
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001373
1374 def makefile(self):
1375 """
1376 The makefile() method is not implemented, since there is no dup semantics
1377 for SSL connections
1378
1379 :raise NotImplementedError
1380 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001381 raise NotImplementedError("Cannot make file object of OpenSSL.SSL.Connection")
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001382
1383
1384 def get_app_data(self):
1385 """
1386 Get application data
1387
1388 :return: The application data
1389 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001390 return self._app_data
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001391
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001392
1393 def set_app_data(self, data):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001394 """
1395 Set application data
1396
1397 :param data - The application data
1398 :return: None
1399 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001400 self._app_data = data
1401
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001402
1403 def get_shutdown(self):
1404 """
1405 Get shutdown state
1406
1407 :return: The shutdown state, a bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
1408 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001409 return _lib.SSL_get_shutdown(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001410
1411
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001412 def set_shutdown(self, state):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001413 """
1414 Set shutdown state
1415
1416 :param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
1417 :return: None
1418 """
Jean-Paul Calderonef73a3cb2014-02-09 08:49:06 -05001419 if not isinstance(state, integer_types):
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001420 raise TypeError("state must be an integer")
1421
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001422 _lib.SSL_set_shutdown(self._ssl, state)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001423
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001424
1425 def state_string(self):
1426 """
1427 Get a verbose state description
1428
1429 :return: A string representing the state
1430 """
1431
1432 def server_random(self):
1433 """
1434 Get a copy of the server hello nonce.
1435
1436 :return: A string representing the state
1437 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001438 if self._ssl.session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001439 return None
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001440 return _ffi.buffer(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001441 self._ssl.s3.server_random,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001442 _lib.SSL3_RANDOM_SIZE)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001443
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001444
1445 def client_random(self):
1446 """
1447 Get a copy of the client hello nonce.
1448
1449 :return: A string representing the state
1450 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001451 if self._ssl.session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001452 return None
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001453 return _ffi.buffer(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001454 self._ssl.s3.client_random,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001455 _lib.SSL3_RANDOM_SIZE)[:]
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001456
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001457
1458 def master_key(self):
1459 """
1460 Get a copy of the master key.
1461
1462 :return: A string representing the state
1463 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001464 if self._ssl.session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001465 return None
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001466 return _ffi.buffer(
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001467 self._ssl.session.master_key,
1468 self._ssl.session.master_key_length)[:]
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001469
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001470
1471 def sock_shutdown(self, *args, **kwargs):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001472 """
1473 See shutdown(2)
1474
1475 :return: What the socket's shutdown() method returns
1476 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001477 return self._socket.shutdown(*args, **kwargs)
1478
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001479
1480 def get_peer_certificate(self):
1481 """
1482 Retrieve the other side's certificate (if any)
1483
1484 :return: The peer's certificate
1485 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001486 cert = _lib.SSL_get_peer_certificate(self._ssl)
1487 if cert != _ffi.NULL:
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001488 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001489 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001490 return pycert
1491 return None
1492
1493
1494 def get_peer_cert_chain(self):
1495 """
1496 Retrieve the other side's certificate (if any)
1497
1498 :return: A list of X509 instances giving the peer's certificate chain,
1499 or None if it does not have one.
1500 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001501 cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl)
1502 if cert_stack == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001503 return None
1504
1505 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001506 for i in range(_lib.sk_X509_num(cert_stack)):
Jean-Paul Calderone73b15c22013-03-05 18:30:39 -08001507 # TODO could incref instead of dup here
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001508 cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i))
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001509 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001510 pycert._x509 = _ffi.gc(cert, _lib.X509_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001511 result.append(pycert)
1512 return result
1513
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001514
1515 def want_read(self):
1516 """
1517 Checks if more data has to be read from the transport layer to complete an
1518 operation.
1519
1520 :return: True iff more data has to be read
1521 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001522 return _lib.SSL_want_read(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001523
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001524
1525 def want_write(self):
1526 """
1527 Checks if there is data to write to the transport layer to complete an
1528 operation.
1529
1530 :return: True iff there is data to write
1531 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001532 return _lib.SSL_want_write(self._ssl)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001533
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001534
1535 def set_accept_state(self):
1536 """
1537 Set the connection to work in server mode. The handshake will be handled
1538 automatically by read/write.
1539
1540 :return: None
1541 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001542 _lib.SSL_set_accept_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001543
1544
1545 def set_connect_state(self):
1546 """
1547 Set the connection to work in client mode. The handshake will be handled
1548 automatically by read/write.
1549
1550 :return: None
1551 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001552 _lib.SSL_set_connect_state(self._ssl)
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001553
1554
1555 def get_session(self):
1556 """
1557 Returns the Session currently used.
1558
1559 @return: An instance of :py:class:`OpenSSL.SSL.Session` or :py:obj:`None` if
1560 no session exists.
1561 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001562 session = _lib.SSL_get1_session(self._ssl)
1563 if session == _ffi.NULL:
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001564 return None
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001565
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001566 pysession = Session.__new__(Session)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001567 pysession._session = _ffi.gc(session, _lib.SSL_SESSION_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001568 return pysession
1569
1570
1571 def set_session(self, session):
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001572 """
1573 Set the session to be used when the TLS/SSL connection is established.
1574
1575 :param session: A Session instance representing the session to use.
1576 :returns: None
1577 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001578 if not isinstance(session, Session):
1579 raise TypeError("session must be a Session instance")
1580
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001581 result = _lib.SSL_set_session(self._ssl, session._session)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001582 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001583 _raise_current_error()
Jean-Paul Calderone131052e2013-03-05 11:56:19 -08001584
1585ConnectionType = Connection
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05001586
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05001587# This is similar to the initialization calls at the end of OpenSSL/crypto.py
1588# but is exercised mostly by the Context initializer.
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05001589_lib.SSL_library_init()