pax_global_header00006660000000000000000000000064150724760400014517gustar00rootroot0000000000000052 comment=1da028def68475ce5798f78dc050882c4748bd79 pwdsphinx-2.0.4/000077500000000000000000000000001507247604000135465ustar00rootroot00000000000000pwdsphinx-2.0.4/.github/000077500000000000000000000000001507247604000151065ustar00rootroot00000000000000pwdsphinx-2.0.4/.github/workflows/000077500000000000000000000000001507247604000171435ustar00rootroot00000000000000pwdsphinx-2.0.4/.github/workflows/hcodeql-analysis.yml000066400000000000000000000034321507247604000231300ustar00rootroot00000000000000name: "CodeQL" on: push: branches: [master] pull_request: # The branches below must be a subset of the branches above branches: [master] schedule: - cron: '0 22 * * 2' jobs: analyze: name: Analyze runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v4 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v3 # Override language selection by uncommenting this and choosing your languages # with: # languages: go, javascript, csharp, python, cpp, java # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) #- name: Autobuild # uses: github/codeql-action/autobuild@v3 # ℹ️ Command-line programs to run using the OS shell. # 📚 https://git.io/JvXDl # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines # and modify them (or add more) to build your code if your project # uses a compiled language - run: | sudo apt update sudo apt install -y libsodium-dev pkgconf # build-essential git python3-pip # liboprf git clone https://github.com/stef/liboprf/ cd liboprf/src sudo mkdir -p /usr/include/oprf/ sudo PREFIX=/usr make install pip3 install ../python/ cd ../.. git clone https://github.com/stef/equihash cd equihash sudo PREFIX=/usr make install pip3 install python/ cd .. sudo ldconfig pip3 install . cd tests python3 -m unittest discover -fcb -v . - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v3 pwdsphinx-2.0.4/GettingStarted.md000066400000000000000000000075231507247604000170270ustar00rootroot00000000000000# Getting Started with SPHINX So you want to start using SPHINX for handling your passwords. Great, welcome! SPHINX is a cryptographic password storage protocol that uses client-server architecture. Unlike traditional password managers that encrypt a database file, SPHINX servers store only cryptographic blobs that are mathematically useless without your master password. Even if compromised, your actual passwords remain secure with information-theoretic security guarantees. **Note:** To use SPHINX, your client needs to be able to connect to the oracle. ## Quick Start ### 1. Install SPHINX Client **Debian/Ubuntu and derivatives:** ```bash sudo apt install pwdsphinx # Optional: for browser extensions and X11 integration sudo apt install pinentry-gtk2 xdotool xinput ``` **Other systems:** See the **[installation guide](https://sphinx.pm/client_install.html)** for building from source and dependencies. ### 2. Initialize Your Client ```bash sphinx init ``` This creates your master key (`~/.sphinx/masterkey`) - **BACK THIS UP!** It also automatically sets up browser extension hosts if `~/.mozilla` or `~/.config/chromium` directories are found. For Android devices, export your config using `sphinx qr key`. This creates a QR code that can be read by the [androsphinx](https://github.com/dnet/androsphinx) Android app, allowing the app to use the same configuration as you have set up above. ### 3. Configure a Server Edit `~/.sphinxrc`: ```ini [servers] [server.server-name] address=your.sphinx-server.tld port=443 ``` **Need a server?** - **Use existing server:** See **[public servers](https://sphinx.pm/servers.html)** - **Host your own:** Follow the **[server setup guide](https://sphinx.pm/server_install.html)** ### 4. Test Your Setup ```bash # Create a test password echo -n "testpassword" | sphinx create testuser example.com # Retrieve it (use getpwd for security) getpwd | sphinx get testuser example.com # Clean up sphinx delete testuser example.com # Verify it's gone echo -n "testpassword" | sphinx get testuser example.com # Should error ``` ## What's Next? - **[Complete Usage Guide](man/sphinx.md)**: All operations and options - **[Browser Extensions](#browser-extensions)**: Seamless web login - **[X11 Integration](https://sphinx.pm/x11-integration.html)**: Desktop automation - **[Server Hosting](https://sphinx.pm/server_install.html)**: Run your own oracle ## Browser Extensions SPHINX provides browser extensions for Firefox and Chrome/Chromium that enable seamless password filling on websites. websphinx consists of two parts: the frontend (which is the add-on to install from the browser extension store) and the backend (which handles everything). The backend is actually a native messaging host that communicates with the browser extension. The native messaging host is auto-configured by `sphinx init`. ### Prerequisites Install pinentry for secure password input: ```bash # Choose one appropriate for your desktop environment: sudo apt install pinentry-gtk2 # GTK/GNOME sudo apt install pinentry-qt # KDE/Qt sudo apt install pinentry-gnome3 # Modern GNOME sudo apt-get install pinentry-fltk # Lightweight option ``` ### Firefox Extension 1. **Install from [Firefox Add-ons Store](https://github.com/stef/pwdsphinx/releases/tag/v2.0.0)** 2. **Configure pinentry** (if not using default `/usr/bin/pinentry`): Add to `~/.sphinxrc`: ```ini [websphinx] pinentry=/usr/bin/pinentry-gtk-2 ``` 3. **Restart Firefox** and enjoy! ### Chrome/Chromium Extension 1. **Download** from [websphinx-chrom repository](https://github.com/stef/websphinx-chrom) 2. **Install in Developer Mode:** - Open `chrome://extensions` - Enable "Developer mode" - Click "Load unpacked extension" - Select the downloaded directory 3. **Configure pinentry** (same as Firefox above) 4. **Restart browser** and enjoy! pwdsphinx-2.0.4/LICENSE000066400000000000000000001045131507247604000145570ustar00rootroot00000000000000 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 . pwdsphinx-2.0.4/LICENSES/000077500000000000000000000000001507247604000147535ustar00rootroot00000000000000pwdsphinx-2.0.4/LICENSES/CC-BY-SA-4.0.txt000066400000000000000000000437701507247604000171240ustar00rootroot00000000000000 Creative Commons Attribution-ShareAlike 4.0 International Creative Commons Corporation ("Creative Commons") is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an "as-is" basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. Using Creative Commons Public Licenses Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors : wiki.creativecommons.org/Considerations_for_licensors Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor's permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public : wiki.creativecommons.org/Considerations_for_licensees Creative Commons Attribution-ShareAlike 4.0 International Public License By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. Section 1 – Definitions. a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. c. BY-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License. d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike. h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. j. Licensor means the individual(s) or entity(ies) granting rights under this Public License. k. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. l. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. m. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. Section 2 – Scope. a. License grant. 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: A. reproduce and Share the Licensed Material, in whole or in part; and B. produce, reproduce, and Share Adapted Material. 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 3. Term. The term of this Public License is specified in Section 6(a). 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. 5. Downstream recipients. A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. B. Additional offer from the Licensor – Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter's License You apply. C. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). b. Other rights. 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 2. Patent and trademark rights are not licensed under this Public License. 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. Section 3 – License Conditions. Your exercise of the Licensed Rights is expressly made subject to the following conditions. a. Attribution. 1. If You Share the Licensed Material (including in modified form), You must: A. retain the following if it is supplied by the Licensor with the Licensed Material: i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); ii. a copyright notice; iii. a notice that refers to this Public License; iv. a notice that refers to the disclaimer of warranties; v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. b. ShareAlike.In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply. 1. The Adapter's License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License. 2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. 3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply. Section 4 – Sui Generis Database Rights. Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. Section 5 – Disclaimer of Warranties and Limitation of Liability. a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You. b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You. c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. Section 6 – Term and Termination. a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 2. upon express reinstatement by the Licensor. c. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. d. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. Section 7 – Other Terms and Conditions. a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. Section 8 – Interpretation. a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the "Licensor." The text of the Creative Commons public licenses is dedicated to the public domain under the CC0 Public Domain Dedication. Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark "Creative Commons" or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. Creative Commons may be contacted at creativecommons.org. pwdsphinx-2.0.4/LICENSES/GPL-3.0-or-later.txt000066400000000000000000001045131507247604000201630ustar00rootroot00000000000000 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 . pwdsphinx-2.0.4/MANIFEST.in000066400000000000000000000001531507247604000153030ustar00rootroot00000000000000include README.md include *.py include pwdsphinx/converters/*.py include man/*.1 include GettingStarted.md pwdsphinx-2.0.4/README.md000066400000000000000000000176051507247604000150360ustar00rootroot00000000000000 # SPHINX: A Password **S**tore that **P**erfectly **H**ides from **I**tself (**N**o **X**aggeration) SPHINX is a cryptographic password storage protocol that provides information-theoretic security. pwdsphinx is a Python wrapper around [liboprf](https://github.com/stef/liboprf) - a cryptographic password storage as described in https://eprint.iacr.org/2015/1099. Unlike traditional password managers, SPHINX only stores random numbers unrelated to your actual passwords, ensuring the server learns nothing about them. **Key Features:** - 🔒 **Information-theoretic security**: Mathematically proven protection - 🌐 **Zero-trust architecture**: Server knows nothing about your passwords - 🚫 **Offline bruteforce resistance**: Your passwords are safe even if the server is compromised - 🏠 **Self-hostable**: Run your own server or use someone else's - 📱 **Cross-platform**: CLI, browser extensions, Android app, and X11 integration - 🔑 **Password generation**: Creates strong passwords according to site requirements ## Also on Radicle To clone this repo on [Radicle](https://radicle.xyz): ```bash rad clone rad:z3rjK2hk7ckb1thexdsuyaM7e4FwS ``` ## Dependencies ### Required Dependencies - **[liboprf](https://github.com/stef/liboprf)**: An Oblivious Pseudo-Random Function (OPRF) is a cryptographic protocol where a client can evaluate a pseudo-random function on their input using a key held by a server, without the server learning the client's input or the function's output. liboprf implements OPRFs, which is used to enables SPHINX's zero-knowledge password storage. - **[libequihash](https://github.com/stef/equihash/)**: This provides rate limiting proof-of-work with fast verification - **pysodium** and **pyoprf**: Python cryptographic bindings. Both can be installed using either your OS package manager or pip. ### Optional Dependencies **For browser extensions:** If you also want to use the websphinx browser extension, you also need to install an X11 variant of pinentry from the GnuPG project. ```bash # Install any one of these, using the equivalent of `apt-get` on your operating system: apt-get install pinentry-qt # For KDE/Qt environments apt-get install pinentry-gtk2 # For older GNOME/GTK environments apt-get install pinentry-gnome3 # For modern GNOME environments apt-get install pinentry-fltk # Lightweight option ``` **For X11 integration:** - **xdotool**: Keyboard/mouse automation - **xinput**: Input device control - **dmenu**: Interactive menus **For extended storage:** If you want to store other "secrets" that are longer than just 77 chars, you can install OPAQUE-Store: - **[opaque-store](https://github.com/stef/opaque-store/)**: Encrypted file storage: `pip3 install opaquestore` - **[OPAQUE-Store](https://github.com/stef/libopaque)**: OPAQUE protocol implementation, a dependency for OPAQUE-Store above. ## Installation ```bash pip3 install pwdsphinx ``` On Debian-based systems, you can also do: ```bash sudo apt install pwdsphinx ``` ## Architecture SPHINX uses a client-server architecture where: ### Server (Oracle) The server stores only cryptographic blobs that are useless without your master password. Even if compromised, your actual passwords remain secure. **Host your own server:** See [`oracle(1)`](man/oracle.md) or the [Server Installation Guide](GettingStarted.md#hosting-your-own-oracle) for how to configure your server. ### Client The client combines your master password with the server's response to regenerate your actual passwords deterministically. **Supported platforms:** - **Command Line:** Full-featured CLI client (see [`sphinx(1)`](man/sphinx.md) for how to configure a client) - **Browser:** [Firefox and Chromium extensions](./GettingStarted.md#setting-up-browser-extensions) with native messaging - **Desktop:** [X11 integration scripts](./contrib/README.md) for form filling - **Mobile:** Android app ([androsphinx](https://github.com/dnet/androsphinx)) ## Usage SPHINX provides a complete lifecycle for password management: ### Core Operations - **`create`**: Generate new password for a site - **`get`**: Retrieve existing password - **`change`**: Update password (two-phase commit) - **`commit`**: Activate changed password - **`undo`**: Revert to previous password - **`delete`**: Remove password record - **`list`**: Show usernames for a site ### Management Operations - **`init`**: Initialize client with new master key. It also sets up browser extensions if `~/.mozilla` or `~/.config/chromium` directories are found. - **`healthcheck`**: Test server connectivity - **`qr`**: Export configuration as QR code See [`sphinx(1)`](man/sphinx.md) for detailed command syntax and examples. ## OPAQUE-Store Client Integration If you have OPAQUE-Store installed and configured correctly, you get a number of additional operations, which allow you to store traditionally encrypted blobs of information. For a gentle introduction on how this works using the OPAQUE protocol, have a look at this post: https://www.ctrlc.hu/~stef/blog/posts/How_to_recover_static_secrets_using_OPAQUE.html The following operations will be available if OPAQUE-Store is setup correctly: ```sh echo -n 'password' | sphinx store file-to-store echo -n 'password' | sphinx read echo -n 'password' | sphinx replace [force] file-to-store echo -n 'password' | sphinx edit [force] echo -n 'password' | sphinx changepwd [force] echo -n 'password' | sphinx erase [force] echo -n 'password' | sphinx recovery-tokens echo -n 'password' | sphinx unlock ``` See the [OPAQUE-Store X11 integration](https://sphinx.pm/opaque-store_integration.html) documentation for more details on these operations and how the integration works with SPHINX. ## Browser Integration There is WebSphinx, our browser extension that provides seamless password filling. See the [browser extension instructions](./GettingStarted.md#Setting-Up-Browser-Extensions) on how to set it up on Firefox and Chrome/Chromium browsers ## X11 Desktop Integration SPHINX includes shell scripts for X11 desktop integration using `dmenu`, `xdotool`, `xinput`, and `pinentry`. The main script [`dmenu-sphinx.sh`](./contrib/dmenu-sphinx) provides interactive password filling with a dmenu interface. It stores hostname history in `~/.sphinx-hosts` (link to `/dev/null` if you consider this sensitive). The integration enables automatic form filling in X11 applications through keyboard automation for password entry. It works with pinentry for secure password input. See [`contrib/README.md`](contrib/README.md) for setup examples and script combinations. ## More documentation ### For Users - **[Getting Started Guide](GettingStarted.md)**: Complete setup and usage tutorial - **[Manual Pages](man/)**: Detailed command reference - [`sphinx(1)`](man/sphinx.md): Main client commands - [`oracle(1)`](man/oracle.md): Server configuration and management - [`getpwd(1)`](man/getpwd.md): Secure password input utility ### For Developers & Advanced Users - **[X11 Integration](https://sphinx.pm/x11-integration.html)**: Desktop automation scripts - **[OPAQUE-Store Integration](https://sphinx.pm/opaque-store_integration.html)**: Encrypted file storage - **[Contributing Scripts](contrib/README.md)**: Helper utilities and examples ## Credits This project was funded through the NGI0 PET Fund, a fund established by NLnet with financial support from the European Commission's Next Generation Internet programme, under the aegis of DG Communications Networks, Content and Technology under grant agreement No 825310. This project was funded through the e-Commons Fund, a fund established by NLnet with financial support from the Netherlands Ministry of the Interior and Kingdom Relations. Everlasting gratuity to asciimoo, dnet, jonathan and hugo for their contributions, patience, and support. pwdsphinx-2.0.4/configs/000077500000000000000000000000001507247604000151765ustar00rootroot00000000000000pwdsphinx-2.0.4/configs/chrome/000077500000000000000000000000001507247604000164535ustar00rootroot00000000000000pwdsphinx-2.0.4/configs/chrome/websphinx.json000066400000000000000000000003331507247604000213540ustar00rootroot00000000000000{ "name": "websphinx", "description": "Host for communicating with Sphinx", "path": "/usr/bin/websphinx", "type": "stdio", "allowed_origins": [ "chrome-extension://ojbhlhidchjkmjmpeonendekpoacahni/" ] } pwdsphinx-2.0.4/configs/firefox/000077500000000000000000000000001507247604000166405ustar00rootroot00000000000000pwdsphinx-2.0.4/configs/firefox/websphinx.json000066400000000000000000000002731507247604000215440ustar00rootroot00000000000000{ "name": "websphinx", "description": "Host for communicating with pwdphinx", "path": "/usr/bin/websphinx", "type": "stdio", "allowed_extensions": [ "sphinx@ctrlc.hu" ] } pwdsphinx-2.0.4/contrib/000077500000000000000000000000001507247604000152065ustar00rootroot00000000000000pwdsphinx-2.0.4/contrib/Makefile000066400000000000000000000032111507247604000166430ustar00rootroot00000000000000clean: install: $(DESTDIR)$(prefix)/usr/bin/dmenu-sphinx $(DESTDIR)$(prefix)/usr/bin/exec-on-click \ $(DESTDIR)$(prefix)/usr/bin/getpwd $(DESTDIR)$(prefix)/usr/bin/type-pwd \ $(DESTDIR)$(prefix)/usr/bin/otp.sphinx $(DESTDIR)$(prefix)/usr/bin/pass.sphinx \ $(DESTDIR)$(prefix)/usr/bin/user-pass-otp.sphinx $(DESTDIR)$(prefix)/usr/bin/user-pass.sphinx \ $(DESTDIR)$(prefix)/usr/bin/getacc-user-pass.sphinx \ $(DESTDIR)$(prefix)/usr/bin/sphinx-x11 $(DESTDIR)$(prefix)/usr/bin/pipe2tmpfile \ $(DESTDIR)$(prefix)/usr/share/doc/pwdsphinx-tools/README.x11.md $(DESTDIR)$(prefix)/usr/bin/dmenu-sphinx: dmenu-sphinx install -D -m 0755 $< $@ $(DESTDIR)$(prefix)/usr/bin/exec-on-click: exec-on-click install -D -m 0755 $< $@ $(DESTDIR)$(prefix)/usr/bin/getpwd: getpwd install -D -m 0755 $< $@ $(DESTDIR)$(prefix)/usr/bin/type-pwd: type-pwd install -D -m 0755 $< $@ $(DESTDIR)$(prefix)/usr/bin/sphinx-x11: sphinx-x11 install -D -m 0755 $< $@ $(DESTDIR)$(prefix)/usr/bin/pipe2tmpfile: pipe2tmpfile install -D -m 0755 $< $@ $(DESTDIR)$(prefix)/usr/bin/otp.sphinx: sphinx-scripts/otp.sphinx install -D -m 0755 $< $@ $(DESTDIR)$(prefix)/usr/bin/pass.sphinx: sphinx-scripts/pass.sphinx install -D -m 0755 $< $@ $(DESTDIR)$(prefix)/usr/bin/user-pass-otp.sphinx: sphinx-scripts/user-pass-otp.sphinx install -D -m 0755 $< $@ $(DESTDIR)$(prefix)/usr/bin/user-pass.sphinx: sphinx-scripts/user-pass.sphinx install -D -m 0755 $< $@ $(DESTDIR)$(prefix)/usr/bin/getacc-user-pass.sphinx: sphinx-scripts/getacc-user-pass.sphinx install -D -m 0755 $< $@ $(DESTDIR)$(prefix)/usr/share/doc/pwdsphinx-tools/README.x11.md: README.md install -D -m 0644 $< $@ .PHONY: clean pwdsphinx-2.0.4/contrib/README.md000066400000000000000000000106661507247604000164760ustar00rootroot00000000000000# SPHINX X11 Integration Tools This directory contains tools that can be used on their own, or in concert to interact with pwdsphinx on X11 desktops. SPHINX is not your average legacy consumer-grade password manager - its CLI is powerful, but its X11 integration is what makes it truly efficient for daily use on Linux desktops and laptops. The tools are designed with security in mind, ensuring that passwords never appear in process lists, command history, or the clipboard where malware could intercept them. Instead, they use secure input methods and direct keyboard injection via `xdotool` and `xinput` to automate password entry and multi-factor authentication seamlessly. These tools build on SPHINX's core operations (`create`, `get`, `change`, `commit`, `undo`, `list`, `delete`) and alternate converters (`otp://`, `age://`, `minisig://`, `ssh-ed25519://`, `raw://`) to provide a complete desktop integration experience. For detailed technical documentation of the scripting language and advanced usage, see the [X11 integration documentation](https://sphinx.pm/x11-integration.html). For core SPHINX CLI operations used by these tools, see [sphinx(1)](../man/sphinx.md). ## Tools Reference ### getpwd (depends on pinentry) This is a simple script that uses `pinentry` from the GnuPG project to securely query a password and write it to standard output. This should be safer than echoing a password into pwdsphinx, since your password will not show up in your process list nor your command line history. See [`getpwd(1)`](../man/getpwd.md) for usage details. ### exec-on-click (depends on xinput) This is a simple shell script that depends on `xinput`, which waits for a left mouse click and then executes the specified command. See [`exec-on-click(1)`](../man/exec-on-click.md) for usage details. ### type-pwd (depends on xdotool, exec-on-click and getpwd) This script combines `getpwd`, `exec-on-click`, and the pwdsphinx client to create a secure password entry workflow. It prompts for your master password, waits for you to click on a password field, then types the password as keystrokes. This approach ensures passwords never appear in the clipboard where malware could intercept them. See [`type-pwd(1)`](../man/type-pwd.md) for usage details. ### dmenu-sphinx (depends on dmenu, type-pwd) This tool provides an interactive interface for retrieving SPHINX passwords using `dmenu` to present hostname and username selection menus. It builds on `type-pwd` for secure password entry with hostname history caching. See [`dmenu-sphinx(1)`](../man/dmenu-sphinx.md) for usage details. ### pipe2tmpfile This tool bridges commands that output to stdout with commands requiring file input. It reads data from stdin, writes it to a secure temporary file, executes a command with `@@keyfile@@` replaced by the temp file path, then automatically cleans up. See [`pipe2tmpfile(1)`](../man/pipe2tmpfile.md) for usage details and security considerations. ### sphinx-x11 This script language interpreter integrates the SPHINX CLI with X11 using a domain-specific language (DSL) for automating password entry and multi-factor authentication. It includes example scripts for various login workflows including 2FA support. See [`sphinx-x11(1)`](../man/sphinx-x11.md) for script language vocabulary, examples, and usage details. ## Customization and Usage You can create your own scripts for different sites and workflows using the scripting language, and bind them to keyboard shortcuts for even faster access. This approach keeps your passwords out of the clipboard and leverages X11 automation for secure, efficient logins. If you prefer browser integration, SPHINX also [provides web extensions for Firefox and Chrome-based browsers](../GettingStarted.md#setting-up-browser-extensions). However, always be cautious with browser extensions and review their security implications. ## See Also **Manual Pages:** [`getpwd(1)`](../man/getpwd.md), [`exec-on-click(1)`](../man/exec-on-click.md), [`type-pwd(1)`](../man/type-pwd.md), [`dmenu-sphinx(1)`](../man/dmenu-sphinx.md), [`pipe2tmpfile(1)`](../man/pipe2tmpfile.md), [`sphinx-x11(1)`](../man/sphinx-x11.md), [`websphinx(1)`](../man/websphinx.md) **[Technical Reference](https://sphinx.pm/x11-integration.html):** Complete scripting language vocabulary, advanced usage patterns, and detailed script analysis **[OPAQUE-Store Integration](https://sphinx.pm/opaque-store_integration.html):** Encrypted storage for keys and secrets beyond password generation pwdsphinx-2.0.4/contrib/dmenu-sphinx000077500000000000000000000005201507247604000175500ustar00rootroot00000000000000#!/usr/bin/env sh host=$(cat ~/.sphinx-hosts 2>/dev/null | dmenu -p hostname) tmp=$(mktemp) { echo $host; cat ~/.sphinx-hosts 2>/dev/null ; } | sort -u >$tmp && mv $tmp ~/.sphinx-hosts users=$(sphinx list $host) [[ "$(echo "$users" | wc -l)" -gt 1 ]] && user=$(echo $users | dmenu -p username) || user=$users type-pwd "$user" "$host" pwdsphinx-2.0.4/contrib/exec-on-click000077500000000000000000000010021507247604000175460ustar00rootroot00000000000000#!/usr/bin/env sh # depends on xinput MOUSEID=$(xinput --list --short | fgrep "Virtual core pointer" | sed 's/.*id=\([0-9]*\).*/\1/') THIS=$$ # wait until left mouse click exec 2>/dev/null xinput --test-xi2 --root $MOUSEID | while true; do read -t 1 line case "$line" in EVENT\ type\ 16\ \(RawButtonRelease\)) read -t 1 line read -t 1 details; case "$details" in detail:\ 1) pkill -P $THIS xinput ; exit ;; esac ;; esac done eval "${@}" ; pwdsphinx-2.0.4/contrib/getpwd000077500000000000000000000002421507247604000164240ustar00rootroot00000000000000#!/bin/sh prompt=${1:-sphinx} echo -en "SETTITLE sphinx password prompt\nSETPROMPT ${prompt} password\nGETPIN\n" | pinentry | grep '^D' | cut -c3- | tr -d '\n' pwdsphinx-2.0.4/contrib/pipe2tmpfile000077500000000000000000000006221507247604000175340ustar00rootroot00000000000000#!/bin/sh -e keyroot=/run/user/$(id -u) keyfile=$(mktemp -p ${keyroot}) cleanup() { rm -f "${keyfile}" } cat >$keyfile trap "cleanup" INT TERM QUIT EXIT replace() { for i do arg="$i" if [ "x$arg" == "x@@keyfile@@" ]; then arg="$keyfile" fi printf %s\\n "$arg" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" done echo " " } newargs=$(replace "$@") eval "set -- $newargs" "${@}" pwdsphinx-2.0.4/contrib/sphage-test.sh000077500000000000000000000007421507247604000177740ustar00rootroot00000000000000#!/bin/sh set -e # simulate output from sphinx rwd=$(echo "asdf" | sha256sum | cut -d' ' -f 1 | rax2 -s) # convert rwd to age "identity" (privkey) privkey=$(mktemp) echo "$rwd" | python3 sphage privkey >"$privkey" # convert rwd to age "recipient" (pubkey) pubkey=$(echo -n "$rwd" | python3 sphage pubkey) # encrypt and decrypt hello world using the above key pair derived from rwd echo "hello world" | age -r $pubkey | age --decrypt -i "$privkey" # clean up rm -rf "$privkey" pwdsphinx-2.0.4/contrib/sphinx-scripts/000077500000000000000000000000001507247604000202045ustar00rootroot00000000000000pwdsphinx-2.0.4/contrib/sphinx-scripts/getacc-user-pass.sphinx000077500000000000000000000001151507247604000246050ustar00rootroot00000000000000#!/usr/bin/sphinx-x11 gethost getuser wait-for-click user tab pwd tab enter pwdsphinx-2.0.4/contrib/sphinx-scripts/otp.sphinx000077500000000000000000000000601507247604000222400ustar00rootroot00000000000000#!/usr/bin/sphinx-x11 wait-for-click otp enter pwdsphinx-2.0.4/contrib/sphinx-scripts/pass.sphinx000077500000000000000000000000641507247604000224100ustar00rootroot00000000000000#!/usr/bin/sphinx-x11 wait-for-click pwd tab enter pwdsphinx-2.0.4/contrib/sphinx-scripts/user-pass-otp.sphinx000077500000000000000000000001261507247604000241630ustar00rootroot00000000000000#!/usr/bin/sphinx-x11 wait-for-click user tab pwd tab enter wait-for-click otp enter pwdsphinx-2.0.4/contrib/sphinx-scripts/user-pass.sphinx000077500000000000000000000000751507247604000233660ustar00rootroot00000000000000#!/usr/bin/sphinx-x11 wait-for-click user tab pwd tab enter pwdsphinx-2.0.4/contrib/sphinx-x11000077500000000000000000000060721507247604000170610ustar00rootroot00000000000000#!/bin/sh set -e #set -x script="$1" user="$2" host="$3" MOUSEID=$(xinput --list --short | grep -F "Virtual core pointer" | sed 's/.*id=\([0-9]*\).*/\1/') x11_type() { xdotool type --clearmodifiers -- "$1" } wfc() { # wait until left mouse click THIS=$(exec sh -c 'echo "$PPID"') xinput --test-xi2 --root "$MOUSEID" | while true; do read -t 1 line || continue echo "$line" | /bin/grep -qs '^EVENT type 16 (RawButtonRelease)$' && { read -t 1 line read -t 1 line read -t 1 details; echo "$details" | /bin/grep -qs '^\s*detail: 1$' && { pkill -9 -e -P "$THIS" xinput >/dev/null break } } done 2>/dev/null } wait_for_click() { # wrapping wfc so that when xinput is killed the message "KILLED" is suppressed wfc >/dev/null 2>&1 } getpwd() { prompt=${1:-sphinx} printf "SETTITLE sphinx password prompt\nSETPROMPT %s password\nGETPIN\n" "${prompt}" | pinentry | grep '^D' | cut -c3- | tr -d '\n' } pwd() { getpwd "$user@$host" | { sphinx get "$user" "$host" || return ; } | xdotool type --clearmodifiers "$(head -1)" } otp() { getpwd "$user@$host" | { sphinx get "otp://$user" "$host" || return ; } | xdotool type --clearmodifiers "$(head -1)" } tab() { xdotool key --clearmodifiers Tab } enter() { xdotool key --clearmodifiers enter } xdoget() { title="$1" shift 1 printf '' | /usr/bin/xclip -i sleep 0.2 /usr/bin/xdotool key --window "$windowid" "$@" retries=0 while [ $retries -lt 3 ]; do sleep 0.2 x=$(/usr/bin/xclip -o) printf "%s" "$x" | /bin/grep -Eqs '^https?:.*' && { echo "$x" | cut -d'/' -f3 break } retries=$((retries+1)) done #[ $retries -ge 3 ] && { echo "failed to get host" >&2 ; false; } } gethost() { wait_for_click windowid=$(/usr/bin/xdotool getactivewindow) title=$(/usr/bin/xdotool getwindowname "$windowid" | /bin/sed -e 's/^ *//g;s/ *$//g') case "$title" in #*Pentadactyl|*Vimperator) host="$(xdoget "$title" Escape y)";; *Iceweasel|*Firefox) host="$(xdoget "$title" Escape ctrl+l ctrl+a ctrl+c Escape Tab)";; *Chromium) host="$(xdoget "$title" Escape ctrl+l ctrl+a ctrl+c Escape Tab)";; #*Uzbl\ browser*) host="$(xdoget "title" Escape y u)";; #luakit*) host="$(xdoget "title" shift+o Home ctrl+Right Right ctrl+shift+End ctrl+c Escape)";; esac #echo "$host" } getuser() { [ -z "$host" ] && { echo "no host" >&2; false; } users=$(sphinx list "$host") [ "$(echo "$users" | wc -l)" -gt 1 ] && user=$(echo $users | dmenu -p username) || user=$users #echo "$user" } cat "$script" | while read -r line; do case "$line" in type\ *) x11_type "${line##type }";; wait-for-click) wait_for_click;; user) x11_type "$user";; host) x11_type "$host";; pwd) pwd;; otp) otp;; tab) tab;; enter) enter;; gethost) gethost;; getuser) getuser;; esac done pwdsphinx-2.0.4/contrib/type-pwd000077500000000000000000000001631507247604000167050ustar00rootroot00000000000000#!/usr/bin/env sh getpwd "$1@$2" | sphinx get "$1" "$2" | exec-on-click xdotool type --clearmodifiers -- '$(cat)' pwdsphinx-2.0.4/ext/000077500000000000000000000000001507247604000143465ustar00rootroot00000000000000pwdsphinx-2.0.4/ext/.gitignore000066400000000000000000000000071507247604000163330ustar00rootroot00000000000000build/ pwdsphinx-2.0.4/ext/_locales/000077500000000000000000000000001507247604000161275ustar00rootroot00000000000000pwdsphinx-2.0.4/ext/_locales/en/000077500000000000000000000000001507247604000165315ustar00rootroot00000000000000pwdsphinx-2.0.4/ext/_locales/en/messages.json000066400000000000000000000003001507247604000212240ustar00rootroot00000000000000{ "extDescription": { "message": "Web extension for PITCHFORKed Sphinx" }, "sizePlaceholder": { "message": "Size" }, "searchPlaceholder": { "message": "User name " } } pwdsphinx-2.0.4/ext/background.js000066400000000000000000000145271507247604000170340ustar00rootroot00000000000000/* * This file is part of WebSphinx. * Copyright (C) 2018 pitchfork@ctrlc.hu * * WebSphinx 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 2 of the License, or * (at your option) any later version. * * WebSphinx 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, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ "use strict"; const APP_NAME = "websphinx"; var browser = browser || chrome; var ports = {}; var nativeport = browser.runtime.connectNative(APP_NAME); var changeData = true; nativeport.onMessage.addListener((response) => { // internal error handling if (browser.runtime.lastError) { var error = browser.runtime.lastError.message; console.error(error); ports['popup'].postMessage({ status: "ERROR", error: error }); return; } // client error handling if(response.results == 'fail') { if(response.cmd) { response.results = {'error': true, 'id': response.id, 'cmd': response.cmd}; const tabId = Number(response.tabId); browser.tabs.sendMessage(tabId, response); } console.log('websphinx failed'); return; } // handle manual inserts if(response.results.mode == "manual") { //console.log("manual"); // its a manual mode response so we just pass it to the popup ports['popup'].postMessage(response); return; } // handle get current pwd if(response.results.cmd == 'login') { // 1st step in an automatic change pwd if(changeData==true) { // we got the old password changeData={password: response.results.password}; // now change the password response.results.cmd="change"; delete response.results['password']; // don't send the password back nativeport.postMessage(response.results); return; } let login = { username: response.results.name, password: response.results.password }; browser.tabs.executeScript({code: 'document.websphinx.login(' + JSON.stringify(login) + ');'}); return; } // handle webauthn create if(response.results.cmd == 'webauthn-create') { const tabId = Number(response.results.tabId); browser.tabs.sendMessage(tabId, response); return; } // handle webauthn get if(response.results.cmd == 'webauthn-get') { const tabId = Number(response.results.tabId); browser.tabs.sendMessage(tabId, response); return; } // handle list users if(response.results.cmd == 'list') { ports['popup'].postMessage(response); return; } // handle create password if(response.results.cmd == 'create') { let account = { username: response.results.name, password: response.results.password }; browser.tabs.executeScript({code: 'document.websphinx.create(' + JSON.stringify(account) + ');'}); return; } // handle change password if(response.results.cmd == 'change') { let change = { 'old': changeData, 'new': response.results } browser.tabs.executeScript({code: 'document.websphinx.change(' + JSON.stringify(change) + ');'}); changeData = false; return; } // handle commit result if(response.results.cmd == 'commit') { ports['popup'].postMessage(response); return; } console.log("unhandled native port response"); console.log(response); }); browser.runtime.onConnect.addListener(function(p) { ports[p.name] = p; if(p.name == 'popup') { // proxy from CS to native backend p.onMessage.addListener(function(request, sender, sendResponse) { // prepare message to native backend let msg = { cmd: request.action, mode: request.mode, site: request.site }; if(request.action!="list") msg.name=request.name; if (request.action == "login") changeData=false; if (request.action == "create") { msg.rules= request.rules; msg.size= request.size; } if (request.action == "change") { if(request.mode != "manual") { // first get old password // but this will trigger the login inject in the nativport onmessage cb changeData = true; msg.cmd= "login"; } } if(request.action!="login" && request.action!="list" && request.action!="create" && request.action!="change" && request.action!="commit") { console.log("unhandled popup request"); console.log(request); return; } // send request to native backend nativeport.postMessage(msg); }); } if(p.name == 'content-script') { p.onMessage.addListener(function(request, sender, sendResponse) { let msg = { cmd: request.action, mode: request.mode, site: request.site, challenge: request.params.challenge, name: request.params.username, id: request.id, }; nativeport.postMessage(msg); }); } }); // handle "synchronous" calls for webauthn chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { if(!request.action || !request.action.startsWith('webauthn')) { return; } let msg = {} const tabId = sender.tab.id; if(request.action == "webauthn-create") { msg = { cmd: request.action, mode: request.mode, site: request.site, clientDataJSON: request.params.clientDataJSON, challenge: request.params.challenge, name: request.params.username, userid: request.params.userid, id: request.id, tabId: tabId, }; } if(request.action == "webauthn-get") { msg = { cmd: request.action, mode: request.mode, site: request.site, clientDataJSON: request.params.clientDataJSON, challenge: request.params.challenge, pk: request.params.pk, name: request.params.username, userid: request.params.userid, id: request.id, tabId: tabId, }; } nativeport.postMessage(msg); } ); pwdsphinx-2.0.4/ext/build.sh000077500000000000000000000014731507247604000160110ustar00rootroot00000000000000#!/bin/sh SCRIPT=$(realpath "$0") BASEDIR=$(dirname "$SCRIPT") BUILDDIR="$BASEDIR/build" FFBUILDDIR="$BUILDDIR/ff" FFEXT="$BUILDDIR/ext_ff.zip" CHROMEBUILDDIR="$BUILDDIR/chrome" CHROMEEXT="$BUILDDIR/ext_chrome.zip" files="$BASEDIR/*js $BASEDIR/*html $BASEDIR/*css $BASEDIR/*png $BASEDIR/_locales/" [ ! -d "$BUILDDIR" ] && mkdir "$BUILDDIR" [ -d "$FFBUILDDIR" ] && rm -r "$FFBUILDDIR" [ -d "$CHROMEBUILDDIR" ] && rm -r "$CHROMEBUILDDIR" [ -f "$FFEXT" ] && rm "$FFEXT" [ -f "$CHROMEEXT" ] && rm "$CHROMEEXT" mkdir "$FFBUILDDIR" cp -r $files "$FFBUILDDIR" cp "$BASEDIR/manifest_ff.json" "$FFBUILDDIR/manifest.json" cd "$FFBUILDDIR" zip "$FFEXT" ./* cd - mkdir "$CHROMEBUILDDIR" cp -r $files "$CHROMEBUILDDIR" cp "$BASEDIR/manifest_chrome.json" "$CHROMEBUILDDIR/manifest.json" cd "$CHROMEBUILDDIR" zip "$CHROMEEXT" ./* cd - pwdsphinx-2.0.4/ext/content_script.js000066400000000000000000000034011507247604000177400ustar00rootroot00000000000000(() => { const br = chrome || browser; const s = document.createElement("script"); const src = br.runtime.getURL("webauthn.js"); //const bg = br.runtime.connect({'name': 'content-script'}); const site = window.location.hostname; let pagePorts = {}; s.setAttribute('src', src); s.setAttribute('id', "sphinx-webauthn-page-script"); (document.head || document.documentElement).appendChild(s); window.addEventListener('message', webauthnEventHandler); br.runtime.onMessage.addListener((m) => { let port = pagePorts[m.results.id]; port.postMessage(m.results); delete pagePorts[m.results.id]; }); function genId() { return Math.random().toString(32).slice(2) + Math.random().toString(32).slice(2); } function webauthnEventHandler(msg) { let options = msg.data; if(!options.type || options.type != "sphinxWebauthnEvent") { return; } if(msg.origin != window.origin) { console.log("invalid webauthnEvent sender"); return; } const site = window.location.hostname; // TODO let bgMsg = { "site": site, "action": options.action, "params": options.params, "id": genId(), }; pagePorts[bgMsg.id] = msg.ports[0]; br.runtime.sendMessage(bgMsg); //br.runtime.sendMessage(bgMsg).then( // function(response) { // console.log('response received from bg', response); // pagePort.postMessage(response); // }, // function(error) { // console.log('error received from bg', error); // pagePort.postMessage(error); // } //); } })(); pwdsphinx-2.0.4/ext/icon.png000066400000000000000000000105001507247604000160000ustar00rootroot00000000000000PNG  IHDR>asBIT|d pHYsuՀtEXtSoftwarewww.inkscape.org<IDATx] tTdY "V(bB VPJ[ąii՚P@˦ $9a޼73wwΜy}wm---p;b3<Zz3^ mLDp?CFQB!?*߃CBo[t"F"8*ʙ2֭[[Fם~㿞JRGE `}+u} "!kWaR]P&qCJpC0a*ҝ>;Q@q8'7Hme3gX𑖞3ھ_MmiyC^$R, K_PUrV~vμK6l+T4i սm@ \yFWcwA M.}Wv݁=:~PvS9lJ'Okp-@^ 泼Q`p!*?A(:ms̪N=KԞwH/* MpΓIj].iv=O2s]E \[ӽu]Yۮ!.{#qumM+v |!u|BR7͊1#ml}O/cǗBr|iV6>pZ{pB1fe?p~i5w*n6`V |M^oӻ37e:N9cʇMN x[A1ˋ#tf \?G#"Zg''a}}'<=f cY|oD=> oK_/']c: ,H?9YIѵ4BwlA4ܻqvH21>ZO<aP `&m ^^AnaN l03"ګorlaw.Y*&Y [|Jo83{Y}{Y[}ٛO> kc%jTRoDy^ɯ{yFWc9 a)vg8)w6&paY_Js(:wޒl7" |D}8 `5U QyrٱUfl[} pZa%iɒl:_I\fl[.8"`GySZHC҈ٹ|@V- Ǒ8kXBUZH:I]zG]U ,1bVr|ϤWFRT>f|=#-HbB]ۖF+/#1J E.RtYT63B E̜dlcBRhuhac2<R,x pH0*7sD%4Q.f ]TJpH02Yl{nsv84~m)pV@[Gz-3&/>,iD ycIO 2pv㭣?Ƌ',#-o˫ӊy"理wmbm4V[2чGe[.9ɌQ6a=p\+ yp(                  @qSr=WЍuu;¥',-DB[z]tGj˷y#-fB,o= 㾪k&0ؑpΡ Q۟Uh[KP oJ8GMȰߌӥo~֮Hg7T#T=c\ݱt =Qq-7esZ_@0DN;|WV6'_Zew %0B2cHIUc~/Pŵ䵶̾nF!Ɋ]Ҝuf&!>k`@Pnq~W|1z_7\|tH|}@u(} →KmvFۿAҞ.[пzWKsל8cʾ&ئp.҂Cpy5.V/N5)T- ǦN9y3יM_ZZp(O M+{G9xw[~G* 8'Ok&@C?c!!!_p{I-}pI/HBZQHun ڨ]:ᄔ3^f(?a[$J.8{ &Ijpڃ_LQlU[!?/O%|"Oۿ8T--Z7n2ArLUe9<-8Gx}(R@OFr~3{I;I&JCUDY$Hv I{#9K5)tQYG63dB,x!KQ 1%A/09i{l<0߀n<9m5sH KDK&~fOh IENDB`pwdsphinx-2.0.4/ext/inject.js000066400000000000000000000272711507247604000161710ustar00rootroot00000000000000/* * This file is part of WebSphinx. * Copyright (c) 2016 Danny van Kooten * Copyright (C) 2017 Iwan Timmer * Copyright (C) 2018 pitchfork@ctrlc.hu * * WebSphinx 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 2 of the License, or * (at your option) any later version. * * WebSphinx 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, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ "use strict"; var browser = browser || chrome; (function(doc) { const FORM_MARKERS = [ "login", "log-in", "log_in", "signin", "sign-in", "sign_in" ]; const USERNAME_FIELDS = { selectors: [ "input[name*=user i]", "input[name*=login i]", "input[name*=email i]", "input[id*=user i]", "input[id*=login i]", "input[id*=email i]", "input[class*=user i]", "input[class*=login i]", "input[class*=email i]", "input[type=email i]", "input[type=text i]", "input[type=tel i]" ], types: ["email", "text", "tel"] }; const PASSWORD_FIELDS = { selectors: ["input[type=password i]"] }; const INPUT_FIELDS = { selectors: PASSWORD_FIELDS.selectors.concat(USERNAME_FIELDS.selectors) }; const SUBMIT_FIELDS = { selectors: [ "[type=submit i]", "button[name*=login i]", "button[name*=log-in i]", "button[name*=log_in i]", "button[name*=signin i]", "button[name*=sign-in i]", "button[name*=sign_in i]", "button[id*=login i]", "button[id*=log-in i]", "button[id*=log_in i]", "button[id*=signin i]", "button[id*=sign-in i]", "button[id*=sign_in i]", "button[class*=login i]", "button[class*=log-in i]", "button[class*=log_in i]", "button[class*=signin i]", "button[class*=sign-in i]", "button[class*=sign_in i]", "input[type=button i][name*=login i]", "input[type=button i][name*=log-in i]", "input[type=button i][name*=log_in i]", "input[type=button i][name*=signin i]", "input[type=button i][name*=sign-in i]", "input[type=button i][name*=sign_in i]", "input[type=button i][id*=login i]", "input[type=button i][id*=log-in i]", "input[type=button i][id*=log_in i]", "input[type=button i][id*=signin i]", "input[type=button i][id*=sign-in i]", "input[type=button i][id*=sign_in i]", "input[type=button i][class*=login i]", "input[type=button i][class*=log-in i]", "input[type=button i][class*=log_in i]", "input[type=button i][class*=signin i]", "input[type=button i][class*=sign-in i]", "input[type=button i][class*=sign_in i]" ] }; function queryAllVisible(parent, field, form) { var result = []; for (var i = 0; i < field.selectors.length; i++) { var elems = parent.querySelectorAll(field.selectors[i]); for (var j = 0; j < elems.length; j++) { var elem = elems[j]; // Select only elements from specified form if (form && form != elem.form) { continue; } // Ignore disabled fields if (elem.disabled) { continue; } // Elem or its parent has a style 'display: none', // or it is just too narrow to be a real field (a trap for spammers?). if (elem.offsetWidth < 30 || elem.offsetHeight < 10) { continue; } // We may have a whitelist of acceptable field types. If so, skip elements of a different type. if (field.types && field.types.indexOf(elem.type.toLowerCase()) < 0) { continue; } // Elem takes space on the screen, but it or its parent is hidden with a visibility style. var style = window.getComputedStyle(elem); if (style.visibility == "hidden") { continue; } // Elem is outside of the boundaries of the visible viewport. var rect = elem.getBoundingClientRect(); if ( rect.x + rect.width < 0 || rect.y + rect.height < 0 || (rect.x > window.innerWidth || rect.y > window.innerHeight) ) { continue; } // This element is visible, will use it. result.push(elem); } } return result; } function queryFirstVisible(parent, field, form) { var elems = queryAllVisible(parent, field, form); return elems.length > 0 ? elems[0] : undefined; } function form() { var elems = queryAllVisible(document, INPUT_FIELDS, undefined); var forms = []; for (var i = 0; i < elems.length; i++) { var form = elems[i].form; if (form && forms.indexOf(form) < 0) { forms.push(form); } } if (forms.length == 0) { return undefined; } if (forms.length == 1) { return forms[0]; } // If there are multiple forms, try to detect which one is a login form var formProps = []; for (var i = 0; i < forms.length; i++) { var form = forms[i]; var props = [form.id, form.name, form.className]; formProps.push(props); for (var j = 0; j < FORM_MARKERS.length; j++) { var marker = FORM_MARKERS[j]; for (var k = 0; k < props.length; k++) { var prop = props[k]; if (prop.toLowerCase().indexOf(marker) > -1) { return form; } } } } console.error( "Unable to detect which of the multiple available forms is the login form. Please submit an issue for browserpass on github, and provide the following list in the details: " + JSON.stringify(formProps) ); return forms[0]; } function find(field) { return queryFirstVisible(document, field, form()); } function update(field, value) { if (!value.length) { return false; } // Focus the input element first var el = find(field); if (!el) { return false; } var eventNames = ["click", "focus"]; eventNames.forEach(function(eventName) { el.dispatchEvent(new Event(eventName, { bubbles: true })); }); // Focus may have triggered unvealing a true input, find it again el = find(field); if (!el) { return false; } // Now set the value and unfocus el.setAttribute("value", value); el.value = value; eventNames = [ "keypress", "keydown", "keyup", "input", "blur", "change" ]; eventNames.forEach(function(eventName) { el.dispatchEvent(new Event(eventName, { bubbles: true })); }); return true; } function update_all(field, value) { if (!value.length) { return false; } let password_inputs = queryAllVisible(document, PASSWORD_FIELDS, form()); password_inputs.forEach(function(el) { let eventNames = ["click", "focus"]; eventNames.forEach(function(eventName) { el.dispatchEvent(new Event(eventName, { bubbles: true })); }); // Focus may have triggered unvealing a true input, find it again let pwd_inputs = queryAllVisible(document, PASSWORD_FIELDS, form()); pwd_inputs.forEach(function(el2) { // Now set the value and unfocus el2.setAttribute("value", value); el2.value = value; let eventNames = [ "keypress", "keydown", "keyup", "input", "blur", "change" ]; eventNames.forEach(function(eventName) { el2.dispatchEvent(new Event(eventName, { bubbles: true })); }); }); }); return true; } function set_pwd(el, value) { let eventNames = ["click", "focus"]; eventNames.forEach(function(eventName) { el.dispatchEvent(new Event(eventName, { bubbles: true })); }); // Focus may have triggered unvealing a true input, find it again //let pwd_inputs = queryAllVisible(document, PASSWORD_FIELDS, form()); // we ignore this for now //pwd_inputs.forEach(function(el2) { // Now set the value and unfocus el.setAttribute("value", value); el.value = value; eventNames = [ "keypress", "keydown", "keyup", "input", "blur", "change" ]; eventNames.forEach(function(eventName) { el.dispatchEvent(new Event(eventName, { bubbles: true })); }); //}); } class WebSphinx { recon() { var username = ''; var el = find(USERNAME_FIELDS); if(el) { username=el.value; } var password_inputs = queryAllVisible(document, PASSWORD_FIELDS, form()); browser.runtime.sendMessage({"username": username, "password_fields": password_inputs.length}); }; login(login) { update(USERNAME_FIELDS, login.username); update(PASSWORD_FIELDS, login.password); var password_inputs = queryAllVisible(document, PASSWORD_FIELDS, form()); if (password_inputs.length > 1) { // There is likely a field asking for OTP code, so do not submit form just yet password_inputs[1].select(); } else { window.requestAnimationFrame(function() { // Try to submit the form, or focus on the submit button (based on user settings) var submit = find(SUBMIT_FIELDS); if (submit) { submit.focus(); } else { // There is no submit button. We need to keep focus somewhere within the form, so that Enter hopefully submits the form. var password = find(PASSWORD_FIELDS); if (password) { password.focus(); } else { var username = find(USERNAME_FIELDS); if (username) { username.focus(); } } } }); } }; create(account) { update(USERNAME_FIELDS, account.username); update_all(PASSWORD_FIELDS, account.password); window.requestAnimationFrame(function() { // Try to submit the form, or focus on the submit button (based on user settings) var submit = find(SUBMIT_FIELDS); if (submit) { submit.focus(); } else { // There is no submit button. We need to keep focus somewhere within the form, so that Enter hopefully submits the form. var password = find(PASSWORD_FIELDS); if (password) { password.focus(); } } }); }; change(changed) { var pwd_inputs = queryAllVisible(document, PASSWORD_FIELDS, form()); if(pwd_inputs.length!=3) { console.log("wtf"); console.log(pwd_inputs); return; } set_pwd(pwd_inputs[0],changed.old.password); set_pwd(pwd_inputs[1],changed.new.password); set_pwd(pwd_inputs[2],changed.new.password); window.requestAnimationFrame(function() { // Try to submit the form, or focus on the submit button (based on user settings) var submit = find(SUBMIT_FIELDS); if (submit) { submit.focus(); } else { // There is no submit button. We need to keep focus somewhere within the form, so that Enter hopefully submits the form. var password = find(PASSWORD_FIELDS); if (password) { password.focus(); } } }); }; inject(pwd) { let el = document.activeElement; if(el.type=="password") { set_pwd(el, pwd); } } } doc.websphinx = new WebSphinx(); })(document); pwdsphinx-2.0.4/ext/manifest_chrome.json000066400000000000000000000023161507247604000204060ustar00rootroot00000000000000{ "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiIpLogUg/aqfPydJjvRyxwUYME3LdoG6tHItPEYPPtquG60U1mFopkN2epr9HoyDEX334AsBkyxY6qxbQZZZVY+8xSPnJZhE/g7Cpo/eLvbX68avgavWp2/RCXjaW4BW06v4IcCKlI09jdWR7Oo33RGcsZer/FJTLiunoUl+6W5ap3KAry1JrLg5FwHYicaghwNrxM9zCDUbr0n7g7C7p/oHC/iCSmJgMZo5qA6sXfxxZgy2lTtB0M5y/NihbgeTvoF+GgJ9iFwfwIP4nyK6JPThRqCFguTQCMcvaqhMey9MjUC5aIZ2fRbuEV4XuyV+48jK5Dun/pDgXlzhmzjowwIDAQAB", "manifest_version": 3, "name": "WebSphinx", "description": "__MSG_extDescription__", "version": "0.1", "default_locale": "en", "background": { "service_worker": "background.js", "type": "module" }, "action": { "default_icon": "icon.png", "default_popup": "popup.html" }, "commands": { "_execute_action": { "suggested_key": { "default": "Ctrl+Shift+L" } } }, "host_permissions": [ "*://*/*" ], "content_scripts": [ { "matches": ["http://*/*", "https://*/*"], "js": ["content_script.js"], "run_at":"document_start" } ], "web_accessible_resources": [ { "resources": ["webauthn.js"], "matches": ["http://*/*", "https://*/*"] } ], "permissions": [ "activeTab", "nativeMessaging" ] } pwdsphinx-2.0.4/ext/manifest_ff.json000066400000000000000000000015201507247604000175200ustar00rootroot00000000000000{ "manifest_version": 2, "name": "WebSphinx", "description": "__MSG_extDescription__", "version": "0.1.1", "default_locale": "en", "applications": { "gecko": { "id": "sphinx@ctrlc.hu", "strict_min_version": "57.0" } }, "background": { "scripts": ["background.js"], "persistent": true }, "browser_action": { "default_icon": "icon.png", "default_popup": "popup.html" }, "commands": { "_execute_browser_action": { "suggested_key": { "default": "Ctrl+Shift+L" } } }, "content_scripts": [ { "matches": ["http://*/*", "https://*/*"], "js": ["content_script.js"], "run_at":"document_start" } ], "web_accessible_resources": ["webauthn.js"], "permissions": [ "scripting", "activeTab", "nativeMessaging", "" ] } pwdsphinx-2.0.4/ext/popup.css000066400000000000000000000022401507247604000162210ustar00rootroot00000000000000html, body { margin: 0; padding: 0; } body { min-width: 217px; } label, input[type="checkbox"] { margin-left: 10px; } input[type='text']#pwdlen { width: auto; padding: 10px; border: 0; box-sizing: border-box; } #search, input[type='text'] { width: 100%; padding: 10px; border: 0; box-sizing: border-box; } #search:focus, input[type='text']:focus { outline: 0; } #results { list-style-type: none; margin: 0; padding: 0; } #results:empty { display: none; } button.selected, button#close { width: auto; background-color: #fff; border-left: 1px solid black; border-right: 1px solid black; border-top: 1px solid black; box-shadow: none; text-align: left; padding: 10px; } button.inactive { width: auto; background-color: #aaa; border: 1px solid black; box-shadow: none; text-align: left; padding: 10px; } button.insert { width: 100%; color: blue; text-align: center; } button { width: 100%; background-color: #fff; border: 0; box-shadow: none; text-align: left; padding: 10px; } button:hover, button:focus, .focus button { outline: 0; background-color: #eee; } .hidden { display: none; } pwdsphinx-2.0.4/ext/popup.html000066400000000000000000000036531507247604000164060ustar00rootroot00000000000000

