├── .coveragerc
├── .gitignore
├── .travis.yml
├── CONTRIBUTING.md
├── COPYING
├── MANIFEST.in
├── README.md
├── deploy
└── prof_omemo_plugin.py
├── docs
├── Workflow.md
└── images
│ └── omemo.png
├── install.sh
├── pytest.ini
├── setup.cfg
├── setup.py
├── src
└── profanity_omemo_plugin
│ ├── __init__.py
│ ├── constants.py
│ ├── db.py
│ ├── errors.py
│ ├── log.py
│ ├── omemo
│ ├── __init__.py
│ ├── aes_gcm.py
│ ├── aes_gcm_native.py
│ ├── db_helpers.py
│ ├── encryption.py
│ ├── liteaxolotlstore.py
│ ├── liteidentitykeystore.py
│ ├── liteprekeystore.py
│ ├── litesessionstore.py
│ ├── litesignedprekeystore.py
│ ├── sql.py
│ └── state.py
│ ├── prof_omemo_state.py
│ ├── weak_message_store.py
│ └── xmpp.py
├── tests
├── __init__.py
├── fixtures
│ ├── __init__.py
│ └── stanzas
│ │ ├── iq_bundle_info.xml
│ │ └── iq_bundle_info_chatsecure.xml
├── test_prof_omemo_plugin.py
├── test_prof_omemo_state.py
└── test_unpacking_xmpp.py
└── tox.ini
/.coveragerc:
--------------------------------------------------------------------------------
1 | [paths]
2 | source = src
3 |
4 | [report]
5 | show_missing = true
6 | precision = 2
7 | omit = *migrations*
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | env/
12 | build/
13 | develop-eggs/
14 | dist/
15 | downloads/
16 | eggs/
17 | .eggs/
18 | lib/
19 | lib64/
20 | parts/
21 | sdist/
22 | var/
23 | *.egg-info/
24 | .installed.cfg
25 | *.egg
26 |
27 | # PyInstaller
28 | # Usually these files are written by a python script from a template
29 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
30 | *.manifest
31 | *.spec
32 |
33 | # Installer logs
34 | pip-log.txt
35 | pip-delete-this-directory.txt
36 |
37 | # Unit test / coverage reports
38 | htmlcov/
39 | .tox/
40 | .coverage
41 | .coverage.*
42 | .cache
43 | nosetests.xml
44 | coverage.xml
45 | *,cover
46 | .hypothesis/
47 |
48 | # Translations
49 | *.mo
50 | *.pot
51 |
52 | # Django stuff:
53 | *.log
54 |
55 | # Sphinx documentation
56 | docs/_build/
57 |
58 | # PyBuilder
59 | target/
60 |
61 | #Ipython Notebook
62 | .ipynb_checkpoints
63 |
64 | # PyCharm
65 | .idea/
66 | /.python-version
67 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: python
2 | python:
3 | - "2.7"
4 | - "3.5"
5 | - "3.6"
6 |
7 | # command to install dependencies
8 | install:
9 | - pip install tox-travis
10 | - pip install coveralls
11 |
12 | # command to run tests
13 | script:
14 | - tox
15 |
16 | after_success:
17 | - coveralls
18 |
19 | notifications:
20 | email:
21 | on_success: never
22 | on_failure: never
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to profanity-omemo-plugin
2 |
3 | When contributing to this repository, please first discuss the change you wish to make via issue,
4 | email, or any other method with the owners of this repository before making a change.
5 |
6 | Please note we have a code of conduct, please follow it in all your interactions with the project.
7 |
8 | ## Submitting an Issue
9 | Did you notice a bug? Do you have a feature request? Please file an issue [here on GitHub](https://github.com/ReneVolution/profanity-omemo-plugin/issues).
10 |
11 | ## Code of Conduct
12 |
13 | ### Our Pledge
14 |
15 | In the interest of fostering an open and welcoming environment, we as
16 | contributors and maintainers pledge to making participation in our project and
17 | our community a harassment-free experience for everyone, regardless of age, body
18 | size, disability, ethnicity, gender identity and expression, level of experience,
19 | nationality, personal appearance, race, religion, or sexual identity and
20 | orientation.
21 |
22 | ### Our Standards
23 |
24 | Examples of behavior that contributes to creating a positive environment
25 | include:
26 |
27 | * Using welcoming and inclusive language
28 | * Being respectful of differing viewpoints and experiences
29 | * Gracefully accepting constructive criticism
30 | * Focusing on what is best for the community
31 | * Showing empathy towards other community members
32 |
33 | Examples of unacceptable behavior by participants include:
34 |
35 | * The use of sexualized language or imagery and unwelcome sexual attention or
36 | advances
37 | * Trolling, insulting/derogatory comments, and personal or political attacks
38 | * Public or private harassment
39 | * Publishing others' private information, such as a physical or electronic
40 | address, without explicit permission
41 | * Other conduct which could reasonably be considered inappropriate in a
42 | professional setting
43 |
44 | ### Our Responsibilities
45 |
46 | Project maintainers are responsible for clarifying the standards of acceptable
47 | behavior and are expected to take appropriate and fair corrective action in
48 | response to any instances of unacceptable behavior.
49 |
50 | Project maintainers have the right and responsibility to remove, edit, or
51 | reject comments, commits, code, wiki edits, issues, and other contributions
52 | that are not aligned to this Code of Conduct, or to ban temporarily or
53 | permanently any contributor for other behaviors that they deem inappropriate,
54 | threatening, offensive, or harmful.
55 |
56 | ### Scope
57 |
58 | This Code of Conduct applies both within project spaces and in public spaces
59 | when an individual is representing the project or its community. Examples of
60 | representing a project or community include using an official project e-mail
61 | address, posting via an official social media account, or acting as an appointed
62 | representative at an online or offline event. Representation of a project may be
63 | further defined and clarified by project maintainers.
64 |
65 | ### Enforcement
66 |
67 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
68 | reported by contacting the project team at info@renevolution.com. All
69 | complaints will be reviewed and investigated and will result in a response that
70 | is deemed necessary and appropriate to the circumstances. The project team is
71 | obligated to maintain confidentiality with regard to the reporter of an incident.
72 | Further details of specific enforcement policies may be posted separately.
73 |
74 | Project maintainers who do not follow or enforce the Code of Conduct in good
75 | faith may face temporary or permanent repercussions as determined by other
76 | members of the project's leadership.
77 |
78 | ### Attribution
79 |
80 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
81 | available at [http://contributor-covenant.org/version/1/4][version]
82 |
83 | [homepage]: http://contributor-covenant.org
84 | [version]: http://contributor-covenant.org/version/1/4/
--------------------------------------------------------------------------------
/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 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
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 | {project} Copyright (C) {year} {fullname}
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 | .
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | # Include the license file
2 | include README.md COPYING
3 |
4 | # Include the actual plugin file
5 | recursive-include deploy *
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | [](https://github.com/ReneVolution/profanity-omemo-plugin)
3 |
4 |
5 | # profanity-omemo-plugin [](https://conversations.im/omemo/)
6 |
7 | A Python plugin to use (axolotl / Signal Protocol) encryption for the [Profanity](http://www.profanity.im/) XMPP messenger
8 |
9 | ## Requirements
10 |
11 | This Plugin requires the ProfanityIM Messenger to be compiled with Python [2.7, 3.5, 3.6] Plugin Support.
12 | Please make sure to match the Plugin-Host requirements from the table below.
13 |
14 | | Plugin | Profanity |
15 | |-------------|----------------|
16 | | master | master |
17 | | v0.1.1 | \>= v0.5.0 |
18 | | v0.1.0 | \>= v0.5.0 |
19 |
20 |
21 | ## Prerequisites
22 |
23 | __Linux__
24 |
25 | Some Linux distributions require to install some header packages before installing the PyPI cryptography package.
26 | Please find more details at [cryptography.io](https://cryptography.io/en/latest/installation/#building-cryptography-on-linux).
27 |
28 | __Android (Termux)__
29 |
30 | - Run `apt install git clang libffi-dev openssl-dev`
31 | - Run `export CONFIG_SHELL="$PREFIX/bin/sh"`
32 |
33 |
34 | **You will also need `setuptools` (e.g. through `pip install setuptools`).**
35 |
36 |
37 | ## Installation
38 |
39 | - Clone this Repository
40 | - Run `./install.sh`
41 | - Open `profanity`
42 | - Load plugin with `/plugins load prof_omemo_plugin.py`
43 |
44 | ## Usage
45 |
46 | `/omemo (on|off)`
47 | Turns on/off the usage of the plugin while it may be still loaded in profanity. (Default=ON)
48 |
49 | `/omemo status`
50 | Displays the current status in profanity's console window
51 |
52 | `/omemo start [contact jid]`
53 | Starts a new conversation with the given contact, if not given, the one in the current chat
54 |
55 | `/omemo end [contact jid]`
56 | Ends the conversation with the given contact jid or, if not given, the one in the current chat
57 |
58 | ## Contributing
59 |
60 | If you want to contribute to this project, please check out [CONTRIBUTING.md](./CONTRIBUTING.md) first.
61 |
62 | ## TODO
63 |
64 | - [ ] Documentation
65 | - [ ] Handle messages from own devices
66 | - [ ] Trust Management
67 | - [ ] Write more tests
68 |
69 |
--------------------------------------------------------------------------------
/deploy/prof_omemo_plugin.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2017 René `reneVolution` Calles
4 | #
5 | # This file is part of Profanity OMEMO plugin.
6 | #
7 | # The Profanity OMEMO plugin 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
10 | # (at your option) any later version.
11 | #
12 | # The Profanity OMEMO plugin is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 | # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 | # more details.
16 | #
17 | # You should have received a copy of the GNU General Public License along with
18 | # the Profanity OMEMO plugin. If not, see .
19 | #
20 |
21 | # This file will be copied to the profanity plugins install location
22 | from __future__ import absolute_import
23 | from __future__ import unicode_literals
24 |
25 | import binascii
26 | from functools import wraps
27 |
28 | import prof
29 |
30 | import profanity_omemo_plugin.xmpp as xmpp
31 | from profanity_omemo_plugin.constants import (NS_DEVICE_LIST_NOTIFY,
32 | SETTINGS_GROUP,
33 | OMEMO_DEFAULT_ENABLED,
34 | OMEMO_DEFAULT_MESSAGE_CHAR,
35 | PLUGIN_NAME)
36 | from profanity_omemo_plugin.log import get_plugin_logger
37 | from profanity_omemo_plugin.prof_omemo_state import (ProfOmemoState,
38 | ProfOmemoUser,
39 | ProfActiveOmemoChats)
40 |
41 | log = get_plugin_logger(__name__)
42 |
43 |
44 | ################################################################################
45 | # Convenience methods
46 | ################################################################################
47 |
48 | def send_stanza(stanza):
49 | """ Sends a stanza via profanity
50 |
51 | Ensures the stanza is valid XML before sending.
52 | """
53 |
54 | if xmpp.stanza_is_valid_xml(stanza):
55 | log.debug('Sending Stanza: {}'.format(stanza))
56 | prof.send_stanza(stanza)
57 | return True
58 |
59 | return False
60 |
61 |
62 | def show_chat_info(barejid, message):
63 | prof.chat_show_themed(
64 | barejid,
65 | PLUGIN_NAME,
66 | 'info',
67 | 'cyan',
68 | None,
69 | message
70 | )
71 |
72 |
73 | def show_chat_warning(barejid, message):
74 | prof.chat_show_themed(
75 | barejid,
76 | PLUGIN_NAME,
77 | 'warning',
78 | 'bold_yellow',
79 | None,
80 | message
81 | )
82 |
83 |
84 | def show_chat_critical(barejid, message):
85 | prof.chat_show_themed(
86 | barejid,
87 | PLUGIN_NAME,
88 | 'critical',
89 | 'bold_red',
90 | None,
91 | message
92 | )
93 |
94 |
95 | def ensure_unicode_stanza(stanza):
96 | if isinstance(stanza, (str, bytes)):
97 | try:
98 | u_stanza = stanza.decode('utf-8')
99 | return u_stanza
100 | except AttributeError: # Python 3 here
101 | pass
102 |
103 | return stanza
104 |
105 |
106 | def _get_omemo_enabled_setting():
107 | return prof.settings_boolean_get(
108 | SETTINGS_GROUP, 'enabled', OMEMO_DEFAULT_ENABLED)
109 |
110 |
111 | def _set_omemo_enabled_setting(enabled):
112 | msg = 'Plugin enabled: {0}'.format(enabled)
113 | log.debug(msg)
114 | prof.cons_show(msg)
115 | prof.settings_boolean_set(SETTINGS_GROUP, 'enabled', enabled)
116 |
117 |
118 | def _get_omemo_message_char():
119 | return prof.settings_string_get(
120 | SETTINGS_GROUP, 'message_char', OMEMO_DEFAULT_MESSAGE_CHAR)
121 |
122 |
123 | def _set_omemo_message_char(char):
124 | msg = 'OMEMO Message Prefix: {0}'.format(char)
125 | log.debug(msg)
126 | prof.cons_show(msg)
127 | prof.settings_string_set(SETTINGS_GROUP, 'message_char', char)
128 |
129 |
130 | ################################################################################
131 | # Decorators
132 | ################################################################################
133 |
134 | def require_sessions_for_all_devices(attrib, else_return=None):
135 | def wrapper(func):
136 | @wraps(func)
137 | def func_wrapper(stanza):
138 | stanza = ensure_unicode_stanza(stanza)
139 |
140 | recipient = xmpp.get_root_attrib(stanza, attrib)
141 | try:
142 | contat_jid = recipient.rsplit('/', 1)[0]
143 | except AttributeError:
144 | log.error('Recipient not valid.')
145 | return else_return
146 |
147 | log.info('Checking Sessions for {0}'.format(recipient))
148 | state = ProfOmemoState()
149 | uninitialized_devices = state.devices_without_sessions(contat_jid)
150 |
151 | own_jid = ProfOmemoUser.account
152 | own_uninitialized = state.devices_without_sessions(own_jid)
153 |
154 | uninitialized_devices += own_uninitialized
155 |
156 | if not uninitialized_devices:
157 | log.info('Recipient {0} has all sessions set up.'.format(recipient))
158 | return func(stanza)
159 |
160 | _query_device_list(contat_jid)
161 | _query_device_list(own_jid)
162 | log.warning('No Session found for user: {0}.'.format(recipient))
163 | prof.notify('Failed to send last Message.', 5000, 'Profanity Omemo Plugin')
164 | return else_return
165 |
166 | return func_wrapper
167 | return wrapper
168 |
169 |
170 | def omemo_enabled(else_return=None):
171 | def wrapper(func):
172 | @wraps(func)
173 | def func_wrapper(*args, **kwargs):
174 | log.debug('Check if Plugins is enabled')
175 | enabled = _get_omemo_enabled_setting()
176 |
177 | if enabled is True:
178 | log.debug('Plugin is enabled')
179 | return func(*args, **kwargs)
180 |
181 | return else_return
182 |
183 | return func_wrapper
184 | return wrapper
185 |
186 |
187 | ################################################################################
188 | # OMEMO helper
189 | ################################################################################
190 |
191 | def _init_omemo():
192 | account = ProfOmemoUser().account
193 | if account:
194 | # subscribe to devicelist updates
195 | log.info('Adding Disco Feature {0}.'.format(NS_DEVICE_LIST_NOTIFY))
196 | # subscribe to device list updates
197 | prof.disco_add_feature(NS_DEVICE_LIST_NOTIFY)
198 |
199 | log.debug('Announcing own bundle info.')
200 | _announce_own_devicelist() # announce own device list
201 | _announce_own_bundle() # announce own bundle
202 |
203 | # we query our own devices to add possible other devices we own
204 | _query_device_list(account)
205 |
206 |
207 | def _announce_own_bundle():
208 | own_bundle_stanza = xmpp.create_own_bundle_stanza()
209 | send_stanza(own_bundle_stanza)
210 |
211 |
212 | def _show_no_trust_mgmt_header(jid):
213 | show_chat_warning(jid, '###############################################')
214 | show_chat_warning(jid, '# #')
215 | show_chat_warning(jid, '# CAUTION #')
216 | show_chat_warning(jid, '# This plugin does not support any form #')
217 | show_chat_warning(jid, '# of Trust Management #')
218 | show_chat_warning(jid, '# All Devices are trusted *blindly* #')
219 | show_chat_warning(jid, '# #')
220 | show_chat_warning(jid, '###############################################')
221 |
222 |
223 | def _start_omemo_session(jid):
224 | # should be started before the first message is sent.
225 |
226 | # we store the jid in ProfActiveOmemoChats as the user at least intends to
227 | # use OMEMO encryption. The respecting methods should then not ignore
228 | # sending OMEMO messages and fail if no session was created then.
229 | if not ProfActiveOmemoChats.account_is_registered(jid):
230 | ProfActiveOmemoChats.add(jid)
231 | else:
232 | ProfActiveOmemoChats.activate(jid)
233 |
234 | # ensure we have no running OTR session
235 | prof.encryption_reset(jid)
236 |
237 | # Visualize that OMEMO is now running
238 | prof.chat_set_titlebar_enctext(jid, 'OMEMO')
239 |
240 | message_char = _get_omemo_message_char()
241 | prof.chat_set_outgoing_char(jid, message_char)
242 |
243 | show_chat_info(jid, 'OMEMO Session started.')
244 | _show_no_trust_mgmt_header(jid)
245 |
246 | log.info('Query Devicelist for {0}'.format(jid))
247 | _query_device_list(jid)
248 |
249 | prof.settings_string_list_add(SETTINGS_GROUP, 'omemo_sessions', jid)
250 |
251 |
252 | def _end_omemo_session(jid):
253 | ProfActiveOmemoChats.deactivate(jid)
254 |
255 | # Release OMEMO from titlebar
256 | prof.chat_unset_titlebar_enctext(jid)
257 |
258 | prof.chat_unset_incoming_char(jid)
259 | prof.chat_unset_outgoing_char(jid)
260 |
261 | prof.settings_string_list_remove(SETTINGS_GROUP, 'omemo_sessions', jid)
262 |
263 | show_chat_info(jid, 'OMEMO Session ended.')
264 |
265 |
266 | ################################################################################
267 | # Stanza handling
268 | ################################################################################
269 |
270 | def _handle_devicelist_update(stanza):
271 | omemo_state = ProfOmemoState()
272 | own_jid = omemo_state.own_jid
273 | msg_dict = xmpp.unpack_devicelist_info(stanza)
274 | sender_jid = msg_dict['from']
275 | log.info('Received devicelist update from {0}'.format(sender_jid))
276 |
277 | known_devices = omemo_state.device_list_for(sender_jid)
278 | new_devices = msg_dict['devices']
279 |
280 | added_devices = set(new_devices) - known_devices
281 |
282 | if added_devices:
283 | device_str = ', '.join([str(d) for d in added_devices])
284 | msg = '{0} added devices with IDs {1}'.format(sender_jid, device_str)
285 | show_chat_warning(sender_jid, msg)
286 | xmpp.update_devicelist(own_jid, sender_jid, new_devices)
287 |
288 | if not omemo_state.own_device_id_published():
289 | _announce_own_devicelist()
290 |
291 | if sender_jid != own_jid:
292 | add_recipient_to_completer(sender_jid)
293 |
294 |
295 | def add_recipient_to_completer(recipient):
296 | log.info('Adding {} to the completer.'.format(recipient))
297 | prof.completer_add('/omemo start', [recipient])
298 | prof.completer_add('/omemo show_devices', [recipient])
299 | prof.completer_add('/omemo fingerprints', [recipient])
300 | prof.completer_add('/omemo reset_devicelist', [recipient])
301 |
302 |
303 | def _handle_bundle_update(stanza):
304 | log.info('Bundle Information received.')
305 | omemo_state = ProfOmemoState()
306 | bundle_info = xmpp.unpack_bundle_info(stanza)
307 |
308 | if not bundle_info:
309 | log.error('Could not unpack bundle info.')
310 | return
311 |
312 | sender = bundle_info.get('sender')
313 | device_id = bundle_info.get('device')
314 |
315 | try:
316 | omemo_state.build_session(sender, device_id, bundle_info)
317 | log.info('Session built with user: {0}:{1}'.format(sender, device_id))
318 | prof.completer_add('/omemo end', [sender])
319 | except Exception as e:
320 | msg_tmpl = 'Could not build session with {0}:{1}. {2}:{3}'
321 | msg = msg_tmpl.format(sender, device_id, type(e).__name__, str(e))
322 | log.error(msg)
323 | return
324 |
325 |
326 | def _announce_own_devicelist():
327 | fulljid = ProfOmemoUser().fulljid
328 | query_msg = xmpp.create_devicelist_update_msg(fulljid)
329 | log.info('Announce own device list.')
330 | log.info(query_msg)
331 | send_stanza(query_msg)
332 |
333 |
334 | def _query_bundle_info_for(recipient, deviceid):
335 | log.info('Query Bundle for {0}:{1}'.format(recipient, deviceid))
336 | account = ProfOmemoUser().account
337 | stanza = xmpp.create_bundle_request_stanza(account, recipient, deviceid)
338 | send_stanza(stanza)
339 |
340 |
341 | def _query_device_list(contact_jid):
342 | log.info('Query Device list for {0}'.format(contact_jid))
343 | fulljid = ProfOmemoUser().fulljid
344 | query_msg = xmpp.create_devicelist_query_msg(fulljid, contact_jid)
345 | send_stanza(query_msg)
346 |
347 |
348 | ################################################################################
349 | # Sending hooks
350 | ################################################################################
351 |
352 | @omemo_enabled()
353 | @require_sessions_for_all_devices('to')
354 | def prof_on_message_stanza_send(stanza):
355 | stanza = ensure_unicode_stanza(stanza)
356 |
357 | contact_jid = xmpp.get_recipient(stanza)
358 | if not ProfActiveOmemoChats.account_is_active(contact_jid):
359 | log.debug('Chat not activated for {0}'.format(contact_jid))
360 | return None
361 |
362 | try:
363 | if xmpp.is_xmpp_plaintext_message(stanza):
364 | encrypted_stanza = xmpp.encrypt_stanza(stanza)
365 | if xmpp.stanza_is_valid_xml(encrypted_stanza):
366 | return encrypted_stanza
367 | except Exception as e:
368 | log.exception('Could not encrypt message')
369 |
370 | show_chat_critical(contact_jid, 'Last message was sent unencrypted.')
371 | return None
372 |
373 |
374 | def prof_pre_chat_message_send(barejid, message):
375 | """ Called before a chat message is sent
376 |
377 | :returns: the new message to send, returning None stops the message
378 | from being sent
379 | """
380 |
381 | plugin_enabled = _get_omemo_enabled_setting()
382 | if not plugin_enabled:
383 | return message
384 |
385 | if not ProfActiveOmemoChats.account_is_active(barejid):
386 | log.info('Chat not activated for {0}'.format(barejid))
387 | return message
388 |
389 | omemo_state = ProfOmemoState()
390 | uninitialzed_devices = omemo_state.devices_without_sessions(barejid)
391 |
392 | if uninitialzed_devices:
393 | d_str = ', '.join([str(d) for d in uninitialzed_devices])
394 | msg = 'Requesting bundles for missing devices {0}'.format(d_str)
395 |
396 | log.info(msg)
397 | prof.notify(msg, 5000, 'Profanity Omemo Plugin')
398 |
399 | for device in uninitialzed_devices:
400 | _query_bundle_info_for(barejid, device)
401 |
402 | own_jid = ProfOmemoUser.account
403 | own_uninitialized = omemo_state.devices_without_sessions(own_jid)
404 |
405 | if own_uninitialized:
406 | d_str = ', '.join([str(d) for d in own_uninitialized])
407 | msg = 'Requesting own bundles for missing devices {0}'.format(d_str)
408 |
409 | log.info(msg)
410 | prof.notify(msg, 5000, 'Profanity Omemo Plugin')
411 |
412 | for device in own_uninitialized:
413 | _query_bundle_info_for(own_jid, device)
414 |
415 | return message
416 |
417 |
418 | ################################################################################
419 | # Receiving hooks
420 | ################################################################################
421 |
422 | @omemo_enabled(else_return=True)
423 | def prof_on_message_stanza_receive(stanza):
424 | stanza = ensure_unicode_stanza(stanza)
425 |
426 | log.info('Received Message: {0}'.format(stanza))
427 | if xmpp.is_devicelist_update(stanza):
428 | log.info('Device List update detected.')
429 | try:
430 | _handle_devicelist_update(stanza)
431 | except:
432 | log.exception('Failed to handle devicelist update.')
433 |
434 | return False
435 |
436 | if xmpp.is_encrypted_message(stanza):
437 | log.info('Received OMEMO encrypted message.')
438 | omemo_state = ProfOmemoState()
439 |
440 | try:
441 | msg_dict = xmpp.unpack_encrypted_stanza(stanza)
442 | sender = msg_dict['sender_jid']
443 | resource = msg_dict['sender_resource']
444 | sender_fulljid = sender + '/' + resource
445 |
446 | if sender_fulljid == ProfOmemoUser().fulljid:
447 | log.debug('Skipping own Message.')
448 | return False
449 |
450 | try:
451 | plain_msg = omemo_state.decrypt_msg(msg_dict)
452 | except Exception:
453 | log.exception('Could not decrypt Message.')
454 | return False
455 |
456 | if plain_msg is None:
457 | log.error('Could not decrypt Message')
458 | return True
459 |
460 | if plain_msg:
461 | # only mark the message if it was an OMEMO encrypted message
462 | try:
463 | message_char = _get_omemo_message_char()
464 | log.debug('Set incoming Message Character: {0}'.format(message_char))
465 | prof.chat_set_incoming_char(sender, message_char)
466 | prof.incoming_message(sender, resource, plain_msg)
467 | finally:
468 | prof.chat_unset_incoming_char(sender)
469 |
470 | # if this was the first OMEMO encrypted message received by
471 | # the sender (a.k.a. whenever profanity opens a new chat window
472 | # for a recipient), we automatically respond with OMEMO encrypted
473 | # messages. If encryption is turned off later by the user,
474 | # we respect that.
475 | if not ProfActiveOmemoChats.account_is_active(sender):
476 | if not ProfActiveOmemoChats.account_is_deactivated(sender):
477 | _start_omemo_session(sender)
478 |
479 | return False
480 |
481 | except Exception:
482 | # maybe not OMEMO encrypted, profanity will take care then
483 | log.exception('Could not handle encrypted message.')
484 |
485 | return True
486 |
487 |
488 | @omemo_enabled(else_return=True)
489 | def prof_on_iq_stanza_receive(stanza):
490 | stanza = ensure_unicode_stanza(stanza)
491 | log.info('Received IQ: {0}'.format(stanza))
492 |
493 | if xmpp.is_bundle_update(stanza): # bundle information received
494 | log.info('Bundle update detected.')
495 | _handle_bundle_update(stanza)
496 | return False
497 |
498 | elif xmpp.is_devicelist_update(stanza):
499 | log.info('Device List update detected.')
500 | _handle_devicelist_update(stanza)
501 | return False
502 |
503 | return True
504 |
505 |
506 | ################################################################################
507 | # Plugin Entry Point
508 | ################################################################################
509 |
510 |
511 | def _parse_args(arg1=None, arg2=None, arg3=None):
512 | """ Parse arguments given in command window
513 |
514 | arg1: start || end
515 | arg2: muc || jid (optional)
516 |
517 | Starts or ends an encrypted chat session
518 |
519 | """
520 | account = ProfOmemoUser().account
521 | fulljid = ProfOmemoUser().fulljid
522 |
523 | if arg1 == 'on':
524 | _set_omemo_enabled_setting(True)
525 |
526 | elif arg1 == 'off':
527 | _set_omemo_enabled_setting(False)
528 |
529 | elif arg1 == 'start':
530 | # ensure we are in a chat window
531 |
532 | current_recipient = prof.get_current_recipient()
533 |
534 | if not current_recipient and arg2 != current_recipient:
535 | log.info('Opening Chat Window for {0}'.format(arg2))
536 | prof.send_line('/msg {0}'.format(arg2))
537 |
538 | recipient = arg2 or current_recipient
539 | if recipient:
540 | log.info('Start OMEMO session with: {0}'.format(recipient))
541 | _start_omemo_session(recipient)
542 |
543 | elif arg1 == 'end':
544 | # ensure we are in a chat window
545 | jid = arg2 or prof.get_current_muc() or prof.get_current_recipient()
546 | log.info('Ending OMEMO session with: {0}'.format(jid))
547 | if jid:
548 | _end_omemo_session(jid)
549 |
550 | elif arg1 == 'set':
551 | if arg2 == 'message_prefix':
552 | if arg3 is not None:
553 | _set_omemo_message_char(arg3)
554 |
555 | elif arg1 == 'account':
556 | prof.cons_show('Account: {0}'.format(account))
557 |
558 | elif arg1 == 'status':
559 | enabled = _get_omemo_enabled_setting()
560 | prof.cons_show('OMEMO Plugin Enabled: {0}'.format(enabled))
561 |
562 | elif arg1 == 'fulljid':
563 | prof.cons_show('Current JID: {0}'.format(fulljid))
564 |
565 | elif arg1 == 'show_devices' and arg2 is not None:
566 | account = arg2
567 | omemo_state = ProfOmemoState()
568 | prof.cons_show('Requesting Devices...')
569 | devices = omemo_state.device_list_for(account)
570 | prof.cons_show('Devices: {0}'.format(devices))
571 | prof.cons_show('{0}: {1}'.format(account, ', '.join(devices)))
572 |
573 | elif arg1 == 'reset_devicelist' and arg2 is not None:
574 | contact_jid = arg2
575 | if contact_jid != ProfOmemoUser.account:
576 | omemo_state = ProfOmemoState()
577 | omemo_state.set_devices(contact_jid, [])
578 | _query_device_list(contact_jid)
579 |
580 | elif arg1 == 'fingerprints':
581 | if arg2:
582 | contact_jid = query_jid = arg2
583 | else:
584 | # The local account is identified as '-1' in the OMEMO database
585 | contact_jid = ProfOmemoUser.account
586 | query_jid = '-1'
587 | omemo_state = ProfOmemoState()
588 |
589 | fingerprints = omemo_state.getFingerprints(query_jid)
590 | prof.cons_show('Fingerprints for account: {0}'.format(contact_jid))
591 |
592 | for record in fingerprints:
593 | _id, recipient_id, public_key, trust = record
594 | fpr = binascii.hexlify(public_key)
595 | fpr = human_hash(fpr[2:])
596 |
597 | prof.cons_show(' {0}'.format(fpr))
598 |
599 | else:
600 | prof.cons_show('Argument {0} not supported.'.format(arg1))
601 |
602 |
603 | ################################################################################
604 | # Plugin State Changes
605 | ################################################################################
606 |
607 |
608 | def prof_on_chat_win_focus(barejid):
609 | if not ProfActiveOmemoChats.account_is_registered(barejid):
610 | # get remembered user sessions
611 | u_sess = prof.settings_string_list_get(SETTINGS_GROUP, 'omemo_sessions')
612 | if u_sess and barejid in u_sess:
613 | _start_omemo_session(barejid)
614 |
615 |
616 | def prof_init(version, status, account_name, fulljid):
617 | log.info('prof_init() called')
618 | synopsis = [
619 | '/omemo',
620 | '/omemo on|off',
621 | '/omemo start|end [jid]',
622 | '/omemo set'
623 | '/omemo status',
624 | '/omemo account',
625 | '/omemo fulljid',
626 | '/omemo fingerprints',
627 | '/omemo show_devices',
628 | '/omemo reset_devicelist'
629 | ]
630 |
631 | description = 'Plugin to enable OMEMO encryption'
632 | args = [
633 | ['on|off', 'Enable/Disable the Profanity OMEMO Plugin'],
634 | ['start|end ', ('Start an OMEMO based conversation with '
635 | 'window or current window.')],
636 | ['set', 'Set Settings like Message Prefix'],
637 | ['status', 'Display the current Profanity OMEMO Plugin status.'],
638 | ['fingerprints ', 'Display the known fingerprints for '],
639 | ['account', 'Show current account name'],
640 | ['reset_devicelist ', 'Manually reset a contacts devicelist.'],
641 | ['fulljid', 'Show current ']
642 | ]
643 |
644 | examples = []
645 |
646 | # ensure the plugin is not registered if python-omemo is not available
647 | prof.register_command('/omemo', 1, 3,
648 | synopsis, description, args, examples, _parse_args)
649 |
650 | prof.completer_add('/omemo', ['on', 'off', 'status', 'start', 'end', 'set'
651 | 'account', 'fulljid', 'show_devices',
652 | 'reset_devicelist', 'fingerprints'])
653 |
654 | prof.completer_add('/omemo set', ['message_prefix'])
655 |
656 | # set user and init omemo only if account_name and fulljid provided
657 | if account_name is not None and fulljid is not None:
658 | ProfOmemoUser.set_user(account_name, fulljid)
659 | _init_omemo()
660 | else:
661 | log.warning('No User logged in on plugin.prof_init()')
662 |
663 |
664 | def prof_on_unload():
665 | log.debug('prof_on_unload() called')
666 | ProfOmemoUser.reset()
667 |
668 |
669 | def prof_on_connect(account_name, fulljid):
670 | log.debug('prof_on_connect() called')
671 | ProfOmemoUser.set_user(account_name, fulljid)
672 | _init_omemo()
673 |
674 |
675 | def prof_on_disconnect(account_name, fulljid):
676 | log.debug('prof_on_disconnect() called')
677 | ProfOmemoUser.reset()
678 |
679 |
680 | def prof_on_shutdown():
681 | log.debug('prof_on_shutdown() called')
682 | ProfOmemoUser.reset()
683 |
684 |
685 | def human_hash(fpr):
686 | fpr = fpr.upper()
687 | fplen = len(fpr)
688 | wordsize = fplen // 8
689 | buf = ''
690 | for w in range(0, fplen, wordsize):
691 | buf += '{0} '.format(fpr[w:w + wordsize].decode())
692 | return buf.rstrip()
693 |
--------------------------------------------------------------------------------
/docs/Workflow.md:
--------------------------------------------------------------------------------
1 | Workflow:
2 |
3 | - Init
4 | - Create Keypair if not existent
5 | - Create sqlite db if necessary
6 | - Announce own device to support OMEMO
7 |
8 | - Receive Messages
9 | - Get devicelist updates and cache them
10 | - If a device receives an update -> check if own device is still announced.
11 | If not re-announce
12 |
13 | Furthermore, a device MUST announce it’s IdentityKey, a signed PreKey,
14 | and a list of PreKeys in a separate, per-device PEP node.
15 | The list SHOULD contain 100 PreKeys, but MUST contain no less than 20.
16 |
17 | - Build a Session
18 | - fetch their bundle
19 |
20 | - Sending a Message
21 | - In order to send a chat message, its first has to be encrypted.
22 | The client MUST use fresh, randomly generated key/IV pairs with AES-128 in
23 | Galois/Counter Mode (GCM). For each intended recipient device, i.e. both
24 | own devices as well as devices associated with the contact, this key is
25 | encrypted using the corresponding long-standing axolotl session.
26 | Each encrypted payload key is tagged with the recipient device’s ID.
27 | This is all serialized into a MessageElement,
28 | which is transmitted in a as follows:
29 |
30 |
31 | - Sending a key
32 | - The client may wish to transmit keying material to the contact. This
33 | first has to be generated. The client MUST generate a fresh, randomly
34 | generated key/IV pair. For each intended recipient device, i.e. both own
35 | devices as well as devices associated with the contact, this key is
36 | encrypted using the corresponding long-standing axolotl session.
37 | Each encrypted payload key is tagged with the recipient device’s ID.
38 | This is all serialized into a KeyTransportElement,
39 | omitting the as follows:
40 |
--------------------------------------------------------------------------------
/docs/images/omemo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReneVolution/profanity-omemo-plugin/bfb0337c318075a419c038fb47a66269e018ea23/docs/images/omemo.png
--------------------------------------------------------------------------------
/install.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | set -e
3 |
4 | which profanity > /dev/null
5 | which scanelf > /dev/null
6 | which tail > /dev/null
7 | which cut > /dev/null
8 | which tr > /dev/null
9 | which sed > /dev/null
10 |
11 | profanity="$(which profanity)"
12 | python_version="$(scanelf -n "${profanity}" | tail -n+2 | cut -d' ' -f2 | tr , '\n' | sed -nre 's/^libpython([0-9]+\.[0-9]+).*$/\1/p')"
13 |
14 | python"${python_version}" setup.py install --force --user --prefix=
15 | mkdir -p ~/.local/share/profanity/plugins
16 | cp deploy/prof_omemo_plugin.py ~/.local/share/profanity/plugins/
17 |
--------------------------------------------------------------------------------
/pytest.ini:
--------------------------------------------------------------------------------
1 | [pytest]
2 | testpaths = tests
3 | addopts = -v
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [bdist_wheel]
2 | # This flag says that the code is written to work on both Python 2 and Python
3 | # 3. If at all possible, it is good practice to do this. If you cannot, you
4 | # will need to generate wheels for each Python version that you support.
5 | universal=1
6 |
7 | [aliases]
8 | test=pytest
9 |
10 | [tool:pytest]
11 | addopts = --verbose
12 | python_files = tests/*/*.py
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | from __future__ import print_function
3 |
4 | import platform
5 | from codecs import open
6 | from glob import glob
7 | from os import path
8 | from os.path import basename
9 | from os.path import splitext
10 |
11 | from setuptools import setup, find_packages
12 | from setuptools.command.install import install
13 |
14 | here = path.abspath(path.dirname(__file__))
15 |
16 | # Get the long description from the README file
17 | with open(path.join(here, 'README.md'), encoding='utf-8') as f:
18 | long_description = f.read()
19 |
20 | requirements = [
21 | 'python-axolotl>=0.1.7',
22 | 'protobuf>=3.0.0b2,<3.2'
23 | ]
24 |
25 | if platform.python_implementation() == 'PyPy':
26 | requirements += ['pycrypto']
27 | else:
28 | requirements += ['cryptography>=1.1', 'pycrypto']
29 |
30 |
31 | setup(
32 | name='profanity-omemo-plugin',
33 | version='0.0.1',
34 | description=('A plugin to enable OMEMO encryption for '
35 | 'the profanity messenger.'),
36 |
37 | long_description=long_description,
38 | url='https://github.com/ReneVolution/profanity-omemo-plugin.git',
39 | author='Rene Calles',
40 | author_email='info@renevolution.com',
41 | license='GPL',
42 |
43 | # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
44 | classifiers=[
45 | 'Development Status :: 3 - Alpha',
46 | 'Intended Audience :: Developers',
47 | 'Topic :: Security :: Cryptography',
48 | 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', # noqa
49 | 'Programming Language :: Python :: 2',
50 | 'Programming Language :: Python :: 2.6',
51 | 'Programming Language :: Python :: 2.7',
52 | 'Programming Language :: Python :: 3',
53 | 'Programming Language :: Python :: 3.5',
54 | 'Programming Language :: Python :: 3.6',
55 | ],
56 |
57 | keywords='omemo encryption messaging profanity xmpp jabber',
58 | packages=find_packages('src'),
59 | package_dir={'': 'src'},
60 | py_modules=[splitext(basename(path))[0] for path in glob('src/*.py')],
61 | include_package_data=True,
62 | zip_safe=False,
63 | data_files=[('profanity_omemo_plugin', ['deploy/prof_omemo_plugin.py'])],
64 | install_requires=requirements,
65 | setup_requires=['pytest-runner'],
66 | tests_require=['pytest', 'mock'],
67 | )
68 |
--------------------------------------------------------------------------------
/src/profanity_omemo_plugin/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2017 René `reneVolution` Calles
4 | #
5 | # This file is part of Profanity OMEMO plugin.
6 | #
7 | # The Profanity OMEMO plugin 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
10 | # (at your option) any later version.
11 | #
12 | # The Profanity OMEMO plugin is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 | # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 | # more details.
16 | #
17 | # You should have received a copy of the GNU General Public License along with
18 | # the Profanity OMEMO plugin. If not, see .
19 | #
20 |
--------------------------------------------------------------------------------
/src/profanity_omemo_plugin/constants.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2017 René `reneVolution` Calles
4 | #
5 | # This file is part of Profanity OMEMO plugin.
6 | #
7 | # The Profanity OMEMO plugin 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
10 | # (at your option) any later version.
11 | #
12 | # The Profanity OMEMO plugin is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 | # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 | # more details.
16 | #
17 | # You should have received a copy of the GNU General Public License along with
18 | # the Profanity OMEMO plugin. If not, see .
19 | #
20 |
21 | from __future__ import unicode_literals
22 |
23 | import os
24 |
25 | PLUGIN_NAME = 'omemo'
26 |
27 | HOME = os.path.expanduser('~')
28 | XDG_DATA_HOME = os.environ.get('XDG_DATA_HOME', os.path.join(HOME, '.local', 'share'))
29 |
30 | LOGGER_NAME = 'ProfOmemoLogger'
31 | SETTINGS_GROUP = 'omemo'
32 | OMEMO_DEFAULT_ENABLED = True
33 | OMEMO_DEFAULT_MESSAGE_CHAR = '@'
34 |
35 | # OMEMO namespace constants
36 | NS_OMEMO = 'eu.siacs.conversations.axolotl'
37 | NS_DEVICE_LIST = NS_OMEMO + '.devicelist'
38 | NS_DEVICE_LIST_NOTIFY = NS_DEVICE_LIST + '+notify'
39 | NS_BUNDLES = NS_OMEMO + '.bundles'
40 |
--------------------------------------------------------------------------------
/src/profanity_omemo_plugin/db.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2017 René `reneVolution` Calles
4 | #
5 | # This file is part of Profanity OMEMO plugin.
6 | #
7 | # The Profanity OMEMO plugin 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
10 | # (at your option) any later version.
11 | #
12 | # The Profanity OMEMO plugin is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 | # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 | # more details.
16 | #
17 | # You should have received a copy of the GNU General Public License along with
18 | # the Profanity OMEMO plugin. If not, see .
19 | #
20 |
21 | from __future__ import absolute_import
22 | from __future__ import unicode_literals
23 |
24 | import os
25 |
26 | from profanity_omemo_plugin.constants import XDG_DATA_HOME
27 | from profanity_omemo_plugin.log import get_plugin_logger
28 |
29 | log = get_plugin_logger(__name__)
30 |
31 | try:
32 | import sqlite3
33 | except ImportError:
34 | log.error('Could not import sqlite3')
35 | raise
36 |
37 |
38 | def get_connection(user):
39 | """ Open in memory sqlite db and create a table. """
40 | db_path = _get_db_path(user)
41 | db_root = os.path.dirname(db_path)
42 | if not os.path.isdir(db_root):
43 | os.makedirs(db_root)
44 | log.info('Using database path {}'.format(db_path))
45 | conn = sqlite3.connect(db_path, check_same_thread=False)
46 | return conn
47 |
48 |
49 | def _get_local_data_path(user):
50 | if not user:
51 | raise RuntimeError('User cannot be None.')
52 |
53 | safe_username = user.replace('@', '_at_')
54 |
55 | return os.path.join(XDG_DATA_HOME, 'profanity', 'omemo', safe_username)
56 |
57 |
58 | def _get_db_path(user):
59 | return os.path.join(_get_local_data_path(user), 'omemo.db')
60 |
--------------------------------------------------------------------------------
/src/profanity_omemo_plugin/errors.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2017 René `reneVolution` Calles
4 | #
5 | # This file is part of Profanity OMEMO plugin.
6 | #
7 | # The Profanity OMEMO plugin 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
10 | # (at your option) any later version.
11 | #
12 | # The Profanity OMEMO plugin is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 | # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 | # more details.
16 | #
17 | # You should have received a copy of the GNU General Public License along with
18 | # the Profanity OMEMO plugin. If not, see .
19 | #
20 |
21 | class NoOmemoMessage(Exception):
22 | pass
23 |
24 |
25 | class UnhandledOmemoMessage(Exception):
26 | pass
27 |
28 |
29 | class StanzaNodeNotFound(Exception):
30 | pass
31 |
32 | class CouldNotCreateBundleStanza(Exception):
33 | pass
--------------------------------------------------------------------------------
/src/profanity_omemo_plugin/log.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2017 René `reneVolution` Calles
4 | #
5 | # This file is part of Profanity OMEMO plugin.
6 | #
7 | # The Profanity OMEMO plugin 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
10 | # (at your option) any later version.
11 | #
12 | # The Profanity OMEMO plugin is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 | # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 | # more details.
16 | #
17 | # You should have received a copy of the GNU General Public License along with
18 | # the Profanity OMEMO plugin. If not, see .
19 | #
20 |
21 | from __future__ import unicode_literals
22 |
23 | import logging
24 | import traceback
25 |
26 | PROFANITY_IS_HOST = True
27 |
28 | try:
29 | import prof
30 | except ImportError:
31 | PROFANITY_IS_HOST = False
32 |
33 |
34 | class ProfLogHandler(logging.Handler):
35 |
36 | def __init__(self, prefix=None):
37 | super(ProfLogHandler, self).__init__()
38 |
39 | if prefix:
40 | fmt_str = '{0} - %(message)s'.format(prefix)
41 | else:
42 | fmt_str = '%(name)s - %(message)s'
43 |
44 | self.prof_formatter = logging.Formatter(fmt_str)
45 | self.setFormatter(self.prof_formatter)
46 |
47 | def emit(self, record):
48 |
49 | if PROFANITY_IS_HOST:
50 | level_fn_map = {
51 | 10: prof.log_debug, # DEBUG
52 | 20: prof.log_info, # INFO
53 | 30: prof.log_warning, # WARNING
54 | 40: prof.log_error # ERROR
55 | }
56 |
57 | try:
58 | log_message = self.format(record)
59 | try:
60 | if record.levelno == 40 and record.exc_info:
61 | tb_info = record.exc_info
62 | log_message += '\n' + traceback.print_exception(*tb_info)
63 | except TypeError: # tb_info is None
64 | pass
65 |
66 | level_fn_map[record.levelno](log_message)
67 | except Exception as e:
68 | prof.log_error('Could not log last message. {0}'.format(repr(e)))
69 |
70 |
71 | python_omemo_logger = logging.getLogger('omemo')
72 | python_omemo_logger.setLevel(logging.DEBUG)
73 | python_omemo_logger.addHandler(ProfLogHandler())
74 |
75 |
76 | def get_plugin_logger(name):
77 | logger = logging.getLogger(name)
78 | logger.setLevel(logging.INFO)
79 | logger.addHandler(ProfLogHandler(prefix='ProfOmemoPlugin'))
80 |
81 | return logger
82 |
--------------------------------------------------------------------------------
/src/profanity_omemo_plugin/omemo/__init__.py:
--------------------------------------------------------------------------------
1 | __version__ = "0.1.0"
2 |
--------------------------------------------------------------------------------
/src/profanity_omemo_plugin/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 |
21 | import logging
22 | import sys
23 |
24 | from .aes_gcm_native import aes_decrypt
25 | from .aes_gcm_native import aes_encrypt
26 |
27 | log = logging.getLogger('gajim.plugin_system.omemo')
28 |
29 | def encrypt(key, iv, plaintext):
30 | return aes_encrypt(key, iv, plaintext)
31 |
32 |
33 | def decrypt(key, iv, ciphertext):
34 | plaintext = aes_decrypt(key, iv, ciphertext).decode('utf-8')
35 | if sys.version_info < (3, 0):
36 | return unicode(plaintext)
37 | else:
38 | return plaintext
39 |
40 |
41 | class NoValidSessions(Exception):
42 | pass
43 |
--------------------------------------------------------------------------------
/src/profanity_omemo_plugin/omemo/aes_gcm_native.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 |
21 | import logging
22 | import os
23 |
24 | from cryptography.hazmat.primitives.ciphers import Cipher
25 | from cryptography.hazmat.primitives.ciphers import algorithms
26 | from cryptography.hazmat.primitives.ciphers.modes import GCM
27 |
28 | # On Windows we have to import a specific backend because the
29 | # default_backend() mechanism doesnt work in Gajim for Windows.
30 | # Its because of how Gajim is build with cx_freeze
31 |
32 | if os.name == 'nt':
33 | from cryptography.hazmat.backends.openssl import backend
34 | else:
35 | from cryptography.hazmat.backends import default_backend
36 |
37 | log = logging.getLogger('gajim.plugin_system.omemo')
38 |
39 | def aes_decrypt(_key, iv, payload):
40 | """ Use AES128 GCM with the given key and iv to decrypt the payload. """
41 | if len(_key) >= 32:
42 | # XEP-0384
43 | log.debug('XEP Compliant Key/Tag')
44 | data = payload
45 | key = _key[:16]
46 | tag = _key[16:]
47 | else:
48 | # Legacy
49 | log.debug('Legacy Key/Tag')
50 | data = payload[:-16]
51 | key = _key
52 | tag = payload[-16:]
53 | if os.name == 'nt':
54 | _backend = backend
55 | else:
56 | _backend = default_backend()
57 | decryptor = Cipher(
58 | algorithms.AES(key),
59 | GCM(iv, tag=tag),
60 | backend=_backend).decryptor()
61 | return decryptor.update(data) + decryptor.finalize()
62 |
63 |
64 | def aes_encrypt(key, iv, plaintext):
65 | """ Use AES128 GCM with the given key and iv to encrypt the plaintext. """
66 | if os.name == 'nt':
67 | _backend = backend
68 | else:
69 | _backend = default_backend()
70 | encryptor = Cipher(
71 | algorithms.AES(key),
72 | GCM(iv),
73 | backend=_backend).encryptor()
74 | return encryptor.update(plaintext) + encryptor.finalize(), encryptor.tag
75 |
--------------------------------------------------------------------------------
/src/profanity_omemo_plugin/omemo/db_helpers.py:
--------------------------------------------------------------------------------
1 | ''' Database helper functions '''
2 |
3 |
4 | def table_exists(db, name):
5 | """ Check if the specified table exists in the db. """
6 |
7 | query = """ SELECT name FROM sqlite_master
8 | WHERE type='table' AND name=?;
9 | """
10 | return db.execute(query, (name, )).fetchone() is not None
11 |
12 |
13 | def user_version(db):
14 | """ Return the value of PRAGMA user_version. """
15 | return db.execute('PRAGMA user_version').fetchone()[0]
16 |
--------------------------------------------------------------------------------
/src/profanity_omemo_plugin/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 |
22 | class EncryptionState():
23 | """ Used to store if OMEMO is enabled or not between gajim restarts """
24 |
25 | def __init__(self, dbConn):
26 | """
27 | :type dbConn: Connection
28 | """
29 | self.dbConn = dbConn
30 |
31 | def activate(self, jid):
32 | q = """INSERT OR REPLACE INTO encryption_state (jid, encryption)
33 | VALUES (?, 1) """
34 |
35 | c = self.dbConn.cursor()
36 | c.execute(q, (jid, ))
37 | self.dbConn.commit()
38 |
39 | def deactivate(self, jid):
40 | q = """INSERT OR REPLACE INTO encryption_state (jid, encryption)
41 | VALUES (?, 0)"""
42 |
43 | c = self.dbConn.cursor()
44 | c.execute(q, (jid, ))
45 | self.dbConn.commit()
46 |
47 | def is_active(self, jid):
48 | q = 'SELECT encryption FROM encryption_state where jid = ?;'
49 | c = self.dbConn.cursor()
50 | c.execute(q, (jid, ))
51 | result = c.fetchone()
52 | if result is None:
53 | return False
54 | return result[0]
55 |
56 | def exist(self, jid):
57 | q = 'SELECT encryption FROM encryption_state where jid = ?;'
58 | c = self.dbConn.cursor()
59 | c.execute(q, (jid, ))
60 | result = c.fetchone()
61 | if result is None:
62 | return False
63 | else:
64 | return True
65 |
--------------------------------------------------------------------------------
/src/profanity_omemo_plugin/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 .encryption import EncryptionState
26 | from .liteidentitykeystore import LiteIdentityKeyStore
27 | from .liteprekeystore import LitePreKeyStore
28 | from .litesessionstore import LiteSessionStore
29 | from .litesignedprekeystore import LiteSignedPreKeyStore
30 | from .sql import SQLDatabase
31 |
32 | log = logging.getLogger('gajim.plugin_system.omemo')
33 |
34 | DEFAULT_PREKEY_AMOUNT = 100
35 | MIN_PREKEY_AMOUNT = 80
36 | SPK_ARCHIVE_TIME = 86400 * 15 # 15 Days
37 | SPK_CYCLE_TIME = 86400 # 24 Hours
38 |
39 |
40 | class LiteAxolotlStore(AxolotlStore):
41 | def __init__(self, connection):
42 | try:
43 | connection.text_factory = bytes
44 | except(AttributeError):
45 | raise AssertionError('Expected a sqlite3.Connection got ' +
46 | str(connection))
47 |
48 | self.sql = SQLDatabase(connection)
49 | self.identityKeyStore = LiteIdentityKeyStore(connection)
50 | self.preKeyStore = LitePreKeyStore(connection)
51 | self.signedPreKeyStore = LiteSignedPreKeyStore(connection)
52 | self.sessionStore = LiteSessionStore(connection)
53 | self.encryptionStore = EncryptionState(connection)
54 |
55 | if not self.getLocalRegistrationId():
56 | log.info("Generating Axolotl keys")
57 | self._generate_axolotl_keys()
58 |
59 | def _generate_axolotl_keys(self):
60 | identityKeyPair = KeyHelper.generateIdentityKeyPair()
61 | registrationId = KeyHelper.generateRegistrationId()
62 | preKeys = KeyHelper.generatePreKeys(KeyHelper.getRandomSequence(),
63 | DEFAULT_PREKEY_AMOUNT)
64 | self.storeLocalData(registrationId, identityKeyPair)
65 |
66 | signedPreKey = KeyHelper.generateSignedPreKey(
67 | identityKeyPair, KeyHelper.getRandomSequence(65536))
68 |
69 | self.storeSignedPreKey(signedPreKey.getId(), signedPreKey)
70 |
71 | for preKey in preKeys:
72 | self.storePreKey(preKey.getId(), preKey)
73 |
74 | def getIdentityKeyPair(self):
75 | return self.identityKeyStore.getIdentityKeyPair()
76 |
77 | def storeLocalData(self, registrationId, identityKeyPair):
78 | self.identityKeyStore.storeLocalData(registrationId, identityKeyPair)
79 |
80 | def getLocalRegistrationId(self):
81 | return self.identityKeyStore.getLocalRegistrationId()
82 |
83 | def saveIdentity(self, recepientId, identityKey):
84 | self.identityKeyStore.saveIdentity(recepientId, identityKey)
85 |
86 | def deleteIdentity(self, recipientId, identityKey):
87 | self.identityKeyStore.deleteIdentity(recipientId, identityKey)
88 |
89 | def isTrustedIdentity(self, recepientId, identityKey):
90 | return self.identityKeyStore.isTrustedIdentity(recepientId,
91 | identityKey)
92 |
93 | def setTrust(self, identityKey, trust):
94 | return self.identityKeyStore.setTrust(identityKey, trust)
95 |
96 | def getFingerprints(self, jid):
97 | return self.identityKeyStore.getFingerprints(jid)
98 |
99 | def getTrustedFingerprints(self, jid):
100 | return self.identityKeyStore.getTrustedFingerprints(jid)
101 |
102 | def getUndecidedFingerprints(self, jid):
103 | return self.identityKeyStore.getUndecidedFingerprints(jid)
104 |
105 | def setShownFingerprints(self, jid):
106 | return self.identityKeyStore.setShownFingerprints(jid)
107 |
108 | def getNewFingerprints(self, jid):
109 | return self.identityKeyStore.getNewFingerprints(jid)
110 |
111 | def loadPreKey(self, preKeyId):
112 | return self.preKeyStore.loadPreKey(preKeyId)
113 |
114 | def loadPreKeys(self):
115 | return self.preKeyStore.loadPendingPreKeys()
116 |
117 | def storePreKey(self, preKeyId, preKeyRecord):
118 | self.preKeyStore.storePreKey(preKeyId, preKeyRecord)
119 |
120 | def containsPreKey(self, preKeyId):
121 | return self.preKeyStore.containsPreKey(preKeyId)
122 |
123 | def removePreKey(self, preKeyId):
124 | self.preKeyStore.removePreKey(preKeyId)
125 |
126 | def loadSession(self, recepientId, deviceId):
127 | return self.sessionStore.loadSession(recepientId, deviceId)
128 |
129 | def getActiveDeviceTuples(self):
130 | return self.sessionStore.getActiveDeviceTuples()
131 |
132 | def getInactiveSessionsKeys(self, recipientId):
133 | return self.sessionStore.getInactiveSessionsKeys(recipientId)
134 |
135 | def getSubDeviceSessions(self, recepientId):
136 | # TODO Reuse this
137 | return self.sessionStore.getSubDeviceSessions(recepientId)
138 |
139 | def getJidFromDevice(self, device_id):
140 | return self.sessionStore.getJidFromDevice(device_id)
141 |
142 | def storeSession(self, recepientId, deviceId, sessionRecord):
143 | self.sessionStore.storeSession(recepientId, deviceId, sessionRecord)
144 |
145 | def containsSession(self, recepientId, deviceId):
146 | return self.sessionStore.containsSession(recepientId, deviceId)
147 |
148 | def deleteSession(self, recepientId, deviceId):
149 | self.sessionStore.deleteSession(recepientId, deviceId)
150 |
151 | def deleteAllSessions(self, recepientId):
152 | self.sessionStore.deleteAllSessions(recepientId)
153 |
154 | def getSessionsFromJid(self, recipientId):
155 | return self.sessionStore.getSessionsFromJid(recipientId)
156 |
157 | def getSessionsFromJids(self, recipientId):
158 | return self.sessionStore.getSessionsFromJids(recipientId)
159 |
160 | def getAllSessions(self):
161 | return self.sessionStore.getAllSessions()
162 |
163 | def loadSignedPreKey(self, signedPreKeyId):
164 | return self.signedPreKeyStore.loadSignedPreKey(signedPreKeyId)
165 |
166 | def loadSignedPreKeys(self):
167 | return self.signedPreKeyStore.loadSignedPreKeys()
168 |
169 | def storeSignedPreKey(self, signedPreKeyId, signedPreKeyRecord):
170 | self.signedPreKeyStore.storeSignedPreKey(signedPreKeyId,
171 | signedPreKeyRecord)
172 |
173 | def containsSignedPreKey(self, signedPreKeyId):
174 | return self.signedPreKeyStore.containsSignedPreKey(signedPreKeyId)
175 |
176 | def removeSignedPreKey(self, signedPreKeyId):
177 | self.signedPreKeyStore.removeSignedPreKey(signedPreKeyId)
178 |
179 | def getNextSignedPreKeyId(self):
180 | return self.signedPreKeyStore.getNextSignedPreKeyId()
181 |
182 | def getCurrentSignedPreKeyId(self):
183 | return self.signedPreKeyStore.getCurrentSignedPreKeyId()
184 |
185 | def getSignedPreKeyTimestamp(self, signedPreKeyId):
186 | return self.signedPreKeyStore.getSignedPreKeyTimestamp(signedPreKeyId)
187 |
188 | def removeOldSignedPreKeys(self, timestamp):
189 | self.signedPreKeyStore.removeOldSignedPreKeys(timestamp)
190 |
--------------------------------------------------------------------------------
/src/profanity_omemo_plugin/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 | UNDECIDED = 2
26 | TRUSTED = 1
27 | UNTRUSTED = 0
28 |
29 |
30 | class LiteIdentityKeyStore(IdentityKeyStore):
31 | def __init__(self, dbConn):
32 | """
33 | :type dbConn: Connection
34 | """
35 | self.dbConn = dbConn
36 |
37 | def getIdentityKeyPair(self):
38 | q = "SELECT public_key, private_key FROM identities " + \
39 | "WHERE recipient_id = -1"
40 | c = self.dbConn.cursor()
41 | c.execute(q)
42 | result = c.fetchone()
43 |
44 | publicKey, privateKey = result
45 | return IdentityKeyPair(
46 | IdentityKey(DjbECPublicKey(publicKey[1:])),
47 | DjbECPrivateKey(privateKey))
48 |
49 | def getLocalRegistrationId(self):
50 | q = "SELECT registration_id FROM identities WHERE recipient_id = -1"
51 | c = self.dbConn.cursor()
52 | c.execute(q)
53 | result = c.fetchone()
54 | return result[0] if result else None
55 |
56 | def storeLocalData(self, registrationId, identityKeyPair):
57 | q = "INSERT INTO identities( " + \
58 | "recipient_id, registration_id, public_key, private_key) " + \
59 | "VALUES(-1, ?, ?, ?)"
60 | c = self.dbConn.cursor()
61 | c.execute(q,
62 | (registrationId,
63 | identityKeyPair.getPublicKey().getPublicKey().serialize(),
64 | identityKeyPair.getPrivateKey().serialize()))
65 |
66 | self.dbConn.commit()
67 |
68 | def saveIdentity(self, recipientId, identityKey):
69 | q = "INSERT INTO identities (recipient_id, public_key, trust) " \
70 | "VALUES(?, ?, ?)"
71 | c = self.dbConn.cursor()
72 |
73 | if not self.getIdentity(recipientId, identityKey):
74 | c.execute(q, (recipientId,
75 | identityKey.getPublicKey().serialize(),
76 | UNDECIDED))
77 | self.dbConn.commit()
78 |
79 | def getIdentity(self, recipientId, identityKey):
80 | q = "SELECT * FROM identities WHERE recipient_id = ? " \
81 | "AND public_key = ?"
82 | c = self.dbConn.cursor()
83 |
84 | c.execute(q, (recipientId, identityKey.getPublicKey().serialize()))
85 | result = c.fetchone()
86 |
87 | return result is not None
88 |
89 | def deleteIdentity(self, recipientId, identityKey):
90 | q = "DELETE FROM identities WHERE recipient_id = ? AND public_key = ?"
91 | c = self.dbConn.cursor()
92 | c.execute(q, (recipientId,
93 | identityKey.getPublicKey().serialize()))
94 | self.dbConn.commit()
95 |
96 | def isTrustedIdentity(self, recipientId, identityKey):
97 | q = "SELECT trust FROM identities WHERE recipient_id = ? " \
98 | "AND public_key = ?"
99 | c = self.dbConn.cursor()
100 |
101 | c.execute(q, (recipientId, identityKey.getPublicKey().serialize()))
102 | result = c.fetchone()
103 |
104 | states = [UNTRUSTED, TRUSTED, UNDECIDED]
105 |
106 | if result and result[0] in states:
107 | return result[0]
108 | else:
109 | return True
110 |
111 | def getAllFingerprints(self):
112 | q = "SELECT _id, recipient_id, public_key, trust FROM identities " \
113 | "WHERE recipient_id != -1 ORDER BY recipient_id ASC"
114 | c = self.dbConn.cursor()
115 |
116 | result = []
117 | for row in c.execute(q):
118 | result.append((row[0], row[1], row[2], row[3]))
119 | return result
120 |
121 | def getFingerprints(self, jid):
122 | q = "SELECT _id, recipient_id, public_key, trust FROM identities " \
123 | "WHERE recipient_id =? ORDER BY trust ASC"
124 | c = self.dbConn.cursor()
125 |
126 | result = []
127 | c.execute(q, (jid,))
128 | rows = c.fetchall()
129 | for row in rows:
130 | result.append((row[0], row[1], row[2], row[3]))
131 | return result
132 |
133 | def getTrustedFingerprints(self, jid):
134 | q = "SELECT public_key FROM identities WHERE recipient_id = ? AND trust = ?"
135 | c = self.dbConn.cursor()
136 |
137 | result = []
138 | c.execute(q, (jid, TRUSTED))
139 | rows = c.fetchall()
140 | for row in rows:
141 | result.append(row[0])
142 | return result
143 |
144 | def getUndecidedFingerprints(self, jid):
145 | q = "SELECT trust FROM identities WHERE recipient_id = ? AND trust = ?"
146 | c = self.dbConn.cursor()
147 |
148 | result = []
149 | c.execute(q, (jid, UNDECIDED))
150 | result = c.fetchall()
151 |
152 | return result
153 |
154 | def getNewFingerprints(self, jid):
155 | q = "SELECT _id FROM identities WHERE shown = 0 AND " \
156 | "recipient_id = ?"
157 | c = self.dbConn.cursor()
158 | result = []
159 | for row in c.execute(q, (jid,)):
160 | result.append(row[0])
161 | return result
162 |
163 | def setShownFingerprints(self, fingerprints):
164 | q = "UPDATE identities SET shown = 1 WHERE _id IN ({})" \
165 | .format(', '.join(['?'] * len(fingerprints)))
166 | c = self.dbConn.cursor()
167 | c.execute(q, fingerprints)
168 | self.dbConn.commit()
169 |
170 | def setTrust(self, identityKey, trust):
171 | q = "UPDATE identities SET trust = ? WHERE public_key = ?"
172 | c = self.dbConn.cursor()
173 | c.execute(q, (trust, identityKey.getPublicKey().serialize()))
174 | self.dbConn.commit()
175 |
--------------------------------------------------------------------------------
/src/profanity_omemo_plugin/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 | from axolotl.util.keyhelper import KeyHelper
23 |
24 |
25 | class LitePreKeyStore(PreKeyStore):
26 | def __init__(self, dbConn):
27 | """
28 | :type dbConn: Connection
29 | """
30 | self.dbConn = dbConn
31 |
32 | def loadPreKey(self, preKeyId):
33 | q = "SELECT record FROM prekeys WHERE prekey_id = ?"
34 |
35 | cursor = self.dbConn.cursor()
36 | cursor.execute(q, (preKeyId, ))
37 |
38 | result = cursor.fetchone()
39 | if not result:
40 | raise Exception("No such prekeyRecord!")
41 |
42 | return PreKeyRecord(serialized=result[0])
43 |
44 | def loadPendingPreKeys(self):
45 | q = "SELECT record FROM prekeys"
46 | cursor = self.dbConn.cursor()
47 | cursor.execute(q)
48 | result = cursor.fetchall()
49 |
50 | return [PreKeyRecord(serialized=r[0]) for r in result]
51 |
52 | def storePreKey(self, preKeyId, preKeyRecord):
53 | q = "INSERT INTO prekeys (prekey_id, record) VALUES(?,?)"
54 | cursor = self.dbConn.cursor()
55 | cursor.execute(q, (preKeyId, preKeyRecord.serialize()))
56 | self.dbConn.commit()
57 |
58 | def containsPreKey(self, preKeyId):
59 | q = "SELECT record FROM prekeys WHERE prekey_id = ?"
60 | cursor = self.dbConn.cursor()
61 | cursor.execute(q, (preKeyId, ))
62 | return cursor.fetchone() is not None
63 |
64 | def removePreKey(self, preKeyId):
65 | q = "DELETE FROM prekeys WHERE prekey_id = ?"
66 | cursor = self.dbConn.cursor()
67 | cursor.execute(q, (preKeyId, ))
68 | self.dbConn.commit()
69 |
70 | def getCurrentPreKeyId(self):
71 | q = "SELECT MAX(prekey_id) FROM prekeys"
72 | cursor = self.dbConn.cursor()
73 | cursor.execute(q)
74 | return cursor.fetchone()[0]
75 |
76 | def getPreKeyCount(self):
77 | q = "SELECT COUNT(prekey_id) FROM prekeys"
78 | cursor = self.dbConn.cursor()
79 | cursor.execute(q)
80 | return cursor.fetchone()[0]
81 |
82 | def generateNewPreKeys(self, count):
83 | startId = self.getCurrentPreKeyId() + 1
84 | preKeys = KeyHelper.generatePreKeys(startId, count)
85 |
86 | for preKey in preKeys:
87 | self.storePreKey(preKey.getId(), preKey)
88 |
--------------------------------------------------------------------------------
/src/profanity_omemo_plugin/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 |
31 | def loadSession(self, recipientId, deviceId):
32 | q = "SELECT record FROM sessions WHERE recipient_id = ? AND device_id = ?"
33 | c = self.dbConn.cursor()
34 | c.execute(q, (recipientId, deviceId))
35 | result = c.fetchone()
36 |
37 | if result:
38 | return SessionRecord(serialized=result[0])
39 | else:
40 | return SessionRecord()
41 |
42 | def getSubDeviceSessions(self, recipientId):
43 | q = "SELECT device_id from sessions WHERE recipient_id = ?"
44 | c = self.dbConn.cursor()
45 | c.execute(q, (recipientId, ))
46 | result = c.fetchall()
47 |
48 | deviceIds = [r[0] for r in result]
49 | return deviceIds
50 |
51 | def getJidFromDevice(self, device_id):
52 | q = "SELECT recipient_id from sessions WHERE device_id = ?"
53 | c = self.dbConn.cursor()
54 | c.execute(q, (device_id, ))
55 | result = c.fetchone()
56 |
57 | return result[0]
58 |
59 | def getActiveDeviceTuples(self):
60 | q = "SELECT recipient_id, device_id FROM sessions WHERE active = 1"
61 | c = self.dbConn.cursor()
62 | result = []
63 | for row in c.execute(q):
64 | result.append((row[0], row[1]))
65 | return result
66 |
67 | def storeSession(self, recipientId, deviceId, sessionRecord):
68 | self.deleteSession(recipientId, deviceId)
69 |
70 | q = "INSERT INTO sessions(recipient_id, device_id, record) VALUES(?,?,?)"
71 | c = self.dbConn.cursor()
72 | c.execute(q, (recipientId, deviceId, sessionRecord.serialize()))
73 | self.dbConn.commit()
74 |
75 | def containsSession(self, recipientId, deviceId):
76 | q = "SELECT record FROM sessions WHERE recipient_id = ? AND device_id = ?"
77 | c = self.dbConn.cursor()
78 | c.execute(q, (recipientId, deviceId))
79 | result = c.fetchone()
80 |
81 | return result is not None
82 |
83 | def deleteSession(self, recipientId, deviceId):
84 | q = "DELETE FROM sessions WHERE recipient_id = ? AND device_id = ?"
85 | self.dbConn.cursor().execute(q, (recipientId, deviceId))
86 | self.dbConn.commit()
87 |
88 | def deleteAllSessions(self, recipientId):
89 | q = "DELETE FROM sessions WHERE recipient_id = ?"
90 | self.dbConn.cursor().execute(q, (recipientId, ))
91 | self.dbConn.commit()
92 |
93 | def getAllSessions(self):
94 | q = "SELECT _id, recipient_id, device_id, record, active from sessions"
95 | c = self.dbConn.cursor()
96 | result = []
97 | for row in c.execute(q):
98 | result.append((row[0], row[1], row[2], row[3], row[4]))
99 | return result
100 |
101 | def getSessionsFromJid(self, recipientId):
102 | q = "SELECT _id, recipient_id, device_id, record, active from sessions" \
103 | " WHERE recipient_id = ?"
104 | c = self.dbConn.cursor()
105 | result = []
106 | for row in c.execute(q, (recipientId,)):
107 | result.append((row[0], row[1], row[2], row[3], row[4]))
108 | return result
109 |
110 | def getSessionsFromJids(self, recipientId):
111 | q = "SELECT _id, recipient_id, device_id, record, active from sessions" \
112 | " WHERE recipient_id IN ({})" \
113 | .format(', '.join(['?'] * len(recipientId)))
114 | c = self.dbConn.cursor()
115 | result = []
116 | for row in c.execute(q, recipientId):
117 | result.append((row[0], row[1], row[2], row[3], row[4]))
118 | return result
119 |
120 | def setActiveState(self, deviceList, jid):
121 | c = self.dbConn.cursor()
122 |
123 | q = "UPDATE sessions SET active = {} " \
124 | "WHERE recipient_id = '{}' AND device_id IN ({})" \
125 | .format(1, jid, ', '.join(['?'] * len(deviceList)))
126 | c.execute(q, deviceList)
127 |
128 | q = "UPDATE sessions SET active = {} " \
129 | "WHERE recipient_id = '{}' AND device_id NOT IN ({})" \
130 | .format(0, jid, ', '.join(['?'] * len(deviceList)))
131 | c.execute(q, deviceList)
132 | self.dbConn.commit()
133 |
134 | def getInactiveSessionsKeys(self, recipientId):
135 | q = "SELECT record FROM sessions WHERE active = 0 AND recipient_id = ?"
136 | c = self.dbConn.cursor()
137 | result = []
138 | for row in c.execute(q, (recipientId,)):
139 | public_key = (SessionRecord(serialized=row[0]).
140 | getSessionState().getRemoteIdentityKey().
141 | getPublicKey())
142 | result.append(public_key.serialize())
143 | return result
144 |
--------------------------------------------------------------------------------
/src/profanity_omemo_plugin/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 | from axolotl.util.medium import Medium
24 |
25 |
26 | class LiteSignedPreKeyStore(SignedPreKeyStore):
27 | def __init__(self, dbConn):
28 | """
29 | :type dbConn: Connection
30 | """
31 | self.dbConn = dbConn
32 |
33 | def loadSignedPreKey(self, signedPreKeyId):
34 | q = "SELECT record FROM signed_prekeys WHERE prekey_id = ?"
35 |
36 | cursor = self.dbConn.cursor()
37 | cursor.execute(q, (signedPreKeyId, ))
38 |
39 | result = cursor.fetchone()
40 | if not result:
41 | raise InvalidKeyIdException("No such signedprekeyrecord! %s " %
42 | signedPreKeyId)
43 |
44 | return SignedPreKeyRecord(serialized=result[0])
45 |
46 | def loadSignedPreKeys(self):
47 | q = "SELECT record FROM signed_prekeys"
48 |
49 | cursor = self.dbConn.cursor()
50 | cursor.execute(q, )
51 | result = cursor.fetchall()
52 | results = []
53 | for row in result:
54 | results.append(SignedPreKeyRecord(serialized=row[0]))
55 |
56 | return results
57 |
58 | def storeSignedPreKey(self, signedPreKeyId, signedPreKeyRecord):
59 | q = "INSERT INTO signed_prekeys (prekey_id, record) VALUES(?,?)"
60 | cursor = self.dbConn.cursor()
61 | cursor.execute(q, (signedPreKeyId, signedPreKeyRecord.serialize()))
62 | self.dbConn.commit()
63 |
64 | def containsSignedPreKey(self, signedPreKeyId):
65 | q = "SELECT record FROM signed_prekeys WHERE prekey_id = ?"
66 | cursor = self.dbConn.cursor()
67 | cursor.execute(q, (signedPreKeyId, ))
68 | return cursor.fetchone() is not None
69 |
70 | def removeSignedPreKey(self, signedPreKeyId):
71 | q = "DELETE FROM signed_prekeys WHERE prekey_id = ?"
72 | cursor = self.dbConn.cursor()
73 | cursor.execute(q, (signedPreKeyId, ))
74 | self.dbConn.commit()
75 |
76 | def getNextSignedPreKeyId(self):
77 | result = self.getCurrentSignedPreKeyId()
78 | if not result:
79 | return 1 # StartId if no SignedPreKeys exist
80 | else:
81 | return (result % (Medium.MAX_VALUE - 1)) + 1
82 |
83 | def getCurrentSignedPreKeyId(self):
84 | q = "SELECT MAX(prekey_id) FROM signed_prekeys"
85 |
86 | cursor = self.dbConn.cursor()
87 | cursor.execute(q)
88 | result = cursor.fetchone()
89 | if not result:
90 | return None
91 | else:
92 | return result[0]
93 |
94 | def getSignedPreKeyTimestamp(self, signedPreKeyId):
95 | q = "SELECT strftime('%s', timestamp) FROM " \
96 | "signed_prekeys WHERE prekey_id = ?"
97 |
98 | cursor = self.dbConn.cursor()
99 | cursor.execute(q, (signedPreKeyId, ))
100 |
101 | result = cursor.fetchone()
102 | if not result:
103 | raise InvalidKeyIdException("No such signedprekeyrecord! %s " %
104 | signedPreKeyId)
105 |
106 | return result[0]
107 |
108 | def removeOldSignedPreKeys(self, timestamp):
109 | q = "DELETE FROM signed_prekeys " \
110 | "WHERE timestamp < datetime(?, 'unixepoch')"
111 | cursor = self.dbConn.cursor()
112 | cursor.execute(q, (timestamp, ))
113 | self.dbConn.commit()
114 |
--------------------------------------------------------------------------------
/src/profanity_omemo_plugin/omemo/sql.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 | from .db_helpers import user_version
20 |
21 |
22 | class SQLDatabase():
23 | """ SQL Database """
24 |
25 | def __init__(self, dbConn):
26 | """
27 | :type dbConn: Connection
28 | """
29 | self.dbConn = dbConn
30 | self.createDb()
31 | self.migrateDb()
32 | c = self.dbConn.cursor()
33 | c.execute("PRAGMA synchronous=NORMAL;")
34 | c.execute("PRAGMA journal_mode;")
35 | mode = c.fetchone()[0]
36 | # WAL is a persistent DB mode, dont override it if user has set it
37 | if mode != 'wal':
38 | c.execute("PRAGMA journal_mode=MEMORY;")
39 | self.dbConn.commit()
40 |
41 | def createDb(self):
42 | if user_version(self.dbConn) == 0:
43 |
44 | # Creates
45 | # IdentityKeyStore
46 | # PreKeyStore
47 | # SignedPreKeyStore
48 | # SessionStore
49 | # EncryptionStore
50 |
51 | create_tables = '''
52 | CREATE TABLE IF NOT EXISTS identities (
53 | _id INTEGER PRIMARY KEY AUTOINCREMENT, recipient_id TEXT,
54 | registration_id INTEGER, public_key BLOB, private_key BLOB,
55 | next_prekey_id INTEGER, timestamp INTEGER, trust INTEGER,
56 | shown INTEGER DEFAULT 0);
57 |
58 | CREATE UNIQUE INDEX IF NOT EXISTS
59 | public_key_index ON identities (public_key, recipient_id);
60 |
61 | CREATE TABLE IF NOT EXISTS prekeys(
62 | _id INTEGER PRIMARY KEY AUTOINCREMENT,
63 | prekey_id INTEGER UNIQUE, sent_to_server BOOLEAN,
64 | record BLOB);
65 |
66 | CREATE TABLE IF NOT EXISTS signed_prekeys (
67 | _id INTEGER PRIMARY KEY AUTOINCREMENT,
68 | prekey_id INTEGER UNIQUE,
69 | timestamp NUMERIC DEFAULT CURRENT_TIMESTAMP, record BLOB);
70 |
71 | CREATE TABLE IF NOT EXISTS sessions (
72 | _id INTEGER PRIMARY KEY AUTOINCREMENT,
73 | recipient_id TEXT, device_id INTEGER,
74 | record BLOB, timestamp INTEGER, active INTEGER DEFAULT 1,
75 | UNIQUE(recipient_id, device_id));
76 |
77 | CREATE TABLE IF NOT EXISTS encryption_state (
78 | id INTEGER PRIMARY KEY AUTOINCREMENT,
79 | jid TEXT UNIQUE,
80 | encryption INTEGER
81 | );
82 | '''
83 |
84 | create_db_sql = """
85 | BEGIN TRANSACTION;
86 | %s
87 | PRAGMA user_version=5;
88 | END TRANSACTION;
89 | """ % (create_tables)
90 | self.dbConn.executescript(create_db_sql)
91 |
92 | def migrateDb(self):
93 | """ Migrates the DB
94 | """
95 |
96 | # Find all double entrys and delete them
97 | if user_version(self.dbConn) < 2:
98 | delete_dupes = """ DELETE FROM identities WHERE _id not in (
99 | SELECT MIN(_id)
100 | FROM identities
101 | GROUP BY
102 | recipient_id, public_key
103 | );
104 | """
105 |
106 | self.dbConn.executescript(""" BEGIN TRANSACTION;
107 | %s
108 | PRAGMA user_version=2;
109 | END TRANSACTION;
110 | """ % (delete_dupes))
111 |
112 | if user_version(self.dbConn) < 3:
113 | # Create a UNIQUE INDEX so every public key/recipient_id tuple
114 | # can only be once in the db
115 | add_index = """ CREATE UNIQUE INDEX IF NOT EXISTS
116 | public_key_index
117 | ON identities (public_key, recipient_id);
118 | """
119 |
120 | self.dbConn.executescript(""" BEGIN TRANSACTION;
121 | %s
122 | PRAGMA user_version=3;
123 | END TRANSACTION;
124 | """ % (add_index))
125 |
126 | if user_version(self.dbConn) < 4:
127 | # Adds column "active" to the sessions table
128 | add_active = """ ALTER TABLE sessions
129 | ADD COLUMN active INTEGER DEFAULT 1;
130 | """
131 |
132 | self.dbConn.executescript(""" BEGIN TRANSACTION;
133 | %s
134 | PRAGMA user_version=4;
135 | END TRANSACTION;
136 | """ % (add_active))
137 |
138 | if user_version(self.dbConn) < 5:
139 | # Adds DEFAULT Timestamp
140 | add_timestamp = """
141 | DROP TABLE signed_prekeys;
142 | CREATE TABLE IF NOT EXISTS signed_prekeys (
143 | _id INTEGER PRIMARY KEY AUTOINCREMENT,
144 | prekey_id INTEGER UNIQUE,
145 | timestamp NUMERIC DEFAULT CURRENT_TIMESTAMP, record BLOB);
146 | ALTER TABLE identities ADD COLUMN shown INTEGER DEFAULT 0;
147 | UPDATE identities SET shown = 1;
148 | """
149 |
150 | self.dbConn.executescript(""" BEGIN TRANSACTION;
151 | %s
152 | PRAGMA user_version=5;
153 | END TRANSACTION;
154 | """ % (add_timestamp))
155 |
--------------------------------------------------------------------------------
/src/profanity_omemo_plugin/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 time
22 | from base64 import b64encode
23 |
24 | from Crypto.Random import get_random_bytes
25 | from axolotl.duplicatemessagexception import DuplicateMessageException
26 | from axolotl.ecc.djbec import DjbECPublicKey
27 | from axolotl.identitykey import IdentityKey
28 | from axolotl.invalidmessageexception import InvalidMessageException
29 | from axolotl.invalidversionexception import InvalidVersionException
30 | from axolotl.nosessionexception import NoSessionException
31 | from axolotl.protocol.prekeywhispermessage import PreKeyWhisperMessage
32 | from axolotl.protocol.whispermessage import WhisperMessage
33 | from axolotl.sessionbuilder import SessionBuilder
34 | from axolotl.sessioncipher import SessionCipher
35 | from axolotl.state.prekeybundle import PreKeyBundle
36 | from axolotl.untrustedidentityexception import UntrustedIdentityException
37 | from axolotl.util.keyhelper import KeyHelper
38 |
39 | from .aes_gcm import NoValidSessions, decrypt, encrypt
40 | from .liteaxolotlstore import (LiteAxolotlStore, DEFAULT_PREKEY_AMOUNT,
41 | MIN_PREKEY_AMOUNT, SPK_CYCLE_TIME,
42 | SPK_ARCHIVE_TIME)
43 |
44 | log = logging.getLogger('gajim.plugin_system.omemo')
45 | logAxolotl = logging.getLogger('axolotl')
46 |
47 |
48 | UNTRUSTED = 0
49 | TRUSTED = 1
50 | UNDECIDED = 2
51 |
52 |
53 | class OmemoState:
54 | def __init__(self, own_jid, connection, account, plugin):
55 | """ Instantiates an OmemoState object.
56 |
57 | :param connection: an :py:class:`sqlite3.Connection`
58 | """
59 | self.account = account
60 | self.plugin = plugin
61 | self.session_ciphers = {}
62 | self.own_jid = own_jid
63 | self.device_ids = {}
64 | self.own_devices = []
65 | self.store = LiteAxolotlStore(connection)
66 | self.encryption = self.store.encryptionStore
67 | for jid, device_id in self.store.getActiveDeviceTuples():
68 | if jid != own_jid:
69 | self.add_device(jid, device_id)
70 | else:
71 | self.add_own_device(device_id)
72 |
73 | log.info(self.account + ' => Roster devices after boot:' +
74 | str(self.device_ids))
75 | log.info(self.account + ' => Own devices after boot:' +
76 | str(self.own_devices))
77 | log.debug(self.account + ' => ' +
78 | str(self.store.preKeyStore.getPreKeyCount()) +
79 | ' PreKeys available')
80 |
81 | def build_session(self, recipient_id, device_id, bundle_dict):
82 | sessionBuilder = SessionBuilder(self.store, self.store, self.store,
83 | self.store, recipient_id, device_id)
84 |
85 | registration_id = self.store.getLocalRegistrationId()
86 |
87 | preKeyPublic = DjbECPublicKey(bundle_dict['preKeyPublic'][1:])
88 |
89 | signedPreKeyPublic = DjbECPublicKey(bundle_dict['signedPreKeyPublic'][
90 | 1:])
91 | identityKey = IdentityKey(DjbECPublicKey(bundle_dict['identityKey'][
92 | 1:]))
93 |
94 | prekey_bundle = PreKeyBundle(
95 | registration_id, device_id, bundle_dict['preKeyId'], preKeyPublic,
96 | bundle_dict['signedPreKeyId'], signedPreKeyPublic,
97 | bundle_dict['signedPreKeySignature'], identityKey)
98 |
99 | sessionBuilder.processPreKeyBundle(prekey_bundle)
100 | return self.get_session_cipher(recipient_id, device_id)
101 |
102 | def set_devices(self, name, devices):
103 | """ Return a an.
104 |
105 | Parameters
106 | ----------
107 | jid : string
108 | The contacts jid
109 |
110 | devices: [int]
111 | A list of devices
112 | """
113 |
114 | self.device_ids[name] = devices
115 | log.info(self.account + ' => Saved devices for ' + name)
116 |
117 | def add_device(self, name, device_id):
118 | if name not in self.device_ids:
119 | self.device_ids[name] = [device_id]
120 | elif device_id not in self.device_ids[name]:
121 | self.device_ids[name].append(device_id)
122 |
123 | def set_own_devices(self, devices):
124 | """ Overwrite the current :py:attribute:`OmemoState.own_devices` with
125 | the given devices.
126 |
127 | Parameters
128 | ----------
129 | devices : [int]
130 | A list of device_ids
131 | """
132 | self.own_devices = devices
133 | log.info(self.account + ' => Saved own devices')
134 |
135 | def add_own_device(self, device_id):
136 | if device_id not in self.own_devices:
137 | self.own_devices.append(device_id)
138 |
139 | @property
140 | def own_device_id(self):
141 | reg_id = self.store.getLocalRegistrationId()
142 | assert reg_id is not None, \
143 | "Requested device_id but there is no generated"
144 |
145 | return ((reg_id % 2147483646) + 1)
146 |
147 | def own_device_id_published(self):
148 | """ Return `True` only if own device id was added via
149 | :py:method:`OmemoState.set_own_devices()`.
150 | """
151 | return self.own_device_id in self.own_devices
152 |
153 | @property
154 | def bundle(self):
155 | self.checkPreKeyAmount()
156 | prekeys = [
157 | (k.getId(), b64encode(k.getKeyPair().getPublicKey().serialize()))
158 | for k in self.store.loadPreKeys()
159 | ]
160 |
161 | identityKeyPair = self.store.getIdentityKeyPair()
162 |
163 | self.cycleSignedPreKey(identityKeyPair)
164 |
165 | signedPreKey = self.store.loadSignedPreKey(
166 | self.store.getCurrentSignedPreKeyId())
167 |
168 | result = {
169 | 'signedPreKeyId': signedPreKey.getId(),
170 | 'signedPreKeyPublic':
171 | b64encode(signedPreKey.getKeyPair().getPublicKey().serialize()),
172 | 'signedPreKeySignature': b64encode(signedPreKey.getSignature()),
173 | 'identityKey':
174 | b64encode(identityKeyPair.getPublicKey().serialize()),
175 | 'prekeys': prekeys
176 | }
177 | return result
178 |
179 | def decrypt_msg(self, msg_dict):
180 | own_id = self.own_device_id
181 | if msg_dict['sid'] == own_id:
182 | log.info('Received previously sent message by us')
183 | return
184 | if own_id not in msg_dict['keys']:
185 | log.warning('OMEMO message does not contain our device key')
186 | return
187 |
188 | iv = msg_dict['iv']
189 | sid = msg_dict['sid']
190 | sender_jid = msg_dict['sender_jid']
191 | payload = msg_dict['payload']
192 |
193 | encrypted_key = msg_dict['keys'][own_id]
194 |
195 | try:
196 | key = self.handlePreKeyWhisperMessage(sender_jid, sid,
197 | encrypted_key)
198 | except (InvalidVersionException, InvalidMessageException):
199 | try:
200 | key = self.handleWhisperMessage(sender_jid, sid, encrypted_key)
201 | except (NoSessionException, InvalidMessageException) as e:
202 | log.warning('No Session found ' + e.message)
203 | log.warning('sender_jid => ' + str(sender_jid) + ' sid =>' +
204 | str(sid))
205 | return
206 | except (DuplicateMessageException) as e:
207 | log.warning('Duplicate message found ' + str(e.args))
208 | return
209 |
210 | except (DuplicateMessageException) as e:
211 | log.warning('Duplicate message found ' + str(e.args))
212 | return
213 |
214 | result = decrypt(key, iv, payload)
215 | try:
216 | result = unicode(result)
217 | except NameError: # Py3
218 | pass
219 |
220 | log.debug("Decrypted Message => " + result)
221 | return result
222 |
223 | def create_msg(self, from_jid, jid, plaintext):
224 | key = get_random_bytes(16)
225 | iv = get_random_bytes(16)
226 | encrypted_keys = {}
227 |
228 | devices_list = self.device_list_for(jid)
229 | if len(devices_list) == 0:
230 | log.error('No known devices')
231 | return
232 |
233 | payload, tag = encrypt(key, iv, plaintext)
234 |
235 | key += tag
236 |
237 | # Encrypt the message key with for each of receivers devices
238 | for device in devices_list:
239 | try:
240 | if self.isTrusted(jid, device) == TRUSTED:
241 | cipher = self.get_session_cipher(jid, device)
242 | cipher_key = cipher.encrypt(key)
243 | prekey = isinstance(cipher_key, PreKeyWhisperMessage)
244 | encrypted_keys[device] = (cipher_key.serialize(), prekey)
245 | else:
246 | log.debug('Skipped Device because Trust is: ' +
247 | str(self.isTrusted(jid, device)))
248 | except:
249 | log.warning('Failed to find key for device ' + str(device))
250 |
251 | if len(encrypted_keys) == 0:
252 | log.error('Encrypted keys empty')
253 | raise NoValidSessions('Encrypted keys empty')
254 |
255 | my_other_devices = set(self.own_devices) - set({self.own_device_id})
256 | # Encrypt the message key with for each of our own devices
257 | for device in my_other_devices:
258 | try:
259 | if self.isTrusted(from_jid, device) == TRUSTED:
260 | cipher = self.get_session_cipher(from_jid, device)
261 | cipher_key = cipher.encrypt(key)
262 | prekey = isinstance(cipher_key, PreKeyWhisperMessage)
263 | encrypted_keys[device] = (cipher_key.serialize(), prekey)
264 | else:
265 | log.debug('Skipped own Device because Trust is: ' +
266 | str(self.isTrusted(from_jid, device)))
267 | except:
268 | log.warning('Failed to find key for device ' + str(device))
269 |
270 | result = {'sid': self.own_device_id,
271 | 'keys': encrypted_keys,
272 | 'jid': jid,
273 | 'iv': iv,
274 | 'payload': payload}
275 |
276 | log.debug('Finished encrypting message')
277 | return result
278 |
279 | def create_gc_msg(self, from_jid, jid, plaintext):
280 | key = get_random_bytes(16)
281 | iv = get_random_bytes(16)
282 | encrypted_keys = {}
283 | room = jid
284 | encrypted_jids = []
285 |
286 | devices_list = self.device_list_for(jid, True)
287 |
288 | if len(devices_list) == 0:
289 | log.error('No known devices')
290 | return
291 |
292 | payload, tag = encrypt(key, iv, plaintext)
293 |
294 | key += tag
295 |
296 | for tup in devices_list:
297 | self.get_session_cipher(tup[0], tup[1])
298 |
299 | # Encrypt the message key with for each of receivers devices
300 | for nick in self.plugin.groupchat[room]:
301 | jid_to = self.plugin.groupchat[room][nick]
302 | if jid_to == self.own_jid:
303 | continue
304 | if jid_to in encrypted_jids: # We already encrypted to this JID
305 | continue
306 | for rid, cipher in self.session_ciphers[jid_to].items():
307 | try:
308 | if self.isTrusted(jid_to, rid) == TRUSTED:
309 | cipher_key = cipher.encrypt(key)
310 | prekey = isinstance(cipher_key, PreKeyWhisperMessage)
311 | encrypted_keys[rid] = (cipher_key.serialize(), prekey)
312 | else:
313 | log.debug('Skipped Device because Trust is: ' +
314 | str(self.isTrusted(jid_to, rid)))
315 | except:
316 | log.exception('ERROR:')
317 | log.warning('Failed to find key for device ' +
318 | str(rid))
319 | encrypted_jids.append(jid_to)
320 | if len(encrypted_keys) == 0:
321 | log_msg = 'Encrypted keys empty'
322 | log.error(log_msg)
323 | raise NoValidSessions(log_msg)
324 |
325 | my_other_devices = set(self.own_devices) - set({self.own_device_id})
326 | # Encrypt the message key with for each of our own devices
327 | for dev in my_other_devices:
328 | try:
329 | cipher = self.get_session_cipher(from_jid, dev)
330 | if self.isTrusted(from_jid, dev) == TRUSTED:
331 | cipher_key = cipher.encrypt(key)
332 | prekey = isinstance(cipher_key, PreKeyWhisperMessage)
333 | encrypted_keys[dev] = (cipher_key.serialize(), prekey)
334 | else:
335 | log.debug('Skipped own Device because Trust is: ' +
336 | str(self.isTrusted(from_jid, dev)))
337 | except:
338 | log.exception('ERROR:')
339 | log.warning('Failed to find key for device ' + str(dev))
340 |
341 | result = {'sid': self.own_device_id,
342 | 'keys': encrypted_keys,
343 | 'jid': jid,
344 | 'iv': iv,
345 | 'payload': payload}
346 |
347 | log.debug('Finished encrypting message')
348 | return result
349 |
350 | def device_list_for(self, jid, gc=False):
351 | """ Return a list of known device ids for the specified jid.
352 | Parameters
353 | ----------
354 | jid : string
355 | The contacts jid
356 | gc : bool
357 | Groupchat Message
358 | """
359 | if gc:
360 | room = jid
361 | devicelist = []
362 | for nick in self.plugin.groupchat[room]:
363 | jid_to = self.plugin.groupchat[room][nick]
364 | if jid_to == self.own_jid:
365 | continue
366 | for device in self.device_ids[jid_to]:
367 | devicelist.append((jid_to, device))
368 | return devicelist
369 |
370 | if jid == self.own_jid:
371 | return set(self.own_devices) - set({self.own_device_id})
372 | if jid not in self.device_ids:
373 | return set()
374 | return set(self.device_ids[jid])
375 |
376 | def isTrusted(self, recipient_id, device_id):
377 | record = self.store.loadSession(recipient_id, device_id)
378 | identity_key = record.getSessionState().getRemoteIdentityKey()
379 | return self.store.isTrustedIdentity(recipient_id, identity_key)
380 |
381 | def getFingerprints(self, recipient_id):
382 | return self.store.getFingerprints(recipient_id)
383 |
384 | def getTrustedFingerprints(self, recipient_id):
385 | inactive = self.store.getInactiveSessionsKeys(recipient_id)
386 | trusted = self.store.getTrustedFingerprints(recipient_id)
387 | trusted = set(trusted) - set(inactive)
388 |
389 | return trusted
390 |
391 | def getUndecidedFingerprints(self, recipient_id):
392 | inactive = self.store.getInactiveSessionsKeys(recipient_id)
393 | undecided = self.store.getUndecidedFingerprints(recipient_id)
394 | undecided = set(undecided) - set(inactive)
395 |
396 | return undecided
397 |
398 | def devices_without_sessions(self, jid):
399 | """ List device_ids for the given jid which have no axolotl session.
400 |
401 | Parameters
402 | ----------
403 | jid : string
404 | The contacts jid
405 |
406 | Returns
407 | -------
408 | [int]
409 | A list of device_ids
410 | """
411 | known_devices = self.device_list_for(jid)
412 | missing_devices = [dev
413 | for dev in known_devices
414 | if not self.store.containsSession(jid, dev)]
415 | if missing_devices:
416 | log.info(self.account + ' => Missing device sessions for ' +
417 | jid + ': ' + str(missing_devices))
418 | return missing_devices
419 |
420 | def get_session_cipher(self, jid, device_id):
421 | if jid not in self.session_ciphers:
422 | self.session_ciphers[jid] = {}
423 |
424 | if device_id not in self.session_ciphers[jid]:
425 | cipher = SessionCipher(self.store, self.store, self.store,
426 | self.store, jid, device_id)
427 | self.session_ciphers[jid][device_id] = cipher
428 |
429 | return self.session_ciphers[jid][device_id]
430 |
431 | def handlePreKeyWhisperMessage(self, recipient_id, device_id, key):
432 | preKeyWhisperMessage = PreKeyWhisperMessage(serialized=key)
433 | if not preKeyWhisperMessage.getPreKeyId():
434 | raise Exception("Received PreKeyWhisperMessage without PreKey =>" +
435 | recipient_id)
436 | sessionCipher = self.get_session_cipher(recipient_id, device_id)
437 | try:
438 | log.debug(self.account +
439 | " => Received PreKeyWhisperMessage from " +
440 | recipient_id)
441 | key = sessionCipher.decryptPkmsg(preKeyWhisperMessage)
442 | # Publish new bundle after PreKey has been used
443 | # for building a new Session
444 | self.plugin.publish_bundle(self.account)
445 | self.add_device(recipient_id, device_id)
446 | return key
447 | except UntrustedIdentityException as e:
448 | log.info(self.account + " => Received WhisperMessage " +
449 | "from Untrusted Fingerprint! => " + e.getName())
450 |
451 | def handleWhisperMessage(self, recipient_id, device_id, key):
452 | whisperMessage = WhisperMessage(serialized=key)
453 | log.debug(self.account + " => Received WhisperMessage from " +
454 | recipient_id)
455 | if self.isTrusted(recipient_id, device_id):
456 | sessionCipher = self.get_session_cipher(recipient_id, device_id)
457 | key = sessionCipher.decryptMsg(whisperMessage)
458 | self.add_device(recipient_id, device_id)
459 | return key
460 | else:
461 | raise Exception("Received WhisperMessage "
462 | "from Untrusted Fingerprint! => " + recipient_id)
463 |
464 | def checkPreKeyAmount(self):
465 | # Check if enough PreKeys are available
466 | preKeyCount = self.store.preKeyStore.getPreKeyCount()
467 | if preKeyCount < MIN_PREKEY_AMOUNT:
468 | newKeys = DEFAULT_PREKEY_AMOUNT - preKeyCount
469 | self.store.preKeyStore.generateNewPreKeys(newKeys)
470 | log.info(self.account + ' => ' + str(newKeys) +
471 | ' PreKeys created')
472 |
473 | def cycleSignedPreKey(self, identityKeyPair):
474 | # Publish every SPK_CYCLE_TIME a new SignedPreKey
475 | # Delete all exsiting SignedPreKeys that are older
476 | # then SPK_ARCHIVE_TIME
477 |
478 | # Check if SignedPreKey exist and create if not
479 | if not self.store.getCurrentSignedPreKeyId():
480 | signedPreKey = KeyHelper.generateSignedPreKey(
481 | identityKeyPair, self.store.getNextSignedPreKeyId())
482 | self.store.storeSignedPreKey(signedPreKey.getId(), signedPreKey)
483 | log.debug(self.account +
484 | ' => New SignedPreKey created, because none existed')
485 |
486 | # if SPK_CYCLE_TIME is reached, generate a new SignedPreKey
487 | now = int(time.time())
488 | timestamp = self.store.getSignedPreKeyTimestamp(
489 | self.store.getCurrentSignedPreKeyId())
490 |
491 | if int(timestamp) < now - SPK_CYCLE_TIME:
492 | signedPreKey = KeyHelper.generateSignedPreKey(
493 | identityKeyPair, self.store.getNextSignedPreKeyId())
494 | self.store.storeSignedPreKey(signedPreKey.getId(), signedPreKey)
495 | log.debug(self.account + ' => Cycled SignedPreKey')
496 |
497 | # Delete all SignedPreKeys that are older than SPK_ARCHIVE_TIME
498 | timestamp = now - SPK_ARCHIVE_TIME
499 | self.store.removeOldSignedPreKeys(timestamp)
500 |
--------------------------------------------------------------------------------
/src/profanity_omemo_plugin/prof_omemo_state.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2017 René `reneVolution` Calles
4 | #
5 | # This file is part of Profanity OMEMO plugin.
6 | #
7 | # The Profanity OMEMO plugin 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
10 | # (at your option) any later version.
11 | #
12 | # The Profanity OMEMO plugin is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 | # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 | # more details.
16 | #
17 | # You should have received a copy of the GNU General Public License along with
18 | # the Profanity OMEMO plugin. If not, see .
19 | #
20 | from __future__ import absolute_import
21 | from __future__ import unicode_literals
22 |
23 | import prof
24 |
25 | from profanity_omemo_plugin.db import get_connection
26 | from profanity_omemo_plugin.log import get_plugin_logger
27 |
28 | logger = get_plugin_logger(__name__)
29 |
30 | from profanity_omemo_plugin.omemo.state import OmemoState
31 |
32 | # Monkeypatching trusted state until it has been implemented correctly
33 | def _isTrusted(self, recipient_id, device_id):
34 | return True
35 |
36 | OmemoState.isTrusted = _isTrusted
37 |
38 |
39 | class DummyPLugin(object):
40 | def publish_bundle(self, account):
41 | pass
42 |
43 |
44 | class ProfOmemoState(object):
45 | """ ProfOmemoState Singleton """
46 |
47 | __states = {}
48 |
49 | def __new__(cls, *args, **kwargs):
50 | account = ProfOmemoUser().account
51 | if ProfOmemoUser().fulljid:
52 | own_jid = ProfOmemoUser().fulljid.rsplit('/', 1)[0]
53 | else:
54 | own_jid = account
55 |
56 | if not own_jid:
57 | raise RuntimeError('No User connected.')
58 |
59 | if own_jid not in cls.__states:
60 | # create the OmemoState for the current user
61 | connection = get_connection(own_jid)
62 | new_state = OmemoState(own_jid, connection, account, DummyPLugin())
63 | cls.__states[own_jid] = new_state
64 |
65 | return cls.__states[own_jid]
66 |
67 |
68 | class ProfActiveOmemoChats(object):
69 |
70 | _active = {}
71 |
72 | @classmethod
73 | def add(cls, contact_jid):
74 | raw_jid = cls.as_raw_jid(contact_jid)
75 | if raw_jid not in cls._active:
76 | cls._active[raw_jid] = {'deactivated': False}
77 | prof.log_info('Added {0} to active chats'.format(raw_jid))
78 | else:
79 | cls.activate(raw_jid)
80 | prof.log_info('Chat with {0} re-activated.')
81 |
82 | @classmethod
83 | def activate(cls, contact_jid):
84 | raw_jid = cls.as_raw_jid(contact_jid)
85 | cls._active[raw_jid] = {'deactivated': False}
86 |
87 | @classmethod
88 | def deactivate(cls, contact_jid):
89 | raw_jid = cls.as_raw_jid(contact_jid)
90 | user = cls._active.get(raw_jid)
91 |
92 | try:
93 | user['deactivated'] = True
94 | except KeyError:
95 | pass
96 |
97 | @classmethod
98 | def remove(cls, contact_jid):
99 | raw_jid = cls.as_raw_jid(contact_jid)
100 | try:
101 | del cls._active[raw_jid]
102 | except KeyError:
103 | pass
104 |
105 | @classmethod
106 | def account_is_registered(cls, contact_jid):
107 | raw_jid = cls.as_raw_jid(contact_jid)
108 | prof.log_info('Active Chats: [{0}]'.format(', '.join(cls._active)))
109 | active_user = cls._active.get(raw_jid)
110 |
111 | return active_user is not None
112 |
113 | @classmethod
114 | def account_is_active(cls, contact_jid):
115 | raw_jid = cls.as_raw_jid(contact_jid)
116 | prof.log_info('Active Chats: [{0}]'.format(', '.join(cls._active)))
117 | active_user = cls._active.get(raw_jid)
118 | if not active_user:
119 | return False
120 |
121 | return not active_user['deactivated']
122 |
123 | @classmethod
124 | def account_is_deactivated(cls, contact_jid):
125 | raw_jid = cls.as_raw_jid(contact_jid)
126 | active_user = cls._active.get(raw_jid)
127 |
128 | # if the user does not have an active session yet,
129 | # the user can't be deactivated
130 | if not active_user:
131 | return False
132 |
133 | return active_user['deactivated']
134 |
135 | @classmethod
136 | def reset(cls):
137 | cls._active = {}
138 |
139 | @staticmethod
140 | def as_raw_jid(contact_jid):
141 | raw_jid = None
142 | if contact_jid:
143 | raw_jid = contact_jid.rsplit('/', 1)[0]
144 |
145 | return raw_jid
146 |
147 |
148 | class ProfOmemoUser(object):
149 | """ ProfOmemoUser Singleton """
150 |
151 | account = None
152 | fulljid = None
153 |
154 | @classmethod
155 | def set_user(cls, account, fulljid):
156 | cls.account = account
157 | cls.fulljid = fulljid
158 |
159 | @classmethod
160 | def reset(cls):
161 | cls.account = None
162 | cls.fulljid = None
163 |
--------------------------------------------------------------------------------
/src/profanity_omemo_plugin/weak_message_store.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2017 René `reneVolution` Calles
4 | #
5 | # This file is part of Profanity OMEMO plugin.
6 | #
7 | # The Profanity OMEMO plugin 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
10 | # (at your option) any later version.
11 | #
12 | # The Profanity OMEMO plugin is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 | # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 | # more details.
16 | #
17 | # You should have received a copy of the GNU General Public License along with
18 | # the Profanity OMEMO plugin. If not, see .
19 | #
20 |
21 | from prof_omemo_state import ProfOmemoState
22 |
23 |
24 | class WeakMessageStore(object):
25 |
26 | def __init__(self):
27 | # - maybe max store size (10 Messages FIFO drop)
28 | # - configure timeout
29 | # - run a checker thread
30 | # - use wait on empty store to save cpu
31 | self._messages = []
32 |
33 | def add(self, message_dict):
34 | """ Adds a Message dict to the store.
35 |
36 | :message_dict: {'from': 'romeo@montague.lit',
37 | 'to': 'juliet@capulet.lit',
38 | 'message': 'Some Message',}
39 |
40 | - adds a timestamp to the dict
41 | - tries to post immediately
42 |
43 | """
44 | pass
45 |
46 | def post_message(self, stanza):
47 | # post the encrypted message, e.g. prof.send_message(stanza)
48 | pass
49 |
50 | def trigger(self):
51 | """
52 | Gets triggered from the outside to check all messages if
53 | they are ready to encrypt and calls post_message.
54 |
55 | Or -> requests the missing bundles.
56 |
57 | """
58 |
59 | def on_timeout(self):
60 | # posts some information to the ui if the bundle is not received yet
61 | # or a device is not trusted."
62 | pass
--------------------------------------------------------------------------------
/src/profanity_omemo_plugin/xmpp.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2017 René `reneVolution` Calles
4 | #
5 | # This file is part of Profanity OMEMO plugin.
6 | #
7 | # The Profanity OMEMO plugin 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
10 | # (at your option) any later version.
11 | #
12 | # The Profanity OMEMO plugin is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 | # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 | # more details.
16 | #
17 | # You should have received a copy of the GNU General Public License along with
18 | # the Profanity OMEMO plugin. If not, see .
19 | #
20 | from __future__ import absolute_import
21 | from __future__ import unicode_literals
22 |
23 | import random
24 | import uuid
25 | from base64 import b64decode, b64encode
26 |
27 | from profanity_omemo_plugin.constants import NS_OMEMO, NS_DEVICE_LIST, \
28 | NS_DEVICE_LIST_NOTIFY, NS_BUNDLES
29 | from profanity_omemo_plugin.errors import StanzaNodeNotFound, \
30 | CouldNotCreateBundleStanza
31 | from profanity_omemo_plugin.log import get_plugin_logger
32 | from profanity_omemo_plugin.prof_omemo_state import ProfOmemoState, \
33 | ProfOmemoUser
34 |
35 | try:
36 | from lxml import etree as ET
37 | except ImportError:
38 | # fallback to the default ElementTree module
39 | import xml.etree.ElementTree as ET
40 |
41 | logger = get_plugin_logger(__name__)
42 |
43 |
44 | ################################################################################
45 | # Helper
46 | ################################################################################
47 |
48 | def stanza_as_xml(stanza):
49 | """ Converting a stanza to XML. """
50 | try:
51 | xml = ET.fromstring(stanza)
52 | except UnicodeEncodeError:
53 | xml = ET.fromstring(stanza.encode('utf-8'))
54 |
55 | return xml
56 |
57 |
58 | def find_node(xml, name, ns=None):
59 | node = None
60 |
61 | if ns:
62 | xq = './/{%s}%s' % (ns, name)
63 | logger.debug('Looking up node for query {0}'.format(xq))
64 | node = xml.find(xq)
65 |
66 | if node is None:
67 | # ChatSecure seems to use the wrong xml namespace
68 | # use a fallback here with the custom namespace for some nodes
69 | xq = './/{%s}%s' % ('jabber:client', name)
70 | logger.debug('Fallback node lookup for query {0}'.format(xq))
71 | node = xml.find(xq)
72 |
73 | if node is None:
74 | raise StanzaNodeNotFound('Node {0} not found.'.format(name))
75 |
76 | return node
77 |
78 |
79 | def encrypt_stanza(stanza):
80 | logger.debug('Enrypting stanza {0}'.format(stanza))
81 | logger.debug('Convert stanza to xml.')
82 | msg_xml = stanza_as_xml(stanza)
83 | fulljid = msg_xml.attrib.get('from', ProfOmemoUser().fulljid)
84 | logger.debug('Sender: {0}'.format(fulljid))
85 | jid = msg_xml.attrib['to']
86 | account, resource = jid.rsplit('/', 1) if '/' in jid else (jid, '')
87 | logger.debug('Recipient {0} [{1}]'.format(account, resource))
88 | msg_id = msg_xml.attrib['id']
89 | logger.debug('Message ID: {0}'.format(msg_id))
90 | body_node = msg_xml.find('.//body')
91 | plaintext = body_node.text
92 | logger.debug('Message: {0}'.format(plaintext))
93 |
94 | try:
95 | plaintext = plaintext.encode('utf-8')
96 | except:
97 | pass
98 |
99 | return create_encrypted_message(fulljid, account, plaintext, msg_id=msg_id)
100 |
101 |
102 | def update_devicelist(from_jid, recipient, devices):
103 | omemo_state = ProfOmemoState()
104 |
105 | logger.debug('Update devices for account: {0}'.format(from_jid))
106 | logger.info('Adding Device ID\'s: {0} for {1}.'.format(devices, recipient))
107 | if devices:
108 | if from_jid == recipient:
109 | logger.info('Adding own devices')
110 | omemo_state.set_own_devices(devices)
111 | else:
112 | logger.info('Adding recipients devices')
113 | omemo_state.set_devices(recipient, devices)
114 |
115 | omemo_state.store.sessionStore.setActiveState(devices, from_jid)
116 | logger.info('Device List update done.')
117 |
118 |
119 | def get_recipient(stanza):
120 | try:
121 | xml = stanza_as_xml(stanza)
122 | recipient = xml.attrib['to']
123 | logger.debug('Found recipient {0} in stanza {1}'.format(recipient, stanza))
124 | except:
125 | logger.error('Recipient not found in stanza {0}'.format(stanza))
126 | return None
127 |
128 | return recipient
129 |
130 |
131 | def get_root_attrib(stanza, attrib):
132 | try:
133 | xml = stanza_as_xml(stanza)
134 | result = xml.attrib[attrib]
135 | except KeyError:
136 | logger.error('Stanza has not attrib {0}'.format(attrib))
137 | return None
138 | except Exception as e:
139 | logger.error('Failed to parse stanza: {0}'.format(stanza))
140 | logger.error('{0}: {1}'.format(type(e).__name__, e.message))
141 | return None
142 |
143 | return result
144 |
145 |
146 | ################################################################################
147 | # Stanza validation
148 | ################################################################################
149 |
150 | def stanza_is_valid_xml(stanza):
151 | """ Validates a given stanza to be valid xml"""
152 | try:
153 | _ = stanza_as_xml(stanza)
154 | except Exception as e:
155 | logger.error('Stanza is not valid xml. {0}'.format(e))
156 | logger.error(stanza)
157 | return False
158 |
159 | return True
160 |
161 |
162 | def is_devicelist_update(stanza):
163 | return NS_DEVICE_LIST in stanza and not NS_DEVICE_LIST_NOTIFY in stanza
164 |
165 |
166 | def is_bundle_update(stanza):
167 | return NS_BUNDLES in stanza
168 |
169 |
170 | def is_encrypted_message(stanza):
171 | # TODO: check in NS_OMEMO only
172 | return 'encrypted' in stanza
173 |
174 |
175 | def is_xmpp_message(stanza):
176 | stanza = stanza or ''
177 | is_valid = all([NS_OMEMO in stanza, 'body' in stanza])
178 | return is_valid
179 |
180 |
181 | def is_xmpp_plaintext_message(stanza):
182 | stanza = stanza or ''
183 | return 'body' in stanza
184 |
185 |
186 | ################################################################################
187 | # Unwrapping XMPP stanzas
188 | ################################################################################
189 |
190 | def unpack_bundle_info(stanza):
191 | logger.info('Unwrapping bundle info.')
192 | bundle_xml = stanza_as_xml(stanza)
193 |
194 | try:
195 | sender = bundle_xml.attrib['from'].rsplit('/', 1)[0]
196 | logger.debug('Found sender jid {0} in bundle info.'.format(sender))
197 | except KeyError:
198 | # we assume bundle updates without sender to be own bundles for
199 | # different devices
200 | sender = ProfOmemoUser.account
201 | logger.debug(
202 | 'Fallback to known sender {0} while unpacking bundle info'.format(sender)
203 | )
204 |
205 | try:
206 | items_node = find_node(bundle_xml, 'items', ns='http://jabber.org/protocol/pubsub')
207 | device_id = items_node.attrib['node'].split(':')[-1]
208 |
209 | bundle_node = find_node(bundle_xml, 'bundle', ns=NS_OMEMO)
210 |
211 | signedPreKeyPublic_node = find_node(bundle_node, 'signedPreKeyPublic', ns=NS_OMEMO)
212 | signedPreKeyPublic = signedPreKeyPublic_node.text
213 |
214 | signedPreKeyId = int(signedPreKeyPublic_node.attrib['signedPreKeyId'])
215 |
216 | signedPreKeySignature_node = find_node(bundle_node, 'signedPreKeySignature', ns=NS_OMEMO)
217 | signedPreKeySignature = signedPreKeySignature_node.text
218 |
219 | identityKey_node = find_node(bundle_node, 'identityKey', ns=NS_OMEMO)
220 | identityKey = identityKey_node.text
221 |
222 | prekeys_node = find_node(bundle_node, 'prekeys', ns=NS_OMEMO)
223 | prekeys = [(int(n.attrib['preKeyId']), n.text) for n in prekeys_node]
224 |
225 | picked_key_tuple = random.SystemRandom().choice(prekeys)
226 | preKeyId, preKeyPublic = picked_key_tuple
227 |
228 | if not preKeyId:
229 | logger.warning('OMEMO PreKey has no id set')
230 | return
231 |
232 | if not preKeyPublic:
233 | logger.warning('No Public PreKey set.')
234 | return
235 |
236 | except StanzaNodeNotFound as e:
237 | logger.warning('Could not unpack bundle info. {0}'.format(e))
238 | return
239 |
240 | bundle_dict = {
241 | 'sender': sender,
242 | 'device': device_id,
243 | 'signedPreKeyId': signedPreKeyId,
244 | 'signedPreKeyPublic': b64decode(signedPreKeyPublic),
245 | 'signedPreKeySignature': b64decode(signedPreKeySignature),
246 | 'identityKey': b64decode(identityKey),
247 | 'preKeyId': preKeyId,
248 | 'preKeyPublic': b64decode(preKeyPublic)
249 | }
250 |
251 | return bundle_dict
252 |
253 |
254 | def unpack_encrypted_stanza(encrypted_stanza):
255 | """
256 |
257 |
258 |
259 | MwiS5dwDEiEFWjz44O8EezFsoc9bt/o85UIUw4zyXxwX5Fk80dpsvmgaIQVnrk8XTORiGHq2TYRM
260 | wS1/WWY+zhN9z1fmazuEOgtfRyJSMwohBe7cHe4zeNI3p4R60hEzY3vwaiPCCDQrr01A+BsyvI0V
261 | EAEYACIgAnkiHmEFyNec2UNZi7wRswx36qUYfWYnHcN3qEUQFDYLe51RMqf+NSj134e5BTAB
262 |
263 | PnZsChVPjwI6jTL6fpkz5Q==
264 |
265 | 5eCvRJz6ASe8YzCyhB6W3JozxHec
266 |
267 |
268 |
269 |
270 | :param encrypted_stanza:
271 | :return:
272 | """
273 |
274 | logger.info('Unpacking encrypted Message stanza.')
275 | xml = ET.fromstring(encrypted_stanza)
276 | if ''
353 | ''
354 | ''
355 | '- '
356 | ''
357 | ''
358 | '
'
359 | ''
360 | ''
361 | '')
362 |
363 | omemo_state = ProfOmemoState()
364 | own_bundle = omemo_state.bundle
365 | own_jid = omemo_state.own_jid
366 | bundle_msg = announce_template.format(from_jid=own_jid,
367 | req_id=str(uuid.uuid4()),
368 | device_id=omemo_state.own_device_id,
369 | bundles_ns=NS_BUNDLES,
370 | omemo_ns=NS_OMEMO)
371 |
372 | bundle_xml = ET.fromstring(bundle_msg)
373 |
374 | # to be appended to announce_template
375 | find_str = './/{%s}bundle' % NS_OMEMO
376 | bundle_node = bundle_xml.find(find_str)
377 | pre_key_signed_node = ET.SubElement(bundle_node, 'signedPreKeyPublic',
378 | attrib={'signedPreKeyId': str(
379 | own_bundle['signedPreKeyId'])})
380 | pre_key_signed_node.text = own_bundle.get('signedPreKeyPublic')
381 |
382 | signedPreKeySignature_node = ET.SubElement(bundle_node,
383 | 'signedPreKeySignature')
384 | signedPreKeySignature_node.text = own_bundle.get('signedPreKeySignature')
385 |
386 | identityKey_node = ET.SubElement(bundle_node, 'identityKey')
387 | identityKey_node.text = own_bundle.get('identityKey')
388 |
389 | prekeys_node = ET.SubElement(bundle_node, 'prekeys')
390 | for key_id, key in own_bundle.get('prekeys', []):
391 | key_node = ET.SubElement(prekeys_node, 'preKeyPublic',
392 | attrib={'preKeyId': str(key_id)})
393 | key_node.text = str(key)
394 |
395 | # reconvert xml to stanza
396 | try:
397 | bundle_stanza = ET.tostring(bundle_xml, encoding='utf-8', method='html')
398 | except:
399 | logger.exception('Could not convert Bunle XML to Stanza.')
400 | raise CouldNotCreateBundleStanza
401 |
402 | return bundle_stanza
403 |
404 |
405 | def create_bundle_request_stanza(account, recipient, deviceid):
406 | logger.info('Fetching bundle for device id {0} of {1}'.format(deviceid, recipient))
407 |
408 | bundle_req_root = ET.Element('iq')
409 | bundle_req_root.set('type', 'get')
410 | bundle_req_root.set('from', account)
411 | bundle_req_root.set('to', recipient)
412 | bundle_req_root.set('id', str(uuid.uuid4()))
413 | pubsub_node = ET.SubElement(bundle_req_root, 'pubsub')
414 | pubsub_node.set('xmlns', 'http://jabber.org/protocol/pubsub')
415 | items_node = ET.SubElement(pubsub_node, 'items')
416 | items_node.set('node', '{0}:{1}'.format(NS_BUNDLES, deviceid))
417 |
418 | stanza = ET.tostring(bundle_req_root, encoding='utf-8', method='html')
419 |
420 | return stanza
421 |
422 |
423 | def create_encrypted_message(from_jid, to_jid, plaintext, msg_id=None):
424 |
425 | OMEMO_MSG = (''
426 | 'I sent you an OMEMO encrypted message.'
427 | ''
428 | ''
429 | '{keys}'
430 | '{iv}'
431 | ''
432 | '{enc_body}'
433 | ''
434 | ''
435 | ''
436 | ''
437 | '')
438 |
439 | omemo_state = ProfOmemoState()
440 | account = ProfOmemoUser.account
441 | msg_data = omemo_state.create_msg(account, to_jid, plaintext)
442 |
443 | # build encrypted message from here
444 | keys_dict = msg_data['keys'] or {}
445 |
446 | # key is now a tuple of (key, is_prekey)
447 | keys_str = ''
448 | for rid, key_info in keys_dict.items():
449 | key, is_prekey = key_info
450 | if is_prekey:
451 | logger.debug('PreKey=True')
452 | tpl = '{1}'
453 | else:
454 | tpl = '{1}'
455 | keys_str += tpl.format(rid, b64encode(key).decode('ascii'))
456 |
457 | msg_dict = {'to': to_jid,
458 | 'from': from_jid,
459 | 'id': msg_id or str(uuid.uuid4()),
460 | 'omemo_ns': NS_OMEMO,
461 | 'sid': msg_data['sid'],
462 | 'keys': keys_str,
463 | 'iv': b64encode(msg_data['iv']).decode('ascii'),
464 | 'enc_body': b64encode(msg_data['payload']).decode('ascii')}
465 |
466 | enc_msg = OMEMO_MSG.format(**msg_dict)
467 |
468 | return enc_msg
469 |
470 |
471 | def create_devicelist_update_msg(fulljid):
472 | logger.debug('Create devicelist update message for jid {0}.'.format(fulljid))
473 | QUERY_MSG = (''
474 | ''
475 | ''
476 | '- '
477 | '
'
478 | '{devices}'
479 | '
'
480 | ' '
481 | ''
482 | ''
483 | '')
484 |
485 | omemo_state = ProfOmemoState()
486 |
487 | own_devices = set(omemo_state.own_devices + [omemo_state.own_device_id])
488 | logger.debug('Found own devices {0}'.format(own_devices))
489 | device_nodes = [''.format(d) for d in own_devices]
490 |
491 | msg_dict = {'from': fulljid,
492 | 'devices': ''.join(device_nodes),
493 | 'id': str(uuid.uuid4()),
494 | 'omemo_ns': NS_OMEMO,
495 | 'devicelist_ns': NS_DEVICE_LIST}
496 |
497 | query_msg = QUERY_MSG.format(**msg_dict)
498 |
499 | return query_msg
500 |
501 |
502 | def create_devicelist_query_msg(sender, recipient):
503 | logger.debug(
504 | 'Create devicelist query message from {0} to {1}'.format(sender, recipient)
505 | )
506 |
507 | QUERY_MSG = (''
508 | ''
509 | ''
510 | ''
511 | '')
512 |
513 | msg_dict = {
514 | 'from': sender,
515 | 'to': recipient,
516 | 'id': str(uuid.uuid4()),
517 | 'device_list_ns': NS_DEVICE_LIST
518 | }
519 |
520 | query_msg = QUERY_MSG.format(**msg_dict)
521 |
522 | logger.debug('Sending Device List Query: {0}'.format(query_msg))
523 |
524 | return query_msg
525 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ReneVolution/profanity-omemo-plugin/bfb0337c318075a419c038fb47a66269e018ea23/tests/__init__.py
--------------------------------------------------------------------------------
/tests/fixtures/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import unicode_literals
2 |
3 | import os
4 |
5 | here = os.path.abspath(__file__)
6 | stanzas_root = os.path.join(os.path.dirname(here), 'stanzas')
7 |
8 |
9 | def get_stanza_fixture(name):
10 | stanza_path = os.path.join(stanzas_root, name)
11 |
12 | with open(stanza_path, 'rb') as stanza_file:
13 | stanza = stanza_file.read()
14 |
15 | return stanza
--------------------------------------------------------------------------------
/tests/fixtures/stanzas/iq_bundle_info.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 |
6 | -
7 |
8 |
9 | BZGkB3LjbUhS6GxeyzkSZ7KLVfvJyE0z0NjVYADvdhRD
10 |
11 |
12 | ypCXhT60MhNScWw33oaVVQLYLkxF1UXanksSRjbVwWwxUPSl6S4WqAjg3M6NrZ5rn5jPDlBNQmaXeNY0vqVPiw==
13 |
14 | BQw8uYlgoCTPIzUMlhJlLYyY+t848TCm0kFNEf4C1i00
15 |
16 |
17 |
18 | BYMVSAn4/21NR07MXp3R2WFqLF5+RfzHgKTPy90M0lF8
19 |
20 |
21 | BRcoFNT/yUN+6dhyhjowHTIeKQEH1nEUFaSVWUyNR5wx
22 |
23 |
24 | Ba/OLh1dgYuYz7Ecwkda6uNFGNkDGMBLx6uinZpcqcw6
25 |
26 |
27 | BfXD8WvHKXxPkm2t5zlaERSADHFBOO987NuHuUJDAkUX
28 |
29 |
30 | BeBiTKDIV+kWAf0nFZccAJW5JqTv3IGJU0Ndc5qCAvFH
31 |
32 |
33 | BXRggqUCA5nTw0IpEx7CVsbyAmwM2+YaigWOxc2aEexn
34 |
35 |
36 | BSOVzVACY5n0DlzJHKChonHw5NdEvksZONtIcWIs1t5b
37 |
38 |
39 | BewzO0FDmxD+FeXyLbkvB3eRwKtqebDNdP56KbpLFEAA
40 |
41 |
42 | Bf1794oDDDiySxZyM9F6r3n9VFClJe6Eq9+CEQhBLncK
43 |
44 |
45 | BbRK8G0n2ZuJLJ+fPPluLSaSln/7Kl3ZvSqW3PoUuugF
46 |
47 |
48 | BXyMiAkZ9cikpyjhPgg8x8Jo1To+LGS59L6O8egRDPEi
49 |
50 |
51 | BTcjS0w3hHkD8ZxeIizJoCk99ECSbLg0r9pXNqKz0yJS
52 |
53 |
54 | BayO/3Q/PDQX/7O8T7YM6422HPaAwaneq0kz3zHUu9kc
55 |
56 |
57 | BY333GzMYZ6gkx/gC/FHQspQTcNvh8fuqDNerUYlzZxm
58 |
59 |
60 | BY/CWx6MFlDdEEX12SLTcIqs3fRwVoItQjwwf0zCM5ph
61 |
62 |
63 | BWy/5R+x2+Qogtlv8vjc5L3sQBr0n28p11wf5acmV+9C
64 |
65 |
66 | BRN8u4kVvaKM5SQHOcp7gteke1c+F1Y3LLEY3IgM7xRp
67 |
68 |
69 | BZJychwqvjL9apogEa69mWnFcYjvROnzJmoSvFQ+mqkl
70 |
71 |
72 | BR4UNF3Q/XsgRKOoecoJyEBmj23gYR/MrghSAVFnGQ9D
73 |
74 |
75 | BVupuv6ArQRQbZiyIHmfbhSbbu0JCkleW46ayXVWU0Q1
76 |
77 |
78 | BVhl9f1P8zDIFKC5uKb8YY/X64YfxHNivb1/MlyEtkFH
79 |
80 |
81 | BW7aUWrntfjzsZZ1OMFDpE3lDsZ+LOvDNhTKdzgrw/Eu
82 |
83 |
84 | BeZL+gVnAm6OEN5XhVk+TLyUJ3IwOLESkx5WIAQzhLhv
85 |
86 |
87 | Bf2Yrz+5Kp01fF6PnF42lYdPMMzXI3Ldjtr/8WCmWhI8
88 |
89 |
90 | BV45lMnyuSTkvM96WL3ljNzEd7mDVEdenh6djJx2tLdI
91 |
92 |
93 | Bfzok8dwr9ysXpjaS3XB2MKC9AhnSb27L31sPygnFr5I
94 |
95 |
96 | BcziCiaSdAeL75yJCrZsFT+b7vROWgKI689YGKMBD5Qo
97 |
98 |
99 | BW4E9Gh/DENB0uXDIYSFZk6ZSkErOdP+0o9SE9u0rMtl
100 |
101 |
102 | BSi5+emqwCz93ddEvYNu024vBmEtBnBRTa47TEtXEG1Q
103 |
104 |
105 | BSeF2p2KrSOSGXJ3aI7hkveKjw/vuJUape3UP5P6HNYn
106 |
107 |
108 | BRVkSNb8FSk7LzkhPehOn+uvfUwwTWqNnUSpS0LlDud4
109 |
110 |
111 | BXCJwkiRpXEK1tnQ/QtWqV+AZxoUcTNaflneEboKc1YZ
112 |
113 |
114 | BQKfYZjbqQoACNcBfzwfz3Y86HeqIJYp+y3bEyWqS4Al
115 |
116 |
117 | BXYmoFg4W3bzC1Icscf/KKWqY85H5oSpXuLFF/obkrBq
118 |
119 |
120 | BTxBOENxIJ9FvTS1vSGv/KbqOZqqE/WoVm+KsT4Rugtw
121 |
122 |
123 | BXY8q9ADn1AD7mD3LbYRtz8w2BRIocR2iK3DoqYPbFF2
124 |
125 |
126 | BcmLV1YAW6mfnMPtVVQeCB0cDf6e56gkOdzjYaRiqR1E
127 |
128 |
129 | BXO7+KWapkcH+w41hgTtkM0mizKkbBsXI4fyHwzLT4kW
130 |
131 |
132 | BWucO+v/uVcdq4XdfYgoJQirv1Ws3rApmxMUQCoKDbcZ
133 |
134 |
135 | BZjoLRuRohvIvFieM72yGgH1H68xr6wkytU70jHaKm8H
136 |
137 |
138 | BTEdLrqB46UuvH9V9L2or7czdwFd8xZCnNCh0SvBBwp9
139 |
140 |
141 | BdAlUBf2Ygwl3OYk3ALNYUTAGc0GTKUqq4Q399CEaUIy
142 |
143 |
144 | BSyBA1WIXkSuJ6v22/KpNwb8PvHfo7+LjSQgGM7PcMdw
145 |
146 |
147 | BQHt73vrCrXM/wN/hppFccwgnsCoqQPv1YDTSwa9jj02
148 |
149 |
150 | BR5h2rE8xGhypJGngbcVVVkvga8S8rv5GqMA2fITyZNO
151 |
152 |
153 | BU7+jsKbBsIUH0f2zlpAeWOzd/juXiWMGNaotjnZ5Go+
154 |
155 |
156 | Bcd9JpwXhUQYgByvA9kNfSSOY6UEHXpKle9Attir2/Z7
157 |
158 |
159 | BVk1lec4tO86wyxd/GaSefVpTfnEUhYSsPqmmVvuu3tQ
160 |
161 |
162 | BcqWKTbR05PWDR/lW5ZRDBd0fJfTrGveRcWvXiBJIL0Y
163 |
164 |
165 | BRA2+oDeBJ6bia1yb+uHRd+cGmI1JIDMmSpBIlFgOWwM
166 |
167 |
168 | Ba2L8JBr9GudT0iN8jtzHKxYWIfKIamvjfdWN7PXqBpG
169 |
170 |
171 | BeKtL25ml4GN1tdEtcen5KcjR5NwUVVOKfx2NNjLTRpe
172 |
173 |
174 | BbcMGT+UfFqNeg3RZ4d0JPwa8LRmamLpWRS+TFOZIEhW
175 |
176 |
177 | BTOqxofokEgQsQc5Rv4xvZLPI3eyydryhHyLdeOGre1X
178 |
179 |
180 | BRxufxrAK5CCm7JdaKjBGAdLTda1ICz7gpl0CjP8Xokr
181 |
182 |
183 | BbaKpcnVZ8mLtMNhTXUG8fHL71IyN6LolsK6fAW1xJcn
184 |
185 |
186 | BfKUWHa53QN1PGTQItQtrtH0lWmnC7mZYSIyDnBNUHt3
187 |
188 |
189 | BQ25GKol97febHoby1n6nnm8otq6CChwHk3IXmsDNJRi
190 |
191 |
192 | BU9X1ILZEPoXQjFqRQHGQIysOoep5BjZhPTghxgm66MV
193 |
194 |
195 | BVYYcfYnEE3bkVqCamY1vLeSKzLNxhMPcoEsgt1GR/xM
196 |
197 |
198 | BQMxZao2LtW4T6anIyzvNzkLR0hRNOYN0c2sEJL1ijAX
199 |
200 |
201 | BcEiJneVvP+/Cp9zBIkcn6i/BApfL+PmB8QJ9ImL5fgc
202 |
203 |
204 | BfPbcjWzeFobD3wnyasBZI/TWg3AzMwnAzQVfzDcUWsy
205 |
206 |
207 | Bdb3DsFmT+yqiixxk1GXmOIUlGKX3bBIIQYndwcgxbtJ
208 |
209 |
210 | BR95VxaGk12nvByhbHOOw5BNrf8QhDycgpA5cSGOendq
211 |
212 |
213 | BeGsHMHSVeUSSVV2bg/G9jXp0EGbAiGWgs2WdoWfFndo
214 |
215 |
216 | Be1+MluPFt78MQZQvdtXntRC13SNHq1gYFnpHe1bkHh6
217 |
218 |
219 | BQqtGDsVHfCPiMCg37aRop4iTyO1Oy3h5Zw3iAHuA5Ul
220 |
221 |
222 | BTGboewQlnLPQ1VJ5vnGj4mb5WajzB+T02aaOaiUnnBP
223 |
224 |
225 | BY5PiicMt23UXnHigQLLb/aafYKu6OcRrzG/zuwv5V1O
226 |
227 |
228 | BXcJAYKqFXEdEXRFNJy7mt2UGbVkKyDdBDjlKa0FxOQm
229 |
230 |
231 | BV64eYhKSuOnWb6yvkx5LlVEEJqvSUpD/k+RyNVvtzoB
232 |
233 |
234 | BS8coFu93/skQ4gvDQxyPkYIGobff93nN6rV4h1qURYF
235 |
236 |
237 | BQkPLh/GSZ//91CGeYzzqeLeyq3nPjbwDoD3rjLzr59T
238 |
239 |
240 | BVk5gQ7zfICBNNC/UgCr+MAU4oSsfOPJPOwuYTy4wIM5
241 |
242 |
243 | Bab1inrAyy7408inv/zu5oXVewHVN40TqXP/VmfcOYZ+
244 |
245 |
246 | BSUG3f7VByFlBY5ZQ/IqElraQA2/ftG3AqLT8n5mkhpH
247 |
248 |
249 | BRVpuOVDbvp/D+0zHWZJINwquOERyFTX34cFmbpFcsJU
250 |
251 |
252 | BcigC+sOQ4BgDN+KvxOukrnI+0dLAz1g+AhPNeLRyEZR
253 |
254 |
255 | BVC4HoFr8pzM6B40Mqx43MVmoQY0EeREHA+fMMxDWeQB
256 |
257 |
258 | BYQBEJ063PuKNRluGX9cuxHl6wh1heyFJDZ3Uh5v9098
259 |
260 |
261 | Ba+FRu5uhZznkwSFNqKOAImoBYFt9TH0CgrdAs67x607
262 |
263 |
264 | BcyjIGNNcscOdEGFN2UJGLFziPk39e2mQW0zYgyQrQgO
265 |
266 |
267 | BZL+QuF9UnI4kiTTdZwLoOJygxL5KxI81kd8IkBUacIk
268 |
269 |
270 | BYlN165dA3NqYJzCe1Wvk041FuaODSjXXQkhzJDqsn1c
271 |
272 |
273 | BTUPGZYNOfx1rRr3dlzqXwhsNul2J5TmpPL0Q7k5FcFd
274 |
275 |
276 | BdVeb+Q8zv9I0QK7LIz2kpDtA5HVdFtbX9JLARqLcmEw
277 |
278 |
279 | Bfw1Tr00KB16JQks2M4Awq7xVCj6y8Pwp8Z5DjJW/HQK
280 |
281 |
282 | BcfDWD4Dwiv/WgNh+7EYkLNwqruff8cJw4xGL4eX0FJo
283 |
284 |
285 | BYqczrtXOuGwfmSXkcOcMZ90hJeb4tRa/X+SJzHajNkd
286 |
287 |
288 | Bb9+EnVsf1e8KClE7oQJPxNafk9Cky7+VP4kYnpc2uVb
289 |
290 |
291 |
292 |
293 |
294 |
295 |
--------------------------------------------------------------------------------
/tests/fixtures/stanzas/iq_bundle_info_chatsecure.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 |
6 | -
7 |
8 |
10 | BR7houagPdnxGALJoXuJof2SYHc3xXaWgU0IBB5WKOBx
11 |
12 |
13 | k/OtnN6fisOYucJ5v9EmC+2Gm5OMmAulIX9A2S3pHwOxGGX1XLM/I0X1AwDObn8JlMrIXw6XbyXkihw1bBwlhg==
14 |
15 |
16 | BeGESku5TlpBkl6WJOOiLUxYRhXbloK0QojewbM8G+ww
17 |
18 |
19 |
20 | BdM/XYQ/4pz3JQ0ZJ8fCj/jlI/WTdOorfi4oH+6ETywg
21 |
22 |
23 | BR9K2s1lvwlCA0MXL08qsgsuEG4if/LffPnUYKdVMNFa
24 |
25 |
26 | Bf3YYTPod0nY3DIpJeDFODG2X1Sfi9ecqBxUljNCM2Fi
27 |
28 |
29 | BSFqhN45hDUzTd2m28UpX4D6rHErMIrWZi7ycHJUGUsK
30 |
31 |
32 | BbXhT0wdcSzI3R1/e5Vxmq66LQGh9w/W0UoQIUIlyv0F
33 |
34 |
35 | BYqUphvPkd56Xz4h2/5gu3qVhkhj2f+SXK0nTWV3f3gD
36 |
37 |
38 | BfjQ97VAYLoKwEFnPPlFQ9aYV9Rv4qzBQsA+cgspLyh+
39 |
40 |
41 | BUtH4ZQ+hdlzlgp5N9XhttKQrx4Hp7DC9fe5fQCNkJB1
42 |
43 |
44 | BQGBQXSMYYp4YW0Xi0cqf5W39dg6g2F9JDuy6wFSwTE7
45 |
46 |
47 | BXBPIzvCdLZV6Zh8krV8fwJtj3kR/zOKglwc2HCgIeMX
48 |
49 |
50 | BTkZH2p7UkCsz+R98TYx5Lpmbfcpb8gCBXRHkTe/Uqsl
51 |
52 |
53 | BSTrbhGF8M/29yQTS/0SF/ZzzPu9DcVeVqJzc00OUOI1
54 |
55 |
56 | BVbuccQkmKgg0Ku4HT/byZ0Y3Mq1J0wPQMZEfHgBxrMe
57 |
58 |
59 | BTvxjv/9Wm8+mElXbNP60uWe1AVNQ4GmlZ5MOj+d6m9P
60 |
61 |
62 | BdF8VKv0XN8947X9tnowQyr60Z0tbn2M7dJ0ojvTD688
63 |
64 |
65 | BUS/etJNP0oA7GxueEshXG0Wzs4XeGdC9q0fc40YD39D
66 |
67 |
68 | BbdNfPDUxzFiJdn7lkDuzPJ+mX7+d8OBmZWujTnDkKsl
69 |
70 |
71 | BSbC4h+Su1aWtZ+1NEiZdmsDY5R1Ck87YKhx42Kz4qcq
72 |
73 |
74 | BUyAdD8XzcB2GWcIzDb4Lk24ddf2/Ti8HmFovNAi30kQ
75 |
76 |
77 | BWkFHc7iKD4vU6Bjk68qTmwZmQ676lNBXQWL7boc+GdB
78 |
79 |
80 | Bev//vfpLehBOBEbUfEeHkk3N8PhzK4EpgxI7lxBflwc
81 |
82 |
83 | BaZqN/2XIQW3zwIytSb1W2wTXgJUPfJtj1GaezU+88YH
84 |
85 |
86 | BRwLPtAFT7Nkl23PlJCsfM/W5EA4pnMcFXihreLhO9Ve
87 |
88 |
89 | BRQLbhyQJgMYrYYQ0AWahj9HPA1eKo8WDf7E2ccFbmAB
90 |
91 |
92 | BcNGA5A7inCn3Ox4pCYUBH2jBP65FmX0EZOUbiSvHscE
93 |
94 |
95 | BerRYgQGdPhy2OMiXHCuoM5ZTb8J2CqRkZGlEhkLaSAC
96 |
97 |
98 | BYsW9HSHikfTeZ3oQguarLOA4BtKQHBrWCPbp5g0uzhL
99 |
100 |
101 | BSJOa2FzoTrNzIwT2DCHwMOC8r3bkie14KvniBo/U4Nb
102 |
103 |
104 | BcTpZQox3fy6fH0cUxB+PSAm1NFXyYoyHkv96d9iOpRG
105 |
106 |
107 | BXDDIuUMCz86f7mVKt4dHHCZ6vyAqKVJsMJgbBcyruYU
108 |
109 |
110 | BZy82iJ1Q9jRbNgtWSfXrHp7S5wdZg3K+dZm2emMBpYp
111 |
112 |
113 | BYliGRh2t0s5G1PcUTInTUIqOJku6vdcQEpV3tY1eV9u
114 |
115 |
116 | BUucl9OAJCelHocwbj64NZUoNri1LtZtYVt4tAQtLCNo
117 |
118 |
119 | BcE5S6M8gfJ7gFwsJsjsEbI3y3n85o85Esp89IZMvLNH
120 |
121 |
122 | BR/6FZbqMjtbvGJGdac8CFd7TpiiCsq6VipJrgPsHQt5
123 |
124 |
125 | BceMB+8ektZH3szGDWWxgwFVcDD4Fx6wdzN97ARjHOMa
126 |
127 |
128 | BTkMAqHHGal3LNoDYtRUh/v72KdZkFEoLxIYAt6kcskb
129 |
130 |
131 | BXq5jDOsvD7A7ZFaixDYME9xiMcb3f5WZl3x1yOD5J1L
132 |
133 |
134 | BbgugqDcZht7rjyZKX7YjZwbzdQemB3HHWvlRu7X1dxY
135 |
136 |
137 | BX3WxEvw2FSSKgCRfId2P/L5ZPgXdEgDjIhzaZ6fbLIX
138 |
139 |
140 | BcN8g+pMljYwg3YM7SSRF+Ruu/sCpQ08bK/FqP8pRM4Q
141 |
142 |
143 | BSboKZYglOLdQDwGTJNAWcNmi448Ux07nQ/S6C93wr0K
144 |
145 |
146 | BS6iFMJgIjsa3UnDjf5kejj6plXICMFYZRtSdXtfh+Nc
147 |
148 |
149 | Bfp5qNpXS8meD9mwwt4FVSEE/tItTnpHvWxKRPwgXc0t
150 |
151 |
152 | BYbIutPmc8k8fVL7cx/xX9CwVLAxObN4eoo0GAM+xyB+
153 |
154 |
155 | BUJZHUKbtTHOMG2hFpLvUtMyZkfj6vFHnXWPWMPnrIZb
156 |
157 |
158 | BZpWFz/3hgO65ylyN4/dum+1aRoa+3KWbrxKlTQU1rgu
159 |
160 |
161 | BQzt7ew6uBCBchtR9o9YLPQh0eb6Ij9C4OuYl+QCL29k
162 |
163 |
164 | Be9ax1h6Mxi0MPMkVEOttpzbO2sXnYib6egwbBB6aE8t
165 |
166 |
167 | Bf+s5Ig4KZX1DPxqSmlJehqjQ4Yxq/FGWVeZ4fs2D+MX
168 |
169 |
170 | Bc1cQ48zeMy53HLX2ssNQJtja+umwQvzljO/JG5uancz
171 |
172 |
173 | BYh7OLhYQ3t61WRKXwg3wYw27lIYDrrThHzlcaQkX/sg
174 |
175 |
176 | BQWXqbdFiwUwEFFo5hqsGuXRdnbbrw7dy5ltzIQjSHs+
177 |
178 |
179 | BfUmyPWH8D3uyBPQ5LPt6A2+pphlvbzN0DifWVC27Chh
180 |
181 |
182 | BUY5AUlV4XnjS9+QloVdsllY9xnDm2VswAn4eKg51wdz
183 |
184 |
185 | BbqVVJpuDAbp2Rl/EG1sW5v51PcN7W3TxRQpKVgmoHlJ
186 |
187 |
188 | BUbNYYz/dyq5JP1q6MJcQ8fXSzN8Ab4cqPiErNAPljFs
189 |
190 |
191 | BYVyZmh93S69spz36XrQZfMgV8fRMIAqlOcINu/dYzUR
192 |
193 |
194 | BWjmyiAVqJTjIIljuhIAUVw171aU6mL1KiJi38NY/bhl
195 |
196 |
197 | BUomRHKARgukHjiyabivg8jVLMARKTrPjx9NBeSbKsdI
198 |
199 |
200 | BWIbU2CFHtnfSdwxEV7HgBahI23wr29qUAxJ+gQvKYZ5
201 |
202 |
203 | BVlJobVk3lCd6/9By60z5nyXqnVQU0kFFng3siceKDkr
204 |
205 |
206 | BclH1ZPYo59oelznLaqZg8iY9mbQB+mxySzcAqNoRSUC
207 |
208 |
209 | BQRNEs1sXOK2aWmMp1FoRsYn3cnmODHXJA36PgPPGdpX
210 |
211 |
212 | BURizZnqm1usoqqdg8wvkgECEl7/+vWuouET7td6nC0T
213 |
214 |
215 | BZ3WRTaCPkWf2ZC/0AQ7Dee+k7gZMmvkZeZcdH0cL3kg
216 |
217 |
218 | BYuMXazJLoYSvSPRTMkTp3x2W0r8591Ls5yIG6LurX41
219 |
220 |
221 | BXV6WVySHc459uTSp0KW4QtEbEa7ofbSSObZVdtgSXdj
222 |
223 |
224 | BaMHLWiN9DYNxpgDUdoUNKqEhw0LxgPsti32BcVMsMh/
225 |
226 |
227 | BWA7ACovIu/A7cq8Hxaf3/sD7GIvA/x4apfNCss7oCgz
228 |
229 |
230 | BbYUoQgLiVnKJj5EBdkkzHQte+w8znrmJsKRnN94pa1T
231 |
232 |
233 | BQazO/u3XMLDsnAFVy4Hcv51FXLJ3+22b0QOt+56OMMb
234 |
235 |
236 | Bf0KkfVP6CIQiK6/QyL9WwN8eOJ83JXLw6gHhx61Xbgo
237 |
238 |
239 | BSivw+WPRGnE/ROxIAeW3jRqb6NSCcI1X5rbzmybLsQn
240 |
241 |
242 | BZIr3HRoEDFY6j2ZAPu9WknPbhl4IOar25mkxxnWkpAA
243 |
244 |
245 | BY9SYyZIoSD15l1pOUFVkcL+Yj2cbl2J5wNL7n12Gjwo
246 |
247 |
248 | Bc+/3DXJMy13Kc08Di1rg3IHj2kAZvxl9NGUuwptszQx
249 |
250 |
251 | Ba2pphwicZ7cy9xd6iwtfMHi9l5qioGfPq8eFNy97LY1
252 |
253 |
254 | BftRwohaYjIVUifZkT1RmOHCo/iQfolfHlMTHY8lJhFO
255 |
256 |
257 | BXRDztGphCGOjiAtuh9urZJCcpFXa/suM2eowqPmELhL
258 |
259 |
260 | BbuYibAVYEDEwpQArs8HX2XPAfTOLAzClLxKZjQaj2Jd
261 |
262 |
263 | BaPfb2XZ8NmMEWvIhkOVM7q5d8/gsz9WzFJKuG1Ffzxt
264 |
265 |
266 | Baoj64FtGLn9bkSqQ/BzHyq9Efg9kElj8pHpfujnOih4
267 |
268 |
269 | BYfiFkCaEOXkP1pqhUS81iaoiXSuzggAA9ivpdF5mTck
270 |
271 |
272 | BUztGhzyVf3BuZOKVm6iYJtm0kV8aA1mgu+kZjr9o0dX
273 |
274 |
275 | BfEdQ9WnHcPiqfP0As4bB3KZAtedjeUzVPx4JHVgdG5+
276 |
277 |
278 | BdOS7GTvF9gEXgLo8sytYouszB01U0MbgyFM+ioibi97
279 |
280 |
281 | BaI+kVLX0HxZEOem61hyTBMxyUhXH3/iJUSG6eDcqZRz
282 |
283 |
284 | BVuR09GeYFB0dSweV54iXY2QGDm+OLnQ/r8mzn3R+JBD
285 |
286 |
287 | BWBsIaULg1Zu8xw74sx4aZ2OqyP11MjSPHnoZQ6ZbhtX
288 |
289 |
290 | BfevnLbOebga2UXc0I+EGREIdH//eITilyBfAmPtPQAF
291 |
292 |
293 | BVbAdML6hHFz4hPc+nZIQwCU7/T3HYC5w5wbVpo3Bn5o
294 |
295 |
296 | BT/b5oHhYzLEFTr9cjsFC14l5BD++1R0uWBvJa3tpOIK
297 |
298 |
299 | BYMLRuwxTblK4lOKjk6QXXMJJzt0n8KWnzrnK6uj1RA0
300 |
301 |
302 | BWT5k28AFg/0YvTUr9GlAKTLQw4VaHedhyH4lsOky4Vc
303 |
304 |
305 | Bf2xC0fJIuZrCwAR3U0b/zsU8hdUQMNeZBVjz/H5W34E
306 |
307 |
308 | BTeHTlCTYdTvKJzSxxk1oKxPe7/EmWgub3r/t7XkHDcD
309 |
310 |
311 | BY+ypYFv7ZiPg+VRCVpr7lz/WIs4/pNrXWLowGIMmhxS
312 |
313 |
314 | BZEdPwOi+AI+G+DG2W5tUQ6RSIroklpKm+tqR2LjLOYc
315 |
316 |
317 | BaCsKzi0DQe2KOigHsOj2Ez01TW7DISyDr4cOjtw7zB5
318 |
319 |
320 |
321 |
322 |
323 |
324 |
--------------------------------------------------------------------------------
/tests/test_prof_omemo_plugin.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from __future__ import print_function
3 | from __future__ import unicode_literals
4 |
5 | import os
6 | import sys
7 |
8 | from mock import MagicMock, patch
9 |
10 | here = os.path.abspath(os.path.dirname(__file__))
11 | deploy_root = os.path.join(here, '..', 'deploy')
12 | sys.path.append(deploy_root)
13 |
14 | # we need to mock the prof module as it is not available outside profanity
15 | sys.modules['prof'] = MagicMock()
16 | import prof_omemo_plugin as plugin
17 | from profanity_omemo_plugin.constants import NS_OMEMO, NS_DEVICE_LIST
18 | from profanity_omemo_plugin.prof_omemo_state import ProfActiveOmemoChats, ProfOmemoUser
19 |
20 |
21 | class TestPluginHooks(object):
22 |
23 | def setup_method(self, test_method):
24 | account = 'me@there.com'
25 | fulljid = 'me@there.com/profanity'
26 |
27 | ProfOmemoUser.set_user(account, fulljid)
28 |
29 |
30 | def teardown_method(self, test_method):
31 | ProfActiveOmemoChats.reset()
32 | ProfOmemoUser.reset()
33 |
34 | def test_ensure_valid_stanza(self):
35 | assert plugin.send_stanza(None) is False
36 |
37 | simple_stanza = ''
38 |
39 | assert plugin.send_stanza(simple_stanza) is True
40 |
41 | test_message = (
42 | ''
43 | ''
44 | ''
45 | '- '
46 | '
'
47 | ''
48 | ''
49 | '
'
50 | ' '
51 | ''
52 | ''
53 | ''
54 | ).format(NS_DEVICE_LIST, NS_OMEMO)
55 |
56 | assert plugin.send_stanza(test_message) is True
57 |
58 | def test_prof_on_message_stanza_send_ignores_none(self):
59 | ret_val = plugin.prof_on_message_stanza_send(None)
60 |
61 | assert ret_val is None
62 |
63 | def test_prof_on_message_stanza_send_rejects_non_omemo_message(self):
64 | msg = 'Hello World'
65 | ret_val = plugin.prof_on_message_stanza_send(msg)
66 |
67 | assert ret_val is None
68 |
69 | @patch('profanity_omemo_plugin.omemo.state.OmemoState.devices_without_sessions')
70 | def test_has_session_decorator_returns_func_result(self, devices_mock):
71 |
72 | devices_mock.return_value = []
73 |
74 | @plugin.require_sessions_for_all_devices('to')
75 | def func(x):
76 | return x
77 |
78 | recipient = 'juliet@capulet.lit'
79 | stanza = ''.format(recipient)
80 |
81 | assert func(stanza) == stanza
82 |
83 | @patch('profanity_omemo_plugin.omemo.state.OmemoState.devices_without_sessions')
84 | def test_has_session_decorator_returns_func_result_on_none_session(self, devices_mock):
85 | devices_mock.return_value = []
86 |
87 | @plugin.require_sessions_for_all_devices('to')
88 | def func(x):
89 | return x
90 |
91 | recipient = 'juliet@capulet.lit'
92 |
93 | ProfActiveOmemoChats.add(recipient)
94 |
95 | stanza = ''.format(recipient)
96 |
97 | assert func(stanza) == stanza
98 |
99 | @patch('profanity_omemo_plugin.omemo.state.OmemoState.devices_without_sessions')
100 | def test_has_session_decorator_returns_default_if_no_session(self, devices_mock):
101 | devices_mock.return_value = [223, 445]
102 |
103 | @plugin.require_sessions_for_all_devices('to')
104 | def func(x):
105 | return x
106 |
107 | recipient = 'juliet@capulet.lit'
108 | stanza = ''.format(recipient)
109 |
110 | assert func(stanza) is None
111 |
112 | @patch('profanity_omemo_plugin.omemo.state.OmemoState.devices_without_sessions')
113 | def test_has_session_decorator_returns_custom_return_if_no_session(self, devices_mock):
114 | devices_mock.return_value = [4711, 1290]
115 |
116 | @plugin.require_sessions_for_all_devices('to', else_return='whatever')
117 | def func(x):
118 | return x
119 |
120 | recipient = 'juliet@capulet.lit'
121 | stanza = ''.format(recipient)
122 |
123 | assert func(stanza) is 'whatever'
124 |
125 | def test_has_session_decorator_returns_default_on_error(self):
126 | @plugin.require_sessions_for_all_devices('not_valid_attrib')
127 | def func(x):
128 | return x
129 |
130 | recipient = 'juliet@capulet.lit'
131 | ProfActiveOmemoChats.add(recipient)
132 |
133 | stanza = ''.format(recipient)
134 |
135 | assert func(stanza) is None
136 |
137 | @patch('prof.settings_boolean_get')
138 | def test_omemo_enabled_decorator_returns_func_if_enabled(self, settings_boolean_get):
139 | @plugin.omemo_enabled()
140 | def func(x):
141 | return x
142 |
143 | settings_boolean_get.return_value = True
144 | stanza = ''
145 |
146 | assert func(stanza) == stanza
147 |
148 | @patch('prof.settings_boolean_get')
149 | def test_omemo_enabled_decorator_returns_default_if_disabled(self, settings_boolean_get):
150 | @plugin.omemo_enabled(else_return='magic_default')
151 | def func(x):
152 | return x
153 |
154 | settings_boolean_get.return_value = False
155 | stanza = ''
156 |
157 | assert func(stanza) == 'magic_default'
158 |
159 | @patch('prof.settings_boolean_get')
160 | def test_stacked_decorators(self, settings_boolean_get):
161 | @plugin.omemo_enabled(else_return='enabled_first')
162 | @plugin.require_sessions_for_all_devices('to', else_return='session_second')
163 | def func(x):
164 | return x
165 |
166 | settings_boolean_get.return_value = True
167 | recipient = 'juliet@capulet.lit'
168 | ProfActiveOmemoChats.add(recipient)
169 |
170 | stanza = ''.format(recipient)
171 |
172 | assert func(stanza) == stanza
173 |
174 | @patch('prof.settings_boolean_get')
175 | def test_stacked_decorators_omemo_enabled_priority(self, settings_boolean_get):
176 | @plugin.omemo_enabled(else_return='enabled_first')
177 | @plugin.require_sessions_for_all_devices('to', else_return='session_second')
178 | def func(x):
179 | return x
180 |
181 | settings_boolean_get.return_value = False
182 | recipient = 'juliet@capulet.lit'
183 | stanza = ''.format(recipient)
184 |
185 | assert func(stanza) == 'enabled_first'
186 |
--------------------------------------------------------------------------------
/tests/test_prof_omemo_state.py:
--------------------------------------------------------------------------------
1 | import sqlite3
2 |
3 | import pytest
4 | from mock import patch
5 |
6 | from profanity_omemo_plugin.prof_omemo_state import ProfOmemoUser, \
7 | ProfOmemoState, ProfActiveOmemoChats
8 |
9 |
10 | def get_test_db_connection():
11 | print('Using In-Memory Database')
12 | return sqlite3.connect(':memory:', check_same_thread=False)
13 |
14 |
15 | class TestProfOmemoUtils(object):
16 |
17 | def teardown_method(self, test_method):
18 | ProfOmemoUser.reset()
19 | ProfActiveOmemoChats.reset()
20 |
21 | def test_prof_omemo_user_is_singleton(self):
22 | assert ProfOmemoUser().account == ProfOmemoUser().account
23 | assert ProfOmemoUser().fulljid == ProfOmemoUser().fulljid
24 |
25 | def test_initial_user_is_not_set(self):
26 | omemo_user = ProfOmemoUser()
27 |
28 | assert omemo_user.account is None
29 | assert omemo_user.fulljid is None
30 |
31 | def test_set_omemo_user(self):
32 | account = 'me@there.com'
33 | fulljid = 'me@there.com/profanity'
34 |
35 | ProfOmemoUser().account is None
36 | ProfOmemoUser().fulljid is None
37 |
38 | ProfOmemoUser.set_user(account, fulljid)
39 |
40 | ProfOmemoUser().account == account
41 | ProfOmemoUser().fulljid == fulljid
42 |
43 | def test_reset_omemo_user(self):
44 | account = 'me@there.com'
45 | fulljid = 'me@there.com/profanity'
46 |
47 | ProfOmemoUser.set_user(account, fulljid)
48 |
49 | ProfOmemoUser().account == account
50 | ProfOmemoUser().fulljid == fulljid
51 |
52 | ProfOmemoUser.reset()
53 |
54 | ProfOmemoUser().account is None
55 | ProfOmemoUser().fulljid is None
56 |
57 | @patch('profanity_omemo_plugin.db.get_connection')
58 | def test_omemo_state_returns_singleton(self, mockdb):
59 | mockdb.return_value = get_test_db_connection()
60 | account = 'me@there.com'
61 | fulljid = 'me@there.com/profanity'
62 |
63 | ProfOmemoUser.set_user(account, fulljid)
64 |
65 | state = ProfOmemoState()
66 |
67 | new_state = ProfOmemoState()
68 |
69 | assert state == new_state
70 |
71 | @patch('profanity_omemo_plugin.db.get_connection')
72 | def test_omemo_state_raises_runtime_error_if_not_connected(self, mockdb):
73 | mockdb.return_value = get_test_db_connection()
74 |
75 | ProfOmemoUser.reset()
76 |
77 | with pytest.raises(RuntimeError):
78 | _ = ProfOmemoState()
79 |
80 | def test_omemo_acitve_chat_is_singleton(self):
81 | account = 'juliet@capulet.lit'
82 |
83 | active_chats_instance = ProfActiveOmemoChats
84 | ProfActiveOmemoChats.add(account)
85 |
86 | new_active_chats_instance = ProfActiveOmemoChats
87 |
88 | assert active_chats_instance._active == new_active_chats_instance._active
89 |
90 | def test_omemo_chat_adds_accounts_uniquely(self):
91 | account = 'juliet@capulet.lit'
92 | assert len(ProfActiveOmemoChats._active) == 0
93 |
94 | ProfActiveOmemoChats.add(account)
95 | assert len(ProfActiveOmemoChats._active) == 1
96 |
97 | ProfActiveOmemoChats.add(account)
98 | assert len(ProfActiveOmemoChats._active) == 1
99 |
100 | def test_omemo_chat_remove_account(self):
101 | account = 'juliet@capulet.lit'
102 | assert len(ProfActiveOmemoChats._active) == 0
103 |
104 | ProfActiveOmemoChats.add(account)
105 | assert len(ProfActiveOmemoChats._active) == 1
106 |
107 | ProfActiveOmemoChats.remove(account)
108 | assert len(ProfActiveOmemoChats._active) == 0
109 |
110 | def test_prof_active_chats_finds_active_chats(self):
111 | account = 'juliet@capulet.lit'
112 | account2 = 'romeo@montague.lit'
113 |
114 | ProfActiveOmemoChats.add(account)
115 | ProfActiveOmemoChats.add(account2)
116 |
117 | assert ProfActiveOmemoChats.account_is_active(account) is True
118 | assert ProfActiveOmemoChats.account_is_active(account2) is True
119 |
120 | ProfActiveOmemoChats.remove(account)
121 | assert ProfActiveOmemoChats.account_is_active(account) is False
122 |
123 | ProfActiveOmemoChats.remove(account2)
124 | assert ProfActiveOmemoChats.account_is_active(account2) is False
125 |
--------------------------------------------------------------------------------
/tests/test_unpacking_xmpp.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | from __future__ import print_function
3 | from __future__ import unicode_literals
4 |
5 | import sqlite3
6 |
7 | import pytest
8 | from mock import patch
9 |
10 | import profanity_omemo_plugin.xmpp as xmpp
11 | from profanity_omemo_plugin.constants import NS_DEVICE_LIST, NS_OMEMO
12 | from profanity_omemo_plugin.prof_omemo_state import ProfOmemoUser, \
13 | ProfOmemoState
14 | from .fixtures import get_stanza_fixture
15 |
16 |
17 | def get_test_db_connection():
18 | print('Using In-Memory Database')
19 | return sqlite3.connect(':memory:', check_same_thread=False)
20 |
21 |
22 | class TestUnpackingXMPP(object):
23 |
24 | def test_unpack_bundle_info(self):
25 | stanza = get_stanza_fixture('iq_bundle_info.xml')
26 | bundle_info = xmpp.unpack_bundle_info(stanza)
27 |
28 | assert bundle_info.get('sender') == 'bob@secure.it'
29 | assert bundle_info.get('device') == '666666'
30 |
31 | def test_unpack_bundle_info_chatsecure(self):
32 | stanza = get_stanza_fixture('iq_bundle_info_chatsecure.xml')
33 | bundle_info = xmpp.unpack_bundle_info(stanza)
34 |
35 | assert bundle_info.get('sender') == 'bob@secure.it'
36 | assert bundle_info.get('device') == '4711'
37 |
38 | @patch('profanity_omemo_plugin.db.get_connection')
39 | def test_unpack_devicelist_update(self, mockdb):
40 | mockdb.return_value = get_test_db_connection()
41 | test_stanza = (
42 | ''
43 | ''
44 | ''
45 | '- '
46 | '
'
47 | ''
48 | ''
49 | '
'
50 | ' '
51 | ''
52 | ''
53 | ''
54 | ).format(NS_DEVICE_LIST, NS_OMEMO)
55 |
56 | msg_dict = xmpp.unpack_devicelist_info(test_stanza)
57 | expected_msg_dict = {'from': 'juliet@capulet.lit',
58 | 'devices': [12345, 4223]}
59 |
60 | assert msg_dict == expected_msg_dict
61 |
62 | @patch('profanity_omemo_plugin.db.get_connection')
63 | def test_unpack_devicelist_request_result_for_own_devices(self, mockdb):
64 | mockdb.return_value = get_test_db_connection()
65 | test_stanza = (''
66 | ''
67 | ''
68 | '- '
69 | '
'
70 | ''
71 | '
'
72 | ' '
73 | ''
74 | ''
75 | ''
76 | ).format(NS_DEVICE_LIST, NS_OMEMO)
77 |
78 | current_user = 'romeo@montague.lit'
79 | ProfOmemoUser.set_user(current_user, current_user + '/profanity')
80 |
81 | msg_dict = xmpp.unpack_devicelist_info(test_stanza)
82 | expected_msg_dict = {'from': current_user,
83 | 'devices': [1426586702]}
84 |
85 | assert msg_dict == expected_msg_dict
86 |
87 | @patch('profanity_omemo_plugin.db.get_connection')
88 | def test_upack_encrypted_message(self, mockdb):
89 | pytest.skip('Skip for now ... needs to be done properly at some point.')
90 | mockdb.return_value = get_test_db_connection()
91 |
92 | msg_stanza = (
93 | ''
94 | 'Some default body if encryption fails.'
95 | ''
96 | ''
97 | 'dummy'
98 | 'PnZsChVPjwI6jTL6fpkz5Q=='
99 | ''
100 | '5eCvRJz6ASe8YzCyhB6W3JozxHec'
101 | ''
102 | ''
103 | ''
104 | ''
105 | ''
106 | ).format(NS_OMEMO)
107 |
108 | msg_dict = xmpp.unpack_encrypted_stanza(msg_stanza)
109 | expected_msg_dict = {'sender_jid': 'romeo@montague.lit',
110 | 'sender_resource': 'profanity',
111 | 'sid': 1461841909,
112 | 'iv': 'PnZsChVPjwI6jTL6fpkz5Q==',
113 | 'keys': {1260459496: 'dummy'},
114 | 'payload': '5eCvRJz6ASe8YzCyhB6W3JozxHec'}
115 |
116 | assert msg_dict == expected_msg_dict
117 |
118 | @patch('profanity_omemo_plugin.db.get_connection')
119 | def test_encrypt_stanza(self, mockdb):
120 | pytest.skip('Work in Progress')
121 | mockdb.return_value = get_test_db_connection()
122 |
123 | current_user = 'romeo@montague.lit'
124 | ProfOmemoUser.set_user(current_user, current_user + '/profanity')
125 |
126 | recipient = 'juliet@capulet.lit'
127 | omemo_state = ProfOmemoState()
128 | omemo_state.set_devices(recipient, [4711, 995746])
129 |
130 | raw_stanza = (''
131 | 'Hollo'
132 | ''
133 | ''
134 | ).format(recipient)
135 |
136 | encrypted = xmpp.encrypt_stanza(raw_stanza)
--------------------------------------------------------------------------------
/tox.ini:
--------------------------------------------------------------------------------
1 | [tox]
2 | envlist = py27,py35,py36
3 |
4 | [testenv]
5 | install_command = pip install --process-dependency-links {opts} {packages}
6 | commands =
7 | coverage run --source profanity_omemo_plugin,prof_omemo_plugin setup.py test
8 | coverage report -m
9 | deps =
10 | pytest-pep8
11 | pytest-cov
12 | pytest
13 | mock
14 | coverage
15 |
--------------------------------------------------------------------------------