← Back to DAGDA | Support | Source: https://github.com/python/cpython/commit/35ac3a7e6be946c26455fd6acf9ace1b16d061a9
Skip to content

Commit 35ac3a7

Browse files
committed
Example of how to extend the ssl library using ctypes
1 parent efe4f06 commit 35ac3a7

2 files changed

Lines changed: 56 additions & 0 deletions

File tree

‎ssl_export_keying_material.py‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
#! /opt/python-master/bin/python3
2+
import ssl
3+
4+
# Only install a ctype version if there isn't alreay a native implementation
5+
if not hasattr(ssl.SSLSocket, 'export_keying_material'):
6+
import ctypes
7+
8+
ssl_lib = ctypes.CDLL(ssl._ssl.SSL_DLL_PATH)
9+
10+
ssl_lib.SSL_export_keying_material.argtypes = (
11+
ctypes.c_void_p, # SSL pointer
12+
ctypes.c_void_p, ctypes.c_size_t, # out pointer, out length
13+
ctypes.c_void_p, ctypes.c_size_t, # label buffer, label length
14+
ctypes.c_void_p, ctypes.c_size_t, # context, context length
15+
ctypes.c_int) # use context flag
16+
ssl_lib.SSL_export_keying_material.restype = ctypes.c_int
17+
18+
def SSL_export_keying_material(self, label, key_len, context = None):
19+
sslobj = self._sslobj
20+
21+
c_ssl_addr = sslobj.get_internal_addr()
22+
23+
c_key_len = key_len
24+
c_key = ctypes.create_string_buffer(c_key_len)
25+
26+
c_label_len = len(label)
27+
c_label = ctypes.create_string_buffer(label, c_label_len)
28+
29+
if context is None:
30+
c_context_len = 0
31+
c_context = 0
32+
c_use_context = 0
33+
else:
34+
c_context_len = len(context)
35+
c_context = ctypes.create_string_buffer(context, c_context_len)
36+
c_use_context = 1
37+
38+
if ssl_lib.SSL_export_keying_material(
39+
c_ssl_addr,
40+
c_key, c_key_len,
41+
c_label, c_label_len,
42+
c_context, c_context_len, c_use_context):
43+
return bytes(c_key)
44+
else:
45+
return None
46+
47+
ssl.SSLSocket.export_keying_material = SSL_export_keying_material

‎ssl_test.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,15 @@
3838
km = ssock.export_keying_material(label, km_len, context)
3939
print("%s:" % ssock.export_keying_material.__name__, binascii.b2a_hex(km))
4040

41+
# And delete it so that the extension version is installed next
42+
del ssl.SSLSocket.export_keying_material
43+
44+
print()
45+
print("extension")
46+
import ssl_export_keying_material
47+
km = ssock.export_keying_material(label, km_len, context)
48+
print("%s:" % ssock.export_keying_material.__name__, binascii.b2a_hex(km))
49+
4150
print()
4251
print("ctypes")
4352

0 commit comments

Comments
 (0)