0
# SSL Connections
1
2
Complete SSL/TLS connection handling with support for modern protocols, session management, and advanced features. Provides high-level SSL/TLS client and server capabilities with extensive configuration options.
3
4
## Capabilities
5
6
### SSL Context Configuration
7
8
SSL contexts define the parameters and behavior for SSL/TLS connections, including protocol versions, certificates, verification settings, and cryptographic options.
9
10
```python { .api }
11
class Context:
12
def __init__(self, method: int):
13
"""
14
Create SSL context with specific method.
15
16
Parameters:
17
- method: SSL method constant (TLS_METHOD, TLS_CLIENT_METHOD, TLS_SERVER_METHOD, etc.)
18
"""
19
20
def set_min_proto_version(self, version: int):
21
"""Set minimum protocol version (TLS1_VERSION, TLS1_2_VERSION, etc.)"""
22
23
def set_max_proto_version(self, version: int):
24
"""Set maximum protocol version"""
25
26
def load_verify_locations(self, cafile, capath=None):
27
"""Load CA certificates from file or directory"""
28
29
def set_default_verify_paths(self):
30
"""Use system default CA certificate locations"""
31
32
def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
33
"""Load certificate from file"""
34
35
def use_privatekey_file(self, keyfile, filetype=FILETYPE_PEM):
36
"""Load private key from file"""
37
38
def check_privatekey(self):
39
"""Verify private key matches certificate"""
40
41
def set_verify(self, mode: int, callback=None):
42
"""
43
Set peer certificate verification mode.
44
45
Parameters:
46
- mode: VERIFY_NONE, VERIFY_PEER, VERIFY_FAIL_IF_NO_PEER_CERT
47
- callback: Optional verification callback function
48
"""
49
50
def set_cipher_list(self, cipher_list):
51
"""Set allowed cipher suites"""
52
53
def set_options(self, options: int):
54
"""Set SSL option flags (OP_NO_SSLv3, OP_SINGLE_DH_USE, etc.)"""
55
56
def set_alpn_protos(self, protos):
57
"""Set ALPN protocols for client"""
58
59
def set_alpn_select_callback(self, callback):
60
"""Set ALPN selection callback for server"""
61
62
def use_certificate(self, cert: X509):
63
"""Use X509 certificate object"""
64
65
def use_certificate_chain_file(self, certfile):
66
"""Load certificate chain from file"""
67
68
def add_extra_chain_cert(self, certobj: X509):
69
"""Add certificate to chain"""
70
71
def use_privatekey(self, pkey: PKey):
72
"""Use PKey private key object"""
73
74
def set_passwd_cb(self, callback, userdata=None):
75
"""Set private key password callback"""
76
77
def load_client_ca(self, cafile):
78
"""Load client CA certificate from file"""
79
80
def set_client_ca_list(self, certificate_authorities):
81
"""Set list of client CA certificates"""
82
83
def add_client_ca(self, certificate_authority: X509):
84
"""Add client CA certificate"""
85
86
def set_session_id(self, buf: bytes):
87
"""Set SSL session ID context"""
88
89
def set_session_cache_mode(self, mode: int) -> int:
90
"""Set session cache mode, returns previous mode"""
91
92
def get_session_cache_mode(self) -> int:
93
"""Get current session cache mode"""
94
95
def set_verify_depth(self, depth: int):
96
"""Set maximum certificate chain depth"""
97
98
def get_verify_mode(self) -> int:
99
"""Get current verification mode"""
100
101
def get_verify_depth(self) -> int:
102
"""Get maximum verification depth"""
103
104
def load_tmp_dh(self, dhfile):
105
"""Load Diffie-Hellman parameters from file"""
106
107
def set_tmp_ecdh(self, curve):
108
"""Set elliptic curve for ECDH"""
109
110
def set_timeout(self, timeout: int):
111
"""Set session timeout in seconds"""
112
113
def get_timeout(self) -> int:
114
"""Get session timeout"""
115
116
def set_info_callback(self, callback):
117
"""Set info callback for debugging"""
118
119
def set_keylog_callback(self, callback):
120
"""Set key logging callback (for debugging)"""
121
122
def get_app_data(self):
123
"""Get application data associated with context"""
124
125
def set_app_data(self, data):
126
"""Set application data for context"""
127
128
def get_cert_store(self):
129
"""Get certificate store (X509Store)"""
130
131
def set_options(self, options: int) -> int:
132
"""Set SSL options, returns new options value"""
133
134
def set_mode(self, mode: int) -> int:
135
"""Set SSL mode, returns new mode value"""
136
137
def set_tlsext_servername_callback(self, callback):
138
"""Set SNI (Server Name Indication) callback"""
139
140
def set_tlsext_use_srtp(self, profiles):
141
"""Set SRTP profiles for DTLS"""
142
143
def set_ocsp_server_callback(self, callback, data=None):
144
"""Set OCSP stapling callback for server"""
145
146
def set_ocsp_client_callback(self, callback, data=None):
147
"""Set OCSP callback for client"""
148
149
def set_cookie_generate_callback(self, callback):
150
"""Set DTLS cookie generation callback"""
151
152
def set_cookie_verify_callback(self, callback):
153
"""Set DTLS cookie verification callback"""
154
```
155
156
### SSL Connections
157
158
SSL connections wrap sockets with SSL/TLS encryption, providing secure data transmission with certificate validation and session management.
159
160
```python { .api }
161
class Connection:
162
def __init__(self, context: Context, socket=None):
163
"""
164
Create SSL connection with context and optional socket.
165
166
Parameters:
167
- context: SSL context defining connection parameters
168
- socket: Optional existing socket to wrap
169
"""
170
171
def connect(self, addr):
172
"""Connect to remote address (client mode)"""
173
174
def accept(self) -> tuple:
175
"""Accept incoming connection (server mode), returns (conn, addr)"""
176
177
def do_handshake(self):
178
"""Perform SSL handshake"""
179
180
def send(self, buf, flags=0) -> int:
181
"""
182
Send data over SSL connection.
183
184
Parameters:
185
- buf: Data to send (bytes)
186
- flags: Optional socket flags
187
188
Returns:
189
Number of bytes sent
190
"""
191
192
def sendall(self, buf, flags=0):
193
"""Send all data over SSL connection"""
194
195
def recv(self, bufsiz, flags=None) -> bytes:
196
"""
197
Receive data from SSL connection.
198
199
Parameters:
200
- bufsiz: Maximum bytes to receive
201
- flags: Optional socket flags
202
203
Returns:
204
Received data as bytes
205
"""
206
207
def recv_into(self, buffer, nbytes=None, flags=None) -> int:
208
"""Receive data into existing buffer"""
209
210
def pending(self) -> int:
211
"""Get number of bytes pending in SSL buffer"""
212
213
def shutdown(self) -> bool:
214
"""Send SSL shutdown notification"""
215
216
def get_peer_certificate(self, *, as_cryptography=False):
217
"""
218
Get peer's certificate.
219
220
Parameters:
221
- as_cryptography: Return cryptography.x509.Certificate if True
222
223
Returns:
224
X509 certificate or None
225
"""
226
227
def get_peer_cert_chain(self, *, as_cryptography=False) -> list:
228
"""Get complete peer certificate chain"""
229
230
def get_cipher_name(self) -> str:
231
"""Get current cipher suite name"""
232
233
def get_protocol_version_name(self) -> str:
234
"""Get protocol version string (e.g., 'TLSv1.3')"""
235
236
def get_protocol_version(self) -> int:
237
"""Get protocol version as integer constant"""
238
239
def get_context(self) -> Context:
240
"""Get SSL context"""
241
242
def set_context(self, context: Context):
243
"""Change SSL context"""
244
245
def get_servername(self) -> bytes:
246
"""Get SNI server name"""
247
248
def set_verify(self, mode: int, callback=None):
249
"""Set verification mode for this connection"""
250
251
def get_verify_mode(self) -> int:
252
"""Get verification mode"""
253
254
def use_certificate(self, cert: X509):
255
"""Use certificate for this connection"""
256
257
def use_privatekey(self, pkey: PKey):
258
"""Use private key for this connection"""
259
260
def set_ciphertext_mtu(self, mtu: int):
261
"""Set DTLS ciphertext MTU"""
262
263
def get_cleartext_mtu(self) -> int:
264
"""Get DTLS cleartext MTU"""
265
266
def set_tlsext_host_name(self, name: bytes):
267
"""Set SNI hostname for client"""
268
269
def bio_read(self, bufsiz: int) -> bytes:
270
"""Read from internal BIO buffer"""
271
272
def bio_write(self, buf: bytes) -> int:
273
"""Write to internal BIO buffer"""
274
275
def renegotiate(self) -> bool:
276
"""Request SSL renegotiation"""
277
278
def renegotiate_pending(self) -> bool:
279
"""Check if renegotiation is pending"""
280
281
def total_renegotiations(self) -> int:
282
"""Get total number of renegotiations"""
283
284
def connect_ex(self, addr) -> int:
285
"""Non-blocking connect, returns error code"""
286
287
def DTLSv1_listen(self):
288
"""DTLS server listen for cookie exchange"""
289
290
def DTLSv1_get_timeout(self) -> int:
291
"""Get DTLS timeout value"""
292
293
def DTLSv1_handle_timeout(self) -> bool:
294
"""Handle DTLS timeout"""
295
296
def bio_shutdown(self):
297
"""Shutdown internal BIO"""
298
299
def get_cipher_list(self) -> list:
300
"""Get list of available ciphers"""
301
302
def get_client_ca_list(self) -> list:
303
"""Get list of client CA names"""
304
305
def get_app_data(self):
306
"""Get application data"""
307
308
def set_app_data(self, data):
309
"""Set application data"""
310
311
def get_shutdown(self) -> int:
312
"""Get shutdown state"""
313
314
def set_shutdown(self, state: int):
315
"""Set shutdown state"""
316
317
def get_state_string(self) -> bytes:
318
"""Get SSL state as string"""
319
320
def server_random(self) -> bytes:
321
"""Get server random bytes"""
322
323
def client_random(self) -> bytes:
324
"""Get client random bytes"""
325
326
def master_key(self) -> bytes:
327
"""Get master key (for debugging)"""
328
329
def export_keying_material(self, label: bytes, olen: int, context: bytes = None) -> bytes:
330
"""Export keying material for external use"""
331
332
def sock_shutdown(self, *args, **kwargs):
333
"""Call underlying socket shutdown"""
334
335
def get_certificate(self, *, as_cryptography=False):
336
"""Get local certificate"""
337
338
def get_peer_cert_chain(self, *, as_cryptography=False) -> list:
339
"""Get complete peer certificate chain"""
340
341
def get_verified_chain(self, *, as_cryptography=False) -> list:
342
"""Get verified certificate chain"""
343
344
def want_read(self) -> bool:
345
"""Check if SSL wants to read"""
346
347
def want_write(self) -> bool:
348
"""Check if SSL wants to write"""
349
350
def set_accept_state(self):
351
"""Set connection to server mode"""
352
353
def set_connect_state(self):
354
"""Set connection to client mode"""
355
356
def get_session(self):
357
"""Get SSL session object"""
358
359
def set_session(self, session):
360
"""Set SSL session for resumption"""
361
362
def get_finished(self) -> bytes:
363
"""Get local finished message"""
364
365
def get_peer_finished(self) -> bytes:
366
"""Get peer finished message"""
367
368
def get_cipher_bits(self) -> int:
369
"""Get cipher strength in bits"""
370
371
def get_cipher_version(self) -> str:
372
"""Get cipher protocol version"""
373
374
def set_alpn_protos(self, protos):
375
"""Set ALPN protocols for this connection"""
376
377
def get_alpn_proto_negotiated(self) -> bytes:
378
"""Get negotiated ALPN protocol"""
379
380
def get_selected_srtp_profile(self) -> bytes:
381
"""Get selected SRTP profile"""
382
383
def request_ocsp(self):
384
"""Request OCSP stapling"""
385
```
386
387
### SSL Sessions
388
389
SSL session objects for session resumption and caching.
390
391
```python { .api }
392
class Session:
393
"""
394
Opaque SSL session object for session resumption.
395
Sessions allow clients to resume previous SSL connections
396
without performing a full handshake.
397
"""
398
pass
399
```
400
401
### SSL Utility Functions
402
403
Utility functions for accessing OpenSSL version information and debugging.
404
405
```python { .api }
406
def OpenSSL_version(type: int = OPENSSL_VERSION) -> bytes:
407
"""
408
Get OpenSSL version information.
409
410
Parameters:
411
- type: Information type (OPENSSL_VERSION, OPENSSL_CFLAGS, etc.)
412
413
Returns:
414
Requested information as bytes
415
"""
416
417
# Backward compatibility alias
418
SSLeay_version = OpenSSL_version
419
```
420
421
### SSL Constants
422
423
Comprehensive set of protocol methods, versions, options, and verification modes for SSL/TLS configuration.
424
425
```python { .api }
426
# SSL Methods
427
TLS_METHOD: int # Auto-negotiate TLS (recommended)
428
TLS_CLIENT_METHOD: int # Client-side TLS
429
TLS_SERVER_METHOD: int # Server-side TLS
430
DTLS_METHOD: int # DTLS protocol
431
DTLS_CLIENT_METHOD: int # Client-side DTLS
432
DTLS_SERVER_METHOD: int # Server-side DTLS
433
434
# Deprecated methods (for backward compatibility)
435
SSLv23_METHOD: int # Deprecated, use TLS_METHOD instead
436
TLSv1_METHOD: int # Deprecated TLS 1.0 only
437
TLSv1_1_METHOD: int # Deprecated TLS 1.1 only
438
TLSv1_2_METHOD: int # Deprecated TLS 1.2 only
439
440
# Protocol Versions
441
SSL3_VERSION: int # SSL 3.0 (deprecated)
442
TLS1_VERSION: int # TLS 1.0
443
TLS1_1_VERSION: int # TLS 1.1
444
TLS1_2_VERSION: int # TLS 1.2
445
TLS1_3_VERSION: int # TLS 1.3
446
447
# OpenSSL Version Information
448
OPENSSL_VERSION_NUMBER: int # OpenSSL version as integer
449
OPENSSL_VERSION: bytes # OpenSSL version string
450
OPENSSL_CFLAGS: bytes # Compilation flags
451
OPENSSL_PLATFORM: bytes # Platform information
452
OPENSSL_DIR: bytes # OpenSSL directory
453
OPENSSL_BUILT_ON: bytes # Build timestamp
454
455
# Legacy aliases
456
SSLEAY_VERSION: bytes # Alias for OPENSSL_VERSION
457
SSLEAY_CFLAGS: bytes # Alias for OPENSSL_CFLAGS
458
SSLEAY_PLATFORM: bytes # Alias for OPENSSL_PLATFORM
459
SSLEAY_DIR: bytes # Alias for OPENSSL_DIR
460
SSLEAY_BUILT_ON: bytes # Alias for OPENSSL_BUILT_ON
461
462
# SSL Options (OP_*)
463
OP_ALL: int # Enable all bug workarounds
464
OP_NO_SSLv2: int # Disable SSL 2.0
465
OP_NO_SSLv3: int # Disable SSL 3.0
466
OP_NO_TLSv1: int # Disable TLS 1.0
467
OP_NO_TLSv1_1: int # Disable TLS 1.1
468
OP_NO_TLSv1_2: int # Disable TLS 1.2
469
OP_NO_TLSv1_3: int # Disable TLS 1.3
470
OP_SINGLE_DH_USE: int # Generate new DH key per handshake
471
OP_SINGLE_ECDH_USE: int # Generate new ECDH key per handshake
472
OP_NO_COMPRESSION: int # Disable compression
473
OP_NO_TICKET: int # Disable session tickets
474
OP_CIPHER_SERVER_PREFERENCE: int # Use server cipher preference
475
OP_COOKIE_EXCHANGE: int # Enable cookie exchange for DTLS
476
OP_NO_QUERY_MTU: int # Don't query MTU for DTLS
477
478
# Verification Modes
479
VERIFY_NONE: int # No peer verification
480
VERIFY_PEER: int # Verify peer certificate
481
VERIFY_FAIL_IF_NO_PEER_CERT: int # Fail if no peer cert
482
VERIFY_CLIENT_ONCE: int # Only verify client once
483
484
# Session Cache Modes
485
SESS_CACHE_OFF: int # Disable session cache
486
SESS_CACHE_CLIENT: int # Client-side caching
487
SESS_CACHE_SERVER: int # Server-side caching
488
SESS_CACHE_BOTH: int # Both client and server caching
489
SESS_CACHE_NO_AUTO_CLEAR: int # Don't auto-clear cache
490
SESS_CACHE_NO_INTERNAL: int # Don't use internal cache
491
SESS_CACHE_NO_INTERNAL_LOOKUP: int # Don't lookup in internal cache
492
SESS_CACHE_NO_INTERNAL_STORE: int # Don't store in internal cache
493
494
# SSL States
495
SSL_ST_CONNECT: int # Connect state
496
SSL_ST_ACCEPT: int # Accept state
497
SSL_ST_MASK: int # State mask
498
499
# Callback Constants
500
SSL_CB_LOOP: int # Handshake loop callback
501
SSL_CB_EXIT: int # Handshake exit callback
502
SSL_CB_READ: int # Read callback
503
SSL_CB_WRITE: int # Write callback
504
SSL_CB_ALERT: int # Alert callback
505
SSL_CB_HANDSHAKE_START: int # Handshake start callback
506
SSL_CB_HANDSHAKE_DONE: int # Handshake done callback
507
508
# Shutdown States
509
SENT_SHUTDOWN: int # Shutdown notification sent
510
RECEIVED_SHUTDOWN: int # Shutdown notification received
511
512
# Special Objects
513
NO_OVERLAPPING_PROTOCOLS: object # Sentinel for ALPN callback
514
```
515
516
### SSL Exceptions
517
518
Specialized exceptions for SSL/TLS operations and non-blocking I/O handling.
519
520
```python { .api }
521
class Error(Exception):
522
"""Base SSL exception"""
523
524
class WantReadError(Error):
525
"""SSL needs to read more data (non-blocking)"""
526
527
class WantWriteError(Error):
528
"""SSL needs to write data (non-blocking)"""
529
530
class WantX509LookupError(Error):
531
"""SSL needs X509 lookup (certificate callback)"""
532
533
class ZeroReturnError(Error):
534
"""Clean SSL connection shutdown"""
535
536
class SysCallError(Error):
537
"""System call error during SSL operation"""
538
```
539
540
## Usage Examples
541
542
### Basic Client Connection
543
544
```python
545
from OpenSSL import SSL
546
import socket
547
548
# Create SSL context
549
context = SSL.Context(SSL.TLS_CLIENT_METHOD)
550
context.set_default_verify_paths()
551
context.set_verify(SSL.VERIFY_PEER, None)
552
553
# Create connection
554
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
555
connection = SSL.Connection(context, sock)
556
557
# Connect and perform handshake
558
connection.connect(('www.example.com', 443))
559
connection.do_handshake()
560
561
# Verify peer certificate
562
peer_cert = connection.get_peer_certificate()
563
if peer_cert:
564
print(f"Connected to: {peer_cert.get_subject().CN}")
565
566
# Send data
567
connection.send(b'GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n')
568
response = connection.recv(4096)
569
570
connection.close()
571
```
572
573
### Server with Certificate
574
575
```python
576
from OpenSSL import SSL
577
import socket
578
579
# Create server context
580
context = SSL.Context(SSL.TLS_SERVER_METHOD)
581
context.use_certificate_file('server.crt')
582
context.use_privatekey_file('server.key')
583
context.check_privatekey()
584
585
# Create server socket
586
server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
587
server_sock.bind(('localhost', 8443))
588
server_sock.listen(5)
589
590
while True:
591
# Accept connection
592
client_sock, addr = server_sock.accept()
593
connection = SSL.Connection(context, client_sock)
594
595
try:
596
connection.do_handshake()
597
data = connection.recv(1024)
598
connection.send(b'HTTP/1.1 200 OK\r\n\r\nHello SSL!')
599
finally:
600
connection.close()
601
```
602
603
### Advanced Configuration
604
605
```python
606
from OpenSSL import SSL
607
608
context = SSL.Context(SSL.TLS_SERVER_METHOD)
609
610
# Set protocol version range
611
context.set_min_proto_version(SSL.TLS1_2_VERSION)
612
context.set_max_proto_version(SSL.TLS1_3_VERSION)
613
614
# Configure cipher suites
615
context.set_cipher_list(b'ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM')
616
617
# Set SSL options
618
context.set_options(SSL.OP_NO_SSLv3 | SSL.OP_SINGLE_DH_USE)
619
620
# Configure ALPN for HTTP/2
621
context.set_alpn_protos([b'h2', b'http/1.1'])
622
623
# Set verification
624
context.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, None)
625
context.load_verify_locations('ca-bundle.crt')
626
```