pwdsphinx-2.0.4/ext/popup.js000066400000000000000000000361271507247604000160600ustar00rootroot00000000000000/* * This file is part of WebSphinx. * Copyright (C) 2017 Iwan Timmer * Copyright (C) 2018 pitchfork@ctrlc.hu * * WebSphinx 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 2 of the License, or * (at your option) any later version. * * WebSphinx 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, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ "use strict"; const APP_NAME = "websphinx"; var browser = browser || chrome; var self = null; class Sphinx { constructor() { this.selectionIndex = -1; this.site = ''; this.user = ''; this.users = []; this.mode = ''; this.inputs = 0; this.background = browser.runtime.connect({'name': 'popup'}); browser.tabs.query({ currentWindow: true, active: true }, this.onTabs.bind(this)); // tabs + close document.getElementById("login_tab").addEventListener("click",this.switchTab.bind(this)); document.getElementById("create_tab").addEventListener("click",this.switchTab.bind(this)); document.getElementById("change_tab").addEventListener("click",this.switchTab.bind(this)); document.getElementById("close").addEventListener("click",function() {window.close();}); // manual get/insert buttons document.getElementById("login_pwd").addEventListener("click",this.getpwd); document.getElementById("old_pwd").addEventListener("click",this.getpwd); document.getElementById("new_pwd").addEventListener("click",this.newpwd); document.getElementById("create_pwd").addEventListener("click",this.createpwd); document.getElementById('save_pwd').addEventListener("click", this.onClickCommit.bind(this)); let size_wdgt = document.getElementById("pwdlen"); size_wdgt.setAttribute("placeholder", browser.i18n.getMessage("sizePlaceholder")); size_wdgt.addEventListener("keydown", this.onKeyDownCreate); this.search = document.getElementById("search"); this.search.setAttribute("placeholder", browser.i18n.getMessage("searchPlaceholder")); this.search.addEventListener("blur", this.onBlur.bind(this)); self = this; } userList() { setTimeout(() => { this.search.focus(); }, 100); let ul = document.getElementById("results"); if(ul.firstChild == null && this.users.length>0) { for (let result of this.users) { let domain = result.split('/').reverse()[0]; let item = document.createElement("li"); let button = document.createElement("button"); //let favicon = document.createElement("img"); let label = document.createElement("span"); label.textContent = result; button.addEventListener("click", this.onClick.bind(this)); button.appendChild(label); item.appendChild(button); ul.appendChild(item); } results.className = null; } } commit_ui() { this.select_tab('change'); //document.getElementById("change_phase1").className = "hidden"; document.getElementById("change_phase2").className = null; document.getElementById("autofill").className = "hidden"; document.getElementById("results").className = "hidden"; } decide() { if(this.inputs == 1) { // one password field -> probably login // only one user in our db - use that to auto login this.select_tab('login'); if(this.users.length == 1) { this.background.postMessage({ "action": "login", "site": this.site, "name": this.users[0], "mode": "insert" }); //window.close(); return; } // user set in the forms user field, auto select that user for(let user of this.users) { if(user == this.user && user != '') { this.background.postMessage({ "action": "login", "site": this.site, "name": user, "mode": "insert" }); //window.close(); return; } } // can't decide let user select which username to use for login } else if(this.inputs == 2) { // 2 password fields -> either create user, or login with OTP field. if(this.users.length == 0) { // no users associated wit this site, should be a register form this.select_tab('create'); return; } // if there is already a user specified in the username field // and that is a registered user with us, then we assume it's a // login form for(let user of this.users) { if(user == this.user && user != '') { this.background.postMessage({ "action": "login", "site": this.site, "name": user, "mode": "insert" }); this.select_tab('login'); return; } } // unsure: could be a login form with an OTP field, but could also be a registration form. this.select_tab('create'); return; } else if(this.inputs == 3) { // probably change password field if(this.users.length == 0) { // no users associated wit this site, can't be a change password form // todo handle this case, but how? this.select_tab('create'); return; } if(this.users.length == 1) { // we have only one registered user with this site, so it's easy this.commit_ui(); this.background.postMessage({ "action": "change", "site": this.site, "name": this.users[0], "mode": "insert" }); //window.close(); return; } // choose user to change password for this.select_tab('change'); } else { console.log("are you kidding me?"); } } recon_cb(response) { browser.runtime.onMessage.removeListener(self.recon_cb); //console.log(response); self.user = response.username; self.inputs = response.password_fields; self.decide(); } get_users_cb(response) { self.background.onMessage.removeListener(self.get_users_cb); //console.log(response); if(response.results) { self.users = response.results.names; } // now also figure out what this page is about browser.tabs.executeScript({ file: '/inject.js', allFrames: true }, function() { browser.tabs.executeScript({code: 'document.websphinx.recon();'}); }); } onTabs(tabs) { // clear user list let results = document.getElementById("results"); while (results.firstChild) results.removeChild(results.firstChild); if (tabs[0] && tabs[0].url) { this.site = new URL(tabs[0].url).hostname; } browser.runtime.onMessage.addListener(this.recon_cb); this.background.onMessage.addListener(this.get_users_cb); // first get users associated with this site this.background.postMessage({ action: "list", mode: "init", site: this.site }); } onBlur(event) { let results = document.getElementById("results"); if (results.children[this.selectionIndex]) results.children[this.selectionIndex].className = ''; this.selectionIndex = -1; } commit_cb(response) { self.background.onMessage.removeListener(self.commit_cb); console.log(response); // todo better handling } onClickCommit(event) { this.background.onMessage.addListener(this.commit_cb); this.background.postMessage({ "action": "commit", "site": this.site, "name": this.user, "mode": "" }); window.close(); } onAutoClick(event) { self.background.postMessage({ "action": self.mode, "site": self.site, "name": self.search.value, "mode": "insert" }); } onClick(event) { this.background.postMessage({ "action": this.mode, "site": this.site, "name": event.target.textContent, "mode": "insert" }); if(this.mode != 'change') window.close(); else { this.user = event.target.textContent; this.commit_ui(); } } onKeyDown(event) { let results = document.getElementById("results"); if (event.keyCode == 0x0d) { if(self.search.value!='') { self.background.postMessage({ "action": self.mode, "site": self.site, "name": self.search.value, "mode": "insert" }); } else if(results.children[self.selectionIndex]) { self.background.postMessage({ "action": self.mode, "site": self.site, "name": results.children[self.selectionIndex].textContent, "mode": "insert" }); } if(self.mode != 'change') window.close(); else self.commit_ui(); } else if (event.keyCode == 0x26 && self.selectionIndex > 0) self.selectionIndex--; else if (event.keyCode == 0x28 && self.selectionIndex < results.childElementCount - 1) self.selectionIndex++; else return; for (let e of results.getElementsByClassName('focus')) e.className = ''; if(self.selectionIndex >= 0 && self.selectionIndex < results.childElementCount) { results.children[self.selectionIndex].className = "focus"; } event.preventDefault(); } flashError(el) { el.style="background: red;"; setTimeout(() => { el.focus(); }, 100); setTimeout(() => { el.style=''; }, 1000); } getpwdrules() { const rules = [{"title": "Upper", "value": 'u',}, {"title": "Lower", "value": 'l'}, {"title": "Symbols", "value": "s"}, {"title": "Digits", "value": "d"}]; // get character class rules let r = ""; for (let rule of rules) { let checkbox = document.getElementById(rule['title']); if(checkbox.checked) r+=rule['value']; } if(r=="") { for (let rule of rules) { let checkbox = document.getElementById(rule['title']); let label = checkbox.nextSibling; label.style="background: red;"; setTimeout(() => { checkbox.focus(); }, 100); setTimeout(() => { label.style=''; }, 1000); } return; } // get password size let size = 0; let input = document.getElementById('pwdlen'); if(input.value != '') { try { size = Number(input.value) } catch (e) { this.sizeError(input); return; } } if(isNaN(size)) { this.flashError(input); return; } return [r,size]; } submitCreate() { let r_ = self.getpwdrules(); if (r_ == null) return; let r=r_[0], size = r_[1]; if(self.user == '') { if(self.search.value == '') { self.flashError(self.search); return; } // we assume the value of the search field to be the username to be created self.user = self.search.value; } self.background.postMessage({ "action": "create", "site": self.site, "name": self.user, "rules": r, "size": size, "mode": "insert" }); window.close(); } onKeyDownCreate(event) { if (event.keyCode == 0x0d) { self.submitCreate(); event.preventDefault(); } } select_tab(tabid) { let tab = document.getElementById(tabid+'_tab'); this.switchTab({target: tab}); } switchTab(event) { if(this.mode==event.target.id.slice(0,-4)) return; // set mode this.mode = event.target.id.slice(0,-4); let autofill = document.getElementById("autofill"); let tabs = document.getElementById("tabs"); for (let selected of tabs.getElementsByClassName('selected')) { selected.className="inactive"; let tab = selected.id.slice(0,-4); document.getElementById(tab).className="hidden"; // remove event listeners if(tab == "create") { this.search.removeEventListener("keydown", this.onKeyDownCreate); autofill.removeEventListener("click", this.submitCreate); } else { this.search.removeEventListener("keydown", this.onKeyDown); autofill.removeEventListener("click", this.onAutoClick); } } event.target.className="selected"; let selected = document.getElementById(this.mode); selected.className=null; if(this.mode=="create") { document.getElementById("results").className = "hidden"; this.search.addEventListener("keydown", this.onKeyDownCreate); autofill.addEventListener("click", this.submitCreate); for(let u of this.users) { if(this.user == u) this.user = ''; if(this.search.value==u) this.search.value = ''; } if(this.user!='' && this.search.value=='') this.search.value=this.user; else if(this.user=='' && this.search.value!='') this.user=this.search.value; else if(this.user!='' && this.search.value!='' && this.user!=this.search.value) this.user=this.search.value; if(this.user == '') setTimeout(() => {this.search.focus();}, 100); else setTimeout(() => {document.getElementById("pwdlen").focus();}, 100); } else { this.search.addEventListener("keydown", this.onKeyDown); autofill.addEventListener("click", this.onAutoClick); this.userList(); if(this.user!='') this.search.value=this.user; let sf = false, uf = false; for(let u of this.users) { if(this.user == u) uf=true; if(this.search.value==u) sf=true; } if(sf && !uf) this.user=this.search.value; else if(!sf && uf) this.search.value=this.user; else if(sf && uf && this.user!=this.search.value) this.user=this.search.value; } if(this.user!='') { autofill.className = "insert"; } } fetchpwd(el, eh, mode, rules, size) { if(this.user == '') { if(this.search.value == '') { this.flashError(this.search); return; } // we assume the value of the search field to be the username to be created this.user = this.search.value; } // todo on change password when inserting new password also show save new password button let fetchpwd_cb = function(response) { self.background.onMessage.removeListener(self.fetchpwd_cb); el.getElementsByClassName('pwd_action')[0].textContent = "Insert"; el.removeEventListener("click", eh); el.addEventListener("click",function(e) { // inject response.password into currently focused element browser.tabs.executeScript({code: 'document.websphinx.inject(' + JSON.stringify(response.results.password) + ');'}); }); if(mode=="change") self.commit_ui(); } this.background.onMessage.addListener(fetchpwd_cb); this.background.postMessage({ "action": mode, "site": this.site, "name": this.user, "rules": rules, // optional only used with create "size": size, // optional only used with create "mode": "manual" }); // needed for background to trigger proper callback } getpwd(e) { self.fetchpwd(e.target, self.getpwd, "login", null, null); } newpwd(e) { self.fetchpwd(e.target, self.newpwd, "change", null, null); } createpwd(e) { let r_ = self.getpwdrules(); if (r_ == null) return; let r=r_[0], size = r_[1]; self.fetchpwd(e.target, self.createpwd, "create", r, size); } } document.addEventListener("DOMContentLoaded", function(event) { new Sphinx(); }); pwdsphinx-2.0.4/ext/webauthn.js000066400000000000000000000141431507247604000165240ustar00rootroot00000000000000// save original credential functions const browserCredentials = { create: navigator.credentials.create.bind(navigator.credentials), get: navigator.credentials.get.bind(navigator.credentials), }; // override credentials.create navigator.credentials.create = async function(args) { let options = args.publicKey; if(!options || !options.pubKeyCredParams) { // not webauthn call // TODO throw popop warning return await browserCredentials.create(options); } //algos: // -8: Ed25519 <- only supported // -7: ES256 // -257: RS256 let hasSupportedAlgo = false; for(let a of options.pubKeyCredParams) { if(a.alg == -8) { hasSupportedAlgo = true; break; } } if(!hasSupportedAlgo) { return await browserCredentials.create(options); } const host = window.location.hostname; options.challenge = arrayBufferToBase64(options.challenge); options["type"] = "webauthn.create"; options["origin"] = window.location.origin; // Required response fields const params = { 'challenge': options.challenge, 'username': options.user.name, 'userid': arrayBufferToBase64(options.user.id), 'clientDataJSON': JSON.stringify(options), }; let response = await createEvent("webauthn-create", params); response.clientDataJSON = JSON.stringify(options); let createObj = createCreateCredentialsResponse(response); return createObj; }; // override credentials.get navigator.credentials.get = async function(options) { if(!options && !options.publicKey) { // not webauthn call return await browserCredentials.get(options); } const pubKeyObj = options.publicKey; if(pubKeyObj['allowCredentials'].length == 0) { return await browserCredentials.get(options); } const key = pubKeyObj['allowCredentials'][0].id; options["type"] = "webauthn.get"; options["origin"] = window.location.origin; options["challenge"] = arrayBufferToBase64(pubKeyObj.challenge); // Required response fields const params = { 'pk': arrayBufferToBase64(key), 'challenge': arrayBufferToBase64(pubKeyObj.challenge), 'clientDataJSON': JSON.stringify(options), }; const response = await createEvent("webauthn-get", params); response.challenge = pubKeyObj.challenge; response.clientDataJSON = JSON.stringify(options); let getObj = createGetCredentialsResponse(response); return getObj; }; // initiate messaging with the backend async function createEvent(action, params) { let msg = { "type": "sphinxWebauthnEvent", "action": action, "params": params, }; const { port1: localPort, port2: remotePort } = new MessageChannel(); const promise = new Promise((resolve) => { localPort.onmessage = (event) => { resolve(event.data); } }); try { window.postMessage(msg, '*', [remotePort]); } catch(err) { console.log("Failed to send message to content script:", err); } let resp = await promise; return resp; } // create the response object of credentials.create function createCreateCredentialsResponse(res) { if(res.error) { return; } res.pk = res.pk.replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', ''); const credential = { id: res.pk, rawId: stringToBuffer(res.pk, true), type: "public-key", authenticatorAttachment: "platform", response: { // TODO attestationObject https://developer.mozilla.org/en-US/docs/Web/API/AuthenticatorAttestationResponse/attestationObject attestationObject: stringToBuffer(res.attestationObject, true), clientDataJSON: stringToBuffer(res.clientDataJSON), // A JSON string in an ArrayBuffer, representing the client data that was passed to CredentialsContainer.create() publicKeyAlgorithm: -8, transports: ["internal"], //getPublicKey: () => stringToBuffer(res.pk, true), //getPublicKeyAlgorithm: () => -8, //getTransport: () => "", //getAuthenticatorData: () => "", }, key: stringToBuffer(res.pk, true), getClientExtensionResults: () => {}, }; Object.setPrototypeOf(credential.response, AuthenticatorAttestationResponse.prototype); Object.setPrototypeOf(credential, PublicKeyCredential.prototype); credential.response.getTransports = () => credential.response.transports; credential.response.getPublicKey = () => credential.rawId; credential.response.getPublicKeyAlgorithm = () => -8; credential.response.getAuthenticatorData = () => stringToBuffer(res.authData, true); return credential; } // create the response object of credentials.get function createGetCredentialsResponse(res) { if(res.error) { return; } res.pk = res.pk.replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', ''); const credential = { id: res.pk, rawId: stringToBuffer(res.pk, true), challenge: res.challenge, response: { clientDataJSON: stringToBuffer(res.clientDataJSON), // A JSON string in an ArrayBuffer, representing the client data that was passed to CredentialsContainer.create() authenticatorData: stringToBuffer(res.authData, true), signature: stringToBuffer(res.sig, true), userHandle: res.userid, }, type: "public-key", authenticatorAttachment: null, } credential.getClientExtensionResults = () => {}; return credential; } function stringToBuffer(s, isB64) { if(!s) { return new Uint8Array(0); } if(isB64) { s = atob(s.replaceAll('-', '+').replaceAll('_', '/')); } const arr = Uint8Array.from(s, c => c.charCodeAt(0)); return arr.buffer; } function arrayBufferToBase64(buffer) { let binary = ''; const bytes = new Uint8Array( buffer ); for (let i = 0; i < bytes.byteLength; i++) { binary += String.fromCharCode(bytes[i]); } return toBase64(binary); } function toBase64(s) { return window.btoa(s).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', ''); } pwdsphinx-2.0.4/man/000077500000000000000000000000001507247604000143215ustar00rootroot00000000000000pwdsphinx-2.0.4/man/bin2pass.md000066400000000000000000000032451507247604000163700ustar00rootroot00000000000000% bin2pass(1) | converts binary input to passwords # NAME bin2pass - converts binary input to passwords # SYNOPSIS ``` bin2pass [d|u|l] [] [] ?@[\]^_`{}~ ``` Note that spaces are allowed in the symbol set. Be careful to properly quote special characters that your shell might interpret, such as `"`, `!`, and `\`. # EXAMPLES Generate the longest possible random password from `/dev/random`, with the resulting password having characters from digits, lowercase and uppercase letters, and the `space` and `*` symbols. ``` dd if=/dev/random bs=1 count=32 | ./pwdsphinx/bin2pass.py " *" ``` # REPORTING BUGS https://github.com/stef/pwdsphinx/issues/ # AUTHOR Written by Stefan Marsiske. # COPYRIGHT Copyright © 2023 Stefan Marsiske. License GPLv3+: GNU GPL version 3 or later https://gnu.org/licenses/gpl.html. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. # SEE ALSO `sphinx(1)` pwdsphinx-2.0.4/man/dmenu-sphinx.md000066400000000000000000000024501507247604000172630ustar00rootroot00000000000000% dmenu-sphinx(1) | dmenu-frontend for retrieving and inserting passwords from sphinx(1) into X11 applications # NAME dmenu-sphinx - dmenu-frontend for retrieving and inserting passwords from sphinx(1) into X11 applications # SYNOPSIS ``` dmenu-sphinx [username] [hostname] ``` # DESCRIPTION `dmenu-sphinx` provides an interactive interface for retrieving SPHINX passwords and automatically typing them into X11 applications. It uses `dmenu(1)` to present hostname selection menus and builds on `type-pwd(1)` for password entry. The tool first displays cached hostnames from previous usage. If multiple usernames exist for the selected hostname, it presents a username selection menu. Otherwise, it proceeds directly to password generation. Finally, it invokes `type-pwd(1)` to type the password into the focused application. The hostname history is cached in the file `~/.sphinx-hosts`. # REPORTING BUGS https://github.com/stef/pwdsphinx/issues/ # AUTHOR Written by Stefan Marsiske. # COPYRIGHT Copyright © 2023 Stefan Marsiske. License GPLv3+: GNU GPL version 3 or later https://gnu.org/licenses/gpl.html. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. # SEE ALSO `sphinx(1)`, `type-pwd(1)`, `exec-on-click(1)`, `getpwd(1)` pwdsphinx-2.0.4/man/exec-on-click.md000066400000000000000000000020051507247604000172610ustar00rootroot00000000000000% exec-on-click(1) | simple tool that executes command when a left mouse-click is detected # NAME exec-on-click - simple tool that executes command when a left mouse-click is detected # SYNOPSIS ``` exec-on-click ``` # DESCRIPTION `exec-on-click` is a simple tool that waits for a left mouse click and then executes whatever parameters the script has been called with. # EXAMPLE ``` echo -n "hello world" | exec-on-click xdotool type --clearmodifiers '$(cat)' ``` Types `hello world` into the current window using [xdotool](https://github.com/jordansissel/xdotool), a program that lets you simulate keyboard input and mouse activity. # REPORTING BUGS https://github.com/stef/pwdsphinx/issues/ # AUTHOR Written by Stefan Marsiske. # COPYRIGHT Copyright © 2023 Stefan Marsiske. License GPLv3+: GNU GPL version 3 or later https://gnu.org/licenses/gpl.html. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. # SEE ALSO `sphinx(1)` pwdsphinx-2.0.4/man/getpwd.md000066400000000000000000000022311507247604000161330ustar00rootroot00000000000000% getpwd(1) | simple tool that queries a password from a user and writes it to standard output # NAME getpwd - simple tool that queries a password from a user and writes it to standard output # SYNOPSIS ``` getpwd ["prompt"] | sphinx get username hostname ``` # DESCRIPTION `getpwd` securely prompts for a password using `pinentry` from the GnuPG project and outputs it to standard output. This approach is safer than echoing passwords directly into commands, as it prevents passwords from appearing in process lists or command history. The tool supports various `pinentry` interfaces including curses, GTK, and Qt variants, allowing you to choose the interface that best fits your desktop environment. The parameter, `prompt`, specifies the prompt text displayed when asking for the password. # REPORTING BUGS https://github.com/stef/pwdsphinx/issues/ # AUTHOR Written by Stefan Marsiske. # COPYRIGHT Copyright © 2023 Stefan Marsiske. License GPLv3+: GNU GPL version 3 or later https://gnu.org/licenses/gpl.html. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. # SEE ALSO `sphinx(1)` pwdsphinx-2.0.4/man/makefile000066400000000000000000000027101507247604000160210ustar00rootroot00000000000000all: sphinx.1 oracle.1 bin2pass.1 websphinx.1 getpwd.1 exec-on-click.1 type-pwd.1 dmenu-sphinx.1 sphinx-x11.1 sphage.1 \ otp.sphinx.1 pass.sphinx.1 user-pass-otp.sphinx.1 user-pass.sphinx.1 getacc-user-pass.sphinx.1 pipe2tmpfile.1 html: sphinx.html oracle.html bin2pass.html websphinx.html getpwd.html exec-on-click.html type-pwd.html dmenu-sphinx.html \ sphinx-x11.html sphage.html pipe2tmpfile.html install: $(DESTDIR)$(PREFIX)/share/man/man1/sphinx.1 $(DESTDIR)$(PREFIX)/share/man/man1/oracle.1 $(DESTDIR)$(PREFIX)/share/man/man1/bin2pass.1 \ $(DESTDIR)$(PREFIX)/share/man/man1/getpwd.1 $(DESTDIR)$(PREFIX)/share/man/man1/exec-on-click.1 $(DESTDIR)$(PREFIX)/share/man/man1/type-pwd.1 \ $(DESTDIR)$(PREFIX)/share/man/man1/dmenu-sphinx.1 $(DESTDIR)$(PREFIX)/share/man/man1/sphinx-x11.1 $(DESTDIR)$(PREFIX)/share/man/man1/sphage.1 \ $(DESTDIR)$(PREFIX)/share/man/man1/websphinx.1 $(DESTDIR)$(PREFIX)/share/man/man1/otp.sphinx.1 $(DESTDIR)$(PREFIX)/share/man/man1/pass.sphinx.1 \ $(DESTDIR)$(PREFIX)/share/man/man1/user-pass-otp.sphinx.1 $(DESTDIR)$(PREFIX)/share/man/man1/user-pass.sphinx.1 $(DESTDIR)$(PREFIX)/share/man/man1/pipe2tmpfile.1 clean: rm -f *.1 rm -f *.html otp.sphinx.1: sphinx-x11.1 ln -s $< $@ pass.sphinx.1: sphinx-x11.1 ln -s $< $@ user-pass-otp.sphinx.1: sphinx-x11.1 ln -s $< $@ user-pass.sphinx.1: sphinx-x11.1 ln -s $< $@ getacc-user-pass.sphinx.1: sphinx-x11.1 ln -s $< $@ %.1: %.md pandoc -s -o $@ $< %.html: %.md pandoc -s -o $@ $< pwdsphinx-2.0.4/man/oracle.md000066400000000000000000000112371507247604000161140ustar00rootroot00000000000000% oracle(1) | server for the SPHINX password manager # NAME oracle - server for the SPHINX password manager # SYNOPSIS `oracle [init]` # DESCRIPTION The SPHINX protocol only makes sense if the server (called *oracle*) is located somewhere other than where you type your password. pwdsphinx comes with a server implemented in Python 3, which you can host off-site from your usual desktop or smartphone. For production deployments, [**zphinx-zerver**](https://github.com/stef/zphinx-zerver) is recommended over pwdsphinx. zphinx-zerver is a production-grade server implementation written in Zig that offers better reliability for hosting SPHINX services. The server can be started simply by running `oracle`. It does not take any parameters. # CONFIGURATION The server can be configured using any of the following files: - `/etc/sphinx/config` - `~/.sphinxrc` - `~/.config/sphinx/config` - `./sphinx.cfg` Files are parsed in the order listed above, so global settings can be overridden by per-user and per-directory settings. Configuration is done by editing variables in the `[server]` section of the configuration file. - `address`: Determines on what address the server is listening. The default is `localhost`: you might want to change that to a specific IP address. - `port`: Sets the port the server is listening on. The default is `2355`. Another recommended port value is `443`, which is allowed by most firewalls, while `2355` is not. - `ssl_key`, `ssl_cert`: Required. Have no defaults, and must be set to point at a traditional TLS certificate and secret key file. It is recommended to not use self-signed certs, but CA-signed certs that are recognized widely by browsers and other TLS clients when possible. - `datadir`: The data directory where all the device "secrets" are stored. This defaults to `data/` in the current directory. Backup this directory regularly and securely, since the loss of this directory means users lose access to their passwords. - `verbose`: Enables logging to standard output. - `timeout`: Sets the TCP connection timeout. Increase for slow networks, with the caveat that this might lead to easier resource exhaustion, by blocking all workers. - `max_kids`: Sets the maximum number of requests handled in parallel. The `timeout` config variable makes sure that all handlers are recycled in predictable time. - `rl_decay`: Specifies the number of seconds after which a rate-limit level decays to an easier difficulty. Together with `rl_threshold` and `rl_gracetime`, these params are used to configure rate limiting. - `rl_threshold`: Configures the number of failed attempts before increasing the difficulty level - `rl_gracetime`: Sets the number of additional seconds allowed - beyond the max solution time fixed for a certain difficulty - before a rate-limiting puzzle expires. - `ltsigkey`: Sets the path to the long-term signature private key. You can generate one by running `oracle init`. This will also create a public key and its Base64 encoded variant, which should be published to all potential users so that they can use your oracle in a threshold setup. # INITIALIZING AN ORACLE Given a configuration, the oracle can generate its own long-term signature key by running: ``` oracle init ``` This stores the private key at the location specified by `ltsigkey` and outputs the corresponding public key at the same location, with a `.pub` extension. The public key is also displayed as a Base64-encoded string on standard output. # SECURITY CONSIDERATIONS The `max_kids` and `timeout` settings can be used to control how many requests are served in parallel and how long each request can run. Without careful tuning, an attacker could launch a denial-of-service attack by keeping all `max_kids` connections busy. Since the server only knows about failed authorizations for management operations (not incorrect master passwords for `get` requests), brute-force attempts can only be mitigated via rate limiting. Adjusting `rl_*` parameters allows you to make puzzles more difficult. On devices with less than 1GB RAM, you can increase the difficulty enough that they cannot solve the puzzles. Rate limiting in general should not be noticeable, unless dozens of `get` requests are made to the same record. At the highest difficulty level, solving should take around 20–40 seconds, depending on CPU performance. # REPORTING BUGS https://github.com/stef/pwdsphinx/issues/ # AUTHOR Written by Stefan Marsiske. # COPYRIGHT Copyright © 2024 Stefan Marsiske. License GPLv3+: GNU GPL version 3 or later https://gnu.org/licenses/gpl.html. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. # SEE ALSO `sphinx(1)`, `getpwd(1)` pwdsphinx-2.0.4/man/pipe2tmpfile.md000066400000000000000000000044401507247604000172450ustar00rootroot00000000000000% pipe2tmpfile(1) | simple tool that allows commands that expect files to work with data coming through a pipe # NAME pipe2tmpfile - simple tool that allows commands that expect files to work with data coming through a pipe # SYNOPSIS ``` echo input | pipe2tmpfile @@keyfile@@ [additional args...] ``` The `command` will run with a temporary file containing the piped content, where `@@keyfile@@` is replaced with the temporary file path. # DESCRIPTION `pipe2tmpfile` is a utility that bridges the gap between commands that output data to stdout and commands that require file input. It reads data from standard input, writes it to a secure temporary file, and then executes a specified command with the temporary file path substituted for the `@@keyfile@@` token. This tool is particularly useful when working with sensitive data like cryptographic keys or passwords that should not be written to permanent storage. The temporary file is automatically deleted after the command finishes running, ensuring no sensitive data remains on disk. # EXAMPLE Sign a file using a minisign key stored in SPHINX: ```sh getpwd | sphinx get minisig://user1 minisign-test-key | pipe2tmpfile minisign -S -s @@keyfile@@ -m filetosign ``` This command: 1. Prompts for your master password via `getpwd` 2. Retrieves the `minisign` private key from SPHINX 3. Writes the key to a secure temporary file 4. Runs `minisign` to sign `filetosign` using the temporary key file 5. Automatically deletes the temporary key file # SECURITY CONSIDERATIONS Since the output of SPHINX is generally sensitive, it is advised not to write it to permanent storage. Thus, `pipe2tmpfile` tries to store it in a temporary file storage. By default, this is stored under `/run/user/$(id -u)`. However, users can provide an alternative path to store these files by setting the environment variable `keyroot`. The temporary files are deleted after the execution of the command. # REPORTING BUGS https://github.com/stef/pwdsphinx/issues/ # AUTHOR Written by Stefan Marsiske. # COPYRIGHT Copyright © 2024 Stefan Marsiske. License GPLv3+: GNU GPL version 3 or later https://gnu.org/licenses/gpl.html. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. # SEE ALSO `sphinx(1)` pwdsphinx-2.0.4/man/sphage.md000066400000000000000000000017731507247604000161220ustar00rootroot00000000000000% sphage(1) | converts 32 bytes binary data into an age(1) keypair # NAME sphage - converts 32 bytes binary data into an age(1) keypair # SYNOPSIS ``` echo "32 byte high-entropy string....." | sphage privkey >/tmp/privatekey echo "32 byte high-entropy string....." | sphage pubkey >/tmp/pubkey ``` # DESCRIPTION `sphage` converts the raw output of `sphinx(1)` into a cryptographic key pair compatible with [age](https://age-encryption.org). It can also convert an age secret key into its corresponding age public key. This enables integration between SPHINX and age-based encryption workflows for sophisticated secrets management setups. # REPORTING BUGS https://github.com/stef/pwdsphinx/issues/ # AUTHOR Written by Stefan Marsiske. # COPYRIGHT Copyright © 2023 Stefan Marsiske. License GPLv3+: GNU GPL version 3 or later https://gnu.org/licenses/gpl.html. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. # SEE ALSO `sphinx(1)` pwdsphinx-2.0.4/man/sphinx-x11.md000066400000000000000000000116501507247604000165660ustar00rootroot00000000000000% sphinx-x11(1) | simple script interpreter for integrating password managers with X11 # NAME sphinx-x11 — simple script interpreter for integrating password managers with X11 # DESCRIPTION `sphinx-x11(1)` is a simple "script" language interpreter that integrates the SPHINX CLI with X11. # SPHINX-SCRIPT PARAMETERS All `sphinx-x11(1)` scripts expect a username and a hostname as the first and second parameter respectively. # VOCABULARY - `type "text..."`: Types the given text into the currently focused X11 window - `wait-for-click`: Waits until the user clicks anywhere - `user`: Types the username (usually given as the first parameter to the sphinx script) into the currently focused X11 window - `host`: Types the hostname (usually given as the second script parameter) into the currently focused X11 window - `pwd`: Gets a password via `getpwd(1)` and `sphinx(1)`, then types it into the currently focused X11 window - `otp`: Calculates the current Time-based One-Time Password (TOTP) pin code using an OTP secret stored in `sphinx(1)` using `getpwd(1)`, then types it into the currently focused X11 window. - `tab`: Types a tab character into the currently focused X11 window, often moving between form fields. - `enter`: Sends an Enter key press into the focused X11 window, usually submitting a form - `gethost`: Waits for a left mouse click on a browser window, copies the URL from the address bar, extracts the hostname, and stores it in the internal `$host` variable for use with `host` or `pwd` defined above. - `getuser`: Runs `sphinx list $host`. If multiple users are found, it presents them in a dmenu widget. If/when one user is found/selected, it is set as an internal `$user` variable which can then be used with `user` or `pwd` defined above. Any lines not consisting of these tokens are simply ignored. # OTP SUPPORT In this implementation, a TOTP value is stored with a username prefixed by `otp://` so that a regular username can co-exist with its TOTP secret in SPHINX. For example, in a common two-factor authentication (2FA) login, the first `pwd` operation might use `joe` as the username, and the TOTP value would be retrieved with `otp://joe` as the username, which allows for seamless 2FA login. # DEFAULT SCRIPTS `sphinx-x11(1)` ships with five default scripts. On Debian-based systems, these use a `sx11-` prefix instead of the `.sphinx` extension. - **pass.sphinx **: Gets a password using `sphinx(1)`, types it, and submits it. - **user-pass.sphinx **: Gets a password using `sphinx(1)`, types the username, and then submits it. - **user-pass-otp.sphinx **: Gets a password, and a TOTP pin code using `sphinx(1)`, types the username, the password, then submits the form, and finally enters the TOTP pin and submits again. - **otp.sphinx **: Gets a TOTP pin using `sphinx(1)` and types and submits it. - **getacc-user-pass.sphinx**: Waits for a click on a browser window, from which it gets the target `host`. It uses this together with `sphinx list` to lists users associated with the host. Then, it waits for another click in the username input field of a login form, gets a password using `sphinx(1)`, types the username, password, and submits. This script is convenient but carries phishing risks if a malicious site manipulates the clipboard. Use this script very carefully. At the moment, this security problem is not fixed since there is no simple way to get the current tab's URL from a browser securely via a web extension. All of these scripts wait for user interaction before retrieving passwords (and/or TOTP tokens) and entering them, navigating with `tab` and `enter`. You are welcome to contribute adapted sphinx scripts for websites that have other login semantics. # EXAMPLE The following example demonstrates the `user-pass-otp.sphinx` script: ``` #!sphinx-x11 wait-for-click user tab pwd tab enter wait-for-click otp enter ``` **Explanation:** - Line 1: Specifies `sphinx-x11(1)` as the script interpreter. - Line 3: Waits for the user to click. - Line 4: Types the username (first script parameter). - Line 5: Sends a `tab` key to move to the next form field. - Line 6: Retrieves and types the password for the specified `user` and `host` (second script parameter). - Line 7: Sends another `tab` key to move focus. - Line 8: Presses `enter` to submit the form. - Line 9: Waits for the user to click in the TOTP input field of the next form. - Line 10: Retrieves the TOTP value via `pwdsphinx/getpwd` and types it. - Line 11: Presses `enter` to submit the TOTP form. # REPORTING BUGS https://github.com/stef/pwdsphinx/issues/ # AUTHOR Written by Stefan Marsiske. # COPYRIGHT Copyright © 2023 Stefan Marsiske. License GPLv3+: GNU GPL version 3 or later https://gnu.org/licenses/gpl.html. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. # SEE ALSO `sphinx(1)`, `type-pwd(1)`, `exec-on-click(1)`, `getpwd(1)` pwdsphinx-2.0.4/man/sphinx.md000066400000000000000000000604671507247604000161710ustar00rootroot00000000000000% sphinx(1) | command-line client for the SPHINX password manager # NAME sphinx - command-line client for the SPHINX password manager # SYNOPSIS `sphinx` init echo "password" | `sphinx` create \ \ [\\\\] [\] [\] [\] echo "password" | `sphinx` get \ \ echo -e "oldpassword\nnewpassword" | `sphinx` change \ \ [\\\\] [\] [\] [\] [ echo "password" | ] `sphinx` commit \ \ [ echo "password" | ] `sphinx` undo \ \ [ echo "password" | ] `sphinx` delete \ \ `sphinx` list \ `sphinx` healthcheck `sphinx` qr [\] [\] In general, if any operation requires a master (input) password, it is expected on standard input, and any resulting account (output) password is printed to standard output. In the examples we use `echo` but it is recommended to use `getpwd(1)` or similar tools to query and pass the input password. # DESCRIPTION SPHINX – password Store that Perfectly Hides from Itself (No Xaggeration) – is an information-theoretically secure cryptographic password storage protocol with strong security guarantees. The protocol is described in the 2015 paper "Device-Enhanced Password Protocols with Optimal Online-Offline Protection" by Jarecki, Krawczyk, Shirvanian, and Saxena (https://ia.cr/2015/1099). # OPERATIONS `sphinx` is the command-line client for the SPHINX protocol. It provides access to all operations over the lifecycle of a password: `init`, `create`, `get`, `change`, `undo`, `commit`, `delete`, and `list`. All operations require a username and a site that the password belongs to, even if they're just empty strings. Additionally, it provides operations that make these features more user-friendly: listing of users associated with a host and export of the configuration using a QR code. `sphinx` not only handles passwords, but also handles Time-based One-Time Password (TOTP) Two-Factor Authentication (2FA) and [age keys](https://age-encryption.org). Additionally, if installed, `sphinx` also provides access to [OPAQUE-Store](https://github.com/stef/opaque-store), a simple tool that allows one to store secrets that need encrypted storage (like keys, phrases, or other data). ## INITIALIZING A CLIENT ``` sphinx init ``` This creates a new masterkey for the client, which is used to address records on the SPHINX server and authorize management operations on those records. You **SHOULD** back up and encrypt this masterkey. If you want to use SPHINX on a different device, you want to copy this masterkey there as well. For copying this key (and other settings) to the Android client, [androsphinx](https://github.com/dnet/androsphinx), see the `qr` operation below. This `init` operation also creates a fixed healthcheck record on the server(s), as described in the `HEALTHCHECK` section below. Additionally, if `~/.mozilla` or `~/.config/chromium` directories are found, the `init` command will automatically set up the web extensions for Firefox and Chromium-based browsers respectively. ## CREATE PASSWORD To create a new password for a site, provide your **master password** via standard input to the client, along with the required parameters. For example: ``` echo -n 'my input password' | sphinx create username example.com ulsd 0 ' !"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' ``` The parameters are: - **Master password on standard input**: Unlike traditional password managers that use a single master password for the entire database, you can use different input passwords for different username/site combinations. - `create`: Specifies the operation type. - `username`: Your username for the site. - `example.com`: The target site. - **Password constraints**: Rules for generating the password. See sections `PASSWORD RULES` and `PREDETERMINED PASSWORDS` for more info. If the command runs successfully, the resulting new high-entropy output password, generated according to the given rules, is printed to the console. ## GET PASSWORD To retrieve a stored password from the SPHINX oracle, run: ``` echo -n 'my master password' | sphinx get username example.com ``` You provide your **master password** via standard input, followed by: - `get`: Specifies the operation. - `username`: Your username. - `example.com`: The site. The corresponding password is printed to standard output. ## CHANGE PASSWORD If you need to change a password (whether required by the site or voluntarily), you can do so without changing your master password — although you may change both if desired. For example: ``` echo -en 'my master password\nnew masterpassword' | sphinx change username example.com 'ulsd' 0 ' !"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' ``` The parameters are: - On standard input, provide your **current master password**, followed by a newline, then your **new master password**. The new master password can be identical to the old one if you only want to update the site password. - `change`: Specifies the operation. - `username`: Your username. - `example.com`: The site. - **Password generation rules**: Same format as when creating the original password. Adjust these if the site now requires different constraints (see `PASSWORD RULES` and `PREDETERMINED PASSWORDS`). The newly generated password will be printed to standard output. **IMPORTANT:** This command *only generates* the new password, but it does not activate it. The `get` command will still return your old password until you run a `commit` operation to make the change effective. See the next section for details. ## COMMITTING A CHANGED PASSWORD After changing a password, the `get` operation will still return the old password. To start using the new password, you must commit the change by running: ``` echo -n 'my master password' | sphinx commit username example.com ``` Depending on your `rwd_keys` configuration (explained in the `SECURITY CONSIDERATIONS` section below), you may need to provide your input password on standard input for this operation. If the operation is successful, there will be no output. If an error occurs, an error message will be displayed and the command will exit with a non-zero status code. ## UNDOING A PASSWORD COMMIT If you need to revert to the old password after committing a new one, run: ``` echo -n 'my master password' | sphinx undo username example.com ``` Depending on your `rwd_keys` configuration, you may need to provide your master password on standard input for this operation. If successful, there will be no output. Otherwise, an error message and a non-zero exit code will indicate a problem. ## DELETING PASSWORDS To delete a password, use the following command: ``` echo -n "my master password" | sphinx delete username example.com ``` Here: - `delete` specifies the operation. - `username` is your account name. - `example.com` is the target site. If the operation succeeds, there will be no output. If it fails, you will see an error message and a non-zero exit code. Depending on your `rwd_keys` configuration, you may need to provide your master password via standard input. ## QR CODE CONFIG If you want to use your phone with the same SPHINX server, you can export your configuration to the phone using a QR code. ``` sphinx qr ``` This displays a QR code containing configuration information from your `[servers]` section and client settings such as `userlist`, `validate_password`, `delete_upgraded`, and `threshold`. This is useful for sharing your setup with trusted friends or family. To connect your own phone to the setup used with `pwdsphinx`, include your client secret in the QR code: ``` sphinx qr key ``` This QR code contains sensitive information, so keep it private and ensure no cameras can capture it while it's displayed. To display the QR code as an SVG instead of text, append the `svg` keyword to the `sphinx qr` command: ``` sphinx qr svg ``` ## HEALTHCHECK If you have run the `sphinx init` command, it has created a fixed healthcheck record. You can verify your setup by running: ``` sphinx healthcheck ``` This checks connectivity to the server without affecting rate limits. Alternatively, you can test with a `get` operation: ``` echo -n 'all ok?' | env/bin/sphinx get healthcheck "sphinx servers" ``` This should output *"everything works fine"*. The difference is that `healthcheck` only fetches rate-limiting challenges and then stops, while `get` will count against your rate limit if used too frequently. ## PASSWORD RULES When creating or changing passwords, you can specify rules limiting the size and characters allowed in the output password. The letters `u`, `l`, `s`, and `d` represent the following character classes: - `u`: Upper-case letters - `l`: Lower-case letters - `s`: Symbols - `d`: Digits The `s` shortcut includes all supported symbols. If you are limited by the server to specific symbols, you can explicitly specify them. Supported symbols (note the leading space character) are: ``` !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ ``` When using these symbols on the command line, be sure to escape quotes and possibly the backslash character. In the `create username` example above, symbols are correctly escaped for copy/paste. For examples, see the sections **CREATE PASSWORD** and **CHANGE PASSWORD**. ### DEFAULT RULES If you do not specify password rules, they will default to `ulsd` with the maximum possible length of 77 characters. This means passwords will use all four character classes, providing 507 bits of entropy. This is far more than necessary for most use cases. ### RECOMMENDED OUTPUT PASSWORD LENGTH When using the `ulsd` character classes, it is recommended to limit the output password length to a maximum of 12 characters. This is especially useful if you ever need to type the password on a TV remote or in other stressful situations. A 12-character password with full entropy using all printable ASCII characters offers almost 80 bits of entropy, making it computationally impossible to brute force with current password-cracking hardware. For comparison, a 15-character password offers nearly 99 bits of entropy. ## PREDETERMINED OUTPUT PASSWORDS If you cannot use random passwords for your account, or if you need to store a fixed "password" such as a PIN code or a shared passphrase, you can set a predetermined password (up to 77 characters). The SPHINX client will generate it for you. For example, the command below (which also works for the `change` operation) sets a fixed password: ``` echo -n 'my master password' | sphinx create username example.com "correct_battery-horse#staple" ``` In this case, you cannot specify character classes, size, or symbols. These values will be inferred from the predetermined password itself. ## Backward compatibility with v1 SPHINX servers/records If you still have SPHINX records on the server created with v1 and want to use them, you must specify this server in the client section as you did in v1. If no v2 record is found during a `get` operation, SPHINX will automatically attempt to retrieve a v1-style record. If a v1 record is found, a new v2 record will be created automatically, so there's no need to manually check for v1 records in this case. If you are not using other v1-only clients (like androsphinx), upgraded v1 records can be automatically deleted after a successful migration to v2. To enable this, set `delete_upgraded` to `true` in the `[client]` section of your SPHINX configuration. This helps keep the server database clean and makes it easy to track how many v1 records still remain. ## OUTPUT PLUGINS (TOTP & AGE) SPHINX can also "store" TOTP secrets and age secret keys. When storing such a secret, SPHINX will automatically handle it appropriately (e.g., outputting the TOTP verification code instead of the secret). To do this, prefix your username with `otp://` for TOTP support, or `age://` for age key support. For age keys, the query will return a correctly formatted private key. Currently, the following converters are supported: ### TOTP Import a TOTP secret ```sh % getpwd | sphinx create otp://username example.com ABCDEF1234567890 ``` Get a TOTP PIN: ``` % getpwd | sphinx get otp://username example.com ``` ### minisign Create a new key and store the public key at `/tmp/minisig.pub`: ```sh % getpwd \ | sphinx create minisig://user example.com >/tmp/minisig.pub ``` `Create` and `Change` SPHINX operations automatically return a public key. Sign a file `filetosign`: ```sh % getpwd \ | sphinx get minisig://user example.com \ | pipe2tmpfile minisign -S -s @@keyfile@@ -m filetosign ``` The `Get` SPHINX operation returns a private key. ### Age Generate an age key and store the public key: ```sh % getpwd \ | sphinx create age://user example.com >/tmp/age.pub ``` `Create` and `Change` SPHINX operations automatically return a public key. Decrypt a file using an age key from SPHINX: ```sh % getpwd \ | sphinx get age://user localhost \ | pipe2tmpfile age --decrypt -i @@keyfile@@ encryptedfile ``` The `Get` SPHINX operation returns a private key. ### SSH-ED25519 Create a key and save the public key: ```sh % getpwd \ | sphinx create ssh-ed25519://test asdf >pubkey ``` `Create` and `Change` SPHINX operations automatically return a public key. Sign a file: ```sh % getpwd \ | sphinx get ssh-ed25519://test asdf \ | pipe2tmpfile ssh-keygen -Y sign -n file -f @@keyfile@@ content.txt > content.txt.sig ``` The `Get` SPHINX operation returns a private key. Verify a file with a public key: ```sh % ssh-keygen -Y check-novalidate -n file -f /tmp/ssh-ed.pubkey -s /tmp/content.txt.sig file-to-store echo -n 'password' | sphinx read echo -n 'password' | sphinx replace [force] file-to-store echo -n 'password' | sphinx edit [force] echo -n 'password' | sphinx changepwd [force] echo -n 'password' | sphinx erase [force] echo -n 'password' | sphinx recovery-tokens echo -n 'password' | sphinx unlock ``` ### How does OPAQUE-Store SPHINX integration work In all OPAQUE-Store commands, a SPHINX `get` operation runs first. This generates the password used with OPAQUE, ensuring that the OPAQUE password is extremely strong and nearly impossible to brute-force without going through SPHINX. However, online brute-force attempts via SPHINX are still possible. OPAQUE can detect invalid passwords and lock records after a configured number of failed attempts. This lock does not apply to the operator of an OPAQUE server, who could bypass it. ### A WARNING: Don't let one entity control enough of your SPHINX and OPAQUE-Store servers Every OPAQUE-Store operation requires a password via standard input. This password is run through SPHINX, and the output password is then used in the OPAQUE protocol as the input password. This means that if both SPHINX and OPAQUE-Store are hosted on the same server or controlled by the same third party, they could potentially perform an offline brute-force attack against your SPHINX master password. If you use a threshold setup where different entities control the servers, you remain secure as long as no single entity controls enough servers to meet the threshold. ### OPAQUE-Store CLI Parameters #### KeyId Every OPAQUE-Store integration command needs a `keyid` parameter, which references your stored record. The client uses the `id_salt` configuration value together with the OPAQUE-Store server's name to hash the `keyid` into a record ID. If you lose or change either `id_salt` or the server name, your record IDs will change, and your data will become inaccessible. Back up your configuration file to avoid this. While `id_salt` does not need to be secret, keeping it private adds an extra layer of security. #### Forced operations In threshold setups, certain commands (`replace`, `edit`, `changepwd`, and `erase`) require that all servers participate successfully in the operation. This is to avoid situations where some servers become out of sync (corrupted) from the others. If you are certain it's safe, you can add the `force` flag to allow the operation to succeed with only the minimum number of servers specified by your `threshold` setting. ### Store an encrypted blob ```sh getpwd | sphinx store file-to-store ``` Stores the specified `file-to-store` in encrypted form on the OPAQUE-Store server, using a password derived from SPHINX. **Note**: This command also outputs a recovery token, which you should keep safe in case the record is ever locked. ### Retrieve an encrypted OPAQUE-Store blob ```sh getpwd | sphinx read ``` Retrieves the record stored at `keyid` and outputs it to standard output. ### Overwrite an encrypted OPAQUE-Store blob ```sh getpwd | sphinx replace [force] file-to-store ``` Replaces the record stored at `keyid` with an encrypted version of `file-to-store`. This command only works if a record already exists at `keyid`. By default, all servers must participate successfully. If some are unavailable, you can use `force` to proceed as long as the threshold is met — but unavailable servers will become out of sync (corrupted) from this point on. ### Edit an OPAQUE-Store blob ```sh getpwd | sphinx edit [force] ``` This operation fetches the file stored at `keyid`, opens it in your default editor (specified by the `EDITOR` environment variable), and stores the saved changes back at the same `keyid`, overwriting the original. ### Change your password on an OPAQUE-Store blob ```sh getpwd | sphinx changepwd [force] ``` This operation rotates all passwords and keys for the record at `keyid`. Even if your own password (supplied to `getpwd`) stays the same, SPHINX will generate a new key, which in turn produces a new OPAQUE password. This results in a completely new encryption key for your file, and the file is re-encrypted with it. ### Delete a stored OPAQUE-Store blob ```sh getpwd | sphinx erase [force] ``` Deletes the record stored at `keyid`. ### Get a recovery token ```sh getpwd | sphinx recovery-tokens ``` This operation generates and returns an additional recovery token, provided the record is not currently locked. ### Unlock a locked OPAQUE-Store blob ```sh getpwd | sphinx unlock ``` This operation unlocks a record that has been locked by the servers (for example, after repeated failed login attempts or if you forgot your master password). It requires a valid recovery token. Once unlocked, the record is automatically retrieved — unless the wrong password is provided again. # SPHINX CONFIGURATION The client can be configured by any of the following files (read in this order): - `/etc/sphinx/config` - `~/.sphinxrc` - `~/.config/sphinx/config` - `./sphinx.cfg` Later files override earlier ones, allowing global settings to be overridden by per-user and per-directory settings. ## Client Settings (`[client]` section) - **`datadir`** (default: `~/.sphinx`): Specifies the directory where client parameters are stored. Particularly, it contains a masterkey which is used to derive secrets. If missing, it is generated by the `init` command. You **SHOULD** back up and encrypt this master key. - **`rwd_keys`** (default: False): Toggles whether the master password is required for authentication of management operations. The oracle is oblivious to this setting, this is purely a client-side toggle. In theory, it is possible to have different settings for different "records" on the oracle. - **`validate_password`** (default: True): Stores a 5-bit check digit on the server that helps to detect most master password typos, while slightly reducing security. - **`userlist`** (default: True): When disabled, it prevents the server from correlating all usernames belonging to the same SPHINX user for the same host. If disabled, the user must remember which username is used for each host. - **`address`** / **`port`**: These variables are only used for backward compatibility with old v1 servers. If no record is found with a v2 `get` operation, SPHINX will then attempt a v1-style `get` request and see if the record is available from "old times". If a v1 record is found, a new v2-style record is created. A v1 `get` request for this particular record is not needed anymore. - **`delete_upgraded`** (default: False): Enables automatic deletion of v1 records after upgrading to v2. This setting is recommended unless using v1-only clients like androsphinx. It enables server operators to see if their users are finally completely v2, so that they can disable v1 support. - **`threshold`**: Specifies the number of servers required for SPHINX operations. If the `[servers]` section contains more than two entries, this value must be greater than 1 and less than the number of servers listed in the `[servers]` section: `1 < threshold < len(servers)`. ## Server Settings (`[servers]` section) The `[servers]` section contains one subsection per server. For example: ``` [servers] [servers.zero] host="localhost" port=10000 ltsigkey = "32byteBase64EncodedValue==" ``` - **Section format:** `[servers.]`. The `name` can be freely chosen and can be a public value. It is **important** to never change it, as long as you want to access your passwords on this server. This name value is used together with other values to create unique record IDs. If you change the `name`, the record IDs change, and you will not be able to access your old records. - **`host`** and **`port`**: should match what you set (or its admin publishes) in the `oracle(1)` server. - **`ltsigkey`**: This is the server's long-term signing key for threshold operations. This should be a base64-encoded value; however, you can also store the raw binary key in a file and use the `ltsigkey_path` option instead. This key is only needed for threshold setup, and is not required in single-server mode. See `oracle(1)` for more configuration parameters. # SECURITY CONSIDERATIONS - You **SHOULD** back up and encrypt your masterkey. You can do this using the `qr key` operation, recording other important details as well. Backing up `webauthn_data_dir` from the `[websphinx]` section is also recommended if using the web extension and WebAuthn. - **`rwd_keys`** setting: - If **False**: protects against offline master password brute-force attacks (a security guarantee of SPHINX). - If **True**: prevents denial-of-service attacks where an attacker could change/delete records for known (host, username) pairs if they have the masterkey, but removes the offline brute-force protection. This is a trade-off between account password availability and master password confidentiality. - **`validate_password`**: Stores a 5-bit check digit on the server that helps to detect most master password typos. If enabled, this setting decreases security slightly but is generally safe to enable. - **`userlist`** (default: enabled): This configuration setting allows a server operator to correlate records belonging to the same SPHINX user for the same online service. If multiple accounts on the same service are managed by the same SPHINX server, the server operator can detect when a userlist record is updated and which SPHINX record belongs to this operation. This leaks some information that can be used by an adversarial server operator to correlate records. ## Password Entry Example In this documentation, `echo` is used only for demonstration. For real usage, use `getpwd(1)` from the `contrib` directory if you are not interested in customizing or consider something like: ``` echo GETPIN | pinentry | grep '^D' | cut -c3- | sphinx create username example.com ulsd 0 ``` Using `pinentry`, you can enable double password input, and password quality checks. It's quite versatile. # REPORTING BUGS https://github.com/stef/pwdsphinx/issues/ # AUTHOR Written by Stefan Marsiske. # COPYRIGHT Copyright © 2024 Stefan Marsiske. License GPLv3+: GNU GPL version 3 or later https://gnu.org/licenses/gpl.html. 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/sphinx.html https://www.ctrlc.hu/~stef/blog/posts/oprf.html https://github.com/stef/opaque-store/ `oracle(1)`, `getpwd(1)`, `opaquestore(1)` ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������pwdsphinx-2.0.4/man/type-pwd.md���������������������������������������������������������������������0000664�0000000�0000000�00000002301�15072476040�0016410�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������% type-pwd(1) | tool which wraps sphinx(1) to get and type a password to an X11 application # NAME type-pwd - tool which wraps sphinx(1) to get and type a password to an X11 application # SYNOPSIS ``` type-pwd username hostname ``` # DESCRIPTION `type-pwd` combines `getpwd(1)`, `exec-on-click(1)`, and `sphinx(1)` to create a secure password entry workflow. It first prompts for your master password, then waits for you to click on a password field before typing the password as keystrokes. This approach ensures that your password never appears in the clipboard where malware could steal it. It also works on websites that disable copy and paste functionality in password fields. When prompted to click, make sure you click directly in the password entry field where you want the password entered. # REPORTING BUGS https://github.com/stef/pwdsphinx/issues/ # AUTHOR Written by Stefan Marsiske. # COPYRIGHT Copyright © 2023 Stefan Marsiske. License GPLv3+: GNU GPL version 3 or later https://gnu.org/licenses/gpl.html. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. # SEE ALSO `sphinx(1)`, `exec-on-click(1)`, `getpwd(1)` �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������pwdsphinx-2.0.4/man/websphinx.md��������������������������������������������������������������������0000664�0000000�0000000�00000001663�15072476040�0016660�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������% websphinx(1) | native-messaging backend for SPHINX browser webextensions # NAME websphinx - native messaging backend for SPHINX browser webextensions # SYNOPSIS `websphinx` is not meant to be run by a user. # DESCRIPTION `websphinx` serves as the native messaging backend for web extensions that expose the SPHINX password storage protocol in a browser. When you install a SPHINX browser extension, the browser automatically launches this backend to handle password operations. # REPORTING BUGS https://github.com/stef/pwdsphinx/issues/ # AUTHOR Written by Stefan Marsiske. # COPYRIGHT Copyright © 2023 Stefan Marsiske. License GPLv3+: GNU GPL version 3 or later https://gnu.org/licenses/gpl.html. 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://github.com/stef/websphinx-chrom/ https://github.com/stef/websphinx-firefox/ `sphinx(1)` �����������������������������������������������������������������������������pwdsphinx-2.0.4/pwdsphinx/��������������������������������������������������������������������������0000775�0000000�0000000�00000000000�15072476040�0015572�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������pwdsphinx-2.0.4/pwdsphinx/__init__.py���������������������������������������������������������������0000664�0000000�0000000�00000000000�15072476040�0017671�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������pwdsphinx-2.0.4/pwdsphinx/bin2pass.py���������������������������������������������������������������0000775�0000000�0000000�00000005755�15072476040�0017704�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python3 # SPDX-FileCopyrightText: 2018, 2021, Marsiske Stefan # SPDX-License-Identifier: GPL-3.0-or-later import sys, math, random #from itertools import chain #tuple(bytes([x]) for x in chain(range(32,48),range(58,65),range(91,97),range(123,127))) symbols = ' !"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' sets = { # symbols # digits 'd': tuple(bytes([x]) for x in range(48,58)), # upper-case 'u': tuple(bytes([x]) for x in range(65,91)), # lower-case 'l': tuple(bytes([x]) for x in range(97,123))} allchars = ''.join(tuple(c.decode('utf8') for x in (sets[c] for c in ('u','l','d') if c in 'uld') for c in x) + tuple(symbols)) def bin2pass(raw, chars, size): v = int.from_bytes(raw, 'big') result = '' while (size > 0 and len(result) < size) or (size == 0 and v > 0): idx = v % len(chars) v //= len(chars) result = chars[idx] + result return result def pass2bin(string, chars = allchars): classes = {'u','l','d'} sym = symbols # reduce char classes to necessary minimum to # accomodate longer passwords if chars == None: chars = [] for c in ('u','l','d'): s = set(x.decode('utf8') for x in sets[c]) if s & set(string): chars.append(''.join(sorted(s))) else: classes.remove(c) if set(string) & set(symbols): chars+=symbols else: sym = '' chars=''.join(chars) le_str = string[::-1] logbase = int(math.log(1<<512, len(chars))) r = sum(chars.find(le_str[i]) * len(chars)**i for i in range(len(le_str))) # add padding r += sum(chars.find(random.choice(chars)) * len(chars)**i for i in range(len(le_str), logbase)) return int.to_bytes(r, 64, 'big'), ''.join(classes), sym def derive(rwd, rule, size, syms=symbols): chars = tuple(c.decode('utf8') for x in (sets[c] for c in ('u','l','d') if c in rule) for c in x) + tuple(x for x in symbols if x in set(syms)) password = bin2pass(rwd,chars, size) if size>0: password=password[:size] return password def usage(): print("usage: %s [d|u|l] [] \" !\"#$%%&'()*+,-./:;<=>?@[\\]^_`{|}~\" {default: uld}" % sys.argv[0]) sys.exit(0) def main(): if len(sys.argv)>4 or 'h' in sys.argv or '--help' in sys.argv: usage() if len(sys.argv)==2: if sys.argv[1]=='s': print("all symbols:", symbols) return size = 0 raw = sys.stdin.buffer.read(64) syms = symbols rule = '' for arg in sys.argv[1:]: try: size = int(arg) continue except ValueError: pass # a symbol set specification? if set(arg) - set(symbols) == set(): syms = set(arg) elif set(arg) - set("uld") == set(): rule = arg elif len(arg) == 0: syms = '' else: usage() if size<0: print("error size must be < 0") usage() print(derive(raw,rule,size,syms)) if __name__ == '__main__': main() �������������������pwdsphinx-2.0.4/pwdsphinx/config.py�����������������������������������������������������������������0000775�0000000�0000000�00000001541�15072476040�0017415�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python3 # SPDX-FileCopyrightText: 2023, Marsiske Stefan # SPDX-License-Identifier: GPL-3.0-or-later import os, tomllib from pwdsphinx.utils import split_by_n def getcfg(name): paths=[ # read global cfg f'/etc/{name}/config', # update with per-user configs os.path.expanduser(f"~/.{name}rc"), # over-ride with local directory config os.path.expanduser(f"~/.config/{name}/config"), os.path.expanduser(f"{name}.cfg") ] config = dict() for path in paths: try: with open(path, "rb") as f: data = tomllib.load(f) except FileNotFoundError: continue except tomllib.TOMLDecodeError as ex: print(f"error in {path} at {ex}") continue config.update(data) return config if __name__ == '__main__': import sys getcfg('sphinx').write(sys.stdout) ���������������������������������������������������������������������������������������������������������������������������������������������������������������pwdsphinx-2.0.4/pwdsphinx/consts.py�����������������������������������������������������������������0000775�0000000�0000000�00000000777�15072476040�0017473�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python3 CREATE =b'\x00' # sphinx READ =b'\x33' # blob UNDO =b'\x55' # change sphinx GET =b'\x66' # sphinx V1GET =b'\x69' # v1 sphinx COMMIT =b'\x99' # change sphinx CHANGE_DKG =b'\xa0' # sphinx/dkg CHANGE =b'\xaa' # sphinx CREATE_DKG =b'\xf0' # sphinx/dkg V1DELETE =b'\xf9' # v1 sphinx+blobs DELETE =b'\xff' # sphinx+blobs CHALLENGE_CREATE = b'\x5a' CHALLENGE_VERIFY = b'\xa5' VERSION = b'\x01' V1RULE_SIZE = 79 RULE_SIZE = V1RULE_SIZE+32 �pwdsphinx-2.0.4/pwdsphinx/converter.py��������������������������������������������������������������0000775�0000000�0000000�00000003160�15072476040�0020156�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python from pwdsphinx import bin2pass import traceback, os, sys from importlib.machinery import SourceFileLoader from pathlib import Path converters = {} def load_converters(): global converters p = Path(__file__).parent.absolute() for converter_fname in os.listdir(f'{p}/converters/'): if converter_fname.startswith('_') or not converter_fname.endswith('.py'): continue try: name = converter_fname[:-3] import_path = 'converters.'+name if import_path in sys.modules: del sys.modules[import_path] s = SourceFileLoader(import_path, f'{p}/converters/' + converter_fname).load_module() except: print("failed to load converter", converter_fname) traceback.print_exc() continue for schema, converter in s.schema.items(): if schema in converters: raise ValueError(f"{schema} is a already in loaded converters") converters[schema]=converter load_converters() def convert(rwd, user, host, op, *opts): if '://' not in user: return bin2pass.derive(rwd, *opts) elif user.startswith('otp://'): # need to recover the predefined base32 otp key rwd = bin2pass.derive(rwd, *opts) schema, name = user.split("://",1) return converters[schema](rwd, name, host, op, *opts) def convertedBy(user): for k in converters.keys(): if user.startswith(f"{k}://"): return k return None if __name__ == "__main__": convert(b'\xaa' * 32, 'asdf', 'uld', 0, '') import sys args = [int(x) if x.isdigit() else x for x in sys.argv[1:]] rwd = sys.stdin.buffer.read(32) print(convert(rwd, *args)) ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������pwdsphinx-2.0.4/pwdsphinx/converters/���������������������������������������������������������������0000775�0000000�0000000�00000000000�15072476040�0017764�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������pwdsphinx-2.0.4/pwdsphinx/converters/__init__.py����������������������������������������������������0000664�0000000�0000000�00000000001�15072476040�0022064�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������ �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������pwdsphinx-2.0.4/pwdsphinx/converters/minisig.py�����������������������������������������������������0000775�0000000�0000000�00000002372�15072476040�0022004�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python3 import sys, base64, pysodium, binascii from pwdsphinx.consts import * # usage # getpwd | env/bin/sphinx create minisig://test asdf | pipe2tmpfile minisign -R -s @@keyfile@@ -p /tmp/minisig.pub # getpwd | env/bin/sphinx get minisig://test asdf | pipe2tmpfile minisign -S -s @@keyfile@@ -m filetosign """format is untrusted comment: sphinx generated minisign key\n base64( 4564 0000 4232 <\x00 * 48> <\x00 * 32> ) use crypto_sign_ed25519_sk_to_pk(unsigned char *pk, const unsigned char *sk); to derive pubkey from secret key """ def privkey(sk, kid): raw = (binascii.unhexlify("456400004232") + b'\x00' * 48 + kid + sk + b'\x00' * 32) return f"untrusted comment: minisign secret key\n{base64.b64encode(raw).decode('utf8')}" def pubkey(pk, kid): raw = (b'Ed' + kid + pk) return f"untrusted comment: minisign public key\n{base64.b64encode(raw).decode('utf8')}" def convert(rwd, user, host, op, *opts): seed=rwd[:32] kid=rwd[32:40] pk,sk=pysodium.crypto_sign_seed_keypair(seed) if op in {CREATE, CHANGE}: return pubkey(pk, kid) return privkey(sk, kid) schema = {'minisig': convert} ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������pwdsphinx-2.0.4/pwdsphinx/converters/raw.py���������������������������������������������������������0000775�0000000�0000000�00000000600�15072476040�0021126�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python3 def convert(rwd, user, host, op, *opts): size = opts[1] # rwd[:] does not copy the underlying data, and thus # a clearmem() not only wipes the original, but also the copy... return rwd[:1] + rwd[1:size] schema = {"raw": convert} def main(): for rwd in sys.stdin: print(convert(rwd.strip())) if __name__ == '__main__': main() ��������������������������������������������������������������������������������������������������������������������������������pwdsphinx-2.0.4/pwdsphinx/converters/sphage.py������������������������������������������������������0000775�0000000�0000000�00000013205�15072476040�0021611�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python3 # SPDX-FileCopyrightText: 2018-2021, Marsiske Stefan # SPDX-License-Identifier: GPL-3.0-or-later # This file contains a copy of the reference implementation for # Bech32/Bech32m, which has this (c) notice: # # Copyright (c) 2017, 2020 Pieter Wuille # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import sys, base64, pysodium from enum import Enum from pwdsphinx.consts import * class Encoding(Enum): """Enumeration type to list the various supported encodings.""" BECH32 = 1 BECH32M = 2 CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l" BECH32M_CONST = 0x2bc830a3 def bech32_polymod(values): """Internal function that computes the Bech32 checksum.""" generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3] chk = 1 for value in values: top = chk >> 25 chk = (chk & 0x1ffffff) << 5 ^ value for i in range(5): chk ^= generator[i] if ((top >> i) & 1) else 0 return chk def bech32_hrp_expand(hrp): """Expand the HRP into values for checksum computation.""" return [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 31 for x in hrp] def bech32_verify_checksum(hrp, data): """Verify a checksum given HRP and converted data characters.""" const = bech32_polymod(bech32_hrp_expand(hrp) + data) if const == 1: return Encoding.BECH32 if const == BECH32M_CONST: return Encoding.BECH32M return None def bech32_create_checksum(hrp, data, spec): """Compute the checksum values given HRP and data.""" values = bech32_hrp_expand(hrp) + data const = BECH32M_CONST if spec == Encoding.BECH32M else 1 polymod = bech32_polymod(values + [0, 0, 0, 0, 0, 0]) ^ const return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)] def bech32_encode(hrp, data, spec=2): """Compute a Bech32 string given HRP and data values.""" combined = data + bech32_create_checksum(hrp, data, spec) return hrp + '1' + ''.join([CHARSET[d] for d in combined]) def bech32_decode(bech): """Validate a Bech32/Bech32m string, and determine HRP and data.""" if ((any(ord(x) < 33 or ord(x) > 126 for x in bech)) or (bech.lower() != bech and bech.upper() != bech)): return (None, None, None) bech = bech.lower() pos = bech.rfind('1') if pos < 1 or pos + 7 > len(bech) or len(bech) > 90: return (None, None, None) if not all(x in CHARSET for x in bech[pos+1:]): return (None, None, None) hrp = bech[:pos] data = [CHARSET.find(x) for x in bech[pos+1:]] spec = bech32_verify_checksum(hrp, data) if spec is None: return (None, None, None) return (hrp, data[:-6], spec) def convertbits(data, frombits, tobits, pad=True): """General power-of-2 base conversion.""" acc = 0 bits = 0 ret = [] maxv = (1 << tobits) - 1 max_acc = (1 << (frombits + tobits - 1)) - 1 for value in data: if value < 0 or (value >> frombits): return None acc = ((acc << frombits) | value) & max_acc bits += frombits while bits >= tobits: bits -= tobits ret.append((acc >> bits) & maxv) if pad: if bits: ret.append((acc << (tobits - bits)) & maxv) elif bits >= frombits or ((acc << (tobits - bits)) & maxv): return None return ret def decode(hrp, addr): hrpgot, data, spec = bech32_decode(addr) if hrpgot != hrp: return None decoded = convertbits(data, 5, 8, False) if decoded is None or len(decoded) < 2 or len(decoded) > 40: return None return bytes(decoded) def encode(hrp, data): ret = bech32_encode(hrp, convertbits(data, 8, 5)) if decode(hrp, ret) == None: return None return ret def convert(rwd, user, host, op, *opts): if op in {CREATE, CHANGE}: pk = pysodium.crypto_scalarmult_base(rwd[:32]) return encode("age", pk) return encode('age-secret-key-', rwd[:32]).upper() schema = {'age': convert} def usage(help=False): print("usage: sphage.py [] <[32 bytes of cryptographic entropy] >key") if help: sys.exit(0) sys.exit(1) def main(): if len(sys.argv)!=2: usage() op = sys.argv[1] if op in ('help', '-h', '--help'): usage(True) if op not in ('pubkey', 'privkey'): usage() rwd = sys.stdin.buffer.readline().rstrip(b'\n') if op == "pubkey": if rwd.startswith(b'AGE-SECRET-KEY-'): rwd = decode('age-secret-key-', rwd.decode('utf8')) pk = pysodium.crypto_scalarmult_base(rwd) ret = encode("age", pk) elif op == "privkey": ret = encode('age-secret-key-', rwd).upper() print(ret) if __name__ == '__main__': main() �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������pwdsphinx-2.0.4/pwdsphinx/converters/ssh-ed25519.py�������������������������������������������������0000775�0000000�0000000�00000010321�15072476040�0022127�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python3 import sys, base64, pysodium, binascii, struct from pwdsphinx.consts import * # usage # create key and save pubkey # getpwd | env/bin/sphinx create ssh-ed25519://test asdf | pipe2tmpfile ssh-keygen -e -f @@keyfile@@ >pubkey # sign file # getpwd | env/bin/sphinx get ssh-ed25519://test asdf | pipe2tmpfile ssh-keygen -Y sign -n file -f @@keyfile@@ content.txt > content.txt.sig # verify file with pubkey # ssh-keygen -Y check-novalidate -n file -f /tmp/ssh-ed.pubkey -s /tmp/content.txt.sig I", len(comment)) + comment secrethalf = ( binascii.unhexlify("a2224bbaa2224bba" # iv/salt? (Not sure about these 8 bytes) # Here's a repeat of the public key (part of the private key pair) "0000000b" # int length = 11 "7373682d65643235353139" # string key type = ssh-ed25519 "00000020") + # int length = 32 # public key payload 32 bytes # probably encoding a point on the ed25519 curve pk + binascii.unhexlify("00000040") + # int length = 64 # 32 bytes private key payload 1 sk + # really sk[32] + pk[32] comment) # int length + comment as string # padding 3 bytes incrementing integers, pads to blocksize 8, starts with "remaining payload" padding = bytes(i+1 for i in range(-len(secrethalf)%8)) secrethalf = secrethalf + padding assert len(secrethalf) % 8 == 0 raw = (binascii.unhexlify("6f70656e7373682d6b65792d763100" # ASCII magic "openssh-key-v1" plus null byte "00000004" # int length = 4 "6e6f6e65" #string cipher = none "00000004" # int length = 4 "6e6f6e65" # string kdfname = none "00000000" # int length = 0 # zero-length kdfoptions placeholder here "00000001" # int number of public keys = 1 "00000033" # int length first public key = 51 (4 + 11 + 4 + 32) "0000000b" # int length = 11 "7373682d65643235353139" # string key type = ssh-ed25519 "00000020") + # int length = 32 # public key payload 32 bytes # probably encoding a point on the ed25519 curve pk + struct.pack(">I", len(secrethalf)) + # int length = 144 size of remaining payload # 8 + 4 + 11 + 4 + 32 + 4 + 64 + 4 + {10 + 3} secrethalf) return ("-----BEGIN OPENSSH PRIVATE KEY-----\n" + '\n'.join(''.join(l) for l in split_by_n(base64.b64encode(raw).decode('utf8'), 70)) + "\n-----END OPENSSH PRIVATE KEY-----") def pubkey(rwd, user, host): seed=rwd[:32] pk,sk=pysodium.crypto_sign_seed_keypair(seed) raw = (binascii.unhexlify("0000000b" # int length = 11 "7373682d65643235353139" # string key type = ssh-ed25519 "00000020") + # int length = 32 pk) return f"ssh-ed25519 {base64.b64encode(raw).decode('utf8')} {user}@{host}" def convert(rwd, user, host, op, *opts): if op in {CREATE, CHANGE}: return pubkey(rwd, user, host) return privkey(rwd,user, host) schema = {'ssh-ed25519': convert} ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������pwdsphinx-2.0.4/pwdsphinx/converters/totp.py��������������������������������������������������������0000775�0000000�0000000�00000001366�15072476040�0021335�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python from base64 import b32decode import hmac from struct import pack, unpack import sys from time import time def totp(key, user, host, *opts, time_step=30, digits=6, digest='sha1'): if isinstance(key, bytes): key=key.decode('utf8') key = b32decode(key.upper() + '=' * ((8 - len(key)) % 8)) ts = pack('>Q', int(time() / time_step)) mac = hmac.new(key, ts, digest).digest() offset = mac[-1] & 0x0f binary = unpack('>L', mac[offset:offset+4])[0] & 0x7fffffff return str(binary)[-digits:].zfill(digits) schema = {"otp": totp} def main(): args = [int(x) if x.isdigit() else x for x in sys.argv[1:]] for key in sys.stdin: print(totp(key.strip(), [], *args)) if __name__ == '__main__': main() ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������pwdsphinx-2.0.4/pwdsphinx/ext.py��������������������������������������������������������������������0000664�0000000�0000000�00000002556�15072476040�0016754�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������from os import mkdir, getenv from os.path import exists, split from pathlib import Path from sys import executable EXT_NM_TPL = '''{{ "name": "websphinx", "description": "Host for communicating with PITCHFORKed Sphinx", "path": "{cmd}", "type": "stdio", ''' CHR_NM_TPL = EXT_NM_TPL + ''' "allowed_origins": [ "chrome-extension://ojbhlhidchjkmjmpeonendekpoacahni/" ] }} ''' FF_NM_TPL = EXT_NM_TPL + ''' "allowed_extensions": [ "sphinx@ctrlc.hu" ] }} ''' def get_executable(): venv = getenv('VIRTUAL_ENV') if venv: return f'{venv}/bin/websphinx' d = split(Path(__file__).absolute())[0] return d + '/websphinx.py' def init_browser_ext(): cmd = get_executable() print(cmd) # init ff if exists(f'{Path.home()}/.mozilla/'): nm_dir = f'{Path.home()}/.mozilla/native-messaging-hosts/' if not exists(nm_dir): mkdir(nm_dir) with open(nm_dir+'websphinx.json', 'w') as outfile: ff_nm = FF_NM_TPL.format(cmd=cmd) outfile.write(ff_nm) # init chrome if exists(f'{Path.home()}/.config/chromium'): nm_dir = f'{Path.home()}/.config/chromium/NativeMessagingHosts/' if not exists(nm_dir): mkdir(nm_dir) with open(nm_dir+'websphinx.json', 'w') as outfile: chr_nm = CHR_NM_TPL.format(cmd=cmd) outfile.write(chr_nm) ��������������������������������������������������������������������������������������������������������������������������������������������������pwdsphinx-2.0.4/pwdsphinx/oracle.py�����������������������������������������������������������������0000775�0000000�0000000�00000056217�15072476040�0017427�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python3 # SPDX-FileCopyrightText: 2018-2024, Marsiske Stefan # SPDX-License-Identifier: GPL-3.0-or-later import socket, sys, ssl, os, datetime, binascii, shutil, os.path, traceback, struct, select from os import access, R_OK from os.path import isfile, getsize import pysodium import equihash import pyoprf from pwdsphinx.config import getcfg from pwdsphinx.consts import * cfg = getcfg('sphinx') # todo genkey ltsig integrate into oracle verbose = cfg['server'].get('verbose', False) address = cfg['server'].get('address', '127.0.0.1') port = int(cfg['server'].get('port',2355)) timeout = int(cfg['server'].get('timeout',"3")) max_kids = int(cfg['server'].get('max_kids',5)) datadir = os.path.expanduser(cfg['server'].get('datadir',"/var/lib/sphinx")) ts_epsilon = 1200 # todo make configurable try: ssl_key = os.path.expanduser(cfg['server']['ssl_key']) except KeyError: print("Error: ssl_key missing! must specify it in the config file") try: ssl_cert = os.path.expanduser(cfg['server']['ssl_cert']) except KeyError: print("Error: ssl_cert missing! must specify it in the config file") try: ltsigkey_path = os.path.expanduser(cfg['server']['ltsigkey']) except KeyError: print("Error: ltsigkey missing! must specify it in the config file") rl_decay = int(cfg['server'].get('rl_decay',1800)) rl_threshold = int(cfg['server'].get('rl_threshold',1)) rl_gracetime = int(cfg['server'].get('rl_gracetime',10)) if(verbose): print(f"pid: {os.getpid()}") print(f"address: {address}:{port}") print(f"timeout: {timeout}s") print(f"max kids: {max_kids}") print(f"datadir: {datadir}") print(f"ssl_key: {ssl_key}") if 'ssl_cert' in globals(): print(f"ssl_cert: {ssl_cert}") print(f"rl decay: {rl_decay}s") print(f"rl threshold: {rl_threshold}") print(f"rl gracetime: {rl_gracetime}s") Difficulties = [ # timeouts are based on benchmarking a raspberry pi 1b { 'n': 60, 'k': 4, 'timeout': 1 }, # 320KiB, ~0.02 { 'n': 65, 'k': 4, 'timeout': 2 }, # 640KiB, ~0.04 { 'n': 70, 'k': 4, 'timeout': 4 }, # 1MiB, ~0.08 { 'n': 75, 'k': 4, 'timeout': 9 }, # 2MiB, ~0.2 { 'n': 80, 'k': 4, 'timeout': 16 }, # 5MiB, ~0.5 { 'n': 85, 'k': 4, 'timeout': 32 }, # 10MiB, ~0.9 { 'n': 90, 'k': 4, 'timeout': 80 }, # 20MiB, ~2.4 { 'n': 95, 'k': 4, 'timeout': 160 }, # 40MiB, ~4.6 # timeouts below are interpolated from above { 'n': 100, 'k': 4, 'timeout': 320 }, # 80MiB, ~7.8 { 'n': 105, 'k': 4, 'timeout': 640 }, # 160MiB, ~25 { 'n': 110, 'k': 4, 'timeout': 1280 }, # 320MiB, ~57 { 'n': 115, 'k': 4, 'timeout': 2560 }, # 640MiB, ~70 { 'n': 120, 'k': 4, 'timeout': 5120 }, # 1GiB, ~109 ] RL_Timeouts = {(e['n'],e['k']): e['timeout'] for e in Difficulties} normal = "\033[38;5;%sm" reset = "\033[0m" def fail(s): if verbose: traceback.print_stack() print('fail') s.send(b'\x00\x04fail') # plaintext :/ todo use ltsigkey? s.shutdown(socket.SHUT_RDWR) s.close() os._exit(0) def pop(obj, cnt, astype=None): if astype is not None: return astype(obj[:cnt]), obj[cnt:] return obj[:cnt], obj[cnt:] def verify_blob(msg, pk): sig = msg[-64:] msg = msg[:-64] pysodium.crypto_sign_verify_detached(sig, msg, pk) return msg def save_blob(path,fname,blob): path = os.path.join(datadir, path, fname) with open(path,'wb') as fd: os.fchmod(fd.fileno(),0o600) fd.write(blob) def read_pkt(s,size): res = [] read = 0 while read 0: msg = read_pkt(s, in_size) else: msg = b'' cur_step = pyoprf.tpdkg_peerstate_step(peer) try: out = pyoprf.tpdkg_peer_next(peer, msg) except Exception as e: print(f"{e} | peer step {cur_step}") fail(s) if(len(out)>0): s.send(out) share = pyoprf.tpdkg_peerstate_share(peer) return share # msg format: 0xf0|msg0[pyoprf.tpdkg_msg0_SIZE]|id[32]|alpha[32]] def create_dkg(s, msg): if len(msg)!=65+pyoprf.tpdkg_msg0_SIZE: print(f"{len(msg)} != {pyoprf.tpdkg_msg0_SIZE}",file=sys.stderr) fail(s) if verbose: print('Create DKG Data received:',msg.hex()) op, msg = pop(msg,1) id, msg = pop(msg,32) alpha, msg0 = pop(msg,32) if len(msg0) != pyoprf.tpdkg_msg0_SIZE: print(f"msg0 is invalid size {len(msg0)}") fail(s) aux = b'%s%s' % (op, alpha) # for the transcript # check if id is unique id = binascii.hexlify(id).decode() tdir = os.path.join(datadir,id) if(os.path.exists(tdir)): fail(s) xi = dkg(s, msg0, aux) #k=pysodium.randombytes(32) try: beta = pyoprf.evaluate(xi[1:], alpha) except: fail(s) msg = bytes([xi[0]])+beta s.send(msg) # wait for auth signing pubkey and rules msg = s.recv(32+RULE_SIZE+64) # pubkey, rule, signature if len(msg)!=32+RULE_SIZE+64: fail(s) # verify auth sig on packet pk = msg[:32] try: msg = verify_blob(msg,pk) except ValueError: fail(s) rules = msg[32:] # 3rd phase update_blob(s) # add user to host record if not os.path.exists(datadir): os.mkdir(datadir,0o700) os.mkdir(tdir,0o700) save_blob(id,'key',xi) save_blob(id,'pub',pk) save_blob(id,'rules',rules) s.send(b'ok') def load_blob(path,fname,size=None): f = os.path.join(datadir,path,fname) if not os.path.exists(f): if verbose: print('%s does not exist' % f) return with open(f,'rb') as fd: v = fd.read() if size and len(v) != size: if verbose: print("wrong size for %s" % f) raise ValueError('corrupted blob: %s is not %s bytes' % (f, size)) return v # msg format: 0x66|id[32]|alpha[32] def get(conn, msg): _, msg = pop(msg,1) id, msg = pop(msg,32) alpha, msg = pop(msg,32) if msg!=b'': if verbose: print('invalid get msg, trailing content %r' % msg) fail(conn) id = binascii.hexlify(id).decode() k = load_blob(id,'key',33) if k is None: # maybe execute protocol with static but random value to not leak which host ids exist? fail(conn) rules = load_blob(id,'rules', RULE_SIZE) if rules is None: fail(conn) try: beta = pyoprf.evaluate(k[1:], alpha) except: fail(conn) conn.send(k[:1]+beta+rules) # msg format: 0x69|id[32]|alpha[32] def v1get(conn, msg): _, msg = pop(msg,1) id, msg = pop(msg,32) alpha, msg = pop(msg,32) if msg!=b'': if verbose: print('invalid get msg, trailing content %r' % msg) fail(conn) id = binascii.hexlify(id).decode() k = load_blob(id,'key',32) if k is None: # maybe execute protocol with static but random value to not leak which host ids exist? fail(conn) rules = load_blob(id,'rules', V1RULE_SIZE) if rules is None: fail(conn) try: if not pysodium.crypto_core_ristretto255_is_valid_point(alpha): raise ValueError("invalid alpha") beta = pysodium.crypto_scalarmult_ristretto255(k, alpha) except: fail(conn) conn.send(beta+rules) def auth(s,op,id,alpha, isv1=False): pk = load_blob(id,'pub',32) if pk is None: print('no pubkey found in %s' % id) fail(s) nonce=pysodium.randombytes(32) k = load_blob(id,'key',33 if not isv1 else 32) if k is not None: try: if not isv1: beta = bytes([k[0]])+pyoprf.evaluate(k[1:], alpha) else: if not pysodium.crypto_core_ristretto255_is_valid_point(alpha): raise ValueError("invalid alpha") beta = pysodium.crypto_scalarmult_ristretto255(k, alpha) except: fail(s) else: beta = b'' s.send(b''.join([beta,nonce])) sig = s.recv(64) try: pysodium.crypto_sign_verify_detached(sig, op+nonce, pk) except: print('bad sig') fail(s) else: s.send(b'\x00\x04auth') # plaintext :/ todo use ltsigkey? def change(conn, msg): op, tmp = pop(msg,1) id, tmp = pop(tmp,32) alpha,tmp = pop(tmp,32) if tmp!=b'': if verbose: print('invalid get msg, trailing content %r' % tmp) fail(conn) id = binascii.hexlify(id).decode() auth(conn, msg, id, alpha) tdir = os.path.join(datadir,id) if not os.path.exists(tdir): if verbose: print("%s doesn't exist" % tdir) fail(conn) alpha = conn.recv(32) if(len(alpha)!=32): fail(conn) k=b'\x01'+pysodium.randombytes(32) try: beta = k[:1]+pyoprf.evaluate(k[1:], alpha) except: fail(conn) conn.send(beta) blob = conn.recv(32+RULE_SIZE+64) if len(blob)!=32+RULE_SIZE+64: fail(conn) pk = blob[:32] try: rules = verify_blob(blob,pk)[32:] except ValueError: fail(conn) save_blob(id,'new',k) save_blob(id,"rules.new", rules) save_blob(id,"pub.new", pk) conn.send(b'ok') def change_dkg(s, msg): op, tmp = pop(msg,1) id, tmp = pop(tmp,32) alpha,tmp = pop(tmp,32) if tmp!=b'': if verbose: print('invalid get msg, trailing content %r' % tmp) fail(s) id = binascii.hexlify(id).decode() auth(s, msg, id, alpha) aux = b'%s%s' % (op, alpha) tdir = os.path.join(datadir,id) if not os.path.exists(tdir): if verbose: print("%s doesn't exist" % tdir) fail(s) msg = s.recv(pyoprf.tpdkg_msg0_SIZE+32) alpha,msg0 = pop(msg,32) if len(msg0) != pyoprf.tpdkg_msg0_SIZE: print(f"msg0 is invalid size {len(msg0)}") fail(s) xi = dkg(s, msg0, aux) try: beta = pyoprf.evaluate(xi[1:], alpha) except: fail(s) s.send(bytes([xi[0]])+beta) blob = s.recv(32+RULE_SIZE+64) if len(blob)!=32+RULE_SIZE+64: fail(s) pk = blob[:32] try: rules = verify_blob(blob,pk)[32:] except ValueError: fail(s) save_blob(id,'new',xi) save_blob(id,"rules.new", rules) save_blob(id,"pub.new", pk) s.send(b'ok') def delete(conn, msg, isv1=False): op, tmp = pop(msg,1) id, tmp = pop(tmp,32) alpha,tmp = pop(tmp,32) if tmp!=b'': if verbose: print('invalid get msg, trailing content %r' % tmp) fail(conn) id = binascii.hexlify(id).decode() auth(conn, msg, id, alpha, isv1) tdir = os.path.join(datadir,id) if not os.path.exists(tdir): if verbose: print("%s doesn't exist" % tdir) fail(conn) update_blob(conn) shutil.rmtree(tdir) conn.send(b'ok') def commit_undo(conn, msg, new, old): op, tmp = pop(msg,1) id, tmp = pop(tmp,32) alpha,tmp = pop(tmp,32) if tmp!=b'': if verbose: print('invalid get msg, trailing content %r' % tmp) fail(conn) id = binascii.hexlify(id).decode() auth(conn, msg, id, alpha) tdir = os.path.join(datadir,id) if not os.path.exists(tdir): if verbose: print("%s doesn't exist" % tdir) fail(conn) if (new_rules:=load_blob(id,'rules.%s' % new, RULE_SIZE)) is None: fail(conn) if (cur_rules:=load_blob(id,'rules', RULE_SIZE)) is None: fail(conn) if (new_pub:=load_blob(id,'pub.%s' % new, 32)) is None: fail(conn) if (cur_pub:=load_blob(id,'pub', 32) )is None: fail(conn) if (new_key:= load_blob(id, new, 33)) is None: fail(conn) if (cur_key:= load_blob(id, 'key', 33)) is None: fail(conn) save_blob(id,old,cur_key) #clearmem(cur_key) save_blob(id,"rules.%s" % old, cur_rules) save_blob(id,"pub.%s" % old, cur_pub) save_blob(id,"key",new_key) #clearmem(new_key) save_blob(id,"rules", new_rules) save_blob(id,"pub", new_pub) os.unlink(os.path.join(tdir,new)) os.unlink(os.path.join(tdir,"pub.%s" % new)) os.unlink(os.path.join(tdir,"rules.%s" % new)) conn.send(b'ok') def read(conn, msg): op, tmp = pop(msg,1) id, tmp = pop(tmp,32) alpha,tmp = pop(tmp,32) id = binascii.hexlify(id).decode() auth(conn, msg, id, alpha) blob = load_blob(id,'blob') if blob is None: blob = b'' conn.send(blob) def handler(conn, data): if verbose: print('Data received:',data.hex()) if data[0:1] == GET: get(conn, data) elif data[0:1] == V1GET: v1get(conn, data) elif data[0:1] == CHANGE: change(conn, data) elif data[0:1] == CHANGE_DKG: change_dkg(conn, data) elif data[0:1] == DELETE: delete(conn, data) elif data[0:1] == V1DELETE: delete(conn, data, True) elif data[0:1] == COMMIT: commit_undo(conn, data, 'new', 'old') elif data[0:1] == UNDO: commit_undo(conn, data, 'old', 'new') elif data[0:1] == READ: read(conn, data) elif verbose: print("unknown op: 0x%02x" % data[0]) conn.close() os._exit(0) def create_challenge(conn): req = conn.read(65) if req[0:1] == READ: if len(req)!=33: fail(conn) elif len(req)!=65: fail(conn) now = datetime.datetime.now().timestamp() id = binascii.hexlify(req[1:33]).decode() diff = load_blob(id,'difficulty',9) # ts: u32, level: u8, count:u32 if not diff: # no diff yet, use easiest hardness n = Difficulties[0]['n'] k = Difficulties[0]['k'] level = 0 count = 0 else: level = struct.unpack("B", diff[0:1])[0] count = struct.unpack("I", diff[1:5])[0] ts = struct.unpack("I", diff[5:])[0] if level >= len(Difficulties): print("invalid level in rl_ctx:", level) level = len(Difficulties) - 1 count = 0 elif ((now - rl_decay) > ts and level > 0): # cooldown, decay difficulty periods = int((now - ts) // rl_decay) if level >= periods: level -= periods else: level = 0 count = 0 else: # increase hardness if count >= rl_threshold and (level < len(Difficulties) - 1): count = 0 level+=1 else: count+=1 n = Difficulties[level]['n'] k = Difficulties[level]['k'] if (level == len(Difficulties) - 1) and count>rl_threshold*2: print(f"{normal}alert{normal}: someones trying (%d) really hard at: %s" % (196, 253, count, id)) rl_ctx = b''.join([ struct.pack("B", level), # level struct.pack("I", count), # count struct.pack('I', int(now)) # ts ]) if(verbose): print("rl difficulty", {"level": level, "count": count, "ts": int(now)}) try: save_blob(id, 'difficulty', rl_ctx) except FileNotFoundError: if diff: raise challenge = b''.join([bytes([n, k]), struct.pack('Q', int(now))]) key = load_blob('', "key", 32) if not key: key=pysodium.randombytes(32) save_blob('','key',key) state = pysodium.crypto_generichash_init(32, key) pysodium.crypto_generichash_update(state,req) pysodium.crypto_generichash_update(state,challenge) sig = pysodium.crypto_generichash_final(state,32) resp = b''.join([challenge, sig]) conn.send(resp) def verify_challenge(conn): # read challenge challenge = conn.read(1+1+8+32) # n,k,ts,sig if(len(challenge)!=42): fail(conn) n, tmp = pop(challenge,1) n = n[0] k, tmp = pop(tmp,1) k = k[0] ts, tmp = pop(tmp,8) ts = struct.unpack("Q", ts)[0] sig, tmp = pop(tmp,32) # read request req_type = conn.read(1) if req_type[0:1] == READ: payload = conn.read(32) if len(payload)!=32: fail(conn) else: payload = conn.read(64) if len(payload)!=64: fail(conn) req = req_type + payload # read mac key key = load_blob('', "key", 32) if not key: fail(conn) tosign = challenge[:10] state = pysodium.crypto_generichash_init(32, key) pysodium.crypto_generichash_update(state,req) pysodium.crypto_generichash_update(state,tosign) mac = pysodium.crypto_generichash_final(state,32) # poor mans const time comparison if(sum(m^i for (m, i) in zip(mac,sig))): fail(conn) now = datetime.datetime.now().timestamp() if now - (RL_Timeouts[(n,k)]+rl_gracetime) > ts: # solution is too old fail(conn) solsize = equihash.solsize(n,k) solution = conn.read(solsize) if len(solution)!= solsize: fail(conn) seed = b''.join([challenge,req]) if not equihash.verify(n,k, seed, solution): fail(conn) handler(conn, req) def ratelimit(conn): op = conn.recv(1) if op == CREATE: data = CREATE+conn.recv(64) create(conn, data) elif op == CREATE_DKG: data = CREATE_DKG+conn.recv(65+pyoprf.tpdkg_msg0_SIZE) create_dkg(conn, data) elif op == CHALLENGE_CREATE: create_challenge(conn) elif op == CHALLENGE_VERIFY: verify_challenge(conn) def main(debug=False): if debug == True: import ctypes libc = ctypes.cdll.LoadLibrary('libc.so.6') fdopen = libc.fdopen log_file = ctypes.c_void_p.in_dll(pyoprf.liboprf,'liboprf_log_file') fdopen.restype = ctypes.c_void_p log_file.value = fdopen(2, 'w') ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) ctx.load_cert_chain(certfile=ssl_cert, keyfile=ssl_key) socket.setdefaulttimeout(timeout) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) try: s.bind((address, port)) except socket.error as msg: print(f'Bind to {address}:{port} failed. Error {msg}') sys.exit() #Start listening on socket s.listen() kids = [] try: # main loop while 1: #wait to accept a connection - blocking call r,w,x = select.select([s], [], [], 0.5) if len(r) == 1: conn, addr = s.accept() else: try: pid, status = os.waitpid(-1, os.WNOHANG) if pid != 0: print("remove pid", pid) kids.remove(pid) continue except ChildProcessError: continue if verbose: print('{} Connection from {}:{}'.format(datetime.datetime.now(), addr[0], addr[1])) while(len(kids)>max_kids): pid, status = os.waitpid(0,0) kids.remove(pid) pid=os.fork() if pid==0: conn = ctx.wrap_socket(conn, server_side=True) ssl.RAND_add(os.urandom(16),0.0) try: ratelimit(conn) except: print("fail") raise finally: try: conn.shutdown(socket.SHUT_RDWR) except OSError: pass conn.close() sys.exit(0) else: kids.append(pid) try: pid, status = os.waitpid(-1,os.WNOHANG) if pid!=0: kids.remove(pid) except ChildProcessError: pass except KeyboardInterrupt: pass s.close() def is_readable(path): return isfile(path) and access(path, R_OK) def missing_file(path): print(f"The SSL key at {path} is not a readable file. Make sure this is a proper ssl key.") print(f"Our GettingStarted document gives simple example of how to do so.") print(f"Check out https://sphinx.pm/server_install.html .") print(f"Aborting.") exit(1) def parse_params(): if not is_readable(ssl_key): missing_file(ssl_key) if not is_readable(ssl_cert): missing_file(ssl_cert) if 'init' not in sys.argv: if not is_readable(ltsigkey_path): print(f"Long-term signing key at {ltsigkey_path} is not readable.") print(f"You can generate one by running: {sys.argv[0]} init") if getsize(ltsigkey_path) != pysodium.crypto_sign_SECRETKEYBYTES: print(f"The long-term signing key of the oracle has an invalid size, maybe it's corrupt?") print("abort.") exit(1) debug=False if 'debug' in sys.argv: debug = True if not 'init' in sys.argv: main(debug) else: # init pk, sk = pysodium.crypto_sign_keypair() with open(ltsigkey_path, 'xb') as fd: fd.write(sk) with open(f"{ltsigkey_path}.pub", 'xb') as fd: fd.write(pk) print(f"successfully created long-term signature key pair at:") print(f"{ltsigkey_path}") print(f"and the public key - which you should make available to all clients -, is at:") print(f"{ltsigkey_path}.pub") print(f"The following is the base64 encoded public key that you can also share:") print(f"{binascii.b2a_base64(pk).strip().decode('utf8')}") if __name__ == '__main__': parse_params() ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������pwdsphinx-2.0.4/pwdsphinx/ostore.py�����������������������������������������������������������������0000775�0000000�0000000�00000011255�15072476040�0017466�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python import os, subprocess from tempfile import mkstemp try: from opaquestore import client available = True except: client = None available = False if available: client.config = client.processcfg(client.getcfg('opaque-store')) def usage(params): print("\nOPAQUE Store style blobs") print(" echo -n 'password' | %s store file-to-store" % params[0]) print(" echo -n 'password' | %s read " % params[0]) print(" echo -n 'password' | %s replace [force] file-to-store" % params[0]) print(" echo -n 'password' | %s edit [force] " % params[0]) print(" echo -n 'password' | %s changepwd [force] " % params[0]) print(" echo -n 'password' | %s erase [force] " % params[0]) print(" echo -n 'password' | %s recovery-tokens " % params[0]) print(" echo -n 'password' | %s unlock " % params[0]) def is_cmd(params): if params[1] not in cmds: return False return True def connect(): s = client.Multiplexer(client.config['servers']) s.connect() return s def store(pwd, keyid, path): # create & recovery-tokens with open(path,'r') as fd: data = fd.read() with connect() as s: client.create(s, pwd, keyid.encode('utf8'), data.encode('utf8')) with connect() as s: token = client.get_recovery_tokens(s, pwd, keyid.encode('utf8')) print("successfully created opaque store record. Store the following recovery token, in case this record is locked") print(token) def read(pwd, keyid): with connect() as s: print(client.get(s, pwd, keyid.encode('utf8'))) def replace(pwd, keyid, path, force=False): with open(path,'r') as fd: data = fd.read() with connect() as s: client.update(s, pwd, keyid.encode('utf8'), data.encode('utf8'), force) def erase(pwd, keyid, ctx, force=False): with connect() as s: client.delete(s, pwd, keyid.encode('utf8'), force) # also handle delete sphinx record in case ostore.erase m = ctx['m'](ctx['servers']) m.connect() try: ctx['delete'](m, ctx['pwd'], ctx['user'], ctx['host']) finally: m.close() def changepwd(pwd, keyid, ctx, force=False): m = ctx['m'](ctx['servers']) m.connect() try: newpwd = ctx['change'](m, ctx['pwd'], ctx['newpwd'], ctx['user'], ctx['host']) finally: m.close() with connect() as s: data = client.get(s, pwd, keyid.encode('utf8')) with connect() as s: client.delete(s, pwd, keyid.encode('utf8'), force) with connect() as s: client.create(s, newpwd, keyid.encode('utf8'), data.encode('utf8')) with connect() as s: token = client.get_recovery_tokens(s, newpwd, keyid.encode('utf8')) m = ctx['m'](ctx['servers']) m.connect() try: ctx['commit'](m, ctx['pwd'], ctx['user'], ctx['host']) finally: m.close() print("Store the following recovery token, in case this record is locked") print(token) def edit(pwd, keyid, force=False): if not os.path.exists('/dev/tty'): print("can only edit on systems that have /dev/tty, sorry") return False with connect() as s: data = client.get(s, pwd, keyid.encode('utf8')) fd, fname = mkstemp() fd = os.fdopen(fd,'w') fd.write(data) fd.close() tty = os.open("/dev/tty", os.O_RDWR|os.O_LARGEFILE) subprocess.run([os.environ.get("EDITOR"), fname], stdin=tty, stdout=tty, stderr=tty) with open(fname,"r") as fd: data = fd.read() os.unlink(fname) with connect() as s: client.update(s, pwd, keyid.encode('utf8'), data.encode('utf8'), force) def recoverytoken(pwd, keyid): with connect() as s: token = client.get_recovery_tokens(s, pwd, keyid.encode('utf8')) print("Store the following recovery token, in case this record is locked") print(token) def unlock(pwd, keyid, token): # unlock + get with connect() as s: client.unlock(s, token, keyid.encode('utf8')) with connect() as s: print(client.get(s, pwd, keyid.encode('utf8'))) cmds = {'store': store, 'read': read, 'replace': replace, 'edit': edit, 'changepwd': changepwd, 'erase': erase, 'recovery-tokens': recoverytoken, 'unlock': unlock} def parse(params): if params[1] not in cmds: return False op = cmds[params[1]] args = [] if params[1] in {'replace', 'edit', 'erase', 'changepwd'} and params[2]=='force': del params[2] args.append(True) keyid=params[2] if params[1] in {'store', 'replace'}: if not os.path.isfile(params[3]): raise ValueError(f'opaque store parameter "{params[3]}" is not a file, how would i store it?') args.insert(0, params[3]) if params[1] == 'unlock': args.insert(0,params[3]) return op, keyid, args ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������pwdsphinx-2.0.4/pwdsphinx/sphinx.py�����������������������������������������������������������������0000775�0000000�0000000�00000124712�15072476040�0017467�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env python3 # SPDX-FileCopyrightText: 2018-2024, Marsiske Stefan # SPDX-License-Identifier: GPL-3.0-or-later import sys, os, socket, ssl, struct, platform, getpass, binascii, zlib import concurrent.futures from SecureString import clearmem import pysodium, pyoprf from qrcodegen import QrCode try: from zxcvbn import zxcvbn except ImportError: zxcvbn = None from equihash import solve from itertools import permutations from pyoprf.multiplexer import Peer, Multiplexer try: from pwdsphinx import bin2pass, v1sphinx from pwdsphinx.config import getcfg from pwdsphinx.consts import * from pwdsphinx.utils import split_by_n from pwdsphinx.ext import init_browser_ext from pwdsphinx.converter import convert, convertedBy from pwdsphinx import ostore except ImportError: import bin2pass, ostore, v1sphinx from config import getcfg from consts import * from utils import split_by_n from ext import init_browser_ext from converter import convert, convertedBy win=False if platform.system() == 'Windows': win=True #### config #### cfg = getcfg('sphinx') if 'client' not in cfg: print("Error: No configuration found. Check out man sphinx(1) to get started.\n" "Look at https://sphinx.pm/servers.html to choose some servers.\n" "Continuing with default values, which will probably not work", file=sys.stderr) debug = cfg.get('client',{}).get('debug', False) verbose = cfg.get('client',{}).get('verbose', False) hostname = cfg.get('client',{}).get('address','127.0.0.1') address = socket.gethostbyname(hostname) port = int(cfg.get('client',{}).get('port',2355)) timeout = int(cfg.get('client',{}).get('timeout', '5')) datadir = os.path.expanduser(cfg.get('client',{}).get('datadir','~/.config/sphinx')) try: ssl_cert = os.path.expanduser(cfg.get('client',{}).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. ssl_cert = None # make RWD optional in (sign|seal)key, if it is b'' then this protects against # offline master pwd bruteforce attacks, drawback that for known (host,username) tuples # the seeds/blobs can be controlled by an attacker if the masterkey is known rwd_keys = cfg.get('client',{}).get('rwd_keys', False) validate_password = cfg.get('client',{}).get('validate_password',True) userlist = cfg.get('client',{}).get('userlist', True) threshold = int(cfg.get('client',{}).get('threshold') or "1") ts_epsilon = 1200 # todo make configurable servers = cfg.get('servers',{}) delete_upgraded = False if v1sphinx.enabled: delete_upgraded = cfg.get('client',{}).get('delete_upgraded',False) if len(servers)==0: print(f'you have no servers defined in your [servers] section\n' f'please add {threshold + (0 if threshold==1 else 1)} more servers to your config') exit(1) if len(servers)>1: if len(servers) >= 129: print("you have to many servers in your config, you can have at most 128, but if that works is questionable, 16 is a practical maximum") exit(1) if threshold < 2: print('if you have multiple servers in your config, you must specify a threshold >1 also') exit(1) if len(servers) 1: print(f'threshold({threshold}) must be less or equal than the number of servers({len(servers)}) in your config') exit(1) if verbose: print("hostname:", hostname, file=sys.stderr) print("address:", address, file=sys.stderr) print("port:", port, file=sys.stderr) print("datadir:", datadir, file=sys.stderr) print("ssl_cert:", ssl_cert, file=sys.stderr) print("rwd_keys:", rwd_keys, file=sys.stderr) print("validate_password:", validate_password, file=sys.stderr) print("userlist:", userlist, file=sys.stderr) print("threshold:", threshold, file=sys.stderr) for name, server in servers.items(): print(f"{name} {server.get('host','localhost')}:{server.get('port', 2355)} {server['ltsigkey'].hex()} cert: {server.get('ssl_cert')}") #### consts #### ENC_CTX = b"sphinx encryption key" SIGN_CTX = b"sphinx signing key" SALT_CTX = b"sphinx host salt" PASS_CTX = b"sphinx password context" CHECK_CTX = b"sphinx check digit context" #### Helper fns #### def get_masterkey(): try: with open(os.path.join(datadir,'masterkey'), 'rb') as fd: mk = fd.read() return mk except FileNotFoundError: raise ValueError("ERROR: Could not find masterkey!\nIf sphinx was working previously it is now broken.\nIf this is a fresh install all is good, you just need to run `%s init`." % sys.argv[0]) def get_signkey(id, rwd): mk = get_masterkey() seed = pysodium.crypto_generichash(SIGN_CTX, mk) clearmem(mk) # rehash with rwd so the user always contributes his pwd and the sphinx server it's seed seed = pysodium.crypto_generichash(seed, id) if rwd_keys: seed = pysodium.crypto_generichash(seed, rwd) pk, sk = pysodium.crypto_sign_seed_keypair(seed) clearmem(seed) return sk, pk def get_sealkey(): mk = get_masterkey() sk = pysodium.crypto_generichash(ENC_CTX, mk) clearmem(mk) return sk def encrypt_blob(blob): # todo implement padding to hide length information sk = get_sealkey() nonce = pysodium.randombytes(pysodium.crypto_secretbox_NONCEBYTES) ct = pysodium.crypto_aead_xchacha20poly1305_ietf_encrypt(blob,VERSION,nonce,sk) clearmem(sk) return VERSION+nonce+ct def decrypt_blob(blob): # todo implement padding to hide length information sk = get_sealkey() version = blob[:1] if version > VERSION: raise ValueError("Your client is too old to handle this response. Please update your client.") blob = blob[1:] nonce = blob[:pysodium.crypto_secretbox_NONCEBYTES] blob = blob[pysodium.crypto_secretbox_NONCEBYTES:] res = pysodium.crypto_aead_xchacha20poly1305_ietf_decrypt(blob,version,nonce,sk) clearmem(sk) return version, res def sign_blob(blob, id, rwd): sk, pk = get_signkey(id, rwd) res = pysodium.crypto_sign_detached(blob,sk) clearmem(sk) return b''.join((blob,res)) def getsalt(): mk = get_masterkey() salt = pysodium.crypto_generichash(SALT_CTX, mk) clearmem(mk) return salt def getid1(host,user,peer,salt=None): if salt is None: salt = getsalt() user_len = struct.pack('!H', len(user)) host_len = struct.pack('!H', len(host)) peer_len = struct.pack('!H', len(peer)) return pysodium.crypto_generichash(b''.join((user_len,user.encode(), host_len,host.encode(), peer_len,peer.encode())), salt, 32) def getid(host, user, m): salt = getsalt() ids = [] for peer in m: ids.append(getid1(host,user,peer.name,salt)) return ids def oprf2rwd(r, beta, pwd, host, user): rwd = pyoprf.unblind_finalize(r, beta, pwd) salt = pysodium.crypto_generichash(getsalt() + struct.pack('!H', len(user.encode('utf8'))) + user.encode('utf8') + struct.pack('!H', len(host.encode('utf8'))) + host.encode('utf8'), outlen=pysodium.crypto_pwhash_SALTBYTES) return pysodium.crypto_pwhash(pyoprf.OPRF_BYTES, rwd, salt, pysodium.crypto_pwhash_OPSLIMIT_INTERACTIVE, pysodium.crypto_pwhash_MEMLIMIT_INTERACTIVE) def unpack_rule(ct): version, packed = decrypt_blob(ct) xor_mask = packed[-64:] v = int.from_bytes(packed[:-64], "big") size = v & ((1<<7) - 1) rule = {c for i,c in enumerate(('u','l','d')) if (v >> 7) & (1 << i)} symbols = [c for i,c in enumerate(bin2pass.symbols) if (v>>(7+3) & (1<>(7+3+33)) else: check_digit = 0 return rule, symbols, size, check_digit, xor_mask def pack_rule(char_classes, syms, size, check_digit, xor_mask=None, with_schema=False): # pack rules into and encrypt them if set(char_classes) - {'u','l','d'}: raise ValueError("ERROR: rules can only contain any of 'uld'.") if set(syms) - set(bin2pass.symbols) != set(): raise ValueError("ERROR: symbols can only contain any of '%s'." % bin2pass.symbols) if not with_schema and (char_classes == '' and len(syms)<2): raise ValueError("ERROR: no char classes and not enough symbols specified.") if not with_schema and (xor_mask is None and (char_classes == '' and len(syms)<2)): raise ValueError("ERROR: no char classes and not enough symbols specified.") if xor_mask is None: xor_mask = b'\x00' * 64 elif len(xor_mask)!=64: raise ValueError("ERROR: xor_mask must be 64bytes, is instead: %d." % len(xor_mask)) if size<0 or size>127: raise ValueError("ERROR: invalid max password size: %d." % size) packed = size packed = packed + (sum(1<= 2**16: s.close() raise ValueError("ERROR: list of usernames is bigger than 64KB. %d" % bsize) blob = struct.pack("!H", bsize) + blob # writes need to be signed, and sinces its a new blob, we need to attach the pubkey blob = b''.join([pk, blob]) # again no rwd, to be independent of the master pwd blob = sign_blob(blob, id, b'') else: blob = read_pkt(s, bsize) if blob == b'fail': s.close() raise ValueError("reading list of user names failed") version, blob = decrypt_blob(blob) items = {x for x in blob.decode().split('\x00') if x} # this should not happen, but maybe it's a sign of corruption? if item in items: print(f'warning: "{item}" is already in the user record', file=sys.stderr) items.add(item) blob = ('\x00'.join(sorted(items))).encode() # notice we do not add rwd to encryption of user blobs blob = encrypt_blob(blob) bsize = len(blob) if bsize >= 2**16: s.close() raise ValueError("ERROR: list of user names is bigger than 64KB. %d" % bsize) blob = struct.pack("!H", bsize) + blob blob = sign_blob(blob, id, b'') s.send(blob) def auth(m,ops,ids,host,user,alpha=None,pwd=None,r=None): if r is None: nonces = m.gather(32) if nonces is None: m.close() return False nonces = list(enumerate(nonces)) rwd = b'' else: msgs = m.gather(65,proc=lambda x: (x[:33],x[33:])) if msgs is None: m.close() return False nonces = [(idx,resp[1]) for idx, resp in enumerate(msgs) if resp is not None] if sum(1 for m in msgs if m is not None) < len(m): raise ValueError("auth: not all peers answered or authenticated") if len(servers)>1: beta = pyoprf.thresholdmult([resp[0] for resp in msgs if resp is not None][:threshold]) else: beta = msgs[0][0][1:] #rwd = pyoprf.unblind_finalize(r, beta, pwd) rwd = oprf2rwd(r, beta, pwd, host, user) for (idx, nonce), op in zip(nonces, ops): sk, pk = get_signkey(ids[idx], rwd) sig = pysodium.crypto_sign_detached(op+nonce,sk) clearmem(sk) m.send(idx, sig) clearmem(rwd) responses = m.gather(6) if responses is None: m.close() return False fails = 0 for idx, resp in enumerate(responses): if resp==b'\x00\x04auth': continue if resp==b'\x00\x04fail': print(f'authentication failed for {m[idx].name}') m[idx].close() fails+=1 else: raise ValueError("unexpected auth result") if fails > 0: raise ValueError("some peers have failed to authenticate us") return True def ratelimit_step1(m, reqs, min_conns): for i, req in enumerate(reqs): pkt0 = b''.join([CHALLENGE_CREATE, req]) m[i].send(pkt0) challenges = m.gather(1+1+8+32, n=min_conns) # n,k,ts,sig if challenges is None: m.close() return False m.close() return challenges def ratelimit(m,reqs,min_conns): challenges = ratelimit_step1(m, reqs, min_conns) puzzles = [] with concurrent.futures.ProcessPoolExecutor() as executor: for idx, challenge in enumerate(challenges): if challenge in {None, b''}: continue n = challenge[0] k = challenge[1] try: os.write(3,f"{idx} {n} {k}\n".encode('utf8')) except OSError: pass if k==4: if n < 90: if verbose: print(f"{m[idx].name} sent an easy puzzle: %d" % n, file=sys.stderr) elif n > 100: if verbose: print(f"{m[idx].name} sent a hard puzzle: %d" % n, file=sys.stderr) else: if verbose: print(f"{m[idx].name} sent a moderate puzzle: %d" % n, file=sys.stderr) seed = challenge + reqs[idx] solution = executor.submit(solve,n,k,seed) puzzles.append((challenge, solution, idx)) for puzzle in puzzles: m[puzzle[2]].connect() pkt1 = b''.join([CHALLENGE_VERIFY, puzzle[0]]) m.send(puzzle[2], pkt1) m.send(puzzle[2], reqs[puzzle[2]]) m.send(puzzle[2], puzzle[1].result()) return m def getpwd(): if sys.stdin.isatty(): return getpass.getpass("enter your password please: ").encode('utf8') else: return sys.stdin.buffer.readline().rstrip(b'\n') def dkg(m, op, threshold, keyids, alpha): n = len(m) # load peer long-term keys peer_lt_pks = [] for name, server in servers.items(): k = server.get('ltsigkey') if k is None: print(f"Warning the ltsigkey for server: {name} is unset.") continue peer_lt_pks.append(k) if len(peer_lt_pks) < len(servers.items()): raise ValueError("cannot create record in threshold setup without having the long-term signing keys of all servers") if op == CREATE_DKG: tp, msg0 = pyoprf.tpdkg_start_tp(n, threshold, ts_epsilon, "threshold sphinx dkg create k", peer_lt_pks) for index, id in enumerate(keyids): msg = b"%c%s%s%s" % (CREATE_DKG, id, alpha, msg0) m.send(index,msg) else: tp, msg0 = pyoprf.tpdkg_start_tp(n, threshold, ts_epsilon, "threshold sphinx dkg change k", peer_lt_pks) msg = b"%s%s" % (alpha, msg0) m.broadcast(msg) while pyoprf.tpdkg_tp_not_done(tp): ret, sizes = pyoprf.tpdkg_tp_input_sizes(tp) peer_msgs = [] if ret: if sizes[0] > 0: #print(f"step: {tp[0].step}") peer_msgs = m.gather(sizes[0],n) #,debug=True) else: peer_msgs = [m[i].read(s) if s>0 else b'' for i, s in enumerate(sizes)] msgs = b''.join(peer_msgs) cur_step = pyoprf.tpdkg_tpstate_step(tp) try: out = pyoprf.tpdkg_tp_next(tp, msgs) except Exception as e: m.close() if pyoprf.tpdkg_tpstate_cheater_len(tp) > 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}") if(len(out)>0): for i in range(pyoprf.tpdkg_tpstate_n(tp)): msg = pyoprf.tpdkg_tp_peer_msg(tp, out, i) m.send(i, msg) betas = m.gather(33, n) if betas is None: m.close() raise ValueError(f"failed to get oprf responses from shareholders in final step of dkg") rwds = set(pyoprf.thresholdmult([betas[i] for i in order]) for order in permutations(range(n),threshold)) if len(rwds) != 1: raise ValueError("DKG shares are inconsistent, aborting operation.") return list(rwds)[0] #### OPs #### def create_masterkey(): kfile = os.path.join(datadir,'masterkey') if os.path.exists(kfile): print("Already initialized.", file=sys.stderr) return 1 if not os.path.exists(datadir): os.makedirs(datadir, 0o700, exist_ok=True) mk = pysodium.randombytes(32) try: with open(kfile,'wb') as fd: if not win: os.fchmod(fd.fileno(),0o600) fd.write(mk) except: print("ERROR: failed to initialize master key", file=sys.stderr) return 1 finally: print("you want to make a backup of the following masterkey, keep it safe and secure", binascii.b2a_base64(mk)) print('this key is also stored - and must be available - at:', kfile) clearmem(mk) def init(): init_browser_ext() create_masterkey() # create health check record m = Multiplexer(servers, ['sphinx/1']) m.connect() create(m, b"all ok?", "healthcheck", "sphinx servers", target="everything works fine") return 0 def create(m, pwd, user, host, char_classes='uld', symbols=bin2pass.symbols, size=0, target=None): # 1st step OPRF on the new seed ids = getid(host, user, m) r, alpha = pyoprf.blind(pwd) if threshold > 1: beta = dkg(m, CREATE_DKG, threshold, ids, alpha) else: msg = b''.join([CREATE, ids[0], alpha]) m.broadcast(msg) # wait for response from sphinx server beta = m.gather(33) if beta is None: m.close() raise ValueError("ERROR: Creating new password, the record probably already exists or the first message to server was corrupted during transport.") # or (less probable) the initial message was longer/shorter than the 65 bytes we sent # or (even? less probable) the value alpha received by the server is not a valid point # both of these less probable causes point at corruption during transport beta = beta[0][1:] #rwd = pyoprf.unblind_finalize(r, beta, pwd) rwd = oprf2rwd(r, beta, pwd, host, user) # second phase, derive new auth signing pubkey sign_keys=[] for id in ids: sk, pk = get_signkey(id, rwd) clearmem(sk) sign_keys.append(pk) if validate_password: checkdigit = pysodium.crypto_generichash(CHECK_CTX, rwd, 1)[0] else: checkdigit = 0 if target and not user.startswith('raw://'): trwd, char_classes, symbols = bin2pass.pass2bin(target, None) xormask = xor(pysodium.crypto_generichash(PASS_CTX, rwd, outlen=64),trwd) size = len(target) #char_classes = 'uld' #symbols = bin2pass.symbols elif target and user.startswith('raw://'): size = len(target) target = target + pysodium.randombytes(64 - len(target)) xormask = xor(pysodium.crypto_generichash(PASS_CTX, rwd, outlen=64),target) elif convertedBy(user) is not None: xormask = pysodium.randombytes(64) else: _uppers = set([x.decode('utf8') for x in bin2pass.sets['u']]) _lowers = set([x.decode('utf8') for x in bin2pass.sets['l']]) _digits = set([x.decode('utf8') for x in bin2pass.sets['d']]) _symbols = set(symbols) while True: xormask = pysodium.randombytes(64) candidate = convert( xor(pysodium.crypto_generichash(PASS_CTX, rwd, outlen=64),xormask), user, host, CREATE, char_classes,size,symbols) if 1 <= size < 8: break # too much of a bias especially for ulsd when size < 5 if 'u' in char_classes and len(_uppers.intersection(candidate)) == 0: continue if 'l' in char_classes and len(_lowers.intersection(candidate)) == 0: continue if 'd' in char_classes and len(_digits.intersection(candidate)) == 0: continue if len(_symbols) > 0 and len(_symbols.intersection(candidate)) == 0: continue break # send over new signed(pubkey, rule) for i,(id,pk) in enumerate(zip(ids, sign_keys)): rule = pack_rule(char_classes, symbols, size, checkdigit, xormask, with_schema='://' in user) msg = b''.join([pk, rule]) msg = sign_blob(msg, id, rwd) m[i].send(msg) # add user to user list for this host # a malicous server could correlate all accounts on this services to this users here for p in m: id = getid1(host, '', p.name) update_rec(p.fd, id, user) p.close() rwd = xor(pysodium.crypto_generichash(PASS_CTX, rwd, outlen=64),xormask) ret = convert(rwd,user,host,CREATE,char_classes,size,symbols) clearmem(rwd) return ret def try_v1get(pwd, host, user): rwd, classes, size, symbols = v1sphinx.get(pwd, user, host) ret = convert(rwd,user,GET,host,classes,size,symbols) if not user.startswith("otp://"): target = ret else: target = bin2pass.derive(rwd, classes, size, symbols) clearmem(rwd) # lift to v2 m = Multiplexer(servers, ['sphinx/1']) m.connect() cret = create(m, pwd, user, host, target=target) assert ret == cret print(f"updated v1 record for {user}@{host} to v2", file=sys.stderr) if delete_upgraded: try: v1sphinx.delete(pwd, user, host) except: print(f"failed to delete v1 record for {user}@{host}", file=sys.stderr) else: print(f"deleted v1 record for {user}@{host} record after update to v2", file=sys.stderr) return ret def get(m, pwd, user, host): ids = getid(host, user, m) r, alpha = pyoprf.blind(pwd) msgs = [b''.join([GET, id, alpha]) for id in ids] try: m = ratelimit(m, msgs, threshold) except ValueError: if v1sphinx.enabled: return try_v1get(pwd, host, user) raise connected = sum([1 for p in m if p.state == 'connected']) if connected < threshold: raise ValueError(f"Failed to get enough shareholders to respond: {connected} responded") if len(servers) > 1: try: resps = m.gather(33+RULE_SIZE, threshold) except ValueError: if v1sphinx.enabled: return try_v1get(pwd, host, user) raise if resps is None: m.close() raise ValueError("Failed to get any answers from shareholders") if len({x for x in resps if x is not None}) == 1 and {x for x in resps if x is not None} == {b'\x00\x04fail'}: raise ValueError("ERROR: The record does not exist, there's a chance you are being fished.") resps = [(x[:33], x[33:]) for x in resps if x is not None] if len({str(unpack_rule(resp[1])) for resp in resps if resp}) != 1: m.close() raise ValueError("ERROR: servers disagree on rules") rules = resps[0][1] beta = pyoprf.thresholdmult([resp[0] for resp in resps if resp]) else: try: resp = m.gather(33+RULE_SIZE, 1)[0] # beta + sealed rules except ValueError: if v1sphinx.enabled: return try_v1get(pwd, host, user) raise if resp is None: m.close() raise ValueError("Failed to get answers from sphinx server") if resp == b'\x00\x04fail': raise ValueError("ERROR: The record does not exist, there's a chance you are being fished.") if len(resp)!=33+RULE_SIZE: m.close() raise ValueError("ERROR: the request to server was corrupted during transport.") beta = resp[1:33] rules = resp[33:] #rwd = pyoprf.unblind_finalize(r, beta, pwd) rwd = oprf2rwd(r, beta, pwd, host, user) m.close() try: classes, symbols, size, checkdigit, xormask = unpack_rule(rules) except ValueError: m.close() raise ValueError("ERROR: failed to unpack password rules from server") if validate_password and (checkdigit != (pysodium.crypto_generichash(CHECK_CTX, rwd, 1)[0] & ((1<<5)-1))): m.close() raise ValueError("ERROR: bad checkdigit") rwd = xor(pysodium.crypto_generichash(PASS_CTX, rwd, outlen=64),xormask) ret = convert(rwd,user,GET,host,classes,size,symbols) clearmem(rwd) return ret def read_blob(m, ids, host, rwd = b''): msgs = [b''.join([READ, id]) for id in ids] m = ratelimit(m, msgs, threshold) if auth(m,msgs,ids,host,'') is False: m.close() return bsizes = set(m.gather(2, proc = lambda x: struct.unpack('!H', x)[0])) if bsizes is None: m.close() raise ValueError("failed to get sizes for user blobs from threshold servers") if len(bsizes) != 1: m.close() raise ValueError(f"ERROR: inconsistent user list blob sizes: {bsizes}") bsize = list(bsizes)[0] #print('got all blobsizes') if bsize == 0: # this should not happen, it means something is corrupt m.close() raise ValueError("ERROR: server has no associated user record for this host", file=sys.stderr) blobs = m.gather(bsize) if blobs is None: m.close() raise ValueError("failed to read user blobs from sphinx servers") #print('got all blobs') ptblobs = set() for blob in blobs: if blob == b'fail': m.close() raise ValueError("ERROR: invalid signature on list of users") ptblobs.add(decrypt_blob(blob)) if len(ptblobs)!=1: raise ValueError(f"ERROR: inconsistent user list blobs") blob = list(ptblobs)[0] return blob def users(m, host): _, users = read_blob(m, getid(host, '', m), host) or (None, set()) if users: users = set(users.decode().split('\x00')) if v1sphinx.enabled: try: v1users = v1sphinx.users(host) except: v1users = set() users = users | v1users if not users: return "no users found" return '\n'.join(sorted(users)) def change(m, oldpwd, newpwd, user, host, char_classes='uld', symbols=bin2pass.symbols, size=0, target=None): ids = getid(host, user, m) r, alpha = pyoprf.blind(oldpwd) if threshold > 1: msgs = [b''.join([CHANGE_DKG, id, alpha]) for id in ids] else: msgs = [b''.join([CHANGE, id, alpha]) for id in ids] m = ratelimit(m, msgs, len(ids)) # auth: do sphinx with current seed, use it to sign the nonce if not auth(m,msgs,ids,host,user,alpha,oldpwd,r): m.close() raise ValueError("ERROR: Failed to authenticate using old password to server while changing password on server or record doesn't exist") r, alpha = pyoprf.blind(newpwd) if threshold > 1: beta = dkg(m, CHANGE_DKG, threshold, None, alpha) else: m.broadcast(alpha) beta = m.gather(33,1) # beta if beta is None or len(beta[0])!=33: m.close() raise ValueError("ERROR: changing password failed due to corruption during transport.") beta = beta[0][1:] #rwd = pyoprf.unblind_finalize(r, beta, newpwd) rwd = oprf2rwd(r, beta, newpwd, host, user) if validate_password: checkdigit = pysodium.crypto_generichash(CHECK_CTX, rwd, 1)[0] else: checkdigit = 0 if target and not user.startswith('raw://'): trwd, char_classes, symbols = bin2pass.pass2bin(target, None) xormask = xor(pysodium.crypto_generichash(PASS_CTX, rwd, outlen=64),trwd) size = len(target) #char_classes = 'uld' #symbols = bin2pass.symbols elif target and user.startswith('raw://'): size = len(target) target = target + pysodium.randombytes(64 - len(target)) xormask = xor(pysodium.crypto_generichash(PASS_CTX, rwd, outlen=64),target) elif convertedBy(user) is not None: xormask = pysodium.randombytes(64) else: _uppers = set([x.decode('utf8') for x in bin2pass.sets['u']]) _lowers = set([x.decode('utf8') for x in bin2pass.sets['l']]) _digits = set([x.decode('utf8') for x in bin2pass.sets['d']]) _symbols = set(symbols) while True: xormask = pysodium.randombytes(64) candidate = convert( xor(pysodium.crypto_generichash(PASS_CTX, rwd, outlen=64),xormask), user, host, CREATE, char_classes,size,symbols) if 1 <= size < 8: break # too much of a bias especially for ulsd when size < 5 if 'u' in char_classes and len(_uppers.intersection(candidate)) == 0: continue if 'l' in char_classes and len(_lowers.intersection(candidate)) == 0: continue if 'd' in char_classes and len(_digits.intersection(candidate)) == 0: continue if len(_symbols) > 0 and len(_symbols.intersection(candidate)) == 0: continue break for i, id in enumerate(ids): rule = pack_rule(char_classes, symbols, size, checkdigit, xormask) sk, pk = get_signkey(id, rwd) clearmem(sk) # send over new signed(pubkey) m[i].send(sign_blob(b''.join([pk,rule]), id, rwd)) if set(m.gather(2))!={b'ok'}: m.close() raise ValueError("ERROR: failed to update password rules on the server during changing of password.") m.close() rwd = xor(pysodium.crypto_generichash(PASS_CTX, rwd, outlen=64),xormask) ret = convert(rwd,user,host,CHANGE,char_classes,size,symbols) clearmem(rwd) return ret def commit(s, pwd, user, host): return commit_undo(s, COMMIT, pwd, user, host) def undo(s, pwd, user, host): return commit_undo(s, UNDO, pwd, user, host) def delete(m, pwd, user, host): # run sphinx to recover rwd for authentication ids = getid(host, user, m) r, alpha = pyoprf.blind(pwd) msgs = [b''.join([DELETE, id, alpha]) for id in ids] m = ratelimit(m, msgs, len(ids)) #print("solved ratelimit puzzles") if auth(m,msgs,ids,host,user,alpha,pwd,r) is False: m.close() raise ValueError("ERROR: Failed to authenticate to server while deleting password on server or record doesn't exist") #print("authenticated") if not userlist: m.broadcast(b"\0"*96) else: # delete user from user list for this host # a malicous server could correlate all accounts on this services to this users here # first query user record for this host for p in m: id = getid1(host, '', p.name) signed_id = sign_blob(id, id, b'') p.send(signed_id) # wait for user blob bsizes = set(m.gather(2, proc = lambda x: struct.unpack('!H', x)[0])) if bsizes is None: m.close() raise ValueError("failed to get sizes for user blobs from threshold servers") if len(bsizes) != 1: m.close() raise ValueError(f"ERROR: inconsistent user list blob sizes: {bsizes}") bsize = list(bsizes)[0] #print('got all blobsizes') if bsize == 0: # this should not happen, it means something is corrupt m.close() raise ValueError("ERROR: server has no associated user record for this host", file=sys.stderr) blobs = m.gather(bsize) if blobs is None: m.close() raise ValueError("failed to read user blobs from sphinx servers") #print('got all blobs') ptblobs = set() for blob in blobs: if blob == b'fail': m.close() raise ValueError("ERROR: invalid signature on list of users") ptblobs.add(decrypt_blob(blob)) if len(ptblobs)!=1: raise ValueError(f"ERROR: inconsistent user list blobs") version, blob = list(ptblobs)[0] users = set(blob.decode().split('\x00')) if user not in users: # this should not happen, but maybe it's a sign of corruption? m.close() raise ValueError(f'warning "{user}" is not in user record', file=sys.stderr) users.remove(user) blob = ('\x00'.join(sorted(users))).encode() # notice we do not add rwd to encryption of user blobs for p in m: xblob = encrypt_blob(blob) bsize = len(xblob) if bsize >= 2**16: m.close() raise ValueError("ERROR: blob is bigger than 64KB.") xblob = struct.pack("!H", bsize) + xblob id = getid1(host, '', p.name) xblob = sign_blob(xblob, id, b'') #print(f'updating {p.name}\t{xblob.hex()}') p.send(xblob) if set(m.gather(2))!={b'ok'}: m.close() raise ValueError("ERROR: server failed to save updated list of user names for host: %s." % host) m.close() return True def print_qr(qrcode: QrCode) -> None: chars = { (True, True): ' ', # empty (False, True): '\u2580', # upper (True, False): '\u2584', # lower (False, False): '\u2588', # full } border = 1 for y in range(-border, qrcode.get_size() + border, 2): for x in range(-border, qrcode.get_size() + border): print(chars[(qrcode.get_module(x,y),qrcode.get_module(x,y+1))], end="") print() print() def healthcheck(m): pwd = b"all ok?" user = "healthcheck" host = "sphinx servers" ids = getid(host, user, m) r, alpha = pyoprf.blind(pwd) msgs = [b''.join([GET, id, alpha]) for id in ids] return ratelimit_step1(m, msgs, len(ids)) != False def qrcode(output, key): mk=get_masterkey() if key else b'' hosts = [] ltsigkeys = [] for name, server in servers.items(): if len(name)>255: raise ValueError(f"server name: {name} is too long, max 255 allowed in qr codes") hosts.append(bytes([len(name.encode('utf8'))]) + name.encode('utf8') + bytes([len(server.get('host','localhost'))]) + server.get('host','localhost').encode('utf8') + struct.pack("!H", server.get('port', 2355))) ltsigkeys.append(server['ltsigkey']) hosts=zlib.compress(b''.join(hosts)) ltsigkeylen = struct.pack("B", len(ltsigkeys)) data = (bytes([1*key+2*rwd_keys + 4*validate_password + 8*userlist + 16+delete_upgraded, threshold]) + mk + ltsigkeylen + b''.join(ltsigkeys) + hosts) qr = QrCode.encode_binary(data, QrCode.Ecc.LOW) if key: clearmem(mk) clearmem(data) if output=='txt': print_qr(qr) else: print(qr.to_svg_str(2)) def ostore_handler(m, pwd, params, newpwd=None): op, keyid, args = ostore.parse(params) user = keyid host = 'opaque store' if op == ostore.changepwd: args.insert(0, {'m': Multiplexer, 'servers': servers, 'change': change, 'commit': commit, 'user': user, 'host': host, 'pwd': pwd, 'newpwd': newpwd}) elif op == ostore.erase: args.insert(0, {'m': Multiplexer, 'servers': servers, 'delete': delete, 'pwd': pwd, 'user': user, 'host': host}) if op == ostore.store: rwd = create(m, pwd, user, host) else: rwd = get(m, pwd, user, host) op(rwd, keyid, *args) return True def usage(params, help=False): print("usage:") print("SPHINX style passwords") print(" %s init" % params[0]) print(" echo -n 'password' | %s <[u][l][d][s] [] []> | []" % params[0]) print(" echo -n 'password' | %s get " % params[0]) if rwd_keys: print(" echo -n 'password' | %s " % params[0]) else: print(" %s " % params[0]) if userlist: print(" %s list " % params[0]) print(" %s healthcheck" % params[0]) print(" %s qr [svg] [key]" % params[0]) if ostore.available: ostore.usage(params) if help: sys.exit(0) sys.exit(100) def arg_rules(params): user = params[2] site = params[3] size = None symbols = None classes = None target = None for param in params[4:]: if not classes and set(list(param)) - {'u','l','s','d'} == set(): if 's' in param: symbols = bin2pass.symbols classes = ''.join(set(param) - set(['s'])) else: classes = param symbols = '' continue if not size: try: tmp = int(param) if tmp<79: size = tmp continue except: pass if set(param) - set(bin2pass.symbols) == set(): symbols = param continue if verbose: print(f'using "{param}" as target password', file=sys.stderr) target = param if target is not None and (symbols or classes or size): print(f"invalid args for {param[1]}: \"{params[4:]}\"", file=sys.stderr) usage(param) return user, site, classes or 'uld', symbols if symbols is not None else bin2pass.symbols, size or 0, target 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 #### 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) m = Multiplexer(servers, ['sphinx/1']) cmd = None args = [] if params[1] in ('help', '-h', '--help'): usage(params, True) elif params[1] == 'create': try: user,site,classes, syms, size, target = arg_rules(params) except: usage(params) cmd = create args = (user, site, classes, syms, size, target) elif params[1] == 'init': if len(params) != 2: usage(params) sys.exit(init()) elif params[1] == 'healthcheck': cmd = healthcheck args = tuple() elif params[1] == 'get': if len(params) != 4: usage(params) cmd = get args = (params[2], params[3]) elif params[1] == 'change': try: user,site,classes,syms,size, target = arg_rules(params) except: usage(params) cmd = change args = (user, site, classes, syms, size, target) elif params[1] == 'commit': if len(params) != 4: usage(params) cmd = commit args = (params[2], params[3]) elif params[1] == 'delete': if len(params) != 4: usage(params) cmd = delete args = (params[2], params[3]) elif userlist and params[1] == 'list': if len(params) != 3: usage(params) cmd = users args = (params[2],) elif params[1] == 'undo': if len(params) != 4: usage(params) cmd = undo args = (params[2],params[3]) elif params[1] == 'qr': cmd = qrcode output = 'txt' key = False if "svg" in params: output="svg" del params[params.index("svg")] if "key" in params: key=True del params[params.index("key")] if params[2:]: usage(params) qrcode(output, key) return elif ostore.available and ostore.is_cmd(params): cmd = ostore_handler args = [params] else: usage(params) error = None if cmd not in {users, healthcheck}: pwd = '' if (rwd_keys or cmd in {create,change,get, ostore_handler}): pwd = getpwd() if cmd == change or (cmd == ostore_handler and params[1] == 'changepwd'): newpwd = getpwd() if not newpwd: newpwd = pwd test_pwd(newpwd) if cmd == change: args=(newpwd,) + args else: args=args + [newpwd] if cmd == create: test_pwd(pwd) try: m.connect() ret = cmd(m, pwd, *args) except Exception as exc: error = exc ret = False if debug: raise # only for dbg clearmem(pwd) else: try: m.connect() ret = cmd(m, *args) except Exception as exc: error = exc ret = False if debug: raise # only for dbg m.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) if str(error) == "ERROR: bad checkdigit": sys.exit(2) # bad check digit sys.exit(1) # generic errors if cmd not in {delete, undo, commit, ostore_handler, healthcheck}: 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) if debug: raise # only for dbg pwdsphinx-2.0.4/pwdsphinx/utils.py000066400000000000000000000002201507247604000172760ustar00rootroot00000000000000from itertools import zip_longest # for Python 3.x def split_by_n(iterable, n): return list(zip_longest(*[iter(iterable)]*n, fillvalue='')) pwdsphinx-2.0.4/pwdsphinx/v1sphinx.py000077500000000000000000000264611507247604000177400ustar00rootroot00000000000000#!/usr/bin/env python3 # SPDX-FileCopyrightText: 2018-2024, Marsiske Stefan # SPDX-License-Identifier: GPL-3.0-or-later import sys, os, socket, ssl, struct, time from SecureString import clearmem from equihash import solve import pysodium try: from pwdsphinx import bin2pass from pwdsphinx.config import getcfg from pwdsphinx.consts import * from pwdsphinx.converter import convert except ImportError: import bin2pass from config import getcfg from consts import * from converter import convert # override consts from consts.py VERSION = b'\x00' RULE_SIZE = 79 #### config #### cfg = getcfg('sphinx') enabled=False verbose = cfg.get('client',{}).get('verbose', False) hostname = cfg.get('client',{}).get('address') timeout = int(cfg.get('client',{}).get('timeout', '5')) if hostname is not None: enabled = True address = socket.gethostbyname(hostname) port = int(cfg.get('client',{}).get('port',2355)) try: ssl_cert = os.path.expanduser(cfg.get('client',{}).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. ssl_cert = None datadir = os.path.expanduser(cfg.get('client',{}).get('datadir','~/.config/sphinx')) # make RWD optional in (sign|seal)key, if it is b'' then this protects against # offline master pwd bruteforce attacks, drawback that for known (host,username) tuples # the seeds/blobs can be controlled by an attacker if the masterkey is known rwd_keys = cfg.get('client',{}).get('rwd_keys', False) validate_password = cfg.get('client',{}).get('validate_password',True) userlist = cfg.get('client',{}).get('userlist', True) if verbose and enabled: print("v1 hostname:", hostname, file=sys.stderr) print("v1 address:", address, file=sys.stderr) print("v1 port:", port, file=sys.stderr) print("v1 timeout:", timeout, file=sys.stderr) print("v1 ssl_cert:", ssl_cert, file=sys.stderr) #### consts #### ENC_CTX = b"sphinx encryption key" SIGN_CTX = b"sphinx signing key" SALT_CTX = b"sphinx host salt" PASS_CTX = b"sphinx password context" CHECK_CTX = b"sphinx check digit context" #### Helper fns #### def get_masterkey(): try: with open(os.path.join(datadir,'masterkey'), 'rb') as fd: mk = fd.read() return mk except FileNotFoundError: raise ValueError("ERROR: Could not find masterkey!\nIf sphinx was working previously it is now broken.\nIf this is a fresh install all is good, you just need to run `%s init`." % sys.argv[0]) def connect(): ctx = ssl.create_default_context() if(ssl_cert): ctx.load_verify_locations(ssl_cert) # only for dev, production system should use proper certs! ctx.check_hostname=False # only for dev, production system should use proper certs! ctx.verify_mode=ssl.CERT_NONE # only for dev, production system should use proper certs! else: ctx.load_default_certs() ctx.verify_mode = ssl.CERT_REQUIRED ctx.check_hostname = True s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(timeout) s = ctx.wrap_socket(s, server_hostname=hostname) s.connect((address, port)) return s def get_signkey(id, rwd): mk = get_masterkey() seed = pysodium.crypto_generichash(SIGN_CTX, mk) clearmem(mk) # rehash with rwd so the user always contributes his pwd and the sphinx server it's seed seed = pysodium.crypto_generichash(seed, id) if rwd_keys: seed = pysodium.crypto_generichash(seed, rwd) pk, sk = pysodium.crypto_sign_seed_keypair(seed) clearmem(seed) return sk, pk def get_sealkey(): mk = get_masterkey() sk = pysodium.crypto_generichash(ENC_CTX, mk) clearmem(mk) return sk def encrypt_blob(blob): # todo implement padding to hide length information sk = get_sealkey() nonce = pysodium.randombytes(pysodium.crypto_secretbox_NONCEBYTES) ct = pysodium.crypto_aead_xchacha20poly1305_ietf_encrypt(blob,VERSION,nonce,sk) clearmem(sk) return VERSION+nonce+ct def decrypt_blob(blob): # todo implement padding to hide length information sk = get_sealkey() version = blob[:1] if version > VERSION: raise ValueError("Your client is too old to handle this response. Please update your client.") blob = blob[1:] nonce = blob[:pysodium.crypto_secretbox_NONCEBYTES] blob = blob[pysodium.crypto_secretbox_NONCEBYTES:] res = pysodium.crypto_aead_xchacha20poly1305_ietf_decrypt(blob,version,nonce,sk) clearmem(sk) return version, res def sign_blob(blob, id, rwd): sk, pk = get_signkey(id, rwd) res = pysodium.crypto_sign_detached(blob,sk) clearmem(sk) return b''.join((blob,res)) def getid(host, user): mk = get_masterkey() salt = pysodium.crypto_generichash(SALT_CTX, mk) clearmem(mk) return pysodium.crypto_generichash(b'|'.join((user.encode(),host.encode())), salt, 32) def unpack_rule(ct): version, packed = decrypt_blob(ct) xor_mask = packed[-32:] v = int.from_bytes(packed[:-32], "big") size = v & ((1<<7) - 1) rule = {c for i,c in enumerate(('u','l','d')) if (v >> 7) & (1 << i)} symbols = [c for i,c in enumerate(bin2pass.symbols) if (v>>(7+3) & (1<>(7+3+33)) else: check_digit = 0 return rule, symbols, size, check_digit, xor_mask def xor(x,y): return bytes(a ^ b for (a, b) in zip(x, y)) def ratelimit(s,req): pkt0 = b''.join([CHALLENGE_CREATE, req]) s.send(pkt0) challenge = s.recv(1+1+8+32) # n,k,ts,sig if len(challenge)!= 1+1+8+32: if verbose: print("challengelen incorrect: %s %s" %(len(challenge), repr(challenge)), file=sys.stderr) raise ValueError("ERROR: failed to get ratelimit challenge") s.close() n = challenge[0] k = challenge[1] try: os.write(3,f"{n} {k}\n".encode('utf8')) except OSError: pass if k==4: if n < 90: if verbose: print("got an easy puzzle: %d" % n, file=sys.stderr) elif n > 100: if verbose: print("got a hard puzzle: %d" % n, file=sys.stderr) else: if verbose: print("got a moderate puzzle: %d" % n, file=sys.stderr) seed = challenge + req delta = time.time() solution = solve(n, k, seed) delta = time.time() - delta try: os.write(3,f"{delta}".encode('utf8')) except OSError: pass s = connect() pkt1 = b''.join([CHALLENGE_VERIFY, challenge]) s.send(pkt1) s.send(req) s.send(solution) return s def auth(s,op,id,alpha=None,pwd=None,r=None): if r is None: nonce = s.recv(32) if len(nonce)!=32: return False rwd = b'' else: msg = s.recv(64) if len(msg)!=64: return False beta = msg[:32] nonce = msg[32:] rwd = finish(pwd, r, alpha, beta, id) sk, pk = get_signkey(id, rwd) clearmem(rwd) sig = pysodium.crypto_sign_detached(op+nonce,sk) clearmem(sk) s.send(sig) resp = s.recv(6) if resp==b'\x00\x04auth': return True return False def challenge(pwd): h0 = pysodium.crypto_generichash(pwd, outlen=pysodium.crypto_core_ristretto255_HASHBYTES); H0 = pysodium.crypto_core_ristretto255_from_hash(h0) clearmem(h0) r = pysodium.crypto_core_ristretto255_scalar_random() alpha = pysodium.crypto_scalarmult_ristretto255(r, H0) clearmem(H0) return r, alpha def finish(pwd, r, alpha, beta, salt): if(alpha==beta): raise ValueError("alpha == beta") if not pysodium.crypto_core_ristretto255_is_valid_point(alpha): raise ValueError("invalid beta") rinv = pysodium.crypto_core_ristretto255_scalar_invert(r) H0_k = pysodium.crypto_scalarmult_ristretto255(rinv, beta) clearmem(rinv) rwd0 = pysodium.crypto_generichash(pwd+H0_k, outlen=pysodium.crypto_core_ristretto255_BYTES); clearmem(H0_k) rwd = pysodium.crypto_pwhash(pysodium.crypto_core_ristretto255_BYTES, rwd0, salt[:pysodium.crypto_pwhash_SALTBYTES], pysodium.crypto_pwhash_OPSLIMIT_INTERACTIVE, pysodium.crypto_pwhash_MEMLIMIT_INTERACTIVE) clearmem(rwd0) return rwd #### OPs #### def get(pwd, user, host): if isinstance(pwd, str): pwd = pwd.encode() s = connect() id = getid(host, user) r, alpha = challenge(pwd) msg = b''.join([V1GET, id, alpha]) s = ratelimit(s, msg) resp = s.recv(32+RULE_SIZE) # beta + sealed rules if resp == b'\x00\x04fail' or len(resp)!=32+RULE_SIZE: s.close() raise ValueError("ERROR: Either the record does not exist, or the request to server was corrupted during transport.") beta = resp[:32] rules = resp[32:] rwd = finish(pwd, r, alpha, beta, id) try: classes, symbols, size, checkdigit, xormask = unpack_rule(rules) except ValueError: s.close() raise ValueError("ERROR: failed to unpack password rules from server") s.close() if validate_password and (checkdigit != (pysodium.crypto_generichash(CHECK_CTX, rwd, 1)[0] & ((1<<5)-1))): raise ValueError("ERROR: bad checkdigit") rwd = xor(pysodium.crypto_generichash(PASS_CTX, rwd),xormask) return rwd, classes, size, symbols def delete(pwd, user, host): s = connect() # run sphinx to recover rwd for authentication id = getid(host, user) r, alpha = challenge(pwd) msg = b''.join([V1DELETE, id, alpha]) s = ratelimit(s, msg) if isinstance(pwd, str): pwd = pwd.encode() if not auth(s,msg,id,alpha,pwd,r): s.close() raise ValueError("ERROR: Failed to authenticate to server while deleting password on server or record doesn't exist") if not userlist: s.send(b"\0"*96) else: # delete user from user list for this host # a malicous server could correlate all accounts on this services to this users here # first query user record for this host id = getid(host, '') signed_id = sign_blob(id, id, b'') s.send(signed_id) # wait for user blob bsize = s.recv(2) bsize = struct.unpack('!H', bsize)[0] if bsize == 0: # this should not happen, it means something is corrupt s.close() raise ValueError("ERROR: server has no associated user record for this host", file=sys.stderr) blob = s.recv(bsize) if blob == b'fail': s.close() raise ValueError("ERROR: invalid signature on list of users") version, blob = decrypt_blob(blob) users = set(blob.decode().split('\x00')) if user not in users: # this should not happen, but maybe it's a sign of corruption? s.close() raise ValueError(f'warning "{user}" is not in user record', file=sys.stderr) users.remove(user) blob = ('\x00'.join(sorted(users))).encode() # notice we do not add rwd to encryption of user blobs blob = encrypt_blob(blob) bsize = len(blob) if bsize >= 2**16: s.close() raise ValueError("ERROR: blob is bigger than 64KB.") blob = struct.pack("!H", bsize) + blob blob = sign_blob(blob, id, b'') s.send(blob) if b'ok' != s.recv(2): s.close() raise ValueError("ERROR: server failed to save updated list of user names for host: %s." % host) s.close() return True def read_blob(s, id): msg = b''.join([READ, id]) s = ratelimit(s, msg) if auth(s,msg,id) is False: s.close() return bsize = s.recv(2) bsize = struct.unpack('!H', bsize)[0] blob = s.recv(bsize) s.close() if blob == b'fail': return return decrypt_blob(blob) def users(host): s = connect() res = read_blob(s, getid(host, '')) if not res: return set() version, res = res users = set(res.decode().split('\x00')) return users #print(get(connect(), b'asdf','asdf','test')) #print(delete(connect(), b'asdf','asdf','test')) pwdsphinx-2.0.4/pwdsphinx/websphinx.py000077500000000000000000000326271507247604000201700ustar00rootroot00000000000000#!/usr/bin/env python3 # # This file is part of WebSphinx. # # SPDX-FileCopyrightText: 2018, Marsiske Stefan # SPDX-License-Identifier: GPL-3.0-or-later # # WebSphinx 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. # # WebSphinx 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 version 3 for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, If not, see . import subprocess import sys, struct, json, pysodium import cbor2 from zxcvbn import zxcvbn from SecureString import clearmem from pyoprf.multiplexer import Multiplexer from binascii import b2a_base64 from base64 import urlsafe_b64decode try: from pwdsphinx import sphinx, bin2pass from pwdsphinx.config import getcfg except ImportError: import sphinx from config import getcfg cfg = getcfg('sphinx') pinentry = cfg['websphinx']['pinentry'] log = cfg['websphinx'].get('log') if 'webauthn_data_dir' not in cfg['websphinx']: raise Exception("Cannot find webauthn user directory (webauthn_data_dir). Add it to your config file") webauthn_data_dir = cfg['websphinx']['webauthn_data_dir'] def handler(cb, cmd, *args): m = Multiplexer(sphinx.servers) m.connect() cb(cmd(m, *args)) m.close() def getpwd(title): proc=subprocess.Popen([pinentry, '-g'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = proc.communicate(input=('SETTITLE sphinx password prompt\nSETDESC %s\nSETPROMPT master password\ngetpin\n' % (title)).encode()) if proc.returncode == 0: for line in out.split(b'\n'): if line.startswith(b"D "): return line[2:] def fetchOK(proc, cmd): proc.stdin.write(f"{cmd}\n".encode("utf8")) proc.stdin.flush() if((line:=proc.stdout.readline())!=b"OK\n"): raise ValueError(f"fail \"{cmd}\": {line}") def pwdq(pwd): q = zxcvbn(pwd.decode('utf8')) q['guesses'] q['score'] q['crack_times_display'] q['feedback'] proc=subprocess.Popen([pinentry, '-g'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if not (resp:=proc.stdout.readline()).startswith(b'OK Pleased to meet you'): raise ValueError(f"strange greeting \"{resp}\"") fetchOK(proc ,"SETTITLE Password Quality Check") fetchOK(proc ,"SETOK use this") fetchOK(proc ,"SETCANCEL try another") fetchOK(proc ,"SETDESC your %s%s (%s/4) master password:%%0a - can be online recovered in %s,%%0a - offline in %s,%%0a - trying ~%s guesses%%0a%%0aAre you sure you want to use this password?" % ("★" * 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'])) try: fetchOK(proc ,"CONFIRM") except ValueError: return False return True # Send message using Native messaging protocol def send_message(data): msg = json.dumps(data).encode('utf-8') if log: log.write(msg) log.write(b'\n') log.flush() length = struct.pack('@I', len(msg)) sys.stdout.buffer.write(length) sys.stdout.buffer.write(msg) sys.stdout.buffer.flush() def users(data): def callback(users): res = {'names': [i for i in users.split("\n")], 'cmd': 'list', "mode": data['mode'], 'site': data['site']} send_message({ 'results': res }) try: handler(callback, sphinx.users, data['site']) except: send_message({ 'results': 'fail' }) def get(data): def callback(arg): res = { 'password': arg, 'name': data['name'], 'site': data['site'], 'cmd': 'login', "mode": data['mode']} send_message({ 'results': res }) try: pwd=getpwd("get password for user \"%s\" at host \"%s\"" % (data['name'], data['site'])) handler(callback, sphinx.get, pwd, data['name'], data['site']) except: send_message({ 'results': 'fail' }) def create(data): def callback(arg): res = { 'password': arg, 'name': data['name'], 'site': data['site'], 'cmd': 'create', "mode": data['mode']} send_message({ 'results': res }) try: pwd=None while not pwd: pwd=getpwd("create password for user \"%s\" at host \"%s\"%%0a" % (data['name'], data['site'])) pwd2=getpwd("REPEAT: create for user \"%s\" at host \"%s\"%%0a" % (data['name'], data['site'])) if pwd != pwd2: send_message({ 'results': 'fail' }) return if not pwdq(pwd): pwd=None symbols = '' if 's' in data['rules']: symbols = bin2pass.symbols data['rules'] = ''.join(set(data['rules']) - set(['s'])) handler(callback, sphinx.create, pwd, data['name'], data['site'], data['rules'], symbols, int(data['size']), None) except: send_message({ 'results': 'fail' }) def change(data): def callback(arg): res = { 'password': arg, 'name': data['name'], 'site': data['site'], 'cmd': 'change', "mode": data['mode']} send_message({ 'results': res }) try: oldpwd="" if cfg['client'].get('rwd_keys'): oldpwd=getpwd("current password for \"%s\" at host: \"%s\"%%0a" % (data['name'], data['site'])) pwd=None while not pwd: pwd=getpwd("new password for user \"%s\" at host \"%s\"%%0a" % (data['name'], data['site'])) pwd2=getpwd("REPEAT: new for user \"%s\" at host \"%s\"%%0a" % (data['name'], data['site'])) if pwd != pwd2: send_message({ 'results': 'fail' }) return if not pwdq(pwd): pwd=None symbols = '' if 's' in data['rules']: symbols = bin2pass.symbols data['rules'] = ''.join(set(data['rules']) - set(['s'])) handler(callback, sphinx.change, oldpwd, pwd, data['name'], data['site'], data['rules'], symbols, int(data['size']), None) except: send_message({ 'results': 'fail' }) def commit(data): def callback(arg): res = { 'result': arg, 'name': data['name'], 'site': data['site'], 'cmd': 'commit', "mode": data['mode']} send_message({ 'results': res }) try: pwd="" if cfg['client'].get('rwd_keys'): pwd=getpwd("commit password for \"%s\" at host: \"%s\"%%0a" % (data['name'], data['site'])) handler(callback, sphinx.commit, pwd, data['name'], data['site']) except: send_message({ 'results': 'fail' }) def undo(data): def callback(arg): res = { 'result': arg, 'name': data['name'], 'site': data['site'], 'cmd': 'undo', "mode": data['mode']} send_message({ 'results': res }) try: pwd="" if cfg['client'].get('rwd_keys'): pwd=getpwd("undo password for \"%s\" at host: \"%s\"%%0a" % (data['name'], data['site'])) handler(callback, sphinx.undo, pwd, data['name'], data['site']) except: send_message({ 'results': 'fail' }) def qrcode(data): try: sphinx.qrcode("svg", True) res = { 'result': arg, 'cmd': 'qrcode', "mode": data['mode']} send_message({ 'results': res }) except: send_message({ 'results': 'fail' }) def echo(data): send_message(data) def webauthn_create(data): try: pwd=None while not pwd: pwd=getpwd("create password for user \"%s\" at host \"%s\"%%0a" % (data['name'], data['site'])) pwd2=getpwd("REPEAT: create for user \"%s\" at host \"%s\"%%0a" % (data['name'], data['site'])) if pwd != pwd2: send_message({ 'results': 'fail', 'id': data['id'], 'tabId': data['tabId'], 'cmd': res['cmd']}) return if not pwdq(pwd): pwd=None # TODO use webauthn:// instead of raw:// - don't forget to rewrite it in handle() rand_bytes = pysodium.randombytes(32) pk, sk = pysodium.crypto_sign_seed_keypair(rand_bytes) # signed_challenge = pysodium.crypto_sign(data['challenge'], sk) auth_data = pysodium.crypto_hash_sha256(data['site'].encode('utf8')) + ( # rpIdHash b'\x4d' + # flags https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API/Authenticator_data b'\x00' * 4 + # signCount b'\x00' * 16 + # attestedCredentialData->AAGUID struct.pack('>H', len(pk)) + # attestedCredentialData->pk length pk + # attestedCredentialData->credentialId (pk) cbor2.dumps({ # cose encoded public key https://datatracker.ietf.org/doc/html/rfc8152#section-13 1: 1, # key type => okp 3: -8, # algorithm => Ed25519 (-8) -1: 6, # curve => ed25519 -2: pk, # x => pubkey # no y required (y is -3) })) # attestedCredentialData->credentialPublicKey # TODO use opaque with open(webauthn_data_dir + "/" + pk.hex(), "wb") as wf: wf.write(urlsafe_b64decode(data['userid']+"==")) att_sig = pysodium.crypto_sign_detached(auth_data + pysodium.crypto_hash_sha256(data['clientDataJSON'].encode('utf-8')), sk) attestation = cbor2.dumps({ 'fmt': 'packed', 'attStmt': { 'alg': -8, 'sig': att_sig, }, 'authData': auth_data }) #log.write((data['clientDataJSON']+"\n").encode('utf-8')) #log.write((auth_data.hex() + "\n").encode('utf-8')) res = { 'pk': b2a_base64(pk).decode('utf8').strip(), 'attestationObject': b2a_base64(attestation).decode('utf-8').strip(), 'authData': b2a_base64(auth_data).decode('utf-8').strip(), 'name': data['name'], 'site': data['site'], 'cmd': 'webauthn-create', 'id': data['id'], 'tabId': data['tabId'] } # create new user with pk m = Multiplexer(sphinx.servers) m.connect() # TODO add optional argument to create() to skip extending the userlist orig_userlist = sphinx.userlist sphinx.userlist = False sphinx.create(m, pwd, 'raw://'+pk.hex(), data['site'], '', '', target = rand_bytes) sphinx.userlist = orig_userlist m.close() clearmem(sk) clearmem(rand_bytes) send_message({'results': res}) except Exception as e: send_message({ 'results': 'fail', 'id': data.get('id', ''), 'tabId': data.get('tabId', -1), 'cmd': 'webauthn-create'}) #send_message({ 'results': 'fail', 'id': data.get('id', ''), 'tabId': data.get('tabId', -1), 'cmd': 'webauthn-create', 'exception': str(e)}) def webauthn_get(data): def callback(rand_bytes): pk, sk = pysodium.crypto_sign_seed_keypair(rand_bytes) clearmem(rand_bytes) # TODO use opaque with open(webauthn_data_dir + "/" + pk.hex(), "rb") as wf: userid = wf.read() auth_data = pysodium.crypto_hash_sha256(data['site'].encode('utf8')) + ( # rpIdHash b'\x4d' + # flags https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API/Authenticator_data b'\x00' * 4 + # signCount b'\x00' * 16 + # attestedCredentialData->AAGUID struct.pack('>H', len(pk)) + # attestedCredentialData->pk length pk + # attestedCredentialData->credentialId (pk) cbor2.dumps({ # cose encoded public key https://datatracker.ietf.org/doc/html/rfc8152#section-13 1: 1, # key type => okp 3: -8, # algorithm => Ed25519 (-8) -1: 6, # curve => ed25519 -2: pk, # x => pubkey # no y required (y is -3) })) # attestedCredentialData->credentialPublicKey sig = pysodium.crypto_sign_detached(auth_data + pysodium.crypto_hash_sha256(data['clientDataJSON'].encode('utf-8')), sk) clearmem(sk) res = { 'userid': b2a_base64(userid).decode('utf-8').strip(), 'sig': b2a_base64(sig).decode('utf8').strip(), 'authData': b2a_base64(auth_data).decode('utf-8').strip(), 'site': data['site'], 'cmd': 'webauthn-get', 'id': data['id'], 'tabId': data['tabId'], 'pk': b2a_base64(pk).decode('utf-8').strip(), } send_message({'results': res}) try: pwd=getpwd("get webauthn password at host \"%s\"" % data['site']) pk = urlsafe_b64decode(data['pk']+"==") handler(callback, sphinx.get, pwd, 'raw://'+pk.hex(), data['site']) except Exception as e: send_message({ 'results': 'fail', 'id': data.get('id', ''), 'tabId': data.get('tabId', -1), 'cmd': 'webauthn-get'}) #send_message({ 'results': 'fail', 'id': data.get('id', ''), 'tabId': data.get('tabId', -1), 'cmd': 'webauthn-get', 'exception': str(e)}) func_map = { 'login': get, 'list': users, 'create': create, 'change': change, 'commit': commit, 'undo': undo, 'qrcode': qrcode, 'echo': echo, 'webauthn-create': webauthn_create, 'webauthn-get': webauthn_get, } def main(): global log if log: log = open(log,'ab') while True: # Read message using Native messaging protocol length_bytes = sys.stdin.buffer.read(4) if len(length_bytes) == 0: return length = struct.unpack('i', length_bytes)[0] data = json.loads(sys.stdin.buffer.read(length).decode('utf-8')) if log: log.write(repr(data).encode()) log.write(b'\n') log.flush() if data['cmd'] in func_map: func_map[data['cmd']](data) else: send_message({ 'results': 'fail' }) if __name__ == '__main__': main() pwdsphinx-2.0.4/setup.py000077500000000000000000000043731507247604000152720ustar00rootroot00000000000000#!/usr/bin/env python # SPDX-FileCopyrightText: 2018, 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() from setuptools.command.sdist import sdist as SetuptoolsSdist class BuildMakefilesSdist(SetuptoolsSdist): def run(self): os.chdir('man') os.system('make') os.chdir('..') SetuptoolsSdist.run(self) from setuptools.command.build import build as SetuptoolsBuild class BuildMakefilesBuild(SetuptoolsBuild): def run(self): os.chdir('man') os.system('make') os.chdir('..') SetuptoolsBuild.run(self) setup(name = 'pwdsphinx', version = '2.0.3', description = 'SPHINX password protocol', license = "GPLv3", author = 'Stefan Marsiske', author_email = 'sphinx@ctrlc.hu', url = 'https://github.com/stef/pwdsphinx', long_description=read('README.md'), long_description_content_type="text/markdown", packages = ['pwdsphinx', 'pwdsphinx.converters'], install_requires = ("pysodium", "SecureString", "qrcodegen","zxcvbn-python", 'pyequihash', 'pyoprf >= 0.6.0'), 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': [ 'oracle = pwdsphinx.oracle:parse_params', 'sphinx = pwdsphinx.sphinx:main', 'websphinx = pwdsphinx.websphinx:main', 'bin2pass = pwdsphinx.bin2pass:main', 'sphage = pwdsphinx.converters.sphage:main', ], }, cmdclass={'sdist': BuildMakefilesSdist, 'build': BuildMakefilesBuild}, #ext_modules = [libsphinx], ) pwdsphinx-2.0.4/sphinx.cfg_sample000066400000000000000000000102711507247604000171020ustar00rootroot00000000000000# the client section is only needed if you use the client functionality [client] # whether to produce some output on the console #verbose = False # the directory where the client stores its master secret - you might want to # back this up #datadir = ~/.config/sphinx # master password optional for authentication, if it is False it protects # against offline master pwd bruteforce attacks. The drawback is that for known # (host,username) tuples the seeds/blobs can be changed/deleted by an attacker # if the client masterkey is known #rwd_keys=False # stores a check digit of 5 bits in the rule blob, this helps to notice most # typos of the master password, while decreasing security slightly #validate_password=True # userlist enables the maintenance of an encrypted blob of all records # belonging to the same sphinx user (defined by their masterkey) and # hostname. This enables the usage of the `list` command to the client. # if you disable this, you have to remember your usernames in other ways. #userlist=True # if you have still v1 passwords on the server, they get automatically upgraded # to v2 records. If you don't have any clients that can only do v1, then it is # safe and nice to delete the old v1 passwords automatically. If you use for # example androsphinx android client, it only supports v1, so you don't want to # delete the v1 records. Default is false. # delete_upgraded = false # the threshold - must specify at least this many servers in the # [servers] section # threshold = 3 # if you still need to consult a v1 server # address = "127.0.0.1" # port = 2355 # the servers used by the client [servers] # you need at least one server. the name is freely chosen (in this case it is # "first", but should not change, unless you want to lose access to your # existing passwords. [servers.first] # the ip address of the server host="127.0.0.1" # the port where the server is running, 443 is nice to punch through firewalls. port=443 # the long term signature key of the server. ltsigkey="32byteBase64EncodedValue==" # or alternatively if you want to store the raw binary public key in a file # ltsigkey_path = "path/to/ltsigkey.pub" # in case you want to use a threshold version of SPHINX you need at least 3 # servers (and the threshold is then 2) #[servers.2nd] #host="127.0.0.1" #port=2355 #ltsigkey="2nd.pub" # #[servers.3rd] #host="127.0.0.1" #port=5523 #ltsigkey="3rd.pub" # the server section is only needed if you run the oracle yourself. [server] # the ipv4 address the server is listening on #address="127.0.0.1" # the port on which the server is listening, use 443 if available, so that # the oracle can be accessed from behind tight firewalls #port=2355 # ssl key - no default must be specified ssl_key="key.pem" # ssl cert - no default must be specified ssl_cert="cert.pem" # 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 # how many worker processes can run in parallel # max_kids=5 # the root directory where all data is stored #datadir= "/var/lib/sphinx" # whether to produce some output on the console #verbose=false # decay ratelimit after rl_decay seconds #rl_decay= 1800 # increase hardness after rl_threshold attempts if not decaying #rl_threshold= 1 # when checking freshness of puzzle solution, allow this extra # gracetime in addition to the hardness max solution time #rl_gracetime=10 # a path pointing at a long-term signing key. If this file doesn't exist, # you can generate it by running `oracle init`, it will also generate a public # key, which all your clients need to put in their ltsigkey configuration # variable. ltsigkey="ltsig.key" # the websphinx section is only needed if you use the browser webextensions [websphinx] # the path of your pinentry program pinentry=/usr/bin/pinentry # a file where websphinx logs, this is only for dev/debug purposes log= # in case you use webauthn, we need to store mappings between webauthn user ids # and webauthn public keys. it's lame, but no way around it. back up this # directory and sync it to other hosts where you want to use the webextension # with the same webauthn accounts. webauthn_data_dir = "path/to/webauthn/data/dir" pwdsphinx-2.0.4/tests/000077500000000000000000000000001507247604000147105ustar00rootroot00000000000000pwdsphinx-2.0.4/tests/__init__.py000066400000000000000000000000011507247604000170100ustar00rootroot00000000000000 pwdsphinx-2.0.4/tests/cert.pem000066400000000000000000000011131507247604000163440ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIIBhTCCASugAwIBAgIURt1h20rXWGwyV5nuLDp2NBaXsgkwCgYIKoZIzj0EAwIw GDEWMBQGA1UEAwwNc3BoaW54IG9yYWNsZTAeFw0yMDA5MjkyMTI5MDBaFw0yMTA5 MjQyMTI5MDBaMBgxFjAUBgNVBAMMDXNwaGlueCBvcmFjbGUwWTATBgcqhkjOPQIB BggqhkjOPQMBBwNCAATPl01K0Nuxm4wZaYzS4AvaXy4pIG96Zk5XC1o0TmkdnNPb kgSUm6dx1OVvx3u8kVGRHYfgC7C4I414W2v41Hb4o1MwUTAdBgNVHQ4EFgQUtpha TRgMR7SeM7gYPKoq8L874tcwHwYDVR0jBBgwFoAUtphaTRgMR7SeM7gYPKoq8L87 4tcwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAgNIADBFAiEAnN1Y9WDfVW6f slgOnPs8eQdyoqA7S/rFf9wE/ZxR4tECICfCYMKpIRMYPEk2C+kqoJueB/JVdGKh pYxdMvjx8bsj -----END CERTIFICATE----- pwdsphinx-2.0.4/tests/data/000077500000000000000000000000001507247604000156215ustar00rootroot00000000000000pwdsphinx-2.0.4/tests/data/masterkey000066400000000000000000000000401507247604000175420ustar00rootroot00000000000000Zg< hqQJ-pwdsphinx-2.0.4/tests/editor.py000077500000000000000000000002611507247604000165520ustar00rootroot00000000000000#!/usr/bin/env python import sys with open(sys.argv[1], 'r') as fd: data = fd.read() with open(sys.argv[1], 'w') as fd: fd.write('\n'.join(sorted(data.split('\n')))) pwdsphinx-2.0.4/tests/key.pem000066400000000000000000000003431507247604000162030ustar00rootroot00000000000000-----BEGIN EC PRIVATE KEY----- MHcCAQEEIBvDA1MfRSB+jbflO/Db0XkbHWoxHceapqqwdww/nXiHoAoGCCqGSM49 AwEHoUQDQgAEz5dNStDbsZuMGWmM0uAL2l8uKSBvemZOVwtaNE5pHZzT25IElJun cdTlb8d7vJFRkR2H4AuwuCONeFtr+NR2+A== -----END EC PRIVATE KEY----- pwdsphinx-2.0.4/tests/opaque-store.cfg000066400000000000000000000034311507247604000200160ustar00rootroot00000000000000[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 timeout=30 # self-signed public key of the server # - not needed for proper Lets Encrypt certs #ssl_cert = "../../../opaque-store/.arch/test-2of3-setup/0/cert.pem" #ltsigkey="../../../opaque-store/.arch/test-2of3-setup/zero.pub" ssl_cert = "cert.pem" ltsigkey = "data/os_zero.pub" [servers.eins] # address of server host="127.0.0.1" # port where server is running port=23001 timeout=30 # public key of the server #ssl_cert = "../../../opaque-store/.arch/test-2of3-setup/1/cert.pem" #ltsigkey="../../../opaque-store/.arch/test-2of3-setup/eins.pub" ssl_cert = "cert.pem" ltsigkey = "data/os_one.pub" [servers.zwei] # address of server host="127.0.0.1" # port where server is running port=23002 timeout=30 # public key of the server #ssl_cert = "../../../opaque-store/.arch/test-2of3-setup/2/cert.pem" #ltsigkey="../../../opaque-store/.arch/test-2of3-setup/zwei.pub" ssl_cert = "cert.pem" ltsigkey = "data/os_two.pub" pwdsphinx-2.0.4/tests/sphinx.cfg000066400000000000000000000017351507247604000167100ustar00rootroot00000000000000[client] verbose = false datadir = "data/" timeout = 37 rwd_keys = true threshold = 2 validate_password = false # v1 server address="localhost" port=10000 ssl_cert = "cert.pem" delete_upgraded=true [servers] [servers.zero] host="localhost" port=10000 ssl_cert = "cert.pem" ltsigkey_path = "data/zero.pub" timeout = 37 #ssl_cert = "servers/0/cert.pem" #ltsigkey = "servers/0/ltsig.key.pub" [servers.one] host="localhost" port=10001 ssl_cert = "cert.pem" ltsigkey_path = "data/one.pub" timeout = 37 #ssl_cert = "servers/1/cert.pem" #ltsigkey = "servers/0/ltsig.key.pub" [servers.two] host="localhost" port=10002 ssl_cert = "cert.pem" ltsigkey_path = "data/two.pub" timeout = 37 #ssl_cert = "servers/2/cert.pem" #ltsigkey = "servers/0/ltsig.key.pub" #[servers.drei] #host="localhost" #port=10003 #ssl_cert = "cert.pem" #ltsigkey = "data/drei.pub" # #[servers.eris] #host="localhost" #port=10004 #ssl_cert = "cert.pem" #ltsigkey = "data/eris.pub" [websphinx] pinentry="/usr/bin/pinentry" pwdsphinx-2.0.4/tests/start-servers.sh000077500000000000000000000006371507247604000201010ustar00rootroot00000000000000#!/bin/sh ORACLE=${ORACLE:-../../../pwdsphinx/oracle.py} PIDS="" cleanup() { echo killing oracles ${PIDS} kill ${PIDS} exit } start_server() { printf "starting %s %s\n" "$ORACLE" "$1" cd "servers/$1" "$ORACLE" >log 2>&1 & PIDS="$PIDS $!" sleep 0.1 cd - >/dev/null } start_server 0 start_server 1 start_server 2 start_server 3 start_server 4 trap "cleanup" INT while true; do sleep 1 ;done pwdsphinx-2.0.4/tests/test.py000066400000000000000000001073461507247604000162540ustar00rootroot00000000000000import unittest from os import listdir, makedirs, environ, path from shutil import rmtree, copyfile from tempfile import mkdtemp from unittest.mock import Mock from io import BytesIO, StringIO import sys, pysodium, subprocess, time, struct import tracemalloc from pyoprf import multiplexer from pwdsphinx import sphinx, bin2pass, ostore, v1sphinx from binascii import b2a_base64, a2b_base64 import pyoprf, ctypes import contextlib #don't run with -b if you want log output from setup/teardown fns #import logging #logger = logging.getLogger(__name__) # to get coverage, run # PYTHONPATH=.. coverage run ../tests/test.py # coverage report -m # to just run the tests do # python3 -m unittest discover --start-directory ../tests # disable the output of sphinx sphinx.print = Mock() N = 3 data_dir = 'data/' char_classes = 'uld' syms = bin2pass.symbols size = 0 pwd = 'asdf' user = 'user1' user2 = 'user2' host = 'example.com' servers = {'zero': {'host': 'localhost', 'port': 10000, 'ssl_cert': 'cert.pem'}, 'one': {'host': 'localhost', 'port': 10001, 'ssl_cert': 'cert.pem'}, 'two': {'host': 'localhost', 'port': 10002, 'ssl_cert': 'cert.pem'}, 'drei': {'host': 'localhost', 'port': 10003, 'ssl_cert': 'cert.pem'}, 'eris': {'host': 'localhost', 'port': 10004, 'ssl_cert': 'cert.pem'} } corrupt_dkg_lib = environ.get('CORRUPT_DKG_LIB') ostore_server = environ.get('OPAQUESTORE_SERVER') orig_servers=sphinx.servers max_recovery_tokens = 2 ostore_max_fails = 3 import random random.seed() unittest.TestLoader.sortTestMethodsUsing = lambda _, x, y: random.randint(-1,1) class Input: def __init__(self, txt = None, pwd = pwd): 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 def connect(peers=None): if peers == None: peers = dict(tuple(servers.items())[:N]) #m = multiplexer.Multiplexer(peers) m = sphinx.Multiplexer(peers) m.connect() return m def bad_signkey(_, __): pk, sk = pysodium.crypto_sign_seed_keypair(b'\xfe'*pysodium.crypto_sign_SEEDBYTES) return sk, pk get_signkey = sphinx.get_signkey class TestEndToEnd(unittest.TestCase): @classmethod def setUpClass(cls): #libc = ctypes.cdll.LoadLibrary('libc.so.6') #cstderr = ctypes.c_void_p.in_dll(libc, 'stderr') #log_file = ctypes.c_void_p.in_dll(pyoprf.liboprf,'log_file') #log_file.value = cstderr.value cls._validate_password = sphinx.validate_password cls._root = mkdtemp(prefix='sphinx-oracle-root.') root = cls._root pks = [] for idx, k in enumerate(servers.keys()): makedirs(f"{root}/servers/{idx}") copyfile("cert.pem", f"{root}/servers/{idx}/cert.pem") copyfile("key.pem", f"{root}/servers/{idx}/key.pem") pk, sk = pysodium.crypto_sign_keypair() with open(f"{root}/servers/{idx}/ltsig.key", 'wb') as fd: fd.write(sk) servers[k]['ltsigkey']=pk if k in sphinx.servers: sphinx.servers[k]['ltsigkey']=pk sphinx.servers[k]['timeout']=30 # for reproducability, in case we want to run manual sphinx ops with open(f"data/{k}.pub",'wb') as fd: fd.write(pk) with open(f"{root}/servers/{idx}/sphinx.cfg", 'w') as fd: fd.write(f'[server]\n' f'verbose = true\n' f'address = "127.0.0.1"\n' f'port={10000+idx}\n' f'timeout = 30\n' f'max_kids = 5\n' f'ssl_key= "key.pem"\n' f'ssl_cert= "cert.pem"\n' f'ltsigkey = "ltsig.key"\n' f'datadir = "data"\n' f'rl_decay=1800\n' f'rl_threshold=10\n') cls._oracles = [] env = environ for idx in range(len(servers)): log = open(f"{root}/servers/{idx}/log", "w") if idx == N and corrupt_dkg_lib is not None: print(f"enabling byzantine peers {corrupt_dkg_lib}", file=log) env["BYZANTINE_DKG"]=corrupt_dkg_lib cls._oracles.append( (subprocess.Popen(["python3", path.dirname(path.abspath(sphinx.__file__)) + "/oracle.py"], cwd = f"{root}/servers/{idx}/", stdout=log, stderr=log, pass_fds=[log.fileno()], env=env), log)) log.close() if "BYZANTINE_DKG" in env: del env["BYZANTINE_DKG"] if ostore.available and ostore_server is not None and path.isfile(ostore_server): cls._ostore_root = mkdtemp(prefix='opaquestore-server-root.') root = cls._ostore_root pks = [] for idx in range(len(servers)): makedirs(f"{root}/servers/{idx}") copyfile("cert.pem", f"{root}/servers/{idx}/cert.pem") copyfile("key.pem", f"{root}/servers/{idx}/key.pem") pk, sk = pysodium.crypto_sign_keypair() with open(f"{root}/servers/{idx}/ltsig.key", 'wb') as fd: fd.write(sk) #pks.append(b2a_base64(pk).decode("utf8")[:-1]) pks.append(pk) with open(f"{root}/servers/{idx}/opaque-stored.cfg", 'w') as fd: fd.write(f'[server]\n' f'verbose = true\n' f'address = "127.0.0.1"\n' f'port={23000+idx}\n' f'timeout = 30\n' f'max_kids = 5\n' f'ssl_key= "key.pem"\n' f'ssl_cert= "cert.pem"\n' f'ltsigkey = "ltsig.key"\n' f'record_salt = "some random string to salt the record ids"\n' f'max_blob_size = 8192\n' f'max_recovery_tokens = {max_recovery_tokens}\n' f'max_fails = {ostore_max_fails}\n' f'datadir = "data"\n\n') # lt sig pubkeys for idx in range(len(servers)): for pk, name in zip(pks, servers.keys()): with open(f"data/os_{name}.pub",'wb') as fd: fd.write(pk) for idx in range(len(servers)): log = open(f"{root}/servers/{idx}/log", "w") cls._oracles.append( (subprocess.Popen([ostore_server], cwd = f"{root}/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() #rmtree(cls._root) time.sleep(0.4) def tearDown(self): sphinx.validate_password=self._validate_password time.sleep(3) sphinx.servers = orig_servers #cleanup() roots = [self._root] if hasattr(self, '_ostore_root'): roots.append(self._ostore_root) for idx in range(len(servers)): for root in roots: ddir = f"{root}/servers/{idx}/data/" if not path.exists(ddir): continue for f in listdir(ddir): if f == 'key': continue rmtree(ddir+f) def test_create_user(self): with connect() as s: self.assertIsInstance(sphinx.create(s, pwd, user, host, char_classes, syms, size), str) def test_huge_user(self): if sphinx.userlist == False: return with connect() as s: self.assertRaises(ValueError, sphinx.create,s, pwd, 'a'*(2**16 - 40), host, char_classes, syms, size) with connect() as s: rwd=sphinx.create(s, pwd, 'a'*(2**16 - 42), host, char_classes, syms, size) self.assertIsInstance(rwd, str) with connect() as s: self.assertRaises(ValueError, sphinx.create, s, pwd, 'a', host, char_classes, syms, size) def test_rules_u(self): with connect() as s: rwd = sphinx.create(s, pwd, user, host, "u", '', 0) self.assertIsInstance(rwd, str) self.assertTrue(rwd.isupper()) def test_rules_l(self): with connect() as s: rwd = sphinx.create(s, pwd, user, host, "l", '', 0) self.assertIsInstance(rwd, str) self.assertTrue(rwd.islower()) def test_rules_d(self): with connect() as s: rwd = sphinx.create(s, pwd, user, host, "d", '', 0) self.assertIsInstance(rwd, str) self.assertTrue(rwd.isdigit()) def test_rules_ulsd(self): with connect() as s: rwd = sphinx.create(s, pwd, user, host, char_classes, syms, 0) self.assertIsInstance(rwd, str) self.assertTrue(len(set([x.decode('utf8') for x in bin2pass.sets['u']]).intersection(rwd)) > 0) self.assertTrue(len(set([x.decode('utf8') for x in bin2pass.sets['l']]).intersection(rwd)) > 0) self.assertTrue(len(set([x.decode('utf8') for x in bin2pass.sets['d']]).intersection(rwd)) > 0) self.assertTrue(len(set(bin2pass.symbols).intersection(rwd)) > 0) def test_pwd_len(self): for i in range(1,32): with connect() as s: rwd = sphinx.create(s, pwd, user, host, char_classes, syms, i) self.assertIsInstance(rwd, str) self.assertTrue(len(rwd)==i) with connect() as s: self.assertTrue(sphinx.delete(s, pwd, user, host)) def test_invalid_rules(self): with connect() as s: self.assertRaises(ValueError, sphinx.create, s, pwd, user, host, "asdf", syms, size) def test_recreate_user(self): with connect() as s: self.assertIsInstance(sphinx.create(s, pwd, user, host, char_classes, syms, size), str) with connect() as s: self.assertRaises(ValueError, sphinx.create,s, pwd, user, host, char_classes, syms, size) s.close() def test_get_nonexistant_record(self): for i in [0, 1,2]: try: makedirs(f"{self._root}/servers/{i}/data/") except: pass with connect() as s: self.assertRaises(ValueError, sphinx.get, s, pwd, user, host) def test_get(self): with connect() as s: rwd0 = sphinx.create(s, pwd, user, host, char_classes, syms, size) self.assertIsInstance(rwd0, str) with connect() as s: rwd = sphinx.get(s, pwd, user, host) self.assertIsInstance(rwd, str) self.assertEqual(rwd,rwd0) def test_v1get(self): if not v1sphinx.enabled: return # synthetically create a v1 record id = v1sphinx.getid(host,user) for i in [1,2]: try: makedirs(f"{self._root}/servers/{i}/data/") except: pass ddir = f"{self._root}/servers/0/data/{id.hex()}" k = b'\x55' * 32 #calculate rwd h0 = pysodium.crypto_generichash(pwd.encode(), outlen=pysodium.crypto_core_ristretto255_HASHBYTES); H0 = pysodium.crypto_core_ristretto255_from_hash(h0) H0_k = pysodium.crypto_scalarmult_ristretto255(k, H0) rwd0 = pysodium.crypto_generichash(pwd.encode()+H0_k, outlen=pysodium.crypto_core_ristretto255_BYTES); rwd0 = pysodium.crypto_pwhash(pysodium.crypto_core_ristretto255_BYTES, rwd0, id[:pysodium.crypto_pwhash_SALTBYTES], pysodium.crypto_pwhash_OPSLIMIT_INTERACTIVE, pysodium.crypto_pwhash_MEMLIMIT_INTERACTIVE) # create a rules blob if sphinx.validate_password: check_digit = pysodium.crypto_generichash(v1sphinx.CHECK_CTX, rwd0, 1)[0] else: check_digit = 0 xor_mask = b'\x55' * 32 packed = 30 packed = packed + (sum(1< () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) class TestRules(unittest.TestCase): def test_rules(self): for cls in powerset('uld'): equ(''.join(cls), bin2pass.symbols, 64, 31, b'\x00'*64) if cls!=tuple(): equ(''.join(cls), '', 64, 31, b'\x00'*64) equ('uld', bin2pass.symbols[:16], 64, 31, b'\x00'*64) equ('uld', bin2pass.symbols[16:], 64, 31, b'\x00'*64) equ('uld', bin2pass.symbols, 64, 31, b'\xff'*64) equ('uld', bin2pass.symbols, 64, 31, b'\xaa'*64) for i in range(128): equ('uld', bin2pass.symbols, i, 31, b'\xaa'*64) for i in range(32): equ('uld', bin2pass.symbols, 64, i, b'\xaa'*64) if __name__ == '__main__': unittest.main() pwdsphinx-2.0.4/tests/tests.sh000077500000000000000000000042551507247604000164170ustar00rootroot00000000000000#!/bin/bash -e hash() { md5sum | { read md5 rest; echo $md5; } } [[ -d data ]] || { echo no data directory found echo please start ../pwdsphinx/oracle.py exit 1 } echo "create user1" rwd0="$(echo -n 'asdf' | ../pwdsphinx/sphinx.py create user1 example.com ulsd)" echo "get user1 rwd" rwd="$(echo -n 'asdf' | ../pwdsphinx/sphinx.py get user1 example.com)" [[ "$rwd" == "$rwd0" ]] || false echo "change user1 rwd" rwd1="$(echo -ne 'asdf\nasdf' | ../pwdsphinx/sphinx.py change user1 example.com)" echo "get user1 rwd" rwd="$(echo -n 'asdf' | ../pwdsphinx/sphinx.py get user1 example.com)" [[ "$rwd" == "$rwd0" ]] || false echo "commit user1 changed rwd" echo -n 'asdf' | ../pwdsphinx/sphinx.py commit user1 example.com rwd="$(echo -n 'asdf' | ../pwdsphinx/sphinx.py get user1 example.com)" [[ "$rwd" == "$rwd1" ]] || false echo "undo user1" echo -n 'asdf' | ../pwdsphinx/sphinx.py undo user1 example.com rwd="$(echo -n 'asdf' | ../pwdsphinx/sphinx.py get user1 example.com)" [[ "$rwd" == "$rwd0" ]] || false echo "commit again user1 changed rwd" echo -n 'asdf' | ../pwdsphinx/sphinx.py commit user1 example.com rwd="$(echo -n 'asdf' | ../pwdsphinx/sphinx.py get user1 example.com)" [[ "$rwd" == "$rwd1" ]] || false rwd0="$rwd1" echo "commit user1 changed rwd again - fail" echo -n 'asdf' | ../pwdsphinx/sphinx.py commit user1 example.com || true echo "get user1 rwd" rwd="$(echo -n 'asdf' | ../pwdsphinx/sphinx.py get user1 example.com)" [[ "$rwd" == "$rwd0" ]] || false echo "create user2 rwd" rwds0="$(echo -n 'asdf' | ../pwdsphinx/sphinx.py create user2 example.com ulsd)" echo "get user2 rwd" rwds="$(echo -n 'asdf' | ../pwdsphinx/sphinx.py get user2 example.com)" [[ "$rwds" == "$rwds0" ]] || false echo "list users rwd" md5="$(echo -n 'asdf' | ../pwdsphinx/sphinx.py list example.com | hash)" [[ "$md5" == "57c246efc4d56f6210462408b5f8ef2e" ]] echo "delete user2 rwd" echo -n 'asdf' | ../pwdsphinx/sphinx.py delete user2 example.com echo "list users rwd" md5="$(echo -n 'asdf' | ../pwdsphinx/sphinx.py list example.com | hash)" [[ "$md5" == "a609316768619f154ef58db4d847b75e" ]] echo "get user2 rwd - fail" echo -n 'asdf' | ../pwdsphinx/sphinx.py get user2 example.com || true echo "all tests passed" pwdsphinx-2.0.4/tests/ws-test.py000077500000000000000000000016701507247604000166770ustar00rootroot00000000000000#!/usr/bin/env python import struct, json, sys, subprocess if sys.argv[1]=="get": msg = {'cmd': "login"} else: msg = {'cmd': sys.argv[1]} if sys.argv[1] in ('create', 'get', 'change', 'commit', 'undo', 'delete'): msg['name']= sys.argv[2] msg['site']= sys.argv[3] if sys.argv[1] in {'create', 'change'}: msg['rules']= sys.argv[4] msg['size']= sys.argv[5] if sys.argv[1] == 'list': msg['site']= sys.argv[2] msg['mode'] = 'ws-test' if sys.argv[1] == 'json': msg = sys.argv[2].replace("'", '"') else: msg = json.dumps(msg) print("cmd:", msg) cmd = struct.pack('i', len(msg))+msg.encode("utf-8") proc=subprocess.Popen(["../pwdsphinx/websphinx.py"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = proc.communicate(input=cmd) print("ret", proc.returncode) print("stdout") for line in out.split(b'\n'): print(line) print("stderr") for line in err.split(b'\n'): print(line) pwdsphinx-2.0.4/whitepaper.org000066400000000000000000001514671507247604000164450ustar00rootroot00000000000000* The Extended Sphinx Protocol SPHINX is a beautiful protocol for password storage querying and inserting of exactly one password. However in a real-life scenario users want to store more than one password, or sometimes user want to change the password or delete it. Users might have more than one account at a site and users do not want to remember the list of user names, nor do they want to synchronize them over all of their devices. These are some things that SPHINX does not provide. Hence it is necessary to extend the original SPHINX protocol. ** Terminology *** Sphinx Records Records are data structures stored at the sphinx server which contain all the necessary information to provide a user with means to query and manage passwords. *** User User is the human attempting to manage its passwords. *** Service A service is some interface where the user wants to login. *** Account An account is a combination of a username and a password authenticating a user at a service. *** Account password An account password is the password that authenticates the user with a service. It is derived from the SPHINX key in a way that makes the output compatible with the password rules mandated by the service. *** rwd (Random word) High entropy 64 bytes derived from the SPHINX protocol by calculating: argon2i(hash(pwd||hash2curve(pwd)*k),salt), where k is a server seed contributed by the sphinx server. *** Master Password The master password is the password which is used in SPHINX to query and derive the account password for a service. Unlike other password managers it is possible with sphinx to have multiple master passwords, since they are not used to open an encrypted database but only contribute to the derivation of the rwd. *** Client Master-key A client master-key is a key shared by all devices of a user which access and manage their SPHINX records on a server. *** Core functions The two core functions that are defined by SPHINX are initialize SPHINX record and query SPHINX. *** Initialize SPHINX record This core SPHINX function creates new record at the server for later usage, this is what you want to run when registering a new users at a service. *** Query SPHINX This core SPHINX function queries the SPHINX server (oracle) which has an associated record previously setup by the other SPHINX core function Initialize SPHINX record. *** Management functions A password manager has other functions besides creating and querying them, such functions are deletion of accounts, changing of account passwords, committing a changed password, undoing a commit to the previous password, listing usernames associated with a host. ** Core Sphinx Protocol This is a simplified description of the protocol, for a full academic papers including security proofs, please see: https://eprint.iacr.org/2015/1099 "Device-Enhanced Password Protocols with Optimal Online-Offline Protection" by Stanislaw Jarecki, Hugo Krawczyk, Maliheh Shirvanian, and Nitesh Saxena. And additionally: https://eprint.iacr.org/2018/695 "SPHINX: A Password Store that Perfectly Hides Passwords from Itself" by Maliheh Shirvanian, Stanislaw Jarecki, Hugo Krawczyk, and Nitesh Saxena The underlying cryptographic primitive (the 2hashDH OPRF) has been rigorously specified by the IRTF/CFRG as RFC9497: https://datatracker.ietf.org/doc/rfc9497/ The most essential operation in the Extended Sphinx Protocol is the Sphinx query. This is the basis for all other operations in the protocol - the only exception being the READ operation. Let's recap how the SPHINX query works: 1. The user hashes their password and then blinds it using the blinding factor `r`, the resulting alpha value is passed to the server. #+BEGIN_SRC r = random(32) alpha = (r * hash(pwd)) #+END_SRC The * operation denotes scalar multiplication over an elliptic curve like curve 25519. Our concrete implementation uses ristretto255. It's also worth noting, that the hash operation here is really a hash-to-curve operation. 2. The server has a secret seed (aka key) which it contributes into the blinded hash of the users password: #+BEGIN_SRC beta = seed * alpha #+END_SRC The server returns the calculated beta value to the client. 3. The user unblinds the servers output (beta) #+BEGIN_SRC pwd_k = 1/r * beta #+END_SRC and hashes it again with the master password, which results in the rwd: #+BEGIN_SRC rwd = hash(pwd, pwd_k) #+END_SRC So far this is regular a regular generic OPRF, as specified by RFC9497 and implemented by liboprf. For a final hardening step SPHINX applies a final argon2i password hash over the rwd, using the user, host, and client master key as a secret: #+BEGIN_SRC rwd = argon2i(rwd,hash(salt_ctx,master_key) | len(user) | user | len(host) | host) #+END_SRC With this final step in our implementation `rwd` results in a high entropy array of 64 bytes. ** Threshold SPHINX protocol v2.0 of SPHINX supports a threshold variant. This further lowers the trust needed in individual SPHINX servers, and greatly improves on robustness and reliability of SPHINX. Instead of one server an attacker must compromise t+1 (threshold) servers to have access to the secret seed from the non-threshold version of SPHINX. Furthermore the threshold setup allows for much greater robustness, there is no single-point-of-failure anymore, if a server is unavailable others can take its role. The threshold variant makes backups possible. By running a number of threshold SPHINX servers by the user themselves, the shares held by those servers can be stored offline and recovered in case all the public servers are unavailable. The following is a simplified description of the protocol used for threshold-SPHINX, for a full academic paper with security proofs see https://eprint.iacr.org/2017/363 "TOPPSS: Cost-minimal Password-Protected Secret Sharing based on Threshold OPRF" by Stanislaw Jarecki, Aggelos Kiayias, Hugo Krawczyk, and Jiayu Xu Quote from the TOPPSS paper (slightly edited for text-representation): #+BEGIN_QUOTE The underlying PRF, f_k(x) = H"(x, (H'(x))^k), remains unchanged, but the key k is shared using Shamir secret-sharing across n servers, where server S_i stores the key share k_i. [...] For evaluation, given any subset SE of t+1 servers, the user U sends to each of them the same message a = (H'(x))^r for random r, exactly as in the single-server OPRF protocol 2HashDH. If each server S_i in SE returned bi = a^k_i then U could reconstruct the value a^k using standard Lagrange interpolation in the exponent, i.e. a_k = Π b_i^λ_i, i∈SE with the Lagrange coefficients λ_i computed using the indexes of servers in SE. After computing a^k, the value of f_k(x) is computed by U by deblinding a_k exactly as in the case of protocol 2HashDH. #+END_QUOTE For the distributed key-generation (DKG) for the creation and change of records operations SPHINX uses the Trusted Party DKG as provided and specified by liboprf at https://github.com/stef/liboprf/blob/master/docs/tp-dkg.txt The domain separator for create type DKG is: "threshold sphinx dkg create k", for update type DKG it is: "threshold sphinx dkg change k" DKG Cheaters MUST be identified and reported to the user. *** Keys and Beta values To be able to calculate the correct Lagrange coefficients in the threshold setup the client needs to know the index of the beta values. The servers have to store their index in a threshold setup next to the key-share they hold. Thus the key is stored in the following format: #+BEGIN_EXAMPLE +--------+------------+ | 1 byte | 32 bytes | +--------+------------+ | index | key | +--------+------------+ #+END_EXAMPLE Similarly the beta value that is the response sent back to the client, based on the key needs to include this index, and thus has the same format as the key: 1 byte for the index, 32 bytes for the beta value. For keys and beta values used in a non-threshold setting, this value SHOULD be 1. Valid values for the index are between 1..128 inclusive, anything else is invalid, and MUST be rejected by the client and/or server. *** Unlinkable records In the threshold variant the client interacts with multiple servers, and thus the protocol needs to store all relevant information (password rules and authentication keys) on all of them. It is a desirable security property to have all related records on all the servers to be unlinkable. Just like all the records belonging to the same user are unlinkable (if the userlist feature is disabled) in the non-threshold variant, having the records belonging to the same account on the threshold servers provides an extra cost multiplier for any attacker having access to multiple leaked threshold SPHINX databases. Since all the records are unlinkable, an attacker must be test all possible combinations of records if they want to reconstruct any secret SPHINX key. And even if they are able to do so, all they managed is to reduce the security of the threshold variant to the security of the non-threshold variant in this case. Unlinkable records thus create another obstacle for attackers that is essentially a combinatorial explosion. Besides the shares that are stored on the servers, the servers also store the public authentication key for management operations. This key is unique for all servers and records, this is achieved by including servers name in the record ID (see below for details), as all servers have different names so will all record IDs be different. The other data that all servers need to store are the password rules. These are encrypted, all with the same key, but with MUST use different nonces, and thus should also be unlinkable. *** Threshold Management Operations Management operations (change, delete, commit, undo) MUST operate on all shares, otherwise they become desynchronized and lead to inconsistencies and failure to recover passwords. * The Extended Sphinx Protocol Details In the following sections we specify our extensions we added to the core Sphinx Protocol and why we did so. ** Password rules The output of the core sphinx protocol (at least in our instantiation) is an array of 64 random bytes. Most services are not expecting binary data (although they should!) and the worse ones even have some rules of what kind of character classes to expect or forbid, or how long the password should be. In order to store these per-service password rules without having to sync this across different devices used by a user we store these per-service password rules on the sphinx server. We extended the core Sphinx Protocol by having the server send along the password rules together with the beta value at the end of step two of the core sphinx protocol - so that the client can derive the correct password. Rules are compacted in the following way: #+BEGIN_EXAMPLE |---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---| | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | a | b | c | d | e | f | |---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---| | password size | U | L | D |' '| ! | " | # | $ | % | |---------------------------+---+---+---+---+-------------------| |---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---| |10 |11 |12 |13 |14 |15 |16 |17 |18 |19 |1a |1b |1c |1d |1e |1f | |---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---| | & | ' | ( | ) | * | + | , | - | . | / | : | ; | < | = | > | ? | |---------------------------+---+---+---+---+-------------------| |---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---| |20 |21 |22 |23 |24 |25 |26 |27 |28 |29 |2a |2b |2c |2d |2e |2f | |---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---| | @ | [ | \ | ] | ^ | _ | ` | { | | | } | ~ | check-digit | |---------------------------+---+---+---+---+-------------------| and a 64 byte long xor mask. #+END_EXAMPLE The longest password we can derive out of 64 bytes, is 155 chars long if only digits are allowed, but maximum 109 for only lower-case or upper-case letters only, and max 86 chars for all alphanumerical characters. Thus 7 bits are enough to encode the size of a password, if you really need to store an all-numeric password that is longer than 128 chars, you might want to review the reasons for this... The bits 7-9 encode the character classes: upper-case, lower-case, digits. Bits 0xa - 0x2a are a boolean array storing if a particular symbol is allowed or not. *** Check digit The check-digit is a 5 bit number that is used as a simple check if the derived password is correct or not. There is a 1/32 chance that a wrong password goes on undetected. The check-digit is calculated as such: #+BEGIN_SRC check-digit = blake2b("sphinx check digit context", rwd, 1)[0] & 0x1f #+END_SRC *** rwd to ASCII conversion The conversion from the 64 byte array to an ASCII printable string containing only the characters allowed by the rules interprets the 64 bytes as an integer in big-endian order and then encodes it base-n, where n is the number of characters allowed by the rules. The digits are in the order - if allowed -: upper-case, lower-case, digits, and the symbols in the order as they are listed in the compacted rules blob. In pseudo-code: #+BEGIN_SRC python v = int.from_bytes(rwd, 'big') result = '' while (size > 0 and len(result) < size) or (size == 0 and v > 0): idx = v % len(chars) v //= len(chars) result = chars[idx] + result return result #+END_SRC *** RWD Xor Masks and Pre-defined Account Passwords Since the conversion from the binary rwd to the ASCII account password is simple arithmetic it is also possible to reverse. This allows us to calculate the binary rwd that SPHINX should output in order to generate a specified password. It is however not possible do actually make SPHINX output this value directly. In order to allow certain non-random pre-defined passwords to be output by SPHINX we xor the rwd with the xor mask from the rules blob. Normally the xor mask is also totally random, and thus the output of the SPHINX query is thus also totally random. If the user specifies a pre-defined password during Create or Change operations, we first calculate backwards the target rwd that would produce that pre-defined output, and then we xor this target-rwd with the rwd of the SPHINX query and store the result in the xor mask. It is important to notice, that the maximum length of such pre-definied output passwords is maximum 77 characters long. __Warning__ this mode generates passwords that violate the security guarantees of the SPHINX protocol and should be avoided if possible. This mode only exists as a convience function and as such is a perfect example of convenience weakening security. Converting a base-n number back into an rwd is as simple as the following example pseudo-code: #+BEGIN_SRC python le_str = string[::-1] result = sum(chars.find(le_str[i]) * len(chars)**i for i in range(len(le_str))) return int.to_bytes(result, 64, 'big') #+END_SRC Xor masks (can) have another purpose, they can ensure that in fact all character classes requested in the rules are actually satisfied. When a create or change operation generates a new password that does not satisfy all rules, then randomly choosing a new xor mask until all rules are satisfied can quickly and transparently guarantee that all rules are satisfied. This is quicker than requesting the server (or running a full DKG again) to generate a new seed. However this SHOULD only be applied at account passwords that are longer than 8, otherwise the different character class rules can introduce a bias that makes it slightly easier to bruteforce the account password. ** Encrypted blobs Although Password Rules contain little information, we decided to keep them confidential from the server, some special combination of rules might leak information regarding which service this password authenticates to. The symmetric encryption key (aka sealkey) for blobs - used for protecting password rules and user records (see later) - is derived from the client master-key (see below) as follows: #+BEGIN_SRC enc_key = blake2b("sphinx encryption key", masterkey) #+END_SRC Encryption/decryption of blobs is done using `crypto_aead_xchacha20poly1305_ietf_encrypt()`. Thus all encrypted blobs are prefixed with a 24 bytes nonce and extended with a 16 bytes authentication tag. Blobs are prepended with an authenticated but unencrypted version byte. The value 0x00 is representing v1 records, and the value 0x01 is representing v2 records, the most important difference between these two is that v2 records have 64 byte xormasks instead of 32 bytes as used by v1 records. ** The client master-key As mentioned in the previous "Encrypted blobs" section the sealkeys are derived from a client master-key. Although SPHINX itself is a protocol which does not require any state stored at the client. It lends itself to use SPHINX itself to authenticate any management operation. Unfortunately this means that the server would be able to mount offline bruteforce attacks against the master password, and hence it is not possible to use SPHINX to authenticate with a SPHINX server directly without throwing out one of the most important security guarantees of the SPHINX protocol. A possible solution is to introduce state in the client, which can be used to create a simple and boring-crypto wrapper around SPHINX, and it also helps solve a few other challenges. We decided for this solution and thus our Extended Sphinx Protocol requires a master-key at the client. This key must be synched to other devices that belong to the same user in case the user wants to use the same accounts on multiple devices. This master-key can (and should) be backed up by the user to provide access to their passwords and to be able to manage them. It is important to note that the passwords themselves to not depend in any way on this master-key. The master-key is only used for generating the record IDs, to derive authentication keys for management operations and to generate encryption keys for the encryption of user and rules blobs. For more information on what the loss of confidentiality of this master-key means see our section: Bruteforce attacks against our Sphinx implementation. ** Record IDs In order to store different accounts, we need to be able to refer to them somehow. Record IDs should be calculated by the client in the following way: #+BEGIN_EXAMPLE id_key = blake2b("sphinx host salt", masterkey) id = blake2b(user||host||sphinx server name, id_key) #+END_EXAMPLE The id_key is necessary to prohibit guessing IDs and pre-computation dictionary attacks against these ids. This way of generating record ids should also protect against phishing as long as the hostname is directly taken from the URL-bar, it should not match the correct hostname, and thus the protocol will fail because no appropriate record is found. The lack of a record where you expect one is also a warning-sign for being phished. The inclusion of the SPHINX server name in the hash of the ID ensures that the ID is unique depending on the server it belongs to. This makes the records unlinkable across servers, which is especially useful in case of a threshold SPHINX setup. An attacker having access to t threshold servers records will be unable to know which record on each of the compromised servers belongs to the same ID and thus can be used to reassemble a record, forcing the attacker to bruteforce- combine also the shares. ** Authentication The following management operations require authentication: Change, Change DKG, Commit, Undo, Delete, Read. Authentication always starts with a basic Sphinx query, so that in case the client uses Authentication-keys with master passwords (see above) it can derive the correct key depending on the master password. Since this is always executed the server does not learn which kind of authentication key method the client uses. When the server sends back the `beta` value from it's part of the Sphinx query, it also sends along a random nonce to the client. The client derives its authentication key, and signs the original request concatenated with the nonce, then sends back the signature to the server. #+BEGIN_SRC python sig = detached_sign(privkey, (op+id+alpha+nonce)) #+END_SRC Note, for READ operations there is no alpha value, and thus the signed payload is only ~op+id+nonce~. The server takes the authentication public key from the Sphinx record and verifies the signature over the the original request and the nonce with this authentication public key. If this verification fails, the server aborts, otherwise it resumes control to the management operation requested. ** Authentication keys for management operations Management operations change the records stored at the sphinx server, these need to be somehow authenticated to prevent denial of service for legitimate users. The following operations are authenticated: Change, Commit, Undo, Delete, Userlist Updates to user records need to be signed with the private key for which the corresponding pub key is already stored at the user record. Our protocol provides two authentication mechanisms, one requiring knowledge of the master password for a record, the other one only requires knowledge of the client secret. Both have their benefits and drawbacks. If the authentication succeeds the server responds with a message "auth" prefixed with the big-endian 16 bit length: '\x00\x04auth' In case of failure the token is "fail" and similarly prefixed with the length: '\x00\x04fail'. *** Authentication-keys without master passwords If the rwd_keys configuration option is set to false, management operations are authenticated in the following way: When creating a new record, the client sends along a unique pubkey, that is used to authenticate all later management operations. The pubkey is generated as such: #+BEGIN_SRC key0 = blake2b("sphinx signing key", masterkey) seed = blake2b(key0, id) pk, sk = ed25519_keypair(seed) #+END_SRC The parameter id used to calculate key1 is the record id, we use this to derive unique keys for each record that cannot be linked to other keys derived from the same master key. Note that the use of the `id` parameter, and the fact that the calculation of it also utilizes the name of the SPHINX server results in unique keys for the same record across all threshold SPHINX servers. This means that also the authentication public keys are unlinkable not only across users and records, but also servers. Drawback of this method is that anyone with the master key can enumerate accounts at the sphinx server and run authenticated management operations against them. However in this case the attacker neither learns the master nor the account password, this can only be used to cause a denial of service by deleting the record or changing the server seed. *** Authentication-keys with master passwords If the configuration option rwd_keys is enabled, then the rwd is also added to the key: #+BEGIN_SRC key0 = blake2b("sphinx signing key", masterkey) key1 = blake2b(key0, id) seed = blake2b(key1, rwd) pk, sk = ed25519_keypair(seed) #+END_SRC The rwd is the raw output of the SPHINX protocol, and by mixing it into the authentication key we make sure only users knowing the master password can execute management operations. Note again that due to the inclusion of the ID and it being dependent on the SPHINX server name, this key is also unique across all servers and records, making them unlinkable. The drawback of this authentication method is that this allows anyone with the authentication public key, the sphinx seed (both of which are on the server) and the client master key to mount an offline bruteforce attack against the master password. ** Sphinx Records Sphinx records are referenced by the record ID. All Sphinx Records stored at the sphinx server have the following three components: - the sphinx seed (aka OPRF key) - authentication public key - encrypted password rules The seed (also referred to as simply the - OPRF - "key"), is the secret component which during the Sphinx Query is contributed by the server to the final rwd. In v2 this is a 33 byte array, with the first byte denoting the index of the share in the threshold setup, if this is a key for a non-threshold setup this value is 1. The index byte can only have valid values 1..128 inclusive, other values are invalid. The remaining 32 bytes are the ristretto255 scalar value, that is used as the key in the OPRF for the server-side evaluation. The authentication public key is a unique ed25519 key used to authenticate management operations on this record. The encrypted password rules are also unique due to the unique nonce used on each server in case of a threshold SPHINX setup. ** User records A convenience function by password managers is to offer the user the list of usernames known by the manager when logging into a site. While not strictly necessary, it is a feature that users expect. In our extended protocol we provide a special kind of record, which we call user records, these are encrypted blobs, which contain a list of usernames. The record id for these records is generated as normal records, with the user component provided as an empty string. Clients might opt to not use User records, if this is not desired, then during any protocol run that accesses user records, the client SHOULD send a record ID of all zeros, and the server will skip user record handling. Our extended protocol provides a READ primitive to fetch these blobs, however writing these blobs is only possible implicitly through the CREATE and DELETE sphinx record management operations. It is of course possible to create some bogus SPHINX entry, just to store some "secret" instead of a username in the user record, but the protection of these records is not very strong, there are countless better methods to do so. The usernames in these records a separated by 0x0 bytes, and the whole record cannot be bigger than (64KB - 40) bytes - the 40 bytes are reserved for the nonce and authentication tag of encrypted blobs. Furthermore these user records are prefixed by their length in 2 bytes network order, but these two bytes do not count towards the maximum size of the user record. The structure of these encrypted user record blobs thus looks like this: #+BEGIN_EXAMPLE +--------------+----------+------------+--------------------+ | 2 bytes | 24 bytes | n bytes | 16 bytes | |--------------+----------+------------+--------------------| | size of blob | nonce | ciphertext | authentication tag | +--------------+----------+------------+--------------------+ #+END_EXAMPLE ** The Extended Sphinx Protocol Messages The following operations make up the extended protocol: - Create: create a new record - Create DKG: create a new threshold SPHINX record by running a DKG - Get: query a record - Change: change the seed and update the password rules and auth pubkey associated with the record - Change DKG: change the record in a threshold setup by running a DKG - Commit: activate the changed seed, password rules and auth pubkey, saving a backup copy of the previous values - Undo: restore the backup seed, password rules and auth pubkey activated by a Commit operation. - Delete: delete a record - Read: query the list of registered users with a host The user needs a client master-key and their master password to successfully address records and to authenticate management operations. ** Initial messages All initial messages (except the `read`, `create` and `*_dkg` operations) sent from the client to the server have the same structure: #+BEGIN_SRC u8 ratelimit_opcode u8 opcode u8 id[32] u8 alpha[32] #+END_SRC All operations - except the create and the create dkg operations - are subject to ratelimiting, and the initial message is part of the puzzle that must be solved, before the operation can be processed. For the create operations there is no ratelimit and hence the initial message for `create` and `create_dkg` operations lacks the first `ratelimit_op` field. The `create_dkg` operation has one extra field, the DKG message 0: #+BEGIN_SRC u8 opcode = 0xf0 u8 id[32] u8 alpha[32] u8 msg0[177] #+END_SRC Since there is no rwd necessary - only the client master-key - for querying the user list the initial message of the read operation is lacking the last `alpha` member. The ratelimit_opcodes are the following: #+BEGIN_SRC CHALLENGE_CREATE = 0x5a CHALLENGE_VERIFY = 0xa5 #+END_SRC Here `CHALLENGE_CREATE` requests a new ratelimiting challenge, and `CHALLENGE_VERIFY` presents a solution. For more information on ratelimiting see the dedicated chapter below. The opcodes for the messages are the following: #+BEGIN_SRC CREATE = 0x00 READ = 0x33 UNDO = 0x55 GET = 0x66 V1GET = 0x69 COMMIT = 0x99 CHANGE_DKG = 0xa0 CHANGE = 0xaa CREATE_DKG = 0xf0 V1DELETE = 0xf9 DELETE = 0xff #+END_SRC The `id` member of the message is the record ID as specified above, and the `alpha` value is the hashed and blinded master password as required by the sphinx Protocol. ** TLS All messages between the client and the sphinx server are conducted over a TLS connection. The original SPHINX protocol was supposed to not need any extra encryption - since the blinding itself already provides confidentiality. However already the fact that the sphinx records need to be indexed by some identifier break this nice property of the original SPHINX protocol. Using TLS provides confidentiality against passive attackers collecting statistics about which IDs are being used. ** Management Operations *** Creation of records Creation of a record is a quite straight-forward matter: 1. The client initiates a CREATE operation on the server - including a run of the SPHINX Query (see above), but the server instead of loading a sphinx seed (which doesn't exist yet) just generates one randomly or engages in a TP-DKG with all other servers in case of a threshold configuration. 2. The client derives the encryption and authentication key. The password rules are encrypted and appended to the authentication public key. The auth pubkey and the encrypted rules are signed with the auth private key and sent to the server 3. If the userlist feature is enabled the client updates the user record (see below) for this host, requesting the current user record or the all-null record to signal skipping of this step if userlists are disabled by the client. If userlists are enabled the client decrypts the userlist received from the server, and appending the new user to this record, finally sending the encrypted blob back to the server. 4. If everything went well, the server stores the pubkey and the password generation rules next to the seed already generated in the first step of the CREATE operation. 4. Finally the client uses the rwd to derive the password using the password rules, and returns the newly generated account password to the user. Notable is that neither ratelimiting nor authentication happen during creation - (note there is authentication when updating the user record, but not when creating a user record). *** Changing of passwords/records 1. Changing of a record requires authentication. 2. Successful authentication is followed by the client initiating a second Sphinx Query - possibly with a changed master password and also sending along a newly encrypted password rules blob. This allows a client - if required - to change either of these, but they can also stay the same. 3. The server generates a new sphinx seed (either randomly or engaging in a TP-DKG with all other servers) and executes its part of the Sphinx query on it - sending back the resulting `beta` value to the client. 4. The client can finish the Sphinx query using the new sphinx rwd. Using this it can generate a new authentication key-pair (if the rwd is included in it). It signs the new public key with the new secret key - just to prove ownership of this keypair, and sends the signed public key back to the server. note when the setting rwd_keys is set to false, no new key is generated, but the old one must still be sent to the server. 5. The server checks if the public key can be used to verify the signature over it, if successful the server stores the new sphinx seed, the new auth public key and the new encrypted password rules blob marking them all as `new` - still keeping the original values active. If all this succeeds the server finally sends back the string "ok" to the client. 6. Upon receiving the "ok" message from the server, the client using the possibly changed password rules derives the new rwd from the result of the second sphinx query and returns the new password to the user. The above procedure allows a user to change or keep their master password, or to change the password rules if needed. But it is also possible to just generate a new password by keeping the old values, the fact that the server generates a new sphinx seed guarantees that the new password will be different from the old one. Also notable is, that this operation in fact does not change the password despite its name, it merely generates a new one, which still needs to be activated using the Commit operation. Client implementations MAY automatically call Commit after a successful Change operation. *** Commit new record To allow for errors during the changing of passwords on a service, the old password is still active until the user commits the change, which effectively replaces the current record with the new one. The Commit operation is a simple flow, it starts with an authentication using the current master password if required by the rwd_keys setting. And if this succeeds the server replaces the current record. The old password, authentication public key and password rules are marked as old, in case the change of the password fails and the account is still stuck with the old password, the Commit operation can be reverted by the Undo operation. *** Undo commit record To allow for errors during the changing of passwords on a service, the old user record is retained after the user commits the change. This allows to revert the Commit and use the old password. This function is provided in case the password change at the service fails for some reason. Undoing is a simple flow and very similar to the Commit operation, it starts with and authentication using the currently active master password if this is required by the rwd_keys setting. If the authentication succeeds the server marks the current record as new. The current password, authentication public key and password rules are replaced bye the old one. The Undo operation can be redone by the Commit operation to accomodate confusion when updating an account password. *** Deletion of keys The Delete operation deletes a sphinx record and updates the user record. The operation starts with an authentication, if it succeeds it optionally - depending on the userlist configuration value - updates the user record and finally deletes the sphinx record. ** User Record Operations The record id for user ids is calculated similarly to sphinx record ids, with the only difference that the username is set to an empty string. The special user record id of all-nulls is reserved for skipping the operation on user records. *** Reading of user records Reading of user is a simple flow which after successful authentication returns the encrypted user record blob. *** Updating of user records Updating user records can only be done by creating or deleting sphinx records. During an create or delete operation: 1. An update is initiated by sending the user record id to the server. 2. The server responds with the user record if there is such, or an empty user record if there is none. User records are always prefixed with 2 bytes representing their size, empty user records are thus signaled by responding with two zero bytes. If there was no existing user record, then a create user record flow is executed: The client 1. derives an authentication key-pair for this user record. 2. it encrypts the user name as an encrypted blob. 3. This blob is prefixed with its size represented by 2 bytes in network order. 4. The prefixed blob is concatenated after the public authentication key. 5. This is then signed by the authentication secret key. 6. And finally this sent to the server In pseudo-code this looks as such #+BEGIN_SRC id = getid(host) authkey, pubkey = getauthkey(id) send(signed_message(authkey, pubkey || (uint16_t) sizeof(blob) || blob)) #+END_SRC The server: 1. receives the authentication pubkey, the size of the blob, the blob itself, and the signature over the whole message. 2. using the authentication pubkey the server verifies the signature, if this verification fails the server aborts. 3. the server stores the auth pubkey and the user record blob under the user record id. If there already was an existing user record, then an update user record flow is executed which is simpler than the create flow, since we do not have to generate or send authentication keys. The client 1. decrypts the user record blob sent by the server 2. it adds the new user to the decrypted list of users 3. it encrypts the list of users into an encrypted user record blob 4. the encrypted user record blob is prefixed by its size represented in two bytes in network order. 5. the size-prefixed blob is signed by the authentication key 6. the signed blob is sent to the server. In pseudo-code this looks as such #+BEGIN_SRC id = getid(host) authkey, pubkey = getauthkey(id) send(signed_message(authkey, (uint16_t) sizeof(blob) || blob)) #+END_SRC The server: 1. receives the size of the blob, the blob, and the signature over this. 2. it loads the authentication public key from the user record 3. it then verifies the signature over the blob, if this verification fails the server aborts. 3. it stores the user record blob under the user record id. ** Weaknesses 1. When using server side user-lists the server can correlate which records belong to the same user and target server. This can be disabled by sending an all-zero record id for the userlists, which skips user records processing. 2. Server can collect usage statistics on sphinx records. 3. Management operations have unique communication patterns, even through the TLS encryption it can be deduced which operation is being run. The info leakage is due to the size and direction of data being passed between the server and the client. 4. When updating user records the requested record (if it exists) is returned without any authentication. It is thus possible to use a create sphinx record and then send an arbitrary user record id, the update user record flow can then be aborted by just closing the connection, or sending an invalid user record that cannot be authenticated by the pubkey known to the server. The server in this case will abort the update user record and the create sphinx record operation without changing anything. And thus it is possible for an attacker to circumvent the authentication required during the READ operation. 5. The change operation leaks if a client is configured to use the rwd in the authentication. If the rwd is included in the auth key then a new unique public auth key is generated, if rwd is not used in the auth key, then the old and new public key are the same. A threshold mitigates the offline bruteforce threat, but not the infoleak threat (which leaks this info to all servers anyway). * Bruteforce attacks against our Sphinx implementation Given the following abstract model of the SPHINX protocol: #+BEGIN_EXAMPLE Sphinx(seed) <--<[get password]--> Client(secret) <--[login]--> Server(userdb) ^ ^ ^ \----------------------------> Attacker <---------------------/ #+END_EXAMPLE If SPHINX is deployed in a threshold setup the compromise of as much servers is necessary to reach the threshold. Compromising less servers than enough to reaching the threshold is equivalent to not compromising a server in the single-server setup.t ** None of the 3 parties are compromised We know that simply bruteforcing the user password on the Server is infeasable for the attacker, since the server password is independent and of high entropy. Lacking any other information makes any online bruteforce attacks involving the Sphinx storage also unfeasable since the user ids under which the seeds are stored an practially ungueassable. ** The Sphinx storage is compromised and the attacker has access to the Sphinx seeds. An attacker can only run online attacks against the Server to recover a single login password to the Server recovering also the master password. The following defenses can make an attack more difficult by: a) using unique master passwords for each account - which is unreasonable. b) using a few master passwords, one for less valuable, and a few for high value accounts. c) using a memory-hard password hashing function on the Client, which also the attacker has to use - slowing down the attack. d) rate-limiting on the Server. e) Account lock-down after a certain threshold of failed logins. Of these defenses a) and b) are up to the user to implement, c) is implemented in our library using argon2i and d) and e) is up to the Server to implement. It is worth noting, that in our Sphinx implementation, the userids for the Sphinx seeds are derived from a client-secret. Thus an attacker having access to the Sphinx seeds but none of the client secrets, has no way of knowing which seed belongs to which user/server account, and thus make the online queries shots in the dark. ** The Client secret is available to the attacker This can happen for example by leaking your client secret while scanning it as a QR code. Using a leaked client secret an attacker can enumerate the username/host combinations known by a sphinx server. This attack is online-bruteforce only though, although a dictionary can significantly aid such an attack. Having recovered an ID allows an attacker to mount an online bruteforce attack against the master password. This attack requires the attacker to first do an online query to the Sphinx server then using the derived password in an online query against the Server to check if the derived password is correct, thus revealing the master password. The only obvious defense against this attack is ratelimiting and (b)locking bruteforce attackers in the enumeration phase and the master password recovery phase. ** The Service user db is leaked Lacking the Client secret makes any online bruteforce attacks involving the Sphinx storage unfeasable since the user ids under which the seeds are stored an practially ungueassable. ** Both the Client secret and the Server user db is available to the attacker Online Bruteforcing the master password means the attacker first - using the Client secret - finds an existing userid on the Sphinx storage belonging to a username/server pair. The attacker then uses online the Sphinx storage to derive the candidate password and then validates the candidate online against the Server with the guessed username. To defend against this case we can deploy rate-limiting on both the Sphinx storage and the Server. ** The Server is compromised and the user db is available to the attacker a) offline dictionary attacks against the Server password are infeasable, since the Server password is unique and of high entropy. b) Online attacks against the master password are possible, and are similar to the Online attack against the master password in the case where the Client Secret and the Server user db is compromised without a need to do online verification against the Server, thus making this attack slightly easier than the online master password guessing attack than that case. To protect against case b) the attacker can be slowed down by - using a memory-hard password hashing function in the protocol, which in our implementation is argon2i. - deploying a rate-limiter at the Sphinx storage. ** Both the Sphinx Storage and a Client secret are available to the attacker In this case the attacker can bruteforce the userids using the client secret to figure out which seed belongs to which username at which server. Having found out a seed belonging to the client secret enables an attacker to mount an offline bruteforce attack against the master password belonging to this account. The attacker simply calculates the OPRF directly without the blinding ( hash(master + hash(master)*seed)), derives the client signing key from it and the client secret, and checks if the resulting client signing pubkey is the same as stored with the seed. ** Both the Sphinx Storage and the Servers user db is available to the attacker The attacker does not know which sphinx seeds contribute to which passwords in the Server user db. This means the attacker can run ab offline bruteforce attack in which each seed must be bruteforced against all the target accounts from the server user database. Although this can be parallelized the attacker is slowed down by the memory-hard password hashing function which is used in our implementation. ** Lucky jackpot: The Sphinx seeds, the Client secret and the Server user db is available to the attacker Using the Client seed and the usernames in the Server user db the attacker can trivially find out which Sphinx seed belongs to which Server user db account. The attacker then can recover the master password used for this specific account by running a targeted offline bruteforce attack. Having recovered the master password, the attacker can offline bruteforce the other username/server combinations of the Sphinx seeds that share the same master password and Client secret, and thus recover all Server username/password/hostnames that share the same master password. * Rate-limiting the Sphinx Storage In the section "Bruteforce attacks against our Sphinx implementation", we identified three cases when the Sphinx storage is not available to the attacker an online bruteforce attack can be futher slowed down by deploying rate-limiting. ** IP address based rate-limiting IP address-based rate-limiting is a common measure. It is supported at the kernel level, but also on application level there are solutions for this (e.g. haproxy). However the problem with ip-based rate-limiting is that it does not protect against botnets with many different ip addresses, and if the server to be protected also can be reached via TOR or via IPv6, in the latter case attackers can simply exploit a /64 address space or even more. On the other hand, IP based rate-limiting is computationally very cheap, and can be done without changing the sphinx protocol. It can be a simple defense-in-depth measure. ** UserID based rate-limiting Another approach could be to rate-limit access to userids. The problem with querying the Sphinx password store is that the password store has no knowledge whether the users password input is correct or not. Thus we cannot limit only failing attempts. This also means we need to store state about number of access within a time-window and exponentially increase or decay a rate-limit. ** Proof-of-Work client puzzles Another approach could be to require the client to solve a small puzzle before the Sphinx server processes any requests. It must be noted, that - in the case of an online bruteforce attack - the client must already compute one elliptic curve scalar multiplication before the request, and one scalar multiplication, one scalar modular invert and one argon2i password hash after receiving the response from the sphinx server. While the Sphinx server only needs to do one scalar multiplication thus the server load is smaller than the client load.. An important aspect is that the cost to verify the client puzzle must be negligible, but solving the puzzle must be hard. The Equihash protocol[1] seems to be a suitable candidate for such since it can be tuned to various difficulties and it provides also memory hardness. [1] https://eprint.iacr.org/2015/946 Equihash client puzzles can be applied against requests based on IP addresses or UserIds with a dynamic difficulty based on number of access within a certain time-window. An open question remains whether to prohibit offline precomputation of equihash puzzles or not. Pre-computation could be prohibited by the Sphinx storage providing a nonce to a rate-limited client. The drawback is, that this nonce needs to be preserved by the Sphinx storage for the duration of the connection and this adds one extra round-trip to the protocol and ties up one worker process possibly leading to quick resource exhaustion. However it would allow to abort any request where the puzzle is not solved in time. An alternative approach would be the non-interactive approach, where the puzzle is the session transcript consisting of the userid and the blinded password together with a fresh timestamp, this approach would not require extra round-trips nor maintaining state at the Sphinx storage, but it would allow precomputation for an attacker. ** Rate-limiting in the threshold setting A client must solve all rate-limit puzzles in time to be able to interact with the SPHINX servers, in case of increased puzzle difficulty in combination with large threshold values can lead to significant strain on the client. ** Equihash puzzle-wrapped Sphinx The current implementation of the wraps our Extended Sphinx protocol in the following way. 0. The server has three configuration settings that affect the speed at which the ratelimiting gets more difficult or easier: - rl_decay: decrease ratelimiting difficulty for each full rl_decay seconds passed without any requests coming in. - rl_threshold: increase difficulty after rl_threshold attempts if not decaying - rl_gracetime: when checking freshness of puzzle solution, allow this extra gracetime in addition to the hardness max solution time The server also has a private puzzle key, with which it signs puzzles using a keyed blake2b hash. 1. all operations - except create, which makes no sense to bruteforce - are wrapped in the ratelimiting protocol. 2. a client prepares their Extended Sphinx request, and if it is not a create operation prepends it with a 0x5a byte - which requests the server to respond with a challenge. This is sent to the sphinx oracle. (note create requests do not have a 0x5a prefix, and get directly handled) 3. The server recognizing the 0x5a prefix as a ratelimiting puzzle request, checks if the userid in the extended sphinx request has already a ratelimiting context available and either loads it or creates one with the easiest possible difficulty. A corrupted context is automatically set to the most difficult hardness. 4. If a correct context was loaded the hardness is either decayed or (slowly) increased. If the previous ratelimiting request was recorded longer than rl_decay seconds ago, the difficulty is decreased by each full rl_decay epoch that has passed since the last request. If the last recorded rate-liming request was less than rl_decay seconds ago, we increase a counter in the context, if this counter is greater than rl_threshold we reset this counter and increase the difficulty of the puzzle by one level. 5. Based on the context difficulty level the puzzle is created as following: The original request and the equihash parameters - based on the context difficulty level - n and k (both unsigned 8bit integers) are concatenated with a 32bit timestamp. Using the servers puzzle key this concatenation is then signed using a keyed blake2b hash. The hash is appended to the concatenation forming the challenge. #+BEGIN_SRC challenge = n || k || timestamp sig = blake2b(key, request || challenge) challenge = challenge || sig #+END_SRC 6. The challenge is sent to the client, the socket is closed. 7. The clients solves the equihash puzzle for the n and k parameters from the challenge, and uses the challenge concatenated to the original request as the seed. 8. The client opens up a new connection to the server (the previous connection was closed by the server at the end of step 6.) and sends the following message: #+BEGIN_SRC '\xa5' || challenge || request || solution #+END_SRC 9. The server recognizing the 0xa5 prefix, first reads the challenge and the original request. The signature over the request and challenge is verified, the server aborts if this does not succeed. 10. The server verifies that the timestamp in the challenge is not older than a difficulty-dependent timeout plus the configuration value rl_gracetime. These timeouts are measured by the average time to solve the challenge on a raspberry pi 1 - except the ones that require more than 256MB of ram, those values are extrapolated from the measurements that fit into this memory. If the timestamp is older than the timeout plus the gracetime, the server aborts. 11. The server reads also the solution from the network and verifies it, if the verification fails, the server aborts. 12. The server hands over the original request to the extended sphinx protocol handler. ** Author Stefan Marsiske |sphinx|O|ctrlc.hu|