pax_global_header00006660000000000000000000000064147330520300014507gustar00rootroot0000000000000052 comment=d760187cac5180b920451fb87e4ffcb94a94a436 opaque-store-0.2.0/000077500000000000000000000000001473305203000141325ustar00rootroot00000000000000opaque-store-0.2.0/.gitignore000066400000000000000000000000511473305203000161160ustar00rootroot00000000000000.arch/ .zig-cache/ __pycache__/ zig-out/ opaque-store-0.2.0/LICENSE000066400000000000000000001045131473305203000151430ustar00rootroot00000000000000 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. Copyright (C) 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: Copyright (C) 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 . opaque-store-0.2.0/README.md000066400000000000000000000030701473305203000154110ustar00rootroot00000000000000# OPAQUE-Store OPAQUE-Store is a simple protocol that allows anyone to store encrypted blobs of information online, with only a password needed to retrieve the information. As the name implies it uses the OPAQUE protocol to do so. OPAQUE-Store uses the `export_key` feature of OPAQUE to encrypt the data that is stored on the OPAQUE-Storage server. You might want to read this blog-post on this topic and on more info: `https://www.ctrlc.hu/~stef/blog/posts/How_to_recover_static_secrets_using_OPAQUE.html` OPAQUE-Store goes beyond the original OPAQUE protocol as specified by the IRTF/CFRG and also supports a threshold variant of OPAQUE. In a threshold setup you have a number N of servers that all hold a share of your secret and at least a threshold number T of these need to cooperate to recover the secret. This provides extra robustness and dillution of responsibility (losing a server is not the end of the world!) while at the same time increases security, as an attacker now has to compromise at least T servers to get access to some information. This project is funded through [NGI0 Entrust](https://nlnet.nl/entrust), a fund established by [NLnet](https://nlnet.nl) with financial support from the European Commission's [Next Generation Internet](https://ngi.eu) program. Learn more at the [NLnet project page](https://nlnet.nl/project/ThresholdOPRF). [NLnet foundation logo](https://nlnet.nl) [NGI Zero Logo](https://nlnet.nl/entrust) opaque-store-0.2.0/client/000077500000000000000000000000001473305203000154105ustar00rootroot00000000000000opaque-store-0.2.0/client/LICENSE000066400000000000000000001045131473305203000164210ustar00rootroot00000000000000 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. Copyright (C) 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: Copyright (C) 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 . opaque-store-0.2.0/client/MANIFEST.in000066400000000000000000000000371473305203000171460ustar00rootroot00000000000000include README.md include *.py opaque-store-0.2.0/client/README.md000066400000000000000000000221401473305203000166660ustar00rootroot00000000000000# OPAQUE-Store OPAQUE-Store is a simple protocol that allows anyone to store encrypted blobs of information online, with only a password needed to retrieve the information. As the name implies it uses the OPAQUE protocol to do so. OPAQUE-Store uses the `export_key` feature of OPAQUE to encrypt the data that is stored on the OPAQUE-Storage server. You might want to read this blog-post on this topic and on more info: `https://www.ctrlc.hu/~stef/blog/posts/How_to_recover_static_secrets_using_OPAQUE.html` OPAQUE-Store goes beyond the original OPAQUE protocol as specified by the IRTF/CFRG and also supports a threshold variant of OPAQUE. In a threshold setup you have a number N of servers that all hold a share of your secret and at least a threshold number T of these need to cooperate to recover the secret. This provides extra robustness and dillution of responsibility (losing a server is not the end of the world!) while at the same time increases security, as an attacker now has to compromise at least T servers to get access to some information. ## Installation opaquestore depends on https://github.com/stef/libopaque/ which in turn depends on - libsodium, - https://github.com/stef/pysodium available on pypi, - https://github.com/stef/liboprf, and - pyoprf (part of https://github.com/stef/liboprf) available on pypi. When you have a working libopaque, a simple `pip install opaquestore` should get you started. ## Configuration Configuration will be looked for in the following order - /etc/opaque-store/config - ~/.config/opaque-store/config - ~/.opaque-storerc - ./opaque-store.cfg For an example and documentation on the values in the config files see: `opaque-store.cfg` for the client configuration, and - in case you want to run your own server(s) - `opaque-stored.cfg` for the server configuration. Example configuration with inline comments about each value: ``` [client] # you must change this value, it ensures that your record ids are # unique you must also make sure to not lose this value, if you do, # you lose access to your records. id_salt="Please_MUST-be_changed! and backed up to something difficult to guess" # the number of servers successfully participating in an # operation. must be less than 129, but lower 1 digit number are # probable the most robust. threshold=2 # the time in seconds a distributed keygen (DKG) protocol message is # considered fresh. anything older than this is considered invalid and # aborts a DKG. Higher values help with laggy links, lower values can # be fine if you have high-speed connections to all servers. ts_epsilon=1200 # the list of servers, must be 1 item, if threshold is 1, or one more # than threshold. [servers] [servers.zero] # address of server host="127.0.0.1" # port where server is running port=23000 # self-signed public key of the server # - not needed for proper Lets Encrypt certs ssl_cert = "/etc/opaquestore/zero/cert.pem" ltsigkey="/etc/opaquestore/zero/zero.pub" [servers.eins] # address of server host="127.0.0.1" # port where server is running port=23001 # public key of the server ltsigkey="/etc/opaquestore/eins/eins.pub" [servers.dva] # address of server host="127.0.0.1" # port where server is running port=23002 # public key of the server ltsigkey="/etc/opaquestore/dva/dva.pub" ``` ## Threshold setup The client config file, contains a `[servers]` section which lists all servers you want to use in a threshold setup. Each server has an `address`, `port` and `ltsigkey` variable that needs to be set accordingly. In case your server runs with a self-signed certificate there is a `ssl_cert` variable that can pin it to the correct cert. It is also important to note, that the name of the server - which is given after a dot in the `[servers.name]` sub-section title is also used to generate record ids specific to that server. Thus once chosen, it should not change, unless you want to lose access to the records on that server. The name doesn't have to be unique by users, but should be unique among all configured servers in this setup, this guarantees that for a record each server has a different record it and thus makes the records unlinkable across servers. In the config files `[client]` section the `threshold` variable specifies the threshold for the setup. The minimum sane configuration for a threshold setup is `threshold=2` with at least 3 servers listed. The maximum of servers is 128, but that is way too many, a reasonable max is around 16 or so. ## Command-line usage and examples It is warmly recommended to use pwdsphinx (https://github.com/stef/pwdsphinx) as a front-end to opaquestore, since it handles passwords in a most secure manner. If you want to use a different password manager, you can use the CLI interface documented below. ### Passwords and Records opaquestore takes the password always on the standard input. If you are creating or updating a record, the record itself is also expected on the standard input. The password and the record - if required - are separated by a newline character. ### KeyIds KeyIds are the identifiers that you use to address your records, they can be any kind of string. Internally this keyId is hashed using the `id_salt` from the configurations `[client]` section into a unique identifier. It is very warmly recommended to set this to some random value, and to back this value up. As this salt is necessary to access your records. If you use a commonly used salt (i.e. the default salt) chances are high that there are collisions for record ids, and that people can guess your record ids. ### Store a new record Storing a record needs 3 parameters: - the password, on standard input, terminated by a newline. - the record itself until the end of the standard input - and a keyId with which you can reference and act on this record ```sh $ echo -en 'password\ntoken2store' | opaquestore create ``` Here is a contrived example: ``` echo -en "mypassword\!sMyV0ice\nmy secretty token data that i need to protect and store using opaque" | opaquestore create myfirstblob ``` In this example: - the password is "mypassword!sMyV0ice" - the record is: "my secretty token data that i need to protect and store using opaque" - and the keyId is "myfirstblob" ### Get a record Retrieving a record has to parameters: - the password on standard input - the keyId as the 2nd parameter to `opaquestore` ```sh $ echo -n 'password' | opaquestore get ``` An example fetching the record created in the previous example: ``` echo -en "mypassword\!sMyV0ice" | opaquestore get myfirstblob ``` ### Update a record It is possible to update a record in place, it is essentially the same as the creation of a record. It is important to note, that this operation only succeeds, if all servers need to process this request, not only those needed for matching the threshold, you want to update the record on all servers not just some. ```sh $ echo -en 'password\ntoken2update' | opaquestore update ``` If you do not care if some servers will not be updated and you really know what you are doing, you can use the alternative command `force-update`, in this case the operation will succeed if at least the threshold is matched. Note however if any of the servers that did not participate in the forced update will participate in later operations will corrupt later operations, so you might want to remove those servers from your config. ```sh $ echo -en 'password\ntoken2update' | opaquestore force-update ``` ### Delete a record Deleting a record is very straight forward, you need your password and keyId, and ensure that all servers that store this record will all be available. The operation will fail if some servers are not available. ```sh $ echo -n 'password' | opaquestore delete ``` Similarly to the update operation there is also a forced delete operation, which will succeed if at least the threshold is matched. Servers not available during this forced delete will still hold the record, if your setup has a n-out-of-2*n setup could mean that you still have enough shares even after a forced-delete. ```sh $ echo -n 'password' | opaquestore force-delete ``` ### Get some recovery-tokens An attacker might be trying different passwords for your record, after a certain amount of consecutive password failures (by default 3) the server locks down the record. A locked record can only be unlocked with a recovery-token. It is not possible to ask for recovery-tokens when a record is already locked. ```sh $ echo -n 'password' | opaquestore recovery-tokens ``` ### Unlock a locked record using a recovery token If a record is locked, and you have a valid recovery-token you can reset the failure counter: ```sh $ echo -n | opaquestore unlock ``` ### Generate long-term signature keys If you run server, you need to generate some long-term signing keys if you want to use this server in a threshold setup. If you don't provide the path to the keys, the secret-key will be taken from the `ltsigkey` config value in your `opaque-storaged` configuration, and the public-key will be the same as the secret-key, but with a `.pub` extension. ``` $ opaquestore genltsigkey [secret-key path] [public-key path] ``` opaque-store-0.2.0/client/opaque-store.cfg000066400000000000000000000026641473305203000205250ustar00rootroot00000000000000[client] # you must change this value, it ensures that your record ids are # unique you must also make sure to not lose this value, if you do, # you lose access to your records. id_salt="Please_MUST-be_changed! and backed up to something difficult to guess" # the number of servers successfully participating in an # operation. must be less than 129, but lower 1 digit number are # probable the most robust. threshold=2 # the time in seconds a distributed keygen (DKG) protocol message is # considered fresh. anything older than this is considered invalid and # aborts a DKG. Higher values help with laggy links, lower values can # be fine if you have high-speed connections to all servers. ts_epsilon=1200 # the list of servers, must be 1 item, if threshold is 1, or one more # than threshold. [servers] [servers.zero] # address of server host="127.0.0.1" # port where server is running port=23000 # self-signed public key of the server # - not needed for proper Lets Encrypt certs ssl_cert = "../server/cert.pem" ltsigkey="../server/test-2of3-setup/zero.pub" [servers.eins] # address of server host="127.0.0.1" # port where server is running port=23001 # public key of the server ssl_cert = "../server/cert.pem" ltsigkey="../server/test-2of3-setup/eins.pub" [servers.zwei] # address of server host="127.0.0.1" # port where server is running port=23002 # public key of the server ssl_cert = "../server/cert.pem" ltsigkey="../server/test-2of3-setup/zwei.pub" opaque-store-0.2.0/client/opaquestore/000077500000000000000000000000001473305203000177575ustar00rootroot00000000000000opaque-store-0.2.0/client/opaquestore/__init__.py000066400000000000000000000000011473305203000220570ustar00rootroot00000000000000 opaque-store-0.2.0/client/opaquestore/cfg.py000077500000000000000000000015011473305203000210700ustar00rootroot00000000000000#!/usr/bin/env python # SPDX-FileCopyrightText: 2023, Marsiske Stefan # SPDX-License-Identifier: GPL-3.0-or-later import os, tomllib def split_by_n(obj, n): # src https://stackoverflow.com/questions/9475241/split-string-every-nth-character return [obj[i:i+n] for i in range(0, len(obj), n)] def getcfg(name, cwd="."): paths=[ # read global cfg f'/etc/{name}/config', # update with per-user configs os.path.expanduser(f"~/.{name}rc"), os.path.expanduser(f"~/.config/{name}/config"), # over-ride with local directory config os.path.expanduser('/'.join([cwd,f"{name}.cfg"])) ] config = dict() for path in paths: try: with open(path, "rb") as f: data = tomllib.load(f) except FileNotFoundError: continue config.update(data) return config opaque-store-0.2.0/client/opaquestore/client.py000077500000000000000000000376741473305203000216330ustar00rootroot00000000000000#!/usr/bin/env python3 # SPDX-FileCopyrightText: 2018-2021, Marsiske Stefan # SPDX-License-Identifier: GPL-3.0-or-later import sys, os, getpass, ssl, socket, struct import pysodium, opaque, pyoprf try: from zxcvbn import zxcvbn except ImportError: zxcvbn = None from SecureString import clearmem from opaquestore.cfg import getcfg from pyoprf.multiplexer import Multiplexer from binascii import a2b_base64, b2a_base64 from itertools import zip_longest #### consts #### CREATE =b'\x00' UPDATE =b'\x33' GET_RTOKEN =b'\x50' GET =b'\x66' CHANGE_DKG =b'\xa0' CREATE_DKG =b'\xf0' UNLOCK =b'\xf5' DELETE =b'\xff' config = None #### Helper fns #### def encrypt_blob(sk, blob): # todo implement padding to hide length information nonce = pysodium.randombytes(pysodium.crypto_secretbox_NONCEBYTES) ct = pysodium.crypto_secretbox(blob,nonce,sk) clearmem(sk) return nonce+ct def decrypt_blob(sk, blob): nonce = blob[:pysodium.crypto_secretbox_NONCEBYTES] blob = blob[pysodium.crypto_secretbox_NONCEBYTES:] res = pysodium.crypto_secretbox_open(blob,nonce,sk) clearmem(sk) return res def split_by_n(iterable, n): return list(zip_longest(*[iter(iterable)]*n, fillvalue='')) def getpwd(): if sys.stdin.isatty(): return getpass.getpass("please enter your password: ").encode('utf8') else: return sys.stdin.buffer.readline().rstrip(b'\n') def processcfg(config): servers = config.get('servers',{}) config = config['client'] config['threshold'] = int(config.get('threshold') or "1") config['ts_epsilon'] = int(config.get('ts_epsilon') or "1200") for server in servers.values(): try: server['ssl_cert'] = os.path.expanduser(server.get('ssl_cert')) # only for dev, production system should use proper certs! except TypeError: # ignore exception in case ssl_cert is not set, thus None is attempted to expand. server['ssl_cert'] = None if len(servers)>1: if config['threshold'] < 2: print('if you have multiple servers in your config, you must specify a threshold, which must be: len(servers) > threshold > 1 also') exit(1) if len(servers) 1: print(f'threshold({config["threshold"]}) must be less than the number of servers({len(servers)}) in your config') exit(1) config['servers']=servers return config def read_pkt(s,i,plen=None): res = [] if plen is None: plen = s[i].read(2) if len(plen)!=2: raise ValueError plen = struct.unpack(">H", plen)[0] read = 0 while readH", len(msg)) if i is None: s.broadcast(plen+msg) else: s.send(i, plen+msg) def opaque_session(s, pwdU, keyid, op, force=False): # user initiates a credential request ke1_0, sec_0 = opaque.CreateCredentialRequest_oprf(pwdU) secs=[] for i, peer in enumerate(s): pkid = pysodium.crypto_generichash(peer.name.encode('utf8') + keyid) ke1, sec = opaque.CreateCredentialRequest_ake(pwdU, sec_0, ke1_0) s.send(i, op+pkid+ke1) secs.append(sec) clearmem(sec_0) ke2s = s.gather(opaque.OPAQUE_SERVER_SESSION_LEN) attempts = dict([(i, struct.unpack(">i", a)[0]) for i, a in enumerate(s.gather(4)) if a is not None]) missing = [] for i, peer in enumerate(s): ke2 = ke2s[i] if ke2 is None: missing.append(i) print(f"oracle {i}: \"{peer.name} at {peer.address[0]}\" failed to load record or create opaque response", file=sys.stderr) if op == DELETE and len(missing)>0: raise ValueError(f'Delete operations require all servers to participate. Aborting. Use force-delete to delete from all available servers.') elif op == UPDATE and len(missing)>0: raise ValueError(f'Update operations require all servers to participate. Aborting. Use force-update to update all available servers.') elif (op == GET or force == True) and len(s) - len(missing) < config['threshold']: raise ValueError(f"Less than threshold ({config['threshold']}) number of servers available. Aborting.") indexes = bytes([i+1 for i,r in enumerate(ke2s) if r is not None]) resps = b''.join(r for r in ke2s if r is not None) beta = opaque.CombineCredentialResponses(config['threshold'], len(indexes), indexes, resps) auths = [] export_keys = [] sks = [] for i, peer in enumerate(s): ke2 = ke2s[i] ## user recovers its credentials from the servers response try: sk, authU, export_key = opaque.RecoverCredentials(ke2, secs[i], b"opaque-store", opaque.Ids(None, None), beta) except: print(f'{s[i].name} ({s[i].address[0]}): {attempts.get(i, '?')} attempts left', file=sys.stderr) raise ValueError(f"opaque failed, possibly wrong password?") clearmem(secs[i]) if op in {GET_RTOKEN}: sks.append(sk) else: clearmem(sk) auths.append((i, authU)) if op in {GET, UPDATE}: export_keys.append(export_key) else: clearmem(export_key) for i, authU in auths: s.send(i, authU) clearmem(authU) # TODO we are in trouble if op in UPDATE/DELETE but connection drops, or we are partly? unauthorized, can that happen? if op in {GET, UPDATE}: return export_keys if op in {GET_RTOKEN}: return sks def dkg(m, threshold): n = len(m) # load peer long-term keys peer_lt_pks = [] for name, server in config['servers'].items(): with open(server.get('ltsigkey'),'rb') as fd: peer_lt_pk = fd.read() if(len(peer_lt_pk)!=pysodium.crypto_sign_PUBLICKEYBYTES): raise ValueError(f"long-term signature key for server {name} is of incorrect size") peer_lt_pks.append(peer_lt_pk) zero_shares = pyoprf.create_shares(bytes([0]*32), n, config['threshold']) tp, msg0 = pyoprf.tpdkg_start_tp(n, threshold, config['ts_epsilon'], "threshold opaque dkg create k", peer_lt_pks) m.broadcast(msg0) for i in range(n): m.send(i, zero_shares[i]) while pyoprf.tpdkg_tp_not_done(tp): cur_step = tp[0].step ret, sizes = pyoprf.tpdkg_tp_input_sizes(tp) #print(f"step: {cur_step} {ret} {sizes}", file=sys.stderr) peer_msgs = [] if ret: if sizes[0] > 0: peer_msgs_sizes = m.gather(2,n) #,debug=True) for i, (msize, size) in enumerate(zip(peer_msgs_sizes, sizes)): if struct.unpack(">H", msize)[0]!=size: raise ValueError(f"peer{i} ({m[i].name}{m[i].address}) sent invalid sized ({msize}) response, should be {size}") peer_msgs = m.gather(sizes[0],n) #,debug=True) else: peer_msgs = [read_pkt(m, i) if s>0 else b'' for i, s in enumerate(sizes)] for i, (pkt, size) in enumerate(zip(peer_msgs, sizes)): if(len(pkt)!=size): raise ValueError(f"peer{i} ({m[i].name}{m[i].address}) sent invalid sized ({len(pkt)}) response, should be {size}") #print(f"[{i}] received {pkt.hex()}", file=sys.stderr) msgs = b''.join(peer_msgs) try: out = pyoprf.tpdkg_tp_next(tp, msgs) except Exception as e: m.close() if tp[0].cheater_len > 0: cheaters, cheats = pyoprf.tpdkg_get_cheaters(tp) msg=[f"Warning during the distributed key generation the peers misbehaved: {sorted(cheaters)}"] for k, v in cheats: msg.append(f"\tmisbehaving peer: {k} was caught: {v}") msg = '\n'.join(msg) raise ValueError(msg) else: raise ValueError(f"{e} | tp step {cur_step}") #print(f"outlen: {len(out)}", file=sys.stderr) if(len(out)>0): for i in range(tp[0].n): msg = pyoprf.tpdkg_tp_peer_msg(tp, out, i) #print(f"sending({i} {m[i].name}({m[i].address}), {msg.hex()})", file=sys.stderr) send_pkt(m, msg, i) #### OPs #### def create(s, pwdU, keyid, data): secs=[] op = CREATE if config['threshold'] > 1: op = CREATE_DKG sec, req = opaque.CreateRegistrationRequest(pwdU) for i, peer in enumerate(s): # TODO TBA hashing the peername means that they cannot be changed # later maybe hash i instead? pkid = pysodium.crypto_generichash(peer.name.encode('utf8') + keyid) s.send(i, op+pkid+req) if op == CREATE_DKG: # conduct DKG dkg(s, config['threshold']) resps = s.gather(opaque.OPAQUE_REGISTER_PUBLIC_LEN) if op == CREATE_DKG: # combine shares into beta tmp = b''.join(resps) opaque.CombineRegistrationResponses(config['threshold'], len(resps), tmp) resps = split_by_n(tmp, opaque.OPAQUE_REGISTER_PUBLIC_LEN) recs=[] blobs=[] for i, peer in enumerate(s): pub = bytes(resps[i]) if pub is None: raise ValueError("oracle failed to create registration response") #print("received pub:", len(pub), opaque.OPAQUE_REGISTER_PUBLIC_LEN, pub.hex()) rec, export_key = opaque.FinalizeRequest(sec, pub, opaque.Ids(None, None)) recs.append(rec) blob = encrypt_blob(export_key[:pysodium.crypto_aead_xchacha20poly1305_ietf_KEYBYTES], data) blobs.append(blob) for i, peer in enumerate(s): #print("send rec") s.send(i,recs[i]) #print("send blob") send_pkt(s, blobs[i], i) for i, peer in enumerate(s): ret = read_pkt(s,i,2) if ret is None: raise ValueError("oracle failed to complete creation of record and/or blob") if ret != b'ok': raise ValueError("oracle failed to acknowledge success") return True def get(s, pwdU, keyid): export_keys = opaque_session(s, pwdU, keyid, GET) blobs = [] for i, peer in enumerate(s): data = read_pkt(s,i) if data is None: raise ValueError("unauthorized") blobs.append(decrypt_blob(export_keys[i][:pysodium.crypto_aead_xchacha20poly1305_ietf_KEYBYTES], data)) clearmem(export_keys[i]) blobs = {blob.decode('utf8') for blob in blobs} if len(blobs) != 1: raise ValueError("inconsistent blobs recovered") return list(blobs)[0] def delete(s, pwdU, keyid, force=False): opaque_session(s, pwdU, keyid, DELETE, force) # todo ensure that all peers are connected! for i, peer in enumerate(s): ret = read_pkt(s,i,2) if ret is None: raise ValueError("unauthorized") if ret != b'ok': raise ValueError("oracle failed to acknowledge success") return True def update(s, pwdU, keyid, data, force=False): export_keys = opaque_session(s, pwdU, keyid, UPDATE, force) # todo ensure that all peers are connected! blobs = [] for i, peer in enumerate(s): blob = encrypt_blob(export_keys[i][:pysodium.crypto_aead_xchacha20poly1305_ietf_KEYBYTES], data) blobs.append(blob) for i, peer in enumerate(s): send_pkt(s, blobs[i], i) for i, peer in enumerate(s): ret = read_pkt(s,i,2) if ret is None: raise ValueError("unauthorized") if ret != b'ok': raise ValueError("oracle failed to acknowledge success") return True def get_recovery_tokens(s, pwdU, keyid): sks = opaque_session(s, pwdU, keyid, GET_RTOKEN) tokens = [] for i, peer in enumerate(s): data = read_pkt(s,i) if data is None: raise ValueError("unauthorized") tokens.append(decrypt_blob(sks[i][:pysodium.crypto_aead_xchacha20poly1305_ietf_KEYBYTES], data)) clearmem(sks[i]) return b2a_base64(b''.join(tokens)).strip().decode('utf8') def unlock(s, pwdU, keyid): tokens = split_by_n(a2b_base64(pwdU), 16) for i, peer in enumerate(s): pkid = pysodium.crypto_generichash(peer.name.encode('utf8') + keyid) s.send(i, UNLOCK+pkid+bytes(tokens[i])) oks = s.gather(2) for i, ok in enumerate(oks): if ok != b'ok': raise ValueError(f"oracle ({s[i].name} @{s[i].address[0]}) failed to acknowledge success") return True def genltsigkey(skpath=None, pkpath=None): if skpath is None: server_config = getcfg('opaque-stored')['server'] if skpath is None: skpath = server_config['ltsigkey'] if pkpath is None: pkpath = f"{skpath}.pub" if os.path.exists(skpath): print(f"{skpath} exists, refusing to overwrite, if you want to generate a new one, delete the old one first. aborting") return 1 if os.path.exists(pkpath): print(f"{pkpath} exists, refusing to overwrite, if you want to generate a new one, delete the old one first. aborting") return 1 pk, sk = pysodium.crypto_sign_keypair() with open(skpath, 'wb') as fd: fd.write(sk) with open(pkpath, 'wb') as fd: fd.write(pk) print(f"wrote secret-key to {skpath} and public-key to {pkpath}.") def usage(params, help=False): print("usage: %s " % params[0]) print(" %s genltsigkey [private-key path] [public-key path]" % params[0]) print(" echo -en 'password\\ntoken2store' | %s create " % params[0]) print(" echo -n 'password' | %s get " % params[0]) print(" echo -en 'password\\ntoken2update' | %s update " % params[0]) print(" echo -en 'password\\ntoken2update' | %s force-update " % params[0]) print(" echo -n 'password' | %s delete " % params[0]) print(" echo -n 'password' | %s force-delete " % params[0]) print(" echo -n 'password' | %s recovery-tokens " % params[0]) print(" echo -n | %s unlock " % params[0]) if help: sys.exit(0) sys.exit(100) def test_pwd(pwd): if zxcvbn is None: return q = zxcvbn(pwd.decode('utf8')) print("your %s%s (%s/4) master password can be online recovered in %s, and offline in %s, trying ~%s guesses" % ("★" * q['score'], "☆" * (4-q['score']), q['score'], q['crack_times_display']['online_throttling_100_per_hour'], q['crack_times_display']['offline_slow_hashing_1e4_per_second'], q['guesses']), file=sys.stderr) #### main #### cmds = {'create': create, 'get': get, 'update': update, 'force-update': update, 'delete': delete, 'force-delete': delete, 'recovery-tokens': get_recovery_tokens, 'unlock': unlock, 'genltsigkey': genltsigkey, } def main(params=sys.argv): #import ctypes #libc = ctypes.cdll.LoadLibrary('libc.so.6') #fdopen = libc.fdopen #log_file = ctypes.c_void_p.in_dll(pyoprf.liboprf,'log_file') #fdopen.restype = ctypes.c_void_p #log_file.value = fdopen(2, 'w') if len(params) < 2: usage(params, True) cmd = None args = [] if params[1] in ('help', '-h', '--help'): usage(params, True) if params[1] not in cmds: usage(params) if params[1] == "genltsigkey": sys.exit(genltsigkey(*params[2:])) global config config = processcfg(getcfg('opaque-store')) if len(params) != 3: usage(params) pwd = getpwd() cmd = cmds[params[1]] if params[1] == 'create': test_pwd(pwd) data = sys.stdin.buffer.read() args = (data,) elif params[1] in {'update', 'force-update'}: test_pwd(pwd) data = sys.stdin.buffer.read() if params[1] == 'force-update': args = (data,True) else: args = (data,) elif params[1] == 'force-delete': args = (True,) error = None s = None try: s = Multiplexer(config['servers']) s.connect() ret = cmd(s, pwd, pysodium.crypto_generichash(params[2], k=config['id_salt']), *args) except Exception as exc: error = exc ret = False raise # only for dbg clearmem(pwd) s.close() if not ret: if not error: print("fail", file=sys.stderr) sys.exit(3) # error not handled by exception print(error, file=sys.stderr) sys.exit(1) # generic errors if cmd in {get, get_recovery_tokens}: print(ret) sys.stdout.flush() clearmem(ret) elif ret != True: print("reached code that should not be reachable: ", ret) if __name__ == '__main__': try: main(sys.argv) except Exception: print("fail", file=sys.stderr) raise # only for dbg opaque-store-0.2.0/client/setup.py000077500000000000000000000026411473305203000171300ustar00rootroot00000000000000#!/usr/bin/env python # SPDX-FileCopyrightText: 2024, Marsiske Stefan # SPDX-License-Identifier: GPL-3.0-or-later import os #from distutils.core import setup, Extension from setuptools import setup # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name = 'opaquestore', version = '0.1.0', description = 'Simple Online secret-storage based on the OPAQUE protocol', license = "GPLv3", author = 'Stefan Marsiske', author_email = 'opaque@ctrlc.hu', url = 'https://github.com/stef/opaque-store/', long_description=read('README.md'), long_description_content_type="text/markdown", packages = ['opaquestore'], install_requires = ("pysodium", "SecureString", "opaque","zxcvbn-python", 'pyoprf'), classifiers = ["Development Status :: 4 - Beta", "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", "Topic :: Security :: Cryptography", "Topic :: Security", ], entry_points = { 'console_scripts': [ 'opaquestore = opaquestore.client:main' ], }, ) opaque-store-0.2.0/man/000077500000000000000000000000001473305203000147055ustar00rootroot00000000000000opaque-store-0.2.0/man/.gitignore000066400000000000000000000000041473305203000166670ustar00rootroot00000000000000*.1 opaque-store-0.2.0/man/makefile000066400000000000000000000005151473305203000164060ustar00rootroot00000000000000all: opaquestore.1 opaqueztore.1 opaque-store.cfg.1 opaque-stored.cfg.1 install: $(PREFIX)/share/man/man1/opaquestore.1 $(PREFIX)/share/man/man1/opaqueztore.1 \ $(PREFIX)/share/man/man5/opaque-store.cfg.1 $(PREFIX)/share/man/man5/opaque-stored.cfg.1 \ clean: rm -f *.1 %.1: %.md cp $(@:.1=.head) $@ cmark -t man $< >>$@ opaque-store-0.2.0/man/opaque-store.cfg.head000066400000000000000000000001051473305203000207060ustar00rootroot00000000000000.TH "opaque-store.cfg" "5" "" "" "OPAQUE-Store client configuration" opaque-store-0.2.0/man/opaque-store.cfg.md000066400000000000000000000065651473305203000204250ustar00rootroot00000000000000# NAME opaque-store.cfg - configuration for for OPAQUE-Store client `opaquestore` # DESCRIPTION The client looks for the configuration in the following files and order: - /etc/opaque-store/config - ~/.config/opaque-store/config - ~/.opaque-storerc - ./opaque-store.cfg The configuration file format is TOML. ## `[Client]` SECTION ### `ID_SALT` you must change this value, it ensures that your record ids are unique you must also make sure to not lose this value, if you do, you lose access to your records. Has no default, must be set. ### THRESHOLD ### `TS_EPSILON` the time in seconds a distributed keygen (DKG) protocol message is considered fresh. anything older than this is considered invalid and aborts a DKG. Higher values help with laggy links, lower values can be fine if you have high-speed connections to all servers. Default: 1200s ### `[servers]` SECTION This section contains the list of servers for the client. The number of items in this list must be 1, if `threshold` is 1, otherwise one more than `threshold`. Servers are in their own sections, with the following pattern: `[servers.]` Where name should be ... TODO #### ADDRESS This can be either an IPv4 or IPv6 address to listen on. #### PORT The port the server listens on. #### `SSL_CERT` This variable is a path pointing at a file containing a TLS certificate. This is only needed for TLS certificates that are self-signed or otherwise not in the list of CAs. #### LTSIGKEY This variable is a path pointing at a file containing a public long-term signing key of the server. ## Threshold setup The client config file, contains a `[servers]` section which lists all servers you want to use in a threshold setup. Each server has an `address`, `port` and `ltsigkey` variable that needs to be set accordingly. In case your server runs with a self-signed certificate there is a `ssl_cert` variable that can pin it to the correct cert. It is also important to note, that the name of the server - which is given after a dot in the `[servers.name]` sub-section title is also used to generate record ids specific to that server. Thus once chosen, it should not change, unless you want to lose access to the records on that server. The name doesn't have to be unique by users, but should be unique among all configured servers in this setup, this guarantees that for a record each server has a different record it and thus makes the records unlinkable across servers. In the config files `[client]` section the `threshold` variable specifies the threshold for the setup. The minimum sane configuration for a threshold setup is `threshold=2` with at least 3 servers listed. The maximum of servers is 128, but that is way too many, a reasonable max is around 16 or so. # FILES - /etc/opaque-store/config - ~/.config/opaque-store/config - ~/.opaque-storerc - ./opaque-store.cfg # SECURITY CONSIDERATIONS You **should** back up and encrypt your master key. # REPORTING BUGS https://github.com/stef/opaque-store/issues/ # AUTHOR Written by Stefan Marsiske. # COPYRIGHT Copyright © 2024 Stefan Marsiske. License GPLv3+: GNU GPL version 3 or later . This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. # SEE ALSO `https://www.ctrlc.hu/~stef/blog/posts/How_to_recover_static_secrets_using_OPAQUE.html` `opaquestore(1)` opaque-store-0.2.0/man/opaque-stored.cfg.head000066400000000000000000000001061473305203000210530ustar00rootroot00000000000000.TH "opaque-stored.cfg" "5" "" "" "OPAQUE-Store server configuration" opaque-store-0.2.0/man/opaque-stored.cfg.md000066400000000000000000000072611473305203000205630ustar00rootroot00000000000000# NAME opaque-stored.cfg - configuration for for OPAQUE-Store server `opaqueztore` # DESCRIPTION The server looks for the configuration in the following files and order: - /etc/opaque-stored/config - ~/.config/opaque-stored/config - ~/.opaque-storedrc - ./opaque-stored.cfg The configuration file format is TOML. ## `[server]` SECTION This section contains all the settings for the server. ### ADDRESS This can be either an IPv4 or IPv6 address to listen on. Default: 127.0.0.1 ### PORT The port the server listens on. If you run a server that is publicly available on the internet, it is recommended to run it on port 443, which - if you ever go to a restricted network environmet - has the biggest chances that a firewall will allow to access this. Default: 443 ### `SSL_KEY` & `SSL_SERVER` These two settings point at files containing the PEM encoded SSL certificate and key of the server. In the times of Let's Encrypt this should not be a big challenge. You do need a domain name you control for this though, but that is a requirement for public servers anyway. If you have a domain name, you can run on that host something like this: ```sh sudo certbot certonly --standalone --preferred-challenges http -d example.com ``` ### TIMEOUT This configures the timeouts for the server. In order to minimize resource exhaustion attack this should be kept as small as possible, but also big enough for clients to answer in time. Since all the messages are very small, something in the low one-digit seconds ballpark should be ample. Default 3s. ### DATADIR This variable contains the path to the directory where all the blobs are stored. Default: `/var/lib/opaque-stored` ### `MAX_KIDS` This setting configures the maximumu of how many handlers (sessions) to run in parallel. Default: 5 ### VERBOSE This setting increases the messages the server prints out during operation. ### `RECORD_SALT` This is a value that internally hashes the record Ids provided by clients. It should be changed uppon installation to a fresh unique value. ### `MAX_BLOB_SIZE` This sets the maximum size for any blobs stored on your server. This should be used to limit resource exhaustion, and can limit the storage of illegal material, like child abuse related material. Default: 1KB. ### `MAX_FAILS` The number of invalid passwords allowed before locking the blob. Default: 3 ### `TS_EPSILON` This setting defines how long a message is considered fresh during a DKG protocol, any messages that have timestamps that are older than this many seconds will abort the DKG protocol. Increase this value if you have/expect laggy links. Default: 600s ### LTSIGKEY This setting points at a file containing the long-term signing key of the server - this is only needed for participation in threshold setups. Can be generated by running the `opaquestore(1)` client with parameter: ```sh $ opaquestore genltsigkey >ltsigkey.key ``` ### `MAX_RECOVERY_TOKENS` This variable defines the maximum number of recovery tokens a server holds for each blob. Default: 5. # FILES - /etc/opaque-stored/config - ~/.config/opaque-stored/config - ~/.opaque-storedrc - ./opaque-stored.cfg # SECURITY CONSIDERATIONS You **should** back up securely your ltsigkey, your SSL cert and key, and the value of your `RECORD_SALT` setting. # REPORTING BUGS https://github.com/stef/opaque-store/issues/ # AUTHOR Written by Stefan Marsiske. # COPYRIGHT Copyright © 2024 Stefan Marsiske. License GPLv3+: GNU GPL version 3 or later . This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. # SEE ALSO `opaqueztore(1)`, `opaquestore(1)`, `opaque-store.cfg(5)` opaque-store-0.2.0/man/opaquestore.head000066400000000000000000000000771473305203000201030ustar00rootroot00000000000000.TH "opaquestore" "1" "" "" "OPAQUE-Store command-line client" opaque-store-0.2.0/man/opaquestore.md000066400000000000000000000157651473305203000176140ustar00rootroot00000000000000# NAME opaquestore - command-line client for OPAQUE-Store # SYNOPSIS `opaquestore` genltsigkey [private-key path] [public-key path] echo -en 'password\ntoken2store' | `opaquestore` create echo -n 'password' | `opaquestore` get echo -en 'password\ntoken2update' | `opaquestore` update echo -en 'password\ntoken2update' | `opaquestore` force-update echo -n 'password' | `opaquestore` delete echo -n 'password' | `opaquestore` force-delete echo -n 'password' | `opaquestore` recovery-tokens echo -n | `opaquestore` unlock # DESCRIPTION OPAQUE-Store is a simple protocol that allows anyone to store encrypted blobs of information online, with only a password needed to retrieve the information. As the name implies it uses the OPAQUE protocol to do so. OPAQUE-Store uses the `export_key` feature of OPAQUE to encrypt the data that is stored on the OPAQUE-Storage server. You might want to read this blog-post on this topic and on more info: `https://www.ctrlc.hu/~stef/blog/posts/How_to_recover_static_secrets_using_OPAQUE.html` OPAQUE-Store goes beyond the original OPAQUE protocol as specified by the IRTF/CFRG and also supports a threshold variant of OPAQUE. In a threshold setup you have a number N of servers that all hold a share of your secret and at least a threshold number T of these need to cooperate to recover the secret. This provides extra robustness and dillution of responsibility (losing a server is not the end of the world!) while at the same time increases security, as an attacker now has to compromise at least T servers to get access to some information. ## Command-line usage and examples It is warmly recommended to use pwdsphinx (https://github.com/stef/pwdsphinx) as a front-end to opaquestore, since it handles passwords in a most secure manner. If you want to use a different password manager, you can use the CLI interface documented below. ### Passwords and Records opaquestore takes the password always on the standard input. If you are creating or updating a record, the record itself is also expected on the standard input. The password and the record - if required - are separated by a newline character. ### KeyIds KeyIds are the identifiers that you use to address your records, they can be any kind of string. Internally this keyId is hashed using the `id_salt` from the configurations `[client]` section into a unique identifier. It is very warmly recommended to set this to some random value, and to back this value up. As this salt is necessary to access your records. If you use a commonly used salt (i.e. the default salt) chances are high that there are collisions for record ids, and that people can guess your record ids. ### Store a new record Storing a record needs 3 parameters: - the password, on standard input, terminated by a newline. - the record itself until the end of the standard input - and a keyId with which you can reference and act on this record ```sh $ echo -en 'password\ntoken2store' | opaquestore create ``` Here is a contrived example: ``` echo -en "mypassword\!sMyV0ice\nmy secretty token data that i need to protect and store using opaque" | opaquestore create myfirstblob ``` In this example: - the password is "mypassword!sMyV0ice" - the record is: "my secretty token data that i need to protect and store using opaque" - and the keyId is "myfirstblob" ### Get a record Retrieving a record has to parameters: - the password on standard input - the keyId as the 2nd parameter to `opaquestore` ```sh $ echo -n 'password' | opaquestore get ``` An example fetching the record created in the previous example: ``` echo -en "mypassword\!sMyV0ice" | opaquestore get myfirstblob ``` ### Update a record It is possible to update a record in place, it is essentially the same as the creation of a record. It is important to note, that this operation only succeeds, if all servers need to process this request, not only those needed for matching the threshold, you want to update the record on all servers not just some. ```sh $ echo -en 'password\ntoken2update' | opaquestore update ``` If you do not care if some servers will not be updated and you really know what you are doing, you can use the alternative command `force-update`, in this case the operation will succeed if at least the threshold is matched. Note however if any of the servers that did not participate in the forced update will participate in later operations will corrupt later operations, so you might want to remove those servers from your config. ```sh $ echo -en 'password\ntoken2update' | opaquestore force-update ``` ### Delete a record Deleting a record is very straight forward, you need your password and keyId, and ensure that all servers that store this record will all be available. The operation will fail if some servers are not available. ```sh $ echo -n 'password' | opaquestore delete ``` Similarly to the update operation there is also a forced delete operation, which will succeed if at least the threshold is matched. Servers not available during this forced delete will still hold the record, if your setup has a n-out-of-2*n setup could mean that you still have enough shares even after a forced-delete. ```sh $ echo -n 'password' | opaquestore force-delete ``` ### Get some recovery-tokens An attacker might be trying different passwords for your record, after a certain amount of consecutive password failures (by default 3) the server locks down the record. A locked record can only be unlocked with a recovery-token. It is not possible to ask for recovery-tokens when a record is already locked. ```sh $ echo -n 'password' | opaquestore recovery-tokens ``` ### Unlock a locked record using a recovery token If a record is locked, and you have a valid recovery-token you can reset the failure counter: ```sh $ echo -n | opaquestore unlock ``` ### Generate long-term signature keys If you run server, you need to generate some long-term signing keys if you want to use this server in a threshold setup. If you don't provide the path to the keys, the secret-key will be taken from the `ltsigkey` config value in your `opaque-storaged` configuration, and the public-key will be the same as the secret-key, but with a `.pub` extension. ``` $ opaquestore genltsigkey [secret-key path] [public-key path] ``` # SECURITY CONSIDERATIONS You **should** back up and encrypt your master key. # REPORTING BUGS https://github.com/stef/opaque-store/issues/ # AUTHOR Written by Stefan Marsiske. # COPYRIGHT Copyright © 2024 Stefan Marsiske. License GPLv3+: GNU GPL version 3 or later . This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. # SEE ALSO `https://www.ctrlc.hu/~stef/blog/posts/How_to_recover_static_secrets_using_OPAQUE.html` `opaque-store.cfg(5)` opaque-store-0.2.0/man/opaqueztore.head000066400000000000000000000000621473305203000201040ustar00rootroot00000000000000.TH "opaqueztore" "1" "" "" "OPAQUE-Store server" opaque-store-0.2.0/man/opaqueztore.md000066400000000000000000000025531473305203000176120ustar00rootroot00000000000000# NAME opaqueztore - OPAQUE-Store server # SYNOPSIS `opaqueztore` # DESCRIPTION OPAQUE-Store is a simple protocol that allows anyone to store encrypted blobs of information online, with only a password needed to retrieve the information. As the name implies it uses the OPAQUE protocol to do so. OPAQUE-Store uses the `export_key` feature of OPAQUE to encrypt the data that is stored on the OPAQUE-Storage server. The server runs in the foreground and emits log messages to standard output. If you want to run it as a daemon, you should deploy it using service supervision tools such as s6, runit or daemontools. When configured, the server should publish its long-term signing public-key so that clients can use it in a threshold setup. # SECURITY CONSIDERATIONS You **should** back up your SSL key, `record_salt` configuration value, ltsigkey and of course all blobs regularly. # REPORTING BUGS https://github.com/stef/opaque-store/issues/ # AUTHOR Written by Stefan Marsiske. # COPYRIGHT Copyright © 2024 Stefan Marsiske. License GPLv3+: GNU GPL version 3 or later . This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. # SEE ALSO `https://www.ctrlc.hu/~stef/blog/posts/How_to_recover_static_secrets_using_OPAQUE.html` `opaquestore(1)`, `opaque-stored.cfg(5)` opaque-store-0.2.0/server/000077500000000000000000000000001473305203000154405ustar00rootroot00000000000000opaque-store-0.2.0/server/README.md000066400000000000000000000060351473305203000167230ustar00rootroot00000000000000# OPAQUE-Store server OPAQUE-Store is a simple protocol that allows anyone to store encrypted blobs of information online, with only a password needed to retrieve the information. As the name implies it uses the OPAQUE protocol to do so. OPAQUE-Store uses the `export_key` feature of OPAQUE to encrypt the data that is stored on the OPAQUE-Storage server. # Dependencies you need to install - libsodium - liboprf https://github.com/stef/liboprf/ - libopaque https://github.com/stef/libopaque/ on debian (unstable) you can install the -dev packages. # Building You need zig 0.13 at least to build, simply do `zig build` # Configuring Configuration will be looked for in the following order - /etc/opaque-stored/config - ~/.config/opaque-stored/config - ~/.opaque-storedrc - ./opaque-stored.cfg For an example file see the file `opaque-stored.cfg` in this directory. The most important is to have a proper SSL certificate, in the times of Let's Encrypt this should not be a big challenge. You do need a domain name you control for this though, but that is a requirement for public servers anyway. If you have a domain name, you can run on that host something like this: ```sh sudo certbot certonly --standalone --preferred-challenges http -d example.com ``` If you run a server that is publicly available on the internet, we recommend to run it on port 443, which - if you ever go to a restricted network environmet - has the biggest chances that a firewall will allow to access this. ## Configuration Example The following is a basic configuration example for a server. ``` [server] # the ipv4 address the server is listening on #address="127.0.0.1" # ssl key ssl_key="server.der" # ssl cert ssl_cert="cert.pem" # the port on which the server is listening, use 443 if available, so that # the server can be accessed from behind tight firewalls, default: 8080 port=2523 # tcp connection timeouts, increase in case you have bad networks, with the # caveat that this might lead to easier resource exhaustion - blocking all # workers. #timeout=3 # the root directory where all data is stored, default: /var/lib/opaque-stored datadir="data" # how many worker processes can run in parallel # max_kids=5 # whether to produce some output verbose=true # key record_salt="some random string to salt the record ids" # Especially if you run a public server you want to limit the maximum size of # stored blobs max_blob_size=8192 # lock a record after this many failed password attempts. max_fails=3 # a file containing the long-term signing key of the server - this is only # needed for participation in threshold setups. Can be generated by running the # client with parameter: "opaquestore genltsigkey >ltsigkey.key" ltsigkey="ltsigkey.key" # set how long a message is considered fresh during a DKG protocol, any # messages that have timestamps that are older than this many seconds will # abort the DKG protocol. Increase this value if you have/expect laggy links. ts_epsilon=600 # the number of recovery tokens a server holds for each blob max_recovery_tokens=5 ``` opaque-store-0.2.0/server/build.zig000066400000000000000000000104771473305203000172630ustar00rootroot00000000000000const std = @import("std"); // Although this function looks imperative, note that its job is to // declaratively construct a build graph that will be executed by an external // runner. pub fn build(b: *std.Build) void { // Standard target options allows the person running `zig build` to choose // what target to build for. Here we do not override the defaults, which // means any target is allowed, and the default is native. Other options // for restricting supported target set are available. const target = b.standardTargetOptions(.{}); // Standard optimization options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not // set a preferred release mode, allowing the user to decide how to optimize. const optimize = b.standardOptimizeOption(.{}); // load the "zig-toml" dependency from build.zig.zon const toml_package = b.dependency("zig-toml", .{ .target = target, .optimize = optimize, }); const toml_module = toml_package.module("toml"); const bearssl_package = b.dependency("zig-bearssl", .{ .target = target, .optimize = optimize, }); const bearssl_module = bearssl_package.module("bearssl"); const exe = b.addExecutable(.{ .name = "opaqueztore", .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); exe.root_module.addImport("toml", toml_module); exe.root_module.addImport("bearssl", bearssl_module); exe.linkLibrary(bearssl_package.artifact("zig-bearssl")); exe.linkSystemLibrary("opaque"); exe.linkSystemLibrary("oprf"); exe.linkSystemLibrary("sodium"); exe.addSystemIncludePath(.{ .cwd_relative = "/usr/include/oprf/noiseXK/" }); exe.addSystemIncludePath(.{ .cwd_relative = "/usr/include/oprf/noiseXK/karmel" }); exe.addSystemIncludePath(.{ .cwd_relative = "/usr/include/oprf/noiseXK/karmel/minimal" }); exe.addIncludePath(b.path(".")); exe.addCSourceFile(.{ .file = b.path("workaround.c"), .flags = &[_][]const u8{"-Wall"} }); exe.linkLibC(); // This declares intent for the executable to be installed into the // standard location when the user invokes the "install" step (the default // step when running `zig build`). b.installArtifact(exe); // This *creates* a Run step in the build graph, to be executed when another // step is evaluated that depends on it. The next line below will establish // such a dependency. const run_cmd = b.addRunArtifact(exe); // By making the run step depend on the install step, it will be run from the // installation directory rather than directly from within the cache directory. // This is not necessary, however, if the application depends on other installed // files, this ensures they will be present and in the expected location. run_cmd.step.dependOn(b.getInstallStep()); // This allows the user to pass arguments to the application in the build // command itself, like this: `zig build run -- arg1 arg2 etc` if (b.args) |args| { run_cmd.addArgs(args); } // This creates a build step. It will be visible in the `zig build --help` menu, // and can be selected like this: `zig build run` // This will evaluate the `run` step rather than the default, which is "install". const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); // Creates a step for unit testing. This only builds the test executable // but does not run it. //const lib_unit_tests = b.addTest(.{ // .root_source_file = b.path("src/root.zig"), // .target = target, // .optimize = optimize, //}); //const run_lib_unit_tests = b.addRunArtifact(lib_unit_tests); const exe_unit_tests = b.addTest(.{ .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests); // Similar to creating the run step earlier, this exposes a `test` step to // the `zig build --help` menu, providing a way for the user to request // running the unit tests. const test_step = b.step("test", "Run unit tests"); //test_step.dependOn(&run_lib_unit_tests.step); test_step.dependOn(&run_exe_unit_tests.step); } opaque-store-0.2.0/server/build.zig.zon000066400000000000000000000033311473305203000200570ustar00rootroot00000000000000.{ // This is the default name used by packages depending on this one. For // example, when a user runs `zig fetch --save `, this field is used // as the key in the `dependencies` table. Although the user can choose a // different name, most users will stick with this provided value. // // It is redundant to include "zig" in this name because it is already // within the Zig package namespace. .name = "opaqueztore", // This is a [Semantic Version](https://semver.org/). // In a future version of Zig it will be used for package deduplication. .version = "0.1.0", // This field is optional. // This is currently advisory only; Zig does not yet do anything // with this value. //.minimum_zig_version = "0.11.0", // This field is optional. // Each dependency must either provide a `url` and `hash`, or a `path`. // `zig build --fetch` can be used to fetch all dependencies of a package, recursively. // Once all dependencies are fetched, `zig build` no longer requires // internet connectivity. .dependencies = .{ .@"zig-toml" = .{ .url = "git+https://github.com/stef/zig-toml/?ref=HEAD#7aa1afa601245b80d1bc988638cda86546a8f83b", .hash = "122028a55546adbba6a6adf7885de5c857aca415e5a5ce1145467fa07625abea7f9f", }, .@"zig-bearssl" = .{ .url = "git+https://github.com/stef/zig-bearssl/?ref=HEAD#4e69fead9c76ab1a9d23d747e133815db4045dd2", .hash = "1220cc068b33ccac81135e3247fda200d9621c679b2b7664fe164cde7cb7c5dcf29e", }, }, .paths = .{ "build.zig", "build.zig.zon", "src", // For example... //"LICENSE", //"README.md", }, } opaque-store-0.2.0/server/cert.pem000066400000000000000000000011131473305203000170740ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIBhTCCASugAwIBAgIURt1h20rXWGwyV5nuLDp2NBaXsgkwCgYIKoZIzj0EAwIw GDEWMBQGA1UEAwwNc3BoaW54IG9yYWNsZTAeFw0yMDA5MjkyMTI5MDBaFw0yMTA5 MjQyMTI5MDBaMBgxFjAUBgNVBAMMDXNwaGlueCBvcmFjbGUwWTATBgcqhkjOPQIB BggqhkjOPQMBBwNCAATPl01K0Nuxm4wZaYzS4AvaXy4pIG96Zk5XC1o0TmkdnNPb kgSUm6dx1OVvx3u8kVGRHYfgC7C4I414W2v41Hb4o1MwUTAdBgNVHQ4EFgQUtpha TRgMR7SeM7gYPKoq8L874tcwHwYDVR0jBBgwFoAUtphaTRgMR7SeM7gYPKoq8L87 4tcwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAgNIADBFAiEAnN1Y9WDfVW6f slgOnPs8eQdyoqA7S/rFf9wE/ZxR4tECICfCYMKpIRMYPEk2C+kqoJueB/JVdGKh pYxdMvjx8bsj -----END CERTIFICATE----- opaque-store-0.2.0/server/opaque-stored.cfg000066400000000000000000000033031473305203000207100ustar00rootroot00000000000000# config is read in this order from the following locations, later ones # overriding settings from the earlier ones: # - /etc/opaque-stored/config # - ~/.config/opaque-stored/config # - ~/.opaque-storedrc # - ./opaque-stored.cfg [server] # the ipv4 address the server is listening on #address="127.0.0.1" # ssl key ssl_key="server.der" # ssl cert ssl_cert="cert.pem" # the port on which the server is listening, use 443 if available, so that # the server can be accessed from behind tight firewalls, default: 8080 port=2523 # tcp connection timeouts, increase in case you have bad networks, with the # caveat that this might lead to easier resource exhaustion - blocking all # workers. #timeout=3 # the root directory where all data is stored, default: /var/lib/opaque-stored datadir="data" # how many worker processes can run in parallel # max_kids=5 # whether to produce some output verbose=true # key record_salt="some random string to salt the record ids" # Especially if you run a public server you want to limit the maximum size of # stored blobs max_blob_size=8192 # lock a record after this many failed password attempts. max_fails=3 # a file containing the long-term signing key of the server - this is only # needed for participation in threshold setups. Can be generated by running the # client with parameter: "opaquestore genltsigkey >ltsigkey.key" ltsigkey="ltsigkey.key" # set how long a message is considered fresh during a DKG protocol, any # messages that have timestamps that are older than this many seconds will # abort the DKG protocol. Increase this value if you have/expect laggy links. ts_epsilon=600 # the number of recovery tokens a server holds for each blob max_recovery_tokens=5 opaque-store-0.2.0/server/server.der000066400000000000000000000001711473305203000174410ustar00rootroot000000000000000w SE ~;yj1ǚw ?x *H=DBϗMJ۱i _.) ozfNW Z4Niےqo{Q #x[kvopaque-store-0.2.0/server/src/000077500000000000000000000000001473305203000162275ustar00rootroot00000000000000opaque-store-0.2.0/server/src/main.zig000066400000000000000000001336311473305203000176750ustar00rootroot00000000000000const std = @import("std"); const builtin = @import("builtin"); const toml = @import("toml"); const ssl = @import("bearssl"); const mem = std.mem; const net = std.net; const posix = std.posix; const BufSet = std.BufSet; const blake2b = std.crypto.hash.blake2.Blake2b256; const utils = @import("utils.zig"); const secret_allocator = @import("secret_allocator.zig"); pub const sodium = @cImport({ @cInclude("sodium.h"); }); pub const o = @cImport({ @cInclude("opaque.h"); }); pub const oprf = @cImport({ @cInclude("oprf/oprf.h"); }); pub const toprf = @cImport({ @cInclude("oprf/toprf.h"); }); pub const tp_dkg = @cImport({ @cInclude("oprf/tp-dkg.h"); }); pub const workaround = @cImport({ @cInclude("workaround.h"); }); pub const stdio = @cImport({ @cInclude("stdio.h"); }); const DEBUG = (builtin.mode == std.builtin.OptimizeMode.Debug); const warn = std.debug.print; /// allocator var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator(); //const allocator = std.heap.c_allocator; var s_state = secret_allocator.secretAllocator(allocator); const s_allocator = s_state.allocator(); /// stdout const stdout_file = std.io.getStdOut().writer(); var bw = std.io.bufferedWriter(stdout_file); const stdout = bw.writer(); const sslStream = ssl.Stream(*net.Stream, *net.Stream); var conn: net.Server.Connection = undefined; const recovery_token_bytes = 16; /// server config data const Config = struct { verbose: bool, /// the ipv4 address the server is listening on address: []const u8, port: u16, /// tcp connection timeouts timeout: u16, /// the root directory where all data is stored datadir: [:0]const u8, /// how many processes can run in parallel max_kids: u16, /// server key in PEM format ssl_key: [:0]const u8, /// server cert in PEM format ssl_cert: [:0]const u8, /// server long-term signature key for DKG ltsigkey: [:0]const u8, /// maximum age still considered fresh, in seconds ts_epsilon: u64, /// salt for hashing record ids record_salt: []const u8, /// do not allow blobs bigger than this size max_blob_size: usize, /// how many failed password tries until locking? max_fails: u8, /// how many recovery tokens / record max_recovery_tokens: u8, }; const CreateReq = extern struct { id: [sodium.crypto_generichash_BYTES]u8 align(1), alpha: [sodium.crypto_core_ristretto255_BYTES]u8 align(1), }; const OpaqueReq = extern struct { id: [sodium.crypto_generichash_BYTES]u8 align(1), ke1: [o.OPAQUE_USER_SESSION_PUBLIC_LEN]u8 align(1), }; const UnlockReq = extern struct { id: [sodium.crypto_generichash_BYTES]u8 align(1), rtoken: [recovery_token_bytes]u8 align(1), }; const OpaqueStoreOp = enum(u8) { CREATE = 0, UPDATE = 0x33, GET_RTOKEN = 0x50, GET = 0x66, CREATE_DKG = 0xf0, UNLOCK =0xf5, DELETE = 0xff, _, }; const WriteBlobError = error{Error}; const LoadBlobError = error{ WrongSize, WrongRead, }; fn expandpath(path: []const u8) [:0]u8 { if(path[0]!='~') { return allocator.dupeZ(u8,path) catch @panic("OOM"); } const home = posix.getenv("HOME") orelse "/nonexistant"; const xpath = mem.concat(allocator, u8, &[_][]const u8{ home, path }) catch @panic("OOM"); const xpathZ = allocator.dupeZ(u8, xpath) catch @panic("OOM"); allocator.free(xpath); return xpathZ; } fn loadcfg() anyerror!Config { @setCold(true); const home = posix.getenv("HOME") orelse "/nonexistant"; const cfg1 = mem.concat(allocator, u8, &[_][]const u8{ home, "/.config/opaque-stored/config" }) catch unreachable; defer allocator.free(cfg1); const cfg2 = mem.concat(allocator, u8, &[_][]const u8{ home, "/.opaque-storedrc" }) catch unreachable; defer allocator.free(cfg2); const paths = [_][]const u8{ "/etc/opaque-stored/config", cfg1, cfg2, "opaque-stored.cfg", }; // default values for the Config structure var cfg = Config{ .verbose = true, .address = "127.0.0.1", .port = 443, .timeout = 3, .datadir = "/var/lib/opaque-stored", .max_kids = 5, .ssl_key = "server.pem", .ssl_cert = "certs.pem", .ltsigkey = "ltsig.key", .ts_epsilon = 600, .record_salt = undefined, .max_blob_size = 1024 + 24 + 16, .max_fails = 3, .max_recovery_tokens = 5, }; //var parser: toml.Parser = undefined; for (paths) |filename| { if(toml.parseFile(allocator, filename)) |p| { var parser: toml.Parser = p; defer parser.deinit(); const t = parser.parse(); if (t) |table| { defer table.deinit(); if (table.keys.get("server")) |server| { cfg.verbose = if (server.Table.keys.get("verbose")) |v| v.Boolean else cfg.verbose; cfg.address = if (server.Table.keys.get("address")) |v| try allocator.dupe(u8, v.String) else cfg.address; cfg.port = if (server.Table.keys.get("port")) |v| @intCast(v.Integer) else cfg.port; cfg.timeout = if (server.Table.keys.get("timeout")) |v| @intCast(v.Integer) else cfg.timeout; cfg.datadir = if (server.Table.keys.get("datadir")) |v| expandpath(v.String) else cfg.datadir; cfg.max_kids = if (server.Table.keys.get("max_kids")) |v| @intCast(v.Integer) else cfg.max_kids; cfg.ssl_key = if (server.Table.keys.get("ssl_key")) |v| expandpath(v.String) else cfg.ssl_key; cfg.ssl_cert = if (server.Table.keys.get("ssl_cert")) |v| expandpath(v.String) else cfg.ssl_cert; cfg.ltsigkey = if (server.Table.keys.get("ltsigkey")) |v| expandpath(v.String) else cfg.ltsigkey; cfg.ts_epsilon = if (server.Table.keys.get("ts_epsilon")) |v| @intCast(v.Integer) else cfg.ts_epsilon; if (server.Table.keys.get("record_salt")) |v| { cfg.record_salt = allocator.dupe(u8, v.String) catch @panic("oom"); } else { warn("missing record_salt in configuration\nabort.", .{}); posix.exit(1); } cfg.max_blob_size = if (server.Table.keys.get("max_blob_size")) |v| @intCast(v.Integer) else cfg.max_blob_size; cfg.max_fails = if (server.Table.keys.get("max_fails")) |v| @intCast(v.Integer) else cfg.max_fails; cfg.max_recovery_tokens = if (server.Table.keys.get("max_recovery_tokens")) |v| @intCast(v.Integer) else cfg.max_recovery_tokens; } } else |err| { if (err == error.FileNotFound) continue; warn("error loading config {s}: {}\n", .{ filename, err }); } } else |err| { if (err == error.FileNotFound) continue; warn("error loading config {s}: {}\n", .{ filename, err }); return err; } } if (cfg.verbose) { warn("cfg.address: {s}\n", .{cfg.address}); warn("cfg.port: {}\n", .{cfg.port}); warn("cfg.datadir: {s}\n", .{cfg.datadir}); warn("cfg.ssl_key: {s}\n", .{cfg.ssl_key}); warn("cfg.ssl_cert: {s}\n", .{cfg.ssl_cert}); warn("cfg.ltsigkey: {s}\n", .{cfg.ltsigkey}); warn("cfg.ts_epsilon: {}\n", .{cfg.ts_epsilon}); warn("cfg.verbose: {}\n", .{cfg.verbose}); warn("cfg.record_salt: \"{s}\"\n", .{cfg.record_salt}); warn("cfg.max_blob_size: {}\n", .{cfg.max_blob_size}); warn("cfg.max_recovery_tokens: {}\n", .{cfg.max_recovery_tokens}); } return cfg; } fn fail(s: *sslStream, cfg: *const Config) noreturn { @setCold(true); if (cfg.verbose) { std.debug.dumpCurrentStackTrace(@frameAddress()); warn("fail\n", .{}); std.debug.dumpCurrentStackTrace(@returnAddress()); } _ = s.write("\x00\x04fail") catch null; _ = s.flush() catch null; _ = std.os.linux.shutdown(conn.stream.handle, std.os.linux.SHUT.RDWR); _ = s.close() catch null; posix.exit(0); } fn read_pkt(s: *sslStream) []u8 { var lenbuf: [2]u8 = undefined; _ = s.read(lenbuf[0..]) catch |err| { handle_read_err(err, s); }; const pktlen = std.mem.readInt(u16, lenbuf[0..2], std.builtin.Endian.big); var buf : []u8 = allocator.alloc(u8, pktlen) catch @panic("OOM"); var i: usize = 0; while(i (1<<16) - 1) { warn("msg is too long: {}, max {}\n", .{msg.len, (1<<16) - 1}); fail(s,cfg); } std.mem.writeInt(u16, pkt[0..2], @truncate(msg.len), std.builtin.Endian.big); @memcpy(pkt[2..], msg); var i: usize = 0; while(i= cfg.max_fails) { posix.close(l); posix.close(f); warn("record {s} is locked {} > {}\n", .{hexid, ctr[0], cfg.max_fails}); std.fs.cwd().deleteFile(lock) catch |e| { warn("failed delete {s}: error: {}\n", .{lock, e}); fail(s, cfg); }; fail(s,cfg); } ctr[0]+=1; try posix.lseek_SET(f, 0); _ = try posix.write(f, &ctr); return cfg.max_fails - ctr[0]; } else |err| { if(err == error.PathAlreadyExists) continue; return err; } } warn("failed to acquire failctr lock\n",.{}); fail(s,cfg); } fn load_rtokens(cfg: *const Config, s: *sslStream, hexid: []const u8, token_buf: []u8) anyerror!void { const lock = mem.concat(allocator, u8, &[_][]const u8{ cfg.datadir, "/", hexid, "/", "rtokens.lock" }) catch @panic("oom"); defer allocator.free(lock); const start = std.time.milliTimestamp(); while(std.time.milliTimestamp() < start + 500) { // wait max 1/2 second if (posix.open(lock, .{.ACCMODE = .WRONLY, .CREAT = true, .EXCL = true }, 0o600)) |l| { defer { posix.close(l); std.fs.cwd().deleteFile(lock) catch |e| { warn("failed delete {s}: error: {}\n", .{lock, e}); fail(s, cfg); }; } const path = mem.concat(allocator, u8, &[_][]const u8{ cfg.datadir, "/", hexid, "/", "rtokens" }) catch @panic("oom"); defer allocator.free(path); const f = posix.open(path, .{.ACCMODE = .RDONLY}, 0o600) catch |e| { if(e == error.FileNotFound) { @memset(token_buf[0..], 0); return; } warn("error open recovery token file for {s}, error: {}\n",.{path,e}); fail(s,cfg); }; defer posix.close(f); _ = try posix.read(f, token_buf); return; } else |err| { if(err == error.PathAlreadyExists) continue; return err; } } warn("failed to acquire rtokens lock for {s}\n",.{lock}); fail(s,cfg); } fn save_rtokens(cfg: *const Config, s: *sslStream, hexid: []const u8, token_buf: []u8) anyerror!void { const lock = mem.concat(allocator, u8, &[_][]const u8{ cfg.datadir, "/", hexid, "/", "rtokens.lock" }) catch @panic("oom"); defer allocator.free(lock); const start = std.time.milliTimestamp(); while(std.time.milliTimestamp() < start + 500) { // wait max 1/2 second if (posix.open(lock, .{.ACCMODE = .WRONLY, .CREAT = true, .EXCL = true }, 0o600)) |l| { defer { posix.close(l); std.fs.cwd().deleteFile(lock) catch |e| { warn("failed delete {s}: error: {}\n", .{lock, e}); fail(s, cfg); }; } const path = mem.concat(allocator, u8, &[_][]const u8{ cfg.datadir, "/", hexid, "/", "rtokens" }) catch @panic("oom"); defer allocator.free(path); const f = posix.open(path, .{.ACCMODE = .WRONLY, .CREAT = true }, 0o600) catch |e| { warn("error open recovery token file for {s}, error: {}\n",.{path,e}); fail(s,cfg); }; defer posix.close(f); _ = try posix.write(f, token_buf); return; } else |err| { if(err == error.PathAlreadyExists) continue; return err; } } warn("failed to acquire rtokens lock for {s}\n",.{lock}); fail(s,cfg); } /// converts a 32B string to a 64B hex string /// caller is responsible to free returned string fn tohexid(id: [32]u8) anyerror![]u8 { const hexbuf = allocator.alloc(u8, 64) catch @panic("oom"); return std.fmt.bufPrint(hexbuf, "{x:0>64}", .{std.fmt.fmtSliceHexLower(id[0..])}); } fn dkg(cfg: *const Config, s: *sslStream, msg0: []const u8, k: [*]u8) void { var ltsigkey: []u8 = undefined; if (posix.open(cfg.ltsigkey, .{.ACCMODE = .RDONLY }, 0)) |f| { defer posix.close(f); ltsigkey = s_allocator.alloc(u8, @intCast(sodium.crypto_sign_SECRETKEYBYTES)) catch @panic("oom"); _ = posix.read(f, ltsigkey) catch |err| { if (cfg.verbose) warn("cannot open {s}/{s} error: {}\n", .{ cfg.datadir, cfg.ltsigkey, err }); fail(s, cfg); }; } else |err| { if (err != error.FileNotFound) { if (cfg.verbose) warn("cannot open {s}/{s} error: {}\n", .{ cfg.datadir, cfg.ltsigkey, err }); fail(s, cfg); } warn("no ltsigkey found at : {s}/{s}\n", .{cfg.datadir, cfg.ltsigkey}); fail(s,cfg); } var peer = workaround.new_peerstate(); defer workaround.del_peerstate(@ptrCast(&peer)); const retsp = tp_dkg.tpdkg_start_peer(@ptrCast(peer), cfg.ts_epsilon, ltsigkey.ptr, @ptrCast(msg0.ptr)); if(retsp!=0) { warn("failed to start tp-dkg peer (error code: {})\n", .{retsp}); fail(s, cfg); } const n = @as(*tp_dkg.TP_DKG_PeerState, @ptrCast(peer)).n; const t = @as(*tp_dkg.TP_DKG_PeerState, @ptrCast(peer)).t; //warn("dkg {}/{}\n", .{t,n}); const peer_sig_pks: [][sodium.crypto_sign_PUBLICKEYBYTES]u8 = allocator.alloc([sodium.crypto_sign_PUBLICKEYBYTES]u8, n) catch @panic("oom"); defer allocator.free(peer_sig_pks); const peer_noise_pks: [][sodium.crypto_scalarmult_BYTES]u8 = allocator.alloc([sodium.crypto_scalarmult_BYTES]u8, n) catch @panic("oom"); defer allocator.free(peer_noise_pks); const noise_outs : []*tp_dkg.Noise_XK_session_t_s = allocator.alloc(*tp_dkg.Noise_XK_session_t_s, n) catch @panic("oom"); defer allocator.free(noise_outs); const noise_ins : []*tp_dkg.Noise_XK_session_t_s = allocator.alloc(*tp_dkg.Noise_XK_session_t_s, n) catch @panic("oom"); defer allocator.free(noise_ins); const ishares : [][toprf.TOPRF_Share_BYTES]u8 = allocator.alloc([toprf.TOPRF_Share_BYTES]u8, n) catch @panic("oom"); defer allocator.free(ishares); const xshares : [][toprf.TOPRF_Share_BYTES]u8 = allocator.alloc([toprf.TOPRF_Share_BYTES]u8, n) catch @panic("oom"); defer allocator.free(xshares); const commitments: [][sodium.crypto_core_ristretto255_BYTES]u8 = allocator.alloc([sodium.crypto_core_ristretto255_BYTES]u8, n * t) catch @panic("oom"); defer allocator.free(commitments); const peer_complaints: []u16 = allocator.alloc(u16, n * n) catch @panic("oom"); defer allocator.free(peer_complaints); const peer_my_complaints: []u8 = allocator.alloc(u8, n) catch @panic("oom"); defer allocator.free(peer_my_complaints); const peer_last_ts: []u64 = allocator.alloc(u64, n) catch @panic("oom"); defer allocator.free(peer_last_ts); tp_dkg.tpdkg_peer_set_bufs(@ptrCast(peer), @alignCast(@ptrCast(peer_sig_pks)), @alignCast(@ptrCast(peer_noise_pks)), @alignCast(@ptrCast(noise_outs)), @alignCast(@ptrCast(noise_ins)), @alignCast(@ptrCast(ishares)), @alignCast(@ptrCast(xshares)), @alignCast(@ptrCast(commitments)), @alignCast(@ptrCast(peer_complaints.ptr)), @alignCast(@ptrCast(peer_my_complaints.ptr)), @ptrCast(peer_last_ts.ptr)); while(tp_dkg.tpdkg_peer_not_done(@ptrCast(peer))!=0) { const cur_step = @as(*tp_dkg.TP_DKG_PeerState, @ptrCast(peer)).step; const msglen = tp_dkg.tpdkg_peer_input_size(@ptrCast(peer)); //if(DEBUG) warn("[{}] input msglen: {}\n", .{cur_step, msglen}); //var msg : []u8 = allocator.alloc(u8, tp_dkg.tpdkg_peer_input_size(@ptrCast(peer))) catch @panic("oom"); //defer allocator.free(msg); var msg : ?[*]u8 = undefined; if(msglen > 0) { const _msg = read_pkt(s); if (msglen != _msg.len) { fail(s, cfg); } msg = _msg.ptr; } else { msg = null; } const resp_size = tp_dkg.tpdkg_peer_output_size(@ptrCast(peer)); //if(DEBUG) warn("[{}] response size: {}\n", .{cur_step, resp_size}); const resp : []u8 = allocator.alloc(u8, resp_size) catch @panic("oom"); defer allocator.free(resp); const ret = tp_dkg.tpdkg_peer_next(@ptrCast(peer), msg, msglen, resp.ptr, resp.len); if(0!=ret) { warn("TP DKG failed with {} in step {}.", .{ret, cur_step}); tp_dkg.tpdkg_peer_free(@ptrCast(peer)); fail(s, cfg); } if(resp.len>0) { //if(DEBUG) { // warn("\nsending: ",.{}); // utils.hexdump(resp[0..]); //} send_pkt(s, cfg, resp); } } const share = s_allocator.alloc(u8, 33) catch @panic("oom"); defer s_allocator.free(share); workaround.extract_share(@ptrCast(peer), share.ptr); //warn("share ", .{}); //utils.hexdump(share[0..]); @memcpy(k, share[1..]); } fn opaque_session(cfg: *const Config, s: *sslStream, req: *const OpaqueReq, sk: ?*[o.OPAQUE_SHARED_SECRETBYTES]u8) void { const hexid = tohexid(req.id) catch @panic("failed to hexid"); defer allocator.free(hexid); // we hash the id, with some local secret, so clients have no control over the record ids // we abuse the key here, because the salt is expected to be exactly 16B // keys however can be of arbitrary size var local_id = [_]u8{0} ** blake2b.digest_length; blake2b.hash(req.id[0..], local_id[0..], .{ .key = cfg.record_salt }); const local_hexid = tohexid(local_id) catch @panic("failed to hexid"); defer allocator.free(local_hexid); // increment fail counter const attempts = load_failctr(cfg, s, local_hexid) catch |e| { warn("incrementing fail ctr for {s} failed {}\n", .{local_hexid, e}); fail(s, cfg); }; const rec: []u8 = load_blob(s_allocator, cfg, local_hexid, "rec", o.OPAQUE_USER_RECORD_LEN) catch |e| { warn("loading record for {s} failed {}\n", .{local_hexid, e}); fail(s, cfg); }; defer s_allocator.free(rec); var zero: ?[]u8 = null; if(load_blob(s_allocator, cfg, local_hexid, "zero", toprf.TOPRF_Share_BYTES)) |b| { zero = b; } else |e| { if(e != error.FileNotFound) { warn("loading record for {s} failed {}\n", .{local_hexid, e}); fail(s, cfg); } } const ids : o.Opaque_Ids = .{ .idU_len = 0, .idU = null, .idS_len = 0, .idS = null, }; const ctx = "opaque-store"; var ke2 = [_]u8{0} ** o.OPAQUE_SERVER_SESSION_LEN; var _sk = [_]u8{0} ** o.OPAQUE_SHARED_SECRETBYTES; var authU = [_]u8{0} ** sodium.crypto_auth_hmacsha512_BYTES; if(zero) |z| { defer s_allocator.free(z); var ssid_S = [_]u8{0} ** (14 + sodium.crypto_core_ristretto255_BYTES); @memcpy(ssid_S[0..14], "OPAQUE session"[0..]); @memcpy(ssid_S[14..], req.ke1[0..sodium.crypto_core_ristretto255_BYTES]); if(DEBUG) { warn("zero: ",.{}); utils.hexdump(z[0..]); warn("ssid_S: ",.{}); utils.hexdump(ssid_S[0..]); } if(0!=o.opaque_CreateCredentialResponse_core(req.ke1[0..].ptr, rec.ptr, &ids, ctx.ptr, ctx.len, z[0..].ptr, ssid_S[0..].ptr, ssid_S[0..].len, ke2[0..].ptr, _sk[0..].ptr, authU[0..].ptr)) { warn("failed to create credential response\n",.{}); } } else { if(0!=o.opaque_CreateCredentialResponse(req.ke1[0..].ptr, rec.ptr, &ids, ctx.ptr, ctx.len, ke2[0..].ptr, _sk[0..].ptr, authU[0..].ptr)) { warn("failed to create credential response\n",.{}); } } if(sk) |dst| { @memcpy(dst, _sk[0..].ptr); } _ = s.write(ke2[0..]) catch |e| { warn("error sending credential response: {}\n", .{e}); @panic("network error"); }; var aux = [_]u8{0} ** 4; std.mem.writeInt(i32, aux[0..4], attempts, std.builtin.Endian.big); _ = s.write(aux[0..]) catch |e| { warn("error sending remaining attempts: {}\n", .{e}); @panic("network error"); }; s.flush() catch |e| { warn("failed to flush connection: {}\n", .{e}); @panic("network error"); }; var ke3: [sodium.crypto_auth_hmacsha512_BYTES]u8 = undefined; _ = s.read(ke3[0..]) catch |err| { handle_read_err(err, s); }; if(0!=o.opaque_UserAuth(authU[0..].ptr,ke3[0..].ptr)) { warn("failed user authentication\n", .{}); fail(s, cfg); } // zero fail counter const failctr_path = mem.concat(allocator, u8, &[_][]const u8{ cfg.datadir, "/", local_hexid, "/", "failctr" }) catch @panic("oom"); defer allocator.free(failctr_path); std.fs.cwd().deleteFile(failctr_path) catch |e| { warn("failed delete {s}: error: {}\n", .{failctr_path, e}); fail(s, cfg); }; } const CB_Ctx = struct { cfg: *const Config, s: *sslStream, msg0: []u8, }; fn keygen_cb(_ctx_: ?*anyopaque, k: [*c]u8) callconv(.C) c_int { var ctx: *CB_Ctx = undefined; if(_ctx_) |_ctx| { ctx = @ptrCast(@alignCast(_ctx)); } else { return 1; } dkg(ctx.cfg, ctx.s, ctx.msg0, @ptrCast(k)); return 0; } fn create(cfg: *const Config, s: *sslStream, req: *const CreateReq, op : OpaqueStoreOp) void { // we hash the id, with some local secret, so clients have no control over the record ids // we abuse the key here, because the salt is expected to be exactly 16B // keys however can be of arbitrary size var local_id = [_]u8{0} ** blake2b.digest_length; blake2b.hash(req.id[0..], &local_id, .{ .key = cfg.record_salt }); const hexid = tohexid(local_id) catch @panic("failed to hexid"); defer allocator.free(hexid); const path = mem.concat(allocator, u8, &[_][]const u8{ cfg.datadir, "/", hexid[0..] }) catch @panic("oom"); defer allocator.free(path); if (utils.dir_exists(path)) fail(s, cfg); var _sec = [_]u8{0} ** o.OPAQUE_REGISTER_SECRET_LEN; var _pub = [_]u8{0} ** o.OPAQUE_REGISTER_PUBLIC_LEN; var zero = [_]u8{0} ** toprf.TOPRF_Share_BYTES; if(op == OpaqueStoreOp.CREATE_DKG) { var msg0 = mem.zeroes([tp_dkg.tpdkg_msg0_SIZE]u8); const msg0len = s.read(msg0[0..]) catch |err| { handle_read_err(err, s); }; if(msg0len != msg0.len) { fail(s, cfg); } const zerolen = s.read(zero[0..]) catch |err| { handle_read_err(err, s); }; if(zerolen != zero.len) { fail(s, cfg); } var keygen_ctx: CB_Ctx = .{ .cfg = cfg, .s = s, .msg0 = &msg0 }; var ssid_S = [_]u8{0} ** (13 + sodium.crypto_core_ristretto255_BYTES); @memcpy(ssid_S[0..13], "OPAQUE create"[0..]); @memcpy(ssid_S[13..], req.alpha[0..]); if(DEBUG) { warn("zero: ",.{}); utils.hexdump(zero[0..]); warn("ssid_S: ",.{}); utils.hexdump(ssid_S[0..]); } if(0!=o.opaque_CreateRegistrationResponse_core(req.alpha[0..].ptr, null, keygen_cb, &keygen_ctx, zero[0..].ptr, ssid_S[0..].ptr, ssid_S.len, _sec[0..].ptr, _pub[0..].ptr)) { fail(s,cfg); } } else { if(0!=o.opaque_CreateRegistrationResponse(req.alpha[0..].ptr, null, _sec[0..].ptr, _pub[0..].ptr)) { fail(s,cfg); } } _ = s.write(_pub[0..]) catch |e| { warn("error: {}\n", .{e}); @panic("network error"); }; _ = s.flush() catch |e| { warn("failed to flush connection: {}\n", .{e}); @panic("network error"); }; var rec0: [o.OPAQUE_REGISTRATION_RECORD_LEN]u8 = undefined; _ = s.read(rec0[0..]) catch |err| { handle_read_err(err, s); }; var blob: []u8 = read_pkt(s); defer allocator.free(blob); if(blob.len > cfg.max_blob_size) { warn("attempt to create blob bigger than allowed size: {}\n", .{blob.len}); fail(s,cfg); } var rec = [_]u8{0} ** o.OPAQUE_USER_RECORD_LEN; o.opaque_StoreUserRecord(@ptrCast(&_sec), rec0[0..].ptr, rec[0..].ptr); save_blob(cfg, hexid, "rec", rec[0..]) catch fail(s, cfg); save_blob(cfg, hexid, "blob", blob[0..]) catch fail(s, cfg); if(op == OpaqueStoreOp.CREATE_DKG) { save_blob(cfg, hexid, "zero", zero[0..]) catch fail(s, cfg); } _ = s.write("ok") catch |e| { warn("error: {}\n", .{e}); @panic("network error"); }; s.flush() catch |e| { warn("failed to flush connection: {}\n", .{e}); @panic("network error"); }; } fn get(cfg: *const Config, s: *sslStream, req: *const OpaqueReq) void { opaque_session(cfg,s,req, null); // we hash the id, with some local secret, so clients have no control over the record ids // we abuse the key here, because the salt is expected to be exactly 16B // keys however can be of arbitrary size var local_id = [_]u8{0} ** blake2b.digest_length; blake2b.hash(req.id[0..], local_id[0..], .{ .key = cfg.record_salt }); const local_hexid = tohexid(local_id) catch @panic("failed to hexid"); defer allocator.free(local_hexid); const blob: []u8 = load_blob(allocator, cfg, local_hexid, "blob", null) catch |e| { warn("loading blob for {s} failed {}\n", .{local_hexid, e}); fail(s, cfg); }; defer allocator.free(blob); send_pkt(s, cfg, blob[0..]); } fn update(cfg: *const Config, s: *sslStream, req: *const OpaqueReq) void { opaque_session(cfg,s,req, null); var blob: []u8 = read_pkt(s); defer allocator.free(blob); if(blob.len > cfg.max_blob_size) { warn("attempt to create blob bigger than allowed size: {}\n", .{blob.len}); fail(s,cfg); } // we hash the id, with some local secret, so clients have no control over the record ids // we abuse the key here, because the salt is expected to be exactly 16B // keys however can be of arbitrary size var local_id = [_]u8{0} ** blake2b.digest_length; blake2b.hash(req.id[0..], &local_id, .{ .key = cfg.record_salt }); const hexid = tohexid(local_id) catch @panic("failed to hexid"); defer allocator.free(hexid); save_blob(cfg, hexid, "blob", blob[0..]) catch fail(s, cfg); _ = s.write("ok") catch |e| { warn("error: {}\n", .{e}); @panic("network error"); }; s.flush() catch |e| { warn("failed to flush connection: {}\n", .{e}); @panic("network error"); }; } fn delete(cfg: *const Config, s: *sslStream, req: *const OpaqueReq) void { opaque_session(cfg,s,req, null); // we hash the id, with some local secret, so clients have no control over the record ids // we abuse the key here, because the salt is expected to be exactly 16B // keys however can be of arbitrary size var local_id = [_]u8{0} ** blake2b.digest_length; blake2b.hash(req.id[0..], local_id[0..], .{ .key = cfg.record_salt }); const local_hexid = tohexid(local_id) catch @panic("failed to hexid"); defer allocator.free(local_hexid); const path = mem.concat(allocator, u8, &[_][]const u8{ cfg.datadir, "/", local_hexid[0..] }) catch @panic("oom"); defer allocator.free(path); if (!utils.dir_exists(path)) fail(s, cfg); std.fs.cwd().deleteTree(path) catch fail(s, cfg); _ = s.write("ok") catch |e| { warn("error: {}\n", .{e}); @panic("network error"); }; s.flush() catch |e| { warn("failed to flush connection: {}\n", .{e}); @panic("network error"); }; } fn get_rtoken(cfg: *const Config, s: *sslStream, req: *const OpaqueReq) void { var sk: []u8 = undefined; sk = s_allocator.alloc(u8, @intCast(o.OPAQUE_SHARED_SECRETBYTES)) catch @panic("oom"); defer s_allocator.free(sk); opaque_session(cfg,s,req, sk[0..o.OPAQUE_SHARED_SECRETBYTES]); // we hash the id, with some local secret, so clients have no control over the record ids // we abuse the key here, because the salt is expected to be exactly 16B // keys however can be of arbitrary size var local_id = [_]u8{0} ** blake2b.digest_length; blake2b.hash(req.id[0..], local_id[0..], .{ .key = cfg.record_salt }); const local_hexid = tohexid(local_id) catch @panic("failed to hexid"); defer allocator.free(local_hexid); var rtoken_buf : []u8 = undefined; rtoken_buf = allocator.alloc(u8, ((cfg.max_recovery_tokens)*recovery_token_bytes)) catch @panic("oom"); @memset(rtoken_buf, 0); load_rtokens(cfg, s, local_hexid, rtoken_buf[0..]) catch |e| { warn("failed loading rtokens for {s}, error: {}\n", .{local_hexid, e}); fail(s, cfg); }; const rtokens: *[*][recovery_token_bytes]u8 = @ptrCast(&rtoken_buf); const zero = [_]u8{0}**recovery_token_bytes; for(0..cfg.max_recovery_tokens) |i| { if(mem.eql(u8,&zero, &rtokens.*[i])) { std.crypto.random.bytes(rtokens.*[i][0..]); var ct = [_]u8{0} ** (sodium.crypto_secretbox_NONCEBYTES + recovery_token_bytes + sodium.crypto_secretbox_MACBYTES); sodium.randombytes(ct[0..sodium.crypto_secretbox_NONCEBYTES].ptr, sodium.crypto_secretbox_NONCEBYTES); _ = sodium.crypto_secretbox_easy(ct[sodium.crypto_secretbox_NONCEBYTES..].ptr, rtokens.*[i][0..].ptr, rtokens.*[i].len , ct[0..sodium.crypto_secretbox_NONCEBYTES].ptr, sk[0..].ptr); save_rtokens(cfg, s, local_hexid, rtoken_buf[0..]) catch |e| { warn("failed saving rtokens for {s}, error: {}\n", .{local_hexid, e}); fail(s, cfg); }; send_pkt(s, cfg, ct[0..]); // todo save list return; } } var prng = std.rand.DefaultPrng.init(blk: { var seed: u64 = undefined; std.posix.getrandom(std.mem.asBytes(&seed)) catch |e| { warn("getrandom returned error: {}\n", .{e}); posix.exit(1); }; break :blk seed; }); const rand = prng.random(); const i = rand.uintLessThan(usize, cfg.max_recovery_tokens); var ct = [_]u8{0} ** (sodium.crypto_secretbox_NONCEBYTES + recovery_token_bytes + sodium.crypto_secretbox_MACBYTES); sodium.randombytes(ct[0..sodium.crypto_secretbox_NONCEBYTES].ptr, sodium.crypto_secretbox_NONCEBYTES); _ = sodium.crypto_secretbox_easy(ct[sodium.crypto_secretbox_NONCEBYTES..].ptr, rtokens.*[i][0..].ptr, rtokens.*[i].len , ct[0..sodium.crypto_secretbox_NONCEBYTES].ptr, sk[0..].ptr); send_pkt(s, cfg, ct[0..]); } fn unlock(cfg: *const Config, s: *sslStream, req: *const UnlockReq) void { const zero = [_]u8{0}**recovery_token_bytes; if(std.crypto.utils.timingSafeEql([recovery_token_bytes]u8, zero, req.rtoken)) { warn("zero recovery token detected, aborting.\n", .{}); fail(s,cfg); } // we hash the id, with some local secret, so clients have no control over the record ids // we abuse the key here, because the salt is expected to be exactly 16B // keys however can be of arbitrary size var local_id = [_]u8{0} ** blake2b.digest_length; blake2b.hash(req.id[0..], local_id[0..], .{ .key = cfg.record_salt }); const local_hexid = tohexid(local_id) catch @panic("failed to hexid"); defer allocator.free(local_hexid); var rtoken_buf : []u8 = undefined; rtoken_buf = allocator.alloc(u8, ((cfg.max_recovery_tokens)*recovery_token_bytes)) catch @panic("oom"); @memset(rtoken_buf, 0); load_rtokens(cfg, s, local_hexid, rtoken_buf[0..]) catch |e| { warn("failed loading rtokens for {s}, error: {}\n", .{local_hexid, e}); fail(s, cfg); }; var msg : *const [2]u8 = "no"[0..2]; const rtokens: *[*][recovery_token_bytes]u8 = @ptrCast(&rtoken_buf); for(0..cfg.max_recovery_tokens) |i| { if(std.crypto.utils.timingSafeEql([recovery_token_bytes]u8, rtokens.*[i][0..].*, req.rtoken)) { msg = "ok"[0..2]; const failpath = mem.concat(allocator, u8, &[_][]const u8{ cfg.datadir, "/", local_hexid, "/", "failctr" }) catch @panic("oom"); defer allocator.free(failpath); std.fs.cwd().deleteFile(failpath) catch |e| { if(e != error.FileNotFound) { warn("failed delete {s}: error: {}\n", .{failpath, e}); fail(s, cfg); } }; @memset(rtokens.*[i][0..], 0); save_rtokens(cfg, s, local_hexid, rtoken_buf[0..]) catch |e| { warn("failed saving rtokens for {s}, error: {}\n", .{local_hexid, e}); fail(s, cfg); }; } } _ = s.write(msg) catch |e| { warn("error: {}\n", .{e}); @panic("network error"); }; s.flush() catch |e| { warn("failed to flush connection: {}\n", .{e}); @panic("network error"); }; } fn handle_read_err(err: anyerror, s: *sslStream) noreturn { if(err==ssl.BearError.UNSUPPORTED_VERSION) { warn("{} unsupported TLS version. aborting.\n",.{conn.address}); s.close() catch unreachable; posix.exit(0); } else if(err==ssl.BearError.UNKNOWN_ERROR_582 or err==ssl.BearError.UNKNOWN_ERROR_552) { warn("{} unknown TLS error: {}. aborting.\n",.{conn.address, err}); s.close() catch unreachable; posix.exit(0); } else if(err==ssl.BearError.BAD_VERSION) { warn("{} bad TLS version. aborting.\n",.{conn.address}); s.close() catch unreachable; posix.exit(0); } warn("read error: {}\n",.{err}); @panic("network error"); } fn read_req(cfg: *const Config, s: *sslStream, comptime T: type, op: []const u8) anyerror!*T { var buf = allocator.alloc(u8, @sizeOf(T)) catch @panic("oom"); const buflen = s.read(buf[0..]) catch |err| { handle_read_err(err, s); return err; }; if(buflen != buf.len) { warn("invalid {s} request. aborting.\n",.{op}); } const req: *T = @ptrCast(buf[0..]); if (cfg.verbose) { const hexid = try tohexid(req.id); defer allocator.free(hexid); warn("{} op {s} {s}\n", .{conn.address, op, hexid}); } return req; } fn handler(cfg: *const Config, s: *sslStream) !void { var op_buf: [1]u8 = undefined; _ = s.read(op_buf[0..]) catch |err| { handle_read_err(err, s); }; const op = @as(OpaqueStoreOp, @enumFromInt(op_buf[0])); switch (op) { OpaqueStoreOp.CREATE_DKG, OpaqueStoreOp.CREATE => { const req: *CreateReq = read_req(cfg, s, CreateReq, "create"[0..]) catch |e| { warn("read create request failed with {}", .{e}); fail(s,cfg); }; defer allocator.free(@as(*[@sizeOf(CreateReq)]u8, @ptrCast(req))); create(cfg, s, req, op); }, OpaqueStoreOp.GET => { const req: *OpaqueReq = read_req(cfg, s, OpaqueReq, "get"[0..]) catch |e| { warn("read get request failed with {}", .{e}); fail(s,cfg); }; defer allocator.free(@as(*[@sizeOf(OpaqueReq)]u8, @ptrCast(req))); get(cfg, s, req); }, OpaqueStoreOp.DELETE => { const req: *OpaqueReq = read_req(cfg, s, OpaqueReq, "delete"[0..]) catch |e| { warn("read delete request failed with {}", .{e}); fail(s,cfg); }; defer allocator.free(@as(*[@sizeOf(OpaqueReq)]u8, @ptrCast(req))); delete(cfg, s, req); }, OpaqueStoreOp.UPDATE => { const req: *OpaqueReq = read_req(cfg, s, OpaqueReq, "update"[0..]) catch |e| { warn("read update request failed with {}", .{e}); fail(s,cfg); }; defer allocator.free(@as(*[@sizeOf(OpaqueReq)]u8, @ptrCast(req))); update(cfg, s, req); }, OpaqueStoreOp.GET_RTOKEN => { const req: *OpaqueReq = read_req(cfg, s, OpaqueReq, "get recovery token"[0..]) catch |e| { warn("read get recovery token request failed with {}", .{e}); fail(s,cfg); }; defer allocator.free(@as(*[@sizeOf(OpaqueReq)]u8, @ptrCast(req))); get_rtoken(cfg, s, req); }, OpaqueStoreOp.UNLOCK => { const req: *UnlockReq = read_req(cfg, s, UnlockReq, "unlock"[0..]) catch |e| { warn("read unlock request failed with {}", .{e}); fail(s,cfg); }; defer allocator.free(@as(*[@sizeOf(UnlockReq)]u8, @ptrCast(req))); unlock(cfg, s, req); }, _ => { if (cfg.verbose) warn("{} invalid op({}). aborting.\n",.{conn.address, op}); } } } pub fn main() !void { try stdout.print("starting up opaque-store server\n", .{}); try bw.flush(); // don't forget to flush! //if(DEBUG) { // tp_dkg.log_file = @ptrCast(stdio.fdopen(2,"w")); //} const cfg = try loadcfg(); const sk: *ssl.c.private_key = ssl.c.read_private_key(@ptrCast(cfg.ssl_key)); var certs_len: usize = undefined; const certs: *ssl.c.br_x509_certificate = ssl.c.read_certificates(@ptrCast(cfg.ssl_cert), &certs_len); const addresses = try std.net.getAddressList(allocator, cfg.address, cfg.port); defer addresses.deinit(); for (addresses.addrs) |addr| { var addrtype: *const [4:0]u8 = undefined; switch (addr.any.family) { posix.AF.INET => addrtype = "ipv4", posix.AF.INET6 => addrtype = "ipv6", posix.AF.UNIX => addrtype = "unix", else => unreachable, } warn("addr: {s}, {}\n", .{addrtype, addr}); } const addr = try net.Address.parseIp(cfg.address, cfg.port); var srv = addr.listen(.{.reuse_address = true }) catch |err| switch (err) { error.AddressInUse => { warn("port {} already in use.", .{cfg.port}); posix.exit(1); }, else => { return err; //unreachable, } }; const to = posix.timeval{ .tv_sec = cfg.timeout, .tv_usec = 0 }; try posix.setsockopt(srv.stream.handle, posix.SOL.SOCKET, posix.SO.SNDTIMEO, mem.asBytes(&to)); try posix.setsockopt(srv.stream.handle, posix.SOL.SOCKET, posix.SO.RCVTIMEO, mem.asBytes(&to)); var kids = BufSet.init(allocator); while (true) { if(srv.accept()) |c| { conn = c; } else |e| { if(e==error.WouldBlock) { const Status = if (builtin.link_libc) c_int else u32; var status: Status = undefined; const rc = posix.system.waitpid(-1, &status, posix.system.W.NOHANG); if(rc>0) { kids.remove(mem.asBytes(&rc)); if(cfg.verbose) warn("removing kid {} from pool\n",.{rc}); } continue; } unreachable; } while (kids.count() >= cfg.max_kids) { if (cfg.verbose) warn("waiting for kid to die\n", .{}); const pid = posix.waitpid(-1, 0).pid; if (cfg.verbose) warn("wait returned: {}\n", .{pid}); kids.remove(mem.asBytes(&pid)); } var pid = try posix.fork(); switch (pid) { 0 => { var sc: ssl.c.br_ssl_server_context = undefined; //c.br_ssl_server_init_full_ec(&sc, certs, certs_len, c.BR_KEYTYPE_EC, &sk.key.ec); ssl.c.br_ssl_server_init_minf2c(&sc, certs, certs_len, &sk.key.ec); var iobuf: [ssl.c.BR_SSL_BUFSIZE_BIDI]u8 = undefined; ssl.c.br_ssl_engine_set_buffer(&sc.eng, &iobuf, iobuf.len, 1); // * Reset the server context, for a new handshake. if (ssl.c.br_ssl_server_reset(&sc) == 0) { return ssl.convertError(ssl.c.br_ssl_engine_last_error(&sc.eng)); } var s = ssl.initStream(&sc.eng, &conn.stream, &conn.stream); handler(&cfg, &s) catch |err| { if(err==error.WouldBlock or err==error.IO) { if(cfg.verbose) warn("timeout, abort.\n",.{}); _ = std.os.linux.shutdown(conn.stream.handle, std.os.linux.SHUT.RDWR); conn.stream.close(); } else { return err; } }; posix.exit(0); }, else => { try kids.insert(mem.asBytes(&pid)); conn.stream.close(); }, } } } opaque-store-0.2.0/server/src/root.zig000066400000000000000000000002771473305203000177330ustar00rootroot00000000000000const std = @import("std"); const testing = std.testing; export fn add(a: i32, b: i32) i32 { return a + b; } test "basic add functionality" { try testing.expect(add(3, 7) == 10); } opaque-store-0.2.0/server/src/secret_allocator.zig000066400000000000000000000054311473305203000222720ustar00rootroot00000000000000const std = @import("std"); const Allocator = std.mem.Allocator; const sodium = @cImport({ @cInclude("sodium.h"); }); pub fn SecretAllocator() type { return struct { parent_allocator: Allocator, const Self = @This(); pub fn init(parent_allocator: Allocator) Self { return Self{ .parent_allocator = parent_allocator, }; } pub fn allocator(self: *Self) Allocator { return .{ .ptr = self, .vtable = &.{ .alloc = alloc, .resize = resize, .free = free, }, }; } fn alloc( ctx: *anyopaque, len: usize, log2_ptr_align: u8, ra: usize, ) ?[*]u8 { const self: *Self = @ptrCast(@alignCast(ctx)); const result = self.parent_allocator.rawAlloc(len, log2_ptr_align, ra); if (result) |buf| { if(len > 0 and 0!=sodium.sodium_mlock(@ptrCast(buf),len)) { self.parent_allocator.rawFree(buf[0..len], log2_ptr_align, ra); return null; } } return result; } fn resize( ctx: *anyopaque, buf: []u8, log2_buf_align: u8, new_len: usize, ra: usize, ) bool { const self: *Self = @ptrCast(@alignCast(ctx)); if(new_len==0) _=sodium.sodium_munlock(@ptrCast(buf),buf.len); if (self.parent_allocator.rawResize(buf, log2_buf_align, new_len, ra)) { if(new_len>buf.len) _=sodium.sodium_mlock(buf.ptr, new_len); return true; } std.debug.assert(new_len > buf.len); return false; } fn free( ctx: *anyopaque, buf: []u8, log2_buf_align: u8, ra: usize, ) void { const self: *Self = @ptrCast(@alignCast(ctx)); _ = sodium.sodium_munlock(buf.ptr,buf.len); self.parent_allocator.rawFree(buf, log2_buf_align, ra); } }; } pub fn secretAllocator( parent_allocator: Allocator, ) SecretAllocator() { return SecretAllocator().init(parent_allocator); } test "SecretAllocator" { var allocator_buf: [10]u8 = undefined; var fixedBufferAllocator = std.mem.validationWrap(std.heap.FixedBufferAllocator.init(&allocator_buf)); var allocator_state = secretAllocator(fixedBufferAllocator.allocator()); const allocator = allocator_state.allocator(); var a = try allocator.alloc(u8, 10); try std.testing.expect(allocator.resize(a, 5)); a = a[0..5]; try std.testing.expect(!allocator.resize(a, 20)); allocator.free(a); } opaque-store-0.2.0/server/src/utils.zig000066400000000000000000000006201473305203000201000ustar00rootroot00000000000000const std = @import("std"); const warn = std.debug.print; pub fn hexdump(buf: []const u8) void { for (buf) |C| { warn("{x:0>2}", .{C}); } warn("\n", .{}); } pub fn dir_exists(path: []const u8) bool { var cwd = std.fs.cwd(); const args: std.fs.Dir.OpenDirOptions = undefined; var dir = cwd.openDir(path, args) catch return false; dir.close(); return true; } opaque-store-0.2.0/server/workaround.c000066400000000000000000000012501473305203000177750ustar00rootroot00000000000000#include "oprf/tp-dkg.h" #include "oprf/toprf.h" #include #include // zig cannot align data at 64Byte (or anything beyond 16 bytes really) // see https://github.com/ziglang/zig/issues/8452 // thus we have to workaround this by allocating/freeing and accessing // the data in c which the zig cc backend (clang) handles correctly. TP_DKG_PeerState* new_peerstate(void) { return aligned_alloc(64,sizeof(TP_DKG_PeerState)); } void extract_share(const TP_DKG_PeerState *ctx, uint8_t share[TOPRF_Share_BYTES]) { memcpy(share, &ctx->share, TOPRF_Share_BYTES); } void del_peerstate(TP_DKG_PeerState **peer) { if(*peer!=NULL) free(*peer); *peer = NULL; } opaque-store-0.2.0/server/workaround.h000066400000000000000000000004561473305203000200110ustar00rootroot00000000000000#ifndef workaround_h #define workaround_h #include #include #include TP_DKG_PeerState* new_peerstate(void); void extract_share(const TP_DKG_PeerState *ctx, uint8_t share[TOPRF_Share_BYTES]); void del_peerstate(TP_DKG_PeerState **peer); #endif // workaround_h opaque-store-0.2.0/test/000077500000000000000000000000001473305203000151115ustar00rootroot00000000000000opaque-store-0.2.0/test/opaque-store.cfg000066400000000000000000000011751473305203000202220ustar00rootroot00000000000000[client] verbose=true context="opaque-store-v0.0.1" id_salt="asdfasdf" threshold=2 [servers] [servers.zero] # address of server host="127.0.0.1" # port where server is running port=23000 # public key of the server ssl_cert = "servers/0/cert.pem" ltsigkey="servers/zero.pub" [servers.eins] # address of server host="127.0.0.1" # port where server is running port=23001 # public key of the server ssl_cert = "servers/1/cert.pem" ltsigkey="servers/eins.pub" [servers.zwei] # address of server host="127.0.0.1" # port where server is running port=23002 # public key of the server ssl_cert = "servers/2/cert.pem" ltsigkey="servers/zwei.pub" opaque-store-0.2.0/test/servers/000077500000000000000000000000001473305203000166025ustar00rootroot00000000000000opaque-store-0.2.0/test/servers/0/000077500000000000000000000000001473305203000167415ustar00rootroot00000000000000opaque-store-0.2.0/test/servers/0/cert.pem000066400000000000000000000011131473305203000203750ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIBhTCCASugAwIBAgIURt1h20rXWGwyV5nuLDp2NBaXsgkwCgYIKoZIzj0EAwIw GDEWMBQGA1UEAwwNc3BoaW54IG9yYWNsZTAeFw0yMDA5MjkyMTI5MDBaFw0yMTA5 MjQyMTI5MDBaMBgxFjAUBgNVBAMMDXNwaGlueCBvcmFjbGUwWTATBgcqhkjOPQIB BggqhkjOPQMBBwNCAATPl01K0Nuxm4wZaYzS4AvaXy4pIG96Zk5XC1o0TmkdnNPb kgSUm6dx1OVvx3u8kVGRHYfgC7C4I414W2v41Hb4o1MwUTAdBgNVHQ4EFgQUtpha TRgMR7SeM7gYPKoq8L874tcwHwYDVR0jBBgwFoAUtphaTRgMR7SeM7gYPKoq8L87 4tcwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAgNIADBFAiEAnN1Y9WDfVW6f slgOnPs8eQdyoqA7S/rFf9wE/ZxR4tECICfCYMKpIRMYPEk2C+kqoJueB/JVdGKh pYxdMvjx8bsj -----END CERTIFICATE----- opaque-store-0.2.0/test/servers/0/ltsig.key000066400000000000000000000001001473305203000205640ustar00rootroot00000000000000z/ ɭMIogsehk8Pq`Yopaque-store-0.2.0/test/servers/0/opaque-stored.cfg000066400000000000000000000017311473305203000222140ustar00rootroot00000000000000# config is read in this order from the following locations, later ones # overriding settings from the earlier ones: # - /etc/sphinx/config # - ~/.config/sphinx/config # - ~/.sphinxrc # - ./sphinx.cfg [server] # the ipv4 address the server is listening on #address="127.0.0.1" # ssl key ssl_key="server.der" # ssl cert ssl_cert="cert.pem" # the port on which the server is listening, use 443 if available, so that # the oracle can be accessed from behind tight firewalls, default: 8080 port=23000 # tcp connection timeouts, increase in case you have bad networks, with the # caveat that this might lead to easier resource exhaustion - blocking all # workers. #timeout=3 # the root directory where all data is stored, default: /var/lib/sphinx datadir="data" # how many worker processes can run in parallel # max_kids=5 # whether to produce some output verbose=true # key record_salt="some random string to salt the record ids" max_blob_size=8192 ltsigkey="ltsig.key" opaque-store-0.2.0/test/servers/0/rtoken.key000066400000000000000000000001001473305203000207440ustar00rootroot00000000000000Q.S =ЀLq ҝ6]g|%r)s903\&S9@Vopaque-store-0.2.0/test/servers/0/server.der000066400000000000000000000001711473305203000207420ustar00rootroot000000000000000w SE ~;yj1ǚw ?x *H=DBϗMJ۱i _.) ozfNW Z4Niےqo{Q #x[kvopaque-store-0.2.0/test/servers/1/000077500000000000000000000000001473305203000167425ustar00rootroot00000000000000opaque-store-0.2.0/test/servers/1/cert.pem000066400000000000000000000011131473305203000203760ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIBhTCCASugAwIBAgIURt1h20rXWGwyV5nuLDp2NBaXsgkwCgYIKoZIzj0EAwIw GDEWMBQGA1UEAwwNc3BoaW54IG9yYWNsZTAeFw0yMDA5MjkyMTI5MDBaFw0yMTA5 MjQyMTI5MDBaMBgxFjAUBgNVBAMMDXNwaGlueCBvcmFjbGUwWTATBgcqhkjOPQIB BggqhkjOPQMBBwNCAATPl01K0Nuxm4wZaYzS4AvaXy4pIG96Zk5XC1o0TmkdnNPb kgSUm6dx1OVvx3u8kVGRHYfgC7C4I414W2v41Hb4o1MwUTAdBgNVHQ4EFgQUtpha TRgMR7SeM7gYPKoq8L874tcwHwYDVR0jBBgwFoAUtphaTRgMR7SeM7gYPKoq8L87 4tcwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAgNIADBFAiEAnN1Y9WDfVW6f slgOnPs8eQdyoqA7S/rFf9wE/ZxR4tECICfCYMKpIRMYPEk2C+kqoJueB/JVdGKh pYxdMvjx8bsj -----END CERTIFICATE----- opaque-store-0.2.0/test/servers/1/ltsig.key000066400000000000000000000001001473305203000205650ustar00rootroot00000000000000GrOiSv,3$EzS#%>sum,MSsɈu\]|ƫfăopaque-store-0.2.0/test/servers/1/opaque-stored.cfg000066400000000000000000000017311473305203000222150ustar00rootroot00000000000000# config is read in this order from the following locations, later ones # overriding settings from the earlier ones: # - /etc/sphinx/config # - ~/.config/sphinx/config # - ~/.sphinxrc # - ./sphinx.cfg [server] # the ipv4 address the server is listening on #address="127.0.0.1" # ssl key ssl_key="server.der" # ssl cert ssl_cert="cert.pem" # the port on which the server is listening, use 443 if available, so that # the oracle can be accessed from behind tight firewalls, default: 8080 port=23001 # tcp connection timeouts, increase in case you have bad networks, with the # caveat that this might lead to easier resource exhaustion - blocking all # workers. #timeout=3 # the root directory where all data is stored, default: /var/lib/sphinx datadir="data" # how many worker processes can run in parallel # max_kids=5 # whether to produce some output verbose=true # key record_salt="some random string to salt the record ids" max_blob_size=8192 ltsigkey="ltsig.key" opaque-store-0.2.0/test/servers/1/rtoken.key000066400000000000000000000001001473305203000207450ustar00rootroot00000000000000`m4zX2 Ainop#@},M|!Yr)ƌ@'gopaque-store-0.2.0/test/servers/2/opaque-stored.cfg000066400000000000000000000017311473305203000222160ustar00rootroot00000000000000# config is read in this order from the following locations, later ones # overriding settings from the earlier ones: # - /etc/sphinx/config # - ~/.config/sphinx/config # - ~/.sphinxrc # - ./sphinx.cfg [server] # the ipv4 address the server is listening on #address="127.0.0.1" # ssl key ssl_key="server.der" # ssl cert ssl_cert="cert.pem" # the port on which the server is listening, use 443 if available, so that # the oracle can be accessed from behind tight firewalls, default: 8080 port=23002 # tcp connection timeouts, increase in case you have bad networks, with the # caveat that this might lead to easier resource exhaustion - blocking all # workers. #timeout=3 # the root directory where all data is stored, default: /var/lib/sphinx datadir="data" # how many worker processes can run in parallel # max_kids=5 # whether to produce some output verbose=true # key record_salt="some random string to salt the record ids" max_blob_size=8192 ltsigkey="ltsig.key" opaque-store-0.2.0/test/servers/2/rtoken.key000066400000000000000000000001001473305203000207460ustar00rootroot0000000000000074V11|{V;SMɬVfzlbDA9⻠S*`c" opaque-store-0.2.0/test/servers/2/server.der000066400000000000000000000001711473305203000207440ustar00rootroot000000000000000w SE ~;yj1ǚw ?x *H=DBϗMJ۱i _.) ozfNW Z4Niےqo{Q #x[kvopaque-store-0.2.0/test/servers/eins.pub000066400000000000000000000000401473305203000202420ustar00rootroot00000000000000sum,MSsɈu\]|ƫfăopaque-store-0.2.0/test/servers/zero.pub000066400000000000000000000000401473305203000202630ustar00rootroot00000000000000ogsehk8Pq`Yopaque-store-0.2.0/test/servers/zwei.pub000066400000000000000000000000401473305203000202620ustar00rootroot00000000000000 @H>op#@},M|!Yr)ƌ@'gopaque-store-0.2.0/test/test.py000066400000000000000000000172241473305203000164500ustar00rootroot00000000000000import unittest from os import listdir, path from shutil import rmtree #from io import BytesIO import sys, subprocess, time from opaquestore import client from opaquestore.cfg import getcfg import tracemalloc from pyoprf import multiplexer # to get coverage, run # PYTHONPATH=.. coverage run test.py # coverage report -m # to just run the tests do # python3 -m unittest discover --start-directory . # disable the output the client N = 3 pwd = 'asdf' otherpwd = 'qwer' keyid = b"keyid" data = b"data1" #class Input: # def __init__(self, txt = None): # if txt: # self.buffer = BytesIO('\n'.join((pwd, txt)).encode()) # else: # self.buffer = BytesIO(pwd.encode()) # def isatty(self): # return False # def close(self): # return test_path = path.dirname(path.abspath(__file__)) client.config = client.processcfg(getcfg('opaque-store', test_path )) for s in client.config['servers'].keys(): client.config['servers'][s]['ssl_cert']='/'.join([test_path, client.config['servers'][s]['ssl_cert']]) client.config['servers'][s]['ltsigkey']='/'.join([test_path, client.config['servers'][s]['ltsigkey']]) def connect(peers=None): if peers == None: peers = dict(tuple(client.config['servers'].items())[:N]) m = multiplexer.Multiplexer(peers) m.connect() return m class TestEndToEnd(unittest.TestCase): @classmethod def setUpClass(cls): cls._oracles = [] for idx in range(N): log = open(f"{test_path}/servers/{idx}/log", "w") cls._oracles.append( (subprocess.Popen("../../../server/zig-out/bin/opaqueztore", cwd = f"{test_path}/servers/{idx}/", stdout=log, stderr=log, pass_fds=[log.fileno()]), log)) log.close() time.sleep(0.8) @classmethod def tearDownClass(cls): for p, log in cls._oracles: p.kill() r = p.wait() log.close() time.sleep(0.4) def tearDown(self): for idx in range(N): ddir = f"{test_path}/servers/{idx}/data/" if not path.exists(ddir): continue for f in listdir(ddir): rmtree(ddir+f) def test_create(self): with connect() as s: self.assertTrue(client.create(s, pwd, keyid, data)) def test_create_2x(self): with connect() as s: self.assertTrue(client.create(s, pwd, keyid, data)) with connect() as s: self.assertRaises(ValueError, client.create, s, pwd, keyid, data) def test_get(self): with connect() as s: self.assertTrue(client.create(s, pwd, keyid, data)) with connect() as s: res = client.get(s, pwd, keyid) self.assertIsInstance(res, str) self.assertEqual(res.encode('utf8'),data) def test_invalid_pwd(self): with connect() as s: self.assertTrue(client.create(s, pwd, keyid, data)) with connect() as s: self.assertRaises(ValueError, client.get, s, otherpwd, keyid) def test_invalid_keyid(self): with connect() as s: self.assertRaises(ValueError, client.get, s, pwd, keyid) def test_update(self): with connect() as s: self.assertTrue(client.create(s, pwd, keyid, data)) with connect() as s: res = client.get(s, pwd, keyid) self.assertIsInstance(res, str) self.assertEqual(res.encode('utf8'),data) updated = b"updated blob" with connect() as s: self.assertTrue(client.update(s, pwd, keyid, updated)) with connect() as s: res1 = client.get(s, pwd, keyid) self.assertIsInstance(res1, str) self.assertEqual(res1.encode('utf8'),updated) def test_update_invalid_pwd(self): with connect() as s: self.assertTrue(client.create(s, pwd, keyid, data)) with connect() as s: res = client.get(s, pwd, keyid) self.assertIsInstance(res, str) self.assertEqual(res.encode('utf8'),data) updated = b"updated blob" with connect() as s: self.assertRaises(ValueError, client.update, s, otherpwd, keyid, updated) def test_delete(self): with connect() as s: self.assertTrue(client.create(s, pwd, keyid, data)) with connect() as s: self.assertTrue(client.delete(s, pwd, keyid)) with connect() as s: self.assertRaises(ValueError, client.get, s, pwd, keyid) def test_delete_invalid_pwd(self): with connect() as s: self.assertTrue(client.create(s, pwd, keyid, data)) with connect() as s: self.assertRaises(ValueError, client.delete, s, otherpwd, keyid) def test_reset_fails(self): with connect() as s: self.assertTrue(client.create(s, pwd, keyid, data)) with connect() as s: self.assertRaises(ValueError, client.get, s, otherpwd, keyid) with connect() as s: res = client.get(s, pwd, keyid) self.assertIsInstance(res, str) self.assertEqual(res.encode('utf8'),data) def test_lock(self): with connect() as s: self.assertTrue(client.create(s, pwd, keyid, data)) # lock it for _ in range(3): with connect() as s: self.assertRaises(ValueError, client.get, s, otherpwd, keyid) # check that it is locked with connect() as s: self.assertRaises(ValueError, client.get, s, pwd, keyid) def test_get_rtoken(self): with connect() as s: self.assertTrue(client.create(s, pwd, keyid, data)) # get recovery token with connect() as s: rtoken = client.get_recovery_tokens(s, pwd, keyid) self.assertIsInstance(rtoken, str) def test_get_rtoken_invalid_pwd(self): with connect() as s: self.assertTrue(client.create(s, pwd, keyid, data)) # get recovery token with connect() as s: self.assertRaises(ValueError, client.get_recovery_tokens, s, otherpwd, keyid) def test_unlock(self): with connect() as s: self.assertTrue(client.create(s, pwd, keyid, data)) # get recovery token with connect() as s: rtoken = client.get_recovery_tokens(s, pwd, keyid) self.assertIsInstance(rtoken, str) # lock it for _ in range(3): with connect() as s: self.assertRaises(ValueError, client.get, s, otherpwd, keyid) # check that it is locked with connect() as s: self.assertRaises(ValueError, client.get, s, pwd, keyid) # unlock it with connect() as s: self.assertTrue(client.unlock(s, rtoken, keyid)) # check success of unlocking with connect() as s: res = client.get(s, pwd, keyid) self.assertIsInstance(res, str) self.assertEqual(res.encode('utf8'),data) def test_unlock_invalid_rtoken(self): with connect() as s: self.assertTrue(client.create(s, pwd, keyid, data)) # get recovery token with connect() as s: rtoken = client.get_recovery_tokens(s, pwd, keyid) self.assertIsInstance(rtoken, str) # lock it for _ in range(3): with connect() as s: self.assertRaises(ValueError, client.get, s, otherpwd, keyid) # check that it is locked with connect() as s: self.assertRaises(ValueError, client.get, s, pwd, keyid) # unlock it with connect() as s: self.assertRaises(ValueError, client.unlock, s, rtoken[::-1], keyid) # check success of unlocking with connect() as s: self.assertRaises(ValueError, client.get, s, pwd, keyid) if __name__ == '__main__': unittest.main()