pyopenssl-psk 1.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ from ._psk import patch_context
openssl_psk/_psk.py ADDED
@@ -0,0 +1,221 @@
1
+ import warnings
2
+ from functools import wraps
3
+
4
+ from OpenSSL import SSL
5
+
6
+
7
+ def _fallback_openssl_assert(ok):
8
+ if not ok:
9
+ # Avoid leaving this failure in OpenSSL's error queue for a later call.
10
+ SSL._lib.ERR_clear_error()
11
+ raise SSL.Error("Failed to set the PSK identity hint.")
12
+
13
+
14
+ # _openssl_assert is private, so retain a fallback for releases that omit it.
15
+ try:
16
+ _openssl_assert = SSL._openssl_assert
17
+ except AttributeError:
18
+ _openssl_assert = _fallback_openssl_assert
19
+
20
+
21
+ def _text_to_bytes_and_warn(label, value):
22
+ if isinstance(value, str):
23
+ warnings.warn(
24
+ f"str for {label} is no longer accepted, use bytes",
25
+ DeprecationWarning,
26
+ stacklevel=3,
27
+ )
28
+ return value.encode("utf-8")
29
+ return value
30
+
31
+
32
+ def _record_callback_exception(conn, error):
33
+ # Older PyOpenSSL versions lack this queue; returning 0 still fails the handshake.
34
+ callback_problems = getattr(conn, "_callback_problems", None)
35
+ if callback_problems is not None:
36
+ callback_problems.append(error)
37
+
38
+
39
+ def _run_psk_server_callback(callback, conn, identity, psk, max_psk_len):
40
+ client_identity = SSL._ffi.string(identity)
41
+
42
+ # An empty PSK signals a failed handshake.
43
+ psk_str = callback(conn, client_identity)
44
+ psk_str = _text_to_bytes_and_warn("psk", psk_str)
45
+
46
+ if not isinstance(psk_str, bytes):
47
+ raise TypeError("Client PSK must be a bytestring.")
48
+
49
+ psk_str_len = len(psk_str)
50
+ if psk_str_len > max_psk_len:
51
+ raise ValueError("PSK is longer than the maximum allowed length.")
52
+
53
+ SSL._ffi.memmove(psk, psk_str, psk_str_len)
54
+ return psk_str_len
55
+
56
+
57
+ def _run_psk_client_callback(
58
+ callback,
59
+ conn,
60
+ hint,
61
+ identity,
62
+ max_identity_len,
63
+ psk,
64
+ max_psk_len,
65
+ ):
66
+ if hint == SSL._ffi.NULL:
67
+ identity_hint = b""
68
+ else:
69
+ identity_hint = SSL._ffi.string(hint)
70
+
71
+ psk_identity, psk_str = callback(conn, identity_hint)
72
+
73
+ psk_identity = _text_to_bytes_and_warn("psk_identity", psk_identity)
74
+ if not isinstance(psk_identity, bytes):
75
+ raise TypeError("Client PSK identity must be a bytestring.")
76
+
77
+ psk_identity_len = len(psk_identity)
78
+ if psk_identity_len > max_identity_len:
79
+ raise ValueError("PSK identity is longer than the maximum allowed length.")
80
+
81
+ psk_str = _text_to_bytes_and_warn("psk", psk_str)
82
+ if not isinstance(psk_str, bytes):
83
+ raise TypeError("Client PSK must be a bytestring.")
84
+
85
+ psk_str_len = len(psk_str)
86
+ if psk_str_len > max_psk_len:
87
+ raise ValueError("PSK is longer than the maximum allowed length.")
88
+
89
+ SSL._ffi.memmove(identity, psk_identity, psk_identity_len)
90
+ SSL._ffi.memmove(psk, psk_str, psk_str_len)
91
+ return psk_str_len
92
+
93
+
94
+ class _PskServerHelper:
95
+ """
96
+ Wrap a callback such that it can be used as a PSK server callback.
97
+ """
98
+
99
+ def __init__(self, callback):
100
+ @wraps(callback)
101
+ def wrapper(ssl, identity, psk, max_psk_len):
102
+ conn = SSL.Connection._reverse_mapping[ssl]
103
+ try:
104
+ return _run_psk_server_callback(
105
+ callback,
106
+ conn,
107
+ identity,
108
+ psk,
109
+ max_psk_len,
110
+ )
111
+ except Exception as e:
112
+ _record_callback_exception(conn, e)
113
+ return 0
114
+
115
+ self.callback = SSL._ffi.callback(
116
+ "unsigned int(*)(SSL *, const char *, unsigned char *, unsigned int)",
117
+ wrapper,
118
+ )
119
+
120
+
121
+ class _PskClientHelper:
122
+ """
123
+ Wrap a callback such that it can be used as a PSK client callback.
124
+ """
125
+
126
+ def __init__(self, callback):
127
+ @wraps(callback)
128
+ def wrapper(ssl, hint, identity, max_identity_len, psk, max_psk_len):
129
+ conn = SSL.Connection._reverse_mapping[ssl]
130
+ try:
131
+ return _run_psk_client_callback(
132
+ callback,
133
+ conn,
134
+ hint,
135
+ identity,
136
+ max_identity_len,
137
+ psk,
138
+ max_psk_len,
139
+ )
140
+ except Exception as e:
141
+ _record_callback_exception(conn, e)
142
+ return 0
143
+
144
+ self.callback = SSL._ffi.callback(
145
+ "unsigned int (*)(SSL *, const char *, char *, unsigned int, unsigned char *, unsigned int)",
146
+ wrapper,
147
+ )
148
+
149
+
150
+ def use_psk_identity_hint(self, hint):
151
+ """
152
+ Set the server PSK identity hint.
153
+
154
+ :param bytes hint: server PSK identity hint
155
+
156
+ """
157
+ hint = _text_to_bytes_and_warn("hint", hint)
158
+
159
+ if not isinstance(hint, bytes):
160
+ raise TypeError("hint must be a byte string.")
161
+
162
+ _openssl_assert(SSL._lib.SSL_CTX_use_psk_identity_hint(self._context, hint) == 1)
163
+
164
+
165
+ def set_psk_server_callback(self, callback):
166
+ """
167
+ Set a callback to populate the server PSK.
168
+
169
+ :param callable callback:
170
+ The callback function. It will be invoked with two
171
+ arguments: the Connection, and a byte string containing the PSK
172
+ identity from the client. The callback must return a byte string
173
+ containing the server PSK that corresponds to the client PSK
174
+ identity. If the callback raises an exception, a handshake error occurs.
175
+
176
+ """
177
+ if not callable(callback):
178
+ raise TypeError("callback must be callable")
179
+
180
+ self._psk_server_helper = _PskServerHelper(callback)
181
+ self._psk_server_callback = self._psk_server_helper.callback
182
+ SSL._lib.SSL_CTX_set_psk_server_callback(
183
+ self._context,
184
+ self._psk_server_callback,
185
+ )
186
+
187
+
188
+ def set_psk_client_callback(self, callback):
189
+ """
190
+ Set a callback to populate the client PSK identity and PSK.
191
+
192
+ :param callback:
193
+ The callback function. It will be invoked with two
194
+ arguments: the Connection, and a byte string containing the PSK
195
+ identity hint from the server. The callback must return a two
196
+ element tuple: a byte string containing the client PSK identity,
197
+ and a byte string containing the client PSK. These byte strings
198
+ will be sent to the server during a handshake.
199
+
200
+ """
201
+ if not callable(callback):
202
+ raise TypeError("callback must be callable")
203
+
204
+ self._psk_client_helper = _PskClientHelper(callback)
205
+ self._psk_client_callback = self._psk_client_helper.callback
206
+ SSL._lib.SSL_CTX_set_psk_client_callback(
207
+ self._context,
208
+ self._psk_client_callback,
209
+ )
210
+
211
+
212
+ def patch_context():
213
+ """
214
+ Add PSK related methods to the `OpenSSL.SSL.Context` class.
215
+ """
216
+ try:
217
+ SSL.Context.use_psk_identity_hint
218
+ except AttributeError:
219
+ SSL.Context.use_psk_identity_hint = use_psk_identity_hint
220
+ SSL.Context.set_psk_server_callback = set_psk_server_callback
221
+ SSL.Context.set_psk_client_callback = set_psk_client_callback
@@ -0,0 +1,110 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyopenssl-psk
3
+ Version: 1.1.0
4
+ Summary: Add PSK support to pyOpenSSL
5
+ Keywords: pyopenssl,openssl,psk
6
+ Author: gesslerpd
7
+ Author-email: gesslerpd <gesslerpd@users.noreply.github.com>
8
+ License-Expression: Apache-2.0
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.9
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Programming Language :: Python :: 3.15
19
+ Requires-Dist: pyopenssl
20
+ Requires-Dist: cryptography>2.2.2
21
+ Requires-Python: >=3.9
22
+ Project-URL: Homepage, https://github.com/gesslerpd/pyopenssl-psk
23
+ Project-URL: Repository, https://github.com/gesslerpd/pyopenssl-psk
24
+ Project-URL: Issues, https://github.com/gesslerpd/pyopenssl-psk/issues
25
+ Description-Content-Type: text/markdown
26
+
27
+ # pyopenssl-psk
28
+
29
+ Add PSK support to pyOpenSSL.
30
+
31
+ **Note:** PSK support is available in Python 3.13+. For more information, refer to the [official Python documentation](https://docs.python.org/3/library/ssl.html).
32
+
33
+ ## Installation
34
+
35
+ ```
36
+ $ pip install pyopenssl-psk
37
+ ```
38
+
39
+ ## API
40
+
41
+ ### Patch Method
42
+
43
+ - `patch_context()`
44
+
45
+ Add PSK related methods to the `OpenSSL.SSL.Context` class.
46
+
47
+ ```python
48
+ from openssl_psk import patch_context
49
+
50
+ patch_context()
51
+ ```
52
+
53
+ ### Server Methods
54
+
55
+ - `Context.use_psk_identity_hint(hint: bytes) -> None` ([docs](https://www.openssl.org/docs/manmaster/man3/SSL_CTX_use_psk_identity_hint.html)) ([stdlib ssl](https://docs.python.org/3/library/ssl.html#ssl.SSLContext.use_psk_identity_hint))
56
+
57
+ Set the server PSK identity hint.
58
+
59
+ - `Context.set_psk_server_callback(callback: server_callback) -> None` ([docs](https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_psk_server_callback.html)) ([stdlib ssl](https://docs.python.org/3/library/ssl.html#ssl.SSLContext.set_psk_server_callback))
60
+
61
+ Set a callback to populate the server PSK.
62
+
63
+ `server_callback(connection: Connection, client_identity: bytes) -> psk: bytes`
64
+
65
+ User provided callback function to populate the connection PSK.
66
+
67
+ ```python
68
+ from OpenSSL.SSL import Context, Connection, TLSv1_2_METHOD
69
+
70
+ PSK_MAP = {
71
+ b"pre_shared_key_identity": b"pre_shared_key",
72
+ }
73
+
74
+
75
+ def server_callback(conn, client_identity):
76
+ return PSK_MAP[client_identity]
77
+
78
+
79
+ ctx = Context(TLSv1_2_METHOD)
80
+ ctx.set_cipher_list(b"PSK")
81
+ ctx.use_psk_identity_hint(b"pre_shared_key_identity_hint")
82
+ ctx.set_psk_server_callback(server_callback)
83
+ server = Connection(ctx)
84
+ ```
85
+
86
+ ### Client Methods
87
+
88
+ - `Context.set_psk_client_callback(callback: client_callback) -> None` ([docs](https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_psk_client_callback.html)) ([stdlib ssl](https://docs.python.org/3/library/ssl.html#ssl.SSLContext.set_psk_client_callback))
89
+
90
+ Set a callback to populate the client PSK identity and PSK.
91
+
92
+ `client_callback(connection: Connection, identity_hint: bytes) -> tuple(psk_identity: bytes, psk: bytes)`
93
+
94
+ User provided callback function to populate the connection PSK identity and PSK.
95
+
96
+ ```python
97
+ from OpenSSL.SSL import Context, Connection, TLSv1_2_METHOD
98
+
99
+
100
+ def client_callback(conn, identity_hint):
101
+ return (b"pre_shared_key_identity", b"pre_shared_key")
102
+
103
+
104
+ ctx = Context(TLSv1_2_METHOD)
105
+ ctx.set_cipher_list(b"PSK")
106
+ ctx.set_psk_client_callback(client_callback)
107
+ client = Connection(ctx)
108
+ ```
109
+
110
+ See `OpenSSL.SSL` [documentation](https://www.pyopenssl.org/en/stable/api/ssl.html) for more information.
@@ -0,0 +1,5 @@
1
+ openssl_psk/__init__.py,sha256=vO5t7Z34XY2bOwlyLnM0x0NwTZM9Bru5ore5IafnL1Y,33
2
+ openssl_psk/_psk.py,sha256=jlpVbc3sR6Xh54aCaERbbySnu1jh1gqL9oHus9vMIzU,7071
3
+ pyopenssl_psk-1.1.0.dist-info/WHEEL,sha256=kiPuyMTIXtn3KwIlb6zIkrxfbMkdQGyzN-kjAsvva48,81
4
+ pyopenssl_psk-1.1.0.dist-info/METADATA,sha256=NcUV92S5ZtYsyVjua3HZZAUtNgfXBfukIZCTY8t9xs4,3722
5
+ pyopenssl_psk-1.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.12
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any