├── .ackrc
├── .bumpversion.cfg
├── .cookiecutterrc
├── .coveragerc
├── .editorconfig
├── .gitignore
├── .travis.yml
├── AUTHORS.rst
├── CHANGELOG.rst
├── CONTRIBUTING.rst
├── COPYING
├── MANIFEST.in
├── README.rst
├── appveyor.yml
├── ci
├── appveyor-bootstrap.py
├── appveyor-download.py
├── appveyor-with-compiler.cmd
├── bootstrap.py
└── templates
│ ├── .travis.yml
│ └── appveyor.yml
├── docs
├── authors.rst
├── changelog.rst
├── conf.py
├── contributing.rst
├── index.rst
├── installation.rst
├── readme.rst
├── reference
│ ├── index.rst
│ └── omemo.rst
├── requirements.txt
├── spelling_wordlist.txt
├── usage.rst
└── xep-omemo.rst
├── setup.cfg
├── setup.py
├── src
├── .gitignore
├── .style.yapf
├── COPYING
├── omemo.png
└── omemo
│ ├── __init__.py
│ ├── aes_gcm.py
│ ├── aes_gcm_fallback.py
│ ├── aes_gcm_native.py
│ ├── db_helpers.py
│ ├── encryption.py
│ ├── liteaxolotlstore.py
│ ├── liteidentitykeystore.py
│ ├── liteprekeystore.py
│ ├── litesessionstore.py
│ ├── litesignedprekeystore.py
│ ├── padding.py
│ └── state.py
├── tests
├── test_aes_gcm.py
├── test_db_helpers.py
├── test_encryption_store.py
├── test_migrate_encryption_state.py
├── test_omemo.py
├── test_omemo_state.py
└── test_padding.py
└── tox.ini
/.ackrc:
--------------------------------------------------------------------------------
1 | --ignore-dir
2 | .tox
3 |
4 | --ignore-dir
5 | dist
6 |
7 | --ignore-dir
8 | .venv
9 |
10 | --ignore-dir
11 | .ropeproject
12 |
13 | --ignore-dir
14 | src/omemo.egg-info/
15 |
16 | --ignore-file
17 | ext:pyc
18 | --ignore-file
19 | match:.coverage.python
20 |
--------------------------------------------------------------------------------
/.bumpversion.cfg:
--------------------------------------------------------------------------------
1 | [bumpversion]
2 | current_version = 0.1.0
3 | commit = True
4 | tag = True
5 |
6 | [bumpversion:file:setup.py]
7 |
8 | [bumpversion:file:docs/conf.py]
9 |
10 | [bumpversion:file:src/omemo/__init__.py]
11 |
12 |
--------------------------------------------------------------------------------
/.cookiecutterrc:
--------------------------------------------------------------------------------
1 | # This file exists so you can easily regenerate your project.
2 | #
3 | # `cookiepatcher` is a convenient shim around `cookiecutter`
4 | # for regenerating projects (it will generate a .cookiecutterrc
5 | # automatically for any template). To use it:
6 | #
7 | # pip install cookiepatcher
8 | # cookiepatcher gh:ionelmc/cookiecutter-pylibrary project-path
9 | #
10 | # See:
11 | # https://pypi.python.org/pypi/cookiecutter
12 | #
13 | # Alternatively, you can run:
14 | #
15 | # cookiecutter --overwrite-if-exists --config-file=project-path/.cookiecutterrc gh:ionelmc/cookiecutter-pylibrary
16 |
17 | default_context:
18 |
19 | appveyor: 'yes'
20 | bin_name: 'omemo'
21 | c_extension_cython: 'no'
22 | c_extension_optional: 'no'
23 | c_extension_support: 'no'
24 | codacy: 'no'
25 | codeclimate: 'no'
26 | codecov: 'yes'
27 | command_line_interface: 'no'
28 | coveralls: 'no'
29 | distribution_name: 'python-omemo'
30 | email: 'bahtiar@gadimov.de'
31 | full_name: 'Bahtiar `kalkin-` Gadimov'
32 | github_username: 'kalkin'
33 | landscape: 'no'
34 | package_name: 'omemo'
35 | project_name: 'Python OMEMO Library'
36 | project_short_description: 'This is an implementation o*OMEMO Multi-End Message and Object Encryption** in Python.'
37 | release_date: 'today'
38 | repo_name: 'python-omemo'
39 | requiresio: 'yes'
40 | scrutinizer: 'no'
41 | sphinx_theme: 'readthedocs'
42 | test_matrix_configurator: 'no'
43 | test_runner: 'pytest'
44 | travis: 'yes'
45 | version: '0.1.0'
46 | website: 'https://github.com/omemo'
47 | year: 'now'
48 |
--------------------------------------------------------------------------------
/.coveragerc:
--------------------------------------------------------------------------------
1 | [paths]
2 | source = src
3 |
4 | [run]
5 | branch = True
6 | source = src
7 | parallel = true
8 |
9 | [report]
10 | show_missing = true
11 | precision = 2
12 | omit = *migrations*
13 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # see http://editorconfig.org
2 | root = true
3 |
4 | [*]
5 | end_of_line = lf
6 | trim_trailing_whitespace = true
7 | insert_final_newline = true
8 | indent_style = space
9 | indent_size = 4
10 | charset = utf-8
11 |
12 | [*.{bat,cmd,ps1}]
13 | end_of_line = crlf
14 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.py[cod]
2 |
3 | # C extensions
4 | *.so
5 |
6 | # Packages
7 | *.egg
8 | *.egg-info
9 | dist
10 | build
11 | eggs
12 | .eggs
13 | parts
14 | bin
15 | var
16 | sdist
17 | develop-eggs
18 | .installed.cfg
19 | lib
20 | lib64
21 | venv*/
22 | pyvenv*/
23 |
24 | # Installer logs
25 | pip-log.txt
26 |
27 | # Unit test / coverage reports
28 | .coverage
29 | .tox
30 | .coverage.*
31 | nosetests.xml
32 | coverage.xml
33 | htmlcov
34 |
35 | # Translations
36 | *.mo
37 |
38 | # Mr Developer
39 | .mr.developer.cfg
40 | .project
41 | .pydevproject
42 | .idea
43 | *.iml
44 | *.komodoproject
45 |
46 | # Complexity
47 | output/*.html
48 | output/*/index.html
49 |
50 | # Sphinx
51 | docs/_build
52 |
53 | .DS_Store
54 | *~
55 | .*.sw[po]
56 | .build
57 | .ve
58 | .env
59 | .cache
60 | .pytest
61 | .bootstrap
62 | .appveyor.token
63 | *.bak
64 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: python
2 | python: '3.5'
3 | sudo: false
4 | env:
5 | global:
6 | - LD_PRELOAD=/lib/x86_64-linux-gnu/libSegFault.so
7 | - SEGFAULT_SIGNALS=all
8 | matrix:
9 | - TOXENV=check
10 |
11 | - TOXENV=py27-cover-crypto,codecov
12 | - TOXENV=py27-nocov-crypto
13 | - TOXENV=py33-cover-crypto,codecov
14 | - TOXENV=py33-nocov-crypto
15 | - TOXENV=py33-nocov-crypto11
16 | - TOXENV=py33-nocov-crypto12
17 | - TOXENV=py34-cover-crypto,codecov
18 | - TOXENV=py34-nocov-crypto
19 | - TOXENV=py34-nocov-crypto11
20 | - TOXENV=py34-nocov-crypto12
21 | - TOXENV=py35-cover-crypto,codecov
22 | - TOXENV=py35-nocov-crypto
23 | - TOXENV=py35-nocov-crypto11
24 | - TOXENV=py35-nocov-crypto12
25 | - TOXENV=pypy-nocov
26 | before_install:
27 | - python --version
28 | - uname -a
29 | - lsb_release -a
30 | install:
31 | - pip install tox
32 | - virtualenv --version
33 | - easy_install --version
34 | - pip --version
35 | - tox --version
36 | script:
37 | - tox -v
38 | after_failure:
39 | - more .tox/log/* | cat
40 | - more .tox/*/log/* | cat
41 | before_cache:
42 | - rm -rf $HOME/.cache/pip/log
43 | cache:
44 | directories:
45 | - $HOME/.cache/pip
46 | notifications:
47 | email:
48 | on_success: never
49 | on_failure: never
50 |
--------------------------------------------------------------------------------
/AUTHORS.rst:
--------------------------------------------------------------------------------
1 |
2 | Authors
3 | =======
4 |
5 | * Bahtiar `kalkin-` Gadimov - https://github.com/kalkin
6 | * Daniel Gultsch - https://github.com/inputmice
7 | * Tarek Galal - https://github.com/tgalal (original axolotl store implementation)
8 | * Bob Mottram - https://github.com/bashrc (message padding)
9 |
--------------------------------------------------------------------------------
/CHANGELOG.rst:
--------------------------------------------------------------------------------
1 |
2 | Changelog
3 | =========
4 |
5 | 0.1.0 (2016-01-11)
6 | -----------------------------------------
7 |
8 | * First release on PyPI.
9 |
--------------------------------------------------------------------------------
/CONTRIBUTING.rst:
--------------------------------------------------------------------------------
1 | .. _c4
2 | =====================================
3 | Collective Code Construction Contract
4 | =====================================
5 |
6 |
7 | The **Collective Code Construction Contract (C4)** is an evolution of the
8 | `github.com Fork + Pull Model
9 | `_, aimed at providing an
10 | optimal collaboration model for free software projects. This is revision 1 of
11 | the C4 specification.
12 |
13 | License
14 | =======
15 | Copyright (c) 2009-2015 Pieter Hintjens.
16 |
17 | This Specification is free software; you can redistribute it and/or modify it
18 | under the terms of the GNU General Public License as published by the Free
19 | Software Foundation; either version 3 of the License, or (at your option) any
20 | later version.
21 |
22 | This Specification is distributed in the hope that it will be useful, but
23 | WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
24 | FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
25 | details.
26 |
27 | You should have received a copy of the GNU General Public License along with
28 | this program; if not, see .
29 |
30 | Language
31 | ========
32 |
33 | The key words "**MUST**", "**MUST NOT**", "**REQUIRED**", "**SHALL**", "**SHALL NOT**", "**SHOULD**",
34 | "**SHOULD NOT**", "**RECOMMENDED**", "**MAY**", and "**OPTIONAL**" in this document are to be
35 | interpreted as described in `RFC 2119 `_.
36 |
37 | Goals
38 | =====
39 |
40 | C4 is meant to provide a reusable optimal collaboration model for open source
41 | software projects. It has these specific goals:
42 |
43 | - To maximize the scale of the community around a project, by reducing the
44 | friction for new Contributors and creating a scaled participation model with
45 | strong positive feedbacks;
46 |
47 | - To relieve dependencies on key individuals by separating different skill sets
48 | so that there is a larger pool of competence in any required domain;
49 |
50 | - To allow the project to develop faster and more accurately, by increasing the
51 | diversity of the decision making process;
52 |
53 | - To support the natural life cycle of project versions from experimental
54 | through to stable, by allowing safe experimentation, rapid failure, and
55 | isolation of stable code;
56 |
57 | - To reduce the internal complexity of project repositories, thus making it
58 | easier for Contributors to participate and reducing the scope for error;
59 |
60 | - To enforce collective ownership of the project, which increases economic
61 | incentive to Contributors and reduces the risk of hijack by hostile entities.
62 |
63 | Design
64 | ======
65 | Preliminaries
66 | -------------
67 | - The project **SHALL** use the git distributed revision control system.
68 |
69 | - The project **SHALL** be hosted on github.com or equivalent, herein called the
70 | "Platform".
71 |
72 | - The project **SHALL** use the Platform issue tracker.
73 |
74 | - The project **SHOULD** have clearly documented guidelines for code style.
75 |
76 | - A "Contributor" is a person who wishes to provide a patch, being a set of
77 | commits that solve some clearly identified problem.
78 |
79 | - A "Maintainer" is a person who merges patches to the project. Maintainers are
80 | not developers; their job is to enforce process.
81 |
82 | - Contributors **SHALL NOT** have commit access to the repository unless they are
83 | also Maintainers.
84 |
85 | - Maintainers **SHALL** have commit access to the repository.
86 |
87 | - Everyone, without distinction or discrimination, **SHALL** have an equal right to
88 | become a Contributor under the terms of this contract.
89 |
90 | Licensing and Ownership
91 | -----------------------
92 |
93 | - The project **SHALL** use a share-alike license, such as the GPLv3 or a variant
94 | thereof (LGPL, AGPL), or the MPLv2.
95 |
96 | - All contributions to the project source code ("patches") **SHALL** use the same
97 | license as the project.
98 |
99 | - All patches are owned by their authors. There **SHALL NOT** be any copyright
100 | assignment process.
101 |
102 | - The copyrights in the project **SHALL** be owned collectively by all its
103 | Contributors.
104 |
105 | - Each Contributor **SHALL** be responsible for identifying themselves in the
106 | project Contributor list.
107 |
108 | Patch Requirements
109 | ------------------
110 |
111 | - Maintainers and Contributors **MUST** have a Platform account and **SHOULD**
112 | use their real names or a well-known alias.
113 |
114 | - A patch **SHOULD** be a minimal and accurate answer to exactly one identified and
115 | agreed problem.
116 |
117 | - A patch **MUST** adhere to the code style guidelines of the project if these are
118 | defined.
119 |
120 | - A patch **MUST** adhere to the "Evolution of Public Contracts" guidelines defined
121 | below.
122 |
123 | - A patch **SHALL NOT** include non-trivial code from other projects unless the
124 | Contributor is the original author of that code.
125 |
126 | - A patch **MUST** compile cleanly and pass project self-tests on at least the
127 | principle target platform.
128 |
129 | - A patch commit message **SHOULD** consist of a single short (less than 50
130 | character) line summarizing the change, optionally followed by a blank line
131 | and then a more thorough description.
132 |
133 | - A "Correct Patch" is one that satisfies the above requirements.
134 |
135 | Development Process
136 | -------------------
137 |
138 | - Change on the project **SHALL** be governed by the pattern of accurately
139 | identifying problems and applying minimal, accurate solutions to these
140 | problems.
141 |
142 | - To request changes, a user **SHOULD** log an issue on the project Platform issue
143 | tracker.
144 |
145 | - The user or Contributor **SHOULD** write the issue by describing the problem they
146 | face or observe.
147 |
148 | - The user or Contributor **SHOULD** seek consensus on the accuracy of their
149 | observation, and the value of solving the problem.
150 |
151 | - Users **SHALL NOT** log feature requests, ideas, suggestions, or any solutions to
152 | problems that are not explicitly documented and provable.
153 |
154 | - Thus, the release history of the project **SHALL** be a list of meaningful issues
155 | logged and solved.
156 |
157 | - To work on an issue, a Contributor **SHALL** fork the project repository and then
158 | work on their forked repository.
159 |
160 | - To submit a patch, a Contributor **SHALL** create a Platform pull request back to
161 | the project.
162 |
163 | - A Contributor **SHALL NOT** commit changes directly to the project.
164 |
165 | - If the Platform implements pull requests as issues, a Contributor **MAY**
166 | directly send a pull request without logging a separate issue.
167 |
168 | - To discuss a patch, people **MAY** comment on the Platform pull request, on the
169 | commit, or elsewhere.
170 |
171 | - To accept or reject a patch, a Maintainer **SHALL** use the Platform interface.
172 |
173 | - Maintainers **SHOULD NOT** merge their own patches except in exceptional cases,
174 | such as non-responsiveness from other Maintainers for an extended period (more
175 | than 1-2 days).
176 |
177 | - Maintainers **SHALL NOT** make value judgments on correct patches.
178 |
179 | - Maintainers **SHALL** merge correct patches from other Contributors rapidly.
180 |
181 | - The Contributor **MAY** tag an issue as "Ready" after making a pull request for
182 | the issue.
183 |
184 | - The user who created an issue **SHOULD** close the issue after checking the patch
185 | is successful.
186 |
187 | - Maintainers **SHOULD** ask for improvements to incorrect patches and
188 | **SHOULD** reject incorrect patches if the Contributor does not respond
189 | constructively.
190 |
191 | - Any Contributor who has value judgments on a correct patch **SHOULD** express
192 | these via their own patches.
193 |
194 | - Maintainers **MAY** commit changes to non-source documentation directly to the
195 | project.
196 |
197 | Creating Stable Releases
198 | ------------------------
199 |
200 | - The project **SHALL** have one branch ("master") that always holds the latest
201 | in-progress version and **SHOULD** always build.
202 |
203 | - The project **SHALL NOT** use topic branches for any reason. Personal forks
204 | **MAY** use topic branches.
205 |
206 | - To make a stable release someone **SHALL** fork the repository by copying it and
207 | thus become maintainer of this repository.
208 |
209 | - Forking a project for stabilization **MAY** be done unilaterally and without
210 | agreement of project maintainers.
211 |
212 | - A stabilization project **SHOULD** be maintained by the same process as the main
213 | project.
214 |
215 | - A patch to a stabilization project declared "stable" **SHALL** be accompanied by
216 | a reproducible test case.
217 |
218 | Evolution of Public Contracts
219 | -----------------------------
220 |
221 | - All Public Contracts (APIs or protocols) **SHALL** be documented.
222 |
223 | - All Public Contracts **SHOULD** have space for extensibility and experimentation.
224 |
225 | - A patch that modifies a stable Public Contract **SHOULD** not break existing
226 | applications unless there is overriding consensus on the value of doing this.
227 |
228 | - A patch that introduces new features to a Public Contract **SHOULD** do so using
229 | new names.
230 |
231 | - Old names **SHOULD** be deprecated in a systematic fashion by marking new names
232 | as "experimental" until they are stable, then marking the old names as
233 | "deprecated".
234 |
235 | - When sufficient time has passed, old deprecated names **SHOULD** be marked
236 | "legacy" and eventually removed.
237 |
238 | - Old names **SHALL NOT** be reused by new features.
239 |
240 | - When old names are removed, their implementations **MUST** provoke an exception
241 | (assertion) if used by applications.
242 |
243 | Project Administration
244 | ----------------------
245 |
246 | - The project founders **SHALL** act as Administrators to manage the set of project
247 | Maintainers.
248 |
249 | - The Administrators **SHALL** ensure their own succession over time by promoting
250 | the most effective Maintainers.
251 |
252 | - A new Contributor who makes a correct patch **SHALL** be invited to become a
253 | Maintainer.
254 |
255 | - Administrators **MAY** remove Maintainers who are inactive for an extended period
256 | of time, or who repeatedly fail to apply this process accurately.
257 |
258 | - Administrators **SHOULD** block or ban "bad actors" who cause stress and pain to
259 | others in the project. This should be done after public discussion, with a
260 | chance for all parties to speak. A bad actor is someone who repeatedly ignores
261 | the rules and culture of the project, who is needlessly argumentative or
262 | hostile, or who is offensive, and who is unable to self-correct their behavior
263 | when asked to do so by others.
264 |
265 | Further Reading
266 | ---------------
267 |
268 | - Argyris' Models 1 and 2 - the goals of C4.1 are consistent with Argyris'
269 | Model 2.
270 |
271 | - Toyota Kata - covering the Improvement Kata (fixing problems one at a time)
272 | and the Coaching Kata (helping others to learn the Improvement Kata).
273 |
274 | Implementations
275 | ---------------
276 |
277 | - The ZeroMQ community uses the C4.1 process for many projects.
278 | - OSSEC uses the C4.1 process.
279 | - The Machinekit community uses the C4.1 process.
280 |
281 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
676 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | graft docs
2 | graft examples
3 | graft src
4 | graft ci
5 | graft tests
6 |
7 | include .bumpversion.cfg
8 | include .coveragerc
9 | include .cookiecutterrc
10 | include .editorconfig
11 | include .isort.cfg
12 |
13 | include AUTHORS.rst
14 | include CHANGELOG.rst
15 | include CONTRIBUTING.rst
16 | include COPYING
17 | include README.rst
18 |
19 | include tox.ini .travis.yml appveyor.yml .ackrc
20 |
21 | global-exclude *.py[cod] __pycache__ *.so *.dylib
22 |
--------------------------------------------------------------------------------
/README.rst:
--------------------------------------------------------------------------------
1 | ========
2 | Overview
3 | ========
4 |
5 | .. start-badges
6 |
7 | .. list-table::
8 | :stub-columns: 1
9 |
10 | * - docs
11 | - |docs|
12 | * - tests
13 | - | |travis| |appveyor| |requires|
14 | | |codecov|
15 | |
16 | * - package
17 | - |version| |downloads| |wheel| |supported-versions| |supported-implementations|
18 |
19 | .. |docs| image:: https://readthedocs.org/projects/python-omemo/badge/?style=flat
20 | :target: https://readthedocs.org/projects/python-omemo
21 | :alt: Documentation Status
22 |
23 | .. |travis| image:: https://travis-ci.org/omemo/python-omemo.svg?branch=master
24 | :alt: Travis-CI Build Status
25 | :target: https://travis-ci.org/omemo/python-omemo
26 |
27 | .. |appveyor| image:: https://ci.appveyor.com/api/projects/status/github/omemo/python-omemo?branch=master&svg=true
28 | :alt: AppVeyor Build Status
29 | :target: https://ci.appveyor.com/project/omemo/python-omemo
30 |
31 | .. |requires| image:: https://requires.io/github/omemo/python-omemo/requirements.svg?branch=master
32 | :alt: Requirements Status
33 | :target: https://requires.io/github/omemo/python-omemo/requirements/?branch=master
34 |
35 | .. |codecov| image:: https://codecov.io/github/omemo/python-omemo/coverage.svg?branch=master
36 | :alt: Coverage Status
37 | :target: https://codecov.io/github/omemo/python-omemo
38 |
39 | .. |version| image:: https://img.shields.io/pypi/v/python-omemo.svg?style=flat
40 | :alt: PyPI Package latest release
41 | :target: https://pypi.python.org/pypi/python-omemo
42 |
43 | .. |downloads| image:: https://img.shields.io/pypi/dm/python-omemo.svg?style=flat
44 | :alt: PyPI Package monthly downloads
45 | :target: https://pypi.python.org/pypi/python-omemo
46 |
47 | .. |wheel| image:: https://img.shields.io/pypi/wheel/python-omemo.svg?style=flat
48 | :alt: PyPI Wheel
49 | :target: https://pypi.python.org/pypi/python-omemo
50 |
51 | .. |supported-versions| image:: https://img.shields.io/pypi/pyversions/python-omemo.svg?style=flat
52 | :alt: Supported versions
53 | :target: https://pypi.python.org/pypi/python-omemo
54 |
55 | .. |supported-implementations| image:: https://img.shields.io/pypi/implementation/python-omemo.svg?style=flat
56 | :alt: Supported implementations
57 | :target: https://pypi.python.org/pypi/python-omemo
58 |
59 |
60 | .. end-badges
61 |
62 | This is an implementation **OMEMO Multi-End Message and Object Encryption** in Python.
63 |
64 |
65 | Installation
66 | ============
67 |
68 | ::
69 |
70 | pip install python-omemo
71 |
72 | Documentation
73 | =============
74 |
75 | https://python-omemo.readthedocs.org/
76 |
77 | Development
78 | ===========
79 |
80 | To set up `python-omemo` for local development:
81 |
82 | 1. `Fork python-omemo on GitHub `_.
83 | 2. Clone your fork locally::
84 |
85 | git clone git@github.com:your_name_here/python-omemo.git
86 |
87 | 3. Create a branch for local development::
88 |
89 | git checkout -b name-of-your-bugfix-or-feature
90 |
91 | Now you can make your changes locally.
92 |
93 | 4. Run all the checks, doc builder and spell checker with `tox `_ one command::
94 |
95 | tox
96 |
97 | Tips
98 | ----
99 |
100 | To run a subset of tests::
101 |
102 | tox -e envname -- py.test -k test_myfeature
103 |
104 | To run all the test environments in *parallel* (you need to ``pip install detox``)::
105 |
106 | detox
107 |
108 |
109 | Contributing
110 | ============
111 |
112 | The **Python OMEMO** project direction is the sum of documented problems:
113 | everybody is invited to describe and discuss a problem in the `issue
114 | tracker `_. Contributed solutions
115 |
116 | encourage participation.
117 |
118 | Some problem fields we initially focus on are:
119 |
120 | - Creation of a reusable python omemo implementation
121 | - Reusability bu the `Gajim OMEMO plugin `_
122 |
123 |
124 |
--------------------------------------------------------------------------------
/appveyor.yml:
--------------------------------------------------------------------------------
1 | version: '{branch}-{build}'
2 | build: off
3 | cache:
4 | - '%LOCALAPPDATA%\pip\Cache'
5 | environment:
6 | global:
7 | WITH_COMPILER: 'cmd /E:ON /V:ON /C .\ci\appveyor-with-compiler.cmd'
8 | matrix:
9 | - TOXENV: check
10 | PYTHON_HOME: C:\Python27
11 | PYTHON_VERSION: '2.7'
12 | PYTHON_ARCH: '32'
13 |
14 | - TOXENV: 'py27-cover,codecov'
15 | TOXPYTHON: C:\Python27\python.exe
16 | PYTHON_HOME: C:\Python27
17 | PYTHON_VERSION: '2.7'
18 | PYTHON_ARCH: '32'
19 |
20 | - TOXENV: 'py27-cover,codecov'
21 | TOXPYTHON: C:\Python27-x64\python.exe
22 | WINDOWS_SDK_VERSION: v7.0
23 | PYTHON_HOME: C:\Python27-x64
24 | PYTHON_VERSION: '2.7'
25 | PYTHON_ARCH: '64'
26 |
27 | - TOXENV: 'py27-nocov'
28 | TOXPYTHON: C:\Python27\python.exe
29 | PYTHON_HOME: C:\Python27
30 | PYTHON_VERSION: '2.7'
31 | PYTHON_ARCH: '32'
32 |
33 | - TOXENV: 'py27-nocov'
34 | TOXPYTHON: C:\Python27-x64\python.exe
35 | WINDOWS_SDK_VERSION: v7.0
36 | PYTHON_HOME: C:\Python27-x64
37 | PYTHON_VERSION: '2.7'
38 | PYTHON_ARCH: '64'
39 |
40 | - TOXENV: 'py34-cover,codecov'
41 | TOXPYTHON: C:\Python34\python.exe
42 | PYTHON_HOME: C:\Python34
43 | PYTHON_VERSION: '3.4'
44 | PYTHON_ARCH: '32'
45 |
46 | - TOXENV: 'py34-cover,codecov'
47 | TOXPYTHON: C:\Python34-x64\python.exe
48 | WINDOWS_SDK_VERSION: v7.1
49 | PYTHON_HOME: C:\Python34-x64
50 | PYTHON_VERSION: '3.4'
51 | PYTHON_ARCH: '64'
52 |
53 | - TOXENV: 'py34-nocov'
54 | TOXPYTHON: C:\Python34\python.exe
55 | PYTHON_HOME: C:\Python34
56 | PYTHON_VERSION: '3.4'
57 | PYTHON_ARCH: '32'
58 |
59 | - TOXENV: 'py34-nocov'
60 | TOXPYTHON: C:\Python34-x64\python.exe
61 | WINDOWS_SDK_VERSION: v7.1
62 | PYTHON_HOME: C:\Python34-x64
63 | PYTHON_VERSION: '3.4'
64 | PYTHON_ARCH: '64'
65 |
66 | - TOXENV: 'py35-cover,codecov'
67 | TOXPYTHON: C:\Python35\python.exe
68 | PYTHON_HOME: C:\Python35
69 | PYTHON_VERSION: '3.5'
70 | PYTHON_ARCH: '32'
71 |
72 | - TOXENV: 'py35-cover,codecov'
73 | TOXPYTHON: C:\Python35-x64\python.exe
74 | PYTHON_HOME: C:\Python35-x64
75 | PYTHON_VERSION: '3.5'
76 | PYTHON_ARCH: '64'
77 |
78 | - TOXENV: 'py35-nocov'
79 | TOXPYTHON: C:\Python35\python.exe
80 | PYTHON_HOME: C:\Python35
81 | PYTHON_VERSION: '3.5'
82 | PYTHON_ARCH: '32'
83 |
84 | - TOXENV: 'py35-nocov'
85 | TOXPYTHON: C:\Python35-x64\python.exe
86 | PYTHON_HOME: C:\Python35-x64
87 | PYTHON_VERSION: '3.5'
88 | PYTHON_ARCH: '64'
89 |
90 | init:
91 | - ps: echo $env:TOXENV
92 | - ps: ls C:\Python*
93 | install:
94 | - python -u ci\appveyor-bootstrap.py
95 | - '%PYTHON_HOME%\Scripts\virtualenv --version'
96 | - '%PYTHON_HOME%\Scripts\easy_install --version'
97 | - '%PYTHON_HOME%\Scripts\pip --version'
98 | - '%PYTHON_HOME%\Scripts\tox --version'
99 | test_script:
100 | - '%WITH_COMPILER% %PYTHON_HOME%\Scripts\tox'
101 |
102 | on_failure:
103 | - ps: dir "env:"
104 | - ps: get-content .tox\*\log\*
105 | artifacts:
106 | - path: dist\*
107 |
108 | ### To enable remote debugging uncomment this (also, see: http://www.appveyor.com/docs/how-to/rdp-to-build-worker):
109 | # on_finish:
110 | # - ps: $blockRdp = $true; iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1'))
111 |
--------------------------------------------------------------------------------
/ci/appveyor-bootstrap.py:
--------------------------------------------------------------------------------
1 | """
2 | AppVeyor will at least have few Pythons around so there's no point of implementing a bootstrapper in PowerShell.
3 |
4 | This is a port of https://github.com/pypa/python-packaging-user-guide/blob/master/source/code/install.ps1
5 | with various fixes and improvements that just weren't feasible to implement in PowerShell.
6 | """
7 | from __future__ import print_function
8 | from os import environ
9 | from os.path import exists
10 | from subprocess import check_call
11 |
12 | try:
13 | from urllib.request import urlretrieve
14 | except ImportError:
15 | from urllib import urlretrieve
16 |
17 | BASE_URL = "https://www.python.org/ftp/python/"
18 | GET_PIP_URL = "https://bootstrap.pypa.io/get-pip.py"
19 | GET_PIP_PATH = "C:\get-pip.py"
20 | URLS = {
21 | ("2.7", "64"): BASE_URL + "2.7.10/python-2.7.10.amd64.msi",
22 | ("2.7", "32"): BASE_URL + "2.7.10/python-2.7.10.msi",
23 | # NOTE: no .msi installer for 3.3.6
24 | ("3.3", "64"): BASE_URL + "3.3.3/python-3.3.3.amd64.msi",
25 | ("3.3", "32"): BASE_URL + "3.3.3/python-3.3.3.msi",
26 | ("3.4", "64"): BASE_URL + "3.4.3/python-3.4.3.amd64.msi",
27 | ("3.4", "32"): BASE_URL + "3.4.3/python-3.4.3.msi",
28 | ("3.5", "64"): BASE_URL + "3.5.0/python-3.5.0-amd64.exe",
29 | ("3.5", "32"): BASE_URL + "3.5.0/python-3.5.0.exe",
30 | }
31 | INSTALL_CMD = {
32 | # Commands are allowed to fail only if they are not the last command. Eg: uninstall (/x) allowed to fail.
33 | "2.7": [["msiexec.exe", "/L*+!", "install.log", "/qn", "/x", "{path}"],
34 | ["msiexec.exe", "/L*+!", "install.log", "/qn", "/i", "{path}", "TARGETDIR={home}"]],
35 | "3.3": [["msiexec.exe", "/L*+!", "install.log", "/qn", "/x", "{path}"],
36 | ["msiexec.exe", "/L*+!", "install.log", "/qn", "/i", "{path}", "TARGETDIR={home}"]],
37 | "3.4": [["msiexec.exe", "/L*+!", "install.log", "/qn", "/x", "{path}"],
38 | ["msiexec.exe", "/L*+!", "install.log", "/qn", "/i", "{path}", "TARGETDIR={home}"]],
39 | "3.5": [["{path}", "/quiet", "TargetDir={home}"]],
40 | }
41 |
42 |
43 | def download_file(url, path):
44 | print("Downloading: {} (into {})".format(url, path))
45 | progress = [0, 0]
46 |
47 | def report(count, size, total):
48 | progress[0] = count * size
49 | if progress[0] - progress[1] > 1000000:
50 | progress[1] = progress[0]
51 | print("Downloaded {:,}/{:,} ...".format(progress[1], total))
52 |
53 | dest, _ = urlretrieve(url, path, reporthook=report)
54 | return dest
55 |
56 |
57 | def install_python(version, arch, home):
58 | print("Installing Python", version, "for", arch, "bit architecture to", home)
59 | if exists(home):
60 | return
61 |
62 | path = download_python(version, arch)
63 | print("Installing", path, "to", home)
64 | success = False
65 | for cmd in INSTALL_CMD[version]:
66 | cmd = [part.format(home=home, path=path) for part in cmd]
67 | print("Running:", " ".join(cmd))
68 | try:
69 | check_call(cmd)
70 | except Exception as exc:
71 | print("Failed command", cmd, "with:", exc)
72 | if exists("install.log"):
73 | with open("install.log") as fh:
74 | print(fh.read())
75 | else:
76 | success = True
77 | if success:
78 | print("Installation complete!")
79 | else:
80 | print("Installation failed")
81 |
82 |
83 | def download_python(version, arch):
84 | for _ in range(3):
85 | try:
86 | return download_file(URLS[version, arch], "installer.exe")
87 | except Exception as exc:
88 | print("Failed to download:", exc)
89 | print("Retrying ...")
90 |
91 |
92 | def install_pip(home):
93 | pip_path = home + "/Scripts/pip.exe"
94 | python_path = home + "/python.exe"
95 | if exists(pip_path):
96 | print("pip already installed.")
97 | else:
98 | print("Installing pip...")
99 | download_file(GET_PIP_URL, GET_PIP_PATH)
100 | print("Executing:", python_path, GET_PIP_PATH)
101 | check_call([python_path, GET_PIP_PATH])
102 |
103 |
104 | def install_packages(home, *packages):
105 | cmd = [home + "/Scripts/pip.exe", "install"]
106 | cmd.extend(packages)
107 | check_call(cmd)
108 |
109 |
110 | if __name__ == "__main__":
111 | install_python(environ['PYTHON_VERSION'], environ['PYTHON_ARCH'], environ['PYTHON_HOME'])
112 | install_pip(environ['PYTHON_HOME'])
113 | install_packages(environ['PYTHON_HOME'], "setuptools>=18.0.1", "wheel", "tox", "virtualenv>=13.1.0")
114 |
--------------------------------------------------------------------------------
/ci/appveyor-download.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | Use the AppVeyor API to download Windows artifacts.
4 |
5 | Taken from: https://bitbucket.org/ned/coveragepy/src/tip/ci/download_appveyor.py
6 | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
7 | # For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt
8 | """
9 | from __future__ import unicode_literals
10 |
11 | import argparse
12 | import os
13 | import requests
14 | import zipfile
15 |
16 |
17 | def make_auth_headers():
18 | """Make the authentication headers needed to use the Appveyor API."""
19 | path = os.path.expanduser("~/.appveyor.token")
20 | if not os.path.exists(path):
21 | raise RuntimeError(
22 | "Please create a file named `.appveyor.token` in your home directory. "
23 | "You can get the token from https://ci.appveyor.com/api-token"
24 | )
25 | with open(path) as f:
26 | token = f.read().strip()
27 |
28 | headers = {
29 | 'Authorization': 'Bearer {}'.format(token),
30 | }
31 | return headers
32 |
33 |
34 | def download_latest_artifacts(account_project, build_id):
35 | """Download all the artifacts from the latest build."""
36 | if build_id is None:
37 | url = "https://ci.appveyor.com/api/projects/{}".format(account_project)
38 | else:
39 | url = "https://ci.appveyor.com/api/projects/{}/build/{}".format(account_project, build_id)
40 | build = requests.get(url, headers=make_auth_headers()).json()
41 | jobs = build['build']['jobs']
42 | print(u"Build {0[build][version]}, {1} jobs: {0[build][message]}".format(build, len(jobs)))
43 |
44 | for job in jobs:
45 | name = job['name']
46 | print(u" {0}: {1[status]}, {1[artifactsCount]} artifacts".format(name, job))
47 |
48 | url = "https://ci.appveyor.com/api/buildjobs/{}/artifacts".format(job['jobId'])
49 | response = requests.get(url, headers=make_auth_headers())
50 | artifacts = response.json()
51 |
52 | for artifact in artifacts:
53 | is_zip = artifact['type'] == "Zip"
54 | filename = artifact['fileName']
55 | print(u" {0}, {1} bytes".format(filename, artifact['size']))
56 |
57 | url = "https://ci.appveyor.com/api/buildjobs/{}/artifacts/{}".format(job['jobId'], filename)
58 | download_url(url, filename, make_auth_headers())
59 |
60 | if is_zip:
61 | unpack_zipfile(filename)
62 | os.remove(filename)
63 |
64 |
65 | def ensure_dirs(filename):
66 | """Make sure the directories exist for `filename`."""
67 | dirname, _ = os.path.split(filename)
68 | if dirname and not os.path.exists(dirname):
69 | os.makedirs(dirname)
70 |
71 |
72 | def download_url(url, filename, headers):
73 | """Download a file from `url` to `filename`."""
74 | ensure_dirs(filename)
75 | response = requests.get(url, headers=headers, stream=True)
76 | if response.status_code == 200:
77 | with open(filename, 'wb') as f:
78 | for chunk in response.iter_content(16 * 1024):
79 | f.write(chunk)
80 | else:
81 | print(u" Error downloading {}: {}".format(url, response))
82 |
83 |
84 | def unpack_zipfile(filename):
85 | """Unpack a zipfile, using the names in the zip."""
86 | with open(filename, 'rb') as fzip:
87 | z = zipfile.ZipFile(fzip)
88 | for name in z.namelist():
89 | print(u" extracting {}".format(name))
90 | ensure_dirs(name)
91 | z.extract(name)
92 |
93 | parser = argparse.ArgumentParser(description='Download artifacts from AppVeyor.')
94 | parser.add_argument('--id',
95 | metavar='PROJECT_ID',
96 | default='omemo/python-omemo',
97 | help='Project ID in AppVeyor.')
98 | parser.add_argument('build',
99 | nargs='?',
100 | metavar='BUILD_ID',
101 | help='Build ID in AppVeyor. Eg: master-123')
102 |
103 | if __name__ == "__main__":
104 | # import logging
105 | # logging.basicConfig(level="DEBUG")
106 | args = parser.parse_args()
107 | download_latest_artifacts(args.id, args.build)
108 |
--------------------------------------------------------------------------------
/ci/appveyor-with-compiler.cmd:
--------------------------------------------------------------------------------
1 | :: To build extensions for 64 bit Python 3, we need to configure environment
2 | :: variables to use the MSVC 2010 C++ compilers from GRMSDKX_EN_DVD.iso of:
3 | :: MS Windows SDK for Windows 7 and .NET Framework 4 (SDK v7.1)
4 | ::
5 | :: To build extensions for 64 bit Python 2, we need to configure environment
6 | :: variables to use the MSVC 2008 C++ compilers from GRMSDKX_EN_DVD.iso of:
7 | :: MS Windows SDK for Windows 7 and .NET Framework 3.5 (SDK v7.0)
8 | ::
9 | :: 32 bit builds do not require specific environment configurations.
10 | ::
11 | :: Note: this script needs to be run with the /E:ON and /V:ON flags for the
12 | :: cmd interpreter, at least for (SDK v7.0)
13 | ::
14 | :: More details at:
15 | :: https://github.com/cython/cython/wiki/64BitCythonExtensionsOnWindows
16 | :: http://stackoverflow.com/a/13751649/163740
17 | ::
18 | :: Author: Olivier Grisel
19 | :: License: CC0 1.0 Universal: http://creativecommons.org/publicdomain/zero/1.0/
20 | SET COMMAND_TO_RUN=%*
21 | SET WIN_SDK_ROOT=C:\Program Files\Microsoft SDKs\Windows
22 | SET WIN_WDK="c:\Program Files (x86)\Windows Kits\10\Include\wdf"
23 | ECHO SDK: %WINDOWS_SDK_VERSION% ARCH: %PYTHON_ARCH%
24 |
25 |
26 | IF "%PYTHON_VERSION%"=="3.5" (
27 | IF EXIST %WIN_WDK% (
28 | REM See: https://connect.microsoft.com/VisualStudio/feedback/details/1610302/
29 | REN %WIN_WDK% 0wdf
30 | )
31 | GOTO main
32 | )
33 |
34 | IF "%PYTHON_ARCH%"=="32" (
35 | GOTO main
36 | )
37 |
38 | SET DISTUTILS_USE_SDK=1
39 | SET MSSdk=1
40 | "%WIN_SDK_ROOT%\%WINDOWS_SDK_VERSION%\Setup\WindowsSdkVer.exe" -q -version:%WINDOWS_SDK_VERSION%
41 | CALL "%WIN_SDK_ROOT%\%WINDOWS_SDK_VERSION%\Bin\SetEnv.cmd" /x64 /release
42 |
43 | :main
44 |
45 | ECHO Executing: %COMMAND_TO_RUN%
46 | CALL %COMMAND_TO_RUN% || EXIT 1
47 |
--------------------------------------------------------------------------------
/ci/bootstrap.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | from __future__ import absolute_import, print_function, unicode_literals
4 |
5 | import os
6 | import sys
7 | from os.path import exists
8 | from os.path import join
9 | from os.path import dirname
10 | from os.path import abspath
11 |
12 |
13 | if __name__ == "__main__":
14 | base_path = dirname(dirname(abspath(__file__)))
15 | print("Project path: {0}".format(base_path))
16 | env_path = join(base_path, ".tox", "bootstrap")
17 | if sys.platform == "win32":
18 | bin_path = join(env_path, "Scripts")
19 | else:
20 | bin_path = join(env_path, "bin")
21 | if not exists(env_path):
22 | import subprocess
23 | print("Making bootstrap env in: {0} ...".format(env_path))
24 | try:
25 | subprocess.check_call(["virtualenv", env_path])
26 | except Exception:
27 | subprocess.check_call([sys.executable, "-m", "virtualenv", env_path])
28 | print("Installing `jinja2` into bootstrap environment ...")
29 | subprocess.check_call([join(bin_path, "pip"), "install", "jinja2"])
30 | activate = join(bin_path, "activate_this.py")
31 | exec(compile(open(activate, "rb").read(), activate, "exec"), dict(__file__=activate))
32 |
33 | import jinja2
34 |
35 | import subprocess
36 |
37 |
38 | jinja = jinja2.Environment(
39 | loader=jinja2.FileSystemLoader(join(base_path, "ci", "templates")),
40 | trim_blocks=True,
41 | lstrip_blocks=True,
42 | keep_trailing_newline=True
43 | )
44 |
45 | tox_environments = [line.strip() for line in subprocess.check_output(['tox', '--listenvs']).splitlines()]
46 | tox_environments = [line for line in tox_environments if line not in ['clean', 'report', 'docs', 'check']]
47 |
48 |
49 | for name in os.listdir(join("ci", "templates")):
50 | with open(join(base_path, name), "w") as fh:
51 | fh.write(jinja.get_template(name).render(tox_environments=tox_environments))
52 | print("Wrote {}".format(name))
53 | print("DONE.")
54 |
--------------------------------------------------------------------------------
/ci/templates/.travis.yml:
--------------------------------------------------------------------------------
1 | language: python
2 | python: '3.5'
3 | sudo: false
4 | env:
5 | global:
6 | - LD_PRELOAD=/lib/x86_64-linux-gnu/libSegFault.so
7 | - SEGFAULT_SIGNALS=all
8 | matrix:
9 | - TOXENV=check
10 | {% for env in tox_environments %}{{ '' }}
11 | - TOXENV={{ env }}{% if 'cover' in env %},codecov{% endif -%}
12 | {% endfor %}
13 |
14 | before_install:
15 | - python --version
16 | - uname -a
17 | - lsb_release -a
18 | install:
19 | - pip install tox
20 | - virtualenv --version
21 | - easy_install --version
22 | - pip --version
23 | - tox --version
24 | script:
25 | - tox -v
26 | after_failure:
27 | - more .tox/log/* | cat
28 | - more .tox/*/log/* | cat
29 | before_cache:
30 | - rm -rf $HOME/.cache/pip/log
31 | cache:
32 | directories:
33 | - $HOME/.cache/pip
34 | notifications:
35 | email:
36 | on_success: never
37 | on_failure: always
38 |
--------------------------------------------------------------------------------
/ci/templates/appveyor.yml:
--------------------------------------------------------------------------------
1 | version: '{branch}-{build}'
2 | build: off
3 | cache:
4 | - '%LOCALAPPDATA%\pip\Cache'
5 | environment:
6 | global:
7 | WITH_COMPILER: 'cmd /E:ON /V:ON /C .\ci\appveyor-with-compiler.cmd'
8 | matrix:
9 | - TOXENV: check
10 | PYTHON_HOME: C:\Python27
11 | PYTHON_VERSION: '2.7'
12 | PYTHON_ARCH: '32'
13 |
14 | {% for env in tox_environments %}{% if env.startswith(('py27', 'py34', 'py35')) %}
15 | - TOXENV: '{{ env }}{% if 'cover' in env %},codecov{% endif %}'
16 | TOXPYTHON: C:\Python{{ env[2:4] }}\python.exe
17 | PYTHON_HOME: C:\Python{{ env[2:4] }}
18 | PYTHON_VERSION: '{{ env[2] }}.{{ env[3] }}'
19 | PYTHON_ARCH: '32'
20 |
21 | - TOXENV: '{{ env }}{% if 'cover' in env %},codecov{% endif %}'
22 | TOXPYTHON: C:\Python{{ env[2:4] }}-x64\python.exe
23 | {%- if env.startswith(('py2', 'py33', 'py34')) %}
24 |
25 | WINDOWS_SDK_VERSION: v7.{{ '1' if env.startswith('py3') else '0' }}
26 | {%- endif %}
27 |
28 | PYTHON_HOME: C:\Python{{ env[2:4] }}-x64
29 | PYTHON_VERSION: '{{ env[2] }}.{{ env[3] }}'
30 | PYTHON_ARCH: '64'
31 |
32 | {% endif %}{% endfor %}
33 | init:
34 | - ps: echo $env:TOXENV
35 | - ps: ls C:\Python*
36 | install:
37 | - python -u ci\appveyor-bootstrap.py
38 | - '%PYTHON_HOME%\Scripts\virtualenv --version'
39 | - '%PYTHON_HOME%\Scripts\easy_install --version'
40 | - '%PYTHON_HOME%\Scripts\pip --version'
41 | - '%PYTHON_HOME%\Scripts\tox --version'
42 | test_script:
43 | - '%WITH_COMPILER% %PYTHON_HOME%\Scripts\tox'
44 |
45 | on_failure:
46 | - ps: dir "env:"
47 | - ps: get-content .tox\*\log\*
48 | artifacts:
49 | - path: dist\*
50 |
51 | ### To enable remote debugging uncomment this (also, see: http://www.appveyor.com/docs/how-to/rdp-to-build-worker):
52 | # on_finish:
53 | # - ps: $blockRdp = $true; iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1'))
54 |
--------------------------------------------------------------------------------
/docs/authors.rst:
--------------------------------------------------------------------------------
1 | .. include:: ../AUTHORS.rst
2 |
--------------------------------------------------------------------------------
/docs/changelog.rst:
--------------------------------------------------------------------------------
1 | .. include:: ../CHANGELOG.rst
2 |
--------------------------------------------------------------------------------
/docs/conf.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import unicode_literals
3 |
4 | import os
5 |
6 |
7 | extensions = [
8 | 'sphinx.ext.autodoc',
9 | 'sphinx.ext.autosummary',
10 | 'sphinx.ext.todo',
11 | 'sphinx.ext.coverage',
12 | 'sphinx.ext.ifconfig',
13 | 'sphinx.ext.viewcode',
14 | 'sphinx.ext.napoleon',
15 | 'sphinx.ext.extlinks',
16 | ]
17 | if os.getenv('SPELLCHECK'):
18 | extensions += 'sphinxcontrib.spelling',
19 | spelling_show_suggestions = True
20 | spelling_lang = 'en_US'
21 |
22 | source_suffix = '.rst'
23 | master_doc = 'index'
24 | project = u'Python OMEMO Library'
25 | year = '2016'
26 | author = u'Bahtiar `kalkin-` Gadimov'
27 | copyright = '{0}, {1}'.format(year, author)
28 | version = release = u'0.1.0'
29 |
30 | pygments_style = 'trac'
31 | templates_path = ['.']
32 | extlinks = {
33 | 'issue': ('https://github.com/omemo/python-omemo/issues/%s', '#'),
34 | 'pr': ('https://github.com/omemo/python-omemo/pull/%s', 'PR #'),
35 | }
36 | # on_rtd is whether we are on readthedocs.org
37 | on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
38 |
39 | if not on_rtd: # only import and set the theme if we're building docs locally
40 | import sphinx_rtd_theme
41 | html_theme = 'sphinx_rtd_theme'
42 | html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
43 |
44 | html_use_smartypants = True
45 | html_last_updated_fmt = '%b %d, %Y'
46 | html_split_index = True
47 | html_sidebars = {
48 | '**': ['searchbox.html', 'globaltoc.html', 'sourcelink.html'],
49 | }
50 | html_short_title = '%s-%s' % (project, version)
51 |
52 | napoleon_use_ivar = True
53 | napoleon_use_rtype = False
54 | napoleon_use_param = False
55 |
--------------------------------------------------------------------------------
/docs/contributing.rst:
--------------------------------------------------------------------------------
1 | .. include:: ../CONTRIBUTING.rst
2 |
--------------------------------------------------------------------------------
/docs/index.rst:
--------------------------------------------------------------------------------
1 | ========
2 | Contents
3 | ========
4 |
5 | .. toctree::
6 | :maxdepth: 2
7 |
8 | readme
9 | installation
10 | usage
11 | xep-omemo
12 | reference/index
13 | contributing
14 | authors
15 | changelog
16 |
17 | Indices and tables
18 | ==================
19 |
20 | * :ref:`genindex`
21 | * :ref:`modindex`
22 | * :ref:`search`
23 |
24 |
--------------------------------------------------------------------------------
/docs/installation.rst:
--------------------------------------------------------------------------------
1 | ============
2 | Installation
3 | ============
4 |
5 | At the command line::
6 |
7 | pip install python-omemo
8 |
--------------------------------------------------------------------------------
/docs/readme.rst:
--------------------------------------------------------------------------------
1 | .. include:: ../README.rst
2 |
--------------------------------------------------------------------------------
/docs/reference/index.rst:
--------------------------------------------------------------------------------
1 | Reference
2 | =========
3 |
4 | .. toctree::
5 | :glob:
6 |
7 | omemo*
8 |
--------------------------------------------------------------------------------
/docs/reference/omemo.rst:
--------------------------------------------------------------------------------
1 | OmemoState
2 | ==========
3 |
4 | .. autoclass:: omemo.state.OmemoState
5 | :members:
6 | :undoc-members:
7 | :show-inheritance:
8 | :special-members:
9 |
--------------------------------------------------------------------------------
/docs/requirements.txt:
--------------------------------------------------------------------------------
1 | sphinx>=1.3
2 | -e .
3 |
--------------------------------------------------------------------------------
/docs/spelling_wordlist.txt:
--------------------------------------------------------------------------------
1 | builtin
2 | builtins
3 | classmethod
4 | staticmethod
5 | classmethods
6 | staticmethods
7 | args
8 | kwargs
9 | callstack
10 | Changelog
11 | Indices
12 |
--------------------------------------------------------------------------------
/docs/usage.rst:
--------------------------------------------------------------------------------
1 | =====
2 | Usage
3 | =====
4 |
5 | To use Python OMEMO Library in a project::
6 |
7 | import omemo
8 |
--------------------------------------------------------------------------------
/docs/xep-omemo.rst:
--------------------------------------------------------------------------------
1 | =====================
2 | XEP: OMEMO Encryption
3 | =====================
4 | Abstract::
5 | This specification defines a protocol for end-to-end encryption in
6 | one-on-one chats that may have multiple clients per account.
7 | Copyright::
8 | © 1999 - 2015 XMPP Standards Foundation. `SEE LEGAL NOTICES`.
9 | Status::
10 | ProtoXEP
11 | Type::
12 | Standards Track
13 | Version::
14 | 0.0.1
15 | Last Updated:
16 | 2015-10-25
17 |
18 | .. warning::
19 | WARNING: This document has not yet been accepted for consideration or
20 | approved in any official manner by the XMPP Standards Foundation, and this
21 | document is not yet an XMPP Extension Protocol (XEP). If this document is
22 | accepted as a XEP by the XMPP Council, it will be published at
23 | and announced on the
24 | mailing list.
25 |
26 | 1. Introduction
27 | ===============
28 | 1.1 Motivation
29 | --------------
30 | There are two main end-to-end encryption schemes in common use in the XMPP
31 | ecosystem, Off-the-Record (OTR) messaging (`Current Off-the_Record Messaging
32 | Usage (XEP-0364) `_) and OpenPGP
33 | (`Current Jabber OpenPGP Usage (XEP-0027)
34 | `_). OTR has significant usability
35 | drawbacks for inter-client mobility. As OTR sessions exist between exactly two
36 | clients, the chat history will not be synchronized across other clients of the
37 | involved parties. Furthermore, OTR chats are only possible if both participants
38 | are currently online, due to how the rolling key agreement scheme of OTR works.
39 | OpenPGP, while not suffering from these mobility issues, does not provide any
40 | kind of forward secrecy and is vulnerable to replay attacks. Additionally, PGP
41 | over XMPP uses a custom wireformat which is defined by convention rather than
42 | standardization, and involves quite a bit of external complexity.
43 |
44 | This XEP defines a protocol that leverages axolotl encryption to provide
45 | multi-end to multi-end encryption, allowing messages to be synchronized
46 | securely across multiple clients, even if some of them are offline.
47 |
48 | 1.2 Overview
49 | ------------
50 | The general idea behind this protocol is to maintain separate, long-standing
51 | axolotl-encrypted sessions with each device of each contact (as well as with
52 | each of our other devices), which are used as secure key transport channels. In
53 | this scheme, each message is encrypted with a fresh, randomly generated
54 | encryption key. An encrypted header is added to the message for each device that
55 | is supposed to receive it. These headers simply contain the key that the payload
56 | message is encrypted with, and they are seperately encrypted using the session
57 | corresponding to the counterpart device. The encrypted payload is sent together
58 | with the headers as a stanza. Individual recipient devices can decrypt
59 | the header item intended for them, and use the contained payload key to decrypt
60 | the payload message.
61 |
62 | As the encrypted payload is common to all recipients, it only has to be included
63 | once, reducing overhead. Furthermore, axolotl's transparent handling of messages
64 | that were lost or received out of order, as well as those sent while the
65 | recipient was offline, is maintained by this protocol. As a result, in
66 | combination with `Message Carbons (XEP-0280)
67 | `_ and `Message Archive Management
68 | (XEP-0313) `_, the desired property of
69 | inter-client history synchronization is achieved.
70 |
71 | OMEMO version 0 uses v3 messages of the axolotl protocol. Instead of an axolotl
72 | key server, PEP (`Personal Eventing Protocol (XEP-0163)
73 | `_) is used to publish key data.
74 |
75 | 2. Requirements
76 | ===============
77 | * Provide forward secrecy
78 | * Ensure chat messages can be deciphered by all (capable) clients of both
79 | * parties
80 | * Be usable regardless of the participants' online statuses
81 | * Provide a method to exchange auxilliary keying material. This
82 | * could for example be used to secure encrypted file transfers.
83 |
84 | 3. Glossary
85 | ===========
86 | 3.1 General Terms
87 | -----------------
88 | Device::
89 | A communication end point, i.e. a specific client instance
90 | OMEMO element::
91 | An `` element in the `urn:xmpp:omemo:0` namespace. Can be either
92 | MessageElement or a KeyTransportElement
93 | MessageElement::
94 | An OMEMO element that contains a chat message. Its ``, when
95 | decrypted, corresponds to a ``'s ``.
96 | KeyTransportElement::
97 | An OMEMO element that does not have a ``. It contains a fresh
98 | encryption key, which can be used for purposes external to this XEP.
99 | Bundle::
100 | A collection of publicly accessible data that can be used to build a
101 | session with a device, namely its public IdentityKey, a signed PreKey with
102 | corresponding signature, and a list of (single use) PreKeys.
103 | rid::
104 | The device id of the intended recipient of the containing ``
105 | sid::
106 | The device id of the sender of the containing OMEMO element
107 |
108 | 3.2 Axolotl-specific
109 | --------------------
110 | IdentityKey::
111 | Per-device public/private key pair used to authenticate communications
112 | PreKey::
113 | A Diffie-Hellman public key, published in bulk and ahead of time
114 | PreKeyWhisperMessage::
115 | An encrypted message that includes the initial key exchange. This is used
116 | to transparently build sessions with the first exchanged message.
117 | WhisperMessage::
118 | An encrypted message
119 |
120 |
121 | 4. Use Cases
122 | ============
123 | 4.1 Setup
124 | ---------
125 |
126 | The first thing that needs to happen if a client wants to start using OMEMO is
127 | they need to generate an IdentityKey and a Device ID. The IdentityKey is a
128 | Curve25519 public/private Key pair. The Device ID is a randomly generated
129 | integer between 1 and 2^31 - 1.
130 |
131 | 4.2 Discovering peer support
132 | ----------------------------
133 |
134 | In order to determine whether a given contact has devices that support OMEMO,
135 | the devicelist node in PEP is consulted. Devices MUST subscribe to
136 | `'urn:xmpp:omemo:0:devicelist` via PEP, so that they are informed whenever their
137 | contacts add a new device. They MUST cache the most up-to-date version of the
138 | devicelist.
139 |
140 | .. highlight:: xml
141 | *Example 1. Devicelist update received by subscribed clients*
142 | ::
143 |
147 |
148 |
149 | -
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 | 4.3 Announcing support
160 | ----------------------
161 |
162 | In order for other devices to be able to initiate a session with a given
163 | device, it first has to announce itself by adding its device ID to the
164 | devicelist PEP node.
165 |
166 | .. highlight:: xml
167 | *Example 2. Adding the own device ID to the list*
168 | ::
169 |
170 |
171 |
172 | -
173 |
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 | This step presents the risk of introducing a race condition: Two devices might
184 | simultaneously try to announce themselves, unaware of the other's existence.
185 | The second device would overwrite the first one. To mitigate this, devices MUST
186 | check that their own device ID is contained in the list whenever they receive a
187 | PEP update from their own account. If they have been removed, they MUST
188 | reannounce themselves.
189 |
190 | Furthermore, a device MUST announce it's IdentityKey, a signed PreKey, and a
191 | list of PreKeys in a separate, per-device PEP node. The list SHOULD contain 100
192 | PreKeys, but MUST contain no less than 20.
193 |
194 | .. highlight:: xml
195 | *Example 3. Announcing bundle information*
196 | ::
197 |
198 |
199 |
200 | -
201 |
202 |
203 | BASE64ENCODED...
204 |
205 |
206 | BASE64ENCODED...
207 |
208 |
209 | BASE64ENCODED...
210 |
211 |
212 |
213 | BASE64ENCODED...
214 |
215 |
216 | BASE64ENCODED...
217 |
218 |
219 | BASE64ENCODED...
220 |
221 |
222 |
223 |
224 |
225 |
226 |
227 |
228 |
229 | 4.4 Building a session
230 | ----------------------
231 |
232 | In order to build a session with a device, their bundle information is fetched.
233 |
234 | .. highlight:: xml
235 | *Example 4. Fetching a device's bundle information*
236 | ::
237 |
241 |
242 |
243 |
244 |
245 |
246 | A random preKeyPublic entry is selected, and used to build an axolotl session.
247 |
248 | 4.5 Sending a message
249 | ---------------------
250 |
251 | In order to send a chat message, its `` first has to be encrypted. The
252 | client MUST use fresh, randomly generated key/IV pairs with AES-128 in
253 | Galois/Counter Mode (GCM). For each intended recipient device, i.e. both own
254 | devices as well as devices associated with the contact, this key is encrypted
255 | using the corresponding long-standing axolotl session. Each encrypted payload
256 | key is tagged with the recipient device's ID. This is all serialized into a
257 | MessageElement, which is transmitted in a `` as follows:
258 |
259 | .. highlight:: xml
260 | *Example 5. Sending a message*
261 | ::
262 |
263 |
264 |
265 | BASE64ENCODED...
266 | BASE64ENCODED...
267 |
268 | BASE64ENCODED...
269 |
270 | BASE64ENCODED
271 |
272 |
273 |
274 |
275 | 4.6 Sending a key
276 | -----------------
277 |
278 | The client may wish to transmit keying material to the contact. This first has
279 | to be generated. The client MUST generate a fresh, randomly generated key/IV
280 | pair. For each intended recipient device, i.e. both own devices as well as
281 | devices associated with the contact, this key is encrypted using the
282 | corresponding long-standing axolotl session. Each encrypted payload key is
283 | tagged with the recipient device's ID. This is all serialized into a
284 | KeyTransportElement, omitting the `` as follows:
285 |
286 | .. highlight:: xml
287 | *Example 6. Sending a key*
288 | ::
289 |
290 |
291 | BASE64ENCODED...
292 | BASE64ENCODED...
293 |
294 | BASE64ENCODED...
295 |
296 |
297 |
298 | This KeyTransportElement can then be sent over any applicable transport mechanism.
299 |
300 | 4.7 Receiving a message
301 | -----------------------
302 |
303 | When an OMEMO element is received, the client MUST check whether there is a
304 | `` element with an rid attribute matching its own device ID. If this is
305 | not the case, the element MUST be silently discarded. If such an element
306 | exists, the client checks whether the element's contents are a
307 | PreKeyWhisperMessage.
308 |
309 | If this is the case, a new session is built from this received element. The
310 | client SHOULD then republish their bundle information, replacing the used
311 | PreKey, such that it won't be used again by a different client. If the client
312 | already has a session with the sender's device, it MUST replace this session
313 | with the newly built session. The client MUST delete the private key belonging
314 | to the PreKey after use.
315 |
316 | If the element's contents are a WhisperMessage, and the client has a session
317 | with the sender's device, it tries to decrypt the WhisperMessage using this
318 | session. If the decryption fails or if the element's contents are not a
319 | WhisperMessage either, the OMEMO element MUST be silently discarded.
320 |
321 | If the OMEMO element contains a ``, it is an OMEMO message element. The
322 | client tries to decrypt the base 64 encoded contents using the key extracted
323 | from the `` element. If the decryption fails, the client MUST silently
324 | discard the OMEMO message. If it succeeds, the decrypted contents are treated
325 | as the `` of the received message.
326 |
327 | If the OMEMO element does not contain a ``, the client has received a
328 | KeyTransportElement. The key extracted from the `` element can then be used
329 | for other purposes (e.g. encrypted file transfer).
330 |
331 | 5. Business Rules
332 | =================
333 |
334 | Before publishing a freshly generated Device ID for the first time, a device
335 | MUST check whether that Device ID already exists, and if so, generate a new
336 | one.
337 |
338 | Clients SHOULD NOT immediately fetch the bundle and build a session as soon as
339 | a new device is announced. Before the first message is exchanged, the contact
340 | does not know which PreKey has been used (or, in fact, that any PreKey was used
341 | at all). As they have not had a chance to remove the used PreKey from their
342 | bundle announcement, this could lead to collisions where both Alice and Bob
343 | pick the same PreKey to build a session with a specific device. As each PreKey
344 | SHOULD only be used once, the party that sends their initial
345 | PreKeyWhisperMessage later loses this race condition. This means that they
346 | think they have a valid session with the contact, when in reality their
347 | messages MAY be ignored by the other end. By postponing building sessions, the
348 | chance of such issues occurring can be drastically reduced. It is RECOMMENDED
349 | to construct sessions only immediately before sending a message.
350 |
351 | As there are no explicit error messages in this protocol, if a client does
352 | receive a PreKeyWhisperMessage using an invalid PreKey, they SHOULD respond
353 | with a KeyTransportElement, sent in a `` using a PreKeyWhisperMessage.
354 | By building a new session with the original sender this way, the invalid
355 | session of the original sender will get overwritten with this newly created,
356 | valid session.
357 |
358 | If a PreKeyWhisperMessage is received as part of a `Message Archive Management
359 | (XEP-0313) `_ catch-up and used to establish a new session with the sender,
360 | the client SHOULD postpone deletion of the private key corresponding to the
361 | used PreKey until after MAM catch-up is completed. If this is done, the client
362 | MUST then also send a KeyTransportMessage using a PreKeyWhisperMessage before
363 | sending any payloads using this session, to trigger re-keying. (as above) This
364 | practice can mitigate the previously mentioned race condition by preventing
365 | message loss.
366 |
367 | As the asynchronous nature of OMEMO allows decryption at a later time to
368 | currently offline devices client SHOULD include a `Message Processing Hints
369 | (XEP-0334) `_ `` hint in
370 | their OMEMO messages. Otherwise, server implementations of `Message Archive
371 | Management (XEP-0313) `_ will
372 | generally not retain OMEMO messages, since they do not contain a ``
373 |
374 | 6. Implementation Notes
375 | =======================
376 |
377 | For details on axoltol, see the specification and reference implementation.
378 |
379 | The axolotl library's reference implementation (and presumably its ports to
380 | various other platforms) uses a trust model that doesn't work very well with
381 | OMEMO. For this reason it may be desirable to have the library consider all
382 | keys trusted, effectively disabling its trust management. This makes it
383 | necessary to implement trust handling oneself.
384 |
385 | 7. Security Considerations
386 | ==========================
387 |
388 | Clients MUST NOT use a newly built session to transmit data without user
389 | intervention. If a client were to opportunistically start using sessions for
390 | sending without asking the user whether to trust a device first, an attacker
391 | could publish a fake device for this user, which would then receive copies of
392 | all messages sent by/to this user. A client MAY use such "not (yet) trusted"
393 | sessions for decryption of received messages, but in that case it SHOULD
394 | indicate the untrusted nature of such messages to the user.
395 |
396 | When prompting the user for a trust decision regarding a key, the client SHOULD
397 | present the user with a fingerprint in the form of a hex string, QR code, or
398 | other unique representation, such that it can be compared by the user.
399 |
400 | While it is RECOMMENDED that clients postpone private key deletion until after
401 | MAM catch-up and this standards mandates that clients MUST NOT use
402 | duplicate-PreKey sessions for sending, clients MAY delete such keys immediately
403 | for security reasons. For additional information on potential security impacts
404 | of this decision, refer to Menezes, Alfred, and Berkant Ustaoglu. "On reusing
405 | ephemeral keys in Diffie-Hellman key agreement protocols." International
406 | Journal of Applied Cryptography 2, no. 2 (2010): 154-158..
407 |
408 | In order to be able to handle out-of-order messages, the axolotl stack has to cache the keys belonging to "skipped" messages that have not been seen yet. It is up to the implementor to decide how long and how many of such keys to keep around.
409 | 8. IANA Considerations
410 |
411 | This document requires no interaction with the Internet Assigned Numbers Authority (IANA).
412 |
413 | 9. XMPP Registrar Considerations
414 | ================================
415 |
416 | 9.1 Protocol Namespaces
417 | -----------------------
418 |
419 | This specification defines the following XMPP namespaces:
420 |
421 | `urn:xmpp:omemo:0`
422 |
423 | The `XMPP Registrar `_ shall include the foregoing
424 | namespace in its registry at , as
425 | goverened by `XMPP Registrar Function (XEP-0053)
426 | `_.
427 |
428 | 9.2 Protocol Versioning
429 | -----------------------
430 |
431 | If the protocol defined in this specification undergoes a revision that is not
432 | fully backwards-compatible with an older version, the XMPP Registrar shall
433 | increment the protocol version number found at the end of the XML namespaces
434 | defined herein, as described in Section 4 of **XEP-0053**.
435 |
436 | 10. XML Schema
437 | ==============
438 | .. highlight:: xml
439 | *Xml Schema*
440 | ::
441 |
442 |
445 |
446 |
447 |
448 |
449 |
450 |
451 |
452 |
453 |
454 |
455 |
456 |
457 |
458 |
459 |
460 |
461 |
462 |
463 |
464 |
465 |
466 |
467 |
468 |
469 |
470 |
471 |
472 |
473 |
474 |
475 |
476 |
477 |
478 |
479 |
480 |
481 |
482 |
483 |
484 |
485 |
486 |
487 |
488 |
489 |
490 |
491 |
492 |
493 |
494 | 11. Acknowledgements
495 | ====================
496 |
497 | Big thanks to Daniel Gultsch for mentoring me during the development of this
498 | protocol. Thanks to Thijs Alkemade and Cornelius Aschermann for talking through
499 | some of the finer points of the protocol with me. And lastly I would also like
500 | to thank Sam Whited, Holger Weiss, and Florian Schmaus for their input on the
501 | standard.
502 |
503 | Appendices
504 | ===========
505 | Appendix A: Document Information
506 | --------------------------------
507 |
508 | Series::
509 | XEP
510 | Number::
511 | xxxx
512 | Publisher::
513 | XMPP Standards Foundation
514 | Status::
515 | ProtoXEP
516 | Type::
517 | Standards Track
518 | Version::
519 | 0.0.1
520 | Last Updated::
521 | 2015-10-25
522 | Approving Body::
523 | XMPP Council
524 | Dependencies::
525 | XMPP Core, XEP-0163
526 | Supersedes::
527 | None
528 | Superseded By::
529 | None
530 | Short Name::
531 | NOT_YET_ASSIGNED
532 | This document in other formats::
533 | XML PDF
534 | Appendix B: Author Information
535 | ------------------------------
536 | Andreas Straub
537 | ~~~~~~~~~~~~~~
538 |
539 | Email::
540 | andy@strb.org
541 | JabberID::
542 | andy@strb.org
543 |
544 | Appendix C: Legal Notices
545 | -------------------------
546 | Copyright
547 | ~~~~~~~~~
548 | This XMPP Extension Protocol is copyright (c) 1999 - 2014 by the XMPP Standards
549 | Foundation (XSF).
550 |
551 | Permissions
552 | ~~~~~~~~~~~
553 | Permission is hereby granted, free of charge, to any person obtaining a copy of
554 | this specification (the "Specification"), to make use of the Specification
555 | without restriction, including without limitation the rights to implement the
556 | Specification in a software program, deploy the Specification in a network
557 | service, and copy, modify, merge, publish, translate, distribute, sublicense,
558 | or sell copies of the Specification, and to permit persons to whom the
559 | Specification is furnished to do so, subject to the condition that the
560 | foregoing copyright notice and this permission notice shall be included in all
561 | copies or substantial portions of the Specification. Unless separate permission
562 | is granted, modified works that are redistributed shall not contain misleading
563 | information regarding the authors, title, number, or publisher of the
564 | Specification, and shall not claim endorsement of the modified works by the
565 | authors, any organization or project to which the authors belong, or the XMPP
566 | Standards Foundation.
567 |
568 | Disclaimer of Warranty
569 | ~~~~~~~~~~~~~~~~~~~~~~
570 |
571 | .. note::
572 | This Specification is provided on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. In no event shall the XMPP Standards Foundation or the authors of this Specification 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 Specification or the implementation, deployment, or other use of the Specification.
573 |
574 | Limitation of Liability
575 | ~~~~~~~~~~~~~~~~~~~~~~~
576 | In no event and under no legal theory, whether in tort (including negligence),
577 | contract, or otherwise, unless required by applicable law (such as deliberate
578 | and grossly negligent acts) or agreed to in writing, shall the XMPP Standards
579 | Foundation or any author of this Specification be liable for damages, including
580 | any direct, indirect, special, incidental, or consequential damages of any
581 | character arising out of the use or inability to use the Specification
582 | (including but not limited to damages for loss of goodwill, work stoppage,
583 | computer failure or malfunction, or any and all other commercial damages or
584 | losses), even if the XMPP Standards Foundation or such author has been advised
585 | of the possibility of such damages.
586 |
587 | IPR Conformance
588 | ~~~~~~~~~~~~~~~
589 | This XMPP Extension Protocol has been contributed in full conformance with the
590 | XSF's Intellectual Property Rights Policy (a copy of which may be found at
591 | or obtained by writing to XSF,
592 | P.O. Box 1641, Denver, CO 80201 USA).
593 |
594 | Appendix D: Relation to XMPP
595 | ----------------------------
596 |
597 | The Extensible Messaging and Presence Protocol (XMPP) is defined in the XMPP
598 | Core (RFC 6120) and XMPP IM (RFC 6121) specifications contributed by the XMPP
599 | Standards Foundation to the Internet Standards Process, which is managed by the
600 | Internet Engineering Task Force in accordance with RFC 2026. Any protocol
601 | defined in this document has been developed outside the Internet Standards
602 | Process and is to be understood as an extension to XMPP rather than as an
603 | evolution, development, or modification of XMPP itself.
604 |
605 | Appendix E: Discussion Venue
606 | ----------------------------
607 |
608 | The primary venue for discussion of XMPP Extension Protocols is the
609 | discussion list.
610 |
611 | Discussion on other xmpp.org discussion lists might also be appropriate; see
612 | for a complete list.
613 |
614 | Errata can be sent to .
615 |
616 | Appendix F: Requirements Conformance
617 | ------------------------------------
618 |
619 | The following requirements keywords as used in this document are to be
620 | interpreted as described in RFC 2119: "MUST", "SHALL", "REQUIRED"; "MUST NOT",
621 | "SHALL NOT"; "SHOULD", "RECOMMENDED"; "SHOULD NOT", "NOT RECOMMENDED"; "MAY",
622 | "OPTIONAL".
623 |
624 | Appendix G: Notes
625 | -----------------
626 |
627 | 1. XEP-0364: Current Off-the-Record Messaging Usage .
628 |
629 | 2. XEP-0027: Current Jabber OpenPGP Usage .
630 |
631 | 3. XEP-0280: Message Carbons .
632 |
633 | 4. XEP-0313: Message Archive Management .
634 |
635 | 5. XEP-0163: Personal Eventing Protocol .
636 |
637 | 6. XEP-0313: Message Archive Management .
638 |
639 | 7. XEP-0334: Message Processing Hints .
640 |
641 | 8. XEP-0313: Message Archive Management .
642 |
643 | 9. Menezes, Alfred, and Berkant Ustaoglu. "On reusing ephemeral keys in Diffie-Hellman key agreement protocols." International Journal of Applied Cryptography 2, no. 2 (2010): 154-158.
644 |
645 | 10. The XMPP Registrar maintains a list of reserved protocol namespaces as well as registries of parameters used in the context of XMPP extension protocols approved by the XMPP Standards Foundation. For further information, see .
646 |
647 | 11. XEP-0053: XMPP Registrar Function .
648 | Appendix H: Revision History
649 |
650 | Note: Older versions of this specification might be available at https://xmpp.org/extensions/attic/
651 | Version 0.0.1 (2015-10-25)
652 |
653 | First draft.
654 | (as)
655 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [bdist_wheel]
2 | universal = 1
3 |
4 | [aliases]
5 | release = register clean --all sdist bdist_wheel
6 |
7 | [flake8]
8 | max-line-length = 140
9 | exclude = tests/*,*/migrations/*,*/south_migrations/*
10 |
11 | [pytest]
12 | norecursedirs =
13 | .git
14 | .tox
15 | .env
16 | dist
17 | build
18 | south_migrations
19 | migrations
20 | python_files =
21 | test_*.py
22 | *_test.py
23 | tests.py
24 | addopts =
25 | -rxEfsw
26 | --strict
27 | --ignore=docs/conf.py
28 | --ignore=setup.py
29 | --ignore=ci
30 | --ignore=.eggs
31 | --doctest-modules
32 | --doctest-glob=\*.rst
33 | --tb=short
34 |
35 | [isort]
36 | force_single_line=True
37 | line_length=120
38 | known_first_party=omemo
39 | default_section=THIRDPARTY
40 | forced_separate=test_omemo
41 |
42 | [check-manifest]
43 | ignore =
44 | *.swp
45 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- encoding: utf-8 -*-
3 | from __future__ import absolute_import, print_function
4 |
5 | import io
6 | import re
7 | import platform
8 | from glob import glob
9 | from os.path import basename
10 | from os.path import dirname
11 | from os.path import join
12 | from os.path import splitext
13 |
14 | from setuptools import find_packages
15 | from setuptools import setup
16 |
17 | requirements = [
18 | 'python-axolotl>=0.1.7',
19 | 'protobuf>=3.0.0b2'
20 | ]
21 |
22 | if platform.python_implementation() == 'PyPy':
23 | requirements += ['pycrypto']
24 | else:
25 | requirements += ['cryptography>=1.1']
26 |
27 |
28 | def read(*names, **kwargs):
29 | return io.open(
30 | join(dirname(__file__), *names),
31 | encoding=kwargs.get('encoding', 'utf8')
32 | ).read()
33 |
34 |
35 | setup(
36 | name='python-omemo',
37 | version='0.1.0',
38 | license='GPLv3',
39 | description='This is an implementation o*OMEMO Multi-End Message and Object Encryption** in Python.',
40 | long_description='%s\n%s' % (
41 | re.compile('^.. start-badges.*^.. end-badges', re.M | re.S).sub('', read('README.rst')),
42 | re.sub(':[a-z]+:`~?(.*?)`', r'``\1``', read('CHANGELOG.rst'))
43 | ),
44 | author='Bahtiar `kalkin-` Gadimov',
45 | author_email='bahtiar@gadimov.de',
46 | url='https://github.com/kalkin/python-omemo',
47 | packages=find_packages('src'),
48 | package_dir={'': 'src'},
49 | py_modules=[splitext(basename(path))[0] for path in glob('src/*.py')],
50 | include_package_data=True,
51 | zip_safe=False,
52 | classifiers=[
53 | # complete classifier list: http://pypi.python.org/pypi?%3Aaction=list_classifiers
54 | 'Development Status :: 1 - Planning',
55 | 'Intended Audience :: Developers',
56 | 'License :: Other/Proprietary License',
57 | 'Operating System :: Unix',
58 | 'Operating System :: POSIX',
59 | 'Programming Language :: Python',
60 | 'Programming Language :: Python :: 2.7',
61 | 'Programming Language :: Python :: 3',
62 | 'Programming Language :: Python :: 3.3',
63 | 'Programming Language :: Python :: 3.4',
64 | 'Programming Language :: Python :: 3.5',
65 | 'Programming Language :: Python :: Implementation :: CPython',
66 | 'Programming Language :: Python :: Implementation :: PyPy',
67 | 'Topic :: Utilities',
68 | ],
69 | keywords=[
70 | # eg: 'keyword1', 'keyword2', 'keyword3',
71 | ],
72 | install_requires=requirements,
73 | extras_require={},
74 | )
75 |
--------------------------------------------------------------------------------
/src/.gitignore:
--------------------------------------------------------------------------------
1 | *.py[c|o]
2 | *.swp
3 |
--------------------------------------------------------------------------------
/src/.style.yapf:
--------------------------------------------------------------------------------
1 | [style]
2 | based_on_style = pep8
3 | align_closing_bracket_with_visual_indent = true
4 | join_multiple_lines = true
5 |
--------------------------------------------------------------------------------
/src/COPYING:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/src/omemo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/omemo/python-omemo/66f1814978ddc13c86fc3f5681c57449e1c01cf2/src/omemo.png
--------------------------------------------------------------------------------
/src/omemo/__init__.py:
--------------------------------------------------------------------------------
1 | __version__ = "0.1.0"
2 |
--------------------------------------------------------------------------------
/src/omemo/aes_gcm.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2015 Bahtiar `kalkin-` Gadimov
4 | #
5 | # This file is part of python-omemo library.
6 | #
7 | # The python-omemo library is free software: you can redistribute it and/or
8 | # modify it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or (at your
10 | # option) any later version.
11 | #
12 | # python-omemo is distributed in the hope that it will be useful, but WITHOUT ANY
13 | # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 | # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License along with
17 | # the python-omemo library. If not, see .
18 | #
19 |
20 | import os
21 | import sys
22 |
23 | from omemo.padding import padding_add
24 | from omemo.padding import padding_remove
25 |
26 | try:
27 | from omemo.aes_gcm_native import aes_decrypt
28 | from omemo.aes_gcm_native import aes_encrypt
29 | except ImportError:
30 | from omemo.aes_gcm_fallback import aes_decrypt
31 | from omemo.aes_gcm_fallback import aes_encrypt
32 |
33 |
34 | def encrypt(plaintext):
35 | key = os.urandom(16)
36 | iv = os.urandom(16)
37 | encoded_plaintext = padding_add(plaintext).encode('utf-8')
38 | return key, iv, aes_encrypt(key, iv, encoded_plaintext)
39 |
40 |
41 | def decrypt(key, iv, ciphertext):
42 | plaintext = padding_remove(aes_decrypt(key, iv, ciphertext).decode('utf-8'))
43 | if sys.version_info < (3, 0):
44 | return unicode(plaintext)
45 | else:
46 | return plaintext
47 |
48 |
49 | class NoValidSessions(Exception):
50 | pass
51 |
--------------------------------------------------------------------------------
/src/omemo/aes_gcm_fallback.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2014 Jonathan Zdziarski
4 | #
5 | # All rights reserved.
6 | #
7 | # Redistribution and use in source and binary forms, with or without
8 | # modification, are permitted provided that the following conditions are met:
9 | #
10 | # 1. Redistributions of source code must retain the above copyright notice, this
11 | # list of conditions and the following disclaimer.
12 | #
13 | # 2. Redistributions in binary form must reproduce the above copyright notice,
14 | # this list of conditions and the following disclaimer in the documentation
15 | # and/or other materials provided with the distribution.
16 | #
17 | # 3. Neither the name of the copyright holder nor the names of its contributors
18 | # may be used to endorse or promote products derived from this software without
19 | # specific prior written permission.
20 | #
21 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22 | # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 | # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
24 | # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
25 | # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 | # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27 | # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28 | # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29 | # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 |
32 | from struct import pack, unpack
33 |
34 | from Crypto.Cipher import AES
35 | from Crypto.Util import strxor
36 |
37 |
38 | def gcm_rightshift(vec):
39 | for x in range(15, 0, -1):
40 | c = vec[x] >> 1
41 | c |= (vec[x - 1] << 7) & 0x80
42 | vec[x] = c
43 | vec[0] >>= 1
44 | return vec
45 |
46 |
47 | def gcm_gf_mult(a, b):
48 | mask = [0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01]
49 | poly = [0x00, 0xe1]
50 |
51 | Z = [0] * 16
52 | V = [c for c in a]
53 |
54 | for x in range(128):
55 | if b[x >> 3] & mask[x & 7]:
56 | Z = [V[y] ^ Z[y] for y in range(16)]
57 | bit = V[15] & 1
58 | V = gcm_rightshift(V)
59 | V[0] ^= poly[bit]
60 | return Z
61 |
62 |
63 | def ghash(h, auth_data, data):
64 | u = (16 - len(data)) % 16
65 | v = (16 - len(auth_data)) % 16
66 |
67 | x = auth_data + chr(0) * v + data + chr(0) * u
68 | x += pack('>QQ', len(auth_data) * 8, len(data) * 8)
69 |
70 | y = [0] * 16
71 | vec_h = [ord(c) for c in h]
72 |
73 | for i in range(0, len(x), 16):
74 | block = [ord(c) for c in x[i:i + 16]]
75 | y = [y[j] ^ block[j] for j in range(16)]
76 | y = gcm_gf_mult(y, vec_h)
77 |
78 | return ''.join(chr(c) for c in y)
79 |
80 |
81 | def inc32(block):
82 | counter, = unpack('>L', block[12:])
83 | counter += 1
84 | return block[:12] + pack('>L', counter)
85 |
86 |
87 | def gctr(k, icb, plaintext):
88 | y = ''
89 | if len(plaintext) == 0:
90 | return y
91 |
92 | aes = AES.new(k)
93 | cb = icb
94 |
95 | for i in range(0, len(plaintext), aes.block_size):
96 | cb = inc32(cb)
97 | encrypted = aes.encrypt(cb)
98 | plaintext_block = plaintext[i:i + aes.block_size]
99 | y += strxor.strxor(plaintext_block, encrypted[:len(plaintext_block)])
100 |
101 | return y
102 |
103 |
104 | def gcm_decrypt(k, iv, encrypted, auth_data, tag):
105 | aes = AES.new(k)
106 | h = aes.encrypt(chr(0) * aes.block_size)
107 |
108 | if len(iv) == 12:
109 | y0 = iv + "\x00\x00\x00\x01"
110 | else:
111 | y0 = ghash(h, '', iv)
112 |
113 | decrypted = gctr(k, y0, encrypted)
114 | s = ghash(h, auth_data, encrypted)
115 |
116 | t = aes.encrypt(y0)
117 | T = strxor.strxor(s, t)
118 | if T != tag:
119 | raise ValueError('Decrypted data is invalid')
120 | else:
121 | return decrypted
122 |
123 |
124 | def gcm_encrypt(k, iv, plaintext, auth_data):
125 | aes = AES.new(k)
126 | h = aes.encrypt(chr(0) * aes.block_size)
127 |
128 | if len(iv) == 12:
129 | y0 = iv + "\x00\x00\x00\x01"
130 | else:
131 | y0 = ghash(h, '', iv)
132 |
133 | encrypted = gctr(k, y0, plaintext)
134 | s = ghash(h, auth_data, encrypted)
135 |
136 | t = aes.encrypt(y0)
137 | T = strxor.strxor(s, t)
138 | return (encrypted, T)
139 |
140 |
141 | def aes_encrypt(key, nonce, plaintext):
142 | """ Use AES128 GCM with the given key and iv to encrypt the payload. """
143 | c, t = gcm_encrypt(key, nonce, plaintext, '')
144 | result = c + t
145 | return result
146 |
147 |
148 | def aes_decrypt(key, nonce, payload):
149 | """ Use AES128 GCM with the given key and iv to decrypt the payload. """
150 | ciphertext = payload[:-16]
151 | mac = payload[-16:]
152 | return gcm_decrypt(key, nonce, ciphertext, '', mac)
153 |
--------------------------------------------------------------------------------
/src/omemo/aes_gcm_native.py:
--------------------------------------------------------------------------------
1 | from cryptography.hazmat.backends import default_backend
2 | from cryptography.hazmat.primitives.ciphers import Cipher
3 | from cryptography.hazmat.primitives.ciphers import algorithms
4 | from cryptography.hazmat.primitives.ciphers.modes import GCM
5 |
6 |
7 | def aes_decrypt(key, iv, payload):
8 | """ Use AES128 GCM with the given key and iv to decrypt the payload. """
9 | data = payload[:-16]
10 | tag = payload[-16:]
11 | backend = default_backend()
12 | decryptor = Cipher(
13 | algorithms.AES(key),
14 | GCM(iv, tag=tag),
15 | backend=backend).decryptor()
16 | return decryptor.update(data) + decryptor.finalize()
17 |
18 |
19 | def aes_encrypt(key, iv, plaintext):
20 | """ Use AES128 GCM with the given key and iv to encrypt the plaintext. """
21 | backend = default_backend()
22 | encryptor = Cipher(
23 | algorithms.AES(key),
24 | GCM(iv),
25 | backend=backend).encryptor()
26 | return encryptor.update(plaintext) + encryptor.finalize() + encryptor.tag
27 |
--------------------------------------------------------------------------------
/src/omemo/db_helpers.py:
--------------------------------------------------------------------------------
1 |
2 | def table_exists(db, name):
3 | """ Check if the specified table exists in the db. """
4 |
5 | q = """ SELECT name FROM sqlite_master
6 | WHERE type='table' AND name=?;
7 | """
8 | return db.execute(q, (name, )).fetchone() is not None
9 |
10 |
11 | def user_version(db):
12 | """ Return the value of PRAGMA user_version. """
13 | return db.execute('PRAGMA user_version').fetchone()[0]
14 |
--------------------------------------------------------------------------------
/src/omemo/encryption.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2015 Bahtiar `kalkin-` Gadimov
4 | # Copyright 2015 Daniel Gultsch
5 | #
6 | # This file is part of Gajim-OMEMO plugin.
7 | #
8 | # The Gajim-OMEMO plugin is free software: you can redistribute it and/or modify
9 | # it under the terms of the GNU General Public License as published by the Free
10 | # Software Foundation, either version 3 of the License, or (at your option) any
11 | # later version.
12 | #
13 | # Gajim-OMEMO is distributed in the hope that it will be useful, but WITHOUT ANY
14 | # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 | # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License along with
18 | # the Gajim-OMEMO plugin. If not, see .
19 | #
20 |
21 | from .db_helpers import table_exists, user_version
22 |
23 |
24 | class EncryptionState():
25 | """ Used to store if OMEMO is enabled or not between gajim restarts """
26 |
27 | def __init__(self, dbConn):
28 | """
29 | :type dbConn: Connection
30 | """
31 | self.dbConn = migrate(dbConn)
32 |
33 | def activate(self, jid):
34 | q = """INSERT OR REPLACE INTO encryption_state (jid, encryption)
35 | VALUES (?, 1) """
36 |
37 | c = self.dbConn.cursor()
38 | c.execute(q, (jid, ))
39 | self.dbConn.commit()
40 |
41 | def deactivate(self, jid):
42 | q = """INSERT OR REPLACE INTO encryption_state (jid, encryption)
43 | VALUES (?, 0)"""
44 |
45 | c = self.dbConn.cursor()
46 | c.execute(q, (jid, ))
47 | self.dbConn.commit()
48 |
49 | def is_active(self, jid):
50 | q = 'SELECT encryption FROM encryption_state where jid = ?;'
51 | c = self.dbConn.cursor()
52 | c.execute(q, (jid, ))
53 | result = c.fetchone()
54 | if result is None:
55 | return False
56 | return result[0] == 1
57 |
58 |
59 | def migrate(dbConn):
60 | """ Creates the encryption_state table and migrates it if needed.
61 | """
62 | if user_version(dbConn) == 0:
63 | create_table = """ CREATE TABLE encryption_state (
64 | id INTEGER PRIMARY KEY AUTOINCREMENT,
65 | jid TEXT UNIQUE,
66 | encryption INTEGER,
67 | timestamp NUMBER DEFAULT CURRENT_TIMESTAMP
68 | );
69 | """
70 |
71 | if table_exists(dbConn, 'encryption_state'):
72 | # Given a database which already has `encryption_state` and has
73 | # `user_version` 0, we assume the database needs migration and
74 | # migrate it to add an `ID INTEGER AUTOINCREMENT` column
75 | migrate_sql = """
76 | BEGIN TRANSACTION;
77 | ALTER TABLE encryption_state RENAME TO encryption_state_back;
78 | %s
79 | INSERT INTO encryption_state(jid, encryption, timestamp)
80 | SELECT jid, encryption, timestamp FROM encryption_state_back;
81 | DROP TABLE encryption_state_back;
82 | PRAGMA user_version=1;
83 | END TRANSACTION ;
84 | """ % (create_table)
85 | dbConn.executescript(migrate_sql)
86 | else:
87 | # The database has `user_version` 0 and has no `encryption_state
88 | # table, so crate it!
89 | dbConn.executescript(""" BEGIN TRANSACTION;
90 | %s
91 | PRAGMA user_version=1;
92 | END TRANSACTION;
93 | """ % (create_table))
94 |
95 | return dbConn
96 |
--------------------------------------------------------------------------------
/src/omemo/liteaxolotlstore.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2015 Tarek Galal
4 | #
5 | # This file is part of Gajim-OMEMO plugin.
6 | #
7 | # The Gajim-OMEMO plugin is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by the Free
9 | # Software Foundation, either version 3 of the License, or (at your option) any
10 | # later version.
11 | #
12 | # Gajim-OMEMO is distributed in the hope that it will be useful, but WITHOUT ANY
13 | # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 | # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License along with
17 | # the Gajim-OMEMO plugin. If not, see .
18 | #
19 |
20 | import logging
21 |
22 | from axolotl.state.axolotlstore import AxolotlStore
23 | from axolotl.util.keyhelper import KeyHelper
24 |
25 | from .liteidentitykeystore import LiteIdentityKeyStore
26 | from .liteprekeystore import LitePreKeyStore
27 | from .litesessionstore import LiteSessionStore
28 | from .litesignedprekeystore import LiteSignedPreKeyStore
29 | from .encryption import EncryptionState
30 |
31 | log = logging.getLogger('omemo')
32 |
33 | DEFAULT_PREKEY_AMOUNT = 100
34 |
35 |
36 | class LiteAxolotlStore(AxolotlStore):
37 | def __init__(self, connection):
38 | try:
39 | connection.text_factory = bytes
40 | except(AttributeError):
41 | raise AssertionError('Expected a sqlite3.Connection got ' +
42 | str(connection))
43 | self.identityKeyStore = LiteIdentityKeyStore(connection)
44 | self.preKeyStore = LitePreKeyStore(connection)
45 | self.signedPreKeyStore = LiteSignedPreKeyStore(connection)
46 | self.sessionStore = LiteSessionStore(connection)
47 | self.encryptionStore = EncryptionState(connection)
48 |
49 | if not self.getLocalRegistrationId():
50 | log.info("Generating Axolotl keys")
51 | self._generate_axolotl_keys()
52 |
53 | def _generate_axolotl_keys(self):
54 | identityKeyPair = KeyHelper.generateIdentityKeyPair()
55 | registrationId = KeyHelper.generateRegistrationId()
56 | preKeys = KeyHelper.generatePreKeys(KeyHelper.getRandomSequence(),
57 | DEFAULT_PREKEY_AMOUNT)
58 | self.storeLocalData(registrationId, identityKeyPair)
59 |
60 | for preKey in preKeys:
61 | self.storePreKey(preKey.getId(), preKey)
62 |
63 | def getIdentityKeyPair(self):
64 | return self.identityKeyStore.getIdentityKeyPair()
65 |
66 | def storeLocalData(self, registrationId, identityKeyPair):
67 | self.identityKeyStore.storeLocalData(registrationId, identityKeyPair)
68 |
69 | def getLocalRegistrationId(self):
70 | return self.identityKeyStore.getLocalRegistrationId()
71 |
72 | def saveIdentity(self, recepientId, identityKey):
73 | self.identityKeyStore.saveIdentity(recepientId, identityKey)
74 |
75 | def isTrustedIdentity(self, recepientId, identityKey):
76 | return self.identityKeyStore.isTrustedIdentity(recepientId,
77 | identityKey)
78 |
79 | def loadPreKey(self, preKeyId):
80 | return self.preKeyStore.loadPreKey(preKeyId)
81 |
82 | def loadPreKeys(self):
83 | return self.preKeyStore.loadPendingPreKeys()
84 |
85 | def storePreKey(self, preKeyId, preKeyRecord):
86 | self.preKeyStore.storePreKey(preKeyId, preKeyRecord)
87 |
88 | def containsPreKey(self, preKeyId):
89 | return self.preKeyStore.containsPreKey(preKeyId)
90 |
91 | def removePreKey(self, preKeyId):
92 | self.preKeyStore.removePreKey(preKeyId)
93 |
94 | def loadSession(self, recepientId, deviceId):
95 | return self.sessionStore.loadSession(recepientId, deviceId)
96 |
97 | def getDeviceTuples(self):
98 | return self.sessionStore.getDeviceTuples()
99 |
100 | def getSubDeviceSessions(self, recepientId):
101 | # TODO Reuse this
102 | return self.sessionStore.getSubDeviceSessions(recepientId)
103 |
104 | def storeSession(self, recepientId, deviceId, sessionRecord):
105 | self.sessionStore.storeSession(recepientId, deviceId, sessionRecord)
106 |
107 | def containsSession(self, recepientId, deviceId):
108 | return self.sessionStore.containsSession(recepientId, deviceId)
109 |
110 | def deleteSession(self, recepientId, deviceId):
111 | self.sessionStore.deleteSession(recepientId, deviceId)
112 |
113 | def deleteAllSessions(self, recepientId):
114 | self.sessionStore.deleteAllSessions(recepientId)
115 |
116 | def loadSignedPreKey(self, signedPreKeyId):
117 | return self.signedPreKeyStore.loadSignedPreKey(signedPreKeyId)
118 |
119 | def loadSignedPreKeys(self):
120 | return self.signedPreKeyStore.loadSignedPreKeys()
121 |
122 | def storeSignedPreKey(self, signedPreKeyId, signedPreKeyRecord):
123 | self.signedPreKeyStore.storeSignedPreKey(signedPreKeyId,
124 | signedPreKeyRecord)
125 |
126 | def containsSignedPreKey(self, signedPreKeyId):
127 | return self.signedPreKeyStore.containsSignedPreKey(signedPreKeyId)
128 |
129 | def removeSignedPreKey(self, signedPreKeyId):
130 | self.signedPreKeyStore.removeSignedPreKey(signedPreKeyId)
131 |
--------------------------------------------------------------------------------
/src/omemo/liteidentitykeystore.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2015 Tarek Galal
4 | #
5 | # This file is part of Gajim-OMEMO plugin.
6 | #
7 | # The Gajim-OMEMO plugin is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by the Free
9 | # Software Foundation, either version 3 of the License, or (at your option) any
10 | # later version.
11 | #
12 | # Gajim-OMEMO is distributed in the hope that it will be useful, but WITHOUT ANY
13 | # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 | # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License along with
17 | # the Gajim-OMEMO plugin. If not, see .
18 | #
19 |
20 | from axolotl.ecc.djbec import DjbECPrivateKey, DjbECPublicKey
21 | from axolotl.identitykey import IdentityKey
22 | from axolotl.identitykeypair import IdentityKeyPair
23 | from axolotl.state.identitykeystore import IdentityKeyStore
24 |
25 |
26 | class LiteIdentityKeyStore(IdentityKeyStore):
27 | def __init__(self, dbConn):
28 | """
29 | :type dbConn: Connection
30 | """
31 | self.dbConn = dbConn
32 | dbConn.execute(
33 | "CREATE TABLE IF NOT EXISTS identities (" +
34 | "_id INTEGER PRIMARY KEY AUTOINCREMENT," + "recipient_id TEXT," +
35 | "registration_id INTEGER, public_key BLOB, private_key BLOB," +
36 | "next_prekey_id NUMBER, timestamp NUMBER, trust NUMBER);")
37 |
38 | def getIdentityKeyPair(self):
39 | q = "SELECT public_key, private_key FROM identities " + \
40 | "WHERE recipient_id = -1"
41 | c = self.dbConn.cursor()
42 | c.execute(q)
43 | result = c.fetchone()
44 |
45 | publicKey, privateKey = result
46 | return IdentityKeyPair(
47 | IdentityKey(DjbECPublicKey(publicKey[1:])),
48 | DjbECPrivateKey(privateKey))
49 |
50 | def getLocalRegistrationId(self):
51 | q = "SELECT registration_id FROM identities WHERE recipient_id = -1"
52 | c = self.dbConn.cursor()
53 | c.execute(q)
54 | result = c.fetchone()
55 | return result[0] if result else None
56 |
57 | def storeLocalData(self, registrationId, identityKeyPair):
58 | q = "INSERT INTO identities( " + \
59 | "recipient_id, registration_id, public_key, private_key) " + \
60 | "VALUES(-1, ?, ?, ?)"
61 | c = self.dbConn.cursor()
62 | c.execute(q,
63 | (registrationId,
64 | identityKeyPair.getPublicKey().getPublicKey().serialize(),
65 | identityKeyPair.getPrivateKey().serialize()))
66 |
67 | self.dbConn.commit()
68 |
69 | def saveIdentity(self, recipientId, identityKey):
70 | q = "INSERT INTO identities (recipient_id, public_key) VALUES(?, ?)"
71 | c = self.dbConn.cursor()
72 | c.execute(q, (recipientId, identityKey.getPublicKey().serialize()))
73 | self.dbConn.commit()
74 |
75 | def isTrustedIdentity(self, recipientId, identityKey):
76 | return True
77 |
--------------------------------------------------------------------------------
/src/omemo/liteprekeystore.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2015 Tarek Galal
4 | #
5 | # This file is part of Gajim-OMEMO plugin.
6 | #
7 | # The Gajim-OMEMO plugin is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by the Free
9 | # Software Foundation, either version 3 of the License, or (at your option) any
10 | # later version.
11 | #
12 | # Gajim-OMEMO is distributed in the hope that it will be useful, but WITHOUT ANY
13 | # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 | # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License along with
17 | # the Gajim-OMEMO plugin. If not, see .
18 | #
19 |
20 | from axolotl.state.prekeyrecord import PreKeyRecord
21 | from axolotl.state.prekeystore import PreKeyStore
22 |
23 |
24 | class LitePreKeyStore(PreKeyStore):
25 | def __init__(self, dbConn):
26 | """
27 | :type dbConn: Connection
28 | """
29 | self.dbConn = dbConn
30 | dbConn.execute("CREATE TABLE IF NOT EXISTS prekeys(" +
31 | "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
32 | "prekey_id INTEGER UNIQUE, sent_to_server BOOLEAN, " +
33 | " record BLOB);")
34 |
35 | def loadPreKey(self, preKeyId):
36 | q = "SELECT record FROM prekeys WHERE prekey_id = ?"
37 |
38 | cursor = self.dbConn.cursor()
39 | cursor.execute(q, (preKeyId, ))
40 |
41 | result = cursor.fetchone()
42 | if not result:
43 | raise Exception("No such prekeyRecord!")
44 |
45 | return PreKeyRecord(serialized=result[0])
46 |
47 | def loadPendingPreKeys(self):
48 | q = "SELECT record FROM prekeys"
49 | cursor = self.dbConn.cursor()
50 | cursor.execute(q)
51 | result = cursor.fetchall()
52 |
53 | return [PreKeyRecord(serialized=r[0]) for r in result]
54 |
55 | def storePreKey(self, preKeyId, preKeyRecord):
56 | # self.removePreKey(preKeyId)
57 | q = "INSERT INTO prekeys (prekey_id, record) VALUES(?,?)"
58 | cursor = self.dbConn.cursor()
59 | cursor.execute(q, (preKeyId, preKeyRecord.serialize()))
60 | self.dbConn.commit()
61 |
62 | def containsPreKey(self, preKeyId):
63 | q = "SELECT record FROM prekeys WHERE prekey_id = ?"
64 | cursor = self.dbConn.cursor()
65 | cursor.execute(q, (preKeyId, ))
66 | return cursor.fetchone() is not None
67 |
68 | def removePreKey(self, preKeyId):
69 | q = "DELETE FROM prekeys WHERE prekey_id = ?"
70 | cursor = self.dbConn.cursor()
71 | cursor.execute(q, (preKeyId, ))
72 | self.dbConn.commit()
73 |
--------------------------------------------------------------------------------
/src/omemo/litesessionstore.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2015 Tarek Galal
4 | #
5 | # This file is part of Gajim-OMEMO plugin.
6 | #
7 | # The Gajim-OMEMO plugin is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by the Free
9 | # Software Foundation, either version 3 of the License, or (at your option) any
10 | # later version.
11 | #
12 | # Gajim-OMEMO is distributed in the hope that it will be useful, but WITHOUT ANY
13 | # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 | # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License along with
17 | # the Gajim-OMEMO plugin. If not, see .
18 | #
19 |
20 | from axolotl.state.sessionrecord import SessionRecord
21 | from axolotl.state.sessionstore import SessionStore
22 |
23 |
24 | class LiteSessionStore(SessionStore):
25 | def __init__(self, dbConn):
26 | """
27 | :type dbConn: Connection
28 | """
29 | self.dbConn = dbConn
30 | dbConn.execute("CREATE TABLE IF NOT EXISTS sessions (" +
31 | "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
32 | "recipient_id TEXT," + "device_id INTEGER," +
33 | "record BLOB," + "timestamp INTEGER, " +
34 | "UNIQUE(recipient_id, device_id));")
35 |
36 | def loadSession(self, recipientId, deviceId):
37 | q = "SELECT record FROM sessions WHERE recipient_id = ? AND device_id = ?"
38 | c = self.dbConn.cursor()
39 | c.execute(q, (recipientId, deviceId))
40 | result = c.fetchone()
41 |
42 | if result:
43 | return SessionRecord(serialized=result[0])
44 | else:
45 | return SessionRecord()
46 |
47 | def getSubDeviceSessions(self, recipientId):
48 | q = "SELECT device_id from sessions WHERE recipient_id = ?"
49 | c = self.dbConn.cursor()
50 | c.execute(q, (recipientId, ))
51 | result = c.fetchall()
52 |
53 | deviceIds = [r[0] for r in result]
54 | return deviceIds
55 |
56 | def getDeviceTuples(self):
57 | q = "SELECT recipient_id, device_id from sessions"
58 | c = self.dbConn.cursor()
59 | result = []
60 | for row in c.execute(q):
61 | result.append((row[0], row[1]))
62 | return result
63 |
64 | def storeSession(self, recipientId, deviceId, sessionRecord):
65 | self.deleteSession(recipientId, deviceId)
66 |
67 | q = "INSERT INTO sessions(recipient_id, device_id, record) VALUES(?,?,?)"
68 | c = self.dbConn.cursor()
69 | c.execute(q, (recipientId, deviceId, sessionRecord.serialize()))
70 | self.dbConn.commit()
71 |
72 | def containsSession(self, recipientId, deviceId):
73 | q = "SELECT record FROM sessions WHERE recipient_id = ? AND device_id = ?"
74 | c = self.dbConn.cursor()
75 | c.execute(q, (recipientId, deviceId))
76 | result = c.fetchone()
77 |
78 | return result is not None
79 |
80 | def deleteSession(self, recipientId, deviceId):
81 | q = "DELETE FROM sessions WHERE recipient_id = ? AND device_id = ?"
82 | self.dbConn.cursor().execute(q, (recipientId, deviceId))
83 | self.dbConn.commit()
84 |
85 | def deleteAllSessions(self, recipientId):
86 | q = "DELETE FROM sessions WHERE recipient_id = ?"
87 | self.dbConn.cursor().execute(q, (recipientId, ))
88 | self.dbConn.commit()
89 |
--------------------------------------------------------------------------------
/src/omemo/litesignedprekeystore.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2015 Tarek Galal
4 | #
5 | # This file is part of Gajim-OMEMO plugin.
6 | #
7 | # The Gajim-OMEMO plugin is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by the Free
9 | # Software Foundation, either version 3 of the License, or (at your option) any
10 | # later version.
11 | #
12 | # Gajim-OMEMO is distributed in the hope that it will be useful, but WITHOUT ANY
13 | # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 | # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License along with
17 | # the Gajim-OMEMO plugin. If not, see .
18 | #
19 |
20 | from axolotl.invalidkeyidexception import InvalidKeyIdException
21 | from axolotl.state.signedprekeyrecord import SignedPreKeyRecord
22 | from axolotl.state.signedprekeystore import SignedPreKeyStore
23 |
24 |
25 | class LiteSignedPreKeyStore(SignedPreKeyStore):
26 | def __init__(self, dbConn):
27 | """
28 | :type dbConn: Connection
29 | """
30 | self.dbConn = dbConn
31 | dbConn.execute(
32 | "CREATE TABLE IF NOT EXISTS signed_prekeys (" +
33 | "_id INTEGER PRIMARY" + " KEY AUTOINCREMENT," +
34 | "prekey_id INTEGER UNIQUE, timestamp INTEGER, record BLOB);")
35 |
36 | def loadSignedPreKey(self, signedPreKeyId):
37 | q = "SELECT record FROM signed_prekeys WHERE prekey_id = ?"
38 |
39 | cursor = self.dbConn.cursor()
40 | cursor.execute(q, (signedPreKeyId, ))
41 |
42 | result = cursor.fetchone()
43 | if not result:
44 | raise InvalidKeyIdException("No such signedprekeyrecord! %s " %
45 | signedPreKeyId)
46 |
47 | return SignedPreKeyRecord(serialized=result[0])
48 |
49 | def loadSignedPreKeys(self):
50 | q = "SELECT record FROM signed_prekeys"
51 |
52 | cursor = self.dbConn.cursor()
53 | cursor.execute(q, )
54 | result = cursor.fetchall()
55 | results = []
56 | for row in result:
57 | results.append(SignedPreKeyRecord(serialized=row[0]))
58 |
59 | return results
60 |
61 | def storeSignedPreKey(self, signedPreKeyId, signedPreKeyRecord):
62 | q = "INSERT INTO signed_prekeys (prekey_id, record) VALUES(?,?)"
63 | cursor = self.dbConn.cursor()
64 | cursor.execute(q, (signedPreKeyId, signedPreKeyRecord.serialize()))
65 | self.dbConn.commit()
66 |
67 | def containsSignedPreKey(self, signedPreKeyId):
68 | q = "SELECT record FROM signed_prekeys WHERE prekey_id = ?"
69 | cursor = self.dbConn.cursor()
70 | cursor.execute(q, (signedPreKeyId, ))
71 | return cursor.fetchone() is not None
72 |
73 | def removeSignedPreKey(self, signedPreKeyId):
74 | q = "DELETE FROM signed_prekeys WHERE prekey_id = ?"
75 | cursor = self.dbConn.cursor()
76 | cursor.execute(q, (signedPreKeyId, ))
77 | self.dbConn.commit()
78 |
--------------------------------------------------------------------------------
/src/omemo/padding.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2016 Bob Mottram
4 | #
5 | # This file is part of python-omemo library.
6 | #
7 | # The python-omemo library is free software: you can redistribute it and/or
8 | # modify it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or (at your
10 | # option) any later version.
11 | #
12 | # python-omemo is distributed in the hope that it will be useful, but WITHOUT ANY
13 | # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 | # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License along with
17 | # the python-omemo library. If not, see .
18 | #
19 |
20 | ''' Helper functions for padding plaintext '''
21 |
22 | from random import randint
23 |
24 |
25 | def padding_add(plaintext):
26 | ''' Pad the text to a minimum of 255 characters, by adding random amount of
27 | spaces before and after plaintext.
28 | '''
29 | # get the padding length
30 | pad = 256
31 | while len(plaintext) > pad:
32 | pad = pad * 2
33 |
34 | # create padding strings
35 | pad_start = ' ' * randint(0, pad - len(plaintext))
36 | pad_end = ' ' * (pad - len(pad_start) - len(plaintext))
37 |
38 | # return padded plaintext
39 | return pad_start + plaintext + pad_end
40 |
41 |
42 | def padding_remove(plaintext):
43 | ''' Strip the padding from plaintext '''
44 | return plaintext.strip(' ')
45 |
--------------------------------------------------------------------------------
/src/omemo/state.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2015 Bahtiar `kalkin-` Gadimov
4 | #
5 | # This file is part of Gajim-OMEMO plugin.
6 | #
7 | # The Gajim-OMEMO plugin is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by the Free
9 | # Software Foundation, either version 3 of the License, or (at your option) any
10 | # later version.
11 | #
12 | # Gajim-OMEMO is distributed in the hope that it will be useful, but WITHOUT ANY
13 | # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 | # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License along with
17 | # the Gajim-OMEMO plugin. If not, see .
18 | #
19 |
20 | import logging
21 | import random
22 | from base64 import b64encode, b64decode
23 |
24 | from axolotl.ecc.djbec import DjbECPublicKey
25 | from axolotl.identitykey import IdentityKey
26 | from axolotl.duplicatemessagexception import DuplicateMessageException
27 | from axolotl.invalidmessageexception import InvalidMessageException
28 | from axolotl.invalidversionexception import InvalidVersionException
29 | from axolotl.nosessionexception import NoSessionException
30 | from axolotl.protocol.prekeywhispermessage import PreKeyWhisperMessage
31 | from axolotl.protocol.whispermessage import WhisperMessage
32 | from axolotl.sessionbuilder import SessionBuilder
33 | from axolotl.sessioncipher import SessionCipher
34 | from axolotl.state.prekeybundle import PreKeyBundle
35 | from axolotl.util.keyhelper import KeyHelper
36 |
37 | from .aes_gcm import NoValidSessions, decrypt, encrypt
38 | from .liteaxolotlstore import LiteAxolotlStore
39 |
40 | log = logging.getLogger('omemo')
41 |
42 |
43 | # Monkey patch axolotl SessionCipher
44 | def s_decryptMsg(self, ciphertext):
45 | """
46 | :type ciphertext: WhisperMessage
47 | """
48 | if not self.sessionStore.containsSession(self.recipientId, self.deviceId):
49 | raise NoSessionException("No session for: %s, %s" %
50 | (self.recipientId, self.deviceId))
51 |
52 | sessionRecord = self.sessionStore.loadSession(self.recipientId,
53 | self.deviceId)
54 | plaintext = self.decryptWithSessionRecord(sessionRecord, ciphertext)
55 |
56 | self.sessionStore.storeSession(self.recipientId, self.deviceId,
57 | sessionRecord)
58 |
59 | return plaintext
60 |
61 |
62 | def s_decryptPkmsg(self, ciphertext):
63 | """
64 | :type ciphertext: PreKeyWhisperMessage
65 | """
66 | sessionRecord = self.sessionStore.loadSession(self.recipientId,
67 | self.deviceId)
68 | unsignedPreKeyId = self.sessionBuilder.process(sessionRecord, ciphertext)
69 | plaintext = self.decryptWithSessionRecord(sessionRecord,
70 | ciphertext.getWhisperMessage())
71 |
72 | self.sessionStore.storeSession(self.recipientId, self.deviceId,
73 | sessionRecord)
74 |
75 | if unsignedPreKeyId is not None:
76 | self.preKeyStore.removePreKey(unsignedPreKeyId)
77 |
78 | return plaintext
79 |
80 |
81 | SessionCipher.decryptMsg = s_decryptMsg
82 | SessionCipher.decryptPkmsg = s_decryptPkmsg
83 |
84 |
85 | class OmemoState:
86 | def __init__(self, own_jid, connection):
87 | """ Instantiates an OmemoState object.
88 |
89 | :param connection: an :py:class:`sqlite3.Connection`
90 | """
91 | self.session_ciphers = {}
92 | self.own_jid = own_jid
93 | self.device_ids = {}
94 | self.own_devices = []
95 | self.store = LiteAxolotlStore(connection)
96 | self.encryption = self.store.encryptionStore
97 | for jid, device_id in self.store.getDeviceTuples():
98 | if jid != own_jid:
99 | self.add_device(jid, device_id)
100 |
101 | log.debug(self.own_jid + ': devices after boot:'+str(self.device_ids))
102 |
103 | def build_session(self, recipient_id, device_id, bundle_dict):
104 | sessionBuilder = SessionBuilder(self.store, self.store, self.store,
105 | self.store, recipient_id, device_id)
106 |
107 | registration_id = self.store.getLocalRegistrationId()
108 | preKey = random.SystemRandom().choice(bundle_dict['prekeys'])
109 | bundle_dict['preKeyId'] = preKey[0]
110 | bundle_dict['preKeyPublic'] = b64decode(preKey[1])
111 |
112 | preKeyPublic = DjbECPublicKey(bundle_dict['preKeyPublic'][1:])
113 |
114 | signedPreKeyPublic = DjbECPublicKey(b64decode(bundle_dict['signedPreKeyPublic'])[1:])
115 | identityKey = IdentityKey(DjbECPublicKey(b64decode(bundle_dict['identityKey'])[1:]))
116 |
117 | prekey_bundle = PreKeyBundle(
118 | registration_id, device_id, bundle_dict['preKeyId'], preKeyPublic,
119 | bundle_dict['signedPreKeyId'], signedPreKeyPublic,
120 | b64decode(bundle_dict['signedPreKeySignature']), identityKey)
121 |
122 | sessionBuilder.processPreKeyBundle(prekey_bundle)
123 | return self.get_session_cipher(recipient_id, device_id)
124 |
125 | def set_devices(self, name, devices):
126 | """ Return a an.
127 |
128 | Parameters
129 | ----------
130 | jid : string
131 | The contacts jid
132 |
133 | devices: [int]
134 | A list of devices
135 | """
136 | log.debug('Saving devices for ' + name + ' → ' + str(devices))
137 | self.device_ids[name] = devices
138 |
139 | def add_device(self, name, device_id):
140 | if name not in self.device_ids:
141 | self.device_ids[name] = [device_id]
142 | elif device_id not in self.device_ids[name]:
143 | self.device_ids[name].append(device_id)
144 |
145 | def set_own_devices(self, devices):
146 | """ Overwrite the current :py:attribute:`OmemoState.own_devices` with
147 | the given devices.
148 |
149 | Parameters
150 | ----------
151 | devices : [int]
152 | A list of device_ids
153 | """
154 | self.own_devices = devices
155 |
156 | def add_own_device(self, device_id):
157 | if device_id not in self.own_devices:
158 | self.own_devices.append(device_id)
159 |
160 | @property
161 | def own_device_id(self):
162 | reg_id = self.store.getLocalRegistrationId()
163 | assert reg_id is not None, \
164 | "Requested device_id but there is no generated"
165 |
166 | return ((reg_id % 2147483646) + 1)
167 |
168 | def own_device_id_published(self):
169 | """ Return `True` only if own device id was added via
170 | :py:method:`OmemoState.set_own_devices()`.
171 | """
172 | return self.own_device_id in self.own_devices
173 |
174 | @property
175 | def bundle(self):
176 | """
177 | .. highlight: python
178 | Returns all data needed to announce bundle information.
179 | ::
180 | bundle_dict = {
181 | 'signedPreKeyPublic': bytes,
182 | 'prekeys': [(int, bytes) (int, bytes)],
183 | 'identityKey': bytes,
184 | 'signedPreKeyId': int,
185 | 'signedPreKeySignature': bytes
186 | }
187 |
188 | """
189 | prekeys = [
190 | (k.getId(), b64encode(k.getKeyPair().getPublicKey().serialize()))
191 | for k in self.store.loadPreKeys()
192 | ]
193 |
194 | identityKeyPair = self.store.getIdentityKeyPair()
195 |
196 | signedPreKey = KeyHelper.generateSignedPreKey(
197 | identityKeyPair, KeyHelper.getRandomSequence(65536))
198 |
199 | self.store.storeSignedPreKey(signedPreKey.getId(), signedPreKey)
200 |
201 | result = {
202 | 'signedPreKeyId': signedPreKey.getId(),
203 | 'signedPreKeyPublic':
204 | b64encode(signedPreKey.getKeyPair().getPublicKey().serialize()),
205 | 'signedPreKeySignature': b64encode(signedPreKey.getSignature()),
206 | 'identityKey':
207 | b64encode(identityKeyPair.getPublicKey().serialize()),
208 | 'prekeys': prekeys
209 | }
210 | return result
211 |
212 | def decrypt_msg(self, msg_dict):
213 | own_id = self.own_device_id
214 | if own_id not in msg_dict['keys']:
215 | log.warn('OMEMO message does not contain our device key')
216 | return
217 |
218 | iv = b64decode(msg_dict['iv'])
219 | sid = msg_dict['sid']
220 | sender_jid = msg_dict['sender_jid']
221 | payload = b64decode(msg_dict['payload'])
222 |
223 | encrypted_key = b64decode(msg_dict['keys'][own_id])
224 |
225 | try:
226 | key = self.handlePreKeyWhisperMessage(sender_jid, sid,
227 | encrypted_key)
228 | except (InvalidVersionException, InvalidMessageException):
229 | try:
230 | key = self.handleWhisperMessage(sender_jid, sid, encrypted_key)
231 | except (NoSessionException, InvalidMessageException) as e:
232 | log.error('No Session found ' + e.message)
233 | log.error('sender_jid → ' + str(sender_jid) + ' sid =>' + str(
234 | sid))
235 | return
236 | except (DuplicateMessageException) as e:
237 | log.error('Duplicate message found ' + str(e.args))
238 | log.error('sender_jid → ' + str(sender_jid) + ' sid => ' + str(
239 | sid))
240 | return
241 | except (Exception) as e:
242 | log.error('Duplicate message found ' + str(e.args))
243 | log.error('sender_jid → ' + str(sender_jid) + ' sid => ' + str(
244 | sid))
245 | return
246 |
247 | except (DuplicateMessageException):
248 | log.error('Duplicate message found ' + e.message)
249 | log.error('sender_jid → ' + str(sender_jid) + ' sid => ' + str(
250 | sid))
251 | return
252 |
253 | result = decrypt(key, iv, payload)
254 |
255 | log.debug(u"Decrypted msg ⇒ " + result)
256 |
257 | if self.own_jid == sender_jid:
258 | self.add_own_device(sid)
259 | else:
260 | self.add_device(sender_jid, sid)
261 |
262 | return result
263 |
264 | def create_msg(self, from_jid, jid, plaintext):
265 | encrypted_keys = {}
266 |
267 | devices_list = self.device_list_for(jid)
268 | if len(devices_list) == 0:
269 | log.error('No known devices')
270 | return
271 |
272 | for dev in devices_list:
273 | self.get_session_cipher(jid, dev)
274 | session_ciphers = self.session_ciphers[jid]
275 | if not session_ciphers:
276 | log.warn('No session ciphers for ' + jid)
277 | return
278 |
279 | (key, iv, payload) = encrypt(plaintext)
280 |
281 | my_other_devices = set(self.own_devices) - set({self.own_device_id})
282 | # Encrypt the message key with for each of our own devices
283 | for dev in my_other_devices:
284 | cipher = self.get_session_cipher(from_jid, dev)
285 | encrypted_keys[dev] = b64encode(cipher.encrypt(key).serialize())
286 |
287 | # Encrypt the message key with for each of receivers devices
288 | for rid, cipher in session_ciphers.items():
289 | try:
290 | encrypted_keys[rid] = b64encode(cipher.encrypt(key).serialize())
291 | except:
292 | log.warn('Failed to find key for device ' + str(rid))
293 |
294 | if len(encrypted_keys) == 0:
295 | log_msg = 'Encrypted keys empty'
296 | log.error(log_msg)
297 | raise NoValidSessions(log_msg)
298 |
299 | result = {'sid': self.own_device_id,
300 | 'keys': encrypted_keys,
301 | 'jid': jid,
302 | 'iv': b64encode(iv),
303 | 'payload': b64encode(payload)}
304 |
305 | log.debug('encrypted message')
306 | log.debug(result)
307 | return result
308 |
309 | def device_list_for(self, jid):
310 | """ Return a list of known device ids for the specified jid.
311 |
312 | Parameters
313 | ----------
314 | jid : string
315 | The contacts jid
316 | """
317 | if jid == self.own_jid:
318 | return set(self.own_devices) - set({self.own_device_id})
319 | if jid not in self.device_ids:
320 | return set()
321 | return set(self.device_ids[jid])
322 |
323 | def devices_without_sessions(self, jid):
324 | """ List device_ids for the given jid which have no axolotl session.
325 |
326 | Parameters
327 | ----------
328 | jid : string
329 | The contacts jid
330 |
331 | Returns
332 | -------
333 | [int]
334 | A list of device_ids
335 | """
336 | known_devices = self.device_list_for(jid)
337 | missing_devices = [dev
338 | for dev in known_devices
339 | if not self.store.containsSession(jid, dev)]
340 | if missing_devices:
341 | log.debug('Missing device sessions: ' + str(
342 | missing_devices))
343 | return missing_devices
344 |
345 | def own_devices_without_sessions(self, own_jid):
346 | """ List own device_ids which have no axolotl session.
347 |
348 | Parameters
349 | ----------
350 | own_jid : string
351 | Workaround for missing own jid in OmemoState
352 |
353 | Returns
354 | -------
355 | [int]
356 | A list of device_ids
357 | """
358 | known_devices = set(self.own_devices) - {self.own_device_id}
359 | missing_devices = [dev
360 | for dev in known_devices
361 | if not self.store.containsSession(own_jid, dev)]
362 | if missing_devices:
363 | log.debug('Missing device sessions: ' + str(
364 | missing_devices))
365 | return missing_devices
366 |
367 | def get_session_cipher(self, jid, device_id):
368 | if jid not in self.session_ciphers:
369 | self.session_ciphers[jid] = {}
370 |
371 | if device_id not in self.session_ciphers[jid]:
372 | cipher = SessionCipher(self.store, self.store, self.store,
373 | self.store, jid, device_id)
374 | self.session_ciphers[jid][device_id] = cipher
375 |
376 | return self.session_ciphers[jid][device_id]
377 |
378 | def handlePreKeyWhisperMessage(self, recipient_id, device_id, key):
379 | preKeyWhisperMessage = PreKeyWhisperMessage(serialized=key)
380 | sessionCipher = self.get_session_cipher(recipient_id, device_id)
381 | key = sessionCipher.decryptPkmsg(preKeyWhisperMessage)
382 | log.debug('PreKeyWhisperMessage -> ' + str(key))
383 | return key
384 |
385 | def handleWhisperMessage(self, recipient_id, device_id, key):
386 | whisperMessage = WhisperMessage(serialized=key)
387 | sessionCipher = self.get_session_cipher(recipient_id, device_id)
388 | key = sessionCipher.decryptMsg(whisperMessage)
389 | log.debug('WhisperMessage -> ' + str(key))
390 | return key
391 |
--------------------------------------------------------------------------------
/tests/test_aes_gcm.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | import pytest
4 |
5 | from omemo.aes_gcm import *
6 |
7 |
8 | @pytest.fixture
9 | def key():
10 | return os.urandom(16)
11 |
12 | @pytest.fixture
13 | def iv():
14 | return os.urandom(16)
15 |
16 | def test_aes_encrypt(key, iv):
17 | plaintext = bytes(u'Oh Romemo!'.encode())
18 | ciphertext = aes_encrypt(key, iv, plaintext)
19 | assert aes_decrypt(key, iv, ciphertext) == plaintext
20 |
21 | def test_encrypt():
22 | plaintext = u'Oh Romemo!'
23 | (key, iv, payload) = encrypt(plaintext)
24 | assert decrypt(key, iv, payload) == plaintext
25 |
--------------------------------------------------------------------------------
/tests/test_db_helpers.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | import sqlite3
3 | from omemo import db_helpers
4 |
5 | def test_table_exists():
6 | db = sqlite3.connect(':memory:', check_same_thread=False)
7 | assert not db_helpers.table_exists(db, 'foo')
8 |
9 | db.execute('CREATE TABLE foo (a TEXT, b INTEGER);')
10 | assert db_helpers.table_exists(db, 'foo')
11 |
12 |
13 | def test_user_version():
14 | db = sqlite3.connect(':memory:', check_same_thread=False)
15 | assert db_helpers.user_version(db) == 0
16 |
17 | db.execute('PRAGMA user_version=1')
18 | assert db_helpers.user_version(db) == 1
19 |
20 |
--------------------------------------------------------------------------------
/tests/test_encryption_store.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | from omemo.encryption import EncryptionState
3 | import os
4 | import sqlite3
5 |
6 |
7 | class TestEncryptionStateStore(unittest.TestCase):
8 |
9 | def setUp(self):
10 | self.conn = sqlite3.connect('test-db', check_same_thread=False)
11 | self.e = EncryptionState(self.conn)
12 |
13 | def test_create(self):
14 | self.assertEquals(self.e.is_active('romeo@example.com'), False)
15 |
16 | def test_enable_encryption(self):
17 | self.e.activate('romeo@example.com')
18 | self.assertEquals(self.e.is_active('romeo@example.com'), True)
19 |
20 | def test_disable_encryption(self):
21 | self.e.activate('romeo@example.com')
22 | self.assertEquals(self.e.is_active('romeo@example.com'), True)
23 | self.e.deactivate('romeo@example.com')
24 | self.assertEquals(self.e.is_active('romeo@example.com'), False)
25 |
26 | def tearDown(self):
27 | os.remove('test-db')
28 |
29 |
30 | if __name__ == '__main__':
31 | unittest.main()
32 |
--------------------------------------------------------------------------------
/tests/test_migrate_encryption_state.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | import sqlite3
3 | from omemo import encryption
4 | from omemo.db_helpers import table_exists, user_version
5 |
6 |
7 | @pytest.fixture
8 | def db():
9 | """ Open in memory sqlite db and crate a table. """
10 | conn = sqlite3.connect(':memory:', check_same_thread=False)
11 | return conn
12 |
13 | def test_downgrade(db):
14 | """ This test asserts a smooth downgrade of sqlite to pre-3.8.2 version.
15 |
16 | Gajim on Windows and TravisCi use an old sqlite version which does not
17 | support `WITHOUT ROW ID` which was added in *6bf2187*. This test make sure
18 | that we can gracefully backup data from the `encryption_state` before
19 | droping the table and reacreating it with an ID column with
20 | `AUTO_INCREMENT`.
21 | """
22 | q = """ CREATE TABLE encryption_state (
23 | jid TEXT PRIMARY KEY,
24 | encryption INTEGER,
25 | timestamp NUMBER DEFAULT CURRENT_TIMESTAMP
26 | );
27 | """
28 | db.execute(q)
29 | q = """ SELECT name FROM sqlite_master
30 | WHERE type='table' AND name='encryption_state';
31 | """
32 |
33 | encryption.migrate(db)
34 | assert db is not None
35 | assert table_exists(db, 'encryption_state')
36 | assert user_version(db) == 1
37 |
38 | def test_fresh_install(db):
39 | """ Test table creation if the uses never had encryption_state table
40 | installed (i.e. user skiped gajim-omemo plugin version 0.3)
41 | """
42 | assert user_version(db) == 0
43 | assert not table_exists(db, 'encryption_state')
44 | encryption.migrate(db)
45 | assert db is not None
46 | assert table_exists(db, 'encryption_state')
47 | assert user_version(db) == 1
48 |
--------------------------------------------------------------------------------
/tests/test_omemo.py:
--------------------------------------------------------------------------------
1 |
2 | import omemo
3 |
4 |
5 | def test_main():
6 | assert omemo # use your library here
7 |
--------------------------------------------------------------------------------
/tests/test_omemo_state.py:
--------------------------------------------------------------------------------
1 | import random
2 | import sqlite3
3 | import sys
4 | from base64 import decodestring
5 |
6 | import pytest
7 | from axolotl.sessioncipher import SessionCipher
8 |
9 | from omemo.state import OmemoState
10 |
11 |
12 | @pytest.fixture
13 | def db():
14 | """ Open in memory sqlite db and crate a table. """
15 | conn = sqlite3.connect(':memory:', check_same_thread=False)
16 | return conn
17 |
18 |
19 | @pytest.fixture
20 | def omemo_state(db):
21 | romeo = "romeo@example.com"
22 | return OmemoState(romeo, db)
23 |
24 | @pytest.fixture
25 | def romeo(db):
26 | romeo = "romeo@example.com"
27 | return OmemoState(romeo, db)
28 |
29 | @pytest.fixture
30 | def julia(db):
31 | julia = "julia@example.com"
32 | return OmemoState(julia, db)
33 |
34 |
35 |
36 | def test_omemo_state_creation(omemo_state):
37 | assert isinstance(omemo_state.own_device_id, int)
38 |
39 | def test_omemo_state_creation_fails():
40 | """ This test makes sure you get a proper error pass a wrong object instea
41 | of a sqlite3.Connection.
42 | """
43 | with pytest.raises(AssertionError):
44 | assert OmemoState("fooo", "bar")
45 | with pytest.raises(AssertionError):
46 | assert OmemoState("asd", None)
47 |
48 |
49 | def test_own_devices(omemo_state):
50 | """ Checks the adding/removing device_ids to own_devices .
51 | """
52 | assert len(omemo_state.own_devices) == 0
53 | assert isinstance(omemo_state.own_device_id, int)
54 | devices_update = [random.randint(0, sys.maxsize) for x in range(0,3)]
55 | omemo_state.set_own_devices(devices_update)
56 | assert len(omemo_state.own_devices) == 3
57 | assert omemo_state.own_devices == devices_update
58 |
59 | @pytest.mark.skipif(True, reason="NOT IMPLEMENTED")
60 | def test_own_device_tupple(omemo_state):
61 | """ :py:attribute:`own_devices` should be a tupple.
62 | """
63 | assert isinstance(omemo_state.own_devices, tuple)
64 |
65 |
66 | @pytest.mark.skipif(True, reason="NOT IMPLEMENTED")
67 | def test_own_devices_accepts_list(omemo_state):
68 | """
69 | :py:attribute:`own_devices` should accept a list as argument, but should
70 | not save duplicates
71 | """
72 | omemo_state.set_own_devices([1, 2, 2, 1])
73 | assert len(omemo_state.own_devices) == 2
74 |
75 |
76 | def test_own_device_id_published(omemo_state):
77 | """ :py:method:`OmemoState.own_device_id_published()` should return True
78 | only if own device id was added via
79 | :py:method:`OmemoState.set_own_devices()`.
80 | """
81 | assert omemo_state.own_device_id_published() == False
82 | omemo_state.set_own_devices([2,3,4,5])
83 | assert omemo_state.own_device_id_published() == False
84 | omemo_state.set_own_devices([omemo_state.own_device_id])
85 | assert omemo_state.own_device_id_published() == True
86 |
87 | def test_add_device(omemo_state):
88 | julia = "julia@example.com"
89 | assert len(omemo_state.device_list_for(julia)) == 0
90 | omemo_state.set_devices(julia, (1,2,3,4))
91 | assert len(omemo_state.device_list_for(julia)) == 4
92 |
93 | montague = "montague@example.com"
94 | assert len(omemo_state.device_list_for(montague)) == 0
95 |
96 |
97 | @pytest.mark.skipif(True, reason="NOT IMPLEMENTED")
98 | def test_device_list_tupple(omemo_state):
99 | name = "romeo@example.com"
100 | omemo_state.set_devices(name, (1,2,3,4))
101 | assert isinstance(omemo_state.device_list_for(name), tuple)
102 |
103 | def test_device_list_duplicate_handling(omemo_state):
104 | """ Should not save duplicate device ids for the same user """
105 | name = "julia@example.com"
106 | omemo_state.set_devices(name, [1,2,2,1])
107 | assert len(omemo_state.device_list_for(name)) == 2
108 |
109 | def test_own_devices_without_sessions(omemo_state):
110 | own_jid = "romeo@example.com"
111 | assert len(omemo_state.own_devices_without_sessions(own_jid)) == 0
112 | omemo_state.set_own_devices([1,2,3,4])
113 | assert len(omemo_state.own_devices_without_sessions(own_jid)) == 4
114 |
115 |
116 | def test_own_devices_without_sessions(omemo_state):
117 | julia = "julia@example.com"
118 | assert len(omemo_state.devices_without_sessions(julia)) == 0
119 | omemo_state.set_devices(julia, [1,2,3,4])
120 | assert len(omemo_state.devices_without_sessions(julia)) == 4
121 |
122 | def test_bundle(omemo_state):
123 | bundle = omemo_state.bundle
124 | assert isinstance(bundle, dict)
125 | assert isinstance(bundle['identityKey'], bytes)
126 | assert isinstance(bundle['prekeys'], list)
127 | for f in bundle['prekeys']:
128 | preKeyId, preKeyPublic = f
129 | assert isinstance(preKeyId, int)
130 | assert isinstance(preKeyPublic, bytes)
131 | assert isinstance(bundle['signedPreKeyId'], int)
132 | assert isinstance(bundle['signedPreKeyPublic'], bytes)
133 | assert isinstance(bundle['signedPreKeySignature'], bytes)
134 |
135 |
136 | def test_build_session(romeo, julia):
137 | assert romeo
138 | assert julia
139 |
140 | romeo_device = romeo.own_device_id
141 |
142 | bundle = romeo.bundle
143 | assert isinstance(bundle, dict)
144 | julias_session = julia.build_session("romeo@example.com", romeo_device,
145 | bundle)
146 | assert isinstance(julias_session, SessionCipher)
147 |
148 | def test_create_message(romeo, julia):
149 | r_jid ="romeo@example.com"
150 | j_jid = "julia@example.com"
151 |
152 | romeo_device = romeo.own_device_id
153 |
154 | bundle = romeo.bundle
155 | julia.set_devices(r_jid, [romeo_device])
156 | julia.build_session(r_jid, romeo_device, bundle)
157 | msg_dict = julia.create_msg(j_jid, r_jid, "Oh Romeo!")
158 | assert isinstance(msg_dict, dict)
159 | assert msg_dict['jid'] == r_jid
160 | assert decodestring(msg_dict['iv'])
161 | assert decodestring(msg_dict['payload'])
162 | for rid, key in msg_dict['keys'].items():
163 | assert isinstance(rid, int)
164 | assert decodestring(key)
165 |
166 |
167 | def test_decrypt_message(romeo, julia):
168 | r_jid ="romeo@example.com"
169 | j_jid = "julia@example.com"
170 |
171 | romeo_device = romeo.own_device_id
172 |
173 | bundle = romeo.bundle
174 | julia.set_devices(r_jid, [romeo_device])
175 | julia.build_session(r_jid, romeo_device, bundle)
176 | msg_dict = julia.create_msg(j_jid, r_jid, "Oh Romeo!")
177 | msg_dict['sender_jid'] = j_jid
178 | assert romeo.decrypt_msg(msg_dict) == "Oh Romeo!"
179 |
180 |
--------------------------------------------------------------------------------
/tests/test_padding.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2016 Bob Mottram
4 | #
5 | # This file is part of python-omemo library.
6 | #
7 | # The python-omemo library is free software: you can redistribute it and/or
8 | # modify it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or (at your
10 | # option) any later version.
11 | #
12 | # python-omemo is distributed in the hope that it will be useful, but WITHOUT ANY
13 | # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 | # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License along with
17 | # the python-omemo library. If not, see .
18 | #
19 |
20 | import os
21 |
22 | import pytest
23 |
24 | from omemo.padding import *
25 |
26 | def test_padding_length():
27 | assert(len(padding_add(u'Oh Romemo!')) == 256)
28 | assert(len(padding_add(u'Wherefore art thou Romeo?')) == 256)
29 |
30 | teststr=u'JULIET O Romeo, Romeo! wherefore art thou Romeo? Deny thy father and refuse thy name; Or, if thou wilt not, be but sworn my love, And I\'ll no longer be a Capulet. ROMEO [Aside] Shall I hear more, or shall I speak at this? JULIET \'Tis but thy name that is my enemy; Thou art thyself, though not a Montague. What\'s Montague? it is nor hand, nor foot, Nor arm, nor face, nor any other part Belonging to a man. O, be some other name! What\'s in a name? that which we call a rose By any other name would smell as sweet; So Romeo would, were he not Romeo call\'d, Retain that dear perfection which he owes Without that title. Romeo, doff thy name, And for that name which is no part of thee Take all myself.'
31 | assert(len(padding_add(teststr)) == 1024)
32 |
33 | def test_padding_offset():
34 | # This tests that the padding offsets for the same string are different each time
35 | # The test could fail, but with very low probability
36 | padded = []
37 | teststr=u'LOL'
38 | padded.append(padding_add(teststr))
39 | padded.append(padding_add(teststr))
40 | padded.append(padding_add(teststr))
41 | same_strings = 0
42 | if padded[0] == padded[1]:
43 | same_strings = same_strings + 1
44 | if padded[0] == padded[2]:
45 | same_strings = same_strings + 1
46 | if padded[1] == padded[2]:
47 | same_strings = same_strings + 1
48 | assert(same_strings < 2)
49 |
50 | def test_padding_remove():
51 | teststr=u'Oh Romemo!'
52 | padded = padding_add(teststr)
53 | assert(len(padding_remove(padded)) == len(teststr))
54 | assert(padding_remove(padded) == teststr)
55 |
--------------------------------------------------------------------------------
/tox.ini:
--------------------------------------------------------------------------------
1 | ; a generative tox configuration, see: https://testrun.org/tox/latest/config.html#generative-envlist
2 |
3 | [tox]
4 | skip_missing_interpreters = true
5 | envlist =
6 | clean,
7 | check,
8 | pypy-nocov
9 | {py27,py33,py34,py35}-nocov-{crypto11,crypto12,crypto}
10 | {py27,py33,py34,py35}-cover-crypto
11 | report,
12 | docs
13 |
14 | [testenv]
15 | basepython =
16 | pypy: {env:TOXPYTHON:pypy}
17 | {py27,docs,spell}: {env:TOXPYTHON:python2.7}
18 | py33: {env:TOXPYTHON:python3.3}
19 | py34: {env:TOXPYTHON:python3.4}
20 | py35: {env:TOXPYTHON:python3.5}
21 | {clean,check,report,extension-coveralls,coveralls,codecov}: python2.7
22 | bootstrap: python
23 | setenv =
24 | PYTHONPATH={toxinidir}/tests
25 | PYTHONUNBUFFERED=yes
26 | passenv =
27 | *
28 | deps =
29 | pytest
30 | python-axolotl
31 | pytest-travis-fold
32 | cover: pytest-cov
33 | crypto: cryptography
34 | crypto11: cryptography>=1.1,<1.2
35 | crypto12: cryptography>=1.2,<1.3
36 | commands =
37 | nocov: {posargs:py.test -vv --ignore=src}
38 | cover: {posargs:py.test --cov --cov-report=term-missing -vv}
39 | usedevelop = true
40 |
41 | [testenv:bootstrap]
42 | deps =
43 | jinja2
44 | matrix
45 | skip_install = true
46 | usedevelop = false
47 | commands =
48 | python ci/bootstrap.py
49 | passenv =
50 | *
51 |
52 | [testenv:spell]
53 | setenv =
54 | SPELLCHECK=1
55 | commands =
56 | sphinx-build -b spelling docs dist/docs
57 | skip_install = true
58 | usedevelop = false
59 | deps =
60 | -r{toxinidir}/docs/requirements.txt
61 | sphinxcontrib-spelling
62 | pyenchant
63 |
64 | [testenv:docs]
65 | deps =
66 | https://github.com/kalkin/python-axolotl/tarball/master#egg=python-axolotl-0.1.7-p1
67 | sphinx>=1.3
68 | commands =
69 | sphinx-build {posargs:-E} -b html docs dist/docs
70 | sphinx-build -b linkcheck docs dist/docs
71 |
72 | [testenv:check]
73 | deps =
74 | docutils
75 | check-manifest
76 | flake8
77 | readme-renderer
78 | pygments
79 | skip_install = true
80 | usedevelop = false
81 | commands =
82 | python setup.py check --strict --metadata --restructuredtext
83 | check-manifest {toxinidir}
84 | flake8 src tests setup.py
85 |
86 | [testenv:coveralls]
87 | deps =
88 | coveralls
89 | skip_install = true
90 | usedevelop = false
91 | commands =
92 | coverage combine
93 | coverage report
94 | coveralls []
95 |
96 | [testenv:codecov]
97 | deps =
98 | codecov
99 | skip_install = true
100 | usedevelop = false
101 | commands =
102 | coverage combine
103 | coverage report
104 | coverage xml --ignore-errors
105 | codecov []
106 |
107 |
108 | [testenv:report]
109 | deps = coverage
110 | skip_install = true
111 | usedevelop = false
112 | commands =
113 | coverage combine
114 | coverage report
115 |
116 | [testenv:clean]
117 | commands = coverage erase
118 | skip_install = true
119 | usedevelop = false
120 | deps = coverage
121 |
122 | [testenv:py27-nocov]
123 | usedevelop = false
124 |
125 | [testenv:py33-nocov]
126 | usedevelop = false
127 |
128 | [testenv:py34-nocov]
129 | usedevelop = false
130 |
131 | [testenv:py35-nocov]
132 | usedevelop = false
133 |
134 | [testenv:pypy-nocov]
135 | usedevelop = false
136 |
137 |
--------------------------------------------------------------------------------