pax_global_header00006660000000000000000000000064146432465220014522gustar00rootroot0000000000000052 comment=757f91266d2cd1daa5eca3c1a062398670b5f368 python-twomemo-1.0.4/000077500000000000000000000000001464324652200145325ustar00rootroot00000000000000python-twomemo-1.0.4/.flake8000066400000000000000000000002121464324652200157000ustar00rootroot00000000000000[flake8] max-line-length = 110 doctests = True ignore = E201,E202,W503 exclude = *_pb2.py per-file-ignores = twomemo/project.py:E203 python-twomemo-1.0.4/.github/000077500000000000000000000000001464324652200160725ustar00rootroot00000000000000python-twomemo-1.0.4/.github/workflows/000077500000000000000000000000001464324652200201275ustar00rootroot00000000000000python-twomemo-1.0.4/.github/workflows/test-and-publish.yml000066400000000000000000000033741464324652200240440ustar00rootroot00000000000000name: Test & Publish on: [push, pull_request] permissions: contents: read jobs: test: runs-on: ubuntu-latest strategy: fail-fast: false matrix: python-version: ["3.8", "3.9", "3.10", "3.11", "3.12", "pypy-3.9"] steps: - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - name: Install/update package management dependencies run: python -m pip install --upgrade pip setuptools wheel - name: Build and install python-twomemo run: pip install .[xml] - name: Install test dependencies run: pip install --upgrade mypy pylint flake8 mypy-protobuf types-protobuf - name: Type-check using mypy run: mypy --strict twomemo/ setup.py - name: Lint using pylint run: pylint twomemo/ setup.py - name: Format-check using Flake8 run: flake8 twomemo/ setup.py build: name: Build source distribution and wheel runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Build source distribution and wheel run: python3 setup.py sdist bdist_wheel - uses: actions/upload-artifact@v4 with: name: sdist path: | dist/*.tar.gz dist/*.whl publish: needs: [test, build] runs-on: ubuntu-latest if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') steps: - uses: actions/download-artifact@v4 with: path: dist merge-multiple: true - uses: pypa/gh-action-pypi-publish@v1.9.0 with: user: __token__ password: ${{ secrets.pypi_token }} python-twomemo-1.0.4/.gitignore000066400000000000000000000001411464324652200165160ustar00rootroot00000000000000dist/ Twomemo.egg-info/ __pycache__/ .pytest_cache/ .mypy_cache/ .coverage build/ docs/_build/ python-twomemo-1.0.4/.readthedocs.yaml000066400000000000000000000003401464324652200177560ustar00rootroot00000000000000version: 2 build: os: ubuntu-lts-latest tools: python: "3" sphinx: configuration: docs/conf.py fail_on_warning: true python: install: - requirements: docs/requirements.txt - method: pip path: .[xml] python-twomemo-1.0.4/CHANGELOG.md000066400000000000000000000030371464324652200163460ustar00rootroot00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ## [1.0.4] - 9th of July 2024 ### Changed - 2024 maintenance (bumped Python versions, adjusted for updates to mypy, pylint and GitHub actions) ## [1.0.3] - 8th of November 2022 ### Changed - Exclude tests from the packages ## [1.0.2] - 4th of November 2022 ### Changed - Increased the minimum version of protobuf to 3.20.3 after reports that earlier versions cause issues - Disabled protobuf's deterministic serialization in an attempt to achieve PyPy3 compatibility ## [1.0.1] - 3rd of November 2022 ### Added - Python 3.11 to the list of supported versions ### Changed - Replaced usages of the walrus operator to correctly support Python 3.7 and 3.8 as advertized - Fixed a bug in the way the authentication tag was calculated during decryption of the AEAD implementation ## [1.0.0] - 1st of November 2022 ### Added - Initial release. [Unreleased]: https://github.com/Syndace/python-twomemo/compare/v1.0.4...HEAD [1.0.4]: https://github.com/Syndace/python-twomemo/compare/v1.0.3...v1.0.4 [1.0.3]: https://github.com/Syndace/python-twomemo/compare/v1.0.2...v1.0.3 [1.0.2]: https://github.com/Syndace/python-twomemo/compare/v1.0.1...v1.0.2 [1.0.1]: https://github.com/Syndace/python-twomemo/compare/v1.0.0...v1.0.1 [1.0.0]: https://github.com/Syndace/python-twomemo/releases/tag/v1.0.0 python-twomemo-1.0.4/LICENSE000066400000000000000000000020711464324652200155370ustar00rootroot00000000000000The MIT License Copyright (c) 2024 Tim Henkes (Syndace) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. python-twomemo-1.0.4/MANIFEST.in000066400000000000000000000000311464324652200162620ustar00rootroot00000000000000include twomemo/py.typed python-twomemo-1.0.4/README.md000066400000000000000000000040611464324652200160120ustar00rootroot00000000000000[![PyPI](https://img.shields.io/pypi/v/Twomemo.svg)](https://pypi.org/project/Twomemo/) [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/Twomemo.svg)](https://pypi.org/project/Twomemo/) [![Build Status](https://github.com/Syndace/python-twomemo/actions/workflows/test-and-publish.yml/badge.svg)](https://github.com/Syndace/python-twomemo/actions/workflows/test-and-publish.yml) [![Documentation Status](https://readthedocs.org/projects/python-twomemo/badge/?version=latest)](https://python-twomemo.readthedocs.io/) # python-twomemo # Backend implementation for [python-omemo](https://github.com/Syndace/python-omemo), equipping python-omemo with support for OMEMO under the namespace `urn:xmpp:omemo:2` (casually/jokingly referred to as "twomemo"). ## Installation ## Install the latest release using pip (`pip install twomemo`) or manually from source by running `pip install .` in the cloned repository. ## Protobuf ## Install `protoc`. Then, in the root directory of this repository, run: ```sh $ pip install protobuf mypy mypy-protobuf types-protobuf $ protoc --python_out=twomemo/ --mypy_out=twomemo/ twomemo.proto ``` This will generate `twomemo/twomemo_pb2.py` and `twomemo/twomemo_pb2.pyi`. ## Type Checks and Linting ## python-twomemo uses [mypy](http://mypy-lang.org/) for static type checks and both [pylint](https://pylint.pycqa.org/en/latest/) and [Flake8](https://flake8.pycqa.org/en/latest/) for linting. All checks can be run locally with the following commands: ```sh $ pip install --upgrade mypy pylint flake8 mypy-protobuf types-protobuf $ mypy --strict twomemo/ setup.py $ pylint twomemo/ setup.py $ flake8 twomemo/ setup.py ``` ## Getting Started ## Refer to the documentation on [readthedocs.io](https://python-twomemo.readthedocs.io/), or build/view it locally in the `docs/` directory. To build the docs locally, install the requirements listed in `docs/requirements.txt`, e.g. using `pip install -r docs/requirements.txt`, and then run `make html` from within the `docs/` directory. The documentation can then be found in `docs/_build/html/`. python-twomemo-1.0.4/docs/000077500000000000000000000000001464324652200154625ustar00rootroot00000000000000python-twomemo-1.0.4/docs/Makefile000066400000000000000000000011351464324652200171220ustar00rootroot00000000000000# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build SPHINXPROJ = Twomemo SOURCEDIR = . BUILDDIR = _build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) python-twomemo-1.0.4/docs/_static/000077500000000000000000000000001464324652200171105ustar00rootroot00000000000000python-twomemo-1.0.4/docs/_static/.gitkeep000066400000000000000000000000001464324652200205270ustar00rootroot00000000000000python-twomemo-1.0.4/docs/conf.py000066400000000000000000000063671464324652200167750ustar00rootroot00000000000000# Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a full list see # the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, add these # directories to sys.path here. If the directory is relative to the documentation root, # use os.path.abspath to make it absolute, like shown here. import os import sys this_file_path = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(this_file_path, "..", "twomemo")) from version import __version__ as __version from project import project as __project # -- Project information ----------------------------------------------------------------- project = __project["name"] author = __project["author"] copyright = f"{__project['year']}, {__project['author']}" # The short X.Y version version = __version["short"] # The full version, including alpha/beta/rc tags release = __version["full"] # -- General configuration --------------------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be extensions coming # with Sphinx (named "sphinx.ext.*") or your custom ones. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.viewcode", "sphinx.ext.napoleon", "sphinx_autodoc_typehints" ] # Add any paths that contain templates here, relative to this directory. templates_path = [ "_templates" ] # List of patterns, relative to source directory, that match files and directories to # ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = [ "_build", "Thumbs.db", ".DS_Store" ] # -- Options for HTML output ------------------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for a list of # builtin themes. html_theme = "sphinx_rtd_theme" # Add any paths that contain custom static files (such as style sheets) here, relative to # this directory. They are copied after the builtin static files, so a file named # "default.css" will overwrite the builtin "default.css". html_static_path = [ "_static" ] # -- Autodoc Configuration --------------------------------------------------------------- # The following two options seem to be ignored... autodoc_typehints = "description" autodoc_type_aliases = { type_alias: f"{type_alias}" for type_alias in { "JSONType", "JSONObject" } } def autodoc_skip_member_handler(app, what, name, obj, skip, options): # Skip private members, i.e. those that start with double underscores but do not end in underscores if name.startswith("__") and not name.endswith("_"): return True # Could be achieved using exclude-members, but this is more comfy if name in { "__abstractmethods__", "__module__", "_abc_impl" }: return True # Skip __init__s without documentation. Those are just used for type hints. if name == "__init__" and obj.__doc__ is None: return True return None def setup(app): app.connect("autodoc-skip-member", autodoc_skip_member_handler) python-twomemo-1.0.4/docs/getting_started.rst000066400000000000000000000011541464324652200214040ustar00rootroot00000000000000Getting Started =============== No further preparation is required to get started with this backend. Create an instance of :class:`~twomemo.twomemo.Twomemo` and pass it to `python-omemo `__ to equip it with ``urn:xmpp:omemo:2`` capabilities. Users of ElementTree can use the helpers in :ref:`etree` for their XML serialization/parsing, which is available after installing `xmlschema `_, or by using ``pip install twomemo[xml]``. Users of a different XML framework can use the module as a reference to write their own serialization/parsing. python-twomemo-1.0.4/docs/index.rst000066400000000000000000000007521464324652200173270ustar00rootroot00000000000000Twomemo - Backend implementation of the ``urn:xmpp:omemo:2`` namespace for python-omemo. ======================================================================================== Backend implementation for `python-omemo `__, equipping python-omemo with support for OMEMO under the namespace ``urn:xmpp:omemo:2`` (casually/jokingly referred to as "twomemo"). .. toctree:: installation getting_started API Documentation python-twomemo-1.0.4/docs/installation.rst000066400000000000000000000002511464324652200207130ustar00rootroot00000000000000Installation ============ Install the latest release using pip (``pip install twomemo``) or manually from source by running ``pip install .`` in the cloned repository. python-twomemo-1.0.4/docs/make.bat000066400000000000000000000014531464324652200170720ustar00rootroot00000000000000@ECHO OFF pushd %~dp0 REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set SOURCEDIR=. set BUILDDIR=_build set SPHINXPROJ=Twomemo if "%1" == "" goto help %SPHINXBUILD% >NUL 2>NUL if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% goto end :help %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% :end popd python-twomemo-1.0.4/docs/requirements.txt000066400000000000000000000000611464324652200207430ustar00rootroot00000000000000sphinx sphinx-rtd-theme sphinx-autodoc-typehints python-twomemo-1.0.4/docs/twomemo/000077500000000000000000000000001464324652200171515ustar00rootroot00000000000000python-twomemo-1.0.4/docs/twomemo/etree.rst000066400000000000000000000003101464324652200210010ustar00rootroot00000000000000.. _etree: Module: etree ============= .. automodule:: twomemo.etree :members: :special-members: :private-members: :undoc-members: :member-order: bysource :show-inheritance: python-twomemo-1.0.4/docs/twomemo/package.rst000066400000000000000000000001501464324652200212720ustar00rootroot00000000000000Package: twomemo ================ .. toctree:: Module: etree Module: twomemo python-twomemo-1.0.4/docs/twomemo/twomemo.rst000066400000000000000000000003021464324652200213650ustar00rootroot00000000000000Module: twomemo =============== .. automodule:: twomemo.twomemo :members: :special-members: :private-members: :undoc-members: :member-order: bysource :show-inheritance: python-twomemo-1.0.4/pylintrc000066400000000000000000000364101464324652200163250ustar00rootroot00000000000000[MASTER] # A comma-separated list of package or module names from where C extensions may # be loaded. Extensions are loading into the active Python interpreter and may # run arbitrary code. extension-pkg-whitelist=schema_pb2 # Add files or directories to the blacklist. They should be base names, not # paths. ignore=CVS # Add files or directories matching the regex patterns to the blacklist. The # regex matches against base names, not paths. ignore-patterns=.+_pb2\.py # Python code to execute, usually for sys.path manipulation such as # pygtk.require(). #init-hook= # Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the # number of processors available to use. jobs=1 # Control the amount of potential inferred values when inferring a single # object. This can help the performance when dealing with large functions or # complex, nested conditions. limit-inference-results=100 # List of plugins (as comma separated values of python module names) to load, # usually to register additional checkers. load-plugins= # Pickle collected data for later comparisons. persistent=yes # Specify a configuration file. #rcfile= # When enabled, pylint would attempt to guess common misconfiguration and emit # user-friendly hints instead of false-positive error messages. suggestion-mode=yes # Allow loading of arbitrary C extensions. Extensions are imported into the # active Python interpreter and may run arbitrary code. unsafe-load-any-extension=no [MESSAGES CONTROL] # Only show warnings with the listed confidence levels. Leave empty to show # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED. confidence= # Disable the message, report, category or checker with the given id(s). You # can either give multiple identifiers separated by comma (,) or put this # option multiple times (only on the command line, not in the configuration # file where it should appear only once). You can also use "--disable=all" to # disable everything first and then reenable specific checks. For example, if # you want to run only the similarities checker, you can use "--disable=all # --enable=similarities". If you want to run only the classes checker, but have # no Warning level messages displayed, use "--disable=all --enable=classes # --disable=W". disable=missing-module-docstring, duplicate-code, fixme, logging-fstring-interpolation # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option # multiple time (only on the command line, not in the configuration file where # it should appear only once). See also the "--disable" option for examples. enable=useless-suppression [REPORTS] # Python expression which should return a score less than or equal to 10. You # have access to the variables 'error', 'warning', 'refactor', and 'convention' # which contain the number of messages in each category, as well as 'statement' # which is the total number of statements analyzed. This score is used by the # global evaluation report (RP0004). evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) # Template used to display messages. This is a python new-style format string # used to format the message information. See doc for all details. #msg-template= # Set the output format. Available formats are text, parseable, colorized, json # and msvs (visual studio). You can also give a reporter class, e.g. # mypackage.mymodule.MyReporterClass. output-format=text # Tells whether to display a full report or only the messages. reports=no # Activate the evaluation score. score=yes [REFACTORING] # Maximum number of nested blocks for function / method body max-nested-blocks=5 # Complete name of functions that never returns. When checking for # inconsistent-return-statements if a never returning function is called then # it will be considered as an explicit return statement and no message will be # printed. never-returning-functions=sys.exit [SPELLING] # Limits count of emitted suggestions for spelling mistakes. max-spelling-suggestions=4 # Spelling dictionary name. Available dictionaries: none. To make it work, # install the python-enchant package. spelling-dict= # List of comma separated words that should not be checked. spelling-ignore-words= # A path to a file that contains the private dictionary; one word per line. spelling-private-dict-file= # Tells whether to store unknown words to the private dictionary (see the # --spelling-private-dict-file option) instead of raising a message. spelling-store-unknown-words=no [VARIABLES] # List of additional names supposed to be defined in builtins. Remember that # you should avoid defining new builtins when possible. additional-builtins= # Tells whether unused global variables should be treated as a violation. allow-global-unused-variables=no # List of strings which can identify a callback function by name. A callback # name must start or end with one of those strings. callbacks=cb_, _cb # A regular expression matching the name of dummy variables (i.e. expected to # not be used). dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ # Argument names that match this expression will be ignored. Default to name # with leading underscore. ignored-argument-names=_.*|^ignored_|^unused_ # Tells whether we should check for unused import in __init__ files. init-import=no # List of qualified module names which can have objects that can redefine # builtins. redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io [LOGGING] # Format style used to check logging format string. `old` means using % # formatting, `new` is for `{}` formatting,and `fstr` is for f-strings. logging-format-style=old # Logging modules to check that the string format arguments are in logging # function parameter format. logging-modules=logging [FORMAT] # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. expected-line-ending-format= # Regexp for a line that is allowed to be longer than the limit. ignore-long-lines=^\s*(# )??$ # Number of spaces of indent required inside a hanging or continued line. indent-after-paren=4 # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 # tab). indent-string=' ' # Maximum number of characters on a single line. max-line-length=110 # Maximum number of lines in a module. max-module-lines=10000 # Allow the body of a class to be on the same line as the declaration if body # contains single statement. single-line-class-stmt=no # Allow the body of an if to be on the same line as the test if there is no # else. single-line-if-stmt=yes [TYPECHECK] # List of decorators that produce context managers, such as # contextlib.contextmanager. Add to this list to register other decorators that # produce valid context managers. contextmanager-decorators=contextlib.contextmanager # List of members which are set dynamically and missed by pylint inference # system, and so shouldn't trigger E1101 when accessed. Python regular # expressions are accepted. generated-members= # Tells whether missing members accessed in mixin class should be ignored. A # mixin class is detected if its name ends with "mixin" (case insensitive). ignore-mixin-members=yes # Tells whether to warn about missing members when the owner of the attribute # is inferred to be None. ignore-none=no # This flag controls whether pylint should warn about no-member and similar # checks whenever an opaque object is returned when inferring. The inference # can return multiple potential results while evaluating a Python object, but # some branches might not be evaluated, which results in partial inference. In # that case, it might be useful to still emit no-member and other checks for # the rest of the inferred objects. ignore-on-opaque-inference=no # List of class names for which member attributes should not be checked (useful # for classes with dynamically set attributes). This supports the use of # qualified names. ignored-classes=optparse.Values,thread._local,_thread._local # List of module names for which member attributes should not be checked # (useful for modules/projects where namespaces are manipulated during runtime # and thus existing member attributes cannot be deduced by static analysis). It # supports qualified module names, as well as Unix pattern matching. ignored-modules= # Show a hint with possible names when a member name was not found. The aspect # of finding the hint is based on edit distance. missing-member-hint=yes # The minimum edit distance a name should have in order to be considered a # similar match for a missing member name. missing-member-hint-distance=1 # The total number of similar names that should be taken in consideration when # showing a hint for a missing member. missing-member-max-choices=1 # List of decorators that change the signature of a decorated function. signature-mutators= [STRING] # This flag controls whether the implicit-str-concat-in-sequence should # generate a warning on implicit string concatenation in sequences defined over # several lines. check-str-concat-over-line-jumps=no [SIMILARITIES] # Ignore comments when computing similarities. ignore-comments=yes # Ignore docstrings when computing similarities. ignore-docstrings=yes # Ignore imports when computing similarities. ignore-imports=no # Minimum lines number of a similarity. min-similarity-lines=4 [BASIC] # Naming style matching correct argument names. argument-naming-style=snake_case # Regular expression matching correct argument names. Overrides argument- # naming-style. #argument-rgx= # Naming style matching correct attribute names. attr-naming-style=snake_case # Regular expression matching correct attribute names. Overrides attr-naming- # style. #attr-rgx= # Bad variable names which should always be refused, separated by a comma. bad-names=foo, bar, baz, toto, tutu, tata # Naming style matching correct class attribute names. class-attribute-naming-style=UPPER_CASE # Regular expression matching correct class attribute names. Overrides class- # attribute-naming-style. #class-attribute-rgx= # Naming style matching correct class names. class-naming-style=PascalCase # Regular expression matching correct class names. Overrides class-naming- # style. #class-rgx= # Naming style matching correct constant names. const-naming-style=any # Regular expression matching correct constant names. Overrides const-naming- # style. #const-rgx= # Minimum line length for functions/classes that require docstrings, shorter # ones are exempt. docstring-min-length=-1 # Naming style matching correct function names. function-naming-style=snake_case # Regular expression matching correct function names. Overrides function- # naming-style. #function-rgx= # Good variable names which should always be accepted, separated by a comma. good-names=i, j, e, # exceptions in except blocks _, iv # Domain-specific two-letter variable names # Include a hint for the correct naming format with invalid-name. include-naming-hint=no # Naming style matching correct inline iteration names. inlinevar-naming-style=any # Regular expression matching correct inline iteration names. Overrides # inlinevar-naming-style. #inlinevar-rgx= # Naming style matching correct method names. method-naming-style=snake_case # Regular expression matching correct method names. Overrides method-naming- # style. #method-rgx= # Naming style matching correct module names. module-naming-style=snake_case # Regular expression matching correct module names. Overrides module-naming- # style. #module-rgx= # Colon-delimited sets of names that determine each other's naming style when # the name regexes allow several styles. name-group= # Regular expression which should only match function or class names that do # not require a docstring. no-docstring-rgx=^_ # List of decorators that produce properties, such as abc.abstractproperty. Add # to this list to register other decorators that produce valid properties. # These decorators are taken in consideration only for invalid-name. property-classes=abc.abstractproperty # Naming style matching correct variable names. variable-naming-style=snake_case # Regular expression matching correct variable names. Overrides variable- # naming-style. #variable-rgx= [MISCELLANEOUS] # List of note tags to take in consideration, separated by a comma. notes=FIXME, XXX, TODO [IMPORTS] # List of modules that can be imported at any level, not just the top level # one. allow-any-import-level= # Allow wildcard imports from modules that define __all__. allow-wildcard-with-all=no # Analyse import fallback blocks. This can be used to support both Python 2 and # 3 compatible code, which means that the block might have code that exists # only in one or another interpreter, leading to false positives when analysed. analyse-fallback-blocks=yes # Deprecated modules which should not be used, separated by a comma. deprecated-modules=optparse,tkinter.tix # Create a graph of external dependencies in the given file (report RP0402 must # not be disabled). ext-import-graph= # Create a graph of every (i.e. internal and external) dependencies in the # given file (report RP0402 must not be disabled). import-graph= # Create a graph of internal dependencies in the given file (report RP0402 must # not be disabled). int-import-graph= # Force import order to recognize a module as part of the standard # compatibility libraries. known-standard-library= # Force import order to recognize a module as part of a third party library. known-third-party=enchant # Couples of modules and preferred modules, separated by a comma. preferred-modules= [CLASSES] # List of method names used to declare (i.e. assign) instance attributes. defining-attr-methods=__init__, __new__, setUp, __post_init__, create # List of member names, which should be excluded from the protected access # warning. exclude-protected=_asdict, _fields, _replace, _source, _make # List of valid names for the first argument in a class method. valid-classmethod-first-arg=cls # List of valid names for the first argument in a metaclass class method. valid-metaclass-classmethod-first-arg=cls [DESIGN] # Maximum number of arguments for function / method. max-args=100 # Maximum number of attributes for a class (see R0902). max-attributes=100 # Maximum number of boolean expressions in an if statement (see R0916). max-bool-expr=10 # Maximum number of branch for function / method body. max-branches=100 # Maximum number of locals for function / method body. max-locals=100 # Maximum number of parents for a class (see R0901). max-parents=10 # Maximum number of public methods for a class (see R0904). max-public-methods=100 # Maximum number of return / yield for function / method body. max-returns=100 # Maximum number of statements in function / method body. max-statements=1000 # Minimum number of public methods for a class (see R0903). min-public-methods=0 [EXCEPTIONS] # Exceptions that will emit a warning when being caught. Defaults to # "BaseException, Exception". overgeneral-exceptions=builtins.BaseException, builtins.Exception python-twomemo-1.0.4/pyproject.toml000066400000000000000000000001211464324652200174400ustar00rootroot00000000000000[build-system] requires = ["setuptools"] build-backend = "setuptools.build_meta" python-twomemo-1.0.4/requirements.txt000066400000000000000000000002031464324652200200110ustar00rootroot00000000000000OMEMO>=1.0.0,<2 DoubleRatchet>=1.0.0,<2 X3DH>=1.0.0,<2 XEdDSA>=1.0.0,<2 protobuf>=3.20.3 typing-extensions>=4.3.0 xmlschema>=2.0.2 python-twomemo-1.0.4/setup.py000066400000000000000000000043251464324652200162500ustar00rootroot00000000000000# pylint: disable=exec-used import os from typing import Dict, Union, List from setuptools import setup, find_packages # type: ignore[import-untyped] source_root = os.path.join(os.path.dirname(os.path.abspath(__file__)), "twomemo") version_scope: Dict[str, Dict[str, str]] = {} with open(os.path.join(source_root, "version.py"), encoding="utf-8") as f: exec(f.read(), version_scope) version = version_scope["__version__"] project_scope: Dict[str, Dict[str, Union[str, List[str]]]] = {} with open(os.path.join(source_root, "project.py"), encoding="utf-8") as f: exec(f.read(), project_scope) project = project_scope["project"] with open("README.md", encoding="utf-8") as f: long_description = f.read() classifiers = [ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy" ] classifiers.extend(project["categories"]) if version["tag"] == "alpha": classifiers.append("Development Status :: 3 - Alpha") if version["tag"] == "beta": classifiers.append("Development Status :: 4 - Beta") if version["tag"] == "stable": classifiers.append("Development Status :: 5 - Production/Stable") del project["categories"] del project["year"] setup( version=version["short"], long_description=long_description, long_description_content_type="text/markdown", license="MIT", packages=find_packages(exclude=["tests"]), install_requires=[ "OMEMO>=1.0.0,<2", "DoubleRatchet>=1.0.0,<2", "X3DH>=1.0.0,<2", "XEdDSA>=1.0.0,<2", "protobuf>=3.20.3", "typing-extensions>=4.3.0" ], extras_require={ "xml": [ "xmlschema>=2.0.2" ] }, python_requires=">=3.8", include_package_data=True, zip_safe=False, classifiers=classifiers, **project ) python-twomemo-1.0.4/twomemo.proto000066400000000000000000000010541464324652200173060ustar00rootroot00000000000000syntax = "proto2"; package twomemo; message OMEMOMessage { required uint32 n = 1; required uint32 pn = 2; required bytes dh_pub = 3; optional bytes ciphertext = 4; } message OMEMOAuthenticatedMessage { required bytes mac = 1; required bytes message = 2; // Byte-encoding of an OMEMOMessage } message OMEMOKeyExchange { required uint32 pk_id = 1; required uint32 spk_id = 2; required bytes ik = 3; required bytes ek = 4; required OMEMOAuthenticatedMessage message = 5; } python-twomemo-1.0.4/twomemo/000077500000000000000000000000001464324652200162215ustar00rootroot00000000000000python-twomemo-1.0.4/twomemo/__init__.py000066400000000000000000000005201464324652200203270ustar00rootroot00000000000000from .version import __version__ from .project import project from .twomemo import Twomemo # Fun: # https://github.com/PyCQA/pylint/issues/6006 # https://github.com/python/mypy/issues/10198 __all__ = [ # pylint: disable=unused-variable # .version "__version__", # .project "project", # .twomemo "Twomemo" ] python-twomemo-1.0.4/twomemo/etree.py000066400000000000000000000264101464324652200177020ustar00rootroot00000000000000import base64 from typing import Dict, Optional, Set, Tuple, cast import xml.etree.ElementTree as ET from omemo import EncryptedKeyMaterial, KeyExchange, Message import x3dh try: import xmlschema except ImportError as e: raise ImportError( "Optional dependency xmlschema not found. Please install xmlschema, or install this package using" " `pip install python-twomemo[xml]`, to use the ElementTree-based XML serialization/parser helpers." ) from e from .twomemo import NAMESPACE, BundleImpl, ContentImpl, EncryptedKeyMaterialImpl, KeyExchangeImpl __all__ = [ # pylint: disable=unused-variable "serialize_device_list", "parse_device_list", "serialize_bundle", "parse_bundle", "serialize_message", "parse_message" ] NS = f"{{{NAMESPACE}}}" DEVICE_LIST_SCHEMA = xmlschema.XMLSchema(""" """) BUNDLE_SCHEMA = xmlschema.XMLSchema(""" """) MESSAGE_SCHEMA = xmlschema.XMLSchema(""" """) def serialize_device_list(device_list: Dict[int, Optional[str]]) -> ET.Element: """ Args: device_list: The device list to serialize. The first entry of each tuple is the device id, and the second entry is the optional label. Returns: The serialized device list as an XML element. """ devices_elt = ET.Element(f"{NS}devices") for device_id, label in device_list.items(): device_elt = ET.SubElement(devices_elt, f"{NS}device") device_elt.set("id", str(device_id)) if label is not None: device_elt.set("label", label) return devices_elt def parse_device_list(element: ET.Element) -> Dict[int, Optional[str]]: """ Args: element: The XML element to parse the device list from. Returns: The extracted device list. The first entry of each tuple is the device id, and the second entry is the optional label. Raises: XMLSchemaValidationError: in case the element does not conform to the XML schema given in the specification. """ DEVICE_LIST_SCHEMA.validate(element) return { int(cast(str, device_elt.get("id"))): device_elt.get("label", None) for device_elt in element.iter(f"{NS}device") } def serialize_bundle(bundle: BundleImpl) -> ET.Element: """ Args: bundle: The bundle to serialize. Returns: The serialized bundle as an XML element. """ bundle_elt = ET.Element(f"{NS}bundle") ET.SubElement( bundle_elt, f"{NS}spk", attrib={ "id": str(bundle.signed_pre_key_id) } ).text = base64.b64encode(bundle.bundle.signed_pre_key).decode("ASCII") ET.SubElement( bundle_elt, f"{NS}spks" ).text = base64.b64encode(bundle.bundle.signed_pre_key_sig).decode("ASCII") ET.SubElement( bundle_elt, f"{NS}ik" ).text = base64.b64encode(bundle.bundle.identity_key).decode("ASCII") prekeys_elt = ET.SubElement(bundle_elt, f"{NS}prekeys") for pre_key in bundle.bundle.pre_keys: ET.SubElement( prekeys_elt, f"{NS}pk", attrib={ "id": str(bundle.pre_key_ids[pre_key]) } ).text = base64.b64encode(pre_key).decode("ASCII") return bundle_elt def parse_bundle(element: ET.Element, bare_jid: str, device_id: int) -> BundleImpl: """ Args: element: The XML element to parse the bundle from. bare_jid: The bare JID this bundle belongs to. device_id: The device id of the specific device this bundle belongs to. Returns: The extracted bundle. Raises: XMLSchemaValidationError: in case the element does not conform to the XML schema given in the specification. """ BUNDLE_SCHEMA.validate(element) spk_elt = cast(ET.Element, element.find(f"{NS}spk")) pk_elts = list(element.iter(f"{NS}pk")) return BundleImpl( bare_jid, device_id, x3dh.Bundle( base64.b64decode(cast(str, cast(ET.Element, element.find(f"{NS}ik")).text)), base64.b64decode(cast(str, spk_elt.text)), base64.b64decode(cast(str, cast(ET.Element, element.find(f"{NS}spks")).text)), frozenset(base64.b64decode(cast(str, pk_elt.text)) for pk_elt in pk_elts) ), int(cast(str, spk_elt.get("id"))), { base64.b64decode(cast(str, pk_elt.text)): int(cast(str, pk_elt.get("id"))) for pk_elt in pk_elts } ) def serialize_message(message: Message) -> ET.Element: """ Args: message: The message to serialize. Returns: The serialized message as an XML element. """ assert isinstance(message.content, ContentImpl) encrypted_elt = ET.Element(f"{NS}encrypted") header_elt = ET.SubElement(encrypted_elt, f"{NS}header", attrib={ "sid": str(message.device_id) }) for bare_jid in frozenset(encrypted_key_material.bare_jid for encrypted_key_material, _ in message.keys): keys_elt = ET.SubElement(header_elt, f"{NS}keys", attrib={ "jid": bare_jid }) keys = frozenset(key for key in message.keys if key[0].bare_jid == bare_jid) for encrypted_key_material, key_exchange in keys: assert isinstance(encrypted_key_material, EncryptedKeyMaterialImpl) key_elt = ET.SubElement( keys_elt, f"{NS}key", attrib={ "rid": str(encrypted_key_material.device_id) } ) authenticated_message = encrypted_key_material.serialize() if key_exchange is None: key_elt.text = base64.b64encode(authenticated_message).decode("ASCII") else: assert isinstance(key_exchange, KeyExchangeImpl) key_elt.set("kex", "true") key_elt.text = base64.b64encode(key_exchange.serialize(authenticated_message)).decode("ASCII") if not message.content.empty: ET.SubElement( encrypted_elt, f"{NS}payload" ).text = base64.b64encode(message.content.ciphertext).decode("ASCII") return encrypted_elt def parse_message(element: ET.Element, bare_jid: str) -> Message: """ Args: element: The XML element to parse the message from. bare_jid: The bare JID of the sender. Returns: The extracted message. Raises: ValueError: in case there is malformed data not caught be the XML schema validation. XMLSchemaValidationError: in case the element does not conform to the XML schema given in the specification. """ MESSAGE_SCHEMA.validate(element) payload_elt = element.find(f"{NS}payload") keys: Set[Tuple[EncryptedKeyMaterial, Optional[KeyExchange]]] = set() for keys_elt in element.iter(f"{NS}keys"): recipient_bare_jid = cast(str, keys_elt.get("jid")) for key_elt in keys_elt.iter(f"{NS}key"): recipient_device_id = int(cast(str, key_elt.get("rid"))) content = base64.b64decode(cast(str, key_elt.text)) key_exchange: Optional[KeyExchangeImpl] = None authenticated_message: bytes if bool(key_elt.get("kex", False)): key_exchange, authenticated_message = KeyExchangeImpl.parse(content) else: authenticated_message = content encrypted_key_material = EncryptedKeyMaterialImpl.parse( authenticated_message, recipient_bare_jid, recipient_device_id ) keys.add((encrypted_key_material, key_exchange)) return Message( NAMESPACE, bare_jid, int(cast(str, cast(ET.Element, element.find(f"{NS}header")).get("sid"))), ( ContentImpl.make_empty() if payload_elt is None else ContentImpl(base64.b64decode(cast(str, payload_elt.text))) ), frozenset(keys) ) python-twomemo-1.0.4/twomemo/project.py000066400000000000000000000007661464324652200202520ustar00rootroot00000000000000__all__ = [ "project" ] # pylint: disable=unused-variable project = { "name" : "Twomemo", "description" : "Backend implementation of the namespace `urn:xmpp:omemo:2` for python-omemo.", "url" : "https://github.com/Syndace/python-twomemo", "year" : "2024", "author" : "Tim Henkes (Syndace)", "author_email" : "me@syndace.dev", "categories" : [ "Topic :: Communications :: Chat", "Topic :: Security :: Cryptography" ] } python-twomemo-1.0.4/twomemo/py.typed000066400000000000000000000000001464324652200177060ustar00rootroot00000000000000python-twomemo-1.0.4/twomemo/twomemo.py000066400000000000000000001447441464324652200203000ustar00rootroot00000000000000# This import from future (theoretically) enables sphinx_autodoc_typehints to handle type aliases better from __future__ import annotations # pylint: disable=unused-variable import base64 import secrets from typing import Dict, Optional, Tuple, cast from typing_extensions import Final import doubleratchet from doubleratchet.recommended import ( aead_aes_hmac, diffie_hellman_ratchet_curve25519, HashFunction, kdf_hkdf, kdf_separate_hmacs ) from doubleratchet.recommended.crypto_provider_impl import CryptoProviderImpl import google.protobuf.message import x3dh import x3dh.identity_key_pair from omemo.backend import Backend, DecryptionFailed, KeyExchangeFailed from omemo.bundle import Bundle from omemo.identity_key_pair import IdentityKeyPair, IdentityKeyPairSeed from omemo.message import Content, EncryptedKeyMaterial, PlainKeyMaterial, KeyExchange from omemo.session import Initiation, Session from omemo.storage import Storage from omemo.types import JSONType # https://github.com/PyCQA/pylint/issues/4987 from .twomemo_pb2 import ( # pylint: disable=no-name-in-module OMEMOAuthenticatedMessage, OMEMOKeyExchange, OMEMOMessage ) __all__ = [ # pylint: disable=unused-variable "Twomemo", "NAMESPACE", "AEADImpl", "BundleImpl", "ContentImpl", "DoubleRatchetImpl", "EncryptedKeyMaterialImpl", "KeyExchangeImpl", "MessageChainKDFImpl", "PlainKeyMaterialImpl", "RootChainKDFImpl", "SessionImpl", "StateImpl" ] NAMESPACE: Final = "urn:xmpp:omemo:2" class RootChainKDFImpl(kdf_hkdf.KDF): """ The root chain KDF implementation used by this version of the specification. """ @staticmethod def _get_hash_function() -> HashFunction: return HashFunction.SHA_256 @staticmethod def _get_info() -> bytes: return "OMEMO Root Chain".encode("ASCII") class MessageChainKDFImpl(kdf_separate_hmacs.KDF): """ The message chain KDF implementation used by this version of the specification. """ @staticmethod def _get_hash_function() -> HashFunction: return HashFunction.SHA_256 class AEADImpl(aead_aes_hmac.AEAD): """ The AEAD used by this backend as part of the Double Ratchet. While this implementation derives from :class:`doubleratchet.recommended.aead_aes_hmac.AEAD`, it actually doesn't use any of its code. This is due to a minor difference in the way the associated data is built. The derivation only has symbolic value. Can only be used with :class:`DoubleRatchetImpl`, due to the reliance on a certain structure of the associated data. """ AUTHENTICATION_TAG_TRUNCATED_LENGTH: Final = 16 @staticmethod def _get_hash_function() -> HashFunction: return HashFunction.SHA_256 @staticmethod def _get_info() -> bytes: return "OMEMO Message Key Material".encode("ASCII") @classmethod async def encrypt(cls, plaintext: bytes, key: bytes, associated_data: bytes) -> bytes: hash_function = cls._get_hash_function() encryption_key, authentication_key, iv = await cls.__derive(key, hash_function, cls._get_info()) # Encrypt the plaintext using AES-256 (the 256 bit are implied by the key size) in CBC mode and the # previously created key and IV, after padding it with PKCS#7 ciphertext = await CryptoProviderImpl.aes_cbc_encrypt(encryption_key, iv, plaintext) # Parse the associated data associated_data, header = cls.__parse_associated_data(associated_data) # Build an OMEMOMessage including the header and the ciphertext omemo_message = OMEMOMessage( n=header.sending_chain_length, pn=header.previous_sending_chain_length, dh_pub=header.ratchet_pub, ciphertext=ciphertext ).SerializeToString() # Calculate the authentication tag over the associated data and the OMEMOMessage, truncate the # authentication tag to AUTHENTICATION_TAG_TRUNCATED_LENGTH bytes auth = (await CryptoProviderImpl.hmac_calculate( authentication_key, hash_function, associated_data + omemo_message ))[:AEADImpl.AUTHENTICATION_TAG_TRUNCATED_LENGTH] # Serialize the authentication tag with the OMEMOMessage in an OMEMOAuthenticatedMessage. return OMEMOAuthenticatedMessage(mac=auth, message=omemo_message).SerializeToString() @classmethod async def decrypt(cls, ciphertext: bytes, key: bytes, associated_data: bytes) -> bytes: hash_function = cls._get_hash_function() decryption_key, authentication_key, iv = await cls.__derive(key, hash_function, cls._get_info()) # Parse the associated data associated_data, header = cls.__parse_associated_data(associated_data) # Parse the ciphertext as an OMEMOAuthenticatedMessage try: omemo_authenticated_message = OMEMOAuthenticatedMessage.FromString(ciphertext) except google.protobuf.message.DecodeError as e: raise doubleratchet.DecryptionFailedException() from e # Calculate and verify the authentication tag new_auth = (await CryptoProviderImpl.hmac_calculate( authentication_key, hash_function, associated_data + omemo_authenticated_message.message ))[:AEADImpl.AUTHENTICATION_TAG_TRUNCATED_LENGTH] if new_auth != omemo_authenticated_message.mac: raise doubleratchet.aead.AuthenticationFailedException("Authentication tags do not match.") # Parse the OMEMOMessage contained in the OMEMOAuthenticatedMessage try: omemo_message = OMEMOMessage.FromString(omemo_authenticated_message.message) except google.protobuf.message.DecodeError as e: raise doubleratchet.DecryptionFailedException() from e # Make sure that the headers match as a little additional consistency check if header != doubleratchet.Header(omemo_message.dh_pub, omemo_message.pn, omemo_message.n): raise doubleratchet.aead.AuthenticationFailedException("Header mismatch.") # Decrypt the plaintext using AES-256 (the 256 bit are implied by the key size) in CBC mode and the # previously created key and IV, and unpad the resulting plaintext with PKCS#7 return await CryptoProviderImpl.aes_cbc_decrypt(decryption_key, iv, omemo_message.ciphertext) @staticmethod async def __derive(key: bytes, hash_function: HashFunction, info: bytes) -> Tuple[bytes, bytes, bytes]: # Prepare the salt, a zero-filled byte sequence with the size of the hash digest salt = b"\x00" * hash_function.hash_size # Derive 80 bytes hkdf_out = await CryptoProviderImpl.hkdf_derive( hash_function=hash_function, length=80, salt=salt, info=info, key_material=key ) # Split these 80 bytes into three parts return hkdf_out[:32], hkdf_out[32:64], hkdf_out[64:] @staticmethod def __parse_associated_data(associated_data: bytes) -> Tuple[bytes, doubleratchet.Header]: """ Parse the associated data as built by :meth:`DoubleRatchetImpl._build_associated_data`. Args: associated_data: The associated data. Returns: The original associated data and the header used to build it. Raises: DecryptionFailedException: if the data is malformed. """ associated_data_length = StateImpl.IDENTITY_KEY_ENCODING_LENGTH * 2 try: omemo_message = OMEMOMessage.FromString(associated_data[associated_data_length:]) except google.protobuf.message.DecodeError as e: raise doubleratchet.DecryptionFailedException() from e associated_data = associated_data[:associated_data_length] return associated_data, doubleratchet.Header(omemo_message.dh_pub, omemo_message.pn, omemo_message.n) class DoubleRatchetImpl(doubleratchet.DoubleRatchet): """ The Double Ratchet implementation used by this version of the specification. """ MESSAGE_CHAIN_CONSTANT: Final = b"\x02\x01" @staticmethod def _build_associated_data(associated_data: bytes, header: doubleratchet.Header) -> bytes: return associated_data + OMEMOMessage( n=header.sending_chain_length, pn=header.previous_sending_chain_length, dh_pub=header.ratchet_pub ).SerializeToString() class StateImpl(x3dh.BaseState): """ The X3DH state implementation used by this version of the specification. """ INFO: Final = "OMEMO X3DH".encode("ASCII") IDENTITY_KEY_ENCODING_LENGTH: Final = 32 @staticmethod def _encode_public_key(key_format: x3dh.IdentityKeyFormat, pub: bytes) -> bytes: return pub class BundleImpl(Bundle): """ :class:`~omemo.bundle.Bundle` implementation as a simple storage type. """ def __init__( self, bare_jid: str, device_id: int, bundle: x3dh.Bundle, signed_pre_key_id: int, pre_key_ids: Dict[bytes, int] ) -> None: """ Args: bare_jid: The bare JID this bundle belongs to. device_id: The device id of the specific device this bundle belongs to. bundle: The bundle to store in this instance. signed_pre_key_id: The id of the signed pre key referenced in the bundle. pre_key_ids: A dictionary that maps each pre key referenced in the bundle to its id. """ self.__bare_jid = bare_jid self.__device_id = device_id self.__bundle = bundle self.__signed_pre_key_id = signed_pre_key_id self.__pre_key_ids = dict(pre_key_ids) @property def namespace(self) -> str: return NAMESPACE @property def bare_jid(self) -> str: return self.__bare_jid @property def device_id(self) -> int: return self.__device_id @property def identity_key(self) -> bytes: return self.__bundle.identity_key def __eq__(self, other: object) -> bool: if isinstance(other, BundleImpl): return ( other.bare_jid == self.bare_jid and other.device_id == self.device_id and other.bundle == self.bundle and other.signed_pre_key_id == self.signed_pre_key_id and other.pre_key_ids == self.pre_key_ids ) return False def __hash__(self) -> int: return hash(( self.bare_jid, self.device_id, self.bundle, self.signed_pre_key_id, frozenset(self.pre_key_ids.items()) )) @property def bundle(self) -> x3dh.Bundle: """ Returns: The bundle held by this instance. """ return self.__bundle @property def signed_pre_key_id(self) -> int: """ Returns: The id of the signed pre key referenced in the bundle. """ return self.__signed_pre_key_id @property def pre_key_ids(self) -> Dict[bytes, int]: """ Returns: A dictionary that maps each pre key referenced in the bundle to its id. """ return dict(self.__pre_key_ids) class ContentImpl(Content): """ :class:`~omemo.message.Content` implementation as a simple storage type. """ def __init__(self, ciphertext: bytes) -> None: """ Args: ciphertext: The ciphertext to store in this instance. Note: For empty OMEMO messages as per the specification, the ciphertext is set to an empty byte string. """ self.__ciphertext = ciphertext @property def empty(self) -> bool: return self.__ciphertext == b"" @staticmethod def make_empty() -> ContentImpl: """ Returns: An "empty" instance, i.e. one that corresponds to an empty OMEMO message as per the specification. The ciphertext stored in empty instances is a byte string of zero length. """ return ContentImpl(b"") @property def ciphertext(self) -> bytes: """ Returns: The ciphertext held by this instance. """ return self.__ciphertext class EncryptedKeyMaterialImpl(EncryptedKeyMaterial): """ :class:`~omemo.message.EncryptedKeyMaterial` implementation as a simple storage type. """ def __init__( self, bare_jid: str, device_id: int, encrypted_message: doubleratchet.EncryptedMessage ) -> None: """ Args: bare_jid: The bare JID of the other party. device_id: The device id of the specific device of the other party. encrypted_message: The encrypted Double Ratchet message to store in this instance. """ self.__bare_jid = bare_jid self.__device_id = device_id self.__encrypted_message = encrypted_message @property def bare_jid(self) -> str: return self.__bare_jid @property def device_id(self) -> int: return self.__device_id @property def encrypted_message(self) -> doubleratchet.EncryptedMessage: """ Returns: The encrypted Double Ratchet message held by this instance. """ return self.__encrypted_message def serialize(self) -> bytes: """ Returns: A serialized OMEMOAuthenticatedMessage message structure representing the content of this instance. """ # The ciphertext field contains the result of :meth:`AEADImpl.encrypt`, which is a serialized # OMEMOAuthenticatedMessage with all fields already correctly set, thus it can be used here as is. return self.__encrypted_message.ciphertext @staticmethod def parse(authenticated_message: bytes, bare_jid: str, device_id: int) -> EncryptedKeyMaterialImpl: """ Args: authenticated_message: A serialized OMEMOAuthenticatedMessage message structure. bare_jid: The bare JID of the other party. device_id: The device id of the specific device of the other party. Returns: An instance of this class, parsed from the OMEMOAuthenticatedMessage. Raises: ValueError: if the data is malformed. """ # Parse the OMEMOAuthenticatedMessage and OMEMOMessage structures to extract the header. try: message = OMEMOMessage.FromString(OMEMOAuthenticatedMessage.FromString( authenticated_message ).message) except google.protobuf.message.DecodeError as e: raise ValueError() from e return EncryptedKeyMaterialImpl( bare_jid, device_id, doubleratchet.EncryptedMessage( doubleratchet.Header(message.dh_pub, message.pn, message.n), authenticated_message ) ) class PlainKeyMaterialImpl(PlainKeyMaterial): """ :class:`~omemo.message.PlainKeyMaterial` implementation as a simple storage type. """ KEY_LENGTH: Final = 32 def __init__(self, key: bytes, auth_tag: bytes) -> None: """ Args: key: The key to store in this instance. auth_tag: The authentication tag to store in this instance. Note: For empty OMEMO messages as per the specification, the key is set to :attr:`KEY_LENGTH` zero-bytes, and the auth tag is set to an empty byte string. """ self.__key = key self.__auth_tag = auth_tag @property def key(self) -> bytes: """ Returns: The key held by this instance. """ return self.__key @property def auth_tag(self) -> bytes: """ Returns: The authentication tag held by this instance. """ return self.__auth_tag @staticmethod def make_empty() -> PlainKeyMaterialImpl: """ Returns: An "empty" instance, i.e. one that corresponds to an empty OMEMO message as per the specification. The key stored in empty instances is a byte string of :attr:`KEY_LENGTH` zero-bytes, and the auth tag is an empty byte string. """ return PlainKeyMaterialImpl(b"\x00" * PlainKeyMaterialImpl.KEY_LENGTH, b"") class KeyExchangeImpl(KeyExchange): """ :class:`~omemo.message.KeyExchange` implementation as a simple storage type. There are two kinds of instances: - Completely filled instances - Partially filled instances received via network Empty fields are filled with filler values such that the data types and lengths still match expectations. """ def __init__(self, header: x3dh.Header, signed_pre_key_id: int, pre_key_id: int) -> None: """ Args: header: The header to store in this instance. signed_pre_key_id: The id of the signed pre key referenced in the header. pre_key_id: The id of the pre key referenced in the header. """ self.__header = header self.__signed_pre_key_id = signed_pre_key_id self.__pre_key_id = pre_key_id @property def identity_key(self) -> bytes: return self.__header.identity_key def builds_same_session(self, other: KeyExchange) -> bool: # The signed pre key id and pre key id are enough for uniqueness; ignoring the actual signed pre key # and pre key bytes here makes it possible to compare network instances with completely filled # instances. return isinstance(other, KeyExchangeImpl) and ( other.header.identity_key == self.header.identity_key and other.header.ephemeral_key == self.header.ephemeral_key and other.signed_pre_key_id == self.signed_pre_key_id and other.pre_key_id == self.pre_key_id ) @property def header(self) -> x3dh.Header: """ Returns: The header held by this instance. """ return self.__header @property def signed_pre_key_id(self) -> int: """ Returns: The id of the signed pre key referenced in the header. """ return self.__signed_pre_key_id @property def pre_key_id(self) -> int: """ Returns: The id of the pre key referenced in the header. """ return self.__pre_key_id def is_network_instance(self) -> bool: """ Returns: Returns whether this is a network instance. A network instance has all fields filled except for the signed pre key and pre key byte data. The missing byte data can be restored by looking it up from storage using the respective ids. """ return self.__header.signed_pre_key == b"" and self.__header.pre_key == b"" def serialize(self, authenticated_message: bytes) -> bytes: """ Args: authenticated_message: The serialized OMEMOAuthenticatedMessage message structure to include with the key exchange information. Returns: A serialized OMEMOKeyExchange message structure representing the content of this instance. Raises: ValueError: if the serialized OMEMOAuthenticatedMessage is malformed. """ try: authenticated_message_parsed = OMEMOAuthenticatedMessage.FromString(authenticated_message) except google.protobuf.message.DecodeError as e: raise ValueError() from e return OMEMOKeyExchange( pk_id=self.__pre_key_id, spk_id=self.__signed_pre_key_id, ik=self.__header.identity_key, ek=self.__header.ephemeral_key, message=authenticated_message_parsed ).SerializeToString() @staticmethod def parse(key_exchange: bytes) -> Tuple[KeyExchangeImpl, bytes]: """ Args: key_exchange: A serialized OMEMOKeyExchange message structure. Returns: An instance of this class, parsed from the OMEMOKeyExchange, and the serialized OMEMOAuthenticatedMessage extracted from the OMEMOKeyExchange. Raises: ValueError: if the data is malformed. Warning: The OMEMOKeyExchange message structure only contains the ids of the signed pre key and the pre key used for the key exchange, not the full public keys. Since the job of this method is just parsing, the X3DH header is initialized without the public keys here, and the code using instances of this class has to handle the public key lookup from the ids. Use :attr:`header_filled` to check whether the header is filled with the public keys. """ try: parsed = OMEMOKeyExchange.FromString(key_exchange) except google.protobuf.message.DecodeError as e: raise ValueError() from e return KeyExchangeImpl( x3dh.Header(parsed.ik, parsed.ek, b"", b""), parsed.spk_id, parsed.pk_id ), parsed.message.SerializeToString() class SessionImpl(Session): """ :class:`~omemo.session.Session` implementation as a simple storage type. """ def __init__( self, bare_jid: str, device_id: int, initiation: Initiation, key_exchange: KeyExchangeImpl, associated_data: bytes, double_ratchet: DoubleRatchetImpl, confirmed: bool = False ): """ Args: bare_jid: The bare JID of the other party. device_id: The device id of the specific device of the other party. initiation: Whether this session was built through active or passive session initiation. key_exchange: The key exchange information to store in this instance. associated_data: The associated data to store in this instance. double_ratchet: The Double Ratchet to store in this instance. confirmed: Whether the session was confirmed, i.e. whether a message was decrypted after actively initiating the session. Leave this at the default value for passively initiated sessions. """ self.__bare_jid = bare_jid self.__device_id = device_id self.__initiation = initiation self.__key_exchange = key_exchange self.__associated_data = associated_data self.__double_ratchet = double_ratchet self.__confirmed = confirmed @property def namespace(self) -> str: return NAMESPACE @property def bare_jid(self) -> str: return self.__bare_jid @property def device_id(self) -> int: return self.__device_id @property def initiation(self) -> Initiation: return self.__initiation @property def confirmed(self) -> bool: return self.__confirmed @property def key_exchange(self) -> KeyExchangeImpl: return self.__key_exchange @property def receiving_chain_length(self) -> Optional[int]: return self.__double_ratchet.receiving_chain_length @property def sending_chain_length(self) -> int: return self.__double_ratchet.sending_chain_length @property def associated_data(self) -> bytes: """ Returns: The associated data held by this instance. """ return self.__associated_data @property def double_ratchet(self) -> DoubleRatchetImpl: """ Returns: The Double Ratchet held by this instance. """ return self.__double_ratchet def confirm(self) -> None: """ Mark this session as confirmed. """ self.__confirmed = True class Twomemo(Backend): """ :class:`~omemo.backend.Backend` implementation providing OMEMO in the `urn:xmpp:omemo:2` namespace. """ def __init__( self, storage: Storage, max_num_per_session_skipped_keys: int = 1000, max_num_per_message_skipped_keys: Optional[int] = None ) -> None: """ Args: storage: The storage to store backend-specific data in. Note that all data keys are prefixed with the backend namespace to avoid name clashes between backends. max_num_per_session_skipped_keys: The maximum number of skipped message keys to keep around per session. Once the maximum is reached, old message keys are deleted to make space for newer ones. Accessible via :attr:`max_num_per_session_skipped_keys`. max_num_per_message_skipped_keys: The maximum number of skipped message keys to accept in a single message. When set to ``None`` (the default), this parameter defaults to the per-session maximum (i.e. the value of the ``max_num_per_session_skipped_keys`` parameter). This parameter may only be 0 if the per-session maximum is 0, otherwise it must be a number between 1 and the per-session maximum. Accessible via :attr:`max_num_per_message_skipped_keys`. """ super().__init__(max_num_per_session_skipped_keys, max_num_per_message_skipped_keys) self.__storage = storage async def __get_state(self) -> StateImpl: """ Returns: The loaded or newly created X3DH state. """ def check_type(value: JSONType) -> x3dh.types.JSONObject: if isinstance(value, dict): return cast(x3dh.types.JSONObject, value) raise TypeError( f"Stored StateImpl under key /{self.namespace}/x3dh corrupt: not a JSON object: {value}" ) state, _ = (await self.__storage.load( f"/{self.namespace}/x3dh" )).fmap(check_type).fmap(lambda serialized: StateImpl.from_json( serialized, x3dh.IdentityKeyFormat.ED_25519, x3dh.HashFunction.SHA_256, StateImpl.INFO )).maybe((None, False)) if state is None: identity_key_pair = await IdentityKeyPair.get(self.__storage) state = StateImpl.create( x3dh.IdentityKeyFormat.ED_25519, x3dh.HashFunction.SHA_256, StateImpl.INFO, ( x3dh.identity_key_pair.IdentityKeyPairSeed(identity_key_pair.seed) if isinstance(identity_key_pair, IdentityKeyPairSeed) else x3dh.identity_key_pair.IdentityKeyPairPriv(identity_key_pair.as_priv().priv) ) ) await self.__storage.store(f"/{self.namespace}/x3dh", state.json) return state @property def namespace(self) -> str: return NAMESPACE async def load_session(self, bare_jid: str, device_id: int) -> Optional[SessionImpl]: def check_type(value: JSONType) -> doubleratchet.types.JSONObject: if isinstance(value, dict): return cast(doubleratchet.types.JSONObject, value) raise TypeError( f"Stored DoubleRatchetImpl under key" f" /{self.namespace}/{bare_jid}/{device_id}/double_ratchet corrupt: not a JSON object:" f" {value}" ) try: double_ratchet = (await self.__storage.load( f"/{self.namespace}/{bare_jid}/{device_id}/double_ratchet" )).fmap(check_type).fmap(lambda serialized: DoubleRatchetImpl.from_json( serialized, diffie_hellman_ratchet_curve25519.DiffieHellmanRatchet, RootChainKDFImpl, MessageChainKDFImpl, DoubleRatchetImpl.MESSAGE_CHAIN_CONSTANT, self.max_num_per_message_skipped_keys, self.max_num_per_session_skipped_keys, AEADImpl )).maybe(None) except doubleratchet.InconsistentSerializationException: return None if double_ratchet is None: return None initiation = Initiation((await self.__storage.load_primitive( f"/{self.namespace}/{bare_jid}/{device_id}/initiation", str )).from_just()) identity_key = (await self.__storage.load_bytes( f"/{self.namespace}/{bare_jid}/{device_id}/key_exchange/identity_key" )).from_just() ephemeral_key = (await self.__storage.load_bytes( f"/{self.namespace}/{bare_jid}/{device_id}/key_exchange/ephemeral_key" )).from_just() signed_pre_key = (await self.__storage.load_bytes( f"/{self.namespace}/{bare_jid}/{device_id}/key_exchange/signed_pre_key" )).from_just() signed_pre_key_id = (await self.__storage.load_primitive( f"/{self.namespace}/{bare_jid}/{device_id}/key_exchange/signed_pre_key_id", int )).from_just() pre_key = (await self.__storage.load_bytes( f"/{self.namespace}/{bare_jid}/{device_id}/key_exchange/pre_key" )).from_just() pre_key_id = (await self.__storage.load_primitive( f"/{self.namespace}/{bare_jid}/{device_id}/key_exchange/pre_key_id", int )).from_just() associated_data = (await self.__storage.load_bytes( f"/{self.namespace}/{bare_jid}/{device_id}/associated_data" )).from_just() confirmed = (await self.__storage.load_primitive( f"/{self.namespace}/{bare_jid}/{device_id}/confirmed", bool )).from_just() return SessionImpl(bare_jid, device_id, initiation, KeyExchangeImpl( x3dh.Header(identity_key, ephemeral_key, signed_pre_key, pre_key), signed_pre_key_id, pre_key_id ), associated_data, double_ratchet, confirmed) async def store_session(self, session: Session) -> None: assert isinstance(session, SessionImpl) assert session.key_exchange.header.pre_key is not None await self.__storage.store( f"/{self.namespace}/{session.bare_jid}/{session.device_id}/initiation", session.initiation.name ) await self.__storage.store_bytes( f"/{self.namespace}/{session.bare_jid}/{session.device_id}/key_exchange/identity_key", session.key_exchange.header.identity_key ) await self.__storage.store_bytes( f"/{self.namespace}/{session.bare_jid}/{session.device_id}/key_exchange/ephemeral_key", session.key_exchange.header.ephemeral_key ) await self.__storage.store_bytes( f"/{self.namespace}/{session.bare_jid}/{session.device_id}/key_exchange/signed_pre_key", session.key_exchange.header.signed_pre_key ) await self.__storage.store( f"/{self.namespace}/{session.bare_jid}/{session.device_id}/key_exchange/signed_pre_key_id", session.key_exchange.signed_pre_key_id ) await self.__storage.store_bytes( f"/{self.namespace}/{session.bare_jid}/{session.device_id}/key_exchange/pre_key", session.key_exchange.header.pre_key ) await self.__storage.store( f"/{self.namespace}/{session.bare_jid}/{session.device_id}/key_exchange/pre_key_id", session.key_exchange.pre_key_id ) await self.__storage.store_bytes( f"/{self.namespace}/{session.bare_jid}/{session.device_id}/associated_data", session.associated_data ) await self.__storage.store( f"/{self.namespace}/{session.bare_jid}/{session.device_id}/double_ratchet", session.double_ratchet.json ) await self.__storage.store( f"/{self.namespace}/{session.bare_jid}/{session.device_id}/confirmed", session.confirmed ) # Keep track of bare JIDs with stored sessions bare_jids = set((await self.__storage.load_list(f"/{self.namespace}/bare_jids", str)).maybe([])) bare_jids.add(session.bare_jid) await self.__storage.store(f"/{self.namespace}/bare_jids", list(bare_jids)) # Keep track of device ids with stored sessions device_ids = set((await self.__storage.load_list( f"/{self.namespace}/{session.bare_jid}/device_ids", int )).maybe([])) device_ids.add(session.device_id) await self.__storage.store(f"/{self.namespace}/{session.bare_jid}/device_ids", list(device_ids)) async def build_session_active( self, bare_jid: str, device_id: int, bundle: Bundle, plain_key_material: PlainKeyMaterial ) -> Tuple[SessionImpl, EncryptedKeyMaterialImpl]: assert isinstance(bundle, BundleImpl) assert isinstance(plain_key_material, PlainKeyMaterialImpl) try: state = await self.__get_state() shared_secret, associated_data, header = await state.get_shared_secret_active(bundle.bundle) except x3dh.KeyAgreementException as e: raise KeyExchangeFailed() from e assert header.pre_key is not None double_ratchet, encrypted_message = await DoubleRatchetImpl.encrypt_initial_message( diffie_hellman_ratchet_curve25519.DiffieHellmanRatchet, RootChainKDFImpl, MessageChainKDFImpl, DoubleRatchetImpl.MESSAGE_CHAIN_CONSTANT, self.max_num_per_message_skipped_keys, self.max_num_per_session_skipped_keys, AEADImpl, shared_secret, bundle.bundle.signed_pre_key, plain_key_material.key + plain_key_material.auth_tag, associated_data ) session = SessionImpl( bare_jid, device_id, Initiation.ACTIVE, KeyExchangeImpl( header, bundle.signed_pre_key_id, bundle.pre_key_ids[header.pre_key] ), associated_data, double_ratchet ) encrypted_key_material = EncryptedKeyMaterialImpl(bare_jid, device_id, encrypted_message) return session, encrypted_key_material async def build_session_passive( self, bare_jid: str, device_id: int, key_exchange: KeyExchange, encrypted_key_material: EncryptedKeyMaterial ) -> Tuple[SessionImpl, PlainKeyMaterialImpl]: assert isinstance(key_exchange, KeyExchangeImpl) assert isinstance(encrypted_key_material, EncryptedKeyMaterialImpl) state = await self.__get_state() if key_exchange.is_network_instance(): # Perform lookup of the signed pre key and pre key public keys in case the header is not filled signed_pre_keys_by_id = { v: k for k, v in (await self.__get_signed_pre_key_ids()).items() } if key_exchange.signed_pre_key_id not in signed_pre_keys_by_id: raise KeyExchangeFailed(f"No signed pre key with id {key_exchange.signed_pre_key_id} known.") pre_keys_by_id = { v: k for k, v in (await self.__get_pre_key_ids()).items() } if key_exchange.pre_key_id not in pre_keys_by_id: raise KeyExchangeFailed(f"No pre key with id {key_exchange.pre_key_id} known.") # Update the key exchange information with the filled header key_exchange = KeyExchangeImpl( x3dh.Header( key_exchange.header.identity_key, key_exchange.header.ephemeral_key, signed_pre_keys_by_id[key_exchange.signed_pre_key_id], pre_keys_by_id[key_exchange.pre_key_id] ), key_exchange.signed_pre_key_id, key_exchange.pre_key_id ) try: shared_secret, associated_data, signed_pre_key = await state.get_shared_secret_passive( key_exchange.header ) except x3dh.KeyAgreementException as e: raise KeyExchangeFailed() from e try: double_ratchet, decrypted_message = await DoubleRatchetImpl.decrypt_initial_message( diffie_hellman_ratchet_curve25519.DiffieHellmanRatchet, RootChainKDFImpl, MessageChainKDFImpl, DoubleRatchetImpl.MESSAGE_CHAIN_CONSTANT, self.max_num_per_message_skipped_keys, self.max_num_per_session_skipped_keys, AEADImpl, shared_secret, signed_pre_key.priv, encrypted_key_material.encrypted_message, associated_data ) except Exception as e: raise DecryptionFailed( "Decryption of the initial message as part of passive session building failed." ) from e session = SessionImpl( bare_jid, device_id, Initiation.PASSIVE, key_exchange, associated_data, double_ratchet ) plain_key_material = PlainKeyMaterialImpl( decrypted_message[:PlainKeyMaterialImpl.KEY_LENGTH], decrypted_message[PlainKeyMaterialImpl.KEY_LENGTH:] ) return session, plain_key_material async def encrypt_plaintext(self, plaintext: bytes) -> Tuple[ContentImpl, PlainKeyMaterialImpl]: # Generate KEY_LENGTH bytes of cryptographically secure random data for the key key = secrets.token_bytes(PlainKeyMaterialImpl.KEY_LENGTH) # Derive 80 bytes from the key using HKDF-SHA-256 key_material = await CryptoProviderImpl.hkdf_derive( hash_function=HashFunction.SHA_256, length=80, salt=b"\x00" * 32, info="OMEMO Payload".encode("ASCII"), key_material=key ) # Split those 80 bytes into an encryption key, authentication key and an initialization vector encryption_key = key_material[:32] authentication_key = key_material[32:64] initialization_vector = key_material[64:] # Encrypt the plaintext using AES-256 (the 256 bit are implied by the key size) in CBC mode and the # previously created key and IV, after padding it with PKCS#7 ciphertext = await CryptoProviderImpl.aes_cbc_encrypt( encryption_key, initialization_vector, plaintext ) # Calculate the authentication tag and truncate it to AUTHENTICATION_TAG_TRUNCATED_LENGTH bytes auth_tag = (await CryptoProviderImpl.hmac_calculate( authentication_key, HashFunction.SHA_256, ciphertext ))[:AEADImpl.AUTHENTICATION_TAG_TRUNCATED_LENGTH] return ContentImpl(ciphertext), PlainKeyMaterialImpl(key, auth_tag) async def encrypt_empty(self) -> Tuple[ContentImpl, PlainKeyMaterialImpl]: return ContentImpl.make_empty(), PlainKeyMaterialImpl.make_empty() async def encrypt_key_material( self, session: Session, plain_key_material: PlainKeyMaterial ) -> EncryptedKeyMaterialImpl: assert isinstance(session, SessionImpl) assert isinstance(plain_key_material, PlainKeyMaterialImpl) return EncryptedKeyMaterialImpl( session.bare_jid, session.device_id, await session.double_ratchet.encrypt_message( plain_key_material.key + plain_key_material.auth_tag, session.associated_data ) ) async def decrypt_plaintext(self, content: Content, plain_key_material: PlainKeyMaterial) -> bytes: assert isinstance(content, ContentImpl) assert isinstance(plain_key_material, PlainKeyMaterialImpl) assert not content.empty # Derive 80 bytes from the key using HKDF-SHA-256 key_material = await CryptoProviderImpl.hkdf_derive( hash_function=HashFunction.SHA_256, length=80, salt=b"\x00" * 32, info="OMEMO Payload".encode("ASCII"), key_material=plain_key_material.key ) # Split those 80 bytes into an encryption key, authentication key and an initialization vector decryption_key = key_material[:32] authentication_key = key_material[32:64] initialization_vector = key_material[64:] # Calculate and verify the authentication tag after truncating it to # AUTHENTICATION_TAG_TRUNCATED_LENGTH bytes auth_tag = (await CryptoProviderImpl.hmac_calculate( authentication_key, HashFunction.SHA_256, content.ciphertext ))[:AEADImpl.AUTHENTICATION_TAG_TRUNCATED_LENGTH] if auth_tag != plain_key_material.auth_tag: raise DecryptionFailed("Authentication tag verification failed.") # Decrypt the plaintext using AES-256 (the 256 bit are implied by the key size) in CBC mode and the # previously created key and IV, and unpad the resulting plaintext with PKCS#7 return await CryptoProviderImpl.aes_cbc_decrypt( decryption_key, initialization_vector, content.ciphertext ) async def decrypt_key_material( self, session: Session, encrypted_key_material: EncryptedKeyMaterial ) -> PlainKeyMaterialImpl: assert isinstance(session, SessionImpl) assert isinstance(encrypted_key_material, EncryptedKeyMaterialImpl) try: decrypted_message = await session.double_ratchet.decrypt_message( encrypted_key_material.encrypted_message, session.associated_data ) except Exception as e: raise DecryptionFailed("Key material decryption failed.") from e session.confirm() return PlainKeyMaterialImpl( decrypted_message[:PlainKeyMaterialImpl.KEY_LENGTH], decrypted_message[PlainKeyMaterialImpl.KEY_LENGTH:] ) async def signed_pre_key_age(self) -> int: return (await self.__get_state()).signed_pre_key_age() async def rotate_signed_pre_key(self) -> None: state = await self.__get_state() state.rotate_signed_pre_key() await self.__storage.store(f"/{self.namespace}/x3dh", state.json) async def hide_pre_key(self, session: Session) -> bool: assert isinstance(session, SessionImpl) # This method is only called with KeyExchangeImpl instances that have the pre key byte data set. We do # not have to worry about the field containing a filler value and the assertion is merely there to # satisfy the type system. assert session.key_exchange.header.pre_key is not None state = await self.__get_state() hidden = state.hide_pre_key(session.key_exchange.header.pre_key) await self.__storage.store(f"/{self.namespace}/x3dh", state.json) return hidden async def delete_pre_key(self, session: Session) -> bool: assert isinstance(session, SessionImpl) # This method is only called with KeyExchangeImpl instances that have the pre key byte data set. We do # not have to worry about the field containing a filler value and the assertion is merely there to # satisfy the type system. assert session.key_exchange.header.pre_key is not None state = await self.__get_state() deleted = state.delete_pre_key(session.key_exchange.header.pre_key) await self.__storage.store(f"/{self.namespace}/x3dh", state.json) return deleted async def delete_hidden_pre_keys(self) -> None: state = await self.__get_state() state.delete_hidden_pre_keys() await self.__storage.store(f"/{self.namespace}/x3dh", state.json) async def get_num_visible_pre_keys(self) -> int: return (await self.__get_state()).get_num_visible_pre_keys() async def generate_pre_keys(self, num_pre_keys: int) -> None: state = await self.__get_state() state.generate_pre_keys(num_pre_keys) await self.__storage.store(f"/{self.namespace}/x3dh", state.json) async def get_bundle(self, bare_jid: str, device_id: int) -> BundleImpl: bundle = (await self.__get_state()).bundle return BundleImpl( bare_jid, device_id, bundle, (await self.__get_signed_pre_key_ids())[bundle.signed_pre_key], { pre_key: pre_key_id for pre_key, pre_key_id in (await self.__get_pre_key_ids()).items() if pre_key in bundle.pre_keys } ) async def purge(self) -> None: for bare_jid in (await self.__storage.load_list(f"/{self.namespace}/bare_jids", str)).maybe([]): await self.purge_bare_jid(bare_jid) await self.__storage.delete(f"/{self.namespace}/bare_jids") await self.__storage.delete(f"/{self.namespace}/x3dh") await self.__storage.delete(f"/{self.namespace}/signed_pre_key_ids") await self.__storage.delete(f"/{self.namespace}/pre_key_ids") await self.__storage.delete(f"/{self.namespace}/pre_key_id_counter") async def purge_bare_jid(self, bare_jid: str) -> None: storage = self.__storage for device_id in (await storage.load_list(f"/{self.namespace}/{bare_jid}/device_ids", int)).maybe([]): await storage.delete(f"/{self.namespace}/{bare_jid}/{device_id}/initiation") await storage.delete(f"/{self.namespace}/{bare_jid}/{device_id}/key_exchange/identity_key") await storage.delete(f"/{self.namespace}/{bare_jid}/{device_id}/key_exchange/ephemeral_key") await storage.delete(f"/{self.namespace}/{bare_jid}/{device_id}/key_exchange/signed_pre_key") await storage.delete(f"/{self.namespace}/{bare_jid}/{device_id}/key_exchange/signed_pre_key_id") await storage.delete(f"/{self.namespace}/{bare_jid}/{device_id}/key_exchange/pre_key") await storage.delete(f"/{self.namespace}/{bare_jid}/{device_id}/key_exchange/pre_key_id") await storage.delete(f"/{self.namespace}/{bare_jid}/{device_id}/associated_data") await storage.delete(f"/{self.namespace}/{bare_jid}/{device_id}/double_ratchet") await storage.delete(f"/{self.namespace}/{bare_jid}/{device_id}/confirmed") await storage.delete(f"/{self.namespace}/{bare_jid}/device_ids") bare_jids = set((await storage.load_list(f"/{self.namespace}/bare_jids", str)).maybe([])) bare_jids.remove(bare_jid) await storage.store(f"/{self.namespace}/bare_jids", list(bare_jids)) async def __get_signed_pre_key_ids(self) -> Dict[bytes, int]: """ Assigns an id to each signed pre key currently available in the X3DH state, both the current signed pre key and the old signed pre key that is kept around for one more rotation period. Once assigned to a signed pre key, its id will never change. Returns: The mapping from signed pre key to id. """ state = await self.__get_state() signed_pre_key = state.bundle.signed_pre_key old_signed_pre_key = state.old_signed_pre_key # Load the existing signed pre key ids from the storage signed_pre_key_ids = { base64.b64decode(signed_pre_key_b64): signed_pre_key_id for signed_pre_key_b64, signed_pre_key_id in (await self.__storage.load_dict( f"/{self.namespace}/signed_pre_key_ids", int )).maybe({}).items() } # Take note of the highest id that was assigned, default to 0 if no ids were assigned yet signed_pre_key_id_counter = max( signed_pre_key_id for _, signed_pre_key_id in signed_pre_key_ids.items() ) if len(signed_pre_key_ids) > 0 else 0 # Prepare the dictionary to hold updated signed pre key ids new_signed_pre_key_ids: Dict[bytes, int] = {} # Assign the next highest id to the signed pre key, if there is no id assigned to it yet. signed_pre_key_id_counter += 1 new_signed_pre_key_ids[signed_pre_key] = signed_pre_key_ids.get( signed_pre_key, signed_pre_key_id_counter ) # Assign the next highest id to the old signed pre key, if there is no id assigned to it yet. This # should never happen, since the old signed pre key should have been assigned an id when it was the # (non-old) signed pre key, however there might be edge cases of the signed pre key rotating twice # before the assigned ids are updated. if old_signed_pre_key is not None: signed_pre_key_id_counter += 1 new_signed_pre_key_ids[old_signed_pre_key] = signed_pre_key_ids.get( old_signed_pre_key, signed_pre_key_id_counter ) # If the ids have changed, store them if new_signed_pre_key_ids != signed_pre_key_ids: await self.__storage.store(f"/{self.namespace}/signed_pre_key_ids", { base64.b64encode(signed_pre_key).decode("ASCII"): signed_pre_key_id for signed_pre_key, signed_pre_key_id in new_signed_pre_key_ids.items() }) return new_signed_pre_key_ids async def __get_pre_key_ids(self) -> Dict[bytes, int]: """ Assigns an id to each pre key currently available in the X3DH state, both hidden and visible pre keys. Once assigned to a pre key, its id will never change. Returns: The mapping from pre key to id. """ state = await self.__get_state() pre_keys = state.bundle.pre_keys | state.hidden_pre_keys # Load the existing pre key ids from the storage pre_key_ids = { base64.b64decode(pre_key_b64): pre_key_id for pre_key_b64, pre_key_id in (await self.__storage.load_dict(f"/{self.namespace}/pre_key_ids", int)).maybe({}).items() } # Load the pre key id counter from the storage pre_key_id_counter = (await self.__storage.load_primitive( f"/{self.namespace}/pre_key_id_counter", int )).maybe(0) # Prepare the dictionary to hold updated pre key ids new_pre_key_ids: Dict[bytes, int] = {} # Assign the next highest id to each pre key if there is no existing id assigned to it for pre_key in pre_keys: pre_key_id_counter += 1 new_pre_key_ids[pre_key] = pre_key_ids.get(pre_key, pre_key_id_counter) # If the ids have changed, store them if new_pre_key_ids != pre_key_ids: await self.__storage.store(f"/{self.namespace}/pre_key_ids", { base64.b64encode(pre_key).decode("ASCII"): pre_key_id for pre_key, pre_key_id in new_pre_key_ids.items() }) await self.__storage.store(f"/{self.namespace}/pre_key_id_counter", pre_key_id_counter) return new_pre_key_ids python-twomemo-1.0.4/twomemo/twomemo_pb2.py000066400000000000000000000030511464324652200210240ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: twomemo.proto """Generated protocol buffer code.""" from google.protobuf.internal import builder as _builder from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\rtwomemo.proto\x12\x07twomemo\"I\n\x0cOMEMOMessage\x12\t\n\x01n\x18\x01 \x02(\r\x12\n\n\x02pn\x18\x02 \x02(\r\x12\x0e\n\x06\x64h_pub\x18\x03 \x02(\x0c\x12\x12\n\nciphertext\x18\x04 \x01(\x0c\"9\n\x19OMEMOAuthenticatedMessage\x12\x0b\n\x03mac\x18\x01 \x02(\x0c\x12\x0f\n\x07message\x18\x02 \x02(\x0c\"~\n\x10OMEMOKeyExchange\x12\r\n\x05pk_id\x18\x01 \x02(\r\x12\x0e\n\x06spk_id\x18\x02 \x02(\r\x12\n\n\x02ik\x18\x03 \x02(\x0c\x12\n\n\x02\x65k\x18\x04 \x02(\x0c\x12\x33\n\x07message\x18\x05 \x02(\x0b\x32\".twomemo.OMEMOAuthenticatedMessage') _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'twomemo_pb2', globals()) if _descriptor._USE_C_DESCRIPTORS == False: DESCRIPTOR._options = None _OMEMOMESSAGE._serialized_start=26 _OMEMOMESSAGE._serialized_end=99 _OMEMOAUTHENTICATEDMESSAGE._serialized_start=101 _OMEMOAUTHENTICATEDMESSAGE._serialized_end=158 _OMEMOKEYEXCHANGE._serialized_start=160 _OMEMOKEYEXCHANGE._serialized_end=286 # @@protoc_insertion_point(module_scope) python-twomemo-1.0.4/twomemo/twomemo_pb2.pyi000066400000000000000000000060711464324652200212020ustar00rootroot00000000000000""" @generated by mypy-protobuf. Do not edit manually! isort:skip_file """ import builtins import google.protobuf.descriptor import google.protobuf.message import typing import typing_extensions DESCRIPTOR: google.protobuf.descriptor.FileDescriptor class OMEMOMessage(google.protobuf.message.Message): DESCRIPTOR: google.protobuf.descriptor.Descriptor N_FIELD_NUMBER: builtins.int PN_FIELD_NUMBER: builtins.int DH_PUB_FIELD_NUMBER: builtins.int CIPHERTEXT_FIELD_NUMBER: builtins.int n: builtins.int pn: builtins.int dh_pub: builtins.bytes ciphertext: builtins.bytes def __init__(self, *, n: typing.Optional[builtins.int] = ..., pn: typing.Optional[builtins.int] = ..., dh_pub: typing.Optional[builtins.bytes] = ..., ciphertext: typing.Optional[builtins.bytes] = ..., ) -> None: ... def HasField(self, field_name: typing_extensions.Literal["ciphertext",b"ciphertext","dh_pub",b"dh_pub","n",b"n","pn",b"pn"]) -> builtins.bool: ... def ClearField(self, field_name: typing_extensions.Literal["ciphertext",b"ciphertext","dh_pub",b"dh_pub","n",b"n","pn",b"pn"]) -> None: ... global___OMEMOMessage = OMEMOMessage class OMEMOAuthenticatedMessage(google.protobuf.message.Message): DESCRIPTOR: google.protobuf.descriptor.Descriptor MAC_FIELD_NUMBER: builtins.int MESSAGE_FIELD_NUMBER: builtins.int mac: builtins.bytes message: builtins.bytes """Byte-encoding of an OMEMOMessage""" def __init__(self, *, mac: typing.Optional[builtins.bytes] = ..., message: typing.Optional[builtins.bytes] = ..., ) -> None: ... def HasField(self, field_name: typing_extensions.Literal["mac",b"mac","message",b"message"]) -> builtins.bool: ... def ClearField(self, field_name: typing_extensions.Literal["mac",b"mac","message",b"message"]) -> None: ... global___OMEMOAuthenticatedMessage = OMEMOAuthenticatedMessage class OMEMOKeyExchange(google.protobuf.message.Message): DESCRIPTOR: google.protobuf.descriptor.Descriptor PK_ID_FIELD_NUMBER: builtins.int SPK_ID_FIELD_NUMBER: builtins.int IK_FIELD_NUMBER: builtins.int EK_FIELD_NUMBER: builtins.int MESSAGE_FIELD_NUMBER: builtins.int pk_id: builtins.int spk_id: builtins.int ik: builtins.bytes ek: builtins.bytes @property def message(self) -> global___OMEMOAuthenticatedMessage: ... def __init__(self, *, pk_id: typing.Optional[builtins.int] = ..., spk_id: typing.Optional[builtins.int] = ..., ik: typing.Optional[builtins.bytes] = ..., ek: typing.Optional[builtins.bytes] = ..., message: typing.Optional[global___OMEMOAuthenticatedMessage] = ..., ) -> None: ... def HasField(self, field_name: typing_extensions.Literal["ek",b"ek","ik",b"ik","message",b"message","pk_id",b"pk_id","spk_id",b"spk_id"]) -> builtins.bool: ... def ClearField(self, field_name: typing_extensions.Literal["ek",b"ek","ik",b"ik","message",b"message","pk_id",b"pk_id","spk_id",b"spk_id"]) -> None: ... global___OMEMOKeyExchange = OMEMOKeyExchange python-twomemo-1.0.4/twomemo/version.py000066400000000000000000000003231464324652200202560ustar00rootroot00000000000000__all__ = [ "__version__" ] # pylint: disable=unused-variable __version__ = {} __version__["short"] = "1.0.4" __version__["tag"] = "stable" __version__["full"] = f"{__version__['short']}-{__version__['tag']}"