pax_global_header00006660000000000000000000000064144620222150014510gustar00rootroot0000000000000052 comment=10a249f6e05804a6424fc50cc357498cac1bdc7c pwdsphinx-1.0.18/000077500000000000000000000000001446202221500136235ustar00rootroot00000000000000pwdsphinx-1.0.18/.github/000077500000000000000000000000001446202221500151635ustar00rootroot00000000000000pwdsphinx-1.0.18/.github/workflows/000077500000000000000000000000001446202221500172205ustar00rootroot00000000000000pwdsphinx-1.0.18/.github/workflows/hcodeql-analysis.yml000066400000000000000000000032151446202221500232040ustar00rootroot00000000000000name: "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@v2 with: # We must fetch at least the immediate parents so that if this is # a pull request then we can checkout the head. fetch-depth: 2 # If this run was triggered by a pull request event, then checkout # the head of the pull request instead of the merge commit. - run: git checkout HEAD^2 if: ${{ github.event_name == 'pull_request' }} # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v1 # 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@v1 # ℹ️ 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: | # make bootstrap # make release - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v1 pwdsphinx-1.0.18/GettingStarted.md000066400000000000000000000334241446202221500171030ustar00rootroot00000000000000# Getting started So you want to start using SPHINX for handling your passwords. Great, Welcome! First you need to decide if you want to host your own server (we call it oracle), or you want to use someone elses oracle. It's ok to use someone elses server, as we say the oracle can be hosted by your worst nightmare enemy, they will not learn anything about your passwords[1]. It is important to note, that if you want to use sphinx, your client needs to be able to connect to the oracle. ## Installing the sphinx CLI client If you are on debian or derivates a simple ``` % sudo apt install pwdsphinx ``` should suffice and you can skip over to the next section to configure the client. But before skipping you might also want to install these optional dependencies: ``` % apt install pinentry-gtk2 xdotool xinput ``` If you are not on debian derivates, you need to build two dependencies manually. Let's start with libsphinx: ``` % git clone https://github.com/stef/libsphinx % cd libsphinx/src % sudo apt install install python3 libsodium libsodium-dev % sudo PREFIX=/usr make install ``` We also need libequihash: ``` % git clone https://github.com/stef/equihash % cd equihash % sudo PREFIX=/usr make install ``` And finally install the client itself: ``` % pip install pwdsphinx ``` Dependencies might also needed for some things: ``` % apt install pinentry-gtk2 xdotool xinput ``` (replace `apt install` and the package names with whatever equivalent your distro provides) ## Configuring the sphinx CLI client Create a config file `~/.sphinxrc` and insert the correct address and port for the server (oracle) you are going to use: ``` [client] address = your.sphinx-server.tld port = 443 timeout = 3 ``` Now you should be ready to initialize your sphinx client: ``` % sphinx init ``` This will create a file `~/.sphinx/masterkey`, you should make a backup of this file, and if you intend to use sphinx on other devices sharing the same passwords on them, you must copy this file there as well. If you intend to use `androsphinx` our android sphinx client, you can also do: ``` sphinx qr key ``` And have this qr-code read by the androsphinx client to use the same config as you have setup here. You should be ready to go: ``` echo -n "password" | sphinx create testuser testhost ``` This should give you a long very random password as output. You can now check if you get the same password back, but since echoing passwords on the command line is not very smart, let's try with a tool that comes with pwdsphinx: `getpwd`: ``` getpwd | sphinx get testuser testhost ``` This should pop up a password query window, where you should enter 'password' as the password, the response should be the long random password that was returned when you used the create command. And you can now also try to delete this test password, as you surely don't want to litter around: ``` sphinx delete testuser testhost ``` You might wonder, why you don't need a password for deletion - that actually depends on the `rwd_keys` setting, read about that in the man page. However deletion does require that the masterkey in `~/.sphinx/` is actually correct. Now if you do again (being lazy and not using `getpwd`): ``` echo -n "password" | sphinx get testuser testhost ``` You should get an error. Congrats, you just setup sphinx! Read up in the man pages (https://github.com/stef/pwdsphinx/tree/master/man) more about how to get the most out of sphinx. ## Setting up a Firefox addon First install the sphinx CLI client - see the section above on more info on that. Then install the addon from the mozilla addons store: https://addons.mozilla.org/en-US/firefox/addon/websphinx/ The WebSphinx addon also requires the installation of a native messaging host - which is terminology and it really means backend. Websphinx consists of two parts, the frontend which is the addon. And the backend which handles everything. You can install the addon from the [firefox addon store](https://addons.mozilla.org/en-US/firefox/addon/websphinx/). The WebSphinx addon requires the installation of a native messaging host - which is terminology and it really means backend. You will need to install a graphical pinentry, - either sudo apt-get install pinentry-qt - or sudo apt-get install pinentry-gtk2 - or sudo apt-get install pinentry-gnome3 - or sudo apt-get install pinentry-fltk (or anything equivalent to apt-get install on your OS) And set the pinentry variant if it is not invoked with `/usr/bin/pinentry` in your sphinx config file in the `websphinx` section Your sphinx config file can be in a couple of locations: - globally: `/etc/sphinx/config` - for your user: `~/.sphinxrc` - or also:`~/.config/sphinx/config` - and always in the current directory. To set the pinentry path, add or modify to have a section like this: ``` [websphinx] pinentry=/usr/bin/pinentry-gtk-2 ``` ### Native Messaging Host Manifest Copy [*websphinx.json*](https://github.com/stef/websphinx-firefox/raw/master/websphinx.json), depending on your browser to finish the installation: - Linux/BSD - User only: `~/.mozilla/native-messaging-hosts/websphinx.json` - System-wide: `/usr/{lib,lib64,share}/mozilla/native-messaging-hosts/websphinx.json` - MacOS: `/Library/Application Support/Mozilla/NativeMessagingHosts/websphinx.json` You need to change *%PATH%* in *websphinx.json* so it refers to *websphinx.py* which came with pwdsphinx. 1. `mkdir -p ~/.mozilla/native-messaging-hosts` 2. `curl -Lo ~/.mozilla/native-messaging-hosts/websphinx.json https://github.com/stef/websphinx-firefox/raw/master/websphinx.json` if you followed this guide, `websphinx` should be installed in `/usr/bin` and you should replace the `%PATH%` in `~/.mozilla/native-messaging-hosts/websphinx.json` to `/usr/bin` so the file looks like this: ``` { "name": "websphinx", "description": "Host for communicating with pwdphinx", "path": "/usr/bin/websphinx", "type": "stdio", "allowed_extensions": [ "sphinx@ctrlc.hu" ] } ``` ### Final step Restart your browser in which the addon is installed and enjoy. ## Setting up a Chrome derivate addon (including ms edge, opera, brave, etc) Websphinx consists of two parts, the frontend which is the addon. And the backend which handles everything. First install the sphinx CLI client, see the above for more information on that. WebSphinx is not in the Chrome Web Store, if you want to install the addon follow these steps (this applies to all Operating Systems): 1. Create a directory on your filesystem containing the files in the websphinx directory. 2. Start your browser if it is not running, 3. open [chrome://extension](chrome://extension) in your browser, 4. enable `Developer Mode`, 5. `Load Unpacked Extension` and provide the directory created in step 1., 6. If all went well, you should get a yellowyish sphinx button. The WebSphinx addon requires the installation of a native messaging host - which is terminology and it really means backend. You will need to install a graphical pinentry, - either sudo apt-get install pinentry-qt - or sudo apt-get install pinentry-gtk2 - or sudo apt-get install pinentry-gnome3 - or sudo apt-get install pinentry-fltk (or anything equivalent to apt-get install on your OS) And set the pinentry variant if it is not invoked with `/usr/bin/pinentry` in your sphinx config file in the `websphinx` section Your sphinx config file can be in a couple of locations: - globally: `/etc/sphinx/config` - for your user: `~/.sphinxrc` - or also:`~/.config/sphinx/config` - and always in the current directory. To set the pinentry path, add or modify to have a section like this: ``` [websphinx] pinentry=/usr/bin/pinentry-gtk-2 ``` ### Native Messaging Host Manifest Copy [*websphinx.json*](https://github.com/stef/websphinx-firefox/raw/master/websphinx.json), depending on your browser to finish the installation: - Linux/BSD - Per-user: `~/.config/{google-chrome,chromium}/NativeMessagingHosts/websphinx.json` - System: `/etc/{opt/chrome,chromium}/native-messaging-hosts/websphinx.json` - MacOS - Per-user: `~/Library/Application Support/{Google/Chrome,Chromium}/NativeMessagingHosts/websphinx.json` - System-wide: `/Library/{Google/Chrome,Chromium}/NativeMessagingHosts/websphinx.json` You need to change *%PATH%* in *websphinx.json* so it refers to *websphinx.py* which came with pwdsphinx. Assuming you have chromium follow these steps (otherwise replace chromium with google-chrome, or even possibly opera?) 1. `mkdir -p ~/.config/chromium/NativeMessagingHosts` 2. `curl -Lo ~/.config/chromium/NativeMessagingHosts/websphinx.json https://github.com/stef/websphinx-chrom/raw/master/websphinx.json` if you followed this guide, `websphinx` should be installed in `/usr/bin` and you should replace the `%PATH%` in `~/.config/chromium/NativeMessagingHosts/websphinx.json` to `/usr/bin` so the file looks like this: ``` { "name": "websphinx", "description": "Host for communicating with Sphinx", "path": "/usr/bin/websphinx", "type": "stdio", "allowed_origins": [ "chrome-extension://ojbhlhidchjkmjmpeonendekpoacahni/" ] } ``` ### Final step Restart your browser in which the addon is installed and enjoy. ## Hosting your own oracle Great! You should host your own oracle, and make it available also to all your friends and family! The recommended way to do so is to dedicate cheap and small single-board-computer to this task, which does nothing else. An old Raspberry Pi 1 is enough, the oracle does not use much resources. ## Installation You need to install sphinx, either by using `pip`: ``` pip install pwdsphinx ``` or on Debian derivates: ``` apt install pwdsphinx ``` ### Getting a TLS certificate using nginx and letsencrypt First you need to generate an account and a domain key: ``` openssl genrsa 4096 > account.key openssl genrsa 4096 > domain.key ``` Then you neeed to create a certificate signing request (CSR) for your domains. For a single domain you can use: ``` openssl req -new -sha256 -key domain.key -subj "/CN=yoursite.com" > domain.csr ``` If you have multiple domains (like www.yoursite.com and yoursite.com) and a new openssl, then: ``` openssl req -new -sha256 -key domain.key -subj "/" -addext "subjectAltName = DNS:yoursite.com, DNS:www.yoursite.com" > domain.csr ``` Or if you have an old openssl < 1.1.1: ``` openssl req -new -sha256 -key domain.key -subj "/" -reqexts SAN -config <(cat /etc/ssl/openssl.cnf <(printf "[SAN]\nsubjectAltName=DNS:yoursite.com,DNS:www.yoursite.com")) > domain.csr ``` Now you need nginx, and a challenges director it can serve: ``` apt install nginx mkdir -p /var/www/challenges/ ``` The configuration of nginx is the following: ``` # Example for nginx server { listen 80; server_name yoursite.com www.yoursite.com; location /.well-known/acme-challenge/ { alias /var/www/challenges/; try_files $uri =404; } ...the rest of your config } ``` And finally use acme-tiny to get our signed certificate ``` apt install acme-tiny acme_tiny --account-key ./account.key --csr ./domain.csr --acme-dir /var/www/challenges/ > ./signed_chain.crt ``` Tada! you should have a file called `signed_chain.crt` which contains your cert, and the file `domain.key` which you generated at the beginning is your secret key for the oracle. ## Configuration When you have a TLS cert and key, you can start configuring the oracle. A full configuration file for the oracle looks as follows: ``` [server] # the IP 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="server.der" # 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 ``` You need to set the `address` to whatever IP address you want the oracle to be listening on. And you should set the `port` if possible to 443, that will enable you to have always access to the oracle when you are on the go, since other ports might very well be firewalled, but port 443 is very-very rarely. You also need to set the `ssl_key` to the file `domain.key` , and the `ssl_cert` to the file `signed_chain.crt` both from the previous section "getting a tls cert..." The rest of the config settings you don't have to touch. When done, simply run `oracle`, this will start the server in the foreground. Use whatever your distro provides to daemonize and log the output of servers to have the server automatically started at reboot. Congratulations! Now invite your friends (and enemies!) to use your instance :) You might also want to setup the whole thing as a tor hidden service, so you can protect the privacy of your users even better, but how to do so is left as an exercise to the dear reader. [1] The only thing they can learn is the frequency how often you interact with a certain password, and which passwords belong to the same user and host, for example if you have an admin and a non-privileged account at the same host the oracle user could find out that these two are related. Also whoever is hosting the oracle can mount a denial-of-service against you by not responding or corrupting their answers. But your passwords would be safe, nevertheless. Even if their "database" leaks to the internet, or criminals. pwdsphinx-1.0.18/LICENSE000066400000000000000000001045131446202221500146340ustar00rootroot00000000000000 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-1.0.18/LICENSES/000077500000000000000000000000001446202221500150305ustar00rootroot00000000000000pwdsphinx-1.0.18/LICENSES/CC-BY-SA-4.0.txt000066400000000000000000000437701446202221500172010ustar00rootroot00000000000000 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-1.0.18/LICENSES/GPL-3.0-or-later.txt000066400000000000000000001045131446202221500202400ustar00rootroot00000000000000 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-1.0.18/MANIFEST.in000066400000000000000000000001111446202221500153520ustar00rootroot00000000000000include README.md include *.py include man/*.1 include GettingStarted.md pwdsphinx-1.0.18/README.md000066400000000000000000000266401446202221500151120ustar00rootroot00000000000000 sphinx: a password **S**tore that **P**erfectly **H**ides from **I**tself (**N**o **X**aggeration) pwdsphinx is python wrapper around libsphinx - a cryptographic password storage as described in https://eprint.iacr.org/2015/1099 ## Dependencies You need [libsphinx](https://github.com/stef/libsphinx) and [libequihash](https://github.com/stef/equihash/) for the python reference frontend. You need also to install `pysodium` using either your OS package manager or pip. If you want to use also the websphinx browser extension you need to install also an X11 variant of pinentry from the gnupg project: - either `apt-get install pinentry-qt` - or `apt-get install pinentry-gtk2` - or `apt-get install pinentry-gnome3` - or `apt-get install pinentry-fltk` (or anything equivalent to `apt-get install` on your OS) ## Installation `pip3 install pwdsphinx` should get you started. ## API `sphinxlib` is a `ctypes`-based python wrapper around [libsphinx](https://github.com/stef/libsphinx), so you can build whatever you fancy immediately in python. The interface exposed wraps the 3 sphinx functions from the library like this: ``` def challenge(pwd) ``` returns bfac and chal ``` def respond(chal, secret) ``` return the response ``` def finish(pwd, bfac, resp) ``` returns the raw 32 byte password. ## Server/Client Since the sphinx protocol only makes sense if the "device" is somewhere else than where you type your password, pwdsphinx comes with a server implemented in py3 which you can host off-site from your usual desktop/smartphone. Also a client is supplied which is able to communicate with the server and manage passwords. Both the client and the server can be configured by any of the following files: - `/etc/sphinx/config` - `~/.sphinxrc` - `~/.config/sphinx/config` - `./sphinx.cfg` Files are parsed in this order, this means global settings can be overridden by per-user and per-directory settings. ### oracle - the server pwdsphinx comes with a python reference implementation of a extended sphinx server called oracle. The server can be "configured" by changing the variables in the `[server]` section of the config file. The `address` is the IP address on which the server is listening, default is `localhost` - you might want to change that. The `port` where the server is listening is by default 2355. `datadir` specifies the data directory where all the device "secrets" are stored, this defaults to "data/" in the current directory. You might want to back up this directory from time to time to an encrypted medium. `verbose` enables logging to standard output. `timeout` sets the timeout for any connection the server keeps open. `max_kids` sets the number maximum 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 ratelimit level decays to an easier difficulty. `rl_threshold` increase the difficulty of ratelimit puzzles if not decaying. `rl_gracetime` gracetime in seconds added to the expcted time to solve a rate-limiting puzzle. Change these settings to fit your needs. Starting the server can be done simply by: ``` oracle ``` ### sphinx - the client This is the client that connects to the oracle to manage passwords using the extended sphinx protocol. #### Client Configuration Like the server, the client can be configured changing the settings in the `[client]` section of the config file. The `host` and `port` should match what you set in the oracle. The datadir (default: `~/.sphinx`) variable holds the location for your client parameters. Particularly it contains a masterkey which is used to derive secrets. The master key - if not available - is generated by issuing an init command. You **should** back up and encrypt this master key. `rwd_keys` toggles if the master password is required for authentication of management operations. If it is False it protects against offline master password bruteforce attacks - which is also a security guarantee of the original SPHINX protocol. The drawback is that for known (host,username) tuples the seeds/blobs can be changed/deleted by an attacker if the clients masterkey is available to them. But neither the master nor the account password can leak this way. This is merely a denial-of-service vector. If rwd_keys is True, then this eliminates the denial-of-service vector, but instead eliminates the offline-bruteforce guarantee of the SPHINX protocol. Note that 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` Stores a check digit of 5 bits in on the oracle, this helps to notice most typos of the master password, while decreasing security slightly. #### Operations The client provides the following operations: Create, Get, Change, Commit, Undo, List and Delete. All operations need a username and a site this password belongs to, even if they're only empty strings. #### Create password Creating a new password for a site is easy, pass your "master" password on standard input to the client, and provide parameters like in this example: ``` echo -n 'my master password' | sphinxy create username example.com ulsd 0 ' !"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' ``` The parameters to the client are `create` for the operation, then `username` for the username on the site `example.com` then a combination of the letters `ulsd` and the `0` for the size of the final password. The letters `ulsd` stand in order for the following character classes: `u` upper-case letters, `l` lower-case letters, `s` symbols and `d` for digits. The `s` is a short-cut to allow all of the symbols, if you have a stupid server that limits some symbols, you can specify the allowed symbols explicitly. Currently these are the symbols supported (note the leading space char): ``` !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ ``` Be careful, if you specify these on the command-line you'll have to escape the quotes you use for enclosing this list and possibly the backslash char that is also part of this list. In the `create username` example above the symbols are correctly escaped, in case you need to copy/paste them. If you do not provide password rules, they will be defaulting to 'ulsd' and length as long as possible. If the command runs successfully - the resulting new high-entropy password according to the given rules is printed to the console. In case for some reason you cannot use random passwords with your account, or you want to store a "password" that you cannot change, like a PIN code for example, or a passphrase shared with your colleagues, you can specify a maximuxm 38 characte long password, that will be generated by the SPHINX client for you. In that case the command line looks like this (note the same syntax also works for the `change` operation) ``` echo -n 'my master password' | sphinx create username example.com "correct_battery-horse#staple" ``` In this case you cannot specify neither the accepted character classes, nor the size, nor symbols. Note1, since the master password is not used to encrypt anything, you can actually use different "master" passwords for different user/site combinations. Note2, using echo is only for demonstration, you should use something like this instead (or even directly getpwd from the contrib directory): ``` echo GETPIN | pinentry | grep '^D' | cut -c3- | sphinx create username example.com ulsd 0 ``` Using pinentry you can go fancy and do double password input, and even have something checking password quality for you, check it out, it's quite versatile. #### Get password Getting a password from the sphinx oracle works by running the following command: ``` echo -n 'my master password' | sphinx get username example.com ``` Here again you supply your master password on standard input, provide the `get` operation as the first parameter, your `username` as the 2nd and the `site` as the 3rd parameter. The resulting password is returned on standard output. #### Change password You might want to (or are forced to regularly) change your password, this is easy while you can keep your master password the unchanged (or you can change it too, if you want). The command is this: ``` echo -en 'my master password\nnew masterpassword' | sphinx change username example.com 'ulsd' 0 ' !"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' ``` Here again you supply your master password on standard input, but separated by a new-line you also provide the new master password. The new master password can be the same as the old, but can also be a new password if you want to change also the master password. You provide the `change` operation as the first parameter to the client, your `username` as the 2nd and the `site` as the 3rd parameter. You also can provide similar password generation rule parameters that were also used to create the original password, in case your account has new password rules and you want/have to accomodate them. Your new new password is returned on standard output. #### Committing a changed password After changing the password, you will still get the old password when running `get`. To switch to use the new password you have to commit the changes with ``` echo -n 'my master password' | sphinx commit username example.com ``` #### Undoing a password commit If you somehow messed up and have to go back to use the old password, you can undo committing your password using: ``` echo -n 'my master password' | sphinx undo username example.com ``` #### Deleting passwords In case you want to delete a password, you can do using the following command: ``` echo -n "my master password" | sphinx delete username example.com ``` You provide the `delete` operation as the first parameter to the client, your `username` as the 2nd and the `site` as the 3rd parameter. This command does not provide anything on standard output in case everything goes well. #### QR code config In case you want to use phone with the same sphinx server, you need to export your config to the phone via a QR code. ``` sphinx qr ``` Will display a QR code containing only public information - like the server host and port, and if you use rwd_keys. This is mostly useful if you want to share your setup with a friend or family. If you want to connect your own phone to the setup used with pwdsphinx, you also need to export your client secret in the QR code: ``` sphinx qr key ``` This contains your client secret, and you should keep this QR code confidential. Make sure there is no cameras making copies of this while this QR code is displayed on your screen. If for whatever reason you want to display the QR code as an SVG, just append the `svg` keyword to the end of the `sphinx qr` command. ## X11 frontend You can find a bunch of shell-scripts that are based on `pinentry-(gtk|qt)`, `xinput`, `xdotool` and `dmenu`, the top-level entry to these is the `dmenu-sphinx.sh` script, which stores its history of entered hostnames in `~/.sphinx-hosts` - if the hosts are in any way sensitive, you might want to link this file to `/dev/null`. The `contrib/README.md` should give you an idea of how else to combine these scripts. ## 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. pwdsphinx-1.0.18/configs/000077500000000000000000000000001446202221500152535ustar00rootroot00000000000000pwdsphinx-1.0.18/configs/chrome/000077500000000000000000000000001446202221500165305ustar00rootroot00000000000000pwdsphinx-1.0.18/configs/chrome/websphinx.json000066400000000000000000000003331446202221500214310ustar00rootroot00000000000000{ "name": "websphinx", "description": "Host for communicating with Sphinx", "path": "/usr/bin/websphinx", "type": "stdio", "allowed_origins": [ "chrome-extension://ojbhlhidchjkmjmpeonendekpoacahni/" ] } pwdsphinx-1.0.18/configs/config000066400000000000000000000041251446202221500164450ustar00rootroot00000000000000# the client section is only needed if you use the client functionality [client] # whether to produce some output on the console verbose = False # the ip address or hostname the server is listening on address = 127.0.0.1 # the port on which the server is listening port = 2355 # the directory where the client stores its master secret - you might want to # back this up datadir = ~/.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 # 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 ssl_key="/etc/ssl/sphinx/server.der" # ssl cert ssl_cert="/etc/ssl/sphinx/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, default: /var/lib/sphinx 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 # 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= pwdsphinx-1.0.18/configs/firefox/000077500000000000000000000000001446202221500167155ustar00rootroot00000000000000pwdsphinx-1.0.18/configs/firefox/websphinx.json000066400000000000000000000002731446202221500216210ustar00rootroot00000000000000{ "name": "websphinx", "description": "Host for communicating with pwdphinx", "path": "/usr/bin/websphinx", "type": "stdio", "allowed_extensions": [ "sphinx@ctrlc.hu" ] } pwdsphinx-1.0.18/contrib/000077500000000000000000000000001446202221500152635ustar00rootroot00000000000000pwdsphinx-1.0.18/contrib/Makefile000066400000000000000000000031671446202221500167320ustar00rootroot00000000000000clean: 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/sphage \ $(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/sphage: sphage 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-1.0.18/contrib/README.md000066400000000000000000000072731446202221500165530ustar00rootroot00000000000000# Simple UI tools for using pwdsphinx on X11 This directory contains tools that can be used on their own, or in concert to interact with pwdsphinx. ## getpwd.sh (depends on pinentry) This is a simple script which uses `pinentry` from the gnupg project to query a password and write it out to standard output. Which `pinentry` variant you use, is up to you, it can be a curses, gtk or qt interface. 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. Use it like this: ``` getpwd.sh | sphinx get username hostname ``` ## exec-on-click.sh (depends on xinput) This is a simple shellscript that depends on `xinput`, which waits until a left-mouse click and then it executes whatever parameters the script has been called with. For example: ``` echo -n "hello world" | bin/exec-on-click.sh xdotool type --clearmodifiers '$(cat)' ``` Types `hello world` into the current window using xdotool. ## type-pwd.sh (depends on xdotool, exec-on-click and getpwd) This script combines `getpwd.sh`, `exec-on-click.sh` and the pwdsphinx client in such a way, that it securely queries for your master password, and then waits until you click somewhere (hopefully into a password entry field) and then sends the password as keystrokes. Using this mechanism you make sure your password is never on your clipboard where malware might steal it. And also it allows to enter your password on those braindead stupid sites that disable copy/pasting into password fields. Use it as such: ``` type-pwd.sh username hostname ``` and click in the password entry field where you want the password to be entered. ## dmenu-sphinx.sh (depends on dmenu, type-pwd.sh) This tool builds on type-pwd.sh, it uses dmenu in order to query a hostname, then depending if only one username or more are known by the oracle - if only one then the next step is skipped: provides a choice which username to use. Then `type-pwd.sh` invoked using the selected user and hostname. ## sphinx-x11 This is a simple "script" language interpreter that integrates the SPHINX CLI with X11. In the `sphinx-scripts` directory you can find 3 example scripts: - pass.sphinx - user-pass.sphinx - user-pass-otp.sphinx each of these scripts waits for the user to click, then they retrieve the relevant password (and TOTP token) before inserting it into the form fields, navigating between them with `tab` and `enter`. You are welcome to contribute adapted sphinx-scripts for websites that have other login semantics. As an example the `user-pass-otp.sphinx` script is explained below: ``` #!./sphinx-x11 wait-for-click user tab pwd tab enter wait-for-click otp enter ``` The first line specifies `sphinx-x11` as the interpreter. The script itself then waits for the user to click (line 3), then in line 4 inserts the `user` - which is specified as the first parameter to this script. Line 5 injects a `tab` so the next form field is selected. Then pwdsphinx/getpwd is used to get the password for `user` and `host` - the host being the 2nd parameter to this script. `enter` is used to submit this form in line 8. Since this is a new form the script waits (line 9) for the user to click in the field where the TOTP value needs to be inserted. Then in line 10 the TOTP value is queried using pwdsphinx/getpwd, and finally in the last line the TOTP value is submitted by injecting `enter` into the application. A note on the OTP support, in this interpreter/implementation an TOTP value is assumed to be stored with a username prefixed with `otp://`, so the first `pwd` operation uses e.g. `joe` as a username and then for the TOTP value it uses `otp://joe` as the username. pwdsphinx-1.0.18/contrib/dmenu-sphinx000077500000000000000000000005201446202221500176250ustar00rootroot00000000000000#!/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-1.0.18/contrib/exec-on-click000077500000000000000000000010021446202221500176230ustar00rootroot00000000000000#!/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-1.0.18/contrib/getpwd000077500000000000000000000002421446202221500165010ustar00rootroot00000000000000#!/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-1.0.18/contrib/sphage000077500000000000000000000121521446202221500164610ustar00rootroot00000000000000#!/usr/bin/env python3 # 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 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 decoded def encode(hrp, data): ret = bech32_encode(hrp, convertbits(data, 8, 5)) if decode(hrp, ret) == None: return None return ret def usage(help=False): print("usage: sphage.py [] <[32 bytes of cryptographic entropy] >key") if help: sys.exit(0) sys.exit(1) if __name__ == '__main__': rwd = sys.stdin.buffer.readline().rstrip(b'\n') if len(sys.argv)!=2: usage() op = sys.argv[1] if op in ('help', '-h', '--help'): usage(True) elif op == "pubkey": pk = pysodium.crypto_scalarmult_base(rwd) ret = encode("age", pk) elif op == "privkey": ret = encode('age-secret-key-', rwd).upper() else: usage() print(ret) pwdsphinx-1.0.18/contrib/sphage-test.sh000077500000000000000000000007421446202221500200510ustar00rootroot00000000000000#!/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-1.0.18/contrib/sphinx-scripts/000077500000000000000000000000001446202221500202615ustar00rootroot00000000000000pwdsphinx-1.0.18/contrib/sphinx-scripts/getacc-user-pass.sphinx000077500000000000000000000001151446202221500246620ustar00rootroot00000000000000#!/usr/bin/sphinx-x11 gethost getuser wait-for-click user tab pwd tab enter pwdsphinx-1.0.18/contrib/sphinx-scripts/otp.sphinx000077500000000000000000000000601446202221500223150ustar00rootroot00000000000000#!/usr/bin/sphinx-x11 wait-for-click otp enter pwdsphinx-1.0.18/contrib/sphinx-scripts/pass.sphinx000077500000000000000000000000641446202221500224650ustar00rootroot00000000000000#!/usr/bin/sphinx-x11 wait-for-click pwd tab enter pwdsphinx-1.0.18/contrib/sphinx-scripts/user-pass-otp.sphinx000077500000000000000000000001261446202221500242400ustar00rootroot00000000000000#!/usr/bin/sphinx-x11 wait-for-click user tab pwd tab enter wait-for-click otp enter pwdsphinx-1.0.18/contrib/sphinx-scripts/user-pass.sphinx000077500000000000000000000000751446202221500234430ustar00rootroot00000000000000#!/usr/bin/sphinx-x11 wait-for-click user tab pwd tab enter pwdsphinx-1.0.18/contrib/sphinx-x11000077500000000000000000000061271446202221500171370ustar00rootroot00000000000000#!/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 ; } | /usr/bin/oathtool -b --totp - | 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-1.0.18/contrib/type-pwd000077500000000000000000000001601446202221500167570ustar00rootroot00000000000000#!/usr/bin/env sh getpwd "$1@$2" | sphinx get "$1" "$2" | exec-on-click xdotool type --clearmodifiers '$(cat)' pwdsphinx-1.0.18/man/000077500000000000000000000000001446202221500143765ustar00rootroot00000000000000pwdsphinx-1.0.18/man/bin2pass.md000066400000000000000000000033371446202221500164470ustar00rootroot00000000000000% bin2pass(1) | converts binary input to passwords # NAME bin2pass - converts binary input to passwords # SYNOPSIS ``` bin2pass [d|u|l] [] [] ?@[\]^_`{}~ ``` Please note that is allowed, and also be careful in quoting special characters that might be interpreted by your shell, such as `"`, `!`, `\`, etc... # EXAMPLES Generate the longest possible random password from /dev/random, with the resulting password having characters from digits, lower- and upper-case letters and the and * symbols. ``` dd if=/dev/random bs=1 count=30 | ./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 . 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-1.0.18/man/dmenu-sphinx.md000066400000000000000000000021171446202221500173400ustar00rootroot00000000000000% 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 ``` type-pwd username hostname ``` # DESCRIPTION This tool builds on `type-pwd(1)`, it uses `dmenu(1)` in order to query a hostname, then depending if only one or more usernames are known by the oracle - if only one then the next step is skipped: provides a choice which username to use. Then `type-pwd(1)` is invoked using the selected user and hostname. This tool cashes the hostnames it was used with 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 . 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-1.0.18/man/exec-on-click.md000066400000000000000000000016241446202221500173440ustar00rootroot00000000000000% 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 This is a simple tool which waits until a left-mouse click and then it 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. # 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 . 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-1.0.18/man/getpwd.md000066400000000000000000000021271446202221500162140ustar00rootroot00000000000000% 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 This is a simple script which uses `pinentry` from the gnupg project to query a password and write it out to standard output. Which `pinentry` variant you use, is up to you, it can be a curses, gtk or qt interface. 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. The only parameter this tool takes is a prompt to display 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 . 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-1.0.18/man/makefile000066400000000000000000000020371446202221500161000ustar00rootroot00000000000000all: 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 install: $(PREFIX)/share/man/man1/sphinx.1 $(PREFIX)/share/man/man1/oracle.1 $(PREFIX)/share/man/man1/bin2pass.1 \ $(PREFIX)/share/man/man1/getpwd.1 $(PREFIX)/share/man/man1/exec-on-click.1 $(PREFIX)/share/man/man1/type-pwd.1 \ $(PREFIX)/share/man/man1/dmenu-sphinx.1 $(PREFIX)/share/man/man1/sphinx-x11.1 $(PREFIX)/share/man/man1/sphage.1 \ $(PREFIX)/share/man/man1/websphinx.1 $(PREFIX)/share/man/man1/otp.sphinx.1 $(PREFIX)/share/man/man1/pass.sphinx.1 \ $(PREFIX)/share/man/man1/user-pass-otp.sphinx.1 $(PREFIX)/share/man/man1/user-pass.sphinx.1 clean: rm -f *.1 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 $@ $< pwdsphinx-1.0.18/man/oracle.md000066400000000000000000000070511446202221500161700ustar00rootroot00000000000000% oracle(1) | server for the SPHINX password manager # NAME oracle - server for the SPHINX password manager # SYNOPSIS `oracle` # DESCRIPTION The SPHINX protocol only makes sense if the server (called oracle) is somewhere else than where you type your password, pwdsphinx comes with a server implemented in python3 which you can host off-site from your usual desktop/smartphone. The server can be started simply by running `oracle` it does not take any parameters. # CONFIGURATION The server can be configured by any of the following files: - `/etc/sphinx/config` - `~/.sphinxrc` - `~/.config/sphinx/config` - `./sphinx.cfg` Files are parsed in this order, this means global settings can be overridden by per-user and per-directory settings. The server can be configured by changing the variables in the `[server]` section of the config file. The `address` is the IP address on which the server is listening, default is `localhost` - you might want to change that. The `port` where the server is listening is by default 2355. Another recommended values is to use port 433 which is allowed by most firewalls while 2355 is not. `ssl_key` and `ssl_cert` must be specified, they point at a traditional TLS certificate and secret key file. It is recommended to not use self-signed certs, but to use certs that signed by CAs that are recognised widely by browsers and other TLS clients. `datadir` specifies the data directory where all the device "secrets" are stored, this defaults to "data/" in the current directory. You might want to back up this directory from time to time to an encrypted medium. `verbose` enables logging to standard output. `timeout` sets the timeout for any connection the server keeps open. `max_kids` sets the number maximum 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 ratelimit level decays to an easier difficulty. `rl_threshold` increase the difficulty of ratelimit puzzles if not decaying. `rl_gracetime` gracetime in seconds added to the expcted time to solve a rate-limiting puzzle. # SECURITY CONSIDERATIONS The configuration values `max_kids` and `timeout` can be used to tune how many requests are served in parallel and how long each request is allowed to take before it gets killed. An attacker might be able to run a denial-of-service attack against your server, by keeping all `max_kids` connections "occupied". Since the server does only know about failed authorizations for management operations, but not about correctness of master passwords for get requests, there is no way to mitigate master password bruteforce attempts aside from ratelimiting. By tuning the configuration variables starting with `rl_` it is possible to configure this. If you have clients that have less than 1G RAM, it might be possible to increase the difficulty to the maximum level where those devices will not be able to solve the ratelimting puzzles. Rate-limiting in general should not be noticable, only if dozens of get requests are served to the same record. At the highest level the solution should take about 20-40 seconds (depending on your cpu). # 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 . 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-1.0.18/man/sphage.md000066400000000000000000000015471446202221500161760ustar00rootroot00000000000000% 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 This is a converter that is meant to convert the raw output of `sphinx(1)` into a key-pair that can be used by `age(1)` allowing for more sophisticated secrets manager 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 . 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-1.0.18/man/sphinx-x11.md000066400000000000000000000117301446202221500166420ustar00rootroot00000000000000% 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 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 parameter to the sphinx-script - into the currently focused X11 window. - `pwd`: gets a password using `getpwd(1)` and `sphinx(1)`, and types it into the currently focused X11 window. - `otp`: gets a TOTP secret stored in `sphinx(1)` using `getpwd(1)` and generates the TOTP pin using `oathtool(1)`, which is then typed into the currently focused X11 window. - `tab`: types a tabulator into the current X11 window, possibly advancing between form-fields. - `enter`: sends an enter key press to the currently focused X11 window, possibly submitting a form. - `gethost`: waits for a left mouse-click on a browser window, and then copies the URL from the urlbar into the clipboard, and then strips it down to the hostname and sets an internal "$host" variable that can then be used with `host` or `pwd`. - `getuser` dispatches a `sphinx list $host` and if more than one user is returned, offers them in a dmenu widget, if/when one user is found/selected it is set as an internal `$user` variable which can then used for verbs like `user` or `pwd`. Any lines not consisting of these tokens are simply ignored. # OTP SUPPORT In this interpreter/implementation a TOTP value is assumed to be stored with a username prefixed with `otp://`, so that a regular login name can co-exist with the according TOTP secret in sphinx. For example in a common 2FA login the first `pwd` operation uses e.g. `joe` as a username and then for the TOTP value it uses `otp://joe` as the username, which allows for seamless 2FA login. # DEFAULT SCRIPTS `sphinx-x11(1)` comes with 5 default sphinx-scripts (note on debian and derivates instead of a `.sphinx` extension they have a `sx11-` prefix): - pass.sphinx : gets a password using `sphinx(1)`, types it and submits it. - user-pass.sphinx : gets a password using `sphinx(1)`, types the user, then the password and submits it. - user-pass-otp.sphinx : gets a password, and a TOTP pin code using `sphinx(1)`, first types the username, then the password, then submits the form, and finally enters the TOTP pin and submits that as well. - otp.sphinx : gets a TOTP pin code using `sphinx(1)` and types and submits it. - getacc-user-pass.sphinx: waits for a click on a browser window, from with it gets the target `host` value, then using that uses `sphinx list` to get the users associated with this host, and if one is selected, waits for another click in the user input field of a login form, then gets a password using `sphinx(1)`, types the user, then the password and submits it. Each of these scripts waits for the user to click, then they retrieve the relevant password (and/or TOTP token) before inserting it into the form fields, navigating between them with `tab` and `enter`. You are welcome to contribute adapted sphinx-scripts for websites that have other login semantics. # EXAMPLE As an example the `user-pass-otp.sphinx` script is explained below: ``` #!./sphinx-x11 wait-for-click user tab pwd tab enter wait-for-click otp enter ``` The first line specifies `sphinx-x11(1)` as the interpreter. The script itself then waits for the user to click (line 3), then in line 4 inserts the `user` - which is specified as the first parameter to this script. Line 5 injects a `tab` so the next form field is selected. Then pwdsphinx/getpwd is used to get the password for `user` and `host` - the host being the 2nd parameter to this script. `enter` is used to submit this form in line 8. Since this is a new form the script waits (line 9) for the user to click in the field where the TOTP value needs to be inserted. Then in line 10 the TOTP value is queried using pwdsphinx/getpwd, and finally in the last line the TOTP value is submitted by injecting `enter` into the application. # 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 . 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-1.0.18/man/sphinx.md000066400000000000000000000265411446202221500162410ustar00rootroot00000000000000% 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` qr [\] [\] # DESCRIPTION SPHINX -- password Store that Perfectly Hides from Itself (No Xaggeration) -- is an information-theoretically secure cryptographic password storage protocol with strong security guarantees, as 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). `sphinx` is the command-line client for the SPHINX protocol, it provides access to all operations over the life-cycle of a password: init, create, get, change, undo, commit, delete. Additionally it provides also operations that make this more user-friendly: listing of users associated with a host and export of the configuration using a qr code. 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. ## INITIALIZING A CLIENT ``` sphinx init ``` This creates a new master key 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 master key. If you want to use sphinx on a different device you want to copy this master key also there. For copying this (and other settigns) to the android client `androsphinx` we have the `qr` operation, see below. ## CREATE PASSWORD Creating a new password for a site is easy, pass your "master" password on standard input to the client, and provide parameters like in this example: ``` echo -n 'my master password' | sphinx create username example.com ulsd 0 ' !"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' ``` The parameters to the client are - Your master password on standard input. Since the master password is not used to encrypt anything, you can actually use different "master" passwords for different user/site combinations. - `create` for the operation, then - `username` for the username on - the site `example.com` then - the password constraints, see sections `PASSWORD RULES` and `PREDETERMINED PASSWORDS` for more info If the command runs successfully - the resulting new high-entropy password according to the given rules is printed to the console. ## GET PASSWORD Getting a password from the sphinx oracle works by running the following command: ``` echo -n 'my master password' | sphinx get username example.com ``` You supply your master password on standard input, provide the `get` operation as the first parameter, your `username` as the 2nd and the `site` as the 3rd parameter. The resulting password is returned on standard output. ## CHANGE PASSWORD You might want to (or are forced to regularly) change your password, this is easy while you can keep your master password the unchanged (or you can change it too, if you want). The command is this: ``` echo -en 'my master password\nnew masterpassword' | sphinx change username example.com 'ulsd' 0 ' !"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' ``` You supply your current master password on standard input, and separated by a new-line you also provide the new master password. The new master password can be the same as the old, but can also be a new password if you want to change also the master password. You provide the `change` operation as the first parameter to the client, your `username` as the 2nd and the `site` as the 3rd parameter. You also can provide similar password generation rule parameters that were also used to create the original password, in case your account has new password rules and you want/have to accomodate them. For more information see the `PASSWORD RULES` and `PREDETERMINED PASSWORDS` sections below. Your new new password is returned on standard output. ## COMMITTING A CHANGED PASSWORD After changing the password, you will still get the old password when running the `get` operation. To switch to use the new password you have to commit the changes with ``` echo -n 'my master password' | sphinx commit username example.com ``` Depending on your `rwd_keys` configuration setting, you might have to provide your master password on standard input to this operation. If all goes well, there is no output expected. ## UNDOING A PASSWORD COMMIT If you somehow messed up and have to go back to use the old password, you can undo committing your password using: ``` echo -n 'my master password' | sphinx undo username example.com ``` Depending on your `rwd_keys` configuration setting, you might have to provide your master password on standard input to this operation. If all goes well, there is no output expected. ## DELETING PASSWORDS In case you want to delete a password, you can do using the following command: ``` echo -n "my master password" | sphinx delete username example.com ``` You provide the `delete` operation as the first parameter to the client, your `username` as the 2nd and the `site` as the 3rd parameter. This command does not provide anything on standard output in case everything goes well. Depending on your `rwd_keys` configuration setting, you might have to provide your master password on standard input to this operation. ## QR CODE CONFIG In case you want to use phone with the same sphinx server, you need to export your config to the phone via a QR code. ``` sphinx qr ``` Will display a QR code containing only public information - like the server host and port, and whether you use rwd_keys. This is mostly useful if you want to share your setup with a friend or family. If you want to connect your own phone to the setup used with pwdsphinx, you also need to export your client secret in the QR code: ``` sphinx qr key ``` This contains your client secret, and you should keep this QR code confidential. Make sure there is no cameras making copies of this while this QR code is displayed on your screen. If for whatever reason you want to display the QR code as an SVG, just append the `svg` keyword to the end of the `sphinx qr` command. ## PASSWORD RULES When creating or changing passwords you can specify rules limiting the size and characters allowed in the output password. This is specified as follows: The letters `ulsd` stand in order for the following character classes: - `u` upper-case letters, - `l` lower-case letters, - `s` symbols and - `d` for digits. The `s` is a short-cut to allow all of the symbols, if you are limited by the server which symbols to use, you can specify the allowed symbols explicitly. Currently these are the symbols supported (note the leading space char): ``` !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ ``` Be careful, if you specify these on the command-line you'll have to escape the quotes you use for enclosing this list and possibly the backslash char that is also part of this list. In the `create username` example above the symbols are correctly escaped, in case you need to copy/paste them. For examples how to use these see the section "CREATE PASSWORD" or "CHANGE PASSWORD". ### DEFAULT RULES If you do not provide password rules, they will be defaulting to 'ulsd' and length as long as possible. ## PREDETERMINED OUTPUT PASSWORDS In case for some reason you cannot use random passwords with your account, or you want to store a "password" that you cannot change, like a PIN code for example, or a passphrase shared with your colleagues, you can specify a maximuxm 38 characte long password, that will be generated by the SPHINX client for you. In that case the command line looks like this (note the same syntax also works for the `change` operation) ``` echo -n 'my master password' | sphinx create username example.com "correct_battery-horse#staple" ``` In this case you cannot specify neither the accepted character classes, nor the size, nor symbols, these will be deducted from the predetermined password itself. # CONFIGURATION The client can be configured by any of the following files: - `/etc/sphinx/config` - `~/.sphinxrc` - `~/.config/sphinx/config` - `./sphinx.cfg` Files are parsed in this order, this means global settings can be overridden by per-user and per-directory settings. The client can be configured changing the settings in the `[client]` section of the config file. The `host` and `port` should match what you set in the `oracle(1)` server. The `datadir` (default: `~/.sphinx`) variable holds the location for your client parameters. Particularly it contains a masterkey which is used to derive secrets. The master key - if not available - is generated by issuing an `init` command. You **should** back up and encrypt this master key. `rwd_keys` toggles if 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` Stores a check digit of 5 bits in on the oracle, this helps to notice most typos of the master password, while decreasing security slightly. # SECURITY CONSIDERATIONS You **should** back up and encrypt your master key. The `rwd_keys` configuration setting, if set to False protects against offline master password bruteforce attacks - which is also a security guarantee of the original SPHINX protocol. The drawback is that for known (host,username) pairs the according record can be changed/deleted by an attacker if the clients masterkey is available to them. However neither the master nor the account password can leak this way. This is merely a denial-of-service attack vector. If `rwd_keys` is set to True, then this eliminates the denial-of-service vector, but also negates the offline-bruteforce guarantee of the SPHINX protocol. This setting is really a compromise between availability of account passwords versus the confidentiality of your master password. The `validate_password` configuration setting if enabled, decreases security slightly (by 5 bits). In general it should be safe to enable. In this man page we are using echo only for demonstration, you should use something like this instead (or even directly `getpwd(1)` from the contrib directory if you are not interested in customizing): ``` echo GETPIN | pinentry | grep '^D' | cut -c3- | sphinx create username example.com ulsd 0 ``` Using pinentry you can go fancy and do double password input, and even have something checking password quality for you, check it out, it's quite versatile. # 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 . 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 `oracle(1)`, `getpwd(1)` ���������������������������������������������������������������������������������������������������������������������������������������������������������������pwdsphinx-1.0.18/man/type-pwd.md��������������������������������������������������������������������0000664�0000000�0000000�00000002343�14462022215�0016473�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 This script combines `getpwd(1)`, `exec-on-click(1)` and the `sphinx(1)` client in such a way, that it securely queries for your master password, and then waits until you click somewhere (hopefully into a password entry field) and then sends the password as keystrokes. Using this mechanism you make sure your password is never on your clipboard where malware might steal it. And also it allows to enter your password on those sites that disable copy/pasting into password fields. When you click make sure you click in the password entry field where you want the password to be 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 . 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-1.0.18/man/websphinx.md�������������������������������������������������������������������0000664�0000000�0000000�00000001650�14462022215�0016731�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` is a native-messaging backend for webextensions that expose the SPHINX password storage protocol in a browser. When a browser starts and the appropriate extension is installed it starts the native-messaging backend automatically. # 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 . 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-1.0.18/pwdsphinx/�������������������������������������������������������������������������0000775�0000000�0000000�00000000000�14462022215�0015647�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������pwdsphinx-1.0.18/pwdsphinx/__init__.py��������������������������������������������������������������0000664�0000000�0000000�00000000000�14462022215�0017746�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������pwdsphinx-1.0.18/pwdsphinx/bin2pass.py��������������������������������������������������������������0000775�0000000�0000000�00000005705�14462022215�0017754�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<<256, 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, 32, '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(32) 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 else: usage() if size<0: print("error size must be < 0") usage() print(derive(raw,rule,size,syms)) if __name__ == '__main__': main() �����������������������������������������������������������pwdsphinx-1.0.18/pwdsphinx/config.py����������������������������������������������������������������0000775�0000000�0000000�00000001505�14462022215�0017472�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 os, configparser class StrippingQuotesConfigParser(configparser.ConfigParser): def get(self, section, option, **kwargs): val = configparser.ConfigParser.get(self, section, option, **kwargs) return val.strip('"') if hasattr(val,'strip') else val def getcfg(app): config = StrippingQuotesConfigParser() # read global cfg config.read('/etc/sphinx/config') # update with per-user configs config.read(os.path.expanduser("~/.sphinxrc")) config.read(os.path.expanduser("~/.config/sphinx/config")) # over-ride with local directory config config.read(os.path.expanduser("sphinx.cfg")) return config if __name__ == '__main__': import sys getcfg('sphinx').write(sys.stdout) �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������pwdsphinx-1.0.18/pwdsphinx/consts.py����������������������������������������������������������������0000664�0000000�0000000�00000000502�14462022215�0017527�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 COMMIT =b'\x99' # change sphinx CHANGE =b'\xaa' # sphinx DELETE =b'\xff' # sphinx+blobs CHALLENGE_CREATE = b'\x5a' CHALLENGE_VERIFY = b'\xa5' VERSION = b'\x00' RULE_SIZE = 79 ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������pwdsphinx-1.0.18/pwdsphinx/oracle.py����������������������������������������������������������������0000775�0000000�0000000�00000037331�14462022215�0017500�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 socket, sys, ssl, os, datetime, binascii, shutil, os.path, traceback, struct import pysodium import equihash from pwdsphinx import sphinxlib from pwdsphinx.config import getcfg from pwdsphinx.consts import * cfg = getcfg('sphinx') verbose = cfg['server'].getboolean('verbose', fallback=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")) 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") 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): cfg.write(sys.stdout) 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 :/ s.shutdown(socket.SHUT_RDWR) s.close() os._exit(0) def pop(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= 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 == CHALLENGE_CREATE: create_challenge(conn) elif op == CHALLENGE_VERIFY: verify_challenge(conn) def main(): 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('Bind failed. Error Code : %s Message: %s' % (str(msg[0]), msg[1])) sys.exit() #Start listening on socket s.listen() kids = [] try: # main loop while 1: #wait to accept a connection - blocking call try: conn, addr = s.accept() except socket.timeout: try: pid, status = os.waitpid(-1, os.WNOHANG) if pid != 0: print("remove pid", pid) kids.remove(pid) continue except ChildProcessError: continue except: raise if verbose: print('{} Connection from {}:{}'.format(datetime.datetime.now(), addr[0], addr[1])) conn = ctx.wrap_socket(conn, server_side=True) while(len(kids)>max_kids): pid, status = os.waitpid(0,0) kids.remove(pid) pid=os.fork() if pid==0: 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() if __name__ == '__main__': main() �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������pwdsphinx-1.0.18/pwdsphinx/sphinx.py����������������������������������������������������������������0000775�0000000�0000000�00000056147�14462022215�0017552�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, os, socket, ssl, struct, platform, getpass, time from SecureString import clearmem import pysodium from qrcodegen import QrCode from zxcvbn import zxcvbn from equihash import solve try: from pwdsphinx import bin2pass, sphinxlib from pwdsphinx.config import getcfg from pwdsphinx.consts import * except ImportError: import bin2pass, sphinxlib from config import getcfg from consts import * win=False if platform.system() == 'Windows': win=True #### config #### cfg = getcfg('sphinx') verbose = cfg['client'].getboolean('verbose', fallback=False) hostname = cfg['client'].get('address','127.0.0.1') address = socket.gethostbyname(hostname) port = int(cfg['client'].get('port',2355)) datadir = os.path.expanduser(cfg['client'].get('datadir','~/.config/sphinx')) try: ssl_cert = os.path.expanduser(cfg['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['client'].getboolean('rwd_keys', fallback=False) validate_password = cfg['client'].getboolean('validate_password',True) 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) #### 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(5) 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) # todo change this to len(user)|user|len(host)|host 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 pack_rule(char_classes, syms, size, check_digit, xor_mask=None): # 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 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' * 32 elif len(xor_mask)!=32: raise ValueError("ERROR: xor_mask must be 32bytes, 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(s,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 = sphinxlib.finish(pwd, r, alpha, beta, id) sk, pk = get_signkey(id, rwd) sig = pysodium.crypto_sign_detached(nonce,sk) clearmem(sk) s.send(sig) return rwd 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 getpwd(): if sys.stdin.isatty(): return getpass.getpass("enter your password please: ").encode('utf8') else: return sys.stdin.buffer.readline().rstrip(b'\n') #### OPs #### def init_key(): 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: clearmem(mk) return 0 def create(s, pwd, user, host, char_classes='uld', symbols=bin2pass.symbols, size=0, target=None): # 1st step OPRF on the new seed id = getid(host, user) r, alpha = sphinxlib.challenge(pwd) msg = b''.join([CREATE, id, alpha]) s.send(msg) # wait for response from sphinx server beta = s.recv(32) if beta == b'\x00\x04fail': s.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 rwd = sphinxlib.finish(pwd, r, alpha, beta, id) # second phase, derive new auth signing pubkey sk, pk = get_signkey(id, rwd) clearmem(sk) if validate_password: checkdigit = pysodium.crypto_generichash(CHECK_CTX, rwd, 1)[0] else: checkdigit = 0 if target: trwd, char_classes, symbols = bin2pass.pass2bin(target, None) xormask = xor(pysodium.crypto_generichash(PASS_CTX, rwd),trwd) size = len(target) #char_classes = 'uld' #symbols = bin2pass.symbols else: xormask = pysodium.randombytes(32) rule = pack_rule(char_classes, symbols, size, checkdigit, xormask) # send over new signed(pubkey, rule) msg = b''.join([pk, rule]) msg = sign_blob(msg, id, rwd) s.send(msg) # add user to user list for this host # a malicous server could correlate all accounts on this services to this users here update_rec(s, host, user) s.close() rwd = xor(pysodium.crypto_generichash(PASS_CTX, rwd),xormask) ret = bin2pass.derive(rwd,char_classes,size,symbols) clearmem(rwd) return ret def get(s, pwd, user, host): id = getid(host, user) r, alpha = sphinxlib.challenge(pwd) msg = b''.join([GET, 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 = sphinxlib.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) ret = bin2pass.derive(rwd,classes,size,symbols) clearmem(rwd) return ret def read_blob(s, id, rwd = b''): msg = b''.join([READ, id]) s = ratelimit(s, msg) if auth(s,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(s, host): res = read_blob(s, getid(host, '')) if not res: return "no users found" version, res = res users = set(res.decode().split('\x00')) return '\n'.join(sorted(users)) def change(s, oldpwd, newpwd, user, host, classes='uld', symbols=bin2pass.symbols, size=0, target=None): id = getid(host, user) r, alpha = sphinxlib.challenge(oldpwd) msg = b''.join([CHANGE, id, alpha]) s = ratelimit(s, msg) # auth: do sphinx with current seed, use it to sign the nonce if not auth(s,id,alpha,oldpwd,r): s.close() raise ValueError("ERROR: Failed to authenticate using old password to server while changing password on server or record doesn't exist") r, alpha = sphinxlib.challenge(newpwd) s.send(alpha) beta = s.recv(32) # beta if beta == b'\x00\x04fail' or len(beta)!=32: s.close() raise ValueError("ERROR: changing password failed due to corruption during transport.") rwd = sphinxlib.finish(newpwd, r, alpha, beta, id) if validate_password: checkdigit = pysodium.crypto_generichash(CHECK_CTX, rwd, 1)[0] else: checkdigit = 0 if target: trwd, classes, symbols = bin2pass.pass2bin(target, None) xormask = xor(pysodium.crypto_generichash(PASS_CTX, rwd),trwd) size = len(target) else: xormask = pysodium.randombytes(32) rule = pack_rule(classes, symbols, size, checkdigit, xormask) sk, pk = get_signkey(id, rwd) clearmem(sk) # send over new signed(pubkey) s.send(sign_blob(b''.join([pk,rule]), id, rwd)) if s.recv(2)!=b'ok': s.close() raise ValueError("ERROR: failed to update password rules on the server during changing of password.") s.close() rwd = xor(pysodium.crypto_generichash(PASS_CTX, rwd),xormask) ret = bin2pass.derive(rwd,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(s, pwd, user, host): # run sphinx to recover rwd for authentication id = getid(host, user) r, alpha = sphinxlib.challenge(pwd) msg = b''.join([DELETE, id, alpha]) s = ratelimit(s, msg) rwd = auth(s,id,alpha,pwd,r) if not rwd: s.close() raise ValueError("ERROR: Failed to authenticate to server while deleting password on server or record doesn't exist") # 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() clearmem(rwd) 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 qrcode(output, key): mk=get_masterkey() if key else b'' data = (bytes([1*key+2*rwd_keys + 4*validate_password]) + mk + struct.pack("!H", port) + hostname.encode("utf8")) 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 usage(params, help=False): print("usage: %s init" % params[0]) print(" echo -n 'password' | %s <[u][l][d][s] [] []> | []" % params[0]) print(" echo -n 'password' | %s get " % params[0]) print(" %s # if rwd_keys is false in your config" % params[0]) print(" echo -n 'password' | %s # if rwd_keys is true in your config" % params[0]) print(" %s list " % params[0]) print(" %s qr [svg] [key]" % params[0]) 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): 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): if len(params) < 2: usage(params, True) 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_key()) 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 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 else: usage(params) error = None s = None if cmd != users: pwd = '' if (rwd_keys or cmd in {create,change,get}): pwd = getpwd() if cmd == change: newpwd = getpwd() if not newpwd: newpwd = pwd test_pwd(newpwd) args=(newpwd,) + args if cmd == create: test_pwd(pwd) try: s = connect() ret = cmd(s, pwd, *args) except Exception as exc: error = exc ret = False #raise # only for dbg clearmem(pwd) else: try: s = connect() ret = cmd(s, *args) except Exception as exc: error = exc ret = False #raise # only for dbg if s and s.fileno() != -1: s.close() if not ret: if not error: print("fail", file=sys.stderr) sys.exit(3) # error not handled by exception print(error, file=sys.stderr) if str(error) == "ERROR: bad checkdigit": sys.exit(2) # bad check digit sys.exit(1) # generic errors if cmd not in {delete, undo, commit}: print(ret) sys.stdout.flush() clearmem(ret) elif ret != True: print("reached code that should not be reachable: ", ret) if __name__ == '__main__': try: main(sys.argv) except Exception: print("fail", file=sys.stderr) #raise # only for dbg pwdsphinx-1.0.18/pwdsphinx/sphinxlib.py000077500000000000000000000057061446202221500202340ustar00rootroot00000000000000"""Wrapper for libsphinx library SPDX-FileCopyrightText: 2018-21, Marsiske Stefan SPDX-License-Identifier: GPL-3.0-or-later This file is part of pwdsphinx. pwdsphinx 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. pwdsphinx 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 pitchforked sphinx. If not, see . """ import ctypes import ctypes.util sphinxlib = ctypes.cdll.LoadLibrary(ctypes.util.find_library('sphinx') or ctypes.util.find_library('libsphinx') or ctypes.util.find_library('libsphinx0')) if not sphinxlib._name: raise ValueError('Unable to find libsphinx') DECAF_255_SCALAR_BYTES = 32 DECAF_255_SER_BYTES = 32 crypto_pwhash_SALTBYTES = 16 def __check(code): if code != 0: raise ValueError # void challenge(const uint8_t *pwd, const size_t p_len, const uint8_t *salt, const size_t salt_len, uint8_t *bfac, uint8_t *chal) def challenge(pwd,salt=''): if pwd is None: raise ValueError("invalid parameter") bfac = ctypes.create_string_buffer(DECAF_255_SCALAR_BYTES) chal = ctypes.create_string_buffer(DECAF_255_SER_BYTES) sphinxlib.sphinx_challenge(pwd, len(pwd), salt, len(salt), bfac, chal) return (bfac.raw, chal.raw) # int respond(const uint8_t *chal, const uint8_t *secret, uint8_t *resp) def respond(chal, secret): if None in (chal, secret): raise ValueError("invalid parameter") if len(chal) != DECAF_255_SER_BYTES: raise ValueError("truncated point") if len(secret) != DECAF_255_SCALAR_BYTES: raise ValueError("truncated secret") resp = ctypes.create_string_buffer(DECAF_255_SER_BYTES) __check(sphinxlib.sphinx_respond(chal, secret, resp)) return resp.raw # int finish(const uint8_t *pwd, const size_t p_len, const uint8_t *bfac, const uint8_t *resp, uint8_t *rwd) def finish(pwd, bfac, chal, resp, salt): if None in (pwd, bfac, resp, salt): raise ValueError("invalid parameter") if len(resp) != DECAF_255_SER_BYTES: raise ValueError("truncated point") if len(chal) != DECAF_255_SER_BYTES: raise ValueError("truncated point") if len(bfac) != DECAF_255_SCALAR_BYTES: raise ValueError("truncated secret") if len(salt) < crypto_pwhash_SALTBYTES: raise ValueError("truncated salt") if(chal==resp): raise ValueError("alpha == beta") rwd = ctypes.create_string_buffer(DECAF_255_SER_BYTES) __check(sphinxlib.sphinx_finish(pwd, len(pwd), bfac, chal, resp, salt, rwd)) return rwd.raw pwdsphinx-1.0.18/pwdsphinx/websphinx.py000077500000000000000000000172561446202221500202460ustar00rootroot00000000000000#!/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 from zxcvbn import zxcvbn 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']['log'] def handler(cb, cmd, *args): s = sphinx.connect() cb(cmd(s, *args)) s.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((resp:=proc.stdout.readline())!=b'OK Pleased to meet you\n'): 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 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'] == 'login': get(data) elif data['cmd'] == 'list': users(data) elif data['cmd'] == 'create': create(data) elif data['cmd'] == 'change': change(data) elif data['cmd'] == 'commit': commit(data) elif data['cmd'] == 'undo': undo(data) elif data['cmd'] == 'qrcode': qrcode(data) if __name__ == '__main__': main() pwdsphinx-1.0.18/setup.py000077500000000000000000000041621446202221500153430ustar00rootroot00000000000000#!/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 = '1.0.16', 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'], install_requires = ("pysodium", "SecureString", "qrcodegen","zxcvbn-python", 'pyequihash'), 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:main', 'sphinx = pwdsphinx.sphinx:main', 'websphinx = pwdsphinx.websphinx:main', 'bin2pass = pwdsphinx.bin2pass:main', ], }, cmdclass={'sdist': BuildMakefilesSdist, 'build': BuildMakefilesBuild}, #ext_modules = [libsphinx], ) pwdsphinx-1.0.18/sphinx.cfg_sample000066400000000000000000000041501446202221500171560ustar00rootroot00000000000000# the client section is only needed if you use the client functionality [client] # whether to produce some output on the console #verbose = False # the ip address or hostname the server is listening on #address = 127.0.0.1 # the port on which the server is listening #port = 2355 # 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 # 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="server.der" # 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 # 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= pwdsphinx-1.0.18/tests/000077500000000000000000000000001446202221500147655ustar00rootroot00000000000000pwdsphinx-1.0.18/tests/test.py000066400000000000000000000325061446202221500163240ustar00rootroot00000000000000import unittest from os import listdir from shutil import rmtree from unittest.mock import Mock from io import BytesIO import sys, pysodium from pwdsphinx import sphinx, bin2pass # 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() data_dir = 'data/' data_dir = '/home/s/tasks/sphinx/zphinx/data/' orig_data_files = set(listdir(data_dir)) char_classes = 'uld' syms = bin2pass.symbols size = 0 pwd = 'asdf' user = 'user1' user2 = 'user2' host = 'example.com' class Input: def __init__(self, txt = None): if txt: self.buffer = BytesIO('\n'.join((pwd, txt)).encode()) else: self.buffer = BytesIO(pwd.encode()) def isatty(self): return False def cleanup(): for f in listdir(data_dir): if f not in orig_data_files: rmtree(data_dir+f) 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): def tearDown(self): cleanup() def test_create_user(self): with sphinx.connect() as s: self.assertIsInstance(sphinx.create(s, pwd, user, host, char_classes, syms, size), str) def test_huge_user(self): with sphinx.connect() as s: self.assertRaises(ValueError, sphinx.create,s, pwd, 'a'*(2**16 - 40), host, char_classes, syms, size) with sphinx.connect() as s: rwd=sphinx.create(s, pwd, 'a'*(2**16 - 42), host, char_classes, syms, size) self.assertIsInstance(rwd, str) with sphinx.connect() as s: self.assertRaises(ValueError, sphinx.create, s, pwd, 'a', host, char_classes, syms, size) def test_rules_u(self): with sphinx.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 sphinx.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 sphinx.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 sphinx.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 sphinx.connect() as s: rwd = sphinx.create(s, pwd, user, host, char_classes, syms, i) self.assertIsInstance(rwd, str) self.assertTrue(len(rwd)==i) with sphinx.connect() as s: self.assertTrue(sphinx.delete(s, pwd, user, host)) def test_invalid_rules(self): with sphinx.connect() as s: self.assertRaises(ValueError, sphinx.create, s, pwd, user, host, "asdf", syms, size) def test_recreate_user(self): with sphinx.connect() as s: self.assertIsInstance(sphinx.create(s, pwd, user, host, char_classes, syms, size), str) with sphinx.connect() as s: self.assertRaises(ValueError, sphinx.create,s, pwd, user, host, char_classes, syms, size) def test_get(self): with sphinx.connect() as s: rwd0 = sphinx.create(s, pwd, user, host, char_classes, syms, size) self.assertIsInstance(rwd0, str) s = sphinx.connect() rwd = sphinx.get(s, pwd, user, host) self.assertIsInstance(rwd, str) self.assertEqual(rwd,rwd0) def test_get_inv_mpwd(self): if not sphinx.validate_password: return with sphinx.connect() as s: rwd0 = sphinx.create(s, pwd, user, host, char_classes, syms, size) self.assertIsInstance(rwd0, str) with sphinx.connect() as s: self.assertRaises(ValueError, sphinx.get, s, 'zxcv1', user, host) def test_get_nonexistant_host(self): with sphinx.connect() as s: self.assertRaises(ValueError, sphinx.get, s, pwd, user, host) def test_delete(self): with sphinx.connect() as s: self.assertIsInstance(sphinx.create(s, pwd, user, host, char_classes, syms, size), str) with sphinx.connect() as s: self.assertTrue(sphinx.delete(s, pwd, user, host)) def test_delete_inv_mpwd(self): with sphinx.connect() as s: self.assertIsInstance(sphinx.create(s, pwd, user, host, char_classes, syms, size), str) with sphinx.connect() as s: self.assertRaises(ValueError, sphinx.delete, s, 'zxcv', user, host) def test_change(self): with sphinx.connect() as s: self.assertIsInstance(sphinx.create(s, pwd, user, host, char_classes, syms, size), str) with sphinx.connect() as s: pwd0 = sphinx.get(s, pwd, user, host) self.assertIsInstance(pwd0, str) with sphinx.connect() as s: pwd1 = sphinx.change(s, pwd, pwd, user, host) self.assertIsInstance(pwd1, str) self.assertNotEqual(pwd0, pwd1) with sphinx.connect() as s: pwd2 = sphinx.change(s, pwd, pwd.upper(), user, host) self.assertIsInstance(pwd2, str) self.assertNotEqual(pwd0, pwd2) self.assertNotEqual(pwd1, pwd2) def test_commit_undo(self): # create with sphinx.connect() as s: pwd0 = sphinx.create(s, pwd, user, host, char_classes, syms, size) self.assertIsInstance(pwd0, str) # get with sphinx.connect() as s: pwd1 = sphinx.get(s, pwd, user, host) self.assertIsInstance(pwd1, str) self.assertEqual(pwd0, pwd1) # change with sphinx.connect() as s: pwd2 = sphinx.change(s, pwd, pwd.upper(), user, host) self.assertIsInstance(pwd2, str) self.assertNotEqual(pwd1, pwd2) # get with sphinx.connect() as s: pwd3 = sphinx.get(s, pwd, user, host) self.assertIsInstance(pwd3, str) self.assertEqual(pwd1, pwd3) # commit with sphinx.connect() as s: sphinx.commit(s, pwd, user, host) with sphinx.connect() as s: pwd4 = sphinx.get(s, pwd.upper(), user, host) self.assertIsInstance(pwd4, str) self.assertEqual(pwd2, pwd4) # undo with sphinx.connect() as s: sphinx.undo(s, pwd.upper(), user, host, ) with sphinx.connect() as s: pwd5 = sphinx.get(s, pwd, user, host) self.assertIsInstance(pwd5, str) self.assertEqual(pwd1, pwd5) def test_commit_undo_inv_mpwd(self): # create with sphinx.connect() as s: pwd0 = sphinx.create(s, pwd, user, host, char_classes, syms, size) self.assertIsInstance(pwd0, str) # change invalid mpwd with sphinx.connect() as s: self.assertRaises(ValueError, sphinx.change,s, 'zxcv', pwd, user, host) # change correct mpwd with sphinx.connect() as s: pwd2 = sphinx.change(s, pwd, pwd, user, host) self.assertIsInstance(pwd2, str) self.assertNotEqual(pwd0, pwd2) # commit invalid mpwd with sphinx.connect() as s: self.assertRaises(ValueError, sphinx.commit,s, 'zxcv', user, host) # commit correct mpwd with sphinx.connect() as s: sphinx.commit(s, pwd, user, host) with sphinx.connect() as s: pwd4 = sphinx.get(s, pwd, user, host) self.assertIsInstance(pwd4, str) self.assertEqual(pwd2, pwd4) # undo invalid mpwd with sphinx.connect() as s: self.assertRaises(ValueError, sphinx.undo,s, 'zxcv', user, host) # undo correct mpwd with sphinx.connect() as s: sphinx.undo(s, pwd, user, host) with sphinx.connect() as s: pwd5 = sphinx.get(s, pwd, user, host) self.assertIsInstance(pwd5, str) self.assertEqual(pwd0, pwd5) def test_list_users(self): with sphinx.connect() as s: self.assertIsInstance(sphinx.create(s, pwd, user, host, char_classes, syms, size), str) with sphinx.connect() as s: self.assertIsInstance(sphinx.create(s, pwd, user2, host, char_classes, syms, size), str) with sphinx.connect() as s: users = sphinx.users(s, host) self.assertIsInstance(users, str) self.assertEqual(users, '\n'.join((user,user2))) def test_list_users_diff_mpwd(self): with sphinx.connect() as s: self.assertIsInstance(sphinx.create(s, pwd, user, host, char_classes, syms, size), str) with sphinx.connect() as s: self.assertIsInstance(sphinx.create(s, 'zxcv', user2, host, char_classes, syms, size), str) with sphinx.connect() as s: users = sphinx.users(s, host) self.assertIsInstance(users, str) self.assertEqual(users, '\n'.join((user,user2))) def test_double_commit(self): # create with sphinx.connect() as s: pwd0 = sphinx.create(s, pwd, user, host, char_classes, syms, size) self.assertIsInstance(pwd0, str) # change with sphinx.connect() as s: pwd2 = sphinx.change(s, pwd, pwd, user, host) self.assertIsInstance(pwd2, str) self.assertNotEqual(pwd0, pwd2) # commit with sphinx.connect() as s: sphinx.commit(s, pwd, user, host) with sphinx.connect() as s: pwd4 = sphinx.get(s, pwd, user, host) self.assertIsInstance(pwd4, str) self.assertEqual(pwd2, pwd4) # commit with sphinx.connect() as s: self.assertRaises(ValueError, sphinx.commit,s, pwd, user, host) def test_auth(self): # create with sphinx.connect() as s: rwd = sphinx.create(s, pwd, user, host, char_classes, syms, size) self.assertIsInstance(rwd, str) sphinx.get_signkey = bad_signkey with sphinx.connect() as s: self.assertRaises(ValueError, sphinx.change, s, pwd, pwd, user, host, char_classes, syms, size) sphinx.get_signkey = get_signkey def test_userblob_auth_create(self): # create with sphinx.connect() as s: rwd = sphinx.create(s, pwd, user, host, char_classes, syms, size) self.assertIsInstance(rwd, str) sphinx.get_signkey = bad_signkey with sphinx.connect() as s: self.assertRaises(ValueError, sphinx.create, s, pwd, user2, host, char_classes, syms, size) sphinx.get_signkey = get_signkey def test_create_user_xormask(self): with sphinx.connect() as s: rwd = sphinx.create(s, pwd, user, host, '', '', 0, pwd) self.assertIsInstance(rwd, str) self.assertEqual(pwd, rwd) def test_change_xormask(self): with sphinx.connect() as s: rwd0 = sphinx.create(s, pwd, user, host, char_classes, syms, size) self.assertIsInstance(rwd0, str) with sphinx.connect() as s: rwd1 = sphinx.change(s, pwd, pwd, user, host, '', '', 0, pwd) self.assertIsInstance(rwd1, str) self.assertEqual(rwd1, pwd) with sphinx.connect() as s: rwd2 = sphinx.change(s, pwd, pwd, user, host, '', '', 0, pwd+pwd) self.assertIsInstance(rwd2, str) self.assertEqual(rwd2, pwd+pwd) def test_main_create(self): sys.stdin = Input() self.assertIsNone(sphinx.main(('sphinx.py', 'create', user, host, char_classes, syms, str(size)))) def test_main_get(self): sys.stdin = Input() self.assertIsNone(sphinx.main(('sphinx.py', 'create', user, host, char_classes, syms, str(size)))) sys.stdin = Input() self.assertIsNone(sphinx.main(('sphinx.py', 'get', user, host))) def test_main_delete(self): sys.stdin = Input() self.assertIsNone(sphinx.main(('sphinx.py', 'create', user, host, char_classes, syms, str(size)))) sys.stdin = Input() self.assertIsNone(sphinx.main(('sphinx.py', 'delete', user, host))) def test_main_change_commit_undo(self): sys.stdin = Input("qwer") self.assertIsNone(sphinx.main(('sphinx.py', 'create', user, host, char_classes, syms, str(size)))) sys.stdin = Input() self.assertIsNone(sphinx.main(('sphinx.py', 'change', user, host, char_classes, syms, str(size)))) sys.stdin = Input() self.assertIsNone(sphinx.main(('sphinx.py', 'commit', user, host))) sys.stdin = Input() self.assertIsNone(sphinx.main(('sphinx.py', 'undo', user, host))) def test_main_inv_params(self): for cmd in ('create','get','change','commit','undo','delete','list'): self.assertRaises(SystemExit, sphinx.main, ('sphinx.py', cmd)) if __name__ == '__main__': unittest.main() pwdsphinx-1.0.18/tests/test_pass2bin.py000077500000000000000000000052001446202221500201170ustar00rootroot00000000000000#!/usr/bin/env python import unittest, random, math from pwdsphinx import bin2pass # to get coverage, run # PYTHONPATH=.. coverage run ../tests/pass2bin.py # coverage report -m # to just run the tests do # python3 -m unittest discover --start-directory ../tests class TestRules(unittest.TestCase): def test_invert_simple(self): target = "this is a pass2bin test string" rwd, classes, symbols = bin2pass.pass2bin(target) self.assertEqual(bin2pass.derive(rwd, classes, len(target), symbols), target) def test_invert_too_long(self): target = "this is a pass2bin test stringthis is a pass2bin test stringthis is a pass2bin test stringthis is a pass2bin test stringthis is a pass2bin test string" self.assertRaises(OverflowError, bin2pass.pass2bin, target) def test_invert_iter(self): chars = bin2pass.allchars for i in range(1,len(chars)): target=''.join(chars[:i]) try: rwd, classes, symbols = bin2pass.pass2bin(target) except OverflowError: break self.assertEqual(bin2pass.derive(rwd, classes, len(target), symbols), target) def test_invert_reviter(self): chars = bin2pass.allchars for i in range(1,len(chars)): target=''.join(chars[-i:]) try: rwd,classes, symbols = bin2pass.pass2bin(target) except OverflowError: break self.assertEqual(bin2pass.derive(rwd, classes, len(target), symbols), target) def test_invert_random(self): chars = bin2pass.allchars for _ in range(1000): target=''.join(random.choices(chars,k=random.randrange(1,39))) rwd,classes, symbols = bin2pass.pass2bin(target) self.assertEqual(bin2pass.derive(rwd, classes, len(target), symbols), target) def test_all_zeroes(self): logbase = int(math.log(1<<256, len(bin2pass.allchars))) target = bin2pass.allchars[0] * (logbase-1) + bin2pass.allchars[1] for _ in range(logbase): rwd,classes, symbols = bin2pass.pass2bin(target) self.assertEqual(bin2pass.derive(rwd, classes, len(target), symbols), target) target = target[1:]+bin2pass.allchars[0] def test_short_zeroes(self): logbase = int(math.log(1<<256, len(bin2pass.allchars))) target = bin2pass.allchars[0] * (logbase//2) + bin2pass.allchars[1] for _ in range(len(target)): ctarget = ''.join(target) (rwd,classes,symbols) = bin2pass.pass2bin(ctarget) self.assertEqual(bin2pass.derive(rwd, classes, len(ctarget), symbols), ctarget) target = target[1:]+bin2pass.allchars[0] if __name__ == '__main__': unittest.main() pwdsphinx-1.0.18/tests/test_rules.py000066400000000000000000000032171446202221500175330ustar00rootroot00000000000000import unittest from os import listdir from shutil import rmtree from unittest.mock import Mock from io import BytesIO import sys, pysodium from pwdsphinx import sphinx, bin2pass # to get coverage, run # PYTHONPATH=.. coverage run ../tests/rules.py # coverage report -m # to just run the tests do # python3 -m unittest discover --start-directory ../tests def equ(classes, syms, size, check, xor): unpacked = sphinx.unpack_rule(sphinx.pack_rule(classes, syms, size, check, xor)) assert set(classes) == unpacked[0] assert list(syms) == unpacked[1] assert size == unpacked[2] if sphinx.validate_password: assert check == unpacked[3] else: assert 0 == unpacked[3] assert xor == unpacked[4] from itertools import chain, combinations def powerset(iterable): "powerset([1,2,3]) --> () (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'*32) if cls!=tuple(): equ(''.join(cls), '', 64, 31, b'\x00'*32) equ('uld', bin2pass.symbols[:16], 64, 31, b'\x00'*32) equ('uld', bin2pass.symbols[16:], 64, 31, b'\x00'*32) equ('uld', bin2pass.symbols, 64, 31, b'\xff'*32) equ('uld', bin2pass.symbols, 64, 31, b'\xaa'*32) for i in range(128): equ('uld', bin2pass.symbols, i, 31, b'\xaa'*32) for i in range(32): equ('uld', bin2pass.symbols, 64, i, b'\xaa'*32) if __name__ == '__main__': unittest.main() pwdsphinx-1.0.18/tests/tests.sh000077500000000000000000000042551446202221500164740ustar00rootroot00000000000000#!/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-1.0.18/tests/ws-test.py000077500000000000000000000015531446202221500167540ustar00rootroot00000000000000#!/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' 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-1.0.18/whitepaper.org000066400000000000000000001226171446202221500165150ustar00rootroot00000000000000* 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 32 bytes derived from the SPHINX protocol by calculating: hash(pwd||hash2curve(pwd)*k), 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 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 which it contributes into the blinded hash of the users password: #+BEGIN_SRC beta = seed*alfa #+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 In our implementation `rwd` results in a high entropy 32 byte array. * 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 32 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 information 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 32 byte long xor mask. #+END_EXAMPLE The longest password we can derive out of 32 bytes, is only 76 chars long if only digits are allowed. Thus 7 bits are enough to encode the size of a password. 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] & 0x1ff #+END_SRC *** rwd to ASCII conversion The conversion from the 32 byte array to an ASCII printable string containing only the characters allowed by the rules interprets the 32 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 all zeroes, and thus the output of the SPHINX query is unchanged and thus 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 38 characters long. __Warning__ this mode generates passwords that violate the security guarantees of the sphinx protocol and should be avoided at all costs. This mode only exists as a convience function and a such a perfect example of convenience violating 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, 32, 'big') #+END_SRC ** 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 a version byte, that is authenticated but not encrypted. ** 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. One possibility would be to use a threshold-version of SPHINX to authenticate to a SPHINX server, however this brings up a few complications and availability issues. Another 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 the latter 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, 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. ** 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, Read 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. *** 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 = e25519_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. 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 = e25519_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. 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 - authentication public key - encrypted password rules The seed (also referred to as simply the "key"), is the secret component which during the Sphinx Query is contributed by the server to the final rwd. The authentication public key is a unique ed25519 key used to authenticate management operations on this record. ** 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. 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 - Get: query a record - Change: change the seed and update the password rules and auth pubkey associated with the record - 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` and `create` operation) 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 operation - 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 operation there is no ratelimit and hence the initial message for `create` operations lacks the first `ratelimit_op` field. 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 COMMIT = 0x99 CHANGE = 0xaa 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. ** Authentication The following management operations require authentication: Change, 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 nonce, then sends back the signature to the server. The server takes the authentication public key from the Sphinx record and verifies the signature over the nonce with this authentication public key. If this verification fails, the server aborts, otherwise it resumes control to the management operation requested. ** 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. 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. The client updates the user record (see below) for this host, requesting the current user record, decrypting it, 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 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. 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. 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 and if that 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 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 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. *** 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. 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. * 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 ** 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 IPv6, 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. ** 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.