python3-olm 3.2.18__cp314-cp314-win_amd64.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.
_libolm.pyd ADDED
Binary file
olm/__init__.py ADDED
@@ -0,0 +1,48 @@
1
+ # -*- coding: utf-8 -*-
2
+ # libolm python bindings
3
+ # Copyright © 2015-2017 OpenMarket Ltd
4
+ # Copyright © 2018 Damir Jelić <poljar@termina.org.uk>
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ """
18
+ Olm Python bindings
19
+ ~~~~~~~~~~~~~~~~~~~~~
20
+ | This package implements python bindings for the libolm C library.
21
+ | © Copyright 2015-2017 by OpenMarket Ltd
22
+ | © Copyright 2018 by Damir Jelić
23
+ """
24
+ from .utility import ed25519_verify, OlmVerifyError, OlmHashError, sha256
25
+ from .account import Account, OlmAccountError
26
+ from .session import (
27
+ Session,
28
+ InboundSession,
29
+ OutboundSession,
30
+ OlmSessionError,
31
+ OlmMessage,
32
+ OlmPreKeyMessage
33
+ )
34
+ from .group_session import (
35
+ InboundGroupSession,
36
+ OutboundGroupSession,
37
+ OlmGroupSessionError
38
+ )
39
+ from .pk import (
40
+ PkMessage,
41
+ PkEncryption,
42
+ PkDecryption,
43
+ PkSigning,
44
+ PkEncryptionError,
45
+ PkDecryptionError,
46
+ PkSigningError
47
+ )
48
+ from .sas import Sas, OlmSasError
olm/_compat.py ADDED
@@ -0,0 +1,67 @@
1
+ # -*- coding: utf-8 -*-
2
+ # libolm python bindings
3
+ # Copyright © 2015-2017 OpenMarket Ltd
4
+ # Copyright © 2018 Damir Jelić <poljar@termina.org.uk>
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ from builtins import bytes, str
19
+ from typing import AnyStr
20
+
21
+ try:
22
+ import secrets
23
+ URANDOM = secrets.token_bytes # pragma: no cover
24
+ except ImportError: # pragma: no cover
25
+ from os import urandom
26
+ URANDOM = urandom # type: ignore
27
+
28
+
29
+ def to_bytearray(string):
30
+ # type: (AnyStr) -> bytes
31
+ if isinstance(string, bytes):
32
+ return bytearray(string)
33
+ elif isinstance(string, str):
34
+ return bytearray(string, "utf-8")
35
+
36
+ raise TypeError("Invalid type {}".format(type(string)))
37
+
38
+
39
+ def to_bytes(string):
40
+ # type: (AnyStr) -> bytes
41
+ if isinstance(string, bytes):
42
+ return string
43
+ elif isinstance(string, str):
44
+ return bytes(string, "utf-8")
45
+
46
+ raise TypeError("Invalid type {}".format(type(string)))
47
+
48
+
49
+ def to_unicode_str(byte_string, errors="replace"):
50
+ """Turn a byte string into a unicode string.
51
+
52
+ Should be used everywhere where the input byte string might not be trusted
53
+ and may contain invalid unicode values.
54
+
55
+ Args:
56
+ byte_string (bytes): The bytestring that will be converted to a native
57
+ string.
58
+ errors (str, optional): The error handling scheme that should be used
59
+ to handle unicode decode errors. Can be one of "strict" (raise an
60
+ UnicodeDecodeError exception, "ignore" (remove the offending
61
+ characters), "replace" (replace the offending character with
62
+ U+FFFD), "xmlcharrefreplace" as well as any other name registered
63
+ with codecs.register_error that can handle UnicodeEncodeErrors.
64
+
65
+ Returns the decoded native string.
66
+ """
67
+ return byte_string.decode(encoding="utf-8", errors=errors)
olm/_finalize.py ADDED
@@ -0,0 +1,64 @@
1
+ # The MIT License (MIT)
2
+ # Copyright (c) 2010 Benjamin Peterson <benjamin@python.org>
3
+
4
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ # of this software and associated documentation files (the "Software"), to deal
6
+ # in the Software without restriction, including without limitation the rights
7
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ # copies of the Software, and to permit persons to whom the Software is
9
+ # furnished to do so, subject to the following conditions:
10
+
11
+ # The above copyright notice and this permission notice shall be included in
12
+ # all copies or substantial portions of the Software.
13
+
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17
+ # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
+ # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
+ # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
20
+ # OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ """Finalization with weakrefs
23
+
24
+ This is designed for avoiding __del__.
25
+ """
26
+
27
+ import sys
28
+ import traceback
29
+ import weakref
30
+
31
+ __author__ = "Benjamin Peterson <benjamin@python.org>"
32
+
33
+
34
+ class OwnerRef(weakref.ref):
35
+ """A simple weakref.ref subclass, so attributes can be added."""
36
+ pass
37
+
38
+
39
+ def _run_finalizer(ref):
40
+ """Internal weakref callback to run finalizers"""
41
+ del _finalize_refs[id(ref)]
42
+ finalizer = ref.finalizer
43
+ item = ref.item
44
+ try:
45
+ finalizer(item)
46
+ except Exception: # pragma: no cover
47
+ print("Exception running {}:".format(finalizer), file=sys.stderr)
48
+ traceback.print_exc()
49
+
50
+
51
+ _finalize_refs = {}
52
+
53
+
54
+ def track_for_finalization(owner, item, finalizer):
55
+ """Register an object for finalization.
56
+
57
+ ``owner`` is the the object which is responsible for ``item``.
58
+ ``finalizer`` will be called with ``item`` as its only argument when
59
+ ``owner`` is destroyed by the garbage collector.
60
+ """
61
+ ref = OwnerRef(owner, _run_finalizer)
62
+ ref.item = item
63
+ ref.finalizer = finalizer
64
+ _finalize_refs[id(ref)] = ref
olm/account.py ADDED
@@ -0,0 +1,321 @@
1
+ # -*- coding: utf-8 -*-
2
+ # libolm python bindings
3
+ # Copyright © 2015-2017 OpenMarket Ltd
4
+ # Copyright © 2018 Damir Jelić <poljar@termina.org.uk>
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ """libolm Account module.
18
+
19
+ This module contains the account part of the Olm library. It contains a single
20
+ Account class which handles the creation of new accounts as well as the storing
21
+ and restoring of them.
22
+
23
+ Examples:
24
+ >>> acc = Account()
25
+ >>> account.identity_keys()
26
+ >>> account.generate_one_time_keys(1)
27
+
28
+ """
29
+
30
+ import json
31
+ # pylint: disable=redefined-builtin,unused-import
32
+ from builtins import bytes, super
33
+ from typing import AnyStr, Dict, Optional, Type
34
+
35
+ # pylint: disable=no-name-in-module
36
+ from _libolm import ffi, lib # type: ignore
37
+
38
+ from ._compat import URANDOM, to_bytearray
39
+ from ._finalize import track_for_finalization
40
+
41
+ # This is imported only for type checking purposes
42
+ if False:
43
+ from .session import Session # pragma: no cover
44
+
45
+
46
+ def _clear_account(account):
47
+ # type: (ffi.cdata) -> None
48
+ lib.olm_clear_account(account)
49
+
50
+
51
+ class OlmAccountError(Exception):
52
+ """libolm Account error exception."""
53
+
54
+
55
+ class Account(object):
56
+ """libolm Account class."""
57
+
58
+ def __new__(cls):
59
+ # type: (Type[Account]) -> Account
60
+ obj = super().__new__(cls)
61
+ obj._buf = ffi.new("char[]", lib.olm_account_size())
62
+ obj._account = lib.olm_account(obj._buf)
63
+ track_for_finalization(obj, obj._account, _clear_account)
64
+ return obj
65
+
66
+ def __init__(self):
67
+ # type: () -> None
68
+ """Create a new Olm account.
69
+
70
+ Creates a new account and its matching identity key pair.
71
+
72
+ Raises OlmAccountError on failure. If there weren't enough random bytes
73
+ for the account creation the error message for the exception will be
74
+ NOT_ENOUGH_RANDOM.
75
+ """
76
+ # This is needed to silence mypy not knowing the type of _account.
77
+ # There has to be a better way for this.
78
+ if False: # pragma: no cover
79
+ self._account = self._account # type: ffi.cdata
80
+
81
+ random_length = lib.olm_create_account_random_length(self._account)
82
+ random = URANDOM(random_length)
83
+
84
+ self._check_error(
85
+ lib.olm_create_account(self._account, ffi.from_buffer(random),
86
+ random_length))
87
+
88
+
89
+ def _check_error(self, ret):
90
+ # type: (int) -> None
91
+ if ret != lib.olm_error():
92
+ return
93
+
94
+ last_error = ffi.string((lib.olm_account_last_error(self._account))).decode()
95
+
96
+ raise OlmAccountError(last_error)
97
+
98
+ def pickle(self, passphrase=""):
99
+ # type: (Optional[str]) -> bytes
100
+ """Store an Olm account.
101
+
102
+ Stores an account as a base64 string. Encrypts the account using the
103
+ supplied passphrase. Returns a byte object containing the base64
104
+ encoded string of the pickled account. Raises OlmAccountError on
105
+ failure.
106
+
107
+ Args:
108
+ passphrase(str, optional): The passphrase to be used to encrypt
109
+ the account.
110
+ """
111
+ byte_key = bytearray(passphrase, "utf-8") if passphrase else b""
112
+
113
+ pickle_length = lib.olm_pickle_account_length(self._account)
114
+ pickle_buffer = ffi.new("char[]", pickle_length)
115
+
116
+ try:
117
+ self._check_error(
118
+ lib.olm_pickle_account(self._account,
119
+ ffi.from_buffer(byte_key),
120
+ len(byte_key),
121
+ pickle_buffer,
122
+ pickle_length))
123
+ finally:
124
+ # zero out copies of the passphrase
125
+ for i in range(0, len(byte_key)):
126
+ byte_key[i] = 0
127
+
128
+ return ffi.unpack(pickle_buffer, pickle_length)
129
+
130
+ @classmethod
131
+ def from_pickle(cls, pickle, passphrase=""):
132
+ # type: (bytes, Optional[str]) -> Account
133
+ """Load a previously stored olm account.
134
+
135
+ Loads an account from a pickled base64-encoded string and returns an
136
+ Account object. Decrypts the account using the supplied passphrase.
137
+ Raises OlmAccountError on failure. If the passphrase doesn't match the
138
+ one used to encrypt the account then the error message for the
139
+ exception will be "BAD_ACCOUNT_KEY". If the base64 couldn't be decoded
140
+ then the error message will be "INVALID_BASE64".
141
+
142
+ Args:
143
+ pickle(bytes): Base64 encoded byte string containing the pickled
144
+ account
145
+ passphrase(str, optional): The passphrase used to encrypt the
146
+ account.
147
+ """
148
+ if not pickle:
149
+ raise ValueError("Pickle can't be empty")
150
+
151
+ byte_key = bytearray(passphrase, "utf-8") if passphrase else b""
152
+ # copy because unpickle will destroy the buffer
153
+ pickle_buffer = ffi.new("char[]", pickle)
154
+
155
+ obj = cls.__new__(cls)
156
+
157
+ try:
158
+ ret = lib.olm_unpickle_account(obj._account,
159
+ ffi.from_buffer(byte_key),
160
+ len(byte_key),
161
+ pickle_buffer,
162
+ len(pickle))
163
+ obj._check_error(ret)
164
+ finally:
165
+ for i in range(0, len(byte_key)):
166
+ byte_key[i] = 0
167
+
168
+ return obj
169
+
170
+ @property
171
+ def identity_keys(self):
172
+ # type: () -> Dict[str, str]
173
+ """dict: Public part of the identity keys of the account."""
174
+ out_length = lib.olm_account_identity_keys_length(self._account)
175
+ out_buffer = ffi.new("char[]", out_length)
176
+
177
+ self._check_error(
178
+ lib.olm_account_identity_keys(self._account, out_buffer,
179
+ out_length))
180
+ return json.loads(ffi.unpack(out_buffer, out_length).decode("utf-8"))
181
+
182
+ def sign(self, message):
183
+ # type: (AnyStr) -> str
184
+ """Signs a message with this account.
185
+
186
+ Signs a message with the private ed25519 identity key of this account.
187
+ Returns the signature.
188
+ Raises OlmAccountError on failure.
189
+
190
+ Args:
191
+ message(str): The message to sign.
192
+ """
193
+ bytes_message = to_bytearray(message)
194
+ out_length = lib.olm_account_signature_length(self._account)
195
+ out_buffer = ffi.new("char[]", out_length)
196
+
197
+ try:
198
+ self._check_error(
199
+ lib.olm_account_sign(self._account,
200
+ ffi.from_buffer(bytes_message),
201
+ len(bytes_message), out_buffer,
202
+ out_length))
203
+ finally:
204
+ # clear out copies of the message, which may be plaintext
205
+ if bytes_message is not message:
206
+ for i in range(0, len(bytes_message)):
207
+ bytes_message[i] = 0
208
+
209
+ return ffi.unpack(out_buffer, out_length).decode()
210
+
211
+ @property
212
+ def max_one_time_keys(self):
213
+ # type: () -> int
214
+ """int: The maximum number of one-time keys the account can store."""
215
+ return lib.olm_account_max_number_of_one_time_keys(self._account)
216
+
217
+ def mark_keys_as_published(self):
218
+ # type: () -> None
219
+ """Mark the current set of one-time keys as being published."""
220
+ lib.olm_account_mark_keys_as_published(self._account)
221
+
222
+ def generate_one_time_keys(self, count):
223
+ # type: (int) -> None
224
+ """Generate a number of new one-time keys.
225
+
226
+ If the total number of keys stored by this account exceeds
227
+ max_one_time_keys() then the old keys are discarded.
228
+ Raises OlmAccountError on error.
229
+
230
+ Args:
231
+ count(int): The number of keys to generate.
232
+ """
233
+ random_length = lib.olm_account_generate_one_time_keys_random_length(
234
+ self._account, count)
235
+ random = URANDOM(random_length)
236
+
237
+ self._check_error(
238
+ lib.olm_account_generate_one_time_keys(
239
+ self._account, count, ffi.from_buffer(random), random_length))
240
+
241
+ @property
242
+ def one_time_keys(self):
243
+ # type: () -> Dict[str, Dict[str, str]]
244
+ """dict: The public part of the one-time keys for this account."""
245
+ out_length = lib.olm_account_one_time_keys_length(self._account)
246
+ out_buffer = ffi.new("char[]", out_length)
247
+
248
+ self._check_error(
249
+ lib.olm_account_one_time_keys(self._account, out_buffer,
250
+ out_length))
251
+
252
+ return json.loads(ffi.unpack(out_buffer, out_length).decode("utf-8"))
253
+
254
+ def remove_one_time_keys(self, session):
255
+ # type: (Session) -> None
256
+ """Remove used one-time keys.
257
+
258
+ Removes the one-time keys that the session used from the account.
259
+ Raises OlmAccountError on failure. If the account doesn't have any
260
+ matching one-time keys then the error message of the exception will be
261
+ "BAD_MESSAGE_KEY_ID".
262
+
263
+ Args:
264
+ session(Session): An Olm Session object that was created with this
265
+ account.
266
+ """
267
+ self._check_error(lib.olm_remove_one_time_keys(self._account,
268
+ session._session))
269
+
270
+ def generate_fallback_key(self):
271
+ # type: () -> None
272
+ """Generate a new fallback key
273
+
274
+ This will overwrite the existing fallback key, make sure that you upload
275
+ the fallback key before rotating again. Internally there are two slots
276
+ for the private part of the fallback key. Rotating without uploading
277
+ means that we'll remove a fallback key that may be still used on the
278
+ server side but has been removed on our side.
279
+
280
+ When we receive pre-key messages that use such a removed fallback key we
281
+ won't be able to create a new Olm session.
282
+ """
283
+ random_length = lib.olm_account_generate_fallback_key_random_length(
284
+ self._account
285
+ )
286
+ random = URANDOM(random_length)
287
+
288
+ self._check_error(
289
+ lib.olm_account_generate_fallback_key(
290
+ self._account, ffi.from_buffer(random), random_length
291
+ )
292
+ )
293
+
294
+ def forget_old_fallback_key(self):
295
+ """Forget about the old fallback key.
296
+
297
+ This should be called once you are reasonably certain that you will not
298
+ receive any more messages that use the old fallback key (e.g. 5 minutes
299
+ after the new fallback key has been published).
300
+ """
301
+ lib.olm_account_forget_old_fallback_key(self._account)
302
+
303
+ @property
304
+ def fallback_key(self):
305
+ """The public part of the current fallback for this account.
306
+
307
+ The fallback key can be uploaded alongside of the one-time keys. It can
308
+ be used instead of a one-time key to establish a new Olm Session. The
309
+ fallback key comes into play if all one-time keys have been used up due
310
+ to the client being offline and not replenishing the pool of one-time
311
+ keys.
312
+ """
313
+ out_length = lib.olm_account_unpublished_fallback_key_length(self._account)
314
+ out_buffer = ffi.new("char[]", out_length)
315
+
316
+ ret = lib.olm_account_unpublished_fallback_key(self._account, out_buffer, out_length)
317
+ self._check_error(ret)
318
+
319
+ fallback_key = ffi.unpack(out_buffer, out_length)
320
+
321
+ return json.loads(fallback_key)