pax_global_header00006660000000000000000000000064141752773530014530gustar00rootroot0000000000000052 comment=86f03172021eae796ef4ede3e7c6a1daea1a3718 axc-0.3.7/000077500000000000000000000000001417527735300123125ustar00rootroot00000000000000axc-0.3.7/.github/000077500000000000000000000000001417527735300136525ustar00rootroot00000000000000axc-0.3.7/.github/dependabot.yml000066400000000000000000000005011417527735300164760ustar00rootroot00000000000000# Copyright (c) 2022 Sebastian Pipping # Licensed under the GPL v2 or later version: 2 updates: - package-ecosystem: "github-actions" commit-message: include: "scope" prefix: "Actions" directory: "/" labels: - "enhancement" schedule: interval: "weekly" axc-0.3.7/.github/workflows/000077500000000000000000000000001417527735300157075ustar00rootroot00000000000000axc-0.3.7/.github/workflows/linux.yml000066400000000000000000000032271417527735300175750ustar00rootroot00000000000000# Copyright (c) 2022 Sebastian Pipping # Licensed under the GPL v2 or later name: Build for Linux on: pull_request: push: schedule: - cron: '0 2 * * 5' # Every Friday at 2am jobs: checks: name: Build for Linux (${{ matrix.libsignal }} libsignal) runs-on: ubuntu-20.04 strategy: matrix: libsignal: ['system', 'bundled'] steps: - uses: actions/checkout@v2.4.0 - name: Install build dependencies (all but libsignal-protocol-c) run: |- set -x sudo apt-get update sudo apt-get install --yes --no-install-recommends -V \ gcovr \ libcmocka-dev \ libgcrypt20-dev \ libglib2.0-dev \ libsqlite3-dev - name: Install build dependency libsignal-protocol-c if: ${{ matrix.libsignal == 'system' }} run: |- sudo apt-get install --yes --no-install-recommends -V \ libsignal-protocol-c-dev - name: Fetch Git submodule for build dependency libsignal-protocol-c if: ${{ matrix.libsignal == 'bundled' }} run: |- git submodule update --init --recursive - name: Build run: |- set -x make -j $(nproc) all build/libaxc-nt.a - name: Test run: |- make coverage # includes tests - name: Install run: |- set -x -o pipefail make DESTDIR="${PWD}"/ROOT install find ROOT/ -not -type d | sort | xargs ls -l - name: Store coverage HTML report uses: actions/upload-artifact@v2.3.1 with: name: coverage_${{ matrix.libsignal }} path: coverage/ if-no-files-found: error axc-0.3.7/.gitignore000066400000000000000000000000601417527735300142760ustar00rootroot00000000000000build/ client/ lib/libaxolotl-c/build *.gc* *.o axc-0.3.7/.gitmodules000066400000000000000000000002121417527735300144620ustar00rootroot00000000000000[submodule "lib/libsignal-protocol-c"] path = lib/libsignal-protocol-c url = https://github.com/WhisperSystems/libsignal-protocol-c.git axc-0.3.7/CHANGELOG.md000066400000000000000000000051201417527735300141210ustar00rootroot00000000000000# Changelog ## [0.3.7] - 2022-01-29 ### Fixed - Compiler warnings ([#21](https://github.com/gkdr/axc/issues/21), [#29](https://github.com/gkdr/axc/pull/29)) (thanks, [@hartwork](https://github.com/hartwork)!) - `gcc` can now be set from env like the rest of the tools. ([#30](https://github.com/gkdr/axc/pull/30))) (thanks, [@henry-nicolas](https://github.com/henry-nicolas) and Helmut Grohne!) - Fix the build for users without libsignal-protocol-c installed system-wide ([#31](https://github.com/gkdr/axc/pull/31)) (thanks, [@hartwork](https://github.com/hartwork)!) - The example code is runnable again, and some memory leaks ([#14](https://github.com/gkdr/axc/pull/14)) (thanks, [@fbrausse](https://github.com/fbrausse)!) - Compiler warnings for test files. ### Infrastructure - Cover Linux build by GitHub Actions CI ([#31](https://github.com/gkdr/axc/pull/31)) (thanks, [@hartwork](https://github.com/hartwork)!) ## [0.3.6] - 2021-09-06 ### Fixed - `pkg_config` can now be set from env like the rest of the tools. ([#28](https://github.com/gkdr/axc/pull/28)) (thanks, [@henry-nicolas](https://github.com/henry-nicolas) and Helmut Grohne!) ## [0.3.5] - 2021-08-21 ### Fixed - Added missing symlinks `libaxc.so.$(VER_MAJ)` and `libaxc.so`. ([#24](https://github.com/gkdr/axc/pull/24)) (thanks, [@hartwork](https://github.com/hartwork)!) - `session_cipher` is now `free()`d using the correct function. ([#25](https://github.com/gkdr/axc/pull/25)) (thanks, [@root-hardenedvault](https://github.com/root-hardenedvault)!) - Already removed files now don't cause an error during cleanup. ([#27](https://github.com/gkdr/axc/pull/27)) (thanks, [@henry-nicolas](https://github.com/henry-nicolas)!) ## [0.3.4] - 2021-02-10 ### Added - Makefile target to build a shared library, optionally depending on a shared libsignal-protocol-c. ([#17](https://github.com/gkdr/axc/pull/17)) (thanks, [@henry-nicolas](https://github.com/henry-nicolas)!) ### Changed - Updated libsignal-protocol-c to v2.3.3. ### Fixed - Added date to 0.3.3 release in changelog. - Delete an unused variable. ([#22](https://github.com/gkdr/axc/pull/22)) (thanks, [@henry-nicolas](https://github.com/henry-nicolas)!) - `axc_context_destroy_all()` now also frees itself. ([#23](https://github.com/gkdr/axc/pull/23)) (thanks, [@henry-nicolas](https://github.com/henry-nicolas)!) ## [0.3.3] - 2020-07-23 ### Added - Correct license headers. (thanks [@henry-nicolas](https://github.com/henry-nicolas)) - This file. ### Fixed - Removed dead code using internal libsignal-protocol-c functionality. ## 0.3.2 and before Lost to commit logs. Might hunt the changed down later. axc-0.3.7/LICENSE000066400000000000000000001045051417527735300133240ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {one line to give the program's name and a brief idea of what it does.} Copyright (C) {year} {name of author} This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: {project} Copyright (C) {year} {fullname} This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . axc-0.3.7/Makefile000066400000000000000000000124341417527735300137560ustar00rootroot00000000000000### toolchain # CC ?= gcc AR ?= ar MKDIR = mkdir MKDIR_P = mkdir -p CMAKE ?= cmake CMAKE_FLAGS = -DCMAKE_BUILD_TYPE=Debug -DCMAKE_C_FLAGS=-fPIC ARCH := $(shell $(CC) -print-multiarch) VER_MAJ = 0 VERSION = 0.3.7 AX_DIR=./lib/libsignal-protocol-c AX_BDIR=$(AX_DIR)/build AX_PATH=$(AX_BDIR)/src/libsignal-protocol-c.a PKG_CONFIG ?= pkg-config GLIB_CFLAGS ?= $(shell $(PKG_CONFIG) --cflags glib-2.0) GLIB_LDFLAGS ?= $(shell $(PKG_CONFIG) --libs glib-2.0) SQLITE3_CFLAGS ?= $(shell $(PKG_CONFIG) --cflags sqlite3) SQLITE3_LDFLAGS ?= $(shell $(PKG_CONFIG) --libs sqlite3) SIGNAL_CFLAGS ?= $(shell $(PKG_CONFIG) --cflags libsignal-protocol-c) SIGNAL_LDFLAGS ?= $(shell $(PKG_CONFIG) --libs libsignal-protocol-c) LIBGCRYPT_CONFIG ?= libgcrypt-config LIBGCRYPT_LDFLAGS ?= $(shell $(LIBGCRYPT_CONFIG) --libs) SDIR = src LDIR = lib BDIR = build TDIR = test TFN = test_all CDIR = coverage PKGCFG_C=$(GLIB_CFLAGS) \ $(SQLITE3_CFLAGS) \ $(LIBGCRYPT_CFLAGS) PKGCFG_L=$(GLIB_LDFLAGS) \ $(SQLITE3_LDFLAGS) \ $(LIBGCRYPT_LDFLAGS) REQPKG=libsignal-protocol-c REQPKG:=$(shell $(PKG_CONFIG) --exists $(REQPKG) && echo '$(REQPKG)') ifneq ($(REQPKG),) AX_PATH_AS_NEEDED = PKGCFG_C += $(SIGNAL_CFLAGS) PKGCFG_L += $(SIGNAL_LDFLAGS) else AX_PATH_AS_NEEDED = $(AX_PATH) HEADERS=-I$(AX_DIR)/src PKGCFG_C +=$(HEADERS) PKGCFG_L +=$(AX_PATH) endif ifeq ($(PREFIX),) PREFIX := /usr/local endif CPPFLAGS += -D_XOPEN_SOURCE=700 -D_BSD_SOURCE -D_POSIX_SOURCE -D_GNU_SOURCE -D_DEFAULT_SOURCE CFLAGS += $(PKGCFG_C) -std=c11 -g -Wall -Wextra -Wpedantic \ -Wstrict-overflow -fno-strict-aliasing -funsigned-char \ -fno-builtin-memset -fstack-protector-strong -Wformat -Werror=format-security TESTFLAGS=$(PKGCFG_C) -g -O0 --coverage -Wall -Wextra -Wpedantic -Wstrict-overflow -fstack-protector-strong -Wformat -Werror=format-security LDFLAGS += -pthread -ldl $(PKGCFG_L) -lm LDFLAGS_T= -lcmocka $(LDFLAGS) PICFLAGS=-fPIC $(CFLAGS) all: $(BDIR)/libaxc.a shared $(BDIR): $(MKDIR_P) $@ client: $(SDIR)/message_client.c $(BDIR)/axc_store.o $(BDIR)/axc_crypto.o $(BDIR)/axc.o $(AX_PATH_AS_NEEDED) $(MKDIR_P) $@ $(CC) $(CPPFLAGS) $(CFLAGS) $^ -o $@/$@.o $(LDFLAGS) $(BDIR)/axc.o: $(SDIR)/axc.c $(AX_PATH_AS_NEEDED) | $(BDIR) $(CC) $(PICFLAGS) $(CPPFLAGS) -c $< -o $@ $(BDIR)/axc-nt.o: $(SDIR)/axc.c $(AX_PATH_AS_NEEDED) | $(BDIR) $(CC) $(PICFLAGS) $(CPPFLAGS) -DNO_THREADS -c $< -o $@ $(BDIR)/axc_crypto.o: $(SDIR)/axc_crypto.c $(AX_PATH_AS_NEEDED) | $(BDIR) $(CC) $(PICFLAGS) $(CPPFLAGS) -c $< -o $@ $(BDIR)/axc_store.o: $(SDIR)/axc_store.c $(AX_PATH_AS_NEEDED) | $(BDIR) $(CC) $(PICFLAGS) $(CPPFLAGS) -c $< -o $@ $(BDIR)/libaxc.a: $(BDIR)/axc.o $(BDIR)/axc_crypto.o $(BDIR)/axc_store.o $(AR) rcs $@ $^ $(BDIR)/libaxc-nt.a: $(BDIR)/axc-nt.o $(BDIR)/axc_crypto.o $(BDIR)/axc_store.o $(AR) rcs $@ $^ $(BDIR)/libaxc.so: $(AX_PATH_AS_NEEDED) | $(BDIR) $(CC) -shared -Wl,-soname,libaxc.so.$(VER_MAJ) -o $@ $(PICFLAGS) $(SDIR)/axc.c $(SDIR)/axc_crypto.c $(SDIR)/axc_store.c $(LDFLAGS) $(CPPFLAGS) $(BDIR)/libaxc.pc: $(BDIR) echo 'prefix='$(PREFIX) > $@ echo 'exec_prefix=$${prefix}' >> $@ echo 'libdir=$${prefix}/lib/$(ARCH)' >> $@ echo 'includedir=$${prefix}/include' >> $@ echo 'Name: libaxc' >> $@ echo 'Version: ${VERSION}' >> $@ echo 'Description: client library for libsignal-protocol-c' >> $@ echo 'Requires: libsignal-protocol-c' >> $@ echo 'Cflags: -I$${includedir}/axc' >> $@ echo 'Libs: -L$${libdir} -laxc' >> $@ $(AX_DIR): @echo "ERROR: Git submodules are not initialized, please run e.g. 'git submodule update --init --recursive' first" >&2 ; false $(AX_BDIR): | $(AX_DIR) $(MKDIR_P) $@ $(AX_PATH): | $(AX_BDIR) cd $(AX_BDIR) && $(CMAKE) $(CMAKE_FLAGS) .. $(MAKE) -C $(AX_BDIR) shared: $(BDIR)/libaxc.so $(BDIR)/libaxc.pc install: $(BDIR) install -d $(DESTDIR)/$(PREFIX)/lib/$(ARCH)/pkgconfig/ install -m 644 $(BDIR)/libaxc.a $(DESTDIR)/$(PREFIX)/lib/$(ARCH)/libaxc.a install -m 644 $(BDIR)/libaxc.so $(DESTDIR)/$(PREFIX)/lib/$(ARCH)/libaxc.so.$(VERSION) ln -s libaxc.so.$(VERSION) $(DESTDIR)/$(PREFIX)/lib/$(ARCH)/libaxc.so.$(VER_MAJ) ln -s libaxc.so.$(VERSION) $(DESTDIR)/$(PREFIX)/lib/$(ARCH)/libaxc.so install -m 644 $(BDIR)/libaxc.pc $(DESTDIR)/$(PREFIX)/lib/$(ARCH)/pkgconfig/ install -d $(DESTDIR)/$(PREFIX)/include/axc/ install -m 644 $(SDIR)/axc.h $(DESTDIR)/$(PREFIX)/include/axc/ install -m 644 $(SDIR)/axc_crypto.h $(DESTDIR)/$(PREFIX)/include/axc/ install -m 644 $(SDIR)/axc_store.h $(DESTDIR)/$(PREFIX)/include/axc/ .PHONY: test test: test_store test_client .PHONY: test_store test_store: $(SDIR)/axc_store.c $(SDIR)/axc_crypto.c $(TDIR)/test_store.c $(AX_PATH_AS_NEEDED) $(CC) $(TESTFLAGS) -o $(TDIR)/$@.o $(TDIR)/test_store.c $(SDIR)/axc_crypto.c $(LDFLAGS_T) -$(TDIR)/$@.o find . -maxdepth 1 -iname 'test*.g*' -exec mv {} $(TDIR) \; .PHONY: test_client test_client: $(SDIR)/axc.c $(SDIR)/axc_crypto.c $(SDIR)/axc_store.c $(TDIR)/test_client.c $(AX_PATH_AS_NEEDED) $(CC) $(TESTFLAGS) -o $(TDIR)/$@.o $(SDIR)/axc_crypto.c $(TDIR)/test_client.c $(LDFLAGS_T) -$(TDIR)/$@.o find . -maxdepth 1 -iname 'test*.g*' -exec mv {} $(TDIR) \; .PHONY: coverage coverage: test gcovr -r . --html --html-details -o $@.html gcovr -r . -s $(MKDIR_P) $@ mv $@.* $@ .PHONY: clean clean: rm -f $(TDIR)/*.o rm -f $(TDIR)/*.gcno $(TDIR)/*.gcda $(TDIR)/*.sqlite .PHONY: clean-all clean-all: clean rm -rf client $(BDIR) $(CDIR) $(AX_BDIR) axc-0.3.7/README.md000066400000000000000000000040471417527735300135760ustar00rootroot00000000000000# axc 0.3.7 Client lib for [libsignal-c](https://github.com/WhisperSystems/libsignal-protocol-c), implementing the needed database and crypto interfaces using SQLite and gcrypt. Initially, the library's name was _libaxolotl_, hence the name. Additionally it provides utility functions for common use cases like encrypting and decrypting, ultimately making direct use of libsignal unnecessary. ## Dependencies * gcrypt for the crypto (`libgcrypt20-dev`) * SQLite for the stores (`libsqlite3-dev`) Optional: * [cmocka](https://cmocka.org/) for testing (`make test`) * [gcovr](http://gcovr.com/) for a coverage report (`make coverage`) ## Installation First, you should pull the _libsignal_ submodule using `git submodule update --init`. If you are using this as a submodule in another project, you should lso append `--recursive` so it gets pulled as well. Since you will need to link _libsignal_ also anyway, it is included here instead of just the headers, and the makefile provides an example of how to compile it as a static library with position independent code. In theory there is also the possibility to install it as a shared lib by typing `cmake -DCMAKE_BUILD_TYPE=Debug -DBUILD_SHARED_LIBS=ON ..` instead and then type `sudo make install` after the `make`. The standard makefile target creates a static library with position independent code. There is also a target for creating a static library without the code for threading support, as it is implemented using `pthread` and will not work on Windows, and is not necessary for the functioning. The `client` make target is a little demo that should explain the usage a bit, and if that is not enough there is also the testcases and the documentation. Unfortunately it is currently broken as the synchronous code was removed. ## Usage The basic idea is to create the `axc_context`, set what is needed (e.g. path to the database or logging function), init it, and then pass it to every function as it contains all necessary data. As said before, In theory you should not have to directly communicate with _libsignal_. axc-0.3.7/lib/000077500000000000000000000000001417527735300130605ustar00rootroot00000000000000axc-0.3.7/lib/libsignal-protocol-c/000077500000000000000000000000001417527735300171035ustar00rootroot00000000000000axc-0.3.7/src/000077500000000000000000000000001417527735300131015ustar00rootroot00000000000000axc-0.3.7/src/axc.c000066400000000000000000001076161417527735300140330ustar00rootroot00000000000000/* * Copyright (C) 2017-2020 Richard Bayerle * SPDX-License-Identifier: GPL-3.0-only * Author: Richard Bayerle */ #include #include // va_* #include // printf, fprintf #include // exit, malloc #include // memset #ifndef NO_THREADS #include // mutex stuff #endif #include #include "signal_protocol.h" #include "key_helper.h" #include "protocol.h" #include "session_builder.h" #include "session_cipher.h" #include "session_state.h" #include "axc.h" #include "axc_store.h" #include "axc_crypto.h" void recursive_mutex_lock(void * user_data); void recursive_mutex_unlock(void * user_data); typedef struct axc_mutexes { #ifndef NO_THREADS pthread_mutex_t * mutex_p; pthread_mutexattr_t * mutex_attr_p; #else int dummy; // to silence "warning: struct has no members [-Wpedantic]" #endif } axc_mutexes; struct axc_context { signal_context * axolotl_global_context_p; signal_protocol_store_context * axolotl_store_context_p; axc_mutexes * mutexes_p; char * db_filename; void (*log_func)(int level, const char * message, size_t len, void * user_data); int log_level; }; struct axc_handshake { session_builder * session_builder_p; axc_buf * handshake_msg_p; }; struct axc_buf_list_item { uint32_t id; axc_buf * buf_p; axc_buf_list_item * next_p; }; struct axc_bundle { uint32_t registration_id; axc_buf_list_item * pre_keys_head_p; uint32_t signed_pre_key_id; axc_buf * signed_pre_key_public_serialized_p; axc_buf * signed_pre_key_signature_p; axc_buf * identity_key_public_serialized_p; }; int axc_buf_list_item_create(axc_buf_list_item ** item_pp, uint32_t * id_p, axc_buf * data_p) { axc_buf_list_item * item_p = malloc(sizeof(axc_buf_list_item)); if (!item_p) { return -1; } memset(item_p, 0, sizeof(axc_buf_list_item)); if (id_p) { item_p->id = *id_p; } if (data_p) { item_p->buf_p = data_p; } *item_pp = item_p; return 0; } void axc_buf_list_item_set_next(axc_buf_list_item * item_p, axc_buf_list_item * next_p) { item_p->next_p = next_p; } axc_buf_list_item * axc_buf_list_item_get_next(axc_buf_list_item * item_p) { return item_p->next_p; } uint32_t axc_buf_list_item_get_id(axc_buf_list_item * item_p) { return item_p->id; } axc_buf * axc_buf_list_item_get_buf(axc_buf_list_item * item_p) { return item_p->buf_p; } void axc_buf_list_free(axc_buf_list_item * head_p) { axc_buf_list_item * next = head_p; axc_buf_list_item * temp = (void *) 0; while (next) { axc_buf_free(next->buf_p); temp = next->next_p; free(next); next = temp; } } int axc_bundle_collect(size_t n, axc_context * ctx_p, axc_bundle ** bundle_pp) { int ret_val = 0; char * err_msg = ""; axc_bundle * bundle_p = (void *) 0; uint32_t reg_id = 0; axc_buf_list_item * pre_key_list_p = (void *) 0; uint32_t signed_prekey_id = 0; //FIXME: right now, only one is ever generated, this should be changed session_signed_pre_key * signed_prekey_p = (void *) 0; ec_key_pair * signed_prekey_pair_p = (void *) 0; ec_public_key * signed_prekey_public_p = (void *) 0; axc_buf * signed_prekey_public_data_p = (void *) 0; axc_buf * signed_prekey_signature_data_p = (void *) 0; ratchet_identity_key_pair * identity_key_pair_p = (void *) 0; ec_public_key * identity_key_public_p = (void *) 0; axc_buf * identity_key_public_data_p = (void *) 0; axc_log(ctx_p, AXC_LOG_DEBUG, "%s: entered", __func__); bundle_p = malloc(sizeof(axc_bundle)); if (!bundle_p) { err_msg = "failed to malloc bundle"; ret_val = AXC_ERR_NOMEM; goto cleanup; } memset(bundle_p, 0, sizeof(axc_bundle)); ret_val = axc_get_device_id(ctx_p, ®_id); if (ret_val) { err_msg = "failed to retrieve device id"; goto cleanup; } bundle_p->registration_id = reg_id; ret_val = axc_db_pre_key_get_list(n, ctx_p, &pre_key_list_p); if (ret_val) { err_msg = "failed to retrieve pre key list"; goto cleanup; } bundle_p->pre_keys_head_p = pre_key_list_p; ret_val = signal_protocol_signed_pre_key_load_key(ctx_p->axolotl_store_context_p, &signed_prekey_p, signed_prekey_id); if (ret_val) { err_msg = "failed to get signed pre key"; goto cleanup; } signed_prekey_pair_p = session_signed_pre_key_get_key_pair(signed_prekey_p); signed_prekey_public_p = ec_key_pair_get_public(signed_prekey_pair_p); ret_val = ec_public_key_serialize(&signed_prekey_public_data_p, signed_prekey_public_p); if (ret_val) { err_msg = "failed to serialize signed pre key"; goto cleanup; } bundle_p->signed_pre_key_public_serialized_p = signed_prekey_public_data_p; signed_prekey_signature_data_p = axc_buf_create(session_signed_pre_key_get_signature(signed_prekey_p), session_signed_pre_key_get_signature_len(signed_prekey_p)); if (!signed_prekey_signature_data_p) { ret_val = AXC_ERR; err_msg = "failed to create buffer for signature data"; goto cleanup; } bundle_p->signed_pre_key_signature_p = signed_prekey_signature_data_p; ret_val = signal_protocol_identity_get_key_pair(ctx_p->axolotl_store_context_p, &identity_key_pair_p); if (ret_val) { err_msg = "failed to retrieve identity key pair"; goto cleanup; } identity_key_public_p = ratchet_identity_key_pair_get_public(identity_key_pair_p); ret_val = ec_public_key_serialize(&identity_key_public_data_p, identity_key_public_p); if (ret_val) { err_msg = "failed to serialize identity key"; goto cleanup; } bundle_p->identity_key_public_serialized_p = identity_key_public_data_p; *bundle_pp = bundle_p; cleanup: if (ret_val) { axc_buf_list_free(pre_key_list_p); axc_buf_free(signed_prekey_public_data_p); axc_buf_free(signed_prekey_signature_data_p); axc_buf_free(identity_key_public_data_p); free(bundle_p); axc_log(ctx_p, AXC_LOG_ERROR, "%s: %s", __func__, err_msg); } SIGNAL_UNREF(signed_prekey_p); SIGNAL_UNREF(identity_key_pair_p); axc_log(ctx_p, AXC_LOG_DEBUG, "%s: leaving", __func__); return ret_val; } uint32_t axc_bundle_get_reg_id(axc_bundle * bundle_p) { return bundle_p->registration_id; } axc_buf_list_item * axc_bundle_get_pre_key_list(axc_bundle * bundle_p) { return bundle_p->pre_keys_head_p; } uint32_t axc_bundle_get_signed_pre_key_id(axc_bundle * bundle_p) { return bundle_p->signed_pre_key_id; } axc_buf * axc_bundle_get_signed_pre_key(axc_bundle * bundle_p) { return bundle_p->signed_pre_key_public_serialized_p; } axc_buf * axc_bundle_get_signature(axc_bundle * bundle_p) { return bundle_p->signed_pre_key_signature_p; } axc_buf * axc_bundle_get_identity_key(axc_bundle * bundle_p) { return bundle_p->identity_key_public_serialized_p; } void axc_bundle_destroy(axc_bundle * bundle_p) { if (bundle_p) { axc_buf_list_free(bundle_p->pre_keys_head_p); axc_buf_free(bundle_p->signed_pre_key_public_serialized_p); axc_buf_free(bundle_p->signed_pre_key_signature_p); axc_buf_free(bundle_p->identity_key_public_serialized_p); free(bundle_p); } } void axc_default_log(int level, const char *message, size_t len, void *user_data) { (void) len; axc_context * ctx_p = (axc_context *) user_data; if (ctx_p->log_level >= AXC_LOG_ERROR) { switch(level) { case AXC_LOG_ERROR: fprintf(stderr, "[AXC ERROR] %s\n", message); break; case AXC_LOG_WARNING: if (ctx_p->log_level >= AXC_LOG_WARNING) { fprintf(stderr, "[AXC WARNING] %s\n", message); } break; case AXC_LOG_NOTICE: if (ctx_p->log_level >= AXC_LOG_NOTICE) { fprintf(stderr, "[AXC NOTICE] %s\n", message); } break; case AXC_LOG_INFO: if (ctx_p->log_level >= AXC_LOG_INFO) { fprintf(stdout, "[AXC INFO] %s\n", message); } break; case AXC_LOG_DEBUG: if (ctx_p->log_level >= AXC_LOG_DEBUG) { fprintf(stdout, "[AXC DEBUG] %s\n", message); } break; default: if (ctx_p->log_level > AXC_LOG_DEBUG) { fprintf(stderr, "[AXC %d] %s\n", level, message); } break; } } } void axc_log(axc_context * ctx_p, int level, const char * format, ...) { if(ctx_p->log_func) { va_list args; va_list args_cpy; va_copy(args_cpy, args); va_start(args, format); size_t len = vsnprintf((void *) 0, 0, format, args) + 1; va_end(args); char msg[len]; va_start(args_cpy, format); size_t final_len = vsnprintf(msg, len, format, args_cpy); va_end(args_cpy); if(final_len > 0) { ctx_p->log_func(level, msg, len, ctx_p); } } } int axc_mutexes_create_and_init(axc_mutexes ** mutexes_pp) { #ifndef NO_THREADS axc_mutexes * mutexes_p = malloc(sizeof(axc_mutexes)); if (!mutexes_p) { return -1; } memset(mutexes_p, 0, sizeof(axc_mutexes)); *mutexes_pp = mutexes_p; pthread_mutex_t * mutex_p = malloc(sizeof(pthread_mutex_t)); if (!mutex_p) { return -2; } mutexes_p->mutex_p = mutex_p; pthread_mutexattr_t * mutex_attr_p = malloc(sizeof(pthread_mutexattr_t)); if (!mutex_attr_p) { return -3; } mutexes_p->mutex_attr_p = mutex_attr_p; if (pthread_mutexattr_init(mutex_attr_p)) { return -4; } if (pthread_mutexattr_settype(mutex_attr_p, PTHREAD_MUTEX_RECURSIVE)) { return -5; } if (pthread_mutex_init(mutex_p, mutex_attr_p)) { return -6; } #else *mutexes_pp = (void *) 0; #endif return 0; } void axc_mutexes_destroy(axc_mutexes * mutexes_p) { #ifndef NO_THREADS if (mutexes_p) { if (mutexes_p->mutex_p) { pthread_mutex_destroy(mutexes_p->mutex_p); free(mutexes_p->mutex_p); } if (mutexes_p->mutex_attr_p) { pthread_mutexattr_destroy(mutexes_p->mutex_attr_p); free(mutexes_p->mutex_attr_p); } free(mutexes_p); } #else (void) mutexes_p; #endif } int axc_context_create(axc_context ** ctx_pp) { if (!ctx_pp) { return -1; } axc_context * ctx_p = (void *) 0; ctx_p = malloc(sizeof(axc_context)); if (!ctx_p) { return -2; } memset(ctx_p, 0, sizeof(axc_context)); ctx_p->log_level = -1; *ctx_pp = ctx_p; return 0; } int axc_context_set_db_fn(axc_context * ctx_p, char * filename, size_t fn_len) { char * db_fn = g_strndup(filename, fn_len); if (!db_fn) { return -1; } ctx_p->db_filename = db_fn; return 0; } char * axc_context_get_db_fn(axc_context * ctx_p) { if (ctx_p->db_filename) { return ctx_p->db_filename; } else { return AXC_DB_DEFAULT_FN; } } void axc_context_set_log_func(axc_context * ctx_p, void (*log_func)(int level, const char * message, size_t len, void * user_data)) { ctx_p->log_func = log_func; } void axc_context_set_log_level(axc_context * ctx_p, int level) { ctx_p->log_level = level; } int axc_context_get_log_level(axc_context * ctx_p) { return ctx_p->log_level; } signal_context * axc_context_get_axolotl_ctx(axc_context * ctx_p) { return ctx_p ? ctx_p->axolotl_global_context_p : (void *) 0; } void axc_context_destroy_all(axc_context * ctx_p) { if (ctx_p) { signal_context_destroy(ctx_p->axolotl_global_context_p); signal_protocol_store_context_destroy(ctx_p->axolotl_store_context_p); axc_mutexes_destroy(ctx_p->mutexes_p); free(ctx_p->db_filename); free(ctx_p); } } void recursive_mutex_lock(void * user_data) { #ifndef NO_THREADS axc_context * ctx_p = (axc_context *) user_data; pthread_mutex_lock(ctx_p->mutexes_p->mutex_p); #else (void) user_data; #endif } void recursive_mutex_unlock(void * user_data) { #ifndef NO_THREADS axc_context * ctx_p = (axc_context *) user_data; pthread_mutex_unlock(ctx_p->mutexes_p->mutex_p); #else (void) user_data; #endif } axc_buf * axc_buf_create(const uint8_t * data, size_t len) { return signal_buffer_create(data, len); } uint8_t * axc_buf_get_data(axc_buf * buf) { return signal_buffer_data(buf); } size_t axc_buf_get_len(axc_buf * buf) { return signal_buffer_len(buf); } void axc_buf_free(axc_buf * buf) { signal_buffer_bzero_free(buf); } int axc_init(axc_context * ctx_p) { axc_log(ctx_p, AXC_LOG_INFO, "%s: initializing axolotl client", __func__); char * err_msg = " "; int ret_val = 0; axc_mutexes * mutexes_p = (void *) 0; signal_protocol_store_context * store_context_p = (void *) 0; signal_protocol_session_store session_store = { .load_session_func = &axc_db_session_load, .get_sub_device_sessions_func = &axc_db_session_get_sub_device_sessions, .store_session_func = &axc_db_session_store, .contains_session_func = &axc_db_session_contains, .delete_session_func = &axc_db_session_delete, .delete_all_sessions_func = &axc_db_session_delete_all, .destroy_func = &axc_db_session_destroy_store_ctx, .user_data = ctx_p }; signal_protocol_pre_key_store pre_key_store = { .load_pre_key = &axc_db_pre_key_load, .store_pre_key = &axc_db_pre_key_store, .contains_pre_key = &axc_db_pre_key_contains, .remove_pre_key = &axc_db_pre_key_remove, .destroy_func = &axc_db_pre_key_destroy_ctx, .user_data = ctx_p }; signal_protocol_signed_pre_key_store signed_pre_key_store = { .load_signed_pre_key = &axc_db_signed_pre_key_load, .store_signed_pre_key = &axc_db_signed_pre_key_store, .contains_signed_pre_key = &axc_db_signed_pre_key_contains, .remove_signed_pre_key = &axc_db_signed_pre_key_remove, .destroy_func = &axc_db_signed_pre_key_destroy_ctx, .user_data = ctx_p }; signal_protocol_identity_key_store identity_key_store = { .get_identity_key_pair = &axc_db_identity_get_key_pair, .get_local_registration_id = &axc_db_identity_get_local_registration_id, .save_identity = &axc_db_identity_save, .is_trusted_identity = &axc_db_identity_always_trusted, .destroy_func = &axc_db_identity_destroy_ctx, .user_data = ctx_p }; // init mutexes ret_val = axc_mutexes_create_and_init(&mutexes_p); if (ret_val) { err_msg = "failed to create or init mutexes"; goto cleanup; } ctx_p->mutexes_p = mutexes_p; // axolotl lib init // 1. create global context if (signal_context_create(&(ctx_p->axolotl_global_context_p), ctx_p)) { err_msg = "failed to create global axolotl context"; ret_val = -1; goto cleanup; } axc_log(ctx_p, AXC_LOG_DEBUG, "%s: created and set axolotl context", __func__); // 2. init and set crypto provider signal_crypto_provider crypto_provider = { .random_func = random_bytes, .hmac_sha256_init_func = hmac_sha256_init, .hmac_sha256_update_func = hmac_sha256_update, .hmac_sha256_final_func = hmac_sha256_final, .hmac_sha256_cleanup_func = hmac_sha256_cleanup, .sha512_digest_init_func = sha512_digest_init, .sha512_digest_update_func = sha512_digest_update, .sha512_digest_final_func = sha512_digest_final, .sha512_digest_cleanup_func = sha512_digest_cleanup, .encrypt_func = aes_encrypt, .decrypt_func = aes_decrypt, .user_data = ctx_p }; if (signal_context_set_crypto_provider(ctx_p->axolotl_global_context_p, &crypto_provider)) { err_msg = "failed to set crypto provider"; ret_val = -1; goto cleanup; } axc_log(ctx_p, AXC_LOG_DEBUG, "%s: set axolotl crypto provider", __func__); // 3. set locking functions #ifndef NO_THREADS if (signal_context_set_locking_functions(ctx_p->axolotl_global_context_p, recursive_mutex_lock, recursive_mutex_unlock)) { err_msg = "failed to set locking functions"; ret_val = -1; goto cleanup; } axc_log(ctx_p, AXC_LOG_DEBUG, "%s: set locking functions", __func__); #endif // init store context if (signal_protocol_store_context_create(&store_context_p, ctx_p->axolotl_global_context_p)) { err_msg = "failed to create store context"; ret_val = -1; goto cleanup; } axc_log(ctx_p, AXC_LOG_DEBUG, "%s: created store context", __func__); if (signal_protocol_store_context_set_session_store(store_context_p, &session_store)) { err_msg = "failed to create session store"; ret_val = -1; goto cleanup; } if (signal_protocol_store_context_set_pre_key_store(store_context_p, &pre_key_store)) { err_msg = "failed to set pre key store"; ret_val = -1; goto cleanup; } if (signal_protocol_store_context_set_signed_pre_key_store(store_context_p, &signed_pre_key_store)) { err_msg = "failed to set signed pre key store"; ret_val = -1; goto cleanup; } if (signal_protocol_store_context_set_identity_key_store(store_context_p, &identity_key_store)) { err_msg = "failed to set identity key store"; ret_val = -1; goto cleanup; } ctx_p->axolotl_store_context_p = store_context_p; axc_log(ctx_p, AXC_LOG_DEBUG, "%s: set store context", __func__); cleanup: if (ret_val < 0) { //FIXME: this frees inited context, make this more fine-grained axc_cleanup(ctx_p); axc_log(ctx_p, AXC_LOG_ERROR, "%s: %s", __func__, err_msg); } else { axc_log(ctx_p, AXC_LOG_INFO, "%s: done initializing axc", __func__); } return ret_val; } void axc_cleanup(axc_context * ctx_p) { axc_context_destroy_all(ctx_p); } int axc_install(axc_context * ctx_p) { char * err_msg = ""; int ret_val = 0; int db_needs_init = 0; signal_context * global_context_p = ctx_p->axolotl_global_context_p; ratchet_identity_key_pair * identity_key_pair_p = (void *) 0; signal_protocol_key_helper_pre_key_list_node * pre_keys_head_p = (void *) 0; session_signed_pre_key * signed_pre_key_p = (void *) 0; signal_buffer * signed_pre_key_data_p = (void *) 0; uint32_t registration_id; axc_log(ctx_p, AXC_LOG_INFO, "%s: calling install-time functions", __func__); ret_val = axc_db_create(ctx_p); if (ret_val){ err_msg = "failed to create db"; goto cleanup; } axc_log(ctx_p, AXC_LOG_DEBUG, "%s: created db if it did not exist already", __func__); int init_status = AXC_DB_NOT_INITIALIZED; int db_needs_reset = 0; ret_val = axc_db_init_status_get(&init_status, ctx_p); switch (ret_val) { case -1: default: err_msg = "failed to read init status"; goto cleanup; break; case 0: // there is a value switch (init_status) { case AXC_DB_NOT_INITIALIZED: // init needed db_needs_init = 1; break; case AXC_DB_NEEDS_ROLLBACK: // reset and init needed db_needs_reset = 1; db_needs_init = 1; break; case AXC_DB_INITIALIZED: default: // the db is already initialised break; } break; case 1: // no value = not initialised -> init needed db_needs_init = 1; break; } if (db_needs_reset) { axc_log(ctx_p, AXC_LOG_DEBUG, "%s: db needs reset", __func__ ); ret_val = axc_db_destroy(ctx_p); if (ret_val) { err_msg = "failed to reset db"; goto cleanup; } ret_val = axc_db_create(ctx_p); if (ret_val) { err_msg = "failed to create db after reset"; goto cleanup; } } else { axc_log(ctx_p, AXC_LOG_DEBUG, "%s: db does not need reset", __func__ ); } if (db_needs_init) { axc_log(ctx_p, AXC_LOG_DEBUG, "%s: db needs init", __func__ ); axc_log(ctx_p, AXC_LOG_DEBUG, "%s: setting init status to AXC_DB_NEEDS_ROLLBACK (%i)", __func__, AXC_DB_NEEDS_ROLLBACK ); ret_val = axc_db_init_status_set(AXC_DB_NEEDS_ROLLBACK, ctx_p); if (ret_val) { err_msg = "failed to set init status to AXC_DB_NEEDS_ROLLBACK"; goto cleanup; } ret_val = signal_protocol_key_helper_generate_identity_key_pair(&identity_key_pair_p, global_context_p); if (ret_val) { err_msg = "failed to generate the identity key pair"; goto cleanup; } axc_log(ctx_p, AXC_LOG_DEBUG, "%s: generated identity key pair", __func__ ); ret_val = signal_protocol_key_helper_generate_registration_id(®istration_id, 1, global_context_p); if (ret_val) { err_msg = "failed to generate registration id"; goto cleanup; } axc_log(ctx_p, AXC_LOG_DEBUG, "%s: generated registration id: %i", __func__, registration_id); ret_val = signal_protocol_key_helper_generate_pre_keys(&pre_keys_head_p, 1, AXC_PRE_KEYS_AMOUNT, global_context_p); if(ret_val) { err_msg = "failed to generate pre keys"; goto cleanup; } axc_log(ctx_p, AXC_LOG_DEBUG, "%s: generated pre keys", __func__ ); ret_val = signal_protocol_key_helper_generate_signed_pre_key(&signed_pre_key_p, identity_key_pair_p, 0, g_get_real_time(), global_context_p); if (ret_val) { err_msg = "failed to generate signed pre key"; goto cleanup; } axc_log(ctx_p, AXC_LOG_DEBUG, "%s: generated signed pre key", __func__ ); ret_val = axc_db_identity_set_key_pair(identity_key_pair_p, ctx_p); if (ret_val) { err_msg = "failed to set identity key pair"; goto cleanup; } axc_log(ctx_p, AXC_LOG_DEBUG, "%s: saved identity key pair", __func__ ); ret_val = axc_db_identity_set_local_registration_id(registration_id, ctx_p); if (ret_val) { err_msg = "failed to set registration id"; goto cleanup; } axc_log(ctx_p, AXC_LOG_DEBUG, "%s: saved registration id", __func__ ); ret_val = axc_db_pre_key_store_list(pre_keys_head_p, ctx_p); if (ret_val) { err_msg = "failed to save pre key list"; goto cleanup; } axc_log(ctx_p, AXC_LOG_DEBUG, "%s: saved pre keys", __func__ ); ret_val = session_signed_pre_key_serialize(&signed_pre_key_data_p, signed_pre_key_p); if (ret_val) { err_msg = "failed to serialize signed pre key"; goto cleanup; } ret_val = axc_db_signed_pre_key_store(session_signed_pre_key_get_id(signed_pre_key_p), signal_buffer_data(signed_pre_key_data_p), signal_buffer_len(signed_pre_key_data_p), ctx_p); if (ret_val) { err_msg = "failed to save signed pre key"; goto cleanup; } axc_log(ctx_p, AXC_LOG_DEBUG, "%s: saved signed pre key", __func__ ); ret_val = axc_db_init_status_set(AXC_DB_INITIALIZED, ctx_p); if (ret_val) { err_msg = "failed to set init status to AXC_DB_INITIALIZED"; goto cleanup; } axc_log(ctx_p, AXC_LOG_DEBUG, "%s: initialised DB", __func__ ); } else { axc_log(ctx_p, AXC_LOG_DEBUG, "%s: db already initialized", __func__ ); } cleanup: if (ret_val < 0) { axc_log(ctx_p, AXC_LOG_ERROR, "%s: %s", __func__, err_msg); } if (db_needs_init) { SIGNAL_UNREF(identity_key_pair_p); signal_protocol_key_helper_key_list_free(pre_keys_head_p); SIGNAL_UNREF(signed_pre_key_p); signal_buffer_bzero_free(signed_pre_key_data_p); } return ret_val; } int axc_get_device_id(axc_context * ctx_p, uint32_t * id_p) { return signal_protocol_identity_get_local_registration_id(ctx_p->axolotl_store_context_p, id_p); } int axc_message_encrypt_and_serialize(axc_buf * msg_p, const axc_address * recipient_addr_p, axc_context * ctx_p, axc_buf ** ciphertext_pp) { char * err_msg = ""; int ret_val = 0; session_cipher * cipher_p = (void *) 0; ciphertext_message * cipher_msg_p = (void *) 0; signal_buffer * cipher_msg_data_p = (void *) 0; axc_buf * cipher_msg_data_cpy_p = (void *) 0; if (!ctx_p) { fprintf(stderr, "%s: axc ctx is null!\n", __func__); return -1; } if (!msg_p) { err_msg = "could not encrypt because msg pointer is null"; ret_val = -1; goto cleanup; } if (!recipient_addr_p) { err_msg = "could not encrypt because recipient addr pointer is null"; ret_val = -1; goto cleanup; } if (!ciphertext_pp) { err_msg = "could not encrypt because ciphertext pointer is null"; ret_val = -1; goto cleanup; } ret_val = session_cipher_create(&cipher_p, ctx_p->axolotl_store_context_p, recipient_addr_p, ctx_p->axolotl_global_context_p); if (ret_val) { err_msg = "failed to create session cipher"; goto cleanup; } ret_val = session_cipher_encrypt(cipher_p, axc_buf_get_data(msg_p), axc_buf_get_len(msg_p), &cipher_msg_p); if (ret_val) { err_msg = "failed to encrypt the message"; goto cleanup; } cipher_msg_data_p = ciphertext_message_get_serialized(cipher_msg_p); cipher_msg_data_cpy_p = signal_buffer_copy(cipher_msg_data_p); if (!cipher_msg_data_cpy_p) { err_msg = "failed to copy cipher msg data"; ret_val = -1; goto cleanup; } *ciphertext_pp = cipher_msg_data_cpy_p; cleanup: if (ret_val < 0) { axc_log(ctx_p, AXC_LOG_ERROR, "%s: %s", __func__, err_msg); axc_buf_free(cipher_msg_data_cpy_p); } session_cipher_free(cipher_p); SIGNAL_UNREF(cipher_msg_p); return ret_val; } int axc_message_decrypt_from_serialized (axc_buf * msg_p, axc_address * sender_addr_p, axc_context * ctx_p, axc_buf ** plaintext_pp) { char * err_msg = ""; int ret_val = 0; //TODO: add session_cipher_set_decryption_callback maybe? //FIXME: check message type signal_message * ciphertext_p = (void *) 0; session_cipher * cipher_p = (void *) 0; axc_buf * plaintext_buf_p = (void *) 0; if (!ctx_p) { fprintf(stderr, "%s: axc ctx is null!\n", __func__); return -1; } if (!msg_p) { err_msg = "could not decrypt because message pointer is null"; ret_val = -1; goto cleanup; } if (!sender_addr_p) { err_msg = "could not decrypt because sender address pointer is null"; ret_val = -1; goto cleanup; } if (!plaintext_pp) { err_msg = "could not decrypt because plaintext pointer is null"; ret_val = -1; goto cleanup; } ret_val = session_cipher_create(&cipher_p, ctx_p->axolotl_store_context_p, sender_addr_p, ctx_p->axolotl_global_context_p); if (ret_val) { err_msg = "failed to create session cipher"; goto cleanup; } ret_val = signal_message_deserialize(&ciphertext_p, axc_buf_get_data(msg_p), axc_buf_get_len(msg_p), ctx_p->axolotl_global_context_p); if (ret_val) { err_msg = "failed to deserialize whisper msg"; goto cleanup; } ret_val = session_cipher_decrypt_signal_message(cipher_p, ciphertext_p, (void *) 0, &plaintext_buf_p); if (ret_val) { err_msg = "failed to decrypt cipher message"; goto cleanup; } *plaintext_pp = plaintext_buf_p; cleanup: if (ret_val < 0) { axc_log(ctx_p, AXC_LOG_ERROR, "%s: %s", __func__, err_msg); } session_cipher_free(cipher_p); SIGNAL_UNREF(ciphertext_p); return ret_val; } int axc_session_exists_initiated(const axc_address * addr_p, axc_context * ctx_p) { int ret_val = 0; char * err_msg = ""; session_record * session_record_p = (void *) 0; session_state * session_state_p = (void *) 0; //TODO: if there was no response yet, even though it is an established session it keeps sending prekeymsgs // maybe that is "uninitiated" too? if(!signal_protocol_session_contains_session(ctx_p->axolotl_store_context_p, addr_p)) { return 0; } ret_val = signal_protocol_session_load_session(ctx_p->axolotl_store_context_p, &session_record_p, addr_p); if (ret_val){ err_msg = "database error when trying to retrieve session"; goto cleanup; } else { session_state_p = session_record_get_state(session_record_p); if (session_state_has_pending_key_exchange(session_state_p)) { err_msg = "session exists but has pending synchronous key exchange"; ret_val = 0; goto cleanup; } ret_val = 1; } cleanup: if (ret_val < 1) { axc_log(ctx_p, AXC_LOG_ERROR, "%s: %s", __func__, err_msg); } SIGNAL_UNREF(session_record_p); return ret_val; } /** * Checks if there exists a session for a user. * * @param name The username. * @param ctx_p Pointer to the axc context. * @return 0 if no session exists, 1 if at least one session exists, negative on error. */ int axc_session_exists_any(const char * name, axc_context * ctx_p) { int ret_val = 0; signal_int_list * sess_l_p = (void *) 0; ret_val = signal_protocol_session_get_sub_device_sessions(ctx_p->axolotl_store_context_p, &sess_l_p, name, strlen(name)); if (ret_val < 0) { goto cleanup; } ret_val = (signal_int_list_size(sess_l_p) > 0) ? 1 : 0; cleanup: signal_int_list_free(sess_l_p); return ret_val; } int axc_session_from_bundle(uint32_t pre_key_id, axc_buf * pre_key_public_serialized_p, uint32_t signed_pre_key_id, axc_buf * signed_pre_key_public_serialized_p, axc_buf * signed_pre_key_signature_p, axc_buf * identity_key_public_serialized_p, const axc_address * remote_address_p, axc_context * ctx_p) { char * err_msg = ""; int ret_val = 0; ec_public_key * pre_key_public_p = (void *) 0; ec_public_key * signed_pre_key_public_p = (void *) 0; ec_public_key * identity_key_public_p = (void *) 0; session_pre_key_bundle * bundle_p = (void *) 0; session_builder * session_builder_p = (void *) 0; ret_val = curve_decode_point(&pre_key_public_p, axc_buf_get_data(pre_key_public_serialized_p), axc_buf_get_len(pre_key_public_serialized_p), ctx_p->axolotl_global_context_p); if (ret_val) { err_msg = "failed to deserialize public pre key"; goto cleanup; } ret_val = curve_decode_point(&signed_pre_key_public_p, axc_buf_get_data(signed_pre_key_public_serialized_p), axc_buf_get_len(signed_pre_key_public_serialized_p), ctx_p->axolotl_global_context_p); if (ret_val) { err_msg = "failed to deserialize signed public pre key"; goto cleanup; } ret_val = curve_decode_point(&identity_key_public_p, axc_buf_get_data(identity_key_public_serialized_p), axc_buf_get_len(identity_key_public_serialized_p), ctx_p->axolotl_global_context_p); if (ret_val) { err_msg = "failed to deserialize public identity key"; goto cleanup; } ret_val = session_pre_key_bundle_create(&bundle_p, remote_address_p->device_id, remote_address_p->device_id, // this value is ignored pre_key_id, pre_key_public_p, signed_pre_key_id, signed_pre_key_public_p, axc_buf_get_data(signed_pre_key_signature_p), axc_buf_get_len(signed_pre_key_signature_p), identity_key_public_p); if (ret_val) { err_msg = "failed to assemble bundle"; goto cleanup; } ret_val = session_builder_create(&session_builder_p, ctx_p->axolotl_store_context_p, remote_address_p, ctx_p->axolotl_global_context_p); if (ret_val) { err_msg = "failed to create session builder"; goto cleanup; } ret_val = session_builder_process_pre_key_bundle(session_builder_p, bundle_p); if (ret_val) { err_msg = "failed to process pre key bundle"; goto cleanup; } cleanup: if (ret_val) { axc_log(ctx_p, AXC_LOG_ERROR, "%s: %s", __func__, err_msg); } SIGNAL_UNREF(pre_key_public_p); SIGNAL_UNREF(signed_pre_key_public_p); SIGNAL_UNREF(identity_key_public_p); SIGNAL_UNREF(bundle_p); session_builder_free(session_builder_p); return ret_val; } int axc_session_delete(const char * user, uint32_t device_id, axc_context * ctx_p) { int ret_val = 0; axc_address addr = {.name = user, .name_len = strlen(user), .device_id = device_id}; ret_val = signal_protocol_session_delete_session(ctx_p->axolotl_store_context_p, &addr); if (ret_val) { axc_log(ctx_p, AXC_LOG_ERROR, "%s: failed to delete session for %s:%i", __func__, user, device_id); } return ret_val; } int axc_pre_key_message_process(axc_buf * pre_key_msg_serialized_p, axc_address * remote_address_p, axc_context * ctx_p, axc_buf ** plaintext_pp) { char * err_msg = ""; int ret_val = 0; pre_key_signal_message * pre_key_msg_p = (void *) 0; uint32_t new_id = 0; session_cipher * session_cipher_p = (void *) 0; axc_buf * plaintext_p = (void *) 0; signal_protocol_key_helper_pre_key_list_node * key_l_p = (void *) 0; ret_val = pre_key_signal_message_deserialize(&pre_key_msg_p, axc_buf_get_data(pre_key_msg_serialized_p), axc_buf_get_len(pre_key_msg_serialized_p), ctx_p->axolotl_global_context_p); if (ret_val == SG_ERR_INVALID_PROTO_BUF) { err_msg = "not a pre key msg"; ret_val = AXC_ERR_NOT_A_PREKEY_MSG; goto cleanup; } else if (ret_val == SG_ERR_INVALID_KEY_ID) { ret_val = AXC_ERR_INVALID_KEY_ID; goto cleanup; } else if (ret_val) { err_msg = "failed to deserialize pre key message"; goto cleanup; } ret_val = axc_db_pre_key_get_max_id(ctx_p, &new_id); if (ret_val) { err_msg = "failed to retrieve max pre key id"; goto cleanup; } do { if (key_l_p) { signal_protocol_key_helper_key_list_free(key_l_p); key_l_p = NULL; } ret_val = signal_protocol_key_helper_generate_pre_keys(&key_l_p, new_id, 1, ctx_p->axolotl_global_context_p); if (ret_val) { err_msg = "failed to generate a new key"; goto cleanup; } new_id++; } while (signal_protocol_pre_key_contains_key(ctx_p->axolotl_store_context_p, session_pre_key_get_id(signal_protocol_key_helper_key_list_element(key_l_p)))); ret_val = session_cipher_create(&session_cipher_p, ctx_p->axolotl_store_context_p, remote_address_p, ctx_p->axolotl_global_context_p); if (ret_val) { err_msg = "failed to create session cipher"; goto cleanup; } //FIXME: find a way to retain the key (for MAM catchup) ret_val = session_cipher_decrypt_pre_key_signal_message(session_cipher_p, pre_key_msg_p, (void *) 0, &plaintext_p); if (ret_val) { err_msg = "failed to decrypt message"; goto cleanup; } ret_val = signal_protocol_pre_key_store_key(ctx_p->axolotl_store_context_p, signal_protocol_key_helper_key_list_element(key_l_p)); if (ret_val) { err_msg = "failed to store new key"; goto cleanup; } *plaintext_pp = plaintext_p; cleanup: if (ret_val < 0) { axc_log(ctx_p, AXC_LOG_ERROR, "%s: %s", __func__, err_msg); } SIGNAL_UNREF(pre_key_msg_p); session_cipher_free(session_cipher_p); signal_protocol_key_helper_key_list_free(key_l_p); return ret_val; } int axc_key_load_public_own(axc_context * ctx_p, axc_buf ** pubkey_data_pp) { char * err_msg = ""; int ret_val = 0; ratchet_identity_key_pair * kp_p = (void *) 0; axc_buf * key_data_p = (void *) 0; ret_val = signal_protocol_identity_get_key_pair(ctx_p->axolotl_store_context_p, &kp_p); if (ret_val) { err_msg = "failed to load identity key pair"; goto cleanup; } ret_val = ec_public_key_serialize(&key_data_p, ratchet_identity_key_pair_get_public(kp_p)); if (ret_val) { err_msg = "failed to serialize public identity key"; goto cleanup; } *pubkey_data_pp = key_data_p; cleanup: if (ret_val) { axc_log(ctx_p, AXC_LOG_ERROR, "%s: %s", __func__, err_msg); axc_buf_free(key_data_p); } SIGNAL_UNREF(kp_p); return ret_val; } int axc_key_load_public_addr(const char * name, uint32_t device_id, axc_context * ctx_p, axc_buf ** pubkey_data_pp) { char * err_msg = ""; int ret_val = 0; session_record * sr_p = (void *) 0; ec_public_key * pubkey_p = (void *) 0; axc_buf * key_data_p = (void *) 0; axc_address addr = {.name = name, .name_len = strlen(name), .device_id = device_id}; ret_val = signal_protocol_session_load_session(ctx_p->axolotl_store_context_p, &sr_p, &addr); if (ret_val) { err_msg = "failed to load session"; goto cleanup; } if (session_record_is_fresh(sr_p)) { goto cleanup; } ret_val = ec_public_key_serialize(&key_data_p, session_state_get_remote_identity_key(session_record_get_state(sr_p))); if (ret_val) { err_msg = "failed to serialize public key"; goto cleanup; } ret_val = 1; *pubkey_data_pp = key_data_p; cleanup: if (ret_val < 0) { axc_log(ctx_p, AXC_LOG_ERROR, "%s: %s", __func__, err_msg); axc_buf_free(key_data_p); } SIGNAL_UNREF(sr_p); SIGNAL_UNREF(pubkey_p); return ret_val; } axc-0.3.7/src/axc.h000066400000000000000000000225521417527735300140330ustar00rootroot00000000000000/* * Copyright (C) 2017-2020 Richard Bayerle * SPDX-License-Identifier: GPL-3.0-only * Author: Richard Bayerle */ #pragma once #include #include "signal_protocol.h" typedef struct axc_context axc_context; typedef struct axc_bundle axc_bundle; typedef struct axc_buf_list_item axc_buf_list_item; typedef signal_buffer axc_buf; typedef signal_protocol_address axc_address; #define AXC_LOG_ERROR 0 #define AXC_LOG_WARNING 1 #define AXC_LOG_NOTICE 2 #define AXC_LOG_INFO 3 #define AXC_LOG_DEBUG 4 #define AXC_ERR -10000 #define AXC_ERR_NOMEM -10001 #define AXC_ERR_NOT_A_PREKEY_MSG -10100 #define AXC_ERR_INVALID_KEY_ID -10200 #define AXC_DB_DEFAULT_FN "axc.sqlite" #define AXC_PRE_KEYS_AMOUNT 100 /** * Allocates the axc context. * * @param ctx_pp Will point to the created context. * @return 0 on success, negative on failure */ int axc_context_create(axc_context ** ctx_pp); /** * Sets the filename/location of the db. * Should be done after creating the context, but before calling axc_init(). * * @param ctx_p The fresh axc context. * @param filename The filename/path to be used. * @param fn_len Length of the filename. * @return 0 on success, negative on failure */ int axc_context_set_db_fn(axc_context * ctx_p, char * filename, size_t fn_len); /** * Returns the filename to be used for the database. * * @param ctx_p The axc context. * @return The filename set via axc_context_set_db_fn(), or AXC_DEFAULT_DB_FN if none was set. */ char * axc_context_get_db_fn(axc_context * ctx_p); void axc_context_set_log_func(axc_context * ctx_p, void (*log_func)(int level, const char * message, size_t len, void * user_data)); void axc_context_set_log_level(axc_context * ctx_p, int level); int axc_context_get_log_level(axc_context * ctx_p); void axc_context_destroy_all(axc_context * ctx_p); signal_context * axc_context_get_axolotl_ctx(axc_context * ctx_p); void axc_default_log(int level, const char *message, size_t len, void *user_data); void axc_log(axc_context * ctx_p, int level, const char * format, ...); int axc_buf_list_item_create(axc_buf_list_item ** item_pp, uint32_t * id_p, axc_buf * data_p); void axc_buf_list_item_set_next(axc_buf_list_item * item_p, axc_buf_list_item * next_p); axc_buf_list_item * axc_buf_list_item_get_next(axc_buf_list_item * item_p); uint32_t axc_buf_list_item_get_id(axc_buf_list_item * item_p); axc_buf * axc_buf_list_item_get_buf(axc_buf_list_item * item_p); void axc_buf_list_free(axc_buf_list_item * head_p); /** * Collects the info needed to publish a bundle. * * @param n Number of pre keys to get. * @param ctx_p Pointer to the initialized axc context. * @param bundle_pp Will be set to the bundle. * @return 0 on success, negative on error. */ int axc_bundle_collect(size_t n, axc_context * ctx_p, axc_bundle ** bundle_pp); uint32_t axc_bundle_get_reg_id(axc_bundle * bundle_p); axc_buf_list_item * axc_bundle_get_pre_key_list(axc_bundle * bundle_p); uint32_t axc_bundle_get_signed_pre_key_id(axc_bundle * bundle_p); axc_buf * axc_bundle_get_signed_pre_key(axc_bundle * bundle_p); axc_buf * axc_bundle_get_signature(axc_bundle * bundle_p); axc_buf * axc_bundle_get_identity_key(axc_bundle * bundle_p); void axc_bundle_destroy(axc_bundle * bundle_p); /** * Initializes the library. Has to be called at every startup. * * @param ctx_p A pointer to an already created axc context. * @return 0 on success, negative on failure */ int axc_init(axc_context * ctx_p); /** * Destroys mutexes and axolotl contexts saved in the axc context. * * @param ctx_p Pointer to the axc context as received from axc_init(). */ void axc_cleanup(axc_context * ctx_p); /** * "Installs" the library by creating the database and saving the necessary encryption keys into it. * Needs to be called once at the beginning, but can be called at every startup as it will not touch an initialized database. * * @param ctx_p Pointer to the axc context as received from axc_init(). * @return 0 on success, negative on failure */ int axc_install(axc_context * ctx_p); /** * Retrieves the local registration ID. * * @param ctx_p Pointer to an initialized and installed axc_context. * @param id_p Will be set to the ID. * @return 0 on success, negative on error. */ int axc_get_device_id(axc_context * ctx_p, uint32_t * id_p); axc_buf * axc_buf_create(const uint8_t * data, size_t len); uint8_t * axc_buf_get_data(axc_buf * buf); size_t axc_buf_get_len(axc_buf * buf); void axc_buf_free(axc_buf * buf); /** * Encrypts a message. Needs an established session, either synchronous or built from bundle. * The buffer containing the ciphertext has to be freed afterwards. * * If data is a string, include the null terminator in the data. * * @param msg_p The data to encrypt. * @param recipient_addr_p Address of the recipient. * @param ctx_p The axc context. * @param ciphertext_pp Will point to the serialized ciphertext afterwards. * @return 0 on success, negative on error. */ int axc_message_encrypt_and_serialize(axc_buf * msg_p, const axc_address * recipient_addr_p, axc_context * ctx_p, axc_buf ** ciphertext_pp); /** * Decrypts a received message. Needs an established session. * * As the null terminator should be included in the data bytes to be encrypted in case of a string, * the data of the axc_buf should also work as a string after decryption. * * @param msg_p The data to decrypt. * @param sender_addr_p Address of the sender. * @param ctx_p The axc context. * @param plaintext_pp Will point to the plaintext afterwards. Has to be freed. * @return 0 on success, negative on error. */ int axc_message_decrypt_from_serialized (axc_buf * msg_p, axc_address * sender_addr_p, axc_context * ctx_p, axc_buf ** plaintext_pp); /** * Checks if an initiated session exists (and no pending synchronous handshake). * * @param addr_p The address for which to check if a session exists. * @param ctx_p The axc context. * @return 1 if it exists, 0 if it does not, negative on error */ int axc_session_exists_initiated(const axc_address * addr_p, axc_context * ctx_p); /** * Checks if there exists a session for a user. * * @param name The username. * @param ctx_p Pointer to the axc context. * @return 1 if at least one session exists, 0 if no session exists, negative on error. */ int axc_session_exists_any(const char * name, axc_context * ctx_p); /** * Creates a session from a fetched bundle which can then instantly be used to encrypt a message. * * @param pre_key_id The ID of the used prekey. * @param pre_key_public_serialized_p Pointer to a buffer containing the serialized public part of the pre key pair. * @param signed_pre_key_id The ID of the signed prekey. * @param signed_pre_key_public_serialized_p Pointer to a buffer containing the serialized public part of the signed pre key pair. * @param signed_pre_key_signature_p Pointer to a buffer containing the signature data of the signed pre key. * @param identity_key_public_serialized_p Pointer to a buffer containing the serialized public part of the identity key pair. * @param remote_address_p Pointer to the address of the recipient. * @param ctx_p Pointer to the axc_context. * @return 0 on success, negative on error. */ int axc_session_from_bundle(uint32_t pre_key_id, axc_buf * pre_key_public_serialized_p, uint32_t signed_pre_key_id, axc_buf * signed_pre_key_public_serialized_p, axc_buf * signed_pre_key_signature_p, axc_buf * identity_key_public_serialized_p, const axc_address * remote_address_p, axc_context * ctx_p); /** * Deletes a session for a user:device combination. * * @param user Username. * @param device_id The device ID. * @param ctx_p Pointer to the axc context. * @return 0 on success, negative on error. */ int axc_session_delete(const char * user, uint32_t device_id, axc_context * ctx_p); /** * Creates a session from a received pre key message and uses it to decrypt the actual message body. * The ciphertext is decrypted here to avoid reserializing the message or having to deal with internal axolotl data structures. * * @param pre_key_msg_serialized_p Pointer to the buffer containing the serialized message. * @param remote_address_p Pointer to the remote (sender) address. * @param ctx_p Pointer to the axc context. * @param msg_pp Will contain a pointer to the decrypted plaintext. * @return 0 on success, negative on error */ int axc_pre_key_message_process(axc_buf * pre_key_msg_serialized_p, axc_address * remote_address_p, axc_context * ctx_p, axc_buf ** plaintext_pp); /** * Retrieves the own public identity key. * * @param ctx_p Pointer to the axc_context. * @param pubkey_data_pp Will point to an axc_buf * containing the serialized key data. * @return 0 on success, negative on error. */ int axc_key_load_public_own(axc_context * ctx_p, axc_buf ** pubkey_data_pp); /** * Retrieves the serialized public identity key for a user's device. * * @param name The user's name. * @param device_id The device's ID. * @param ctx_p Pointer to the axc_context. * @param pubkey_data_pp Will point to an axc_buf * which contains the data. * @return 1 if the key was loaded, 0 if no session exists, negative on error. */ int axc_key_load_public_addr(const char * name, uint32_t device_id, axc_context * ctx_p, axc_buf ** pubkey_data_pp); axc-0.3.7/src/axc_crypto.c000066400000000000000000000300771417527735300154270ustar00rootroot00000000000000/* * Copyright (C) 2017-2020 Richard Bayerle * SPDX-License-Identifier: GPL-3.0-only * Author: Richard Bayerle */ #include // int types #include // fprintf #include // malloc #include #include "signal_protocol.h" #include "axc.h" void axc_crypto_init(void) { (void) gcry_check_version((void *) 0); gcry_control(GCRYCTL_SUSPEND_SECMEM_WARN); gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0); gcry_control (GCRYCTL_RESUME_SECMEM_WARN); gcry_control(GCRYCTL_USE_SECURE_RNDPOOL); gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); } void axc_crypto_teardown(void) { } int random_bytes(uint8_t * data_p, size_t len, void * user_data_p) { axc_context * axc_ctx_p = (axc_context *) user_data_p; (void) axc_ctx_p; gcry_randomize(data_p, len, GCRY_STRONG_RANDOM); return SG_SUCCESS; } int hmac_sha256_init(void ** hmac_context_pp, const uint8_t * key_p, size_t key_len, void * user_data_p) { axc_context * axc_ctx_p = (axc_context *) user_data_p; int ret_val = 0; char * err_msg = (void *) 0; gcry_mac_hd_t * hmac_hd_p = (void *) 0; hmac_hd_p = malloc(sizeof(gcry_mac_hd_t)); if (!hmac_hd_p) { err_msg = "could not malloc hmac-sha256 ctx"; ret_val = SG_ERR_NOMEM; goto cleanup; } ret_val = gcry_mac_open(hmac_hd_p, GCRY_MAC_HMAC_SHA256, 0, (void *) 0); if (ret_val) { err_msg = "could not create hmac-sha256 ctx"; goto cleanup; } ret_val = gcry_mac_setkey(*hmac_hd_p, key_p, key_len); if (ret_val) { err_msg = "could not set key for hmac"; goto cleanup; } *hmac_context_pp = hmac_hd_p; cleanup: if (ret_val) { if (ret_val > 0) { axc_log(axc_ctx_p, AXC_LOG_ERROR, "%s: %s (%s: %s)\n", __func__, err_msg, gcry_strsource(ret_val), gcry_strerror(ret_val)); ret_val = SG_ERR_UNKNOWN; } else { axc_log(axc_ctx_p, AXC_LOG_ERROR, "%s: %s\n", __func__, err_msg); } if (hmac_hd_p) { gcry_mac_close(*hmac_hd_p); free(hmac_hd_p); } } return ret_val; } int hmac_sha256_update(void * hmac_context_p, const uint8_t * data_p, size_t data_len, void * user_data_p) { axc_context * axc_ctx_p = (axc_context *) user_data_p; (void) axc_ctx_p; gcry_mac_write(*((gcry_mac_hd_t *) hmac_context_p), data_p, data_len); return SG_SUCCESS; } int hmac_sha256_final(void * hmac_context_p, signal_buffer ** output_pp, void * user_data_p) { axc_context * axc_ctx_p = (axc_context *) user_data_p; int ret_val = 0; char * err_msg = (void *) 0; int algo = GCRY_MAC_HMAC_SHA256; size_t mac_len = 0; uint8_t * mac_data_p = (void *) 0; signal_buffer * out_buf_p = (void *) 0; mac_len = gcry_mac_get_algo_maclen(algo); mac_data_p = malloc(sizeof(uint8_t) * mac_len); if (!mac_data_p) { ret_val = SG_ERR_NOMEM; err_msg = "failed to malloc mac buf"; goto cleanup; } ret_val = gcry_mac_read(*((gcry_mac_hd_t *) hmac_context_p), mac_data_p, &mac_len); if (ret_val) { err_msg = "failed to read mac"; goto cleanup; } out_buf_p = signal_buffer_create(mac_data_p, mac_len); if (!out_buf_p) { ret_val = SG_ERR_NOMEM; err_msg = "failed to create mac output buf"; goto cleanup; } *output_pp = out_buf_p; cleanup: if (ret_val) { if (ret_val > 0) { axc_log(axc_ctx_p, AXC_LOG_ERROR, "%s: %s (%s: %s)\n", __func__, err_msg, gcry_strsource(ret_val), gcry_strerror(ret_val)); ret_val = SG_ERR_UNKNOWN; } else { axc_log(axc_ctx_p, AXC_LOG_ERROR, "%s: %s\n", __func__, err_msg); } } free(mac_data_p); return ret_val; } void hmac_sha256_cleanup(void * hmac_context_p, void * user_data_p) { (void) user_data_p; gcry_mac_hd_t * mac_hd_p = (gcry_mac_hd_t *) hmac_context_p; gcry_mac_close(*mac_hd_p); free(mac_hd_p); } int sha512_digest_init(void ** digest_context_pp, void * user_data_p) { axc_context * axc_ctx_p = (axc_context *) user_data_p; int ret_val = 0; char * err_msg = (void *) 0; gcry_md_hd_t * hash_hd_p = (void *) 0; hash_hd_p = malloc(sizeof(gcry_mac_hd_t)); if (!hash_hd_p) { err_msg = "could not malloc sha512 ctx"; ret_val = SG_ERR_NOMEM; goto cleanup; } ret_val = gcry_md_open(hash_hd_p, GCRY_MD_SHA512, 0); if (ret_val) { err_msg = "could not create sha512 ctx"; goto cleanup; } *digest_context_pp = hash_hd_p; cleanup: if (ret_val) { if (ret_val > 0) { axc_log(axc_ctx_p, AXC_LOG_ERROR, "%s: %s (%s: %s)\n", __func__, err_msg, gcry_strsource(ret_val), gcry_strerror(ret_val)); ret_val = SG_ERR_UNKNOWN; } else { axc_log(axc_ctx_p, AXC_LOG_ERROR, "%s: %s\n", __func__, err_msg); } if (hash_hd_p) { gcry_md_close(*hash_hd_p); free(hash_hd_p); } } return ret_val; } int sha512_digest_update(void * digest_context_p, const uint8_t * data_p, size_t data_len, void * user_data_p) { (void) user_data_p; gcry_md_write(*((gcry_md_hd_t *) digest_context_p), data_p, data_len); return 0; } int sha512_digest_final(void * digest_context_p, signal_buffer ** output_pp, void * user_data_p) { axc_context * axc_ctx_p = (axc_context *) user_data_p; gcry_md_hd_t * hash_hd_p = (gcry_md_hd_t *) digest_context_p; int ret_val = 0; char * err_msg = (void *) 0; int algo = GCRY_MD_SHA512; size_t hash_len = 0; unsigned char * hash_data_p = (void *) 0; signal_buffer * out_buf_p = (void *) 0; hash_len = gcry_md_get_algo_dlen(algo); hash_data_p = gcry_md_read(*hash_hd_p, algo); if (!hash_data_p) { ret_val = SG_ERR_UNKNOWN; err_msg = "failed to read hash"; goto cleanup; } out_buf_p = signal_buffer_create((uint8_t *) hash_data_p, hash_len); if (!out_buf_p) { ret_val = SG_ERR_NOMEM; err_msg = "failed to create hash output buf"; goto cleanup; } gcry_md_reset(*hash_hd_p); *output_pp = out_buf_p; cleanup: if (ret_val) { if (ret_val > 0) { axc_log(axc_ctx_p, AXC_LOG_ERROR, "%s: %s (%s: %s)\n", __func__, err_msg, gcry_strsource(ret_val), gcry_strerror(ret_val)); ret_val = SG_ERR_UNKNOWN; } else { axc_log(axc_ctx_p, AXC_LOG_ERROR, "%s: %s\n", __func__, err_msg); } } return ret_val; } void sha512_digest_cleanup(void * digest_context_p, void * user_data_p) { (void) user_data_p; gcry_md_hd_t * hash_hd_p = (gcry_md_hd_t *) digest_context_p; gcry_md_close(*hash_hd_p); free(hash_hd_p); } static int choose_aes(int cipher, size_t key_len, int * algo_p, int * mode_p) { int algo = 0; int mode = 0; switch(key_len) { case 16: algo = GCRY_CIPHER_AES128; break; case 24: algo = GCRY_CIPHER_AES192; break; case 32: algo = GCRY_CIPHER_AES256; break; default: return SG_ERR_UNKNOWN; } switch (cipher) { case SG_CIPHER_AES_CBC_PKCS5: mode = GCRY_CIPHER_MODE_CBC; break; case SG_CIPHER_AES_CTR_NOPADDING: mode = GCRY_CIPHER_MODE_CTR; break; default: return SG_ERR_UNKNOWN; } *algo_p = algo; *mode_p = mode; return 0; } int aes_encrypt(signal_buffer ** output_pp, int cipher, const uint8_t * key_p, size_t key_len, const uint8_t * iv_p, size_t iv_len, const uint8_t * plaintext_p, size_t plaintext_len, void * user_data_p) { int ret_val = SG_SUCCESS; char * err_msg = (void *) 0; axc_context * axc_ctx_p = (axc_context *) user_data_p; int algo = 0; int mode = 0; size_t pad_len = 0; size_t ct_len = 0; gcry_cipher_hd_t cipher_hd = {0}; uint8_t * pt_p = (void *) 0; uint8_t * out_p = (void *) 0; signal_buffer * out_buf_p = (void *) 0; if(iv_len != 16) { err_msg = "invalid AES IV size (must be 16)"; ret_val = SG_ERR_UNKNOWN; goto cleanup; } ret_val = choose_aes(cipher, key_len, &algo, &mode); if (ret_val) { err_msg = "failed to choose cipher"; ret_val = SG_ERR_UNKNOWN; goto cleanup; } ret_val = gcry_cipher_open(&cipher_hd, algo, mode, 0); if (ret_val) { err_msg = "failed to init cipher"; goto cleanup; } ret_val = gcry_cipher_setkey(cipher_hd, key_p, key_len); if (ret_val) { err_msg = "failed to set key"; goto cleanup; } switch (cipher) { case SG_CIPHER_AES_CBC_PKCS5: pad_len = 16 - (plaintext_len % 16); if (pad_len == 0) { pad_len = 16; } ct_len = plaintext_len + pad_len; ret_val = gcry_cipher_setiv(cipher_hd, iv_p, iv_len); if (ret_val) { err_msg = "failed to set iv"; goto cleanup; } break; case SG_CIPHER_AES_CTR_NOPADDING: ct_len = plaintext_len; ret_val = gcry_cipher_setctr(cipher_hd, iv_p, iv_len); if (ret_val) { err_msg = "failed to set iv"; goto cleanup; } break; default: ret_val = SG_ERR_UNKNOWN; err_msg = "unknown cipher"; goto cleanup; } pt_p = malloc(sizeof(uint8_t) * ct_len); if (!pt_p) { err_msg = "failed to malloc pt buf"; ret_val = SG_ERR_NOMEM; goto cleanup; } memset(pt_p, pad_len, ct_len); memcpy(pt_p, plaintext_p, plaintext_len); out_p = malloc(sizeof(uint8_t) * ct_len); if (!out_p) { err_msg = "failed to malloc ct buf"; ret_val = SG_ERR_NOMEM; goto cleanup; } ret_val = gcry_cipher_encrypt(cipher_hd, out_p, ct_len, pt_p, ct_len); if (ret_val) { err_msg = "failed to encrypt"; goto cleanup; } out_buf_p = signal_buffer_create(out_p, ct_len); *output_pp = out_buf_p; cleanup: if (ret_val) { if (ret_val > 0) { axc_log(axc_ctx_p, AXC_LOG_ERROR, "%s: %s (%s: %s)\n", __func__, err_msg, gcry_strsource(ret_val), gcry_strerror(ret_val)); ret_val = SG_ERR_UNKNOWN; } else { axc_log(axc_ctx_p, AXC_LOG_ERROR, "%s: %s\n", __func__, err_msg); } } free(pt_p); free(out_p); gcry_cipher_close(cipher_hd); return ret_val; } int aes_decrypt(signal_buffer ** output_pp, int cipher, const uint8_t * key_p, size_t key_len, const uint8_t * iv_p, size_t iv_len, const uint8_t * ciphertext_p, size_t ciphertext_len, void * user_data_p) { int ret_val = SG_SUCCESS; char * err_msg = (void *) 0; axc_context * axc_ctx_p = (axc_context *) user_data_p; int algo = 0; int mode = 0; gcry_cipher_hd_t cipher_hd = {0}; uint8_t * out_p = (void *) 0; size_t pad_len = 0; signal_buffer * out_buf_p = (void *) 0; if(iv_len != 16) { err_msg = "invalid AES IV size (must be 16)"; ret_val = SG_ERR_UNKNOWN; goto cleanup; } ret_val = choose_aes(cipher, key_len, &algo, &mode); if (ret_val) { err_msg = "failed to choose cipher"; ret_val = SG_ERR_UNKNOWN; goto cleanup; } ret_val = gcry_cipher_open(&cipher_hd, algo, mode, 0); if (ret_val) { err_msg = "failed to init cipher"; goto cleanup; } ret_val = gcry_cipher_setkey(cipher_hd, key_p, key_len); if (ret_val) { err_msg = "failed to set key"; goto cleanup; } switch (cipher) { case SG_CIPHER_AES_CBC_PKCS5: pad_len = 1; ret_val = gcry_cipher_setiv(cipher_hd, iv_p, iv_len); if (ret_val) { err_msg = "failed to set iv"; goto cleanup; } break; case SG_CIPHER_AES_CTR_NOPADDING: ret_val = gcry_cipher_setctr(cipher_hd, iv_p, iv_len); if (ret_val) { err_msg = "failed to set iv"; goto cleanup; } break; default: ret_val = SG_ERR_UNKNOWN; err_msg = "unknown cipher"; goto cleanup; } out_p = malloc(sizeof(uint8_t) * ciphertext_len); if (!out_p) { err_msg = "failed to malloc pt buf"; ret_val = SG_ERR_NOMEM; goto cleanup; } ret_val = gcry_cipher_decrypt(cipher_hd, out_p, ciphertext_len, ciphertext_p, ciphertext_len); if (ret_val) { err_msg = "failed to decrypt"; goto cleanup; } if (pad_len) { pad_len = out_p[ciphertext_len - 1]; } out_buf_p = signal_buffer_create(out_p, ciphertext_len - pad_len); *output_pp = out_buf_p; cleanup: if (ret_val) { if (ret_val > 0) { axc_log(axc_ctx_p, AXC_LOG_ERROR, "%s: %s (%s: %s)\n", __func__, err_msg, gcry_strsource(ret_val), gcry_strerror(ret_val)); ret_val = SG_ERR_UNKNOWN; } else { axc_log(axc_ctx_p, AXC_LOG_ERROR, "%s: %s\n", __func__, err_msg); } } free(out_p); gcry_cipher_close(cipher_hd); return ret_val; } axc-0.3.7/src/axc_crypto.h000066400000000000000000000030501417527735300154230ustar00rootroot00000000000000/* * Copyright (C) 2017-2020 Richard Bayerle * SPDX-License-Identifier: GPL-3.0-only * Author: Richard Bayerle */ #pragma once #include #include "signal_protocol.h" void axc_crypto_init(void); void axc_crypto_teardown(void); int random_bytes(uint8_t * data_p, size_t len, void * user_data_p); int hmac_sha256_init(void ** hmac_context_pp, const uint8_t * key_p, size_t key_len, void * user_data_p); int hmac_sha256_update(void * hmac_context_p, const uint8_t * data_p, size_t data_len, void * user_data_p); int hmac_sha256_final(void * hmac_context_p, signal_buffer ** output_pp, void * user_data_p); void hmac_sha256_cleanup(void * hmac_context_p, void * user_data_p); int sha512_digest_init(void ** digest_context_pp, void * user_data_p); int sha512_digest_update(void * digest_context_p, const uint8_t * data_p, size_t data_len, void * user_data_p); int sha512_digest_final(void * digest_context_p, signal_buffer ** output_pp, void * user_data_p); void sha512_digest_cleanup(void * digest_context_p, void * user_data_p); int aes_encrypt(signal_buffer ** output_pp, int cipher, const uint8_t * key_p, size_t key_len, const uint8_t * iv_p, size_t iv_len, const uint8_t * plaintext_p, size_t plaintext_len, void * user_data_p); int aes_decrypt(signal_buffer ** output_pp, int cipher, const uint8_t * key_p, size_t key_len, const uint8_t * iv_p, size_t iv_len, const uint8_t * ciphertext_p, size_t ciphertext_len, void * user_data_p); axc-0.3.7/src/axc_store.c000066400000000000000000001347741417527735300152540ustar00rootroot00000000000000/* * Copyright (C) 2017-2020 Richard Bayerle * SPDX-License-Identifier: GPL-3.0-only * Author: Richard Bayerle */ #include // int types #include // printf #include // exit #include // strlen #include "signal_protocol.h" #include "key_helper.h" #include #include "axc.h" #include "axc_store.h" #define INIT_STATUS_NAME "init_status" #define OWN_PUBLIC_KEY_NAME "own_public_key" #define OWN_PRIVATE_KEY_NAME "own_private_key" #define OWN_KEY 2 #define REG_ID_NAME "axolotl_registration_id" #define IDENTITY_KEY_TRUSTED 1 #define IDENTITY_KEY_UNTRUSTED 1 #define SESSION_STORE_TABLE_NAME "session_store" #define SESSION_STORE_NAME_NAME "name" #define SESSION_STORE_NAME_LEN_NAME "name_len" #define SESSION_STORE_DEVICE_ID_NAME "device_id" #define SESSION_STORE_RECORD_NAME "session_record" #define SESSION_STORE_RECORD_LEN_NAME "record_len" #define PRE_KEY_STORE_TABLE_NAME "pre_key_store" #define PRE_KEY_STORE_ID_NAME "id" #define PRE_KEY_STORE_RECORD_NAME "pre_key_record" #define PRE_KEY_STORE_RECORD_LEN_NAME "record_len" #define SIGNED_PRE_KEY_STORE_TABLE_NAME "signed_pre_key_store" #define SIGNED_PRE_KEY_STORE_ID_NAME "id" #define SIGNED_PRE_KEY_STORE_RECORD_NAME "signed_pre_key_record" #define SIGNED_PRE_KEY_STORE_RECORD_LEN_NAME "record_len" #define IDENTITY_KEY_STORE_TABLE_NAME "identity_key_store" #define IDENTITY_KEY_STORE_NAME_NAME "name" #define IDENTITY_KEY_STORE_KEY_NAME "key" #define IDENTITY_KEY_STORE_KEY_LEN_NAME "key_len" #define IDENTITY_KEY_STORE_TRUSTED_NAME "trusted" #define SETTINGS_STORE_TABLE_NAME "settings" #define SETTINGS_STORE_NAME_NAME "name" #define SETTINGS_STORE_PROPERTY_NAME "property" //TODO: clarify error return values //TODO: maybe change the db scheme to that there is a connection between clients and their keys (???) //TODO: maybe reimplement saving of own key by means of the save_identity function //FIXME: add option to cleanup function to see if it's a db error or not and change output accordingly /** * Logs the error message and closes the db connection. * If the error message is an empty string, only cleans up. * Both the database and statement can be NULL, then only the error message is logged. * * @param db_p Database connetion to close. * @param pstmt_p Prepared statement to finalize. * @param msg Error message to log. */ static void db_conn_cleanup(sqlite3 * db_p, sqlite3_stmt * pstmt_p, const char * err_msg, const char * func_name, axc_context * ctx_p) { if (err_msg) { axc_log(ctx_p, AXC_LOG_ERROR, "%s: %s (sqlite err: %s)\n", func_name, err_msg, sqlite3_errmsg(db_p)); } (void) sqlite3_finalize(pstmt_p); (void) sqlite3_close(db_p); } /** * Convenience function for opening a db "connection" and at the same time preparing a statement. * * @param db_pp Will be set to the db connection pointer. * @param pstmt_pp Will be set to the pointer of the prepared statement * @param stmt The SQL statement. * @param user_data_p Optional. The user_data as received from the axolotl interface, will be used to set the database name. * @return 0 on success, negative on failure */ static int db_conn_open(sqlite3 ** db_pp, sqlite3_stmt ** pstmt_pp, const char stmt[], void * user_data_p) { axc_context * axc_ctx_p = (axc_context *) user_data_p; int ret_val = 0; char * err_msg = (void *) 0; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; if (!stmt) { ret_val = -1; err_msg = "stmt is null"; goto cleanup; } ret_val = sqlite3_open(axc_context_get_db_fn(axc_ctx_p), &db_p); if (ret_val) { err_msg = "Failed to open db_p"; goto cleanup; } if (sqlite3_prepare_v2(db_p, stmt, -1, &pstmt_p, (void *) 0)) { ret_val = -2; err_msg = "Failed to prepare statement"; goto cleanup; } *db_pp = db_p; *pstmt_pp = pstmt_p; cleanup: if (ret_val) { db_conn_cleanup(db_p, (void *) 0, err_msg, __func__, axc_ctx_p); } return ret_val; } /** * Executes the sqlite_step() function once and checks if there was a corresponding change in the db. * Can be used for single insert or delete. * * @param pstmt_p Pointer to the completely prepared (i.e. including bound values) statement that finishes in one step. * @return 0 on success, negative on failure */ int db_exec_single_change(sqlite3 * db_p, sqlite3_stmt * pstmt_p, axc_context * axc_ctx_p) { if (sqlite3_step(pstmt_p) != SQLITE_DONE) { db_conn_cleanup(db_p, pstmt_p, "Failed to execute statement", __func__, axc_ctx_p); return -3; } int changes = sqlite3_changes(db_p); if (changes != 1) { db_conn_cleanup(db_p, pstmt_p, "less or more than 1 change", __func__, axc_ctx_p); return -3; } return 0; } /** * Uses the one-step query execution interface to execute the given statement. * Ignores any results or errors. * * @param stmt The SQL statement to execute. * @param user_data_p Optional. The user_data as received from the axolotl interface, will be used to set the database name. */ void db_exec_quick(const char stmt[], void * user_data_p) { axc_context * axc_ctx_p = (axc_context *) user_data_p; sqlite3 * db_p = (void *) 0; if (sqlite3_open(axc_context_get_db_fn(axc_ctx_p), &db_p)) { db_conn_cleanup(db_p, (void *) 0, "Failed to open db", __func__, axc_ctx_p); } sqlite3_exec(db_p, stmt, (void *) 0, (void *) 0, (void *) 0); db_conn_cleanup(db_p, (void *) 0, (void *) 0, __func__, axc_ctx_p); } int axc_db_create(axc_context * axc_ctx_p) { const char stmt[] = "BEGIN TRANSACTION;" "CREATE TABLE IF NOT EXISTS " SESSION_STORE_TABLE_NAME "(" SESSION_STORE_NAME_NAME " TEXT NOT NULL, " SESSION_STORE_NAME_LEN_NAME " INTEGER NOT NULL, " SESSION_STORE_DEVICE_ID_NAME " INTEGER NOT NULL, " SESSION_STORE_RECORD_NAME " BLOB NOT NULL, " SESSION_STORE_RECORD_LEN_NAME " INTEGER NOT NULL, " " PRIMARY KEY("SESSION_STORE_NAME_NAME", "SESSION_STORE_DEVICE_ID_NAME")); " "CREATE TABLE IF NOT EXISTS " PRE_KEY_STORE_TABLE_NAME "(" PRE_KEY_STORE_ID_NAME " INTEGER NOT NULL PRIMARY KEY, " PRE_KEY_STORE_RECORD_NAME " BLOB NOT NULL, " PRE_KEY_STORE_RECORD_LEN_NAME " INTEGER NOT NULL); " "CREATE TABLE IF NOT EXISTS " SIGNED_PRE_KEY_STORE_TABLE_NAME "(" SIGNED_PRE_KEY_STORE_ID_NAME " INTEGER NOT NULL PRIMARY KEY, " SIGNED_PRE_KEY_STORE_RECORD_NAME " BLOB NOT NULL, " SIGNED_PRE_KEY_STORE_RECORD_LEN_NAME " INTEGER NOT NULL);" "CREATE TABLE IF NOT EXISTS " IDENTITY_KEY_STORE_TABLE_NAME "(" IDENTITY_KEY_STORE_NAME_NAME " TEXT NOT NULL PRIMARY KEY, " IDENTITY_KEY_STORE_KEY_NAME " BLOB NOT NULL, " IDENTITY_KEY_STORE_KEY_LEN_NAME " INTEGER NOT NULL, " IDENTITY_KEY_STORE_TRUSTED_NAME " INTEGER NOT NULL);" "CREATE TABLE IF NOT EXISTS " SETTINGS_STORE_TABLE_NAME "(" SETTINGS_STORE_NAME_NAME " TEXT NOT NULL PRIMARY KEY, " SETTINGS_STORE_PROPERTY_NAME " INTEGER NOT NULL);" "COMMIT TRANSACTION;"; sqlite3 * db_p = (void *) 0; char * err_msg = (void *) 0; if (sqlite3_open(axc_context_get_db_fn(axc_ctx_p), &db_p)) { db_conn_cleanup(db_p, (void *) 0, "Failed to open db", __func__, axc_ctx_p); return -1; } sqlite3_exec(db_p, stmt, (void *) 0, (void *) 0, &err_msg); if (err_msg) { db_conn_cleanup(db_p, (void *) 0, err_msg, __func__, axc_ctx_p); sqlite3_free(err_msg); return -1; } db_conn_cleanup(db_p, (void *) 0, (void *) 0, __func__, axc_ctx_p); return 0; } /** * Drops all tables. * * @param axc_ctx_p Pointer to the axc context. */ int axc_db_destroy(axc_context * axc_ctx_p) { const char stmt[] = "BEGIN TRANSACTION;" "DROP TABLE IF EXISTS " SESSION_STORE_TABLE_NAME ";" "DROP TABLE IF EXISTS " PRE_KEY_STORE_TABLE_NAME ";" "DROP TABLE IF EXISTS " SIGNED_PRE_KEY_STORE_TABLE_NAME ";" "DROP TABLE IF EXISTS " IDENTITY_KEY_STORE_TABLE_NAME ";" "DROP TABLE IF EXISTS " SETTINGS_STORE_TABLE_NAME ";" "COMMIT TRANSACTION;"; sqlite3 * db_p = (void *) 0; char * err_msg = (void *) 0; if (sqlite3_open(axc_context_get_db_fn(axc_ctx_p), &db_p)) { db_conn_cleanup(db_p, (void *) 0, "Failed to open db", __func__, axc_ctx_p); return -1; } sqlite3_exec(db_p, stmt, (void *) 0, (void *) 0, &err_msg); if (err_msg) { db_conn_cleanup(db_p, (void *) 0, err_msg, __func__, axc_ctx_p); sqlite3_free(err_msg); return -1; } db_conn_cleanup(db_p, (void *) 0, (void *) 0, __func__, axc_ctx_p); return 0; } int axc_db_property_set(const char * name, const int val, axc_context * axc_ctx_p) { // 1 - name of property // 2 - value const char stmt[] = "INSERT OR REPLACE INTO " SETTINGS_STORE_TABLE_NAME " VALUES (?1, ?2);"; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; if (db_conn_open(&db_p, &pstmt_p, stmt, axc_ctx_p)) return -1; if (sqlite3_bind_text(pstmt_p, 1, name, -1, SQLITE_STATIC)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind", __func__, axc_ctx_p); return -21; } if (sqlite3_bind_int(pstmt_p, 2, val)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind", __func__, axc_ctx_p); return -22; } if (db_exec_single_change(db_p, pstmt_p, axc_ctx_p)) return -3; db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); return 0; } int axc_db_property_get(const char * name, int * val_p, axc_context * axc_ctx_p) { const char stmt[] = "SELECT * FROM " SETTINGS_STORE_TABLE_NAME " WHERE name IS ?1;"; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; if (db_conn_open(&db_p, &pstmt_p, stmt, axc_ctx_p)) return -1; if (sqlite3_bind_text(pstmt_p, 1, name, -1, SQLITE_STATIC)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind", __func__, axc_ctx_p); return -21; } const int step_result = sqlite3_step(pstmt_p); if (step_result == SQLITE_DONE) { db_conn_cleanup(db_p, pstmt_p, "Result not found", __func__, axc_ctx_p); return 1; } else if (step_result == SQLITE_ROW) { const int temp = sqlite3_column_int(pstmt_p, 1); // exactly one result if (sqlite3_step(pstmt_p) != SQLITE_DONE) { db_conn_cleanup(db_p, pstmt_p, "Too many results", __func__, axc_ctx_p); return -3; } db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); *val_p = temp; return 0; } else { db_conn_cleanup(db_p, pstmt_p, "Failed to execute statement", __func__, axc_ctx_p); return -3; } } int axc_db_init_status_set(const int status, axc_context * axc_ctx_p) { return axc_db_property_set(INIT_STATUS_NAME, status, axc_ctx_p); } int axc_db_init_status_get(int * init_status_p, axc_context * axc_ctx_p) { return axc_db_property_get(INIT_STATUS_NAME, init_status_p, axc_ctx_p); } // session store impl int axc_db_session_load(signal_buffer ** record, signal_buffer ** user_record, const signal_protocol_address * address, void * user_data) { const char stmt[] = "SELECT * FROM " SESSION_STORE_TABLE_NAME " WHERE " SESSION_STORE_NAME_NAME " IS ?1" " AND " SESSION_STORE_DEVICE_ID_NAME " IS ?2;"; (void) user_record; axc_context * axc_ctx_p = (axc_context *) user_data; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; if (db_conn_open(&db_p, &pstmt_p, stmt, user_data)) return -1; if (sqlite3_bind_text(pstmt_p, 1, address->name, -1, SQLITE_TRANSIENT)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind name when trying to load a session", __func__, axc_ctx_p); return -21; } if (sqlite3_bind_int(pstmt_p, 2, address->device_id)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind device_id when trying to load a session", __func__, axc_ctx_p); return -22; } int step_result = sqlite3_step(pstmt_p); if (step_result == SQLITE_DONE) { // session not found db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); return 0; } else if (step_result == SQLITE_ROW) { const int record_len = sqlite3_column_int(pstmt_p, 4); *record = signal_buffer_create(sqlite3_column_blob(pstmt_p, 3), record_len); if (*record == 0) { db_conn_cleanup(db_p, pstmt_p, "Buffer could not be initialised", __func__, axc_ctx_p); return -3; } } else { db_conn_cleanup(db_p, pstmt_p, "Failed executing SQL statement", __func__, axc_ctx_p); return -3; } db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); return 1; } int axc_db_session_get_sub_device_sessions(signal_int_list ** sessions, const char * name, size_t name_len, void * user_data) { const char stmt[] = "SELECT * FROM " SESSION_STORE_TABLE_NAME " WHERE " SESSION_STORE_NAME_NAME " IS ?1;"; axc_context * axc_ctx_p = (axc_context *) user_data; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; if (db_conn_open(&db_p, &pstmt_p, stmt, user_data)) return -1; signal_int_list * session_list_p = (void *) 0; char * err_msg = (void *) 0; int ret_val = 0; if (sqlite3_bind_text(pstmt_p, 1, name, -1, SQLITE_TRANSIENT)) { err_msg = "Failed to bind name when trying to find sub device sessions"; ret_val = -21; goto cleanup; } session_list_p = signal_int_list_alloc(); int step_result = sqlite3_step(pstmt_p); while (step_result == SQLITE_ROW) { signal_int_list_push_back(session_list_p, sqlite3_column_int(pstmt_p, 2)); step_result = sqlite3_step(pstmt_p); } if (step_result != SQLITE_DONE) { err_msg = "Error while retrieving result rows"; ret_val = -3; goto cleanup; } (void) name_len; *sessions = session_list_p; ret_val = signal_int_list_size(*sessions); cleanup: if (ret_val < 0) { if (session_list_p) { signal_int_list_free(session_list_p); } } db_conn_cleanup(db_p, pstmt_p, err_msg, __func__, axc_ctx_p); return ret_val; } int axc_db_session_store(const signal_protocol_address *address, uint8_t *record, size_t record_len, uint8_t *user_record, size_t user_record_len, void *user_data) { const char stmt[] = "INSERT OR REPLACE INTO " SESSION_STORE_TABLE_NAME " VALUES (:name, :name_len, :device_id, :session_record, :record_len);"; (void) user_record; (void) user_record_len; axc_context * axc_ctx_p = (axc_context *) user_data; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; if (db_conn_open(&db_p, &pstmt_p, stmt, user_data)) return -1; if(sqlite3_bind_text(pstmt_p, 1, address->name, -1, SQLITE_TRANSIENT)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind name when trying to store a session", __func__, axc_ctx_p); return -21; } if (sqlite3_bind_int(pstmt_p, 2, address->name_len)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind name length when trying to store a session", __func__, axc_ctx_p); return -22; } if (sqlite3_bind_int(pstmt_p, 3, address->device_id)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind device id when trying to store a session", __func__, axc_ctx_p); return -23; } if (sqlite3_bind_blob(pstmt_p, 4, record, record_len, SQLITE_TRANSIENT)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind record when trying to store a session", __func__, axc_ctx_p); return -24; } if (sqlite3_bind_int(pstmt_p, 5, record_len)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind record length when trying to store a session", __func__, axc_ctx_p); return -25; } if (db_exec_single_change(db_p, pstmt_p, axc_ctx_p)) return -3; db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); return 0; } int axc_db_session_contains(const signal_protocol_address * address, void * user_data) { const char stmt[] = "SELECT * FROM " SESSION_STORE_TABLE_NAME " WHERE " SESSION_STORE_NAME_NAME " IS ?1" " AND " SESSION_STORE_DEVICE_ID_NAME " IS ?2;"; axc_context * axc_ctx_p = (axc_context *) user_data; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; if (db_conn_open(&db_p, &pstmt_p, stmt, user_data)) return -1; if (sqlite3_bind_text(pstmt_p, 1, address->name, -1, SQLITE_TRANSIENT)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind name when checking if session exists", __func__, axc_ctx_p); return -21; } if (sqlite3_bind_int(pstmt_p, 2, address->device_id)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind device id when checking if session exists", __func__, axc_ctx_p); return -22; } int step_result = sqlite3_step(pstmt_p); if (step_result == SQLITE_DONE) { // no result db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); return 0; } else if (step_result == SQLITE_ROW) { // result exists db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); return 1; } else { db_conn_cleanup(db_p, pstmt_p, "Failed executing SQL statement", __func__, axc_ctx_p); return -3; } } int axc_db_session_delete(const signal_protocol_address * address, void * user_data) { const char stmt[] = "DELETE FROM " SESSION_STORE_TABLE_NAME " WHERE " SESSION_STORE_NAME_NAME " IS ?1" " AND " SESSION_STORE_DEVICE_ID_NAME " IS ?2;"; axc_context * axc_ctx_p = (axc_context *) user_data; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; if (db_conn_open(&db_p, &pstmt_p, stmt, user_data)) return -1; if (sqlite3_bind_text(pstmt_p, 1, address->name, -1, SQLITE_TRANSIENT)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind name when trying to delete session", __func__, axc_ctx_p); return -21; } if (sqlite3_bind_int(pstmt_p, 2, address->device_id)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind device id when trying to delete session", __func__, axc_ctx_p); return -22; } if (sqlite3_step(pstmt_p) == SQLITE_DONE) { if (sqlite3_changes(db_p)) { db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); return 1; } else { db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); return 0; } } else { db_conn_cleanup(db_p, pstmt_p, "Failed to delete session", __func__, axc_ctx_p); return -4; } } int axc_db_session_delete_all(const char * name, size_t name_len, void * user_data) { const char stmt[] = "DELETE FROM " SESSION_STORE_TABLE_NAME " WHERE " SESSION_STORE_NAME_NAME " IS ?1;"; axc_context * axc_ctx_p = (axc_context *) user_data; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; if (db_conn_open(&db_p, &pstmt_p, stmt, user_data)) return -1; if (sqlite3_bind_text(pstmt_p, 1, name, -1, SQLITE_TRANSIENT)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind name when trying to delete all sessions", __func__, axc_ctx_p); return -21; } if (sqlite3_step(pstmt_p) == SQLITE_DONE) { const int changes = sqlite3_changes(db_p); db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); return changes; } else { db_conn_cleanup(db_p, pstmt_p, "Failed to delete sessions", __func__, axc_ctx_p); return -4; } (void)name_len; } void axc_db_session_destroy_store_ctx(void * user_data) { (void) user_data; //const char stmt[] = "DELETE FROM session_store; VACUUM;"; //db_exec_quick(stmt, user_data); } // pre key store impl int axc_db_pre_key_load(signal_buffer ** record, uint32_t pre_key_id, void * user_data) { const char stmt[] = "SELECT * FROM " PRE_KEY_STORE_TABLE_NAME " WHERE " PRE_KEY_STORE_ID_NAME " IS ?1;"; axc_context * axc_ctx_p = (axc_context *) user_data; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; if (db_conn_open(&db_p, &pstmt_p, stmt, user_data)) return -1; if (sqlite3_bind_int(pstmt_p, 1, pre_key_id)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind", __func__, axc_ctx_p); return -21; } int step_result = sqlite3_step(pstmt_p); if (step_result == SQLITE_DONE) { // session not found db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); return SG_ERR_INVALID_KEY_ID; } else if (step_result == SQLITE_ROW) { const int record_len = sqlite3_column_int(pstmt_p, 2); *record = signal_buffer_create(sqlite3_column_blob(pstmt_p, 1), record_len); if (*record == 0) { db_conn_cleanup(db_p, pstmt_p, "Buffer could not be initialised", __func__, axc_ctx_p); return -3; } } else { db_conn_cleanup(db_p, pstmt_p, "Failed executing SQL statement", __func__, axc_ctx_p); return -3; } db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); return SG_SUCCESS; } int axc_db_pre_key_store(uint32_t pre_key_id, uint8_t * record, size_t record_len, void * user_data) { const char stmt[] = "INSERT OR REPLACE INTO " PRE_KEY_STORE_TABLE_NAME " VALUES (?1, ?2, ?3);"; axc_context * axc_ctx_p = (axc_context *) user_data; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; if (db_conn_open(&db_p, &pstmt_p, stmt, user_data)) return -1; if(sqlite3_bind_int(pstmt_p, 1, pre_key_id)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind", __func__, axc_ctx_p); return -21; } if (sqlite3_bind_blob(pstmt_p, 2, record, record_len, SQLITE_TRANSIENT)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind", __func__, axc_ctx_p); return -22; } if (sqlite3_bind_int(pstmt_p, 3, record_len)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind", __func__, axc_ctx_p); return -23; } if (db_exec_single_change(db_p, pstmt_p, axc_ctx_p)) return -3; db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); return 0; } int axc_db_pre_key_store_list(signal_protocol_key_helper_pre_key_list_node * pre_keys_head, axc_context * axc_ctx_p) { const char stmt_begin[] = "BEGIN TRANSACTION;"; const char stmt[] = "INSERT OR REPLACE INTO " PRE_KEY_STORE_TABLE_NAME " VALUES (?1, ?2, ?3);"; const char stmt_commit[] = "COMMIT TRANSACTION;"; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; signal_buffer * key_buf_p = (void *) 0; signal_protocol_key_helper_pre_key_list_node * pre_keys_curr_p = (void *) 0; session_pre_key * pre_key_p = (void *) 0; if (db_conn_open(&db_p, &pstmt_p, stmt_begin, axc_ctx_p)) return -1; if (sqlite3_step(pstmt_p) != SQLITE_DONE) { db_conn_cleanup(db_p, pstmt_p, "Failed to execute statement", __func__, axc_ctx_p); return -3; } sqlite3_finalize(pstmt_p); if (sqlite3_prepare_v2(db_p, stmt, -1, &pstmt_p, (void *) 0)) { db_conn_cleanup(db_p, pstmt_p, "Failed to prepare statement", __func__, axc_ctx_p); return -2; } pre_keys_curr_p = pre_keys_head; while (pre_keys_curr_p) { pre_key_p = signal_protocol_key_helper_key_list_element(pre_keys_curr_p); if (session_pre_key_serialize(&key_buf_p, pre_key_p)) { db_conn_cleanup(db_p, pstmt_p, "failed to serialize pre key", __func__, axc_ctx_p); return -1; } if(sqlite3_bind_int(pstmt_p, 1, session_pre_key_get_id(pre_key_p))) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind", __func__, axc_ctx_p); return -21; } if (sqlite3_bind_blob(pstmt_p, 2, signal_buffer_data(key_buf_p), signal_buffer_len(key_buf_p), SQLITE_TRANSIENT)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind", __func__, axc_ctx_p); return -22; } if (sqlite3_bind_int(pstmt_p, 3, signal_buffer_len(key_buf_p))) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind", __func__, axc_ctx_p); return -23; } if (sqlite3_step(pstmt_p) != SQLITE_DONE) { db_conn_cleanup(db_p, pstmt_p, "Failed to execute statement", __func__, axc_ctx_p); return -3; } signal_buffer_bzero_free(key_buf_p); sqlite3_reset(pstmt_p); sqlite3_clear_bindings(pstmt_p); pre_keys_curr_p = signal_protocol_key_helper_key_list_next(pre_keys_curr_p); } sqlite3_finalize(pstmt_p); if (sqlite3_prepare_v2(db_p, stmt_commit, -1, &pstmt_p, (void *) 0)) { db_conn_cleanup(db_p, pstmt_p, "Failed to prepare statement", __func__, axc_ctx_p); return -2; } if (sqlite3_step(pstmt_p) != SQLITE_DONE) { db_conn_cleanup(db_p, pstmt_p, "Failed to execute statement", __func__, axc_ctx_p); return -3; } db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); return 0; } int axc_db_pre_key_get_list(size_t amount, axc_context * axc_ctx_p, axc_buf_list_item ** list_head_pp) { const char stmt[] = "SELECT * FROM " PRE_KEY_STORE_TABLE_NAME " ORDER BY " PRE_KEY_STORE_ID_NAME " ASC LIMIT ?1;"; int ret_val = -1; char * err_msg = (void *) 0; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; axc_buf_list_item * head_p = (void *) 0; axc_buf_list_item * curr_p = (void *) 0; uint32_t key_id = 0; axc_buf * serialized_keypair_data_p = (void *) 0; size_t record_len = 0; session_pre_key * pre_key_p = (void *) 0; ec_key_pair * pre_key_pair_p = (void *) 0; ec_public_key * pre_key_public_p = (void *) 0; axc_buf * pre_key_public_serialized_p = (void *) 0; axc_buf_list_item * temp_item_p = (void *) 0; if (db_conn_open(&db_p, &pstmt_p, stmt, axc_ctx_p)) return -1; ret_val = sqlite3_bind_int(pstmt_p, 1, amount); if (ret_val) { err_msg = "failed to bind"; goto cleanup; } ret_val = axc_buf_list_item_create(&head_p, (void *) 0, (void *) 0); if (ret_val) { err_msg = "failed to create list"; goto cleanup; } curr_p = head_p; ret_val = sqlite3_step(pstmt_p); while (ret_val == SQLITE_ROW) { key_id = sqlite3_column_int(pstmt_p, 0); record_len = sqlite3_column_int(pstmt_p, 2); serialized_keypair_data_p = signal_buffer_create(sqlite3_column_blob(pstmt_p, 1), record_len); if (!serialized_keypair_data_p) { err_msg = "failed to initialize buffer"; ret_val = -3; goto cleanup; } ret_val = session_pre_key_deserialize(&pre_key_p, axc_buf_get_data(serialized_keypair_data_p), record_len, axc_context_get_axolotl_ctx(axc_ctx_p)); if (ret_val) { err_msg = "failed to deserialize keypair"; goto cleanup; } pre_key_pair_p = session_pre_key_get_key_pair(pre_key_p); pre_key_public_p = ec_key_pair_get_public(pre_key_pair_p); ret_val = ec_public_key_serialize(&pre_key_public_serialized_p, pre_key_public_p); if (ret_val) { err_msg = "failed to serialize public key"; goto cleanup; } ret_val = axc_buf_list_item_create(&temp_item_p, &key_id, pre_key_public_serialized_p); if (ret_val) { err_msg = "failed to create list item"; goto cleanup; } axc_buf_list_item_set_next(curr_p, temp_item_p); curr_p = axc_buf_list_item_get_next(curr_p); axc_buf_free(serialized_keypair_data_p); SIGNAL_UNREF(pre_key_p); pre_key_p = (void *) 0; ret_val = sqlite3_step(pstmt_p); } if (ret_val != SQLITE_DONE) { err_msg = "sql error when retrieving keys"; goto cleanup; } *list_head_pp = axc_buf_list_item_get_next(head_p); axc_buf_list_item_set_next(head_p, NULL); ret_val = 0; cleanup: if (ret_val) { axc_buf_free(serialized_keypair_data_p); SIGNAL_UNREF(pre_key_p); axc_buf_free(pre_key_public_serialized_p); } axc_buf_list_free(head_p); db_conn_cleanup(db_p, pstmt_p, err_msg, __func__, axc_ctx_p); return ret_val; } int axc_db_pre_key_contains(uint32_t pre_key_id, void * user_data) { const char stmt[] = "SELECT * FROM " PRE_KEY_STORE_TABLE_NAME " WHERE " PRE_KEY_STORE_ID_NAME " IS ?1;"; axc_context * axc_ctx_p = (axc_context *) user_data; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; if (db_conn_open(&db_p, &pstmt_p, stmt, user_data)) return -1; if (sqlite3_bind_int(pstmt_p, 1, pre_key_id)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind", __func__, axc_ctx_p); return -21; } int step_result = sqlite3_step(pstmt_p); if (step_result == SQLITE_DONE) { // no result db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); return 0; } else if (step_result == SQLITE_ROW) { // result exists db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); return 1; } else { db_conn_cleanup(db_p, pstmt_p, "Failed executing SQL statement", __func__, axc_ctx_p); return -3; } } int axc_db_pre_key_get_max_id(axc_context * axc_ctx_p, uint32_t * max_id_p) { const char * stmt = "SELECT MAX(" PRE_KEY_STORE_ID_NAME ") FROM " PRE_KEY_STORE_TABLE_NAME " WHERE " PRE_KEY_STORE_ID_NAME " IS NOT (" " SELECT MAX(" PRE_KEY_STORE_ID_NAME ") FROM " PRE_KEY_STORE_TABLE_NAME " );"; char * err_msg = (void *) 0; int ret_val = 0; uint32_t id = 0; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; if (db_conn_open(&db_p, &pstmt_p, stmt, axc_ctx_p)) return -1; ret_val = sqlite3_step(pstmt_p); if (ret_val == SQLITE_ROW) { id = sqlite3_column_int(pstmt_p, 0); if (!id) { err_msg = "db not initialized"; ret_val = -1; } else { *max_id_p = id; ret_val = 0; } } else { err_msg = "db error"; ret_val = -ret_val; } db_conn_cleanup(db_p, pstmt_p, err_msg, __func__, axc_ctx_p); return ret_val; } int axc_db_pre_key_get_count(axc_context * axc_ctx_p, size_t * count_p) { const char * stmt = "SELECT count(" PRE_KEY_STORE_ID_NAME") FROM " PRE_KEY_STORE_TABLE_NAME ";"; int ret_val = 0; char * err_msg = (void *) 0; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; if (db_conn_open(&db_p, &pstmt_p, stmt, axc_ctx_p)) return -1; ret_val = sqlite3_step(pstmt_p); if (ret_val != SQLITE_ROW) { err_msg = "count returned an error"; ret_val = -1; } else { *count_p = sqlite3_column_int(pstmt_p, 0); ret_val = 0; } db_conn_cleanup(db_p, pstmt_p, err_msg, __func__, axc_ctx_p); return ret_val; } int axc_db_pre_key_remove(uint32_t pre_key_id, void * user_data) { const char stmt[] = "DELETE FROM " PRE_KEY_STORE_TABLE_NAME " WHERE " PRE_KEY_STORE_ID_NAME " IS ?1;"; axc_context * axc_ctx_p = (axc_context *) user_data; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; if (db_conn_open(&db_p, &pstmt_p, stmt, user_data)) return -1; if (sqlite3_bind_int(pstmt_p, 1, pre_key_id)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind", __func__, axc_ctx_p); return -21; } if (sqlite3_step(pstmt_p) == SQLITE_DONE) { if (sqlite3_changes(db_p)) { db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); return 0; } else { db_conn_cleanup(db_p, pstmt_p, "Key does not exist", __func__, axc_ctx_p); return -4; } } else { db_conn_cleanup(db_p, pstmt_p, "Failed to delete session", __func__, axc_ctx_p); return -4; } } void axc_db_pre_key_destroy_ctx(void * user_data) { (void) user_data; //const char stmt[] = "DELETE FROM pre_key_store; VACUUM;"; //db_exec_quick(stmt, user_data); } // signed pre key store impl int axc_db_signed_pre_key_load(signal_buffer ** record, uint32_t signed_pre_key_id, void * user_data) { const char stmt[] = "SELECT * FROM " SIGNED_PRE_KEY_STORE_TABLE_NAME " WHERE " SIGNED_PRE_KEY_STORE_ID_NAME " IS ?1;"; axc_context * axc_ctx_p = (axc_context *) user_data; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; if (db_conn_open(&db_p, &pstmt_p, stmt, user_data)) return -1; if (sqlite3_bind_int(pstmt_p, 1, signed_pre_key_id)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind", __func__, axc_ctx_p); return -21; } int step_result = sqlite3_step(pstmt_p); if (step_result == SQLITE_DONE) { // session not found db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); return SG_ERR_INVALID_KEY_ID; } else if (step_result == SQLITE_ROW) { const int record_len = sqlite3_column_int(pstmt_p, 2); *record = signal_buffer_create(sqlite3_column_blob(pstmt_p, 1), record_len); if (*record == 0) { db_conn_cleanup(db_p, pstmt_p, "Buffer could not be initialised", __func__, axc_ctx_p); return -3; } } else { db_conn_cleanup(db_p, pstmt_p, "Failed executing SQL statement", __func__, axc_ctx_p); return -3; } db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); return SG_SUCCESS; } int axc_db_signed_pre_key_store(uint32_t signed_pre_key_id, uint8_t * record, size_t record_len, void * user_data) { const char stmt[] = "INSERT OR REPLACE INTO " SIGNED_PRE_KEY_STORE_TABLE_NAME " VALUES (?1, ?2, ?3);"; axc_context * axc_ctx_p = (axc_context *) user_data; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; if (db_conn_open(&db_p, &pstmt_p, stmt, user_data)) return -1; if(sqlite3_bind_int(pstmt_p, 1, signed_pre_key_id)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind", __func__, axc_ctx_p); return -21; } if (sqlite3_bind_blob(pstmt_p, 2, record, record_len, SQLITE_TRANSIENT)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind", __func__, axc_ctx_p); return -22; } if (sqlite3_bind_int(pstmt_p, 3, record_len)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind", __func__, axc_ctx_p); return -23; } if (db_exec_single_change(db_p, pstmt_p, axc_ctx_p)) return -3; db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); return 0; } int axc_db_signed_pre_key_contains(uint32_t signed_pre_key_id, void * user_data) { const char stmt[] = "SELECT * FROM " SIGNED_PRE_KEY_STORE_TABLE_NAME " WHERE " SIGNED_PRE_KEY_STORE_ID_NAME " IS ?1;"; axc_context * axc_ctx_p = (axc_context *) user_data; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; if (db_conn_open(&db_p, &pstmt_p, stmt, user_data)) return -1; if (sqlite3_bind_int(pstmt_p, 1, signed_pre_key_id)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind", __func__, axc_ctx_p); return -21; } int step_result = sqlite3_step(pstmt_p); if (step_result == SQLITE_DONE) { // no result db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); return 0; } else if (step_result == SQLITE_ROW) { // result exists db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); return 1; } else { db_conn_cleanup(db_p, pstmt_p, "Failed executing SQL statement", __func__, axc_ctx_p); return -3; } } int axc_db_signed_pre_key_remove(uint32_t signed_pre_key_id, void * user_data) { const char stmt[] = "DELETE FROM " SIGNED_PRE_KEY_STORE_TABLE_NAME " WHERE " SIGNED_PRE_KEY_STORE_ID_NAME " IS ?1;"; axc_context * axc_ctx_p = (axc_context *) user_data; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; if (db_conn_open(&db_p, &pstmt_p, stmt, user_data)) return -1; if (sqlite3_bind_int(pstmt_p, 1, signed_pre_key_id)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind", __func__, axc_ctx_p); return -21; } if (sqlite3_step(pstmt_p) == SQLITE_DONE) { if (sqlite3_changes(db_p)) { db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); return 0; } else { db_conn_cleanup(db_p, pstmt_p, "Key does not exist", __func__, axc_ctx_p); return -4; } } else { db_conn_cleanup(db_p, pstmt_p, "Failed to delete session", __func__, axc_ctx_p); return -4; } } void axc_db_signed_pre_key_destroy_ctx(void * user_data) { (void) user_data; //const char stmt[] = "DELETE FROM signed_pre_key_store; VACUUM;"; //db_exec_quick(stmt, user_data); } // identity key store impl /** * saves the public and private key by using the api serialization calls, as this format (and not the higher-level key type) is needed by the getter. */ int axc_db_identity_set_key_pair(const ratchet_identity_key_pair * key_pair_p, axc_context * axc_ctx_p) { // 1 - name ("public" or "private") // 2 - key blob // 3 - length of the key // 4 - trusted (1 for true, 0 for false) const char stmt[] = "INSERT INTO " IDENTITY_KEY_STORE_TABLE_NAME " VALUES (?1, ?2, ?3, ?4);"; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; char * err_msg = (void *) 0; int ret_val = 0; signal_buffer * pubkey_buf_p = (void *) 0; signal_buffer * privkey_buf_p = (void *) 0; size_t pubkey_buf_len = 0; uint8_t * pubkey_buf_data_p = (void *) 0; size_t privkey_buf_len = 0; uint8_t * privkey_buf_data_p = (void *) 0; if (db_conn_open(&db_p, &pstmt_p, stmt, axc_ctx_p)) return -1; // public key if (sqlite3_bind_text(pstmt_p, 1, OWN_PUBLIC_KEY_NAME, -1, SQLITE_STATIC)) { err_msg = "Failed to bind"; ret_val = -21; goto cleanup; } if (ec_public_key_serialize(&pubkey_buf_p, ratchet_identity_key_pair_get_public(key_pair_p))) { err_msg = "Failed to allocate memory to serialize the public key"; ret_val = SG_ERR_NOMEM; goto cleanup; } pubkey_buf_len = signal_buffer_len(pubkey_buf_p); pubkey_buf_data_p = signal_buffer_data(pubkey_buf_p); if (sqlite3_bind_blob(pstmt_p, 2, pubkey_buf_data_p, pubkey_buf_len, SQLITE_TRANSIENT)) { err_msg = "Failed to bind"; ret_val = -22; goto cleanup; } if(sqlite3_bind_int(pstmt_p, 3, pubkey_buf_len)) { err_msg = "Failed to bind"; ret_val = -23; goto cleanup; } if (sqlite3_bind_int(pstmt_p, 4, OWN_KEY)) { err_msg = "Failed to bind"; ret_val = -24; goto cleanup; } if (sqlite3_step(pstmt_p) != SQLITE_DONE) { err_msg = "Failed to execute statement"; ret_val = -3; goto cleanup; } if (sqlite3_changes(db_p) != 1) { err_msg = "Failed to insert"; ret_val = -3; goto cleanup; } // private key if (sqlite3_reset(pstmt_p)) { err_msg = "Failed to reset prepared statement"; ret_val = -2; goto cleanup; } sqlite3_clear_bindings(pstmt_p); if (sqlite3_bind_text(pstmt_p, 1, OWN_PRIVATE_KEY_NAME, -1, SQLITE_STATIC)) { err_msg = "Failed to bind"; ret_val = -21; goto cleanup; } if (ec_private_key_serialize(&privkey_buf_p, ratchet_identity_key_pair_get_private(key_pair_p))) { err_msg = "Failed to allocate memory to serialize the private key"; ret_val = SG_ERR_NOMEM; goto cleanup; } privkey_buf_len = signal_buffer_len(privkey_buf_p); privkey_buf_data_p = signal_buffer_data(privkey_buf_p); if (sqlite3_bind_blob(pstmt_p, 2, privkey_buf_data_p, privkey_buf_len, SQLITE_TRANSIENT)) { err_msg = "Failed to bind"; ret_val = -22; goto cleanup; } if(sqlite3_bind_int(pstmt_p, 3, privkey_buf_len)) { err_msg = "Failed to bind"; ret_val = -23; goto cleanup; } if (sqlite3_bind_int(pstmt_p, 4, OWN_KEY)) { err_msg = "Failed to bind"; ret_val = -24; goto cleanup; } if (sqlite3_step(pstmt_p) != SQLITE_DONE) { err_msg = "Failed to execute statement"; ret_val = -3; goto cleanup; } if (sqlite3_changes(db_p) != 1) { err_msg = "Failed to insert"; ret_val = -3; goto cleanup; } cleanup: if (pubkey_buf_p) { signal_buffer_bzero_free(pubkey_buf_p); } if (privkey_buf_p) { signal_buffer_bzero_free(privkey_buf_p); } db_conn_cleanup(db_p, pstmt_p, err_msg, __func__, axc_ctx_p); return ret_val; } int axc_db_identity_get_key_pair(signal_buffer ** public_data, signal_buffer ** private_data, void * user_data) { const char stmt[] = "SELECT * FROM " IDENTITY_KEY_STORE_TABLE_NAME " WHERE " IDENTITY_KEY_STORE_NAME_NAME " IS ?1;"; axc_context * axc_ctx_p = (axc_context *) user_data; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; if (db_conn_open(&db_p, &pstmt_p, stmt, user_data)) return -1; char * err_msg = (void *) 0; int ret_val = 0; signal_buffer * pubkey_buf_p = (void *) 0; signal_buffer * privkey_buf_p = (void *) 0; // public key if (sqlite3_bind_text(pstmt_p, 1, OWN_PUBLIC_KEY_NAME, -1, SQLITE_STATIC)) { err_msg = "Failed to bind public key name when trying to get the identity key pair"; ret_val = -21; goto cleanup; } size_t pubkey_len = 0; int step_result = sqlite3_step(pstmt_p); if (step_result == SQLITE_DONE) { // public key not found err_msg = "Own public key not found"; ret_val = SG_ERR_INVALID_KEY_ID; goto cleanup; } else if (step_result == SQLITE_ROW) { pubkey_len = sqlite3_column_int(pstmt_p, 2); pubkey_buf_p = signal_buffer_create(sqlite3_column_blob(pstmt_p, 1), pubkey_len); if (pubkey_buf_p == 0) { err_msg = "Buffer could not be initialised"; ret_val = -3; goto cleanup; } } else { err_msg = "Failed executing SQL statement"; ret_val = -3; goto cleanup; } sqlite3_reset(pstmt_p); sqlite3_clear_bindings(pstmt_p); // private key if (sqlite3_bind_text(pstmt_p, 1, OWN_PRIVATE_KEY_NAME, -1, SQLITE_STATIC)) { err_msg = "Failed to bind private key name when trying to get the identity key pair"; ret_val = -21; goto cleanup; } size_t privkey_len = 0; step_result = sqlite3_step(pstmt_p); if (step_result == SQLITE_DONE) { // private key not found err_msg = "Own private key not found"; ret_val = SG_ERR_INVALID_KEY_ID; goto cleanup; } else if (step_result == SQLITE_ROW) { privkey_len = sqlite3_column_int(pstmt_p, 2); privkey_buf_p = signal_buffer_create(sqlite3_column_blob(pstmt_p, 1), privkey_len); if (privkey_buf_p == 0) { err_msg = "Buffer could not be initialised"; ret_val = -3; goto cleanup; } } else { err_msg = "Failed executing SQL statement"; ret_val = -3; goto cleanup; } *public_data = pubkey_buf_p; *private_data = privkey_buf_p; cleanup: if (ret_val < 0) { if (pubkey_buf_p) { signal_buffer_bzero_free(pubkey_buf_p); } if (privkey_buf_p) { signal_buffer_bzero_free(privkey_buf_p); } } db_conn_cleanup(db_p, pstmt_p, err_msg, __func__, axc_ctx_p); return ret_val; } int axc_db_identity_set_local_registration_id(const uint32_t reg_id, axc_context * axc_ctx_p) { return (axc_db_property_set(REG_ID_NAME, reg_id, axc_ctx_p)) ? -1 : 0; } int axc_db_identity_get_local_registration_id(void * user_data, uint32_t * registration_id) { const char stmt[] = "SELECT * FROM " SETTINGS_STORE_TABLE_NAME " WHERE " SETTINGS_STORE_NAME_NAME " IS ?1;"; axc_context * axc_ctx_p = (axc_context *) user_data; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; if (db_conn_open(&db_p, &pstmt_p, stmt, user_data)) return -1; if (sqlite3_bind_text(pstmt_p, 1, REG_ID_NAME, -1, SQLITE_STATIC)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind", __func__, axc_ctx_p); return -21; } const int step_result = sqlite3_step(pstmt_p); if (step_result == SQLITE_DONE) { // registration ID not found db_conn_cleanup(db_p, pstmt_p, "Own registration ID not found", __func__, axc_ctx_p); return -31; } else if (step_result == SQLITE_ROW) { *registration_id = sqlite3_column_int(pstmt_p, 1); } else { db_conn_cleanup(db_p, pstmt_p, "Failed executing SQL statement", __func__, axc_ctx_p); return -32; } db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); return 0; } int axc_db_identity_save(const signal_protocol_address * addr_p, uint8_t * key_data, size_t key_len, void * user_data) { // 1 - name ("public" or "private" for own keys, name for contacts) // 2 - key blob // 3 - length of the key // 4 - trusted (1 for true, 0 for false) char save_stmt[] = "INSERT OR REPLACE INTO " IDENTITY_KEY_STORE_TABLE_NAME " VALUES (?1, ?2, ?3, ?4);"; char del_stmt[] = "DELETE FROM " IDENTITY_KEY_STORE_TABLE_NAME " WHERE " IDENTITY_KEY_STORE_NAME_NAME " IS ?1;"; char * stmt = (void *) 0; if (key_data) { stmt = save_stmt; } else { stmt = del_stmt; } axc_context * axc_ctx_p = (axc_context *) user_data; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; if (db_conn_open(&db_p, &pstmt_p, stmt, user_data)) return -1; if (sqlite3_bind_text(pstmt_p, 1, addr_p->name, -1, SQLITE_TRANSIENT)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind", __func__, axc_ctx_p); return -21; } if (key_data) { if (sqlite3_bind_blob(pstmt_p, 2, key_data, key_len, SQLITE_TRANSIENT)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind", __func__, axc_ctx_p); return -22; } if(sqlite3_bind_int(pstmt_p, 3, key_len)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind", __func__, axc_ctx_p); return -23; } if(sqlite3_bind_int(pstmt_p, 4, IDENTITY_KEY_TRUSTED)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind", __func__, axc_ctx_p); return -24; } } if (db_exec_single_change(db_p, pstmt_p, axc_ctx_p)) return -3; db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); return 0; } int axc_db_identity_is_trusted(const char * name, size_t name_len, uint8_t * key_data, size_t key_len, void * user_data) { const char stmt[] = "SELECT * FROM " IDENTITY_KEY_STORE_TABLE_NAME " WHERE " IDENTITY_KEY_STORE_NAME_NAME " IS ?1;"; axc_context * axc_ctx_p = (axc_context *) user_data; sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; signal_buffer * key_record = (void *) 0; int step_result = 0; size_t record_len = 0; if (db_conn_open(&db_p, &pstmt_p, stmt, user_data)) return -1; if (sqlite3_bind_text(pstmt_p, 1, name, -1, SQLITE_TRANSIENT)) { db_conn_cleanup(db_p, pstmt_p, "Failed to bind", __func__, axc_ctx_p); return -21; } step_result = sqlite3_step(pstmt_p); if (step_result == SQLITE_DONE) { // no entry = trusted, according to docs db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); return 1; } else if (step_result == SQLITE_ROW) { // theoretically could be checked if trusted or not but it's TOFU record_len = sqlite3_column_int(pstmt_p, 2); if (record_len != key_len) { db_conn_cleanup(db_p, pstmt_p, "Key length does not match", __func__, axc_ctx_p); return 0; } key_record = signal_buffer_create(sqlite3_column_blob(pstmt_p, 1), record_len); if (key_record == 0) { db_conn_cleanup(db_p, pstmt_p, "Buffer could not be initialised", __func__, axc_ctx_p); return -3; } if (memcmp(key_data, signal_buffer_data(key_record), key_len)) { db_conn_cleanup(db_p, pstmt_p, "Key data does not match", __func__, axc_ctx_p); } db_conn_cleanup(db_p, pstmt_p, (void *) 0, __func__, axc_ctx_p); signal_buffer_bzero_free(key_record); return 1; } else { db_conn_cleanup(db_p, pstmt_p, "Failed executing SQL statement", __func__, axc_ctx_p); return -32; } (void)name_len; } int axc_db_identity_always_trusted(const signal_protocol_address * addr_p, uint8_t * key_data, size_t key_len, void * user_data) { (void) addr_p; (void) key_data; (void) key_len; (void) user_data; return 1; } void axc_db_identity_destroy_ctx(void * user_data) { (void) user_data; //const char stmt[] = "DELETE FROM identity_key_store; VACUUM;"; //db_exec_quick(stmt, user_data); } axc-0.3.7/src/axc_store.h000066400000000000000000000153251417527735300152470ustar00rootroot00000000000000/* * Copyright (C) 2017-2020 Richard Bayerle * SPDX-License-Identifier: GPL-3.0-only * Author: Richard Bayerle */ #pragma once #include "signal_protocol.h" #include "key_helper.h" #include "axc.h" // For docs see signal_protocol.h // Function signatures implementing their interfaces intentionally left in their code style. #define AXC_DB_NOT_INITIALIZED (-1) #define AXC_DB_NEEDS_ROLLBACK 0 #define AXC_DB_INITIALIZED 1 // session store int axc_db_session_load(signal_buffer **record, signal_buffer **user_record, const signal_protocol_address *address, void *user_data); int axc_db_session_get_sub_device_sessions(signal_int_list **sessions, const char *name, size_t name_len, void *user_data); int axc_db_session_store(const signal_protocol_address *address, uint8_t *record, size_t record_len, uint8_t *user_record, size_t user_record_len, void *user_data); int axc_db_session_contains(const signal_protocol_address *address, void *user_data); int axc_db_session_delete(const signal_protocol_address *address, void *user_data); int axc_db_session_delete_all(const char *name, size_t name_len, void *user_data); void axc_db_session_destroy_store_ctx(void *user_data); // pre key store int axc_db_pre_key_load(signal_buffer **record, uint32_t pre_key_id, void *user_data); int axc_db_pre_key_store(uint32_t pre_key_id, uint8_t *record, size_t record_len, void *user_data); int axc_db_pre_key_contains(uint32_t pre_key_id, void *user_data); int axc_db_pre_key_remove(uint32_t pre_key_id, void *user_data); void axc_db_pre_key_destroy_ctx(void *user_data); /** * Stores a whole list of pre keys at once, inside a single transaction. * * @param pre_keys_head Pointer to the first element of the list. * @param user_data_p Optional. The user_data as received from the axolotl interface, will be used to set the database name. */ int axc_db_pre_key_store_list(signal_protocol_key_helper_pre_key_list_node * pre_keys_head, axc_context * ctx_p); /** * Gets the specified number of pre keys for publishing, i.e. only their public part. * * @param amount Number of keys to retrieve. * @param ctx_p Pointer to the initialized axc context. * @param list_head_pp Will be set to the head of the list. * @return 0 on success, negative on error. */ int axc_db_pre_key_get_list(size_t amount, axc_context * ctx_p, axc_buf_list_item ** list_head_pp); /** * Retrieves the highest existing pre key ID that is not the last resort key's ID. * * @param ctx_p Pointer to the axc context. * @param max_id_p Will be set to the highest ID that is not MAX_INT. * @return 0 on success, negative on error. */ int axc_db_pre_key_get_max_id(axc_context * ctx_p, uint32_t * max_id_p); /** * Returns the count of pre keys saved in the database. * This includes the "last resort" key that is additionally generated at db init. * * @param ctx_p Pointer to the axc context. * @param count_p Will point to the number of pre keys. * @return 0 on success, negative on error. */ int axc_db_pre_key_get_count(axc_context * ctx_p, size_t * count_p); // signed pre key store int axc_db_signed_pre_key_load(signal_buffer **record, uint32_t signed_pre_key_id, void *user_data); int axc_db_signed_pre_key_store(uint32_t signed_pre_key_id, uint8_t *record, size_t record_len, void *user_data); int axc_db_signed_pre_key_contains(uint32_t signed_pre_key_id, void *user_data); int axc_db_signed_pre_key_remove(uint32_t signed_pre_key_id, void *user_data); void axc_db_signed_pre_key_destroy_ctx(void *user_data); // identity key store int axc_db_identity_get_key_pair(signal_buffer **public_data, signal_buffer **private_data, void *user_data); int axc_db_identity_get_local_registration_id(void *user_data, uint32_t *registration_id); int axc_db_identity_save(const signal_protocol_address * addr_p, uint8_t *key_data, size_t key_len, void *user_data); int axc_db_identity_is_trusted(const char *name, size_t name_len, uint8_t *key_data, size_t key_len, void *user_data); int axc_db_identity_always_trusted(const signal_protocol_address * addr_p, uint8_t * key_data, size_t key_len, void * user_data); void axc_db_identity_destroy_ctx(void *user_data); // additional helper functions /** * Saves the public and private key by using the api serialization calls, as this format (and not the higher-level key type) is needed by the getter. * * @param Pointer to the keypair as returned by axolotl_key_helper_generate_identity_key_pair * @param axc_ctx_p Pointer to the axc context. * @return 0 on success, negative on error */ int axc_db_identity_set_key_pair(const ratchet_identity_key_pair * key_pair_p, axc_context * axc_ctx_p); /** * Saves the axolotl registration ID which was obtained by a call to axolotl_key_helper_generate_registration_id(). * * @param reg_id The ID. * @param axc_ctx_p Pointer to the axc context. * @return 0 on success, negative on error */ int axc_db_identity_set_local_registration_id(const uint32_t reg_id, axc_context * axc_ctx_p); // other /** * Creates the necessary tables. Safe to call if they already exist. * * @param axc_ctx_p Pointer to the axc context. * @return 0 on success, negative on error */ int axc_db_create(axc_context * axc_ctx_p); /** * Drops all the tables so that the db can be reset. * * @param axc_ctx_p Pointer to the axc context. * @return 0 on success, negative on error */ int axc_db_destroy(axc_context * axc_ctx_p); /** * Sets the value of a property in the database's "settings" table. * * @param name The name of the property. * @param status The int value of the property. * @param axc_ctx_p Pointer to the axc context. * @return 0 on success, negative on error */ int axc_db_property_set(const char * name, const int val, axc_context * axc_ctx_p); /** * Gets a property from the settings table. * * @param name Name of the property * @param val_p Pointer to where the saved value should be stored. * @param axc_ctx_p Pointer to the axc context. * @return 0 on success, negative on error, 1 if no sql error but no result */ int axc_db_property_get(const char * name, int * val_p, axc_context * axc_ctx_p); /** * "Partial application" of db_set_property, setting the init status value. * * @param status AXC_DB_NOT INITIALIZED, AXC_DB_NEEDS_ROOLBACK, or AXC_DB_INITIALIZED * @param axc_ctx_p Pointer to the axc context. * @return 0 on success, negative on error */ int axc_db_init_status_set(const int status, axc_context * axc_ctx_p); /** * "Partial application" of db_get_property, getting the init status value. * * @param init_status_p The value behind this pointer will be set to the init status number. * @param axc_ctx_p Pointer to the axc context. * @return 0 on success, negative on error, 1 if no sql error but no result */ int axc_db_init_status_get(int * init_status_p, axc_context * axc_ctx_p); axc-0.3.7/src/message_client.c000066400000000000000000000146031417527735300162330ustar00rootroot00000000000000/* * Copyright (C) 2017-2020 Richard Bayerle * SPDX-License-Identifier: GPL-3.0-only * Author: Richard Bayerle */ #include // toupper #include // printf, getline #include // exit codes #include // memset, strlen #include "axc.h" #define FAIL0(lbl,...) do { ret = EXIT_FAILURE; fprintf(stderr, __VA_ARGS__); goto lbl; } while (0) #define FAIL(...) FAIL0(cleanup,__VA_ARGS__) int main(void) { printf("sup\n"); printf("initializing context for alice...\n"); axc_context * ctx_a_p; int ret = EXIT_SUCCESS; if (axc_context_create(&ctx_a_p)) FAIL0(cleanup_none, "failed to create axc context\n"); axc_context_set_log_func(ctx_a_p, axc_default_log); axc_context_set_log_level(ctx_a_p, AXC_LOG_DEBUG); char * db_a_fn = "client/a.sqlite"; if (axc_context_set_db_fn(ctx_a_p, db_a_fn, strlen(db_a_fn))) FAIL0(cleanup_a, "failed to set db filename\n"); printf("set db fn\n"); if (axc_init(ctx_a_p)) FAIL0(cleanup_a, "failed to init axc\n"); printf("installing client for alice...\n"); if (axc_install(ctx_a_p)) FAIL0(cleanup_a, "failed to install axc\n"); printf("initializing context for bob...\n"); axc_context * ctx_b_p; if (axc_context_create(&ctx_b_p)) FAIL0(cleanup_a, "failed to create axc context\n"); char * db_b_fn = "client/b.sqlite"; if (axc_context_set_db_fn(ctx_b_p, db_b_fn, strlen(db_b_fn))) FAIL("failed to set db filename\n"); axc_context_set_log_func(ctx_b_p, axc_default_log); axc_context_set_log_level(ctx_b_p, AXC_LOG_DEBUG); if (axc_init(ctx_b_p)) FAIL("failed to init axc\n"); printf("installing client for bob...\n"); if (axc_install(ctx_b_p)) FAIL("failed to install axc\n"); axc_address addr_a = { .name = "alice", .name_len = 5, .device_id = 1 }; axc_address addr_b = { .name = "bob", .name_len = 3, .device_id = 1 }; printf("checking if session already exists\n"); if (!axc_session_exists_initiated(&addr_b, ctx_a_p)) { printf("creating session between alice and bob\n"); axc_bundle *bundle_bob; if (axc_bundle_collect(AXC_PRE_KEYS_AMOUNT, ctx_b_p, &bundle_bob)) FAIL("failed to collect bob's bundle\n"); // addr_b.device_id = axc_bundle_get_reg_id(bundle_bob); if (axc_session_from_bundle(axc_buf_list_item_get_id(axc_bundle_get_pre_key_list(bundle_bob)), axc_buf_list_item_get_buf(axc_bundle_get_pre_key_list(bundle_bob)), axc_bundle_get_signed_pre_key_id(bundle_bob), axc_bundle_get_signed_pre_key(bundle_bob), axc_bundle_get_signature(bundle_bob), axc_bundle_get_identity_key(bundle_bob), &addr_b, ctx_a_p)) FAIL("failed to create session from bob's bundle\n"); axc_bundle_destroy(bundle_bob); axc_buf * msg_buf_p = axc_buf_create((const uint8_t *)"hello", strlen("hello") + 1); if (!msg_buf_p) FAIL("failed to create 'hello' msg buffer\n"); axc_buf * ct_buf_p; if (axc_message_encrypt_and_serialize(msg_buf_p, &addr_b, ctx_a_p, &ct_buf_p)) FAIL("failed to encrypt 'hello' message\n"); uint32_t alice_id; if (axc_get_device_id(ctx_a_p, &alice_id)) FAIL("failed to retrieve alice's device_id\n"); addr_a.device_id = alice_id; axc_buf * pt_buf_p; if (axc_pre_key_message_process(ct_buf_p, &addr_a, ctx_b_p, &pt_buf_p)) FAIL("failed to process 'hello' pre_key_message\n"); axc_buf_free(ct_buf_p); axc_buf_free(pt_buf_p); if (axc_message_encrypt_and_serialize(msg_buf_p, &addr_a, ctx_b_p, &ct_buf_p)) FAIL("failed encrypting 2nd 'hello' message\n"); if (axc_message_decrypt_from_serialized(ct_buf_p, &addr_b, ctx_a_p, &pt_buf_p)) FAIL("failed decrypting 2nd 'hello' message\n"); axc_buf_free(ct_buf_p); axc_buf_free(pt_buf_p); axc_buf_free(msg_buf_p); printf("session created on each side\n"); } else { printf("session exists.\n"); uint32_t alice_id; if (axc_get_device_id(ctx_a_p, &alice_id)) FAIL("failed to retrieve alice's device_id\n"); addr_a.device_id = alice_id; } printf("now trying to ready to 'send' and 'receive' messages\n"); char * line = (void *) 0; size_t len = 0; printf("enter message: "); while(getline(&line, &len, stdin) > 0) { axc_buf * ciphertext_p; { axc_buf * msg_p = axc_buf_create((uint8_t *) line, strlen(line) + 1); if (axc_message_encrypt_and_serialize(msg_p, &addr_b, ctx_a_p, &ciphertext_p)) FAIL("failed to encrypt message from alice to bob\n"); printf("encrypted message from alice to bob: %s\n", line); axc_buf_free(msg_p); } uint8_t * buf = signal_buffer_data(ciphertext_p); printf("serialized ciphertext (hex):\n"); for (size_t i = 0; i < axc_buf_get_len(ciphertext_p); i++) { printf("%02X ", buf[i]); } printf("\n"); axc_buf * upper_buf; axc_buf * plaintext_p; if (axc_message_decrypt_from_serialized(ciphertext_p, &addr_a, ctx_b_p, &plaintext_p)) FAIL("failed to decrypt message from alice to bob\n"); axc_buf_free(ciphertext_p); printf("decrypted message: %s\n", axc_buf_get_data(plaintext_p)); char * upper = (char *)axc_buf_get_data(plaintext_p); for (size_t i = 0; i < strlen(upper); i++) { upper[i] = toupper(upper[i]); } printf("bob sending reply...\n"); upper_buf = axc_buf_create((uint8_t *) upper, strlen(upper) + 1); axc_buf_free(plaintext_p); if (axc_message_encrypt_and_serialize(upper_buf, &addr_a, ctx_b_p, &ciphertext_p)) FAIL("failed to encrypt message from bob to alice\n"); axc_buf_free(upper_buf); buf = signal_buffer_data(ciphertext_p); printf("serialized ciphertext (hex):\n"); for (size_t i = 0; i < axc_buf_get_len(ciphertext_p); i++) { printf("%02X ", buf[i]); } printf("\n"); if (axc_message_decrypt_from_serialized(ciphertext_p, &addr_b, ctx_a_p, &plaintext_p)) FAIL("failed to decrypt message from bob to alice\n"); axc_buf_free(ciphertext_p); printf("received reply from bob: %s\n", axc_buf_get_data(plaintext_p)); axc_buf_free(plaintext_p); printf("enter message: "); } free(line); printf("done, exiting.\n"); cleanup: axc_cleanup(ctx_b_p); cleanup_a: axc_cleanup(ctx_a_p); cleanup_none: return ret; } axc-0.3.7/test/000077500000000000000000000000001417527735300132715ustar00rootroot00000000000000axc-0.3.7/test/test_client.c000066400000000000000000000631321417527735300157570ustar00rootroot00000000000000/* * Copyright (C) 2017-2020 Richard Bayerle * SPDX-License-Identifier: GPL-3.0-only * Author: Richard Bayerle */ #include #include #include #include #include "../src/axc_crypto.h" #include "../src/axc.c" #include "../src/axc_store.c" char * test_fn = "test/test.sqlite"; char * a_fn = "test/a.sqlite"; char * b_fn = "test/b.sqlite"; signal_protocol_address addr_alice_42 = {.name = "alice", .name_len = 5, .device_id = 42}; signal_protocol_address addr_alice_21 = {.name = "alice", .name_len = 5, .device_id = 21}; signal_protocol_address addr_alice = {.name = "alice", .name_len = 5, .device_id = 0}; signal_protocol_address addr_bob_12 = {.name = "bob", .name_len = 3, .device_id = 12}; axc_address addr_bob = {.name = "bob", .name_len = 3, .device_id = 0}; axc_context * ctx_global_p; axc_context * ctx_a_p = (void *) 0; axc_context * ctx_b_p = (void *) 0; int global_setup(void ** state) { (void) state; axc_crypto_init(); return 0; } int global_teardown(void ** state) { (void) state; axc_crypto_teardown(); return 0; } int client_setup(void **state) { (void) state; ctx_global_p = (void *) 0; assert_int_equal(axc_context_create(&ctx_global_p), 0); assert_int_equal(axc_context_set_db_fn(ctx_global_p, test_fn, strlen(test_fn)), 0); //axc_context_set_log_func(ctx_global_p, axc_default_log); //axc_context_set_log_level(ctx_global_p, AXC_LOG_DEBUG); return axc_init(ctx_global_p); } int client_teardown(void ** state) { (void) state; axc_crypto_teardown(); axc_cleanup(ctx_global_p); ctx_global_p = (void *) 0; remove(test_fn); return 0; } int client_setup_two_dbs(void ** state) { (void) state; ctx_a_p = (void *) 0; ctx_b_p = (void *) 0; assert_int_equal(axc_context_create(&ctx_a_p), 0); assert_int_equal(axc_context_create(&ctx_b_p), 0); assert_int_equal(axc_context_set_db_fn(ctx_a_p, a_fn, strlen(a_fn)), 0); assert_int_equal(axc_context_set_db_fn(ctx_b_p, b_fn, strlen(b_fn)), 0); /* axc_context_set_log_func(ctx_a_p, axc_default_log); axc_context_set_log_level(ctx_a_p, AXC_LOG_DEBUG); axc_context_set_log_func(ctx_b_p, axc_default_log); axc_context_set_log_level(ctx_b_p, AXC_LOG_DEBUG); */ assert_int_equal(axc_init(ctx_a_p), 0); assert_int_equal(axc_init(ctx_b_p), 0); assert_int_equal(axc_install(ctx_a_p), 0); assert_int_equal(axc_install(ctx_b_p), 0); return 0; } int client_setup_sessions(void ** state) { assert_int_equal(client_setup_two_dbs(state), 0); axc_bundle * bundle_bob_p; assert_int_equal(axc_bundle_collect(AXC_PRE_KEYS_AMOUNT, ctx_b_p, &bundle_bob_p), 0); addr_bob.device_id = bundle_bob_p->registration_id; assert_int_equal(axc_session_from_bundle(axc_buf_list_item_get_id(bundle_bob_p->pre_keys_head_p), axc_buf_list_item_get_buf(bundle_bob_p->pre_keys_head_p), bundle_bob_p->signed_pre_key_id, bundle_bob_p->signed_pre_key_public_serialized_p, bundle_bob_p->signed_pre_key_signature_p, bundle_bob_p->identity_key_public_serialized_p, &addr_bob, ctx_a_p), 0); const char * data = "hello"; axc_buf * msg_buf_p = axc_buf_create((uint8_t *) data, strlen(data) + 1); assert_ptr_not_equal(msg_buf_p, (void *) 0); axc_buf * ct_buf_p; assert_int_equal(axc_message_encrypt_and_serialize(msg_buf_p, &addr_bob, ctx_a_p, &ct_buf_p), 0); uint32_t alice_id; assert_int_equal(axc_get_device_id(ctx_a_p, &alice_id), 0); addr_alice.device_id = alice_id; axc_buf * pt_buf_p; assert_int_equal(axc_pre_key_message_process(ct_buf_p, &addr_alice, ctx_b_p, &pt_buf_p), 0); axc_buf_free(ct_buf_p); axc_buf_free(pt_buf_p); assert_int_equal(axc_message_encrypt_and_serialize(msg_buf_p, &addr_alice, ctx_b_p, &ct_buf_p), 0); assert_int_equal(axc_message_decrypt_from_serialized(ct_buf_p, &addr_bob, ctx_a_p, &pt_buf_p), 0); assert_int_equal(axc_session_exists_initiated(&addr_bob, ctx_a_p), 1); assert_int_equal(axc_session_exists_initiated(&addr_alice, ctx_b_p), 1); axc_buf_free(msg_buf_p); axc_buf_free(ct_buf_p); axc_buf_free(pt_buf_p); return 0; } int client_teardown_two_dbs(void **state) { (void) state; axc_cleanup(ctx_a_p); axc_cleanup(ctx_b_p); remove(a_fn); remove(b_fn); return 0; } void test_init(void **state) { (void) state; ctx_global_p = (void *) 0; assert_int_equal(axc_context_create(&ctx_global_p), 0); assert_ptr_not_equal(ctx_global_p, (void *) 0); assert_int_equal(axc_context_set_db_fn(ctx_global_p, test_fn, strlen(test_fn)), 0); assert_int_equal(axc_init(ctx_global_p), 0); #ifndef NO_THREADS assert_ptr_not_equal(ctx_global_p->mutexes_p, (void *) 0); assert_ptr_not_equal(ctx_global_p->mutexes_p->mutex_p, (void *) 0); assert_ptr_not_equal(ctx_global_p->mutexes_p->mutex_attr_p, (void *) 0); int type = 0; assert_int_equal(pthread_mutexattr_gettype(ctx_global_p->mutexes_p->mutex_attr_p, &type), 0); assert_int_equal(type, PTHREAD_MUTEX_RECURSIVE); #endif assert_ptr_not_equal(ctx_global_p->axolotl_global_context_p, (void *) 0); assert_ptr_not_equal(ctx_global_p->axolotl_store_context_p, (void *) 0); } void test_recursive_mutex_lock(void **state) { (void) state; #ifndef NO_THREADS assert_ptr_not_equal(ctx_global_p->mutexes_p, (void *) 0); recursive_mutex_lock(ctx_global_p); assert_int_equal(pthread_mutex_unlock(ctx_global_p->mutexes_p->mutex_p), 0); #else skip(); #endif } void test_recursive_mutex_unlock(void **state){ (void) state; #ifndef NO_THREADS recursive_mutex_lock(ctx_global_p); recursive_mutex_unlock(ctx_global_p); assert_int_not_equal(pthread_mutex_unlock(ctx_global_p->mutexes_p->mutex_p), 0); #else skip(); #endif } void test_install_should_generate_necessary_data(void **state) { (void) state; assert_int_equal(axc_install(ctx_global_p), 0); sqlite3 * db_p = (void *) 0; sqlite3_stmt * pstmt_p = (void *) 0; char stmt[100]; assert_int_not_equal(sprintf(stmt, "SELECT count(*) FROM identity_key_store WHERE name IS '%s';", OWN_PUBLIC_KEY_NAME), 0); assert_int_equal(sqlite3_open(test_fn, &db_p), SQLITE_OK); assert_int_equal(sqlite3_prepare_v2(db_p, stmt, -1, &pstmt_p, (void *) 0), SQLITE_OK); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_int_equal(sqlite3_column_int(pstmt_p, 0), 1); assert_int_equal(sqlite3_finalize(pstmt_p), SQLITE_OK); assert_int_not_equal(sprintf(stmt, "SELECT count(*) FROM identity_key_store WHERE name IS '%s';", OWN_PRIVATE_KEY_NAME), 0); assert_int_equal(sqlite3_prepare_v2(db_p, stmt, -1, &pstmt_p, (void *) 0), SQLITE_OK); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_int_equal(sqlite3_column_int(pstmt_p, 0), 1); assert_int_equal(sqlite3_finalize(pstmt_p), SQLITE_OK); assert_int_not_equal(sprintf(stmt, "SELECT count(*) FROM settings WHERE name IS '%s';", REG_ID_NAME), 0); assert_int_equal(sqlite3_prepare_v2(db_p, stmt, -1, &pstmt_p, (void *) 0), SQLITE_OK); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_int_equal(sqlite3_column_int(pstmt_p, 0), 1); assert_int_equal(sqlite3_finalize(pstmt_p), SQLITE_OK); assert_int_not_equal(sprintf(stmt, "SELECT count(*) FROM pre_key_store;"), 0); assert_int_equal(sqlite3_prepare_v2(db_p, stmt, -1, &pstmt_p, (void *) 0), SQLITE_OK); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_int_equal(sqlite3_column_int(pstmt_p, 0), AXC_PRE_KEYS_AMOUNT); assert_int_equal(sqlite3_finalize(pstmt_p), SQLITE_OK); assert_int_not_equal(sprintf(stmt, "SELECT count(*) FROM signed_pre_key_store;"), 0); assert_int_equal(sqlite3_prepare_v2(db_p, stmt, -1, &pstmt_p, (void *) 0), SQLITE_OK); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_int_equal(sqlite3_column_int(pstmt_p, 0), 1); assert_int_equal(sqlite3_finalize(pstmt_p), SQLITE_OK); assert_int_equal(sqlite3_close(db_p), SQLITE_OK); int result = 0; assert_int_equal(axc_db_init_status_get(&result, ctx_global_p), 0); assert_int_equal(result, AXC_DB_INITIALIZED); } void test_install_should_not_do_anything_if_already_initialiased(void **state) { (void) state; assert_int_equal(axc_install(ctx_global_p), 0); uint32_t reg_id_1 = 0; assert_int_equal(axc_db_identity_get_local_registration_id(ctx_global_p, ®_id_1), 0); assert_int_not_equal(reg_id_1, 0); uint32_t reg_id_2 = 0; assert_int_equal(axc_install(ctx_global_p), 0); assert_int_equal(axc_db_identity_get_local_registration_id(ctx_global_p, ®_id_2), 0); assert_int_not_equal(reg_id_2, 0); assert_int_equal(reg_id_1, reg_id_2); } void test_install_should_reset_if_needed(void **state) { (void) state; assert_int_equal(axc_install(ctx_global_p), 0); uint32_t reg_id_1 = 0; assert_int_equal(axc_db_identity_get_local_registration_id(ctx_global_p, ®_id_1), 0); assert_int_not_equal(reg_id_1, 0); assert_int_equal(axc_db_init_status_set(0, ctx_global_p), 0); uint32_t reg_id_2 = 0; assert_int_equal(axc_install(ctx_global_p), 0); assert_int_equal(axc_db_identity_get_local_registration_id(ctx_global_p, ®_id_2), 0); assert_int_not_equal(reg_id_2, 0); assert_int_not_equal(reg_id_1, reg_id_2); } void test_message_encrypt_decrypt(void **state) { (void) state; axc_buf * msg_a1_p = axc_buf_create((uint8_t *) "hallo", 6); axc_buf * msg_a2_p = axc_buf_create((uint8_t *) "sup", 4); axc_buf * msg_b1_p = axc_buf_create((uint8_t *) "0123456789abcdef", 16); axc_buf * msg_b2_p = axc_buf_create((uint8_t *) "na", 3); assert_int_not_equal(axc_message_encrypt_and_serialize((void *) 0, (void *) 0, (void *) 0, (void *) 0), 0); assert_int_not_equal(axc_message_encrypt_and_serialize(msg_a1_p, (void *) 0, (void *) 0, (void *) 0), 0); assert_int_not_equal(axc_message_encrypt_and_serialize(msg_a1_p, &addr_bob_12, (void *) 0, (void *) 0), 0); assert_int_not_equal(axc_message_encrypt_and_serialize(msg_a1_p, &addr_bob_12, ctx_a_p, (void *) 0), 0); axc_buf * ct_a1_p = (void *) 0; axc_buf * ct_a2_p = (void *) 0; assert_int_equal(axc_message_encrypt_and_serialize(msg_a1_p, &addr_bob, ctx_a_p, &ct_a1_p), 0); assert_int_equal(axc_message_encrypt_and_serialize(msg_a2_p, &addr_bob, ctx_a_p, &ct_a2_p), 0); axc_buf * pt_a1_p = (void *) 0; axc_buf * pt_a2_p = (void *) 0; assert_int_not_equal(axc_message_decrypt_from_serialized((void *) 0, (void *) 0, (void *) 0, (void *) 0), 0); assert_int_not_equal(axc_message_decrypt_from_serialized(ct_a1_p, (void *) 0, (void *) 0, (void *) 0), 0); assert_int_not_equal(axc_message_decrypt_from_serialized(ct_a1_p, &addr_alice, (void *) 0, (void *) 0), 0); assert_int_not_equal(axc_message_decrypt_from_serialized(ct_a1_p, &addr_alice, ctx_b_p, (void *) 0), 0); assert_int_equal(axc_message_decrypt_from_serialized(ct_a1_p, &addr_alice, ctx_b_p, &pt_a1_p), 0); assert_int_equal(axc_message_decrypt_from_serialized(ct_a2_p, &addr_alice, ctx_b_p, &pt_a2_p), 0); axc_buf * ct_b1_p = (void *) 0; axc_buf * ct_b2_p = (void *) 0; assert_int_equal(axc_message_encrypt_and_serialize(msg_b1_p, &addr_alice, ctx_b_p, &ct_b1_p), 0); assert_int_equal(axc_message_encrypt_and_serialize(msg_b2_p, &addr_alice, ctx_b_p, &ct_b2_p), 0); axc_buf * pt_b1_p = (void *) 0; axc_buf * pt_b2_p = (void *) 0; assert_int_equal(axc_message_decrypt_from_serialized(ct_b2_p, &addr_bob, ctx_a_p, &pt_b2_p), 0); assert_int_equal(axc_message_decrypt_from_serialized(ct_b1_p, &addr_bob, ctx_a_p, &pt_b1_p), 0); assert_int_equal(axc_buf_get_len(msg_a1_p), axc_buf_get_len(pt_a1_p)); assert_memory_equal(axc_buf_get_data(msg_a1_p), axc_buf_get_data(pt_a1_p), axc_buf_get_len(pt_a1_p)); assert_int_equal(axc_buf_get_len(msg_a2_p), axc_buf_get_len(pt_a2_p)); assert_memory_equal(axc_buf_get_data(msg_a2_p), axc_buf_get_data(pt_a2_p), axc_buf_get_len(pt_a2_p)); assert_int_equal(axc_buf_get_len(msg_b1_p), axc_buf_get_len(pt_b1_p)); assert_memory_equal(axc_buf_get_data(msg_b1_p), axc_buf_get_data(pt_b1_p), axc_buf_get_len(pt_b1_p)); assert_int_equal(axc_buf_get_len(msg_b2_p), axc_buf_get_len(pt_b2_p)); assert_memory_equal(axc_buf_get_data(msg_b2_p), axc_buf_get_data(pt_b2_p), axc_buf_get_len(pt_b2_p)); axc_buf_free(msg_a1_p); axc_buf_free(msg_a2_p); axc_buf_free(msg_b1_p); axc_buf_free(msg_b2_p); axc_buf_free(ct_a1_p); axc_buf_free(ct_a2_p); axc_buf_free(ct_b1_p); axc_buf_free(ct_b2_p); axc_buf_free(pt_a1_p); axc_buf_free(pt_a2_p); axc_buf_free(pt_b1_p); axc_buf_free(pt_b2_p); } void test_session_exists_any(void ** state) { (void) state; assert_int_equal(axc_session_exists_initiated(&addr_bob, ctx_a_p), 0); assert_int_equal(axc_session_exists_any(addr_bob.name, ctx_a_p), 0); assert_int_equal(axc_session_exists_initiated(&addr_alice, ctx_b_p), 0); assert_int_equal(axc_session_exists_any(addr_alice.name, ctx_b_p), 0); axc_bundle * bundle_bob_p; assert_int_equal(axc_bundle_collect(AXC_PRE_KEYS_AMOUNT, ctx_b_p, &bundle_bob_p), 0); addr_bob.device_id = bundle_bob_p->registration_id; assert_int_equal(axc_session_from_bundle(axc_buf_list_item_get_id(bundle_bob_p->pre_keys_head_p), axc_buf_list_item_get_buf(bundle_bob_p->pre_keys_head_p), bundle_bob_p->signed_pre_key_id, bundle_bob_p->signed_pre_key_public_serialized_p, bundle_bob_p->signed_pre_key_signature_p, bundle_bob_p->identity_key_public_serialized_p, &addr_bob, ctx_a_p), 0); const char * data = "hello"; axc_buf * msg_buf_p = axc_buf_create((uint8_t *) data, strlen(data) + 1); assert_ptr_not_equal(msg_buf_p, (void *) 0); axc_buf * ct_buf_p; assert_int_equal(axc_message_encrypt_and_serialize(msg_buf_p, &addr_bob, ctx_a_p, &ct_buf_p), 0); uint32_t alice_id; assert_int_equal(axc_get_device_id(ctx_a_p, &alice_id), 0); addr_alice.device_id = alice_id; axc_buf * pt_buf_p; assert_int_equal(axc_pre_key_message_process(ct_buf_p, &addr_alice, ctx_b_p, &pt_buf_p), 0); assert_int_equal(axc_session_exists_initiated(&addr_alice, ctx_b_p), 1); assert_int_equal(axc_session_exists_initiated(&addr_alice_42, ctx_b_p), 0); assert_int_equal(axc_session_exists_any(addr_alice.name, ctx_b_p), 1); } void test_session_from_bundle_and_handle_prekey_message(void **state) { (void) state; axc_address addr_bob = {.name = "bob", .name_len = 3, .device_id = 0}; assert_int_equal(axc_db_identity_get_local_registration_id(ctx_b_p, (uint32_t *)&(addr_bob.device_id)), 0); assert_int_equal(axc_session_exists_initiated(&addr_bob, ctx_a_p), 0); uint32_t pre_key_id_bob = 10; session_pre_key * pre_key_bob_p = (void *) 0; assert_int_equal(signal_protocol_pre_key_load_key(ctx_b_p->axolotl_store_context_p, &pre_key_bob_p, pre_key_id_bob), 0); ec_key_pair * pre_key_pair_p = session_pre_key_get_key_pair(pre_key_bob_p); ec_public_key * pre_key_public_p = ec_key_pair_get_public(pre_key_pair_p); axc_buf * pre_key_public_data_p = (void *) 0; assert_int_equal(ec_public_key_serialize(&pre_key_public_data_p, pre_key_public_p), 0); uint32_t signed_pre_key_id_bob = 0; session_signed_pre_key * signed_pre_key_bob_p = (void *) 0; assert_int_equal(signal_protocol_signed_pre_key_load_key(ctx_b_p->axolotl_store_context_p, &signed_pre_key_bob_p, signed_pre_key_id_bob), 0); ec_key_pair * signed_pre_key_pair_p = session_signed_pre_key_get_key_pair(signed_pre_key_bob_p); ec_public_key * signed_pre_key_public_p = ec_key_pair_get_public(signed_pre_key_pair_p); axc_buf * signed_pre_key_public_data_p = (void *) 0; assert_int_equal(ec_public_key_serialize(&signed_pre_key_public_data_p, signed_pre_key_public_p), 0); axc_buf * signed_pre_key_signature_p = axc_buf_create(session_signed_pre_key_get_signature(signed_pre_key_bob_p), session_signed_pre_key_get_signature_len(signed_pre_key_bob_p)); assert_ptr_not_equal(signed_pre_key_signature_p, (void *) 0); axc_buf * identity_public_key_bob_p = (void *) 0; axc_buf * identity_private_key_throwaway = (void *) 0; assert_int_equal(axc_db_identity_get_key_pair(&identity_public_key_bob_p, &identity_private_key_throwaway, ctx_b_p), 0); assert_int_equal(axc_session_from_bundle(pre_key_id_bob, pre_key_public_data_p, signed_pre_key_id_bob, signed_pre_key_public_data_p, signed_pre_key_signature_p, identity_public_key_bob_p, &addr_bob, ctx_a_p), 0); assert_int_equal(axc_session_exists_initiated(&addr_bob, ctx_a_p), 1); char * test_msg_p = "butter für den buttergott"; axc_buf * test_msg_data_p = axc_buf_create((uint8_t *) test_msg_p, strlen(test_msg_p) + 1); axc_buf * test_msg_ct_p = (void *) 0; assert_int_equal(axc_message_encrypt_and_serialize(test_msg_data_p, &addr_bob, ctx_a_p, &test_msg_ct_p), 0); size_t pre_keys_count_bob = 0; uint32_t max_id_bob = 0; assert_int_equal(axc_db_pre_key_get_count(ctx_b_p, &pre_keys_count_bob), 0); assert_int_equal(pre_keys_count_bob, AXC_PRE_KEYS_AMOUNT); assert_int_equal(axc_db_pre_key_get_max_id(ctx_b_p, &max_id_bob), 0); assert_int_equal(max_id_bob, AXC_PRE_KEYS_AMOUNT - 1); axc_buf * test_msg_decrypted_p = (void *) 0; assert_int_equal(axc_pre_key_message_process(test_msg_ct_p, &addr_alice_21, ctx_b_p, &test_msg_decrypted_p), 0); assert_string_equal(test_msg_p, (char *) axc_buf_get_data(test_msg_decrypted_p)); assert_int_equal(axc_db_pre_key_contains(pre_key_id_bob, ctx_b_p), 0); assert_int_equal(axc_db_pre_key_get_count(ctx_b_p, &pre_keys_count_bob), 0); assert_int_equal(pre_keys_count_bob, AXC_PRE_KEYS_AMOUNT); assert_int_equal(axc_db_pre_key_get_max_id(ctx_b_p, &max_id_bob), 0); assert_int_equal(max_id_bob, AXC_PRE_KEYS_AMOUNT); } void test_bundle_collect(void ** state) { (void) state; assert_int_equal(axc_install(ctx_global_p), 0); axc_bundle * bundle_p; assert_int_equal(axc_bundle_collect(AXC_PRE_KEYS_AMOUNT, ctx_global_p, &bundle_p), 0); assert_ptr_not_equal(bundle_p, (void *) 0); uint32_t reg_id; assert_int_equal(axc_get_device_id(ctx_global_p, ®_id), 0); assert_int_equal(bundle_p->registration_id, reg_id); assert_ptr_not_equal(bundle_p->pre_keys_head_p, (void *) 0); ec_public_key * signed_pre_key_p; assert_ptr_not_equal(bundle_p->signed_pre_key_public_serialized_p, (void *) 0); assert_int_equal(curve_decode_point(&signed_pre_key_p, axc_buf_get_data(bundle_p->signed_pre_key_public_serialized_p), axc_buf_get_len(bundle_p->signed_pre_key_public_serialized_p), ctx_global_p->axolotl_global_context_p), 0); assert_ptr_not_equal(bundle_p->signed_pre_key_signature_p, (void *) 0); ec_public_key * identity_key_p; assert_ptr_not_equal(bundle_p->identity_key_public_serialized_p, (void *) 0); assert_int_equal(curve_decode_point(&identity_key_p, axc_buf_get_data(bundle_p->identity_key_public_serialized_p), axc_buf_get_len(bundle_p->identity_key_public_serialized_p), ctx_global_p->axolotl_global_context_p), 0); axc_bundle_destroy(bundle_p); } void test_session_exists_prekeys(void ** state) { (void) state; axc_bundle * bundle_bob_p; assert_int_equal(axc_bundle_collect(AXC_PRE_KEYS_AMOUNT, ctx_b_p, &bundle_bob_p), 0); axc_address addr_bob = {.name = "bob", .name_len = 3, .device_id = bundle_bob_p->registration_id}; assert_int_equal(axc_session_exists_initiated(&addr_bob, ctx_a_p), 0); assert_int_equal(axc_session_from_bundle(axc_buf_list_item_get_id(bundle_bob_p->pre_keys_head_p), axc_buf_list_item_get_buf(bundle_bob_p->pre_keys_head_p), bundle_bob_p->signed_pre_key_id, bundle_bob_p->signed_pre_key_public_serialized_p, bundle_bob_p->signed_pre_key_signature_p, bundle_bob_p->identity_key_public_serialized_p, &addr_bob, ctx_a_p), 0); assert_int_equal(axc_session_exists_initiated(&addr_bob, ctx_a_p), 1); const char * data = "hello"; axc_buf * msg_buf_p = axc_buf_create((uint8_t *) data, strlen(data) + 1); assert_ptr_not_equal(msg_buf_p, (void *) 0); axc_buf * ct_buf_p; assert_int_equal(axc_message_encrypt_and_serialize(msg_buf_p, &addr_bob, ctx_a_p, &ct_buf_p), 0); assert_int_equal(axc_session_exists_initiated(&addr_bob, ctx_a_p), 1); uint32_t alice_id; assert_int_equal(axc_get_device_id(ctx_a_p, &alice_id), 0); axc_address addr_alice = {.name = "alice", .name_len = strlen("alice"), .device_id = alice_id}; assert_int_equal(axc_session_exists_initiated(&addr_alice, ctx_b_p), 0); axc_buf * pt_buf_p; assert_int_equal(axc_pre_key_message_process(ct_buf_p, &addr_alice, ctx_b_p, &pt_buf_p), 0); assert_string_equal(axc_buf_get_data(pt_buf_p), "hello"); assert_memory_equal(axc_buf_get_data(msg_buf_p), axc_buf_get_data(pt_buf_p), axc_buf_get_len(msg_buf_p)); assert_int_equal(axc_session_exists_initiated(&addr_alice, ctx_b_p), 1); axc_buf_free(msg_buf_p); axc_buf_free(ct_buf_p); axc_buf_free(pt_buf_p); const char * other_data = "hello 234"; msg_buf_p = axc_buf_create((uint8_t *) other_data, strlen(other_data) + 1); assert_ptr_not_equal(msg_buf_p, (void *) 0); assert_int_equal(axc_message_encrypt_and_serialize(msg_buf_p, &addr_bob, ctx_a_p, &ct_buf_p), 0); int ret_val = axc_message_decrypt_from_serialized(ct_buf_p, &addr_alice, ctx_b_p, &pt_buf_p); assert_int_not_equal(ret_val, 0); // if no reply was received yet, axolotl keeps sending prekey messages assert_int_equal(axc_pre_key_message_process(ct_buf_p, &addr_alice, ctx_b_p, &pt_buf_p), 0); assert_memory_equal(axc_buf_get_data(msg_buf_p), axc_buf_get_data(pt_buf_p), axc_buf_get_len(msg_buf_p)); axc_buf_free(msg_buf_p); axc_buf_free(ct_buf_p); axc_buf_free(pt_buf_p); } void test_key_load_public_own(void ** state) { (void) state; axc_buf * key_buf_p; assert_int_not_equal(axc_key_load_public_own(ctx_global_p, &key_buf_p), 0); assert_int_equal(axc_install(ctx_global_p), 0); assert_int_equal(axc_key_load_public_own(ctx_global_p, &key_buf_p), 0); ratchet_identity_key_pair * kp_p; assert_int_equal(signal_protocol_identity_get_key_pair(ctx_global_p->axolotl_store_context_p, &kp_p), 0); axc_buf * db_key_buf_p; assert_int_equal(ec_public_key_serialize(&db_key_buf_p, ratchet_identity_key_pair_get_public(kp_p)), 0); assert_memory_equal(axc_buf_get_data(key_buf_p), axc_buf_get_data(db_key_buf_p), axc_buf_get_len(key_buf_p)); } void test_key_load_public_addr(void ** state) { (void) state; assert_int_equal(axc_session_exists_any("bob", ctx_a_p), 1); assert_int_equal(axc_session_exists_initiated(&addr_bob, ctx_a_p), 1); axc_buf * key_buf_p; assert_int_equal(axc_key_load_public_addr(addr_bob.name, 1337, ctx_a_p, &key_buf_p), 0); assert_int_equal(axc_key_load_public_addr(addr_bob.name, addr_bob.device_id, ctx_a_p, &key_buf_p), 1); session_record * sr_p; assert_int_equal(signal_protocol_session_load_session(ctx_a_p->axolotl_store_context_p, &sr_p, &addr_bob), 0); assert_int_equal(session_record_is_fresh(sr_p), 0); axc_buf * db_key_buf_p; assert_int_equal(ec_public_key_serialize(&db_key_buf_p, session_state_get_remote_identity_key(session_record_get_state(sr_p))), 0); assert_memory_equal(axc_buf_get_data(key_buf_p), axc_buf_get_data(db_key_buf_p), axc_buf_get_len(key_buf_p)); axc_buf_free(key_buf_p); axc_buf_free(db_key_buf_p); SIGNAL_UNREF(sr_p); } int main(void) { const struct CMUnitTest tests[] = { cmocka_unit_test_teardown(test_init, client_teardown), cmocka_unit_test_setup_teardown(test_recursive_mutex_lock, client_setup, client_teardown), cmocka_unit_test_setup_teardown(test_recursive_mutex_unlock, client_setup, client_teardown), cmocka_unit_test_setup_teardown(test_install_should_generate_necessary_data, client_setup, client_teardown), cmocka_unit_test_setup_teardown(test_install_should_not_do_anything_if_already_initialiased, client_setup, client_teardown), cmocka_unit_test_setup_teardown(test_install_should_reset_if_needed, client_setup, client_teardown), cmocka_unit_test_setup_teardown(test_message_encrypt_decrypt, client_setup_sessions, client_teardown_two_dbs), cmocka_unit_test_setup_teardown(test_session_exists_any, client_setup_two_dbs, client_teardown_two_dbs), cmocka_unit_test_setup_teardown(test_session_exists_prekeys, client_setup_two_dbs, client_teardown_two_dbs), cmocka_unit_test_setup_teardown(test_session_from_bundle_and_handle_prekey_message, client_setup_two_dbs, client_teardown_two_dbs), cmocka_unit_test_setup_teardown(test_bundle_collect, client_setup, client_teardown), cmocka_unit_test_setup_teardown(test_key_load_public_own, client_setup, client_teardown), cmocka_unit_test_setup_teardown(test_key_load_public_addr, client_setup_sessions, client_teardown_two_dbs) }; return cmocka_run_group_tests(tests, global_setup, global_teardown); } axc-0.3.7/test/test_store.c000066400000000000000000000773071417527735300156460ustar00rootroot00000000000000/* * Copyright (C) 2017-2020 Richard Bayerle * SPDX-License-Identifier: GPL-3.0-only * Author: Richard Bayerle */ #include #include #include #include #include // remove #include // strlen #include // access #include "../src/axc.c" #include "../src/axc_store.c" sqlite3 * db_p; sqlite3_stmt * pstmt_p; char * db_filename = "test/test.sqlite"; axc_context * ctx_global_p; signal_protocol_address addr_alice_42 = {.name = "alice", .name_len = 5, .device_id = 42}; signal_protocol_address addr_alice_21 = {.name = "alice", .name_len = 5, .device_id = 21}; signal_protocol_address addr_bob_12 = {.name = "bob", .name_len = 3, .device_id = 12}; uint8_t bytes_1[] = {0xB1, 0x6B, 0x00, 0xB5}; size_t bytes_1_len = sizeof(bytes_1); uint8_t bytes_2[] = {0xBA, 0xDF, 0xEE, 0x15}; uint8_t bytes_2_len = sizeof(bytes_2); const int id = 1337; int db_setup_internal(void **state) { (void) state; ctx_global_p = (void *) 0; assert_int_equal(axc_context_create(&ctx_global_p), 0); assert_int_equal(axc_context_set_db_fn(ctx_global_p, db_filename, strlen(db_filename)), 0); db_p = (void *) 0; pstmt_p = (void *) 0; return 0; } int db_setup(void **state) { (void) state; db_setup_internal((void *) 0); assert_int_equal(axc_db_create(ctx_global_p), 0); return 0; } int db_teardown(void ** state) { (void) state; sqlite3_finalize(pstmt_p); sqlite3_close(db_p); axc_context_destroy_all(ctx_global_p); db_p = (void *) 0; pstmt_p = (void *) 0; remove(AXC_DB_DEFAULT_FN); remove(db_filename); return 0; } void test_db_conn_open_should_create_db_default_filename(void **state) { (void) state; axc_context * ctx_p = (void *) 0; assert_int_equal(axc_context_create(&ctx_p), 0); assert_int_equal(db_conn_open(&db_p, &pstmt_p, "", ctx_p), 0); assert_int_equal(access(AXC_DB_DEFAULT_FN, F_OK), 0); axc_context_destroy_all(ctx_p); } void test_db_conn_open_should_create_db(void **state) { (void) state; assert_int_equal(db_conn_open(&db_p, &pstmt_p, "", ctx_global_p), 0); assert_int_not_equal(db_p, 0); assert_int_equal(access(db_filename, F_OK), 0); } void test_db_conn_open_should_prepare_statement(void **state) { (void) state; const char * stmt = "VACUUM;"; assert_int_equal(db_conn_open(&db_p, &pstmt_p, stmt, ctx_global_p), 0); assert_int_not_equal(pstmt_p, (void *) 0); } void test_db_conn_open_should_fail_on_null_pointer(void **state) { (void) state; assert_int_not_equal(db_conn_open(&db_p, &pstmt_p, (void *) 0, ctx_global_p), 0); assert_int_equal(pstmt_p, (void *) 0); } void test_db_exec_single_change_should_only_succeed_on_correct_number_of_changes(void **state) { (void) state; const char * stmt1 = "CREATE TABLE test(id INTEGER);"; const char * stmt2 = "INSERT INTO test VALUES (1)"; assert_int_equal(db_conn_open(&db_p, &pstmt_p, stmt1, ctx_global_p), 0); assert_int_not_equal(db_exec_single_change(db_p, pstmt_p, ctx_global_p), 0); assert_int_equal(db_conn_open(&db_p, &pstmt_p, stmt2, ctx_global_p), 0); assert_int_equal(db_exec_single_change(db_p, pstmt_p, ctx_global_p), 0); } void test_db_exec_quick_should_exec(void **state) { (void) state; const char * stmt1 = "CREATE TABLE test(id INTEGER);"; const char * stmt2 = "INSERT INTO test VALUES (1)"; db_exec_quick(stmt1, ctx_global_p); db_exec_quick(stmt2, ctx_global_p); const char * stmt3 ="SELECT * FROM test;"; assert_int_equal(db_conn_open(&db_p, &pstmt_p, stmt3, ctx_global_p), 0); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); } void test_db_create_should_create_necessary_tables(void **state) { (void) state; char * stmt = "PRAGMA table_info(session_store);"; assert_int_equal(axc_db_create(ctx_global_p), 0); assert_int_equal(db_conn_open(&db_p, &pstmt_p, stmt, ctx_global_p), 0); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_string_equal(sqlite3_column_text(pstmt_p, 1), "name"); assert_string_equal(sqlite3_column_text(pstmt_p, 2), "TEXT"); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_string_equal(sqlite3_column_text(pstmt_p, 1), "name_len"); assert_string_equal(sqlite3_column_text(pstmt_p, 2), "INTEGER"); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_string_equal(sqlite3_column_text(pstmt_p, 1), "device_id"); assert_string_equal(sqlite3_column_text(pstmt_p, 2), "INTEGER"); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_string_equal(sqlite3_column_text(pstmt_p, 1), "session_record"); assert_string_equal(sqlite3_column_text(pstmt_p, 2), "BLOB"); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_string_equal(sqlite3_column_text(pstmt_p, 1), "record_len"); assert_string_equal(sqlite3_column_text(pstmt_p, 2), "INTEGER"); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_DONE); assert_int_equal(sqlite3_finalize(pstmt_p), SQLITE_OK); stmt = "PRAGMA table_info(pre_key_store);"; assert_int_equal(sqlite3_prepare_v2(db_p, stmt, -1, &pstmt_p, (void *) 0), SQLITE_OK); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_string_equal(sqlite3_column_text(pstmt_p, 1), "id"); assert_string_equal(sqlite3_column_text(pstmt_p, 2), "INTEGER"); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_string_equal(sqlite3_column_text(pstmt_p, 1), "pre_key_record"); assert_string_equal(sqlite3_column_text(pstmt_p, 2), "BLOB"); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_string_equal(sqlite3_column_text(pstmt_p, 1), "record_len"); assert_string_equal(sqlite3_column_text(pstmt_p, 2), "INTEGER"); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_DONE); assert_int_equal(sqlite3_finalize(pstmt_p), SQLITE_OK); stmt = "PRAGMA table_info(signed_pre_key_store);"; assert_int_equal(sqlite3_prepare_v2(db_p, stmt, -1, &pstmt_p, (void *) 0), SQLITE_OK); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_string_equal(sqlite3_column_text(pstmt_p, 1), "id"); assert_string_equal(sqlite3_column_text(pstmt_p, 2), "INTEGER"); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_string_equal(sqlite3_column_text(pstmt_p, 1), "signed_pre_key_record"); assert_string_equal(sqlite3_column_text(pstmt_p, 2), "BLOB"); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_string_equal(sqlite3_column_text(pstmt_p, 1), "record_len"); assert_string_equal(sqlite3_column_text(pstmt_p, 2), "INTEGER"); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_DONE); assert_int_equal(sqlite3_finalize(pstmt_p), SQLITE_OK); stmt = "PRAGMA table_info(identity_key_store);"; assert_int_equal(sqlite3_prepare_v2(db_p, stmt, -1, &pstmt_p, (void *) 0), SQLITE_OK); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_string_equal(sqlite3_column_text(pstmt_p, 1), "name"); assert_string_equal(sqlite3_column_text(pstmt_p, 2), "TEXT"); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_string_equal(sqlite3_column_text(pstmt_p, 1), "key"); assert_string_equal(sqlite3_column_text(pstmt_p, 2), "BLOB"); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_string_equal(sqlite3_column_text(pstmt_p, 1), "key_len"); assert_string_equal(sqlite3_column_text(pstmt_p, 2), "INTEGER"); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_string_equal(sqlite3_column_text(pstmt_p, 1), "trusted"); assert_string_equal(sqlite3_column_text(pstmt_p, 2), "INTEGER"); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_DONE); assert_int_equal(sqlite3_finalize(pstmt_p), SQLITE_OK); stmt = "PRAGMA table_info(settings);"; assert_int_equal(sqlite3_prepare_v2(db_p, stmt, -1, &pstmt_p, (void *) 0), SQLITE_OK); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_string_equal(sqlite3_column_text(pstmt_p, 1), "name"); assert_string_equal(sqlite3_column_text(pstmt_p, 2), "TEXT"); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_string_equal(sqlite3_column_text(pstmt_p, 1), "property"); assert_string_equal(sqlite3_column_text(pstmt_p, 2), "INTEGER"); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_DONE); } void test_db_destroy_should_drop_all_tables(void **state) { (void) state; char * stmt = "PRAGMA table_info(session_store);"; assert_int_equal(axc_db_create(ctx_global_p), 0); assert_int_equal(axc_db_destroy(ctx_global_p), 0); assert_int_equal(db_conn_open(&db_p, &pstmt_p, stmt, ctx_global_p), 0); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_DONE); stmt = "PRAGMA table_info(pre_key_store);"; assert_int_equal(sqlite3_prepare_v2(db_p, stmt, -1, &pstmt_p, (void *) 0), SQLITE_OK); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_DONE); assert_int_equal(sqlite3_finalize(pstmt_p), SQLITE_OK); stmt = "PRAGMA table_info(signed_pre_key_store);"; assert_int_equal(sqlite3_prepare_v2(db_p, stmt, -1, &pstmt_p, (void *) 0), SQLITE_OK); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_DONE); assert_int_equal(sqlite3_finalize(pstmt_p), SQLITE_OK); stmt = "PRAGMA table_info(identity_key_store);"; assert_int_equal(sqlite3_prepare_v2(db_p, stmt, -1, &pstmt_p, (void *) 0), SQLITE_OK); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_DONE); assert_int_equal(sqlite3_finalize(pstmt_p), SQLITE_OK); stmt = "PRAGMA table_info(settings);"; assert_int_equal(sqlite3_prepare_v2(db_p, stmt, -1, &pstmt_p, (void *) 0), SQLITE_OK); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_DONE); } void test_db_property_set_should_set_property_correctly(void **state) { (void) state; assert_int_equal(axc_db_property_set("test", 1337, ctx_global_p), 0); assert_int_equal(db_conn_open(&db_p, &pstmt_p, "SELECT property FROM settings WHERE name='test';", ctx_global_p), 0); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_int_equal(sqlite3_column_int(pstmt_p, 0), 1337); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_DONE); } void test_db_property_get_should_get_correctly(void **state) { (void) state; const char * prop_name = "test"; const int prop_val = 1337; assert_int_equal(axc_db_property_set(prop_name, prop_val, ctx_global_p), 0); int result = 0; assert_int_equal(axc_db_property_get(prop_name, &result, ctx_global_p), 0); assert_int_equal(result, prop_val); } void test_db_property_get_should_fail_on_no_results(void **state) { (void) state; int result = 0; assert_int_not_equal(axc_db_property_get("test", &result, ctx_global_p), 0); } void test_db_init_status_set_should_work(void **state) { (void) state; const int val = 1337; assert_int_equal(axc_db_init_status_set(val, ctx_global_p), 0); int result = 0; assert_int_equal(axc_db_property_get(INIT_STATUS_NAME, &result, ctx_global_p), 0); assert_int_equal(result, val); } void test_db_init_status_get_should_work(void **state) { (void) state; const int val = 1337; assert_int_equal(axc_db_init_status_set(val, ctx_global_p), 0); int result = 0; assert_int_equal(axc_db_init_status_get(&result, ctx_global_p), 0); assert_int_equal(result, val); } void test_db_session_store_should_work(void **state) { (void) state; assert_int_equal(axc_db_session_store(&addr_alice_42, bytes_1, bytes_1_len, (void *) 0, 0, ctx_global_p), 0); assert_int_equal(db_conn_open(&db_p, &pstmt_p, "SELECT * FROM session_store WHERE name='alice' AND device_id IS 42;", ctx_global_p), 0); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_string_equal(sqlite3_column_text(pstmt_p, 0), addr_alice_42.name); assert_int_equal(sqlite3_column_int(pstmt_p, 1), strlen(addr_alice_42.name)); assert_int_equal(sqlite3_column_int(pstmt_p, 2), addr_alice_42.device_id); assert_memory_equal(sqlite3_column_blob(pstmt_p, 3), bytes_1, bytes_1_len); assert_int_equal(sqlite3_column_int(pstmt_p, 4), bytes_1_len); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_DONE); } void test_db_session_load_should_find_session(void **state) { (void) state; assert_int_equal(axc_db_session_store(&addr_alice_42, bytes_1, bytes_1_len, (void *) 0, 0, ctx_global_p), 0); signal_buffer * buf = (void *) 0; assert_int_equal(axc_db_session_load(&buf, (void *) 0, &addr_alice_42, ctx_global_p), 1); assert_memory_equal(signal_buffer_data(buf), bytes_1, bytes_1_len); assert_int_equal(signal_buffer_len(buf), bytes_1_len); } void test_db_session_load_should_not_find_session(void **state) { (void) state; signal_buffer * buf = (void *) 0; assert_int_equal(axc_db_session_load(&buf, (void *) 0, &addr_alice_42, ctx_global_p), 0); } void test_db_session_get_sub_device_sessions_should_find_and_return_correct_number(void **state) { (void) state; assert_int_equal(axc_db_session_store(&addr_alice_42, bytes_1, bytes_1_len, (void *) 0, 0, ctx_global_p), 0); assert_int_equal(axc_db_session_store(&addr_alice_21, bytes_2, bytes_2_len, (void *) 0, 0, ctx_global_p), 0); signal_int_list * list_a = (void *) 0; assert_int_equal(axc_db_session_get_sub_device_sessions(&list_a, addr_alice_42.name, addr_alice_42.name_len, ctx_global_p), 2); signal_int_list * list_b = (void *) 0; assert_int_equal(axc_db_session_get_sub_device_sessions(&list_b, addr_bob_12.name, addr_bob_12.name_len, ctx_global_p), 0); assert_int_equal(signal_int_list_size(list_a), 2); assert_int_equal(signal_int_list_size(list_b), 0); } void test_db_session_contains_should_return_correct_values(void ** state) { (void) state; char * a_db_filename = "test/a.sqlite"; char * b_db_filename = "test/b.sqlite"; axc_context * ctx_a_p = (void *) 0; axc_context * ctx_b_p = (void *) 0; signal_protocol_address addr_alice = {.name = "alice", .name_len = 5, .device_id = 0}; axc_address addr_bob = {.name = "bob", .name_len = 3, .device_id = 0}; assert_int_equal(axc_context_create(&ctx_a_p), 0); assert_int_equal(axc_context_create(&ctx_b_p), 0); assert_int_equal(axc_context_set_db_fn(ctx_a_p, a_db_filename, strlen(a_db_filename)), 0); assert_int_equal(axc_context_set_db_fn(ctx_b_p, b_db_filename, strlen(b_db_filename)), 0); assert_int_equal(axc_init(ctx_a_p), 0); assert_int_equal(axc_init(ctx_b_p), 0); assert_int_equal(axc_install(ctx_a_p), 0); assert_int_equal(axc_install(ctx_b_p), 0); assert_int_equal(axc_db_session_contains(&addr_alice, ctx_b_p), 0); assert_int_equal(axc_db_session_contains(&addr_bob, ctx_a_p), 0); axc_bundle * bundle_bob_p; assert_int_equal(axc_bundle_collect(AXC_PRE_KEYS_AMOUNT, ctx_b_p, &bundle_bob_p), 0); addr_bob.device_id = bundle_bob_p->registration_id; assert_int_equal(axc_session_from_bundle(axc_buf_list_item_get_id(bundle_bob_p->pre_keys_head_p), axc_buf_list_item_get_buf(bundle_bob_p->pre_keys_head_p), bundle_bob_p->signed_pre_key_id, bundle_bob_p->signed_pre_key_public_serialized_p, bundle_bob_p->signed_pre_key_signature_p, bundle_bob_p->identity_key_public_serialized_p, &addr_bob, ctx_a_p), 0); const char * data = "hello"; axc_buf * msg_buf_p = axc_buf_create((uint8_t *)data, strlen(data) + 1); assert_ptr_not_equal(msg_buf_p, (void *) 0); axc_buf * ct_buf_p; assert_int_equal(axc_message_encrypt_and_serialize(msg_buf_p, &addr_bob, ctx_a_p, &ct_buf_p), 0); uint32_t alice_id; assert_int_equal(axc_get_device_id(ctx_a_p, &alice_id), 0); addr_alice.device_id = alice_id; axc_buf * pt_buf_p; assert_int_equal(axc_pre_key_message_process(ct_buf_p, &addr_alice, ctx_b_p, &pt_buf_p), 0); assert_int_equal(axc_session_exists_initiated(&addr_bob, ctx_a_p), 1); assert_int_equal(axc_session_exists_initiated(&addr_alice, ctx_b_p), 1); axc_buf_free(msg_buf_p); axc_buf_free(ct_buf_p); axc_buf_free(pt_buf_p); axc_cleanup(ctx_a_p); axc_cleanup(ctx_b_p); remove(a_db_filename); remove(b_db_filename); } void test_db_session_delete_should_return_correct_values(void **state) { (void) state; assert_int_equal(axc_db_session_delete(&addr_alice_21, ctx_global_p), 0); assert_int_equal(axc_db_session_store(&addr_alice_42, bytes_1, bytes_1_len, (void *) 0, 0, ctx_global_p), 0); assert_int_equal(axc_db_session_delete(&addr_alice_42, ctx_global_p), 1); } void test_db_session_delete_all_should_return_correct_values(void **state) { (void) state; signal_int_list * sessions = (void *) 0; assert_int_equal(axc_db_session_store(&addr_alice_42, bytes_1, bytes_1_len, (void *) 0, 0, ctx_global_p), 0); assert_int_equal(axc_db_session_store(&addr_alice_21, bytes_2, bytes_2_len, (void *) 0, 0, ctx_global_p), 0); assert_int_equal(axc_db_session_get_sub_device_sessions(&sessions, addr_alice_42.name, addr_alice_42.name_len, ctx_global_p), 2); assert_int_equal(axc_db_session_delete_all(addr_alice_42.name, addr_alice_42.name_len, ctx_global_p), 2); assert_int_equal(axc_db_session_get_sub_device_sessions(&sessions, addr_alice_42.name, addr_alice_42.name_len, ctx_global_p), 0); } void test_db_pre_key_store_should_work(void **state) { (void) state; assert_int_equal(axc_db_pre_key_store(1337, bytes_1, bytes_1_len, ctx_global_p), 0); assert_int_equal(db_conn_open(&db_p, &pstmt_p, "SELECT * FROM pre_key_store WHERE id IS 1337;", ctx_global_p), 0); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_int_equal(sqlite3_column_int(pstmt_p, 0), 1337); assert_memory_equal(sqlite3_column_blob(pstmt_p, 1), bytes_1, bytes_1_len); assert_int_equal(sqlite3_column_int(pstmt_p, 2), bytes_1_len); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_DONE); } void test_db_pre_key_load_should_return_correct_values_and_key(void **state) { (void) state; assert_int_equal(axc_db_pre_key_store(id, bytes_1, bytes_1_len, ctx_global_p), 0); signal_buffer * buf = (void *) 0; assert_int_equal(axc_db_pre_key_load(&buf, id, ctx_global_p), SG_SUCCESS); assert_memory_equal(signal_buffer_data(buf), bytes_1, bytes_1_len); assert_int_equal(axc_db_pre_key_load(&buf, id + 1, ctx_global_p), SG_ERR_INVALID_KEY_ID); } void test_db_pre_key_contains_should_return_correct_values(void **state) { (void) state; assert_int_equal(axc_db_pre_key_store(id, bytes_1, bytes_1_len, ctx_global_p), 0); assert_int_equal(axc_db_pre_key_contains(id, ctx_global_p), 1); assert_int_equal(axc_db_pre_key_contains(id + 1, ctx_global_p), 0); } void test_db_pre_key_remove(void **state) { (void) state; assert_int_not_equal(axc_db_pre_key_remove(id, ctx_global_p), 0); assert_int_equal(axc_db_pre_key_store(id, bytes_1, bytes_1_len, ctx_global_p), 0); assert_int_equal(axc_db_pre_key_remove(id, ctx_global_p), 0); assert_int_equal(axc_db_pre_key_contains(id, ctx_global_p), 0); } void test_db_pre_key_store_list(void **state) { (void) state; const int pre_key_num = 5; char stmt[100]; axc_context * ctx_p = (void *) 0; assert_int_equal(axc_context_create(&ctx_p), 0); assert_int_equal(axc_context_set_db_fn(ctx_p, db_filename, strlen(db_filename)), 0); assert_int_equal(axc_init(ctx_p), 0); signal_protocol_key_helper_pre_key_list_node * pre_keys_head_p = (void *) 0; // for some reason, key IDs is not inclusive and starts at +1! assert_int_equal(signal_protocol_key_helper_generate_pre_keys(&pre_keys_head_p, 0, pre_key_num, ctx_p->axolotl_global_context_p), 0); assert_int_equal(axc_db_pre_key_store_list(pre_keys_head_p, ctx_p), 0); assert_int_not_equal(sprintf(stmt, "SELECT count(*) FROM pre_key_store;"), 0); assert_int_equal(db_conn_open(&db_p, &pstmt_p, stmt, ctx_p), 0); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_int_equal(sqlite3_column_int(pstmt_p, 0), pre_key_num); assert_int_equal(sqlite3_finalize(pstmt_p), SQLITE_OK); session_pre_key * pre_key_p = signal_protocol_key_helper_key_list_element(pre_keys_head_p); assert_ptr_not_equal(pre_key_p, (void *) 0); signal_buffer * key_buf_p = (void *) 0; assert_int_equal(session_pre_key_serialize(&key_buf_p, pre_key_p), 0); assert_int_not_equal(sprintf(stmt, "SELECT * FROM pre_key_store WHERE id IS %i;", session_pre_key_get_id(pre_key_p)), 0); assert_int_equal(sqlite3_prepare_v2(db_p, stmt, -1, &pstmt_p, (void *) 0), SQLITE_OK); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_int_equal(sqlite3_column_int(pstmt_p, 0), session_pre_key_get_id(pre_key_p)); assert_memory_equal(sqlite3_column_blob(pstmt_p, 1), signal_buffer_data(key_buf_p), signal_buffer_len(key_buf_p)); assert_int_equal(sqlite3_column_int(pstmt_p, 2), signal_buffer_len(key_buf_p)); } void test_db_pre_key_get_list(void ** state) { (void) state; assert_int_equal(axc_init(ctx_global_p), 0); assert_int_equal(axc_install(ctx_global_p), 0); axc_buf_list_item * head_p = (void *) 0; assert_int_equal(axc_db_pre_key_get_list(AXC_PRE_KEYS_AMOUNT, ctx_global_p, &head_p), 0); assert_ptr_not_equal(head_p, (void *) 0); axc_buf_list_item * curr = head_p; int count = 0; ec_public_key * pre_key_public_p = (void *) 0; axc_buf * buf_p = (void *) 0; while (curr) { count++; buf_p = axc_buf_list_item_get_buf(curr); assert_int_equal(curve_decode_point(&pre_key_public_p, axc_buf_get_data(buf_p), axc_buf_get_len(buf_p), ctx_global_p->axolotl_global_context_p), 0); SIGNAL_UNREF(pre_key_public_p); curr = curr->next_p; } assert_int_equal(count, AXC_PRE_KEYS_AMOUNT); axc_buf_list_free(head_p); } void test_db_pre_key_get_max_id(void ** state) { (void) state; assert_int_equal(axc_init(ctx_global_p), 0); assert_int_equal(axc_install(ctx_global_p), 0); uint32_t id = 10; assert_int_equal(axc_db_pre_key_get_max_id(ctx_global_p, &id), 0); assert_int_equal(id, AXC_PRE_KEYS_AMOUNT - 1); // ids start with 0 } void test_db_signed_pre_key_store_should_work(void **state) { (void) state; assert_int_equal(axc_db_signed_pre_key_store(1337, bytes_1, bytes_1_len, ctx_global_p), 0); assert_int_equal(db_conn_open(&db_p, &pstmt_p, "SELECT * FROM signed_pre_key_store WHERE id IS 1337;", ctx_global_p), 0); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_int_equal(sqlite3_column_int(pstmt_p, 0), 1337); assert_memory_equal(sqlite3_column_blob(pstmt_p, 1), bytes_1, bytes_1_len); assert_int_equal(sqlite3_column_int(pstmt_p, 2), bytes_1_len); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_DONE); } void test_db_signed_pre_key_load_should_return_correct_values_and_key(void **state) { (void) state; assert_int_equal(axc_db_signed_pre_key_store(id, bytes_1, bytes_1_len, ctx_global_p), 0); signal_buffer * buf = (void *) 0; assert_int_equal(axc_db_signed_pre_key_load(&buf, id, ctx_global_p), SG_SUCCESS); assert_memory_equal(signal_buffer_data(buf), bytes_1, bytes_1_len); assert_int_equal(axc_db_signed_pre_key_load(&buf, id + 1, ctx_global_p), SG_ERR_INVALID_KEY_ID); } void test_db_signed_pre_key_contains_should_return_correct_values(void **state) { (void) state; assert_int_equal(axc_db_signed_pre_key_store(id, bytes_1, bytes_1_len, ctx_global_p), 0); assert_int_equal(axc_db_signed_pre_key_contains(id, ctx_global_p), 1); assert_int_equal(axc_db_signed_pre_key_contains(id + 1, ctx_global_p), 0); } void test_db_signed_pre_key_remove(void **state) { (void) state; assert_int_not_equal(axc_db_signed_pre_key_remove(id, ctx_global_p), 0); assert_int_equal(axc_db_signed_pre_key_store(id, bytes_1, bytes_1_len, ctx_global_p), 0); assert_int_equal(axc_db_signed_pre_key_remove(id, ctx_global_p), 0); assert_int_equal(axc_db_signed_pre_key_contains(id, ctx_global_p), 0); } void test_db_identity_set_and_get_key_pair(void **state) { (void) state; axc_context * ctx_p = (void *) 0; assert_int_equal(axc_context_create(&ctx_p), 0); assert_int_equal(axc_context_set_db_fn(ctx_p, db_filename, strlen(db_filename)), 0); assert_int_equal(axc_init(ctx_p), 0); ratchet_identity_key_pair * identity_key_pair_p = (void *) 0; assert_int_equal(signal_protocol_key_helper_generate_identity_key_pair(&identity_key_pair_p, ctx_p->axolotl_global_context_p), 0); assert_int_equal(axc_db_identity_set_key_pair(identity_key_pair_p, ctx_p), 0); signal_buffer * pubkey_saved_p = (void *) 0; signal_buffer * privkey_saved_p = (void *) 0; assert_int_equal(axc_db_identity_get_key_pair(&pubkey_saved_p, &privkey_saved_p, ctx_p), 0); signal_buffer * pubkey_orig_p = (void *) 0; signal_buffer * privkey_orig_p = (void *) 0; assert_int_equal(ec_public_key_serialize(&pubkey_orig_p, ratchet_identity_key_pair_get_public(identity_key_pair_p)), 0); assert_memory_equal(signal_buffer_data(pubkey_orig_p), signal_buffer_data(pubkey_saved_p), signal_buffer_len(pubkey_saved_p)); assert_int_equal(ec_private_key_serialize(&privkey_orig_p, ratchet_identity_key_pair_get_private(identity_key_pair_p)), 0); assert_memory_equal(signal_buffer_data(privkey_orig_p), signal_buffer_data(privkey_saved_p), signal_buffer_len(privkey_saved_p)); signal_buffer_free(pubkey_orig_p); signal_buffer_free(pubkey_saved_p); signal_buffer_free(privkey_orig_p); signal_buffer_free(privkey_saved_p); } void test_db_identity_get_key_pair_keys_not_found(void ** state) { (void) state; assert_int_equal(axc_db_identity_get_key_pair((void * ) 0, (void *) 0, ctx_global_p), SG_ERR_INVALID_KEY_ID); axc_context * ctx_p = (void *) 0; assert_int_equal(axc_context_create(&ctx_p), 0); assert_int_equal(axc_context_set_db_fn(ctx_p, db_filename, strlen(db_filename)), 0); assert_int_equal(axc_init(ctx_p), 0); assert_int_equal(axc_install(ctx_p), 0); char stmt[100]; assert_int_not_equal(sprintf(stmt, "DELETE FROM identity_key_store WHERE name IS '%s';", OWN_PRIVATE_KEY_NAME), 0); assert_int_equal(db_conn_open(&db_p, &pstmt_p, stmt, ctx_p), 0); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_DONE); assert_int_equal(axc_db_identity_get_key_pair((void *) 0, (void *) 0, ctx_p), SG_ERR_INVALID_KEY_ID); } void test_db_identity_set_local_registration_id(void ** state) { (void) state; assert_int_equal(axc_db_identity_set_local_registration_id(id, ctx_global_p), 0); int result = 0; assert_int_equal(axc_db_property_get(REG_ID_NAME, &result, ctx_global_p), 0); assert_int_equal(id, result); } void test_db_identity_get_local_registration_id(void **state) { (void) state; assert_int_equal(axc_db_identity_set_local_registration_id(id, ctx_global_p), 0); uint32_t result = 0; assert_int_equal(axc_db_identity_get_local_registration_id(ctx_global_p, &result), 0); assert_int_equal(id, result); } void test_db_identity_save(void **state) { (void) state; assert_int_equal(axc_db_identity_save(&addr_alice_21, bytes_1, bytes_1_len, ctx_global_p), 0); const char * stmt = "SELECT * FROM identity_key_store WHERE name='alice';"; assert_int_equal(db_conn_open(&db_p, &pstmt_p, stmt, ctx_global_p), 0); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_ROW); assert_string_equal(sqlite3_column_text(pstmt_p, 0), addr_alice_21.name); assert_memory_equal(sqlite3_column_blob(pstmt_p, 1), bytes_1, bytes_1_len); assert_int_equal(sqlite3_column_int(pstmt_p, 2), bytes_1_len); assert_int_equal(sqlite3_column_int(pstmt_p, 3), IDENTITY_KEY_TRUSTED); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_DONE); assert_int_equal(axc_db_identity_save(&addr_alice_21, (void *) 0, 0, ctx_global_p), 0); assert_int_equal(sqlite3_reset(pstmt_p), SQLITE_OK); assert_int_equal(sqlite3_step(pstmt_p), SQLITE_DONE); } /* void test_db_identity_is_trusted(void **state) { (void) state; assert_int_equal(axc_db_identity_save(addr_alice_21.name, 0, bytes_1, bytes_1_len, ctx_global_p), 0); assert_int_equal(axc_db_identity_is_trusted(addr_alice_21.name, addr_alice_21.name_len, bytes_1, bytes_1_len, ctx_global_p), 1); assert_int_equal(axc_db_identity_is_trusted(addr_alice_21.name, addr_alice_21.name_len, bytes_2, bytes_2_len, ctx_global_p), 0); assert_int_equal(axc_db_identity_is_trusted(addr_bob_12.name, addr_bob_12.name_len, bytes_2, bytes_2_len, ctx_global_p), 1); } */ int main(void) { const struct CMUnitTest tests[] = { cmocka_unit_test_setup_teardown(test_db_conn_open_should_create_db_default_filename, db_setup_internal, db_teardown), cmocka_unit_test_setup_teardown(test_db_conn_open_should_create_db, db_setup_internal, db_teardown), cmocka_unit_test_setup_teardown(test_db_conn_open_should_prepare_statement, db_setup_internal, db_teardown), cmocka_unit_test_setup_teardown(test_db_conn_open_should_fail_on_null_pointer, db_setup_internal, db_teardown), cmocka_unit_test_setup_teardown(test_db_exec_single_change_should_only_succeed_on_correct_number_of_changes, db_setup_internal, db_teardown), cmocka_unit_test_setup_teardown(test_db_exec_quick_should_exec, db_setup_internal, db_teardown), cmocka_unit_test_setup_teardown(test_db_create_should_create_necessary_tables, db_setup_internal, db_teardown), cmocka_unit_test_setup_teardown(test_db_destroy_should_drop_all_tables, db_setup_internal, db_teardown), cmocka_unit_test_setup_teardown(test_db_property_set_should_set_property_correctly, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_property_get_should_get_correctly, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_property_get_should_fail_on_no_results, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_init_status_set_should_work, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_init_status_get_should_work, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_session_store_should_work, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_session_load_should_find_session, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_session_load_should_not_find_session, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_session_get_sub_device_sessions_should_find_and_return_correct_number, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_session_contains_should_return_correct_values, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_session_delete_should_return_correct_values, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_session_delete_all_should_return_correct_values, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_pre_key_store_should_work, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_pre_key_store_list, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_pre_key_get_list, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_pre_key_load_should_return_correct_values_and_key, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_pre_key_contains_should_return_correct_values, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_pre_key_remove, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_pre_key_get_max_id, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_signed_pre_key_store_should_work, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_signed_pre_key_load_should_return_correct_values_and_key, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_signed_pre_key_contains_should_return_correct_values, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_signed_pre_key_remove, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_identity_set_local_registration_id, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_identity_get_local_registration_id, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_identity_set_and_get_key_pair, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_identity_save, db_setup, db_teardown), //cmocka_unit_test_setup_teardown(test_db_identity_is_trusted, db_setup, db_teardown), cmocka_unit_test_setup_teardown(test_db_identity_get_key_pair_keys_not_found, db_setup, db_teardown) }; return cmocka_run_group_tests(tests, NULL, NULL); }