pax_global_header00006660000000000000000000000064145700277340014523gustar00rootroot0000000000000052 comment=8b32afc3f7d5411c92f91801870898b056f565fc pykeepass-4.0.7/000077500000000000000000000000001457002773400135375ustar00rootroot00000000000000pykeepass-4.0.7/.github/000077500000000000000000000000001457002773400150775ustar00rootroot00000000000000pykeepass-4.0.7/.github/dependabot.yml000066400000000000000000000002641457002773400177310ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "pip" # See documentation for possible values directory: "/" # Location of package manifests schedule: interval: "monthly" pykeepass-4.0.7/.github/workflows/000077500000000000000000000000001457002773400171345ustar00rootroot00000000000000pykeepass-4.0.7/.github/workflows/ci.yaml000066400000000000000000000013111457002773400204070ustar00rootroot00000000000000name: CI on: [push, pull_request, workflow_dispatch] jobs: tests: runs-on: ubuntu-20.04 strategy: matrix: python-version: [3.6, 3.7, 3.8, 3.9, "3.10", "3.11"] fail-fast: false steps: - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | sudo apt update sudo apt-get install -y libxml2-dev libxmlsec1-dev python -m pip install --upgrade pip pip install .[test] - name: Run tests run: | python -m unittest tests.tests pykeepass-4.0.7/.gitignore000066400000000000000000000001471457002773400155310ustar00rootroot00000000000000.ropeproject/ *.pyc dist/ *.egg-info/ build/ *.xml Pipfile Pipfile.lock *.kdbx *.kdbx.out .idea .venv* pykeepass-4.0.7/CHANGELOG.rst000066400000000000000000000062061457002773400155640ustar00rootroot000000000000004.0.7 - 2024-02-29 ------------------ - fixed #359 - PyKeePass has `decrypt` kwarg for accessing header info - merged PR#347 - added Entry.index and Entry.move for moving entries - merged PR#367 - added Entry.autotype_window setter - merged PR#364 - allow filename/keyfile to be file-like objects - merged PR#371 - drop dateutil dependency - merged PR#348 - switch to pyproject.toml 4.0.6 - 2023-08-22 ------------------ - fixed #350 - fixed all Python 2 deprecation FIXMEs (e.g. future, ) 4.0.5 - 2023-06-05 ------------------ - fixed #344 - AttributeError when accessing Times with None value - use __hash__ when evaluating equality - use mtime/uuid for HistoryEntry hashing 4.0.4 - 2023-05-23 ------------------ - fixed #314 - correctly handle binaries with no data - fixed #265 - check for keepass signature - fixed #319 - support pathlib for filename/keyfile - fixed #194 - added 'protected' arg to _set_string_field - use official icon names from KeePass source and deprecate old icons - added Entry.is_custom_property_protected() - fixed #338 - allow comma entry tag separator 4.0.3 - 2022-06-21 ------------------ - added otp support - added debug_setup() function 4.0.2 - 2022-05-21 ------------------ - added support for argon2id key derivation function - added credential expiry functions - fixes #223 - safe saving 4.0.1 - 2021-05-22 ------------------ - added Entry.delete_history() - added HistoryEntry class - added Group.touch() - support 2.0 keyfiles - added PyKeePass.reload() - dropped python2 tests - fixed #284 - autotype_sequence returns string 'None' - fixed #244 - incorrect PKCS padding error 4.0.0 - 2021-01-15 ------------------ - paths changed from strings to lists - added PyKeePass.recyclebin_group - added PyKeePass.trash_group() - added PyKeePass.trash_entry() - added PyKeePass.empty_group() - support reading/saving from streams - fixed PyKeePass.dump_xml() pretty printing - fixed #212 - properly pad encrypted payload - fixed #222 - corrected transform_rounds field length 3.2.1 - 2020-07-19 ------------------ - pin construct version to last supporting python2 - hard dependency on pycryptodomex - fixed #193 - kp.groups, kp.entries not returning elements with name/title None 3.2.0 - 2020-01-18 ------------------ - added PyKeePass.xml() - added create_database() - added tag searching - #182 - fixed #181 - binary attachments missing Compressed attribute unparseable - fixed #129 - protected multiline fields missing newline - fixed problem where entries are protected after save 3.1.0 - 2019-10-24 ------------------ - removed context manager - added autotype string support - added attachments - fixed find_entries(path=xxx) behavior - Entry.uuid, Group.uuid now return uuid.UUID object instead of string 3.0.0 - 2018-09-07 ------------------ - added context manager - added custom string field searching - added 'Notes' field - renamed 'tree' argument to 'group' - KDBX4 support 2.8.0 - 2017-11-09 ------------------ 2.7.0 - 2017-06-25 ------------------ 2.6.0 - 2017-08-19 ------------------ 2.5.0 - 2017-03-19 ------------------ 2.4.0 - 2016-09-25 ------------------ 2.3.0 - 2016-10-13 ------------------- 2.2.0 - 2016-10-10 ------------------ pykeepass-4.0.7/LICENSE000066400000000000000000001045131457002773400145500ustar00rootroot00000000000000 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 . pykeepass-4.0.7/MANIFEST.in000066400000000000000000000002631457002773400152760ustar00rootroot00000000000000include LICENSE README.rst requirements.txt include pykeepass/blank_database.kdbx recursive-exclude * __pycache__ recursive-exclude * *.pyc recursive-exclude * *.pyo prune tests* pykeepass-4.0.7/Makefile000066400000000000000000000014211457002773400151750ustar00rootroot00000000000000.ONESHELL: .SHELLFLAGS = -ec .SILENT: version := $(shell python -c "import tomllib;print(tomllib.load(open('pyproject.toml', 'rb'))['project']['version'])") .PHONY: dist dist: python -m build .PHONY: release release: lock dist # check that changelog is updated if ! grep ${version} CHANGELOG.rst then echo "Changelog doesn't seem to be updated! Quitting..." exit 1 fi twine upload dist/pykeepass-$(version)* gh release create pykeepass-$(version) dist/pykeepass-$(version)* .PHONY: lock lock: # make a requirements.txt lockfile rm -rf .venv_lock virtualenv .venv_lock . .venv_lock/bin/activate pip install .[test] python tests/tests.py pip freeze > requirements.txt .PHONY: docs docs: lazydocs pykeepass --overview-file README.md ghp-import -f -p -b docs docs pykeepass-4.0.7/README.rst000066400000000000000000000367001457002773400152340ustar00rootroot00000000000000pykeepass ============ .. image:: https://github.com/libkeepass/pykeepass/workflows/CI/badge.svg :target: https://github.com/libkeepass/pykeepass/actions?query=workflow%3ACI .. image:: https://readthedocs.org/projects/pykeepass/badge/?version=latest :target: https://pykeepass.readthedocs.io/en/latest/?badge=latest :alt: Documentation Status .. image:: https://img.shields.io/matrix/pykeepass:matrix.org.svg :target: https://matrix.to/#/#pykeepass:matrix.org .. image:: https://img.shields.io/badge/irc-%23pykeepass-brightgreen :target: https://webchat.freenode.net/?channels=pykeepass This library allows you to write entries to a KeePass database. Come chat at `#pykeepass`_ on Freenode or `#pykeepass:matrix.org`_ on Matrix. .. _#pykeepass: irc://irc.freenode.net .. _#pykeepass\:matrix.org: https://matrix.to/#/%23pykeepass:matrix.org Installation ------------ .. code:: sudo apt install python3-lxml pip install pykeepass Example ------- .. code:: python from pykeepass import PyKeePass # load database >>> kp = PyKeePass('db.kdbx', password='somePassw0rd') # find any group by its name >>> group = kp.find_groups(name='social', first=True) # get the entries in a group >>> group.entries [Entry: "social/facebook (myusername)", Entry: "social/twitter (myusername)"] # find any entry by its title >>> entry = kp.find_entries(title='facebook', first=True) # retrieve the associated password >>> entry.password 's3cure_p455w0rd' # update an entry >>> entry.notes = 'primary facebook account' # create a new group >>> group = kp.add_group(kp.root_group, 'email') # create a new entry >>> kp.add_entry(group, 'gmail', 'myusername', 'myPassw0rdXX') Entry: "email/gmail (myusername)" # save database >>> kp.save() .. TODO: add `Entry` and `Group` sections to document attributes of each Finding Entries --------------- **find_entries** (title=None, username=None, password=None, url=None, notes=None, otp=None, path=None, uuid=None, tags=None, string=None, group=None, recursive=True, regex=False, flags=None, history=False, first=False) Returns entries which match all provided parameters, where ``title``, ``username``, ``password``, ``url``, ``notes``, ``otp``, ``autotype_window`` and ``autotype_sequence`` are strings, ``path`` is a list, ``string`` is a dict, ``autotype_enabled`` is a boolean, ``uuid`` is a ``uuid.UUID`` and ``tags`` is a list of strings. This function has optional ``regex`` boolean and ``flags`` string arguments, which means to interpret search strings as `XSLT style`_ regular expressions with `flags`_. .. _XSLT style: https://www.xml.com/pub/a/2003/06/04/tr.html .. _flags: https://www.w3.org/TR/xpath-functions/#flags The ``path`` list is a full path to an entry (ex. ``['foobar_group', 'foobar_entry']``). This implies ``first=True``. All other arguments are ignored when this is given. This is useful for handling user input. The ``string`` dict allows for searching custom string fields. ex. ``{'custom_field1': 'custom value', 'custom_field2': 'custom value'}`` The ``group`` argument determines what ``Group`` to search under, and the ``recursive`` boolean controls whether to search recursively. The ``history`` (default ``False``) boolean controls whether history entries should be included in the search results. The ``first`` (default ``False``) boolean controls whether to return the first matched item, or a list of matched items. * if ``first=False``, the function returns a list of ``Entry`` s or ``[]`` if there are no matches * if ``first=True``, the function returns the first ``Entry`` match, or ``None`` if there are no matches **entries** a flattened list of all entries in the database .. code:: python >>> kp.entries [Entry: "foo_entry (myusername)", Entry: "foobar_entry (myusername)", Entry: "social/gmail (myusername)", Entry: "social/facebook (myusername)"] >>> kp.find_entries(title='gmail', first=True) Entry: "social/gmail (myusername)" >>> kp.find_entries(title='foo.*', regex=True) [Entry: "foo_entry (myusername)", Entry: "foobar_entry (myusername)"] >>> entry = kp.find_entries(title='foo.*', url='.*facebook.*', regex=True, first=True) >>> entry.url 'facebook.com' >>> entry.title 'foo_entry' >>> entry.title = 'hello' >>> group = kp.find_group(name='social', first=True) >>> kp.find_entries(title='facebook', group=group, recursive=False, first=True) Entry: "social/facebook (myusername)" >>> entry.otp otpauth://totp/test:lkj?secret=TEST%3D%3D%3D%3D&period=30&digits=6&issuer=test Finding Groups -------------- **find_groups** (name=None, path=None, uuid=None, notes=None, group=None, recursive=True, regex=False, flags=None, first=False) where ``name`` and ``notes`` are strings, ``path`` is a list, ``uuid`` is a ``uuid.UUID``. This function has optional ``regex`` boolean and ``flags`` string arguments, which means to interpret search strings as `XSLT style`_ regular expressions with `flags`_. .. _XSLT style: https://www.xml.com/pub/a/2003/06/04/tr.html .. _flags: https://www.w3.org/TR/xpath-functions/#flags The ``path`` list is a full path to a group (ex. ``['foobar_group', 'sub_group']``). This implies ``first=True``. All other arguments are ignored when this is given. This is useful for handling user input. The ``group`` argument determines what ``Group`` to search under, and the ``recursive`` boolean controls whether to search recursively. The ``first`` (default ``False``) boolean controls whether to return the first matched item, or a list of matched items. * if ``first=False``, the function returns a list of ``Group`` s or ``[]`` if there are no matches * if ``first=True``, the function returns the first ``Group`` match, or ``None`` if there are no matches **root_group** the ``Root`` group to the database **groups** a flattened list of all groups in the database .. code:: python >>> kp.groups [Group: "foo", Group "foobar", Group: "social", Group: "social/foo_subgroup"] >>> kp.find_groups(name='foo', first=True) Group: "foo" >>> kp.find_groups(name='foo.*', regex=True) [Group: "foo", Group "foobar"] >>> kp.find_groups(path=['social'], regex=True) [Group: "social", Group: "social/foo_subgroup"] >>> kp.find_groups(name='social', first=True).subgroups [Group: "social/foo_subgroup"] >>> kp.root_group Group: "/" Entry Functions and Properties ------------------------------ **add_entry** (destination_group, title, username, password, url=None, notes=None, tags=None, expiry_time=None, icon=None, force_creation=False) **delete_entry** (entry) **trash_entry** (entry) move a group to the recycle bin. The recycle bin is created if it does not exit. ``entry`` must be an empty Entry. **move_entry** (entry, destination_group) **atime** access time **ctime** creation time **mtime** modification time where ``destination_group`` is a ``Group`` instance. ``entry`` is an ``Entry`` instance. ``title``, ``username``, ``password``, ``url``, ``notes``, ``tags``, ``icon`` are strings. ``expiry_time`` is a ``datetime`` instance. If ``expiry_time`` is a naive datetime object (i.e. ``expiry_time.tzinfo`` is not set), the timezone is retrieved from ``dateutil.tz.gettz()``. .. code:: python # add a new entry to the Root group >>> kp.add_entry(kp.root_group, 'testing', 'foo_user', 'passw0rd') Entry: "testing (foo_user)" # add a new entry to the social group >>> group = kp.find_groups(name='social', first=True) >>> entry = kp.add_entry(group, 'testing', 'foo_user', 'passw0rd') Entry: "testing (foo_user)" # save the database >>> kp.save() # delete an entry >>> kp.delete_entry(entry) # move an entry >>> kp.move_entry(entry, kp.root_group) # save the database >>> kp.save() # change creation time >>> from datetime import datetime, timezone >>> entry.ctime = datetime(2023, 1, 1, tzinfo=timezone.utc) # update modification or access time >>> entry.touch(modify=True) Group Functions and Properties ------------------------------ **add_group** (destination_group, group_name, icon=None, notes=None) **delete_group** (group) **trash_group** (group) move a group to the recycle bin. The recycle bin is created if it does not exit. ``group`` must be an empty Group. **empty_group** (group) delete all entries and subgroups of a group. ``group`` is an instance of ``Group``. **move_group** (group, destination_group) **atime** access time **ctime** creation time **mtime** modification time ``destination_group`` and ``group`` are instances of ``Group``. ``group_name`` is a string .. code:: python # add a new group to the Root group >>> group = kp.add_group(kp.root_group, 'social') # add a new group to the social group >>> group2 = kp.add_group(group, 'gmail') Group: "social/gmail" # save the database >>> kp.save() # delete a group >>> kp.delete_group(group) # move a group >>> kp.move_group(group2, kp.root_group) # save the database >>> kp.save() # change creation time >>> from datetime import datetime, timezone >>> group.ctime = datetime(2023, 1, 1, tzinfo=timezone.utc) # update modification or access time >>> group.touch(modify=True) Attachments ----------- In this section, *binary* refers to the bytes of the attached data (stored at the root level of the database), while *attachment* is a reference to a binary (stored in an entry). A binary can be referenced by none, one or many attachments. **add_binary** (data, compressed=True, protected=True) where ``data`` is bytes. Adds a blob of data to the database. The attachment reference must still be added to an entry (see below). ``compressed`` only applies to KDBX3 and ``protected`` only applies to KDBX4 (no effect if used on wrong database version). Returns id of attachment. **delete_binary** (id) where ``id`` is an int. Removes binary data from the database and deletes any attachments that reference it. Since attachments reference binaries by their positional index, attachments that reference binaries with id > ``id`` will automatically be decremented. **find_attachments** (id=None, filename=None, element=None, recursive=True, regex=False, flags=None, history=False, first=False) where ``id`` is an int, ``filename`` is a string, and element is an ``Entry`` or ``Group`` to search under. * if ``first=False``, the function returns a list of ``Attachment`` s or ``[]`` if there are no matches * if ``first=True``, the function returns the first ``Attachment`` match, or ``None`` if there are no matches **binaries** list of bytestrings containing binary data. List index corresponds to attachment id **attachments** list containing all ``Attachment`` s in the database. **Entry.add_attachment** (id, filename) where ``id`` is an int and ``filename`` is a string. Creates a reference using the given filename to a database binary. The existence of a binary with the given id is not checked. Returns ``Attachment``. **Entry.delete_attachment** (attachment) where ``attachment`` is an ``Attachment``. Deletes a reference to a database binary. **Entry.attachments** list of ``Attachment`` s for this Entry. **Attachment.id** id of data that this attachment points to **Attachment.filename** string representing this attachment **Attachment.data** the data that this attachment points to. Raises ``BinaryError`` if data does not exist. **Attachment.entry** the entry that this attachment is attached to .. code:: python >>> e = kp.add_entry(kp.root_group, title='foo', username='', password='') # add attachment data to the db >>> binary_id = kp.add_binary(b'Hello world') >>> kp.binaries [b'Hello world'] # add attachment reference to entry >>> a = e.add_attachment(binary_id, 'hello.txt') >>> a Attachment: 'hello.txt' -> 0 # access attachments >>> a Attachment: 'hello.txt' -> 0 >>> a.id 0 >>> a.filename 'hello.txt' >>> a.data b'Hello world' >>> e.attachments [Attachment: 'hello.txt' -> 0] # list all attachments in the database >>> kp.attachments [Attachment: 'hello.txt' -> 0] # search attachments >>> kp.find_attachments(filename='hello.txt') [Attachment: 'hello.txt** -> 0] # delete attachment reference >>> e.delete_attachment(a) # or, delete both attachment reference and binary >>> kp.delete_binary(binary_id** Credential Expiry ----------------- **credchange_date** datetime object with date of last credentials change **credchange_required** boolean whether database credentials have expired and are required to change **credchange_recommended** boolean whether database credentials have expired and are recommended to change **credchange_required_days** days after **credchange_date** that credential update is required **credchange_recommended_days** days after **credchange_date** that credential update is recommended Miscellaneous ------------- **read** (filename=None, password=None, keyfile=None, transformed_key=None, decrypt=False) where ``filename``, ``password``, and ``keyfile`` are strings ( ``filename`` and ``keyfile`` may also be file-like objects). ``filename`` is the path to the database, ``password`` is the master password string, and ``keyfile`` is the path to the database keyfile. At least one of ``password`` and ``keyfile`` is required. Alternatively, the derived key can be supplied directly through ``transformed_key``. ``decrypt`` tells whether the file should be decrypted or not. Can raise ``CredentialsError``, ``HeaderChecksumError``, or ``PayloadChecksumError``. **reload** () reload database from disk using previous credentials **save** (filename=None) where ``filename`` is the path of the file to save to (``filename`` may also be file-like object). If ``filename`` is not given, the path given in ``read`` will be used. **password** string containing database password. Can also be set. Use ``None`` for no password. **filename** string containing path to database. Can also be set **keyfile** string containing path to the database keyfile. Can also be set. Use ``None`` for no keyfile. **version** tuple containing database version. e.g. ``(3, 1)`` is a KDBX version 3.1 database. **encryption_algorithm** string containing algorithm used to encrypt database. Possible values are ``aes256``, ``chacha20``, and ``twofish``. **create_database** (filename, password=None, keyfile=None, transformed_key=None) create a new database at ``filename`` with supplied credentials. Returns ``PyKeePass`` object **tree** database lxml tree **xml** get database XML data as string **dump_xml** (filename) pretty print database XML to file TOTP ------- **Entry.otp** TOTP URI which can be passed to an OTP library to generate codes .. code:: python # find an entry which has otp attribute >>> e = kp.find_entries(otp='.*', regex=True, first=True) >>> import pyotp >>> pyotp.parse_uri(e.otp).now() 799270 Tests and Debugging ------------------- Run tests with :code:`python tests/tests.py` or :code:`python tests/tests.py SomeSpecificTest` Enable debugging when doing tests in console: >>> from pykeepass.pykeepass import debug_setup >>> debug_setup() >>> kp.entries[0] DEBUG:pykeepass.pykeepass:xpath query: //Entry DEBUG:pykeepass.pykeepass:xpath query: (ancestor::Group)[last()] DEBUG:pykeepass.pykeepass:xpath query: (ancestor::Group)[last()] DEBUG:pykeepass.pykeepass:xpath query: String/Key[text()="Title"]/../Value DEBUG:pykeepass.pykeepass:xpath query: String/Key[text()="UserName"]/../Value Entry: "root_entry (foobar_user)" pykeepass-4.0.7/pykeepass/000077500000000000000000000000001457002773400155435ustar00rootroot00000000000000pykeepass-4.0.7/pykeepass/__init__.py000066400000000000000000000002661457002773400176600ustar00rootroot00000000000000from __future__ import absolute_import from .pykeepass import PyKeePass, create_database from .version import __version__ __all__ = ["PyKeePass", "create_database", "__version__"] pykeepass-4.0.7/pykeepass/attachment.py000066400000000000000000000025721457002773400202530ustar00rootroot00000000000000from . import entry from .exceptions import BinaryError class Attachment(object): def __init__(self, element=None, kp=None, id=None, filename=None): self._element = element self._kp = kp def __repr__(self): return "Attachment: '{}' -> {}".format(self.filename, self.id) @property def id(self): """str: get or set id of binary the attachment points to""" return int(self._element.find('Value').attrib['Ref']) @id.setter def id(self, id): self._element.find('Value').attrib['Ref'] = str(id) @property def filename(self): """str: get or set filename attachment""" return self._element.find('Key').text @filename.setter def filename(self, filename): self._element.find('Key').text = filename @property def entry(self): """Entry: get entry this attachment is associated with""" ancestor = self._element.getparent() return entry.Entry(element=ancestor, kp=self._kp) @property def binary(self): """bytes: get binary this attachment points to""" try: return self._kp.binaries[self.id] except IndexError: raise BinaryError('No such binary with id {}'.format(self.id)) data = binary def delete(self): """delete this attachment""" self._element.getparent().remove(self._element) pykeepass-4.0.7/pykeepass/baseelement.py000066400000000000000000000125051457002773400204040ustar00rootroot00000000000000import base64 import uuid from lxml import etree from lxml.builder import E from datetime import datetime, timezone class BaseElement(): """Entry and Group inherit from this class""" def __init__(self, element, kp=None, icon=None, expires=False, expiry_time=None): self._element = element self._element.append( E.UUID(base64.b64encode(uuid.uuid1().bytes).decode('utf-8')) ) if icon: self._element.append(E.IconID(icon)) current_time_str = self._kp._encode_time(datetime.now(timezone.utc)) if expiry_time: expiry_time_str = self._kp._encode_time(expiry_time.astimezone(timezone.utc)) else: expiry_time_str = current_time_str self._element.append( E.Times( E.CreationTime(current_time_str), E.LastModificationTime(current_time_str), E.LastAccessTime(current_time_str), E.ExpiryTime(expiry_time_str), E.Expires(str(expires if expires is not None else False)), E.UsageCount(str(0)), E.LocationChanged(current_time_str) ) ) def _xpath(self, xpath, **kwargs): return self._kp._xpath(xpath, tree=self._element, **kwargs) def _get_subelement_text(self, tag): v = self._element.find(tag) if v is not None: return v.text def _set_subelement_text(self, tag, value): v = self._element.find(tag) if v is not None: self._element.remove(v) self._element.append(getattr(E, tag)(value)) @property def group(self): return self._xpath( '(ancestor::Group)[last()]', first=True, cast=True ) parentgroup = group def dump_xml(self, pretty_print=False): return etree.tostring(self._element, pretty_print=pretty_print) @property def uuid(self): """Returns uuid of this element as a uuid.UUID object""" b64_uuid = self._get_subelement_text('UUID') return uuid.UUID(bytes=base64.b64decode(b64_uuid)) @uuid.setter def uuid(self, uuid): """Set element uuid. `uuid` is a uuid.UUID object""" b64_uuid = base64.b64encode(uuid.bytes).decode('utf-8') return self._set_subelement_text('UUID', b64_uuid) @property def icon(self): return self._get_subelement_text('IconID') @icon.setter def icon(self, value): return self._set_subelement_text('IconID', value) @property def _path(self): return self._element.getroottree().getpath(self._element) def _get_times_property(self, prop): times = self._element.find('Times') if times is not None: prop = times.find(prop) if prop is not None and prop.text is not None: return self._kp._decode_time(prop.text) def _set_times_property(self, prop, value): times = self._element.find('Times') if times is not None: prop = times.find(prop) if prop is not None: prop.text = self._kp._encode_time(value) @property def expires(self): times = self._element.find('Times') d = times.find('Expires').text if d is not None: return d == 'True' @expires.setter def expires(self, value): d = self._element.find('Times').find('Expires') d.text = 'True' if value else 'False' @property def expired(self): if self.expires: return ( datetime.now(timezone.utc) > self.expiry_time ) return False @property def expiry_time(self): return self._get_times_property('ExpiryTime') @expiry_time.setter def expiry_time(self, value): self._set_times_property('ExpiryTime', value) @property def ctime(self): """(datetime.datetime): Creation time.""" return self._get_times_property('CreationTime') @ctime.setter def ctime(self, value): self._set_times_property('CreationTime', value) @property def atime(self): """(datetime.datetime): Access time. Update with touch()""" return self._get_times_property('LastAccessTime') @atime.setter def atime(self, value): self._set_times_property('LastAccessTime', value) @property def mtime(self): """(datetime.datetime): Access time. Update with touch(modify=True)""" return self._get_times_property('LastModificationTime') @mtime.setter def mtime(self, value): self._set_times_property('LastModificationTime', value) def delete(self): self._element.getparent().remove(self._element) def __unicode__(self): return self.__str__() def __repr__(self): return self.__str__() def __hash__(self): return hash((self.uuid,)) def __eq__(self, other): if isinstance(other, BaseElement): return hash(self) == hash(other) return NotImplemented def touch(self, modify=False): """ Update last access time of an entry/group Args: modify (bool): update access time as well a modification time """ now = datetime.now(timezone.utc) self.atime = now if modify: self.mtime = now pykeepass-4.0.7/pykeepass/blank_database.kdbx000066400000000000000000000025251457002773400213340ustar00rootroot00000000000000٢gK1qCPX!jZ !x4еwB6y*}|xa-RT!#7P(V˖5Ev B$UUIDcmߌ)DK IMPBS x9eCD=lk}Q~d/j_V *]lHeXN 'YibNKj%\_A?@LYA#\ͭ/>/H_%~m""!-ox~wih`V8/9kE@L $PYpkl/Z_aiwc%iʱ52٪8F:^F2WH5(,;)7mpY0>l=ex5O:9f1Khj߉Ty(muH%ڤ3٢'5 At3"=ىҡ1P ]4Y,ax)> FTȊ9]5]&%Ih ]}AJNjمdW;H߃VU:D,-EeHa6O3"6A} kXjL\Z/'܋)sac$$.ގE="ofo\ pB3rVYa4|j)gA N'-ROUyn&&z2kT#hw>pld$Abk "XDT){(=K#Yo Hx"NUr :Ge`7Od- ]]zWx]*9F%4 Container Convenience mapping so we dont have to iterate ListContainer to find the right item FIXME: lump kwarg was added to get around the fact that InnerHeader is not truly a dict. We lump all 'binary' InnerHeaderItems into a single list """ def __init__(self, key, subcon, lump=[]): super().__init__(subcon) self.key = key self.lump = lump # map ListContainer to Container def _decode(self, obj, context, path): d = OrderedDict() for l in self.lump: d[l] = ListContainer([]) for item in obj: if item[self.key] in self.lump: d[item[self.key]].append(item) else: d[item[self.key]] = item return Container(d) # map Container to ListContainer def _encode(self, obj, context, path): l = [] for key in obj: if key in self.lump: l += obj[key] else: l.append(obj[key]) return ListContainer(l) def Reparsed(subcon_out): class Reparsed(Adapter): """Bytes <---> Parsed subcon result Takes in bytes and reparses it with subcon_out""" def _decode(self, data, con, path): return subcon_out.parse(data, **con) def _encode(self, obj, con, path): return subcon_out.build(obj, **con) return Reparsed # is the payload compressed? CompressionFlags = BitsSwapped( BitStruct("compression" / Flag, Padding(8 * 4 - 1)) ) # -------------------- Key Computation -------------------- def aes_kdf(key, rounds, key_composite): """Set up a context for AES128-ECB encryption to find transformed_key""" cipher = AES.new(key, AES.MODE_ECB) # get the number of rounds from the header and transform the key_composite transformed_key = key_composite for _ in range(0, rounds): transformed_key = cipher.encrypt(transformed_key) return hashlib.sha256(transformed_key).digest() def compute_key_composite(password=None, keyfile=None): """Compute composite key. Used in header verification and payload decryption.""" # hash the password if password: password_composite = hashlib.sha256(password.encode('utf-8')).digest() else: password_composite = b'' # hash the keyfile if keyfile: if hasattr(keyfile, "read"): keyfile_bytes = keyfile.read() else: with open(keyfile, 'rb') as f: keyfile_bytes = f.read() # try to read XML keyfile try: tree = etree.fromstring(keyfile_bytes) version = tree.find('Meta/Version').text data_element = tree.find('Key/Data') if version.startswith('1.0'): keyfile_composite = base64.b64decode(data_element.text) elif version.startswith('2.0'): # read keyfile data and convert to bytes keyfile_composite = bytes.fromhex(data_element.text.strip()) # validate bytes against hash hash = bytes.fromhex(data_element.attrib['Hash']) hash_computed = hashlib.sha256(keyfile_composite).digest()[:4] assert hash == hash_computed, "Keyfile has invalid hash" else: raise AttributeError("Invalid version in keyfile") # otherwise, try to read plain keyfile except (etree.XMLSyntaxError, UnicodeDecodeError, AttributeError): try: try: int(keyfile_bytes, 16) is_hex = True except ValueError: is_hex = False # if the length is 32 bytes we assume it is the key if len(keyfile_bytes) == 32: keyfile_composite = keyfile_bytes # if the length is 64 bytes we assume the key is hex encoded elif len(keyfile_bytes) == 64 and is_hex: keyfile_composite = codecs.decode(keyfile_bytes, 'hex') # anything else may be a file to hash for the key else: keyfile_composite = hashlib.sha256(keyfile_bytes).digest() except: raise IOError('Could not read keyfile') else: keyfile_composite = b'' # create composite key from password and keyfile composites return hashlib.sha256(password_composite + keyfile_composite).digest() def compute_master(context): """Computes master key from transformed key and master seed. Used in payload decryption.""" # combine the transformed key with the header master seed to find the master_key master_key = hashlib.sha256( context._.header.value.dynamic_header.master_seed.data + context.transformed_key).digest() return master_key # -------------------- XML Processing -------------------- class XML(Adapter): """Bytes <---> lxml etree""" def _decode(self, data, con, path): parser = etree.XMLParser(remove_blank_text=True) return etree.parse(BytesIO(data), parser) def _encode(self, tree, con, path): return etree.tostring(tree) class UnprotectedStream(Adapter): """lxml etree <---> unprotected lxml etree Iterate etree for Protected elements and decrypt using cipher provided by get_cipher""" protected_xpath = '//Value[@Protected=\'True\']' def __init__(self, protected_stream_key, subcon): super().__init__(subcon) self.protected_stream_key = protected_stream_key def _decode(self, tree, con, path): cipher = self.get_cipher(self.protected_stream_key(con)) for elem in tree.xpath(self.protected_xpath): if elem.text is not None: try: result = cipher.decrypt(base64.b64decode(elem.text)).decode('utf-8') # strip invalid XML characters - https://stackoverflow.com/questions/8733233 result = re.sub( u'[^\u0020-\uD7FF\u0009\u000A\u000D\uE000-\uFFFD\U00010000-\U0010FFFF]+', '', result ) elem.text = result except (UnicodeDecodeError, BinasciiError, ValueError): # FIXME: this should be a warning eventually, need to fix all databases in tests/ first log.error( "Element at {} marked as protected, but could not unprotect".format(tree.getpath(elem)) ) return tree def _encode(self, tree, con, path): tree_copy = deepcopy(tree) cipher = self.get_cipher(self.protected_stream_key(con)) for elem in tree_copy.xpath(self.protected_xpath): if elem.text is not None: elem.text = base64.b64encode( cipher.encrypt( elem.text.encode('utf-8') ) ) return tree_copy class ARCFourVariantStream(UnprotectedStream): def get_cipher(self, protected_stream_key): raise Exception("ARCFourVariant not implemented") # https://github.com/dlech/KeePass2.x/blob/97141c02733cd3abf8d4dce1187fa7959ded58a8/KeePassLib/Cryptography/CryptoRandomStream.cs#L115-L119 class Salsa20Stream(UnprotectedStream): def get_cipher(self, protected_stream_key): key = hashlib.sha256(protected_stream_key).digest() return Salsa20.new( key=key, nonce=b'\xE8\x30\x09\x4B\x97\x20\x5D\x2A' ) # https://github.com/dlech/KeePass2.x/blob/97141c02733cd3abf8d4dce1187fa7959ded58a8/KeePassLib/Cryptography/CryptoRandomStream.cs#L103-L111 class ChaCha20Stream(UnprotectedStream): def get_cipher(self, protected_stream_key): key_hash = hashlib.sha512(protected_stream_key).digest() key = key_hash[:32] nonce = key_hash[32:44] return ChaCha20.new( key=key, nonce=nonce ) def Unprotect(protected_stream_id, protected_stream_key, subcon): """Select stream cipher based on protected_stream_id""" return Switch( protected_stream_id, {'arcfourvariant': ARCFourVariantStream(protected_stream_key, subcon), 'salsa20': Salsa20Stream(protected_stream_key, subcon), 'chacha20': ChaCha20Stream(protected_stream_key, subcon), }, default=subcon ) # -------------------- Payload Encryption/Decompression -------------------- class Concatenated(Adapter): """Data Blocks <---> Bytes""" def _decode(self, blocks, con, path): return b''.join([block.block_data for block in blocks]) def _encode(self, payload_data, con, path): blocks = [] # split payload_data into 1 MB blocks (spec default) i = 0 while i < len(payload_data): blocks.append(Container(block_data=payload_data[i:i + 2**20])) i += 2**20 blocks.append(Container(block_data=b'')) return blocks class DecryptedPayload(Adapter): """Encrypted Bytes <---> Decrypted Bytes""" def _decode(self, payload_data, con, path): cipher = self.get_cipher( con.master_key, con._.header.value.dynamic_header.encryption_iv.data ) payload_data = cipher.decrypt(payload_data) # FIXME: Construct ugliness. Fixes #244. First 32 bytes of decrypted kdbx3 payload # should be checked against stream_start_bytes for a CredentialsError. Due to construct # limitations, we have to decrypt the whole payload in order to check the first 32 bytes. # However, when the credentials are wrong the invalid decrypted payload cannot # be unpadded correctly. Instead, catch the unpad ValueError exception raised by unpad() # and allow kdbx3.py to raise a ChecksumError try: payload_data = self.unpad(payload_data) except ValueError: log.debug("Decryption unpadding failed") return payload_data def _encode(self, payload_data, con, path): payload_data = self.pad(payload_data) cipher = self.get_cipher( con.master_key, con._.header.value.dynamic_header.encryption_iv.data ) payload_data = cipher.encrypt(payload_data) return payload_data class AES256Payload(DecryptedPayload): def get_cipher(self, master_key, encryption_iv): return AES.new(master_key, AES.MODE_CBC, encryption_iv) def pad(self, data): return CryptoPadding.pad(data, 16) def unpad(self, data): return CryptoPadding.unpad(data, 16) class ChaCha20Payload(DecryptedPayload): def get_cipher(self, master_key, encryption_iv): return ChaCha20.new(key=master_key, nonce=encryption_iv) def pad(self, data): return data def unpad(self, data): return data class TwoFishPayload(DecryptedPayload): def get_cipher(self, master_key, encryption_iv): return Twofish.new(master_key, mode=Twofish.MODE_CBC, IV=encryption_iv) def pad(self, data): return CryptoPadding.pad(data, 16) def unpad(self, data): return CryptoPadding.unpad(data, 16) class Decompressed(Adapter): """Compressed Bytes <---> Decompressed Bytes""" def _decode(self, data, con, path): return zlib.decompress(data, 16 + 15) def _encode(self, data, con, path): compressobj = zlib.compressobj( 6, zlib.DEFLATED, 16 + 15, zlib.DEF_MEM_LEVEL, 0 ) data = compressobj.compress(data) data += compressobj.flush() return data # -------------------- Cipher Enums -------------------- # payload encryption method # https://github.com/keepassxreboot/keepassxc/blob/8324d03f0a015e62b6182843b4478226a5197090/src/format/KeePass2.cpp#L24-L26 CipherId = Mapping( GreedyBytes, {'aes256': b'1\xc1\xf2\xe6\xbfqCP\xbeX\x05!j\xfcZ\xff', 'twofish': b'\xadh\xf2\x9fWoK\xb9\xa3j\xd4z\xf9e4l', 'chacha20': b'\xd6\x03\x8a+\x8boL\xb5\xa5$3\x9a1\xdb\xb5\x9a' } ) # protected entry encryption method # https://github.com/dlech/KeePass2.x/blob/149ab342338ffade24b44aaa1fd89f14b64fda09/KeePassLib/Cryptography/CryptoRandomStream.cs#L35 ProtectedStreamId = Mapping( Int32ul, {'none': 0, 'arcfourvariant': 1, 'salsa20': 2, 'chacha20': 3, } ) pykeepass-4.0.7/pykeepass/kdbx_parsing/kdbx.py000066400000000000000000000016451457002773400215260ustar00rootroot00000000000000from construct import Struct, Switch, Bytes, Int16ul, RawCopy, Check, this from .kdbx3 import DynamicHeader as DynamicHeader3 from .kdbx3 import Body as Body3 from .kdbx4 import DynamicHeader as DynamicHeader4 from .kdbx4 import Body as Body4 # verify file signature def check_signature(ctx): return ctx.sig1 == b'\x03\xd9\xa2\x9a' and ctx.sig2 == b'\x67\xFB\x4B\xB5' KDBX = Struct( "header" / RawCopy( Struct( "sig1" / Bytes(4), "sig2" / Bytes(4), "sig_check" / Check(check_signature), "minor_version" / Int16ul, "major_version" / Int16ul, "dynamic_header" / Switch( this.major_version, {3: DynamicHeader3, 4: DynamicHeader4 } ) ) ), "body" / Switch( this.header.value.major_version, {3: Body3, 4: Body4 } ) ) pykeepass-4.0.7/pykeepass/kdbx_parsing/kdbx3.py000066400000000000000000000116011457002773400216020ustar00rootroot00000000000000# Evan Widloski - 2018-04-11 # keepass decrypt experimentation import hashlib from construct import ( Byte, Bytes, Int16ul, Int32ul, Int64ul, RepeatUntil, GreedyBytes, Struct, this, Mapping, Switch, Prefixed, Padding, Checksum, Computed, IfThenElse, Pointer, Tell, len_, If ) from .common import ( aes_kdf, AES256Payload, ChaCha20Payload, TwoFishPayload, Concatenated, DynamicDict, compute_key_composite, Decompressed, Reparsed, compute_master, CompressionFlags, XML, CipherId, ProtectedStreamId, Unprotect ) # -------------------- Key Derivation -------------------- # https://github.com/keepassxreboot/keepassxc/blob/8324d03f0a015e62b6182843b4478226a5197090/src/format/KeePass2.cpp#L24-L26 kdf_uuids = { 'aes': b'\xc9\xd9\xf3\x9ab\x8aD`\xbft\r\x08\xc1\x8aO\xea', } def compute_transformed(context): """Compute transformed key for opening database""" if context._._.transformed_key is not None: transformed_key = context._._.transformed_key else: key_composite = compute_key_composite( password=context._._.password, keyfile=context._._.keyfile ) transformed_key = aes_kdf( context._.header.value.dynamic_header.transform_seed.data, context._.header.value.dynamic_header.transform_rounds.data, key_composite ) return transformed_key # -------------------- Dynamic Header -------------------- # https://github.com/dlech/KeePass2.x/blob/dbb9d60095ef39e6abc95d708fb7d03ce5ae865e/KeePassLib/Serialization/KdbxFile.cs#L234-L246 DynamicHeaderItem = Struct( "id" / Mapping( Byte, {'end': 0, 'comment': 1, 'cipher_id': 2, 'compression_flags': 3, 'master_seed': 4, 'transform_seed': 5, 'transform_rounds': 6, 'encryption_iv': 7, 'protected_stream_key': 8, 'stream_start_bytes': 9, 'protected_stream_id': 10, } ), "data" / Prefixed( Int16ul, Switch( this.id, {'compression_flags': CompressionFlags, 'cipher_id': CipherId, 'transform_rounds': Int64ul, 'protected_stream_id': ProtectedStreamId }, default=GreedyBytes ) ), ) DynamicHeader = DynamicDict( 'id', RepeatUntil( lambda item, a, b: item.id == 'end', DynamicHeaderItem ) ) # -------------------- Payload Verification -------------------- # encrypted payload is split into multiple data blocks with hashes PayloadBlock = Struct( "block_index" / Checksum( Int32ul, lambda this: this._index, this ), "block_hash_offset" / Tell, Padding(32), "block_data" / Prefixed(Int32ul, GreedyBytes), # block_hash has to be at the end with a pointer because it needs to # come after other fields "block_hash" / Pointer( this.block_hash_offset, IfThenElse( len_(this.block_data) == 0, Checksum( Bytes(32), lambda _: b'\x00' * 32, this ), Checksum( Bytes(32), lambda block_data: hashlib.sha256(block_data).digest(), this.block_data, # exception=PayloadChecksumError ) ) ), ) PayloadBlocks = RepeatUntil( lambda item, a, b: len(item.block_data) == 0, # and item.block_hash == b'\x00' * 32, PayloadBlock ) # -------------------- Payload Decryption/Decompression -------------------- # Compressed Bytes <---> Stream Start Bytes, Decompressed XML UnpackedPayload = Reparsed( Struct( # validate payload decryption "cred_check" / Checksum( Bytes(32), lambda this: this._._.header.value.dynamic_header.stream_start_bytes.data, this, # exception=CredentialsError ), "xml" / Unprotect( this._._.header.value.dynamic_header.protected_stream_id.data, this._._.header.value.dynamic_header.protected_stream_key.data, XML( IfThenElse( this._._.header.value.dynamic_header.compression_flags.data.compression, Decompressed(Concatenated(PayloadBlocks)), Concatenated(PayloadBlocks) ) ) ) ) ) # -------------------- Main KDBX Structure -------------------- Body = Struct( "transformed_key" / Computed(compute_transformed), "master_key" / Computed(compute_master), "payload" / If(this._._.decrypt, UnpackedPayload( Switch( this._.header.value.dynamic_header.cipher_id.data, {'aes256': AES256Payload(GreedyBytes), 'chacha20': ChaCha20Payload(GreedyBytes), 'twofish': TwoFishPayload(GreedyBytes), } ) ) ), ) pykeepass-4.0.7/pykeepass/kdbx_parsing/kdbx4.py000066400000000000000000000176101457002773400216110ustar00rootroot00000000000000# Evan Widloski - 2018-04-11 # keepass decrypt experimentation import struct import hashlib import argon2 import hmac from construct import ( Byte, Bytes, Int32ul, RepeatUntil, GreedyBytes, Struct, this, Mapping, Switch, Flag, Prefixed, Int64ul, Int32sl, Int64sl, GreedyString, Padding, Peek, Checksum, Computed, IfThenElse, Pointer, Tell, If ) from .common import ( aes_kdf, Concatenated, AES256Payload, ChaCha20Payload, TwoFishPayload, DynamicDict, compute_key_composite, Reparsed, Decompressed, compute_master, CompressionFlags, XML, CipherId, ProtectedStreamId, Unprotect ) # -------------------- Key Derivation -------------------- # https://github.com/keepassxreboot/keepassxc/blob/bc55974ff304794e53c925442784c50a2fdaf6ee/src/format/KeePass2.cpp#L30-L33 kdf_uuids = { 'argon2': b'\xefcm\xdf\x8c)DK\x91\xf7\xa9\xa4\x03\xe3\n\x0c', 'argon2id': b'\x9e)\x8b\x19V\xdbGs\xb2=\xfc>\xc6\xf0\xa1\xe6', 'aeskdf': b'\xc9\xd9\xf3\x9ab\x8aD`\xbft\r\x08\xc1\x8aO\xea', } def compute_transformed(context): """Compute transformed key for opening database""" key_composite = compute_key_composite( password=context._._.password, keyfile=context._._.keyfile ) kdf_parameters = context._.header.value.dynamic_header.kdf_parameters.data.dict if context._._.transformed_key is not None: transformed_key = context._._.transformed_key elif kdf_parameters['$UUID'].value in (kdf_uuids['argon2'], kdf_uuids['argon2id']): transformed_key = argon2.low_level.hash_secret_raw( secret=key_composite, salt=kdf_parameters['S'].value, hash_len=32, type=(argon2.low_level.Type.ID if kdf_parameters['$UUID'].value == kdf_uuids['argon2id'] else argon2.low_level.Type.D), time_cost=kdf_parameters['I'].value, memory_cost=kdf_parameters['M'].value // 1024, parallelism=kdf_parameters['P'].value, version=kdf_parameters['V'].value ) elif kdf_parameters['$UUID'].value == kdf_uuids['aeskdf']: key_composite = compute_key_composite( password=context._._.password, keyfile=context._._.keyfile ) transformed_key = aes_kdf( kdf_parameters['S'].value, kdf_parameters['R'].value, key_composite ) else: raise Exception('Unsupported key derivation method') return transformed_key def compute_header_hmac_hash(context): """Compute HMAC-SHA256 hash of header. Used to prevent header tampering.""" return hmac.new( hashlib.sha512( b'\xff' * 8 + hashlib.sha512( context._.header.value.dynamic_header.master_seed.data + context.transformed_key + b'\x01' ).digest() ).digest(), context._.header.data, hashlib.sha256 ).digest() # --------------- KDF Params / Plugin Data ---------------- VariantDictionaryItem = Struct( "type" / Byte, "key" / Prefixed(Int32ul, GreedyString('utf-8')), "value" / Prefixed( Int32ul, Switch( this.type, {0x04: Int32ul, 0x05: Int64ul, 0x08: Flag, 0x0C: Int32sl, 0x0D: Int64sl, 0x42: GreedyBytes, 0x18: GreedyString('utf-8') } ) ), "next_byte" / Peek(Byte) ) # new dynamic dictionary structure added in KDBX4 VariantDictionary = Struct( "version" / Bytes(2), "dict" / DynamicDict( 'key', RepeatUntil( lambda item, a, b: item.next_byte == 0x00, VariantDictionaryItem ) ), Padding(1) * "null padding" ) # -------------------- Dynamic Header -------------------- # https://github.com/dlech/KeePass2.x/blob/dbb9d60095ef39e6abc95d708fb7d03ce5ae865e/KeePassLib/Serialization/KdbxFile.cs#L234-L246 DynamicHeaderItem = Struct( "id" / Mapping( Byte, {'end': 0, 'comment': 1, 'cipher_id': 2, 'compression_flags': 3, 'master_seed': 4, 'encryption_iv': 7, 'kdf_parameters': 11, 'public_custom_data': 12 } ), "data" / Prefixed( Int32ul, Switch( this.id, {'compression_flags': CompressionFlags, 'kdf_parameters': VariantDictionary, 'cipher_id': CipherId }, default=GreedyBytes ) ) ) DynamicHeader = DynamicDict( 'id', RepeatUntil( lambda item, a, b: item.id == 'end', DynamicHeaderItem ) ) # -------------------- Payload Verification -------------------- def compute_payload_block_hash(this): """Compute hash of each payload block. Used to prevent payload corruption and tampering.""" return hmac.new( hashlib.sha512( struct.pack(' 13 december 2007. ## ## Copyrights ## ========== ## ## This code is a derived from an implementation by Dr Brian Gladman ## (gladman@seven77.demon.co.uk) which is subject to the following license. ## This Python implementation is not subject to any other license. ## ##/* This is an independent implementation of the encryption algorithm: */ ##/* */ ##/* Twofish by Bruce Schneier and colleagues */ ##/* */ ##/* which is a candidate algorithm in the Advanced Encryption Standard */ ##/* programme of the US National Institute of Standards and Technology. */ ##/* */ ##/* Copyright in this implementation is held by Dr B R Gladman but I */ ##/* hereby give permission for its free direct or derivative use subject */ ##/* to acknowledgment of its origin and compliance with any conditions */ ##/* that the originators of t he algorithm place on its exploitation. */ ##/* */ ##/* My thanks to Doug Whiting and Niels Ferguson for comments that led */ ##/* to improvements in this implementation. */ ##/* */ ##/* Dr Brian Gladman (gladman@seven77.demon.co.uk) 14th January 1999 */ ## ## The above copyright notice must not be removed. ## ## Information ## =========== ## ## Anyone thinking of using this code should reconsider. It's slow. ## Try python-mcrypt instead. In case a faster library is not installed ## on the target system, this code can be used as a portable fallback. try: import psyco psyco.full() except ImportError: pass block_size = 16 key_size = 32 class Twofish: def __init__(self, key=None): """Twofish.""" if key: self.set_key(key) def set_key(self, key): """Init.""" key_len = len(key) if key_len not in [16, 24, 32]: # XXX: add padding? raise KeyError("key must be 16, 24 or 32 bytes") if key_len % 4: # XXX: add padding? raise KeyError("key not a multiple of 4") if key_len > 32: # XXX: prune? raise KeyError("key_len > 32") self.context = TWI() key_word32 = [0] * 32 i = 0 while key: key_word32[i] = struct.unpack("> n) | ((x << (32 - n)) & 0xFFFFFFFF) def rotl32(x, n): return ((x << n) & 0xFFFFFFFF) | (x >> (32 - n)) class TWI: def __init__(self): self.k_len = 0 # word32 self.l_key = [0]*40 # word32 self.s_key = [0]*4 # word32 self.qt_gen = 0 # word32 self.q_tab = [[0]*256, [0]*256] # byte self.mt_gen = 0 # word32 self.m_tab = [[0]*256, [0]*256, [0]*256, [0]*256] # word32 self.mk_tab = [[0]*256, [0]*256, [0]*256, [0]*256] # word32 def byte(x, n): return (x >> (8 * n)) & 0xff tab_5b = [0, 90, 180, 238] tab_ef = [0, 238, 180, 90] ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15] ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7] qt0 = [[8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4], [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5]] qt1 = [[14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13], [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8]] qt2 = [[11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1], [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15]] qt3 = [[13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10], [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10]] def qp(n, x): # word32, byte n %= 0x100000000 x %= 0x100 a0 = x >> 4; b0 = x & 15; a1 = a0 ^ b0; b1 = ror4[b0] ^ ashx[a0]; a2 = qt0[n][a1]; b2 = qt1[n][b1]; a3 = a2 ^ b2; b3 = ror4[b2] ^ ashx[a2]; a4 = qt2[n][a3]; b4 = qt3[n][b3]; return (b4 << 4) | a4; def gen_qtab(pkey): for i in range(256): pkey.q_tab[0][i] = qp(0, i) pkey.q_tab[1][i] = qp(1, i) def gen_mtab(pkey): for i in range(256): f01 = pkey.q_tab[1][i] f01 = pkey.q_tab[1][i]; f5b = ((f01) ^ ((f01) >> 2) ^ tab_5b[(f01) & 3]); fef = ((f01) ^ ((f01) >> 1) ^ ((f01) >> 2) ^ tab_ef[(f01) & 3]); pkey.m_tab[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24); pkey.m_tab[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24); f01 = pkey.q_tab[0][i]; f5b = ((f01) ^ ((f01) >> 2) ^ tab_5b[(f01) & 3]); fef = ((f01) ^ ((f01) >> 1) ^ ((f01) >> 2) ^ tab_ef[(f01) & 3]); pkey.m_tab[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24); pkey.m_tab[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24); def gen_mk_tab(pkey, key): if pkey.k_len == 2: for i in range(256): by = i % 0x100 pkey.mk_tab[0][i] = pkey.m_tab[0][pkey.q_tab[0][pkey.q_tab[0][by] ^ byte(key[1],0)] ^ byte(key[0],0)]; pkey.mk_tab[1][i] = pkey.m_tab[1][pkey.q_tab[0][pkey.q_tab[1][by] ^ byte(key[1],1)] ^ byte(key[0],1)]; pkey.mk_tab[2][i] = pkey.m_tab[2][pkey.q_tab[1][pkey.q_tab[0][by] ^ byte(key[1],2)] ^ byte(key[0],2)]; pkey.mk_tab[3][i] = pkey.m_tab[3][pkey.q_tab[1][pkey.q_tab[1][by] ^ byte(key[1],3)] ^ byte(key[0],3)]; if pkey.k_len == 3: for i in range(256): by = i % 0x100 pkey.mk_tab[0][i] = pkey.m_tab[0][pkey.q_tab[0][pkey.q_tab[0][pkey.q_tab[1][by] ^ byte(key[2], 0)] ^ byte(key[1], 0)] ^ byte(key[0], 0)]; pkey.mk_tab[1][i] = pkey.m_tab[1][pkey.q_tab[0][pkey.q_tab[1][pkey.q_tab[1][by] ^ byte(key[2], 1)] ^ byte(key[1], 1)] ^ byte(key[0], 1)]; pkey.mk_tab[2][i] = pkey.m_tab[2][pkey.q_tab[1][pkey.q_tab[0][pkey.q_tab[0][by] ^ byte(key[2], 2)] ^ byte(key[1], 2)] ^ byte(key[0], 2)]; pkey.mk_tab[3][i] = pkey.m_tab[3][pkey.q_tab[1][pkey.q_tab[1][pkey.q_tab[0][by] ^ byte(key[2], 3)] ^ byte(key[1], 3)] ^ byte(key[0], 3)]; if pkey.k_len == 4: for i in range(256): by = i % 0x100 pkey.mk_tab[0][i] = pkey.m_tab[0][pkey.q_tab[0][pkey.q_tab[0][pkey.q_tab[1][pkey.q_tab[1][by] ^ byte(key[3], 0)] ^ byte(key[2], 0)] ^ byte(key[1], 0)] ^ byte(key[0], 0)]; pkey.mk_tab[1][i] = pkey.m_tab[1][pkey.q_tab[0][pkey.q_tab[1][pkey.q_tab[1][pkey.q_tab[0][by] ^ byte(key[3], 1)] ^ byte(key[2], 1)] ^ byte(key[1], 1)] ^ byte(key[0], 1)]; pkey.mk_tab[2][i] = pkey.m_tab[2][pkey.q_tab[1][pkey.q_tab[0][pkey.q_tab[0][pkey.q_tab[0][by] ^ byte(key[3], 2)] ^ byte(key[2], 2)] ^ byte(key[1], 2)] ^ byte(key[0], 2)]; pkey.mk_tab[3][i] = pkey.m_tab[3][pkey.q_tab[1][pkey.q_tab[1][pkey.q_tab[0][pkey.q_tab[1][by] ^ byte(key[3], 3)] ^ byte(key[2], 3)] ^ byte(key[1], 3)] ^ byte(key[0], 3)]; def h_fun(pkey, x, key): b0 = byte(x, 0); b1 = byte(x, 1); b2 = byte(x, 2); b3 = byte(x, 3); if pkey.k_len >= 4: b0 = pkey.q_tab[1][b0] ^ byte(key[3], 0); b1 = pkey.q_tab[0][b1] ^ byte(key[3], 1); b2 = pkey.q_tab[0][b2] ^ byte(key[3], 2); b3 = pkey.q_tab[1][b3] ^ byte(key[3], 3); if pkey.k_len >= 3: b0 = pkey.q_tab[1][b0] ^ byte(key[2], 0); b1 = pkey.q_tab[1][b1] ^ byte(key[2], 1); b2 = pkey.q_tab[0][b2] ^ byte(key[2], 2); b3 = pkey.q_tab[0][b3] ^ byte(key[2], 3); if pkey.k_len >= 2: b0 = pkey.q_tab[0][pkey.q_tab[0][b0] ^ byte(key[1], 0)] ^ byte(key[0], 0); b1 = pkey.q_tab[0][pkey.q_tab[1][b1] ^ byte(key[1], 1)] ^ byte(key[0], 1); b2 = pkey.q_tab[1][pkey.q_tab[0][b2] ^ byte(key[1], 2)] ^ byte(key[0], 2); b3 = pkey.q_tab[1][pkey.q_tab[1][b3] ^ byte(key[1], 3)] ^ byte(key[0], 3); return pkey.m_tab[0][b0] ^ pkey.m_tab[1][b1] ^ pkey.m_tab[2][b2] ^ pkey.m_tab[3][b3]; def mds_rem(p0, p1): i, t, u = 0, 0, 0 for i in range(8): t = p1 >> 24 p1 = ((p1 << 8) & 0xffffffff) | (p0 >> 24) p0 = (p0 << 8) & 0xffffffff u = (t << 1) & 0xffffffff if t & 0x80: u ^= 0x0000014d p1 ^= t ^ ((u << 16) & 0xffffffff) u ^= (t >> 1) if t & 0x01: u ^= 0x0000014d >> 1 p1 ^= ((u << 24) & 0xffffffff) | ((u << 8) & 0xffffffff) return p1 def set_key(pkey, in_key, key_len): pkey.qt_gen = 0 if not pkey.qt_gen: gen_qtab(pkey) pkey.qt_gen = 1 pkey.mt_gen = 0 if not pkey.mt_gen: gen_mtab(pkey) pkey.mt_gen = 1 pkey.k_len = int((key_len * 8) / 64) a = 0 b = 0 me_key = [0,0,0,0] mo_key = [0,0,0,0] for i in range(pkey.k_len): a = in_key[i + i] me_key[i] = a b = in_key[i + i + 1] mo_key[i] = b pkey.s_key[pkey.k_len - i - 1] = mds_rem(a, b); for i in range(0, 40, 2): a = (0x01010101 * i) % 0x100000000; b = (a + 0x01010101) % 0x100000000; a = h_fun(pkey, a, me_key); b = rotl32(h_fun(pkey, b, mo_key), 8); pkey.l_key[i] = (a + b) % 0x100000000; pkey.l_key[i + 1] = rotl32((a + 2 * b) % 0x100000000, 9); gen_mk_tab(pkey, pkey.s_key) def encrypt(pkey, in_blk): blk = [0, 0, 0, 0] blk[0] = in_blk[0] ^ pkey.l_key[0]; blk[1] = in_blk[1] ^ pkey.l_key[1]; blk[2] = in_blk[2] ^ pkey.l_key[2]; blk[3] = in_blk[3] ^ pkey.l_key[3]; for i in range(8): t1 = ( pkey.mk_tab[0][byte(blk[1],3)] ^ pkey.mk_tab[1][byte(blk[1],0)] ^ pkey.mk_tab[2][byte(blk[1],1)] ^ pkey.mk_tab[3][byte(blk[1],2)] ); t0 = ( pkey.mk_tab[0][byte(blk[0],0)] ^ pkey.mk_tab[1][byte(blk[0],1)] ^ pkey.mk_tab[2][byte(blk[0],2)] ^ pkey.mk_tab[3][byte(blk[0],3)] ); blk[2] = rotr32(blk[2] ^ ((t0 + t1 + pkey.l_key[4 * (i) + 8]) % 0x100000000), 1); blk[3] = rotl32(blk[3], 1) ^ ((t0 + 2 * t1 + pkey.l_key[4 * (i) + 9]) % 0x100000000); t1 = ( pkey.mk_tab[0][byte(blk[3],3)] ^ pkey.mk_tab[1][byte(blk[3],0)] ^ pkey.mk_tab[2][byte(blk[3],1)] ^ pkey.mk_tab[3][byte(blk[3],2)] ); t0 = ( pkey.mk_tab[0][byte(blk[2],0)] ^ pkey.mk_tab[1][byte(blk[2],1)] ^ pkey.mk_tab[2][byte(blk[2],2)] ^ pkey.mk_tab[3][byte(blk[2],3)] ); blk[0] = rotr32(blk[0] ^ ((t0 + t1 + pkey.l_key[4 * (i) + 10]) % 0x100000000), 1); blk[1] = rotl32(blk[1], 1) ^ ((t0 + 2 * t1 + pkey.l_key[4 * (i) + 11]) % 0x100000000); in_blk[0] = blk[2] ^ pkey.l_key[4]; in_blk[1] = blk[3] ^ pkey.l_key[5]; in_blk[2] = blk[0] ^ pkey.l_key[6]; in_blk[3] = blk[1] ^ pkey.l_key[7]; return def decrypt(pkey, in_blk): blk = [0, 0, 0, 0] blk[0] = in_blk[0] ^ pkey.l_key[4]; blk[1] = in_blk[1] ^ pkey.l_key[5]; blk[2] = in_blk[2] ^ pkey.l_key[6]; blk[3] = in_blk[3] ^ pkey.l_key[7]; for i in range(7, -1, -1): t1 = ( pkey.mk_tab[0][byte(blk[1],3)] ^ pkey.mk_tab[1][byte(blk[1],0)] ^ pkey.mk_tab[2][byte(blk[1],1)] ^ pkey.mk_tab[3][byte(blk[1],2)] ) t0 = ( pkey.mk_tab[0][byte(blk[0],0)] ^ pkey.mk_tab[1][byte(blk[0],1)] ^ pkey.mk_tab[2][byte(blk[0],2)] ^ pkey.mk_tab[3][byte(blk[0],3)] ) blk[2] = rotl32(blk[2], 1) ^ ((t0 + t1 + pkey.l_key[4 * (i) + 10]) % 0x100000000) blk[3] = rotr32(blk[3] ^ ((t0 + 2 * t1 + pkey.l_key[4 * (i) + 11]) % 0x100000000), 1) t1 = ( pkey.mk_tab[0][byte(blk[3],3)] ^ pkey.mk_tab[1][byte(blk[3],0)] ^ pkey.mk_tab[2][byte(blk[3],1)] ^ pkey.mk_tab[3][byte(blk[3],2)] ) t0 = ( pkey.mk_tab[0][byte(blk[2],0)] ^ pkey.mk_tab[1][byte(blk[2],1)] ^ pkey.mk_tab[2][byte(blk[2],2)] ^ pkey.mk_tab[3][byte(blk[2],3)] ) blk[0] = rotl32(blk[0], 1) ^ ((t0 + t1 + pkey.l_key[4 * (i) + 8]) % 0x100000000) blk[1] = rotr32(blk[1] ^ ((t0 + 2 * t1 + pkey.l_key[4 * (i) + 9]) % 0x100000000), 1) in_blk[0] = blk[2] ^ pkey.l_key[0]; in_blk[1] = blk[3] ^ pkey.l_key[1]; in_blk[2] = blk[0] ^ pkey.l_key[2]; in_blk[3] = blk[1] ^ pkey.l_key[3]; return __testkey = b'\xD4\x3B\xB7\x55\x6E\xA3\x2E\x46\xF2\xA2\x82\xB7\xD4\x5B\x4E\x0D\x57\xFF\x73\x9D\x4D\xC9\x2C\x1B\xD7\xFC\x01\x70\x0C\xC8\x21\x6F' __testdat = b'\x90\xAF\xE9\x1B\xB2\x88\x54\x4F\x2C\x32\xDC\x23\x9B\x26\x35\xE6' assert b'l\xb4V\x1c@\xbf\n\x97\x05\x93\x1c\xb6\xd4\x08\xe7\xfa' == Twofish(__testkey).encrypt(__testdat) assert __testdat == Twofish(__testkey).decrypt(b'l\xb4V\x1c@\xbf\n\x97\x05\x93\x1c\xb6\xd4\x08\xe7\xfa') pykeepass-4.0.7/pykeepass/kdbx_parsing/twofish.py000066400000000000000000000317731457002773400222660ustar00rootroot00000000000000# ============================================================================= # Copyright (c) 2008 Christophe Oosterlynck # & NXP ( Philippe Teuwen ) # # 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. # ============================================================================= # -*- coding: utf-8 -*- __all__ = ['Twofish'] from . import pytwofish from Cryptodome.Util.strxor import strxor from Cryptodome.Util.Padding import pad MODE_ECB = 1 MODE_CBC = 2 MODE_CFB = 3 MODE_OFB = 5 MODE_CTR = 6 MODE_XTS = 7 MODE_CMAC = 8 class BlockCipher(): """ Base class for all blockciphers """ MODE_ECB = MODE_ECB MODE_CBC = MODE_CBC MODE_CFB = MODE_CFB MODE_OFB = MODE_OFB MODE_CTR = MODE_CTR MODE_XTS = MODE_XTS MODE_CMAC = MODE_CMAC key_error_message = "Wrong key size" #should be overwritten in child classes def __init__(self,key,mode,IV,counter,cipher_module,segment_size,args={}): # Cipher classes inheriting from this one take care of: # self.blocksize # self.cipher self.key = key self.mode = mode self.cache = b'' self.ed = None if 'keylen_valid' in dir(self): #wrappers for pycrypto functions don't have this function if not self.keylen_valid(key) and type(key) is not tuple: raise ValueError(self.key_error_message) if IV == None: self.IV = b'\x00'*self.blocksize else: self.IV = IV if mode != MODE_XTS: self.cipher = cipher_module(self.key,**args) if mode == MODE_ECB: self.chain = ECB(self.cipher, self.blocksize) elif mode == MODE_CBC: if len(self.IV) != self.blocksize: raise Exception("the IV length should be %i bytes"%self.blocksize) self.chain = CBC(self.cipher, self.blocksize,self.IV) elif mode == MODE_CFB: if len(self.IV) != self.blocksize: raise Exception("the IV length should be %i bytes"%self.blocksize) if segment_size == None: raise ValueError("segment size must be defined explicitely for CFB mode") if segment_size > self.blocksize*8 or segment_size%8 != 0: # current CFB implementation doesn't support bit level acces => segment_size should be multiple of bytes raise ValueError("segment size should be a multiple of 8 bits between 8 and %i"%(self.blocksize*8)) self.chain = CFB(self.cipher, self.blocksize,self.IV,segment_size) elif mode == MODE_OFB: if len(self.IV) != self.blocksize: raise ValueError("the IV length should be %i bytes"%self.blocksize) self.chain = OFB(self.cipher, self.blocksize,self.IV) elif mode == MODE_CTR: if (counter == None) or not callable(counter): raise Exception("Supply a valid counter object for the CTR mode") self.chain = CTR(self.cipher,self.blocksize,counter) elif mode == MODE_XTS: if self.blocksize != 16: raise Exception('XTS only works with blockcipher that have a 128-bit blocksize') if not(type(key) == tuple and len(key) == 2): raise Exception('Supply two keys as a tuple when using XTS') if 'keylen_valid' in dir(self): #wrappers for pycrypto functions don't have this function if not self.keylen_valid(key[0]) or not self.keylen_valid(key[1]): raise ValueError(self.key_error_message) self.cipher = cipher_module(self.key[0],**args) self.cipher2 = cipher_module(self.key[1],**args) self.chain = XTS(self.cipher, self.cipher2) elif mode == MODE_CMAC: if self.blocksize not in (8,16): raise Exception('CMAC only works with blockcipher that have a 64 or 128-bit blocksize') self.chain = CMAC(self.cipher,self.blocksize,self.IV) else: raise Exception("Unknown chaining mode!") def encrypt(self,plaintext,n=''): """Encrypt some plaintext plaintext = a string of binary data n = the 'tweak' value when the chaining mode is XTS The encrypt function will encrypt the supplied plaintext. The behavior varies slightly depending on the chaining mode. ECB, CBC: --------- When the supplied plaintext is not a multiple of the blocksize of the cipher, then the remaining plaintext will be cached. The next time the encrypt function is called with some plaintext, the new plaintext will be concatenated to the cache and then cache+plaintext will be encrypted. CFB, OFB, CTR: -------------- When the chaining mode allows the cipher to act as a stream cipher, the encrypt function will always encrypt all of the supplied plaintext immediately. No cache will be kept. XTS: ---- Because the handling of the last two blocks is linked, it needs the whole block of plaintext to be supplied at once. Every encrypt function called on a XTS cipher will output an encrypted block based on the current supplied plaintext block. CMAC: ----- Everytime the function is called, the hash from the input data is calculated. No finalizing needed. The hashlength is equal to block size of the used block cipher. """ #self.ed = 'e' if chain is encrypting, 'd' if decrypting, # None if nothing happened with the chain yet #assert self.ed in ('e',None) # makes sure you don't encrypt with a cipher that has started decrypting self.ed = 'e' if self.mode == MODE_XTS: # data sequence number (or 'tweak') has to be provided when in XTS mode return self.chain.update(plaintext,'e',n) else: return self.chain.update(plaintext,'e') def decrypt(self,ciphertext,n=''): """Decrypt some ciphertext ciphertext = a string of binary data n = the 'tweak' value when the chaining mode is XTS The decrypt function will decrypt the supplied ciphertext. The behavior varies slightly depending on the chaining mode. ECB, CBC: --------- When the supplied ciphertext is not a multiple of the blocksize of the cipher, then the remaining ciphertext will be cached. The next time the decrypt function is called with some ciphertext, the new ciphertext will be concatenated to the cache and then cache+ciphertext will be decrypted. CFB, OFB, CTR: -------------- When the chaining mode allows the cipher to act as a stream cipher, the decrypt function will always decrypt all of the supplied ciphertext immediately. No cache will be kept. XTS: ---- Because the handling of the last two blocks is linked, it needs the whole block of ciphertext to be supplied at once. Every decrypt function called on a XTS cipher will output a decrypted block based on the current supplied ciphertext block. CMAC: ----- Mode not supported for decryption as this does not make sense. """ #self.ed = 'e' if chain is encrypting, 'd' if decrypting, # None if nothing happened with the chain yet #assert self.ed in ('d',None) # makes sure you don't decrypt with a cipher that has started encrypting self.ed = 'd' if self.mode == MODE_XTS: # data sequence number (or 'tweak') has to be provided when in XTS mode return self.chain.update(ciphertext,'d',n) else: return self.chain.update(ciphertext,'d') def final(self,style='pkcs7'): # TODO: after calling final, reset the IV? so the cipher is as good as new? """Finalizes the encryption by padding the cache padfct = padding function import from CryptoPlus.Util.padding For ECB, CBC: the remaining bytes in the cache will be padded and encrypted. For OFB,CFB, CTR: an encrypted padding will be returned, making the total outputed bytes since construction of the cipher a multiple of the blocksize of that cipher. If the cipher has been used for decryption, the final function won't do anything. You have to manually unpad if necessary. After finalization, the chain can still be used but the IV, counter etc aren't reset but just continue as they were after the last step (finalization step). """ assert self.mode not in (MODE_XTS, MODE_CMAC) # finalizing (=padding) doesn't make sense when in XTS or CMAC mode if self.ed == b'e': # when the chain is in encryption mode, finalizing will pad the cache and encrypt this last block if self.mode in (MODE_OFB,MODE_CFB,MODE_CTR): dummy = b'0'*(self.chain.totalbytes%self.blocksize) # a dummy string that will be used to get a valid padding else: #ECB, CBC dummy = self.chain.cache pdata = pad(dummy,self.blocksize,style=style)[len(dummy):] #~ pad = padfct(dummy,padding.PAD,self.blocksize)[len(dummy):] # construct the padding necessary return self.chain.update(pdata,b'e') # supply the padding to the update function => chain cache will be "cache+padding" else: # final function doesn't make sense when decrypting => padding should be removed manually pass class CBC: """CBC chaining mode """ def __init__(self, codebook, blocksize, IV): self.IV = IV self.cache = b'' self.codebook = codebook self.blocksize = blocksize def update(self, data, ed): """Processes the given ciphertext/plaintext Inputs: data: raw string of any length ed: 'e' for encryption, 'd' for decryption Output: processed raw string block(s), if any When the supplied data is not a multiple of the blocksize of the cipher, then the remaining input data will be cached. The next time the update function is called with some data, the new data will be concatenated to the cache and then cache+data will be processed and full blocks will be outputted. """ if ed == 'e': encrypted_blocks = b'' self.cache += data if len(self.cache) < self.blocksize: return b'' for i in range(0, len(self.cache)-self.blocksize+1, self.blocksize): self.IV = self.codebook.encrypt(strxor(self.cache[i:i+self.blocksize],self.IV)) encrypted_blocks += self.IV self.cache = self.cache[i+self.blocksize:] return encrypted_blocks else: decrypted_blocks = b'' self.cache += data if len(self.cache) < self.blocksize: return b'' for i in range(0, len(self.cache)-self.blocksize+1, self.blocksize): plaintext = strxor(self.IV,self.codebook.decrypt(self.cache[i:i + self.blocksize])) self.IV = self.cache[i:i + self.blocksize] decrypted_blocks+=plaintext self.cache = self.cache[i+self.blocksize:] return decrypted_blocks class python_Twofish(BlockCipher): def __init__(self,key,mode,IV,counter,segment_size): if len(key) not in (16,24,32) and type(key) is not tuple: raise ValueError("Key should be 128, 192 or 256 bits") cipher_module = pytwofish.Twofish self.blocksize = 16 BlockCipher.__init__(self,key,mode,IV,counter,cipher_module,segment_size) @classmethod def new(cls, key,mode=MODE_ECB,IV=None,counter=None,segment_size=None): return cls(key,mode,IV,counter,segment_size) Twofish = python_Twofish pykeepass-4.0.7/pykeepass/pykeepass.py000066400000000000000000000717751457002773400201420ustar00rootroot00000000000000# coding: utf-8 import base64 import logging import os import re import shutil import struct import uuid import zlib from binascii import Error as BinasciiError from construct import Container, ChecksumError, CheckError from datetime import datetime, timedelta, timezone from lxml import etree from lxml.builder import E from pathlib import Path from .attachment import Attachment from .entry import Entry from .exceptions import * from .group import Group from .kdbx_parsing import KDBX, kdf_uuids from .xpath import attachment_xp, entry_xp, group_xp, path_xp logger = logging.getLogger(__name__) BLANK_DATABASE_FILENAME = "blank_database.kdbx" BLANK_DATABASE_LOCATION = os.path.join(os.path.dirname(os.path.realpath(__file__)), BLANK_DATABASE_FILENAME) BLANK_DATABASE_PASSWORD = "password" DT_ISOFORMAT = "%Y-%m-%dT%H:%M:%S%fZ" class PyKeePass(): """Open a KeePass database Args: filename (:obj:`str`, optional): path to database or stream object. If None, the path given when the database was opened is used. password (:obj:`str`, optional): database password. If None, database is assumed to have no password keyfile (:obj:`str`, optional): path to keyfile. If None, database is assumed to have no keyfile transformed_key (:obj:`bytes`, optional): precomputed transformed key. decrypt (:obj:`bool`, optional): whether to decrypt XML payload. Set `False` to access outer header information without decrypting database. Raises: CredentialsError: raised when password/keyfile or transformed key are wrong HeaderChecksumError: raised when checksum in database header is is wrong. e.g. database tampering or file corruption PayloadChecksumError: raised when payload blocks checksum is wrong, e.g. corruption during database saving Todo: - raise, no filename provided, database not open """ def __init__(self, filename, password=None, keyfile=None, transformed_key=None, decrypt=True): self.read( filename=filename, password=password, keyfile=keyfile, transformed_key=transformed_key, decrypt=decrypt ) def __enter__(self): return self def __exit__(self, typ, value, tb): # see issue 137 pass def read(self, filename=None, password=None, keyfile=None, transformed_key=None, decrypt=True): """ See class docstring. Todo: - raise, no filename provided, database not open """ self._password = password self._keyfile = keyfile if filename: self.filename = filename else: filename = self.filename try: if hasattr(filename, "read"): self.kdbx = KDBX.parse_stream( filename, password=password, keyfile=keyfile, transformed_key=transformed_key, decrypt=decrypt ) else: self.kdbx = KDBX.parse_file( filename, password=password, keyfile=keyfile, transformed_key=transformed_key, decrypt=decrypt ) except CheckError as e: if e.path == '(parsing) -> header -> sig_check': raise HeaderChecksumError("Not a KeePass database") else: raise # body integrity/verification except ChecksumError as e: if e.path in ( '(parsing) -> body -> cred_check', # KDBX4 '(parsing) -> cred_check' # KDBX3 ): raise CredentialsError("Invalid credentials") elif e.path == '(parsing) -> body -> sha256': raise HeaderChecksumError("Corrupted database") elif e.path in ( '(parsing) -> body -> payload -> hmac_hash', # KDBX4 '(parsing) -> xml -> block_hash' # KDBX3 ): raise PayloadChecksumError("Error reading database contents") else: raise def reload(self): """Reload current database using previous credentials """ self.read(self.filename, self.password, self.keyfile) def save(self, filename=None, transformed_key=None): """Save current database object to disk. Args: filename (:obj:`str`, optional): path to database or stream object. If None, the path given when the database was opened is used. PyKeePass.filename is unchanged. transformed_key (:obj:`bytes`, optional): precomputed transformed key. """ if not filename: filename = self.filename if hasattr(filename, "write"): KDBX.build_stream( self.kdbx, filename, password=self.password, keyfile=self.keyfile, transformed_key=transformed_key, decrypt=True ) else: # save to temporary file to prevent database clobbering # see issues 223, 101 filename_tmp = Path(filename).with_suffix('.tmp') try: KDBX.build_file( self.kdbx, filename_tmp, password=self.password, keyfile=self.keyfile, transformed_key=transformed_key, decrypt=True ) except Exception as e: os.remove(filename_tmp) raise e shutil.move(filename_tmp, filename) @property def version(self): """tuple: Length 2 tuple of ints containing major and minor versions. Generally (3, 1) or (4, 0).""" return ( self.kdbx.header.value.major_version, self.kdbx.header.value.minor_version ) @property def encryption_algorithm(self): """str: encryption algorithm used by database during decryption. Can be one of 'aes256', 'chacha20', or 'twofish'.""" return self.kdbx.header.value.dynamic_header.cipher_id.data @property def kdf_algorithm(self): """str: key derivation algorithm used by database during decryption. Can be one of 'aeskdf', 'argon2', or 'aeskdf'""" if self.version == (3, 1): return 'aeskdf' elif self.version == (4, 0): kdf_parameters = self.kdbx.header.value.dynamic_header.kdf_parameters.data.dict if kdf_parameters['$UUID'].value == kdf_uuids['argon2']: return 'argon2' elif kdf_parameters['$UUID'].value == kdf_uuids['argon2id']: return 'argon2id' elif kdf_parameters['$UUID'].value == kdf_uuids['aeskdf']: return 'aeskdf' @property def transformed_key(self): """bytes: transformed key used in database decryption. May be cached and passed to `open` for faster database opening""" return self.kdbx.body.transformed_key @property def database_salt(self): """bytes: salt of database kdf. This can be used for adding additional credentials which are used in extension to current keyfile.""" if self.version == (3, 1): return self.kdbx.header.value.dynamic_header.transform_seed.data kdf_parameters = self.kdbx.header.value.dynamic_header.kdf_parameters.data.dict return kdf_parameters['S'].value @property def payload(self): """Encrypted payload of keepass database""" # check if payload is decrypted if self.kdbx.body.payload is None: raise ValueError("Database is not decrypted") else: return self.kdbx.body.payload @property def tree(self): """lxml.etree._ElementTree: database XML payload""" return self.payload.xml @property def root_group(self): """Group: root Group of database""" return self.find_groups(path='', first=True) @property def recyclebin_group(self): """Group: RecycleBin Group of database""" elem = self._xpath('/KeePassFile/Meta/RecycleBinUUID', first=True) recyclebin_uuid = uuid.UUID( bytes = base64.b64decode(elem.text) ) return self.find_groups(uuid=recyclebin_uuid, first=True) @property def groups(self): """:obj:`list` of :obj:`Group`: list of all Group objects in database """ return self.find_groups() @property def entries(self): """:obj:`list` of :obj:`Entry`: list of all Entry objects in database, excluding history""" return self.find_entries() def xml(self): """Get XML part of database as string Returns: str: XML payload section of database. """ return etree.tostring( self.tree, pretty_print=True, standalone=True, encoding='unicode' ) def dump_xml(self, filename): """ Dump the contents of the database to file as XML Args: filename (str): path to output file """ with open(filename, 'wb') as f: f.write( etree.tostring( self.tree, pretty_print=True, standalone=True, encoding='utf-8' ) ) def _xpath(self, xpath_str, tree=None, first=False, cast=False, **kwargs): """Look up elements in the XML payload and return corresponding object. Internal function which searches the payload lxml ElementTree for elements via XPath. Matched entry, group, and attachment elements are automatically cast to their corresponding objects, otherwise an error is raised. Args: xpath_str (str): XPath query for finding element(s) tree (:obj:`_ElementTree`, :obj:`Element`, optional): use this element as root node when searching first (bool): If True, function returns first result or None. If False, function returns list of matches or empty list. Default is False. cast (bool): If True, matches are instead instantiated as pykeepass Group, Entry, or Attachment objects. An exception is raised if a match cannot be cast. Default is False. Returns: `Group`, `Entry`, `Attachment`, or `lxml.etree.Element` """ if tree is None: tree = self.tree logger.debug('xpath query: ' + xpath_str) elements = tree.xpath( xpath_str, namespaces={'re': 'http://exslt.org/regular-expressions'} ) res = [] for e in elements: if cast: if e.tag == 'Entry': res.append(Entry(element=e, kp=self)) elif e.tag == 'Group': res.append(Group(element=e, kp=self)) elif e.tag == 'Binary' and e.getparent().tag == 'Entry': res.append(Attachment(element=e, kp=self)) else: raise Exception('Could not cast element {}'.format(e)) else: res.append(e) # return first object in list or None if first: res = res[0] if res else None return res def _find(self, prefix, keys_xp, path=None, tree=None, first=False, history=False, regex=False, flags=None, **kwargs): """Internal function for converting a search into an XPath string""" xp = '' if not history: prefix += '[not(ancestor::History)]' if path is not None: first = True xp += '/KeePassFile/Root/Group' # split provided path into group and element group_path = path[:-1] element = path[-1] if len(path) > 0 else '' # build xpath from group_path and element for group in group_path: xp += path_xp[regex]['group'].format(group, flags=flags) if 'Entry' in prefix: xp += path_xp[regex]['entry'].format(element, flags=flags) elif element and 'Group' in prefix: xp += path_xp[regex]['group'].format(element, flags=flags) else: if tree is not None: xp += '.' xp += prefix # handle searching custom string fields if 'string' in kwargs.keys(): for key, value in kwargs['string'].items(): xp += keys_xp[regex]['string'].format(key, value, flags=flags) kwargs.pop('string') # convert uuid to base64 form before building xpath if 'uuid' in kwargs.keys(): kwargs['uuid'] = base64.b64encode(kwargs['uuid'].bytes).decode('utf-8') # convert tags to semicolon separated string before building xpath # FIXME: this isn't a reliable way to search tags. e.g. searching ['tag1', 'tag2'] will match 'tag1tag2 if 'tags' in kwargs.keys(): kwargs['tags'] = ' and '.join(f'contains(text(),"{t}")' for t in kwargs['tags']) # build xpath to filter results with specified attributes for key, value in kwargs.items(): if key not in keys_xp[regex].keys(): raise TypeError('Invalid keyword argument "{}"'.format(key)) if value is not None: xp += keys_xp[regex][key].format(value, flags=flags) res = self._xpath( xp, tree=tree._element if tree else None, first=first, cast=True, **kwargs ) return res def _can_be_moved_to_recyclebin(self, entry_or_group): if entry_or_group == self.root_group: return False recyclebin_group = self.recyclebin_group if recyclebin_group is None: return True uuid_str = base64.b64encode( entry_or_group.uuid.bytes).decode('utf-8') elem = self._xpath('./UUID[text()="{}"]/..'.format(uuid_str), tree=recyclebin_group._element, first=True, cast=False) return elem is None # ---------- Groups ---------- from .deprecated import ( find_groups_by_name, find_groups_by_path, find_groups_by_uuid, find_groups_by_notes ) def find_groups(self, recursive=True, path=None, group=None, **kwargs): """ Find groups in a database Args: name (str): name of group first (bool): return first result instead of list (default False) recursive (bool): do a recursive search of all groups/subgroups path (str): do group search starting from path group (Group): search underneath group uuid (uuid.UUID): group UUID regex (bool): whether `str` search arguments contain [XSLT style][XSLT style] regular expression flags (str): XPath [flags][flags] Returns: :obj:`list` of :obj:`Group` or :obj:`Group` [XSLT style]: https://www.xml.com/pub/a/2003/06/04/tr.html [flags]: https://www.w3.org/TR/xpath-functions/#flags """ prefix = '//Group' if recursive else '/Group' res = self._find(prefix, group_xp, path=path, tree=group, **kwargs) return res # creates a new group and all parent groups, if necessary def add_group(self, destination_group, group_name, icon=None, notes=None): logger.debug('Creating group {}'.format(group_name)) if icon: group = Group(name=group_name, icon=icon, notes=notes, kp=self) else: group = Group(name=group_name, notes=notes, kp=self) destination_group.append(group) return group def delete_group(self, group): group.delete() def move_group(self, group, destination_group): destination_group.append(group) def _create_or_get_recyclebin_group(self, **kwargs): existing_group = self.recyclebin_group if existing_group is not None: return existing_group kwargs.setdefault('group_name', 'Recycle Bin') group = self.add_group( self.root_group, **kwargs) elem = self._xpath('/KeePassFile/Meta/RecycleBinUUID', first=True) elem.text = base64.b64encode(group.uuid.bytes).decode('utf-8') return group def trash_group(self, group): """Move a group to the RecycleBin Args: group (:obj:`Group`): Group to send to the RecycleBin """ if not self._can_be_moved_to_recyclebin(group): raise UnableToSendToRecycleBin recyclebin_group = self._create_or_get_recyclebin_group() self.move_group( group, recyclebin_group) def empty_group(self, group): """Delete the content of a group. This does not delete the group itself Args: group (:obj:`Group`): Group to empty """ while len(group.subgroups): self.delete_group(group.subgroups[0]) while len(group.entries): self.delete_entry(group.entries[0]) # ---------- Entries ---------- from .deprecated import ( find_entries_by_title, find_entries_by_username, find_entries_by_password, find_entries_by_url, find_entries_by_path, find_entries_by_notes, find_entries_by_string, find_entries_by_uuid ) def find_entries(self, recursive=True, path=None, group=None, **kwargs): prefix = '//Entry' if recursive else '/Entry' res = self._find(prefix, entry_xp, path=path, tree=group, **kwargs) return res def add_entry(self, destination_group, title, username, password, url=None, notes=None, expiry_time=None, tags=None, otp=None, icon=None, force_creation=False): entries = self.find_entries( title=title, username=username, first=True, group=destination_group, recursive=False ) if entries and not force_creation: raise Exception( 'An entry "{}" already exists in "{}"'.format( title, destination_group ) ) else: logger.debug('Creating a new entry') entry = Entry( title=title, username=username, password=password, notes=notes, otp=otp, url=url, tags=tags, expires=True if expiry_time else False, expiry_time=expiry_time, icon=icon, kp=self ) destination_group.append(entry) return entry def delete_entry(self, entry): entry.delete() def move_entry(self, entry, destination_group): destination_group.append(entry) def trash_entry(self, entry): """Move an entry to the RecycleBin Args: entry (:obj:`Entry`): Entry to send to the RecycleBin """ if not self._can_be_moved_to_recyclebin(entry): raise UnableToSendToRecycleBin recyclebin_group = self._create_or_get_recyclebin_group() self.move_entry( entry, recyclebin_group) # ---------- Attachments ---------- def find_attachments(self, recursive=True, path=None, element=None, **kwargs): prefix = '//Binary' if recursive else '/Binary' res = self._find(prefix, attachment_xp, path=path, tree=element, **kwargs) return res @property def attachments(self): return self.find_attachments(filename='.*', regex=True) @property def binaries(self): if self.version >= (4, 0): # first byte is a prepended flag binaries = [a.data[1:] for a in self.payload.inner_header.binary] else: binaries = [] for elem in self._xpath('/KeePassFile/Meta/Binaries/Binary'): if elem.text is not None: if elem.get('Compressed') == 'True': data = zlib.decompress( base64.b64decode(elem.text), zlib.MAX_WBITS | 32 ) else: data = base64.b64decode(elem.text) else: data = b'' binaries.insert(int(elem.attrib['ID']), data) return binaries def add_binary(self, data, compressed=True, protected=True): if self.version >= (4, 0): # add protected flag byte if protected: data = b'\x01' + data else: data = b'\x00' + data # add binary element to inner header c = Container(type='binary', data=data) self.payload.inner_header.binary.append(c) else: binaries = self._xpath( '/KeePassFile/Meta/Binaries', first=True ) if compressed: # gzip compression compressor = zlib.compressobj( zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, zlib.MAX_WBITS | 16 ) data = compressor.compress(data) data += compressor.flush() data = base64.b64encode(data).decode() # set ID for Binary Element binary_id = len(self.binaries) # add binary element to XML binaries.append( E.Binary(data, ID=str(binary_id), Compressed=str(compressed)) ) # return binary id return len(self.binaries) - 1 def delete_binary(self, id): try: if self.version >= (4, 0): # remove binary element from inner header self.payload.inner_header.binary.pop(id) else: # remove binary element from XML binaries = self._xpath('/KeePassFile/Meta/Binaries', first=True) binaries.remove(binaries.getchildren()[id]) except IndexError: raise BinaryError('No such binary with id {}'.format(id)) # remove all entry references to this attachment for reference in self.find_attachments(id=id): reference.delete() # decrement references greater than this id binaries_gt = self._xpath( '//Binary/Value[@Ref > "{}"]/..'.format(id), cast=True ) for reference in binaries_gt: reference.id = reference.id - 1 # ---------- Misc ---------- def deref(self, value): """Dereference [field reference][fieldref] of Entry Args: ref (str): KeePass reference string to another field Returns: str or uuid.UUID [fieldref]: https://keepass.info/help/base/fieldrefs.html """ if not value: return value references = set(re.findall(r'({REF:([TUPANI])@([TUPANI]):([^}]+)})', value)) if not references: return value field_to_attribute = { 'T': 'title', 'U': 'username', 'P': 'password', 'A': 'url', 'N': 'notes', 'I': 'uuid', } for ref, wanted_field, search_in, search_value in references: wanted_field = field_to_attribute[wanted_field] search_in = field_to_attribute[search_in] if search_in == 'uuid': search_value = uuid.UUID(search_value) ref_entry = self.find_entries(first=True, **{search_in: search_value}) value = value.replace(ref, getattr(ref_entry, wanted_field)) return self.deref(value) # ---------- Credential Changing and Expiry ---------- @property def password(self): """str: Get or set database password""" return self._password @password.setter def password(self, password): self._password = password self.credchange_date = datetime.now(timezone.utc) @property def keyfile(self): """str or pathlib.Path: get or set database keyfile""" return self._keyfile @keyfile.setter def keyfile(self, keyfile): self._keyfile = keyfile self.credchange_date = datetime.now(timezone.utc) @property def credchange_required_days(self): """int: Days until password update should be required""" e = self._xpath('/KeePassFile/Meta/MasterKeyChangeForce', first=True) if e is not None: return int(e.text) @property def credchange_recommended_days(self): """int: Days until password update should be recommended""" e = self._xpath('/KeePassFile/Meta/MasterKeyChangeRec', first=True) if e is not None: return int(e.text) @credchange_required_days.setter def credchange_required_days(self, days): path = '/KeePassFile/Meta/MasterKeyChangeForce' item = self._xpath(path, first=True) item.text = str(days) @credchange_recommended_days.setter def credchange_recommended_days(self, days): path = '/KeePassFile/Meta/MasterKeyChangeRec' item = self._xpath(path, first=True) item.text = str(days) @property def credchange_date(self): """datetime.datetime: get or set UTC time of last credential change""" e = self._xpath('/KeePassFile/Meta/MasterKeyChanged', first=True) if e is not None: return self._decode_time(e.text) @credchange_date.setter def credchange_date(self, date): mk_time = self._xpath('/KeePassFile/Meta/MasterKeyChanged', first=True) mk_time.text = self._encode_time(date) @property def credchange_required(self): """bool: Check if credential change is required""" change_date = self.credchange_date if change_date is None or self.credchange_required_days == -1: return False now_date = datetime.now(timezone.utc) return (now_date - change_date).days > self.credchange_required_days @property def credchange_recommended(self): """bool: Check if credential change is recommended""" change_date = self.credchange_date if change_date is None or self.credchange_recommended_days == -1: return False now_date = datetime.now(timezone.utc) return (now_date - change_date).days > self.credchange_recommended_days # ---------- Datetime Functions ---------- def _encode_time(self, value): """bytestring or plaintext string: Convert datetime to base64 or plaintext string""" if self.version >= (4, 0): diff_seconds = int( ( value - datetime( year=1, month=1, day=1, tzinfo=timezone.utc ) ).total_seconds() ) return base64.b64encode( struct.pack('= (4, 0): # decode KDBX4 date from b64 format try: return ( datetime(year=1, month=1, day=1, tzinfo=timezone.utc) + timedelta( seconds=struct.unpack('=2.10.53", "argon2_cffi>=18.1.0", "pycryptodomex>=3.6.2", "lxml", ] classifiers = [ "Topic :: Security", "Topic :: Software Development :: Libraries", "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", ] [project.optional-dependencies] test = ["pyotp"] [project.urls] Homepage = "https://github.com/libkeepass/pykeepass" Repository = "https://github.com/libkeepass/pykeepass" Issues = "https://github.com/libkeepass/pykeepass/issues" Changelog = "https://github.com/libkeepass/pykeepass/blob/master/CHANGELOG.rst" [tool.setuptools] packages = ["pykeepass"] include-package-data = true [build-system] requires = ["setuptools>=59.0.0"] build-backend = 'setuptools.build_meta' pykeepass-4.0.7/tests/000077500000000000000000000000001457002773400147015ustar00rootroot00000000000000pykeepass-4.0.7/tests/__init__.py000066400000000000000000000000001457002773400170000ustar00rootroot00000000000000pykeepass-4.0.7/tests/change.key000066400000000000000000000002731457002773400166420ustar00rootroot00000000000000 1.00 1zbxTmH0xdaJjXjkuDi3XFNkUCXWidPeNP2fPh4HJWk= pykeepass-4.0.7/tests/extra_content.kdbx000066400000000000000000000054451457002773400204400ustar00rootroot00000000000000٢gK1qCPX!jZ &u,cBՂ.1!`1R\o yg7 B$UUIDcmߌ)DK IMPBS 4? 7c*)֠tV yX$P+t .YiEX3ZzqRo0#\Ddag>SjݴUbv_ӸgHar+qN1V aBM&YMc7nH ?ӧ2F8r%ރ,nv/mxQ:*NHyYqvlAvs<,ubK Z%d)ѝGN>Ue# ,c˃:xiOTD47dPj W~[@#$>r<1*]_)bت:2SPh F[قđ6/AtDxy4$r<*d*KA (VL`\tܓv5tyb3ݚ };a=C2oEPczyvHFZ`/CrY}ʁ#J l;e !fDz~ y1XY@ԝ9 $2d|2ݐ $`$@-Py c$[0an{i HpU[ u6o_еN_ShA3kȟc HO,^0cOy%ۋ.˪!ՊTlah: eq>%&1y7㦶kyM>7g08nHD un16y}-Unt/^y6MjoP u;y2x=UwBwD$>CYduNzGFE*!o$]h*9wE3Ep {1%%܌mq:"WU/Rh\ܐX6-y.uS/ w[bZ#د2(EB*j)-U)Tv15+}'# !zk4 ڏ(SUWR^!德EYq`cMQ٠0-;<zZjSâ4dNFiZXq*k3DeE| D= El M&8 [QqxDwox6)p?Sh 7G -#Nx qDdM 㮃2eq =k7pAȒQE,-1CAr(DsnpN8pood6.6דU2ێspkl!IyJWq_,1w9U'#8'elE9~!e /|oHq_IcZǩ'%.5ʪ=>.eO }R&o00oRe[ Wa$fJtr*TZQAmCDӑM2ݟ̤R&~~ T05Mpykeepass-4.0.7/tests/test.svg000066400000000000000000000124321457002773400164030ustar00rootroot00000000000000 image/svg+xml pykeepass-4.0.7/tests/test3.kdbx000066400000000000000000000133161457002773400166210ustar00rootroot00000000000000٢gK1qCP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דi=iaa%;m"h ݠ,~4AyO5-'CQ,_;X%JUlv0Dm6ds"zc8|?w,H|;SVB:8 CqV&dL^oO4h $Æ9#!u(mdur~ B`hBT܇#hl ޭ'Xʫ<1'hDmuå9i]r]8PS mS<⟊a7 #+z])8KNύS# Ji 'לPʊxmH۶b ”y i.D4j9 Y*QHsS1d O ELJx]xGd[_#(6CJԙwH_gGm,BGSuxɠb7ϸBz 4rYk cBrzcЦFfw|nZIwTzgQ,i'}_pykeepass-4.0.7/tests/test3.key000066400000000000000000000002731457002773400164570ustar00rootroot00000000000000 1.00 Qp9MrFM1RpSLO8iHZHGAiPbr8Z+hDFpp0cgtH+RM0hw= pykeepass-4.0.7/tests/test3_transformed.kdbx000066400000000000000000000103361457002773400212240ustar00rootroot00000000000000٢gK1qCPX!jZ TZ @ yp~rMɼʚi`A_ 3vL}̹(ɋl̗p\[pdFa&$02QB osҖƊ:DqF(rxG6nW DT'4uog|^].sqz  yhaՄNUt?>jr56c6-? d!&> ĆlRݖ##(M?(Ib3Pm-_Z|בD@Yu %fzǸnm6VddsPš0b~=G 5PP&2"IG}+b`r{ر;蝆adؽ_?mJ^![y)qbƍ2>^ά6]NΫ֫43QCjp|\i_WNߪ;M Wt_/x2S;̕\+'Ұ𣦦E7v1;as,;6=t>ԍn&6 \l1m#|{WyX+'_ a[8!7}_:']WE'˷9gם* =,eSP0U8/ f)%!4\ c\I-$!뿿D~N0l٧8F"ͷf}wm{hXrL5?N=iVRfcrRR[tQS+i6#?OȧƇLk$OS.٬pv(w) + jZ[C4Ke5U;xh~~(-$ :;#aKuYC>.zF_I6' io8VXo  !K}N=?*6[l2n`P'780sJseA4 Fbmc}TFJ2L6? 2\0Pc\J봁Liwn7#C(\D_u /&beh o*Nmd2%xxjY>s>;0wI-Z1`P-ܥN!'?x/[.,XKY%<>2w*۸Tf }y)>7װ614<1F﮲,% UMFnj+_ⳣg[˞n]uKW=rM#v.hkrY~_ y"@aXε6!^vpv5|>(CH(ɰwn .7fosܝq<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(CDw, VaIhP>,Ŝ"A.)AY?wRIaO aހpykeepass-4.0.7/tests/test4.key000066400000000000000000000002001457002773400164460ustar00rootroot00000000000000lr:Thz>xw-P9ֵLK:Q*z߭3aRa+&kjt\?Ն<sd7Oq %XS e$+DʡZ9pykeepass-4.0.7/tests/test4_aes.kdbx000066400000000000000000000037051457002773400174530ustar00rootroot00000000000000٢gK1qCPX!jZ U>@3o)7?e_z[SF7RK.2J B$UUIDcmߌ)DK IMPBS 'P6XL=\jaw|rV EZ:}[QiD{A)r$!0uZ首17Q{NiWःlh{ox6yu VA{`cMD@X$W~XYNV]B6֩[v9V*@c^d5;RC)+˲ȏ(ZbeIt(,P[A_~Y2k-#<(̼WLŒ=xrЋx#0:Vv0[lbɾOM]QHYk9kItHשи k.]g[,dtYi9VzPJ5Ņ "ps6!R4I1P$-)ce+F0\:vkZ֞ ~tI뗹&DkREUrD~NmGϣ*}OlAaa #FW§7SGɐQBa>Tf:IHX|9YoIی!'BގYt=gJlpK/I'W'>Q^ _ aC[4l0=IS;R9>E'qTA4rv~qF?8X5U5BCy;C( 14a>}f ZFeNV|1䲫 ϑsS"ŚP#%1Ot/G"f֘Q TZjՍy9cfR<ԇL6]S!Pۻ? D}~zpVWFXj|jB΄,9:Q\f}8h0J\|MI Kkɒ޸$) ɦCSu@D `)"Ԡ8BOk7Fg>0~+y|TTuCa魦"9IMmfZ/p!>PIGCB8oT̢ ,b? J4Gxlj;Sqk|P}@ġgQ 氪18+Zl W>C,^[Kփݍ$] B$UUIDcmߌ)DK IMPBS S@qo^U4 eUR픊{V >("Q?d/:y@d׼KkZ; ׊}{U\~s-XrW -xyZs8,HI.( møOj!!^ٚG!5haߥ]2{O`7;aOxDR0 ' G:~oEgs02( B Yglbk7Gۃ'd[ϣGmmmf6f1HsSfY`%2.fU7ǖ-BN0ޥYwL#('"E;*?Secyz$T'# qk'ihz{C ᤹NGy -R@2r_P]0)$VYsOyY)=ڴdF^8Jf8տ3v}}/ی |'ďN %^ۢ`m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T-|>C(NۇDL$gιDXh[d,QȔ*ٯboصt]k%ߺhwRH%-lL =Wn0<.Ux*k;IѼt3pB!e o_87?/tqw:7 -DہA9Xw/}k.ܩhR[]z;a(&oێ*ETͺ!M&$N#)'XR$"7Gpykeepass-4.0.7/tests/test4_aeskdf.kdbx000066400000000000000000000036471457002773400201450ustar00rootroot00000000000000٢gK1qCPX!jZ Xd/PSY-PQ=찞ڴ_&{ąW". ]B$UUIDbD`t ORdBS $V}']m:,{`Yh rע#{;i}^Hӷ>Pm8TUwy=SV$Dvݢ}+}:PRhZP]?d>2p x.5nu'X~8U W/3_2h**lrB.V4RɭFq%b8謕Qp‘["*"@J}krTEU=)'Pv yP_ Ѥ+Li:}w^R~2 =h3ז45P-k/ _ E^/1XTc(R/8RO/Ͱrͪ4W^ZyMAnB$u9j4( ZM@m>qMɄQLY4wTeb_Fn `q,AHʵdVd,_ʽSC>1FG!j+/MPtuI7ף椡IbQT3nU8$ۉ$RRF4HEJ+Y$W)e_#_ WFA8~a'aLWI?QOnsi#kvx4t(iKO0j96SƌV?Ih>kn>P"'yX f'::ݽ~6r{!*vUZa7yTN I<CBݒ ^+NrSJ\berh V@c/3 \$K IH:Ru 0uVeiTU$|t$wHQ#&T*-RS:B1`XWpykeepass-4.0.7/tests/test4_argon2id.kdbx000066400000000000000000000025251457002773400204070ustar00rootroot00000000000000٢gK1qCPX!jZ Xc^ߵ9}i g!I>"J5 B$UUID)VGs=>IMPBS M^.MXɜNui?IaV U$ 58JնV\epAhkȊD[N) { FmLiN[4;iUsDaߟp LjN_%o")jnv~9.Ô}=ݟ8N~9 ސ/3H]6ou KtbLNwoqsi*i궶lCu)5q"N!d"F݌f =H] 0 8H7r\T M >:W%JE9=8w:=xwan;rKK 7G9",ll'fpʹ\GrV?E@Upkt X9\s@%bNz[__m,Ɏ9o?+)4DMqAxSxxl.颙!Lx I,NWv@Y25Ԃ&|cx!j6NXJ;;g]p,ܣ!t%Vf*wQѶ~<4㲒(7䅉X1=V N(+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ʒgh _A H |ȅa^#,;&i>/Yb+OL#$H EB2֫+zd{S7Z+BB56j/?9)>P&odOg9#6oE<=܆ x;y{d5{NV6V7~'v!HG73V߱}~awq,K%_b ,gM?;yU:3;vV\dK-qKQ_܀;}"[w 1U"Z>0βVY6K:N- ̺%Z|?X7 D|5A pe^T-v?, YXXPG= oIP_D0 '6,N640x0 \[:eO\I_Ybkǧlzes]8(?n|>8&tK+g/w}PT|V1(ٛOVE[ xZ@&SЍA4z:]hupֿ]蒋  uc.ף8{PU#ݍ̍1K,%ჟ_@}WeDA8dr^<CC- ťxu@ PW׻%VpAcayJ * ʝ[LŚQޫh%1V_0,%Bɏ\'$O^:};jg@+J8DfH:p;OGҳc@M#DbPH BV'NgVᭅ]_ 53hGzD^"t7am.ݻ:|HͦR̒Jeo+0KC jX a-*F|CnRr֖ zY_iTDn68)0mZm,4$Ó΍1<{W:GB-fV [UPXo$@ A[hO(jQw_9kUjt Sd{?)l +͎&eF8\c1fu)pykeepass-4.0.7/tests/test4_keyx.keyx000066400000000000000000000003451457002773400177100ustar00rootroot00000000000000 2.0 30D73184 FBE1C7C4 B07EE4D6 BC4F118B 87577CAB 5CB8846F 5FD286FF F98BF9A9 pykeepass-4.0.7/tests/test4_transformed.kdbx000066400000000000000000000105271457002773400212270ustar00rootroot00000000000000٢gK+oL$31۵ ^c._X]'UnG0.7Q B$UUIDcmߌ)DK IMPBS 8ŏ4R$a\WCELCϢ~X6V e'׺G 'u옕/u&?s>^E<'WE1w޵SI9yyͬ` WУqAi@?@[E#N^oAV^SO9&ڕRft[ZP,ꚵW5 /=$\ALd5eACj>d36.,JL*]Gd ?ocÁB6%"!H]DIɑ:=>Vr}3Tw|mWAo%aPUj$_~"[*Rd< űBq)$Wc;spg7;{ÂKNn_^"C+-4 $y :@zRIAnN8#'tPn>sCUI 9Zg>d.ei+eK{a2HxO>憅eR x`hYf5;Ѽd0gB\OMV3.|83AL2ẘ´w`6llda2sU> *F(qiŰ͖2 /0sy pH GbM=K/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_invalidversion.key000066400000000000000000000002731457002773400215100ustar00rootroot00000000000000 3.00 Qp9MrFM1RpSLO8iHZHGAiPbr8Z+hDFpp0cgtH+RM0hw= pykeepass-4.0.7/tests/tests.py000066400000000000000000001405161457002773400164240ustar00rootroot00000000000000# -*- coding: utf-8 -*- import logging import os import shutil import unittest import uuid from datetime import datetime, timedelta, timezone from pathlib import Path from io import BytesIO from pykeepass import PyKeePass, icons from pykeepass.entry import Entry from pykeepass.group import Group from pykeepass.exceptions import BinaryError, CredentialsError, HeaderChecksumError """ Missing Tests: - add entry - force_creation - root_group - Group attribute tests - Entry attribute tests - ctime - get/set - atime - get/set - mtime - get/set - expiry_time - get/set """ base_dir = Path(os.path.dirname(os.path.realpath(__file__))) logger = logging.getLogger("pykeepass") class KDBX3Tests(unittest.TestCase): database = base_dir / 'test3.kdbx' password = 'password' keyfile = base_dir / 'test3.key' database_tmp = base_dir / 'test3_tmp.kdbx' keyfile_tmp = base_dir / 'test3_tmp.key' # get some things ready before testing def setUp(self): shutil.copy(self.database, self.database_tmp) shutil.copy(self.keyfile, self.keyfile_tmp) self.kp = PyKeePass( base_dir / self.database, password=self.password, keyfile=base_dir / self.keyfile ) # for tests which modify the database, use this self.kp_tmp = PyKeePass( base_dir / self.database_tmp, password=self.password, keyfile=base_dir / self.keyfile_tmp ) def tearDown(self): os.remove(self.keyfile_tmp) os.remove(self.database_tmp) class KDBX4Tests(KDBX3Tests): database = base_dir / 'test4.kdbx' password = 'password' keyfile = base_dir / 'test4.key' database_tmp = base_dir / 'test4_tmp.kdbx' keyfile_tmp = base_dir / 'test4_tmp.key' class EntryFindTests3(KDBX3Tests): # ---------- Finding entries ----------- def test_find_entries_by_title(self): results = self.kp.find_entries_by_title('root_entry') self.assertEqual(len(results), 1) results = self.kp.find_entries_by_title('Root_entry', regex=True, flags='i', first=True) self.assertEqual('root_entry', results.title) def test_find_entries_by_username(self): results = self.kp.find_entries_by_username('foobar_user') self.assertEqual(len(results), 2) results = self.kp.find_entries_by_username('Foobar_user', regex=True, flags='i', first=True) self.assertEqual('foobar_user', results.username) def test_find_entries_by_password(self): results = self.kp.find_entries_by_password('passw0rd') self.assertEqual(len(results), 2) results = self.kp.find_entries_by_password('Passw0rd', regex=True, flags='i', first=True) self.assertEqual('passw0rd', results.password) def test_find_entries_by_url(self): results = self.kp.find_entries_by_url('http://example.com') self.assertEqual(len(results), 2) results = self.kp.find_entries_by_url('http://example.com', first=True) self.assertEqual('http://example.com', results.url) def test_find_entries_by_notes(self): results = self.kp.find_entries_by_notes('entry notes') self.assertEqual(len(results), 1) results = self.kp.find_entries_by_notes('entry notes', regex=True) self.assertEqual(len(results), 2) results = self.kp.find_entries_by_notes('Entry notes', regex=True, flags='i', first=True) self.assertEqual('root entry notes', results.notes) def test_find_entries_by_path(self): results = self.kp.find_entries(path=['foobar_group', 'group_entry']) self.assertIsInstance(results, Entry) results = self.kp.find_entries(path=['foobar_group']) self.assertEqual(results, None) results = self.kp.find_entries(path=['foobar_group', 'Group_entry'], regex=True, flags='i', first=True) self.assertIsInstance(results, Entry) self.assertEqual('group_entry', results.title) def test_find_entries_by_uuid(self): uu = uuid.UUID('cc5f7ecd-2a00-48ca-9621-c222a347b0bb') results = self.kp.find_entries_by_uuid(uu)[0] self.assertIsInstance(results, Entry) self.assertEqual(uu, results.uuid) self.assertEqual('foobar_user', results.username) def test_find_entries_by_tags(self): results = self.kp.find_entries(tags=['tag1', 'tag2'], first=True) self.assertIsInstance(results, Entry) self.assertEqual('foobar_entry', results.title) def test_find_entries_by_string(self): results = self.kp.find_entries_by_string({'custom_field': 'custom field value'})[0] self.assertIsInstance(results, Entry) self.assertEqual('custom field value', results.get_custom_property('custom_field')) uu = uuid.UUID('1e73786c-7495-8c4c-9b3d-ff273aad5b54') self.assertEqual(uu, results.uuid) def test_find_entries_by_autotype_sequence(self): results = self.kp.find_entries(autotype_sequence='{TAB}', regex=True) self.assertEqual(len(results), 1) self.assertEqual(results[0].autotype_sequence, '{USERNAME}{TAB}{PASSWORD}{ENTER}') def test_find_entries_by_autotype_window(self): results = self.kp.find_entries(autotype_window='test', regex=True, flags="i") self.assertEqual(len(results), 1) self.assertEqual(results[0].autotype_window, 'TEST') def test_find_entries_by_autotype_enabled(self): results = self.kp.find_entries(autotype_enabled=True) self.assertEqual(len(results), len(self.kp.entries) - 1) def test_find_entries_by_otp(self): results = self.kp.find_entries(otp='nonmatch', regex=True, flags='i') self.assertEqual(len(results), 0) results = self.kp.find_entries(otp='OTPSECRETT', regex=True) self.assertEqual(len(results), 1) self.assertEqual('foobar_entry', results[0].title) import pyotp self.assertEqual(len(pyotp.parse_uri(results[0].otp).now()), 6) def test_find_entries(self): results = self.kp.find_entries(title='Root_entry', regex=True) self.assertEqual(len(results), 0) results = self.kp.find_entries(title='Root_entry', regex=True, flags='i', first=True) self.assertEqual('root_entry', results.title) results = self.kp.find_entries(url="http://example.com") self.assertEqual(len(results), 2) results = self.kp.find_entries(notes="entry notes", url="http://example.com") self.assertEqual(len(results), 1) self.assertTrue(self.kp.find_entries(title='group_entry', first=True) in results) # test `group` argument results = self.kp.find_entries(title='foobar_entry', group=None) self.assertEqual(len(results), 3) group = self.kp.find_groups(name='foobar_group', first=True) results = self.kp.find_entries(title='foobar_entry', group=group) self.assertEqual(len(results), 2) # ---------- History ----------- def test_is_a_history_entry(self): for title in ["root_entry", "subentry"]: res1 = self.kp.find_entries(title=title) for entry in res1: self.assertFalse(entry.is_a_history_entry) res2 = self.kp.find_entries(title=title, history=True) self.assertTrue(len(res2) > len(res1)) for entry in res2: if entry not in res1: self.assertTrue(entry.is_a_history_entry) def test_history(self): entry = self.kp.find_entries(title="subentry2", first=True) hist = entry.history self.assertIsInstance(hist, list) self.assertEqual(len(hist), 0) entry = self.kp.find_entries(title="subentry", first=True) hist = entry.history self.assertIsInstance(hist, list) self.assertEqual(len(hist), 4) self.assertEqual(len(set(hist)), 4) self.assertNotEqual(hist[0], hist[1]) def test_history_path(self): for title in ["root_entry", "subentry"]: entry = self.kp.find_entries(title=title, first=True) hist = entry.history self.assertTrue(len(hist) > 0) for item in hist: self.assertEqual(item.path, entry.path) def test_history_group(self): for title in ["root_entry", "subentry"]: entry = self.kp.find_entries(title=title, first=True) grp1 = entry.group hist = entry.history self.assertTrue(len(hist) > 0) for item in hist: grp2 = item.group self.assertEqual(grp1, grp2) # ---------- Adding/Deleting entries ----------- def test_add_delete_move_entry(self): unique_str = 'test_add_entry_' expiry_time = datetime.now(timezone.utc) entry = self.kp.add_entry( self.kp.root_group, unique_str + 'title', unique_str + 'user', unique_str + 'pass', url=unique_str + 'url', notes=unique_str + 'notes', tags=['tag1', 'tag2', 'tag3;tag4', 'tag5,tag6'], expiry_time=expiry_time, icon=icons.KEY ) results = self.kp.find_entries_by_title(unique_str + 'title') self.assertEqual(len(results), 1) results = self.kp.find_entries_by_title(unique_str + 'title', first=True) self.assertEqual(results.title, unique_str + 'title') self.assertEqual(results.username, unique_str + 'user') self.assertEqual(results.password, unique_str + 'pass') self.assertEqual(results.url, unique_str + 'url') self.assertEqual(results.notes, unique_str + 'notes') self.assertEqual(len(results.tags), 6) self.assertTrue(results.uuid != None) self.assertTrue(results.autotype_sequence is None) self.assertEqual(results.icon, icons.KEY) sub_group = self.kp.add_group(self.kp.root_group, 'sub_group') self.kp.move_entry(entry, sub_group) results = self.kp.find_entries(path=['sub_group', 'test_add_entry_title'], first=True) self.assertEqual(results.title, entry.title) self.kp.delete_entry(entry) results = self.kp.find_entries_by_title(unique_str + 'title', first=True) self.assertIsNone(results) # test adding entry which exists in another group subgroup = self.kp.find_groups(name='subgroup2', first=True) self.kp.add_entry(subgroup, title='foobar_entry', username='foobar', password='foobar') # test adding entry to root which exists in subgroup self.kp.add_entry(subgroup, title='foobar_entry2', username='foobar', password='foobar') self.kp.add_entry(self.kp.root_group, title='foobar_entry2', username='foobar', password='foobar') def test_raise_exception_entry(self): # Entries name collision exception unique_str = 'test_add_entry_' entry = self.kp.add_entry( self.kp.root_group, unique_str + 'title', unique_str + 'user', unique_str + 'pass', url=unique_str + 'url', notes=unique_str + 'notes', tags=unique_str + 'tags', icon=icons.KEY ) self.assertRaises(Exception, entry) # ---------- Timezone test ----------- def test_expiration_time_tz(self): # The expiration date is compared in UTC # setting expiration date with tz offset 6 hours should result in expired entry unique_str = 'test_exptime_tz_1_' expiry_time = datetime.now(timezone(offset=timedelta(hours=6))).replace(microsecond=0) self.kp.add_entry( self.kp.root_group, unique_str + 'title', unique_str + 'user', unique_str + 'pass', expiry_time=expiry_time ) results = self.kp.find_entries_by_title(unique_str + 'title', first=True) self.assertEqual(results.expired, True) self.assertEqual(results.expiry_time, expiry_time.astimezone(timezone.utc)) # setting expiration date with UTC tz should result in expired entry unique_str = 'test_exptime_tz_2_' expiry_time = datetime.now(timezone.utc).replace(microsecond=0) self.kp.add_entry( self.kp.root_group, unique_str + 'title', unique_str + 'user', unique_str + 'pass', expiry_time=expiry_time ) results = self.kp.find_entries_by_title(unique_str + 'title', first=True) self.assertEqual(results.expired, True) self.assertEqual(results.expiry_time, expiry_time.astimezone(timezone.utc)) # setting expiration date with tz offset -6 hours while adding 6 hours should result in valid entry unique_str = 'test_exptime_tz_3_' expiry_time = datetime.now(timezone(offset=timedelta(hours=-6))).replace(microsecond=0) + timedelta(hours=6) self.kp.add_entry( self.kp.root_group, unique_str + 'title', unique_str + 'user', unique_str + 'pass', expiry_time=expiry_time ) results = self.kp.find_entries_by_title(unique_str + 'title', first=True) self.assertEqual(results.expired, False) self.assertEqual(results.expiry_time, expiry_time.astimezone(timezone.utc)) # ---------- Entries representation ----------- def test_print_entries(self): self.assertIsInstance(self.kp.entries.__repr__(), str) e = self.kp.find_entries(title='Тест', first=True) e.save_history() self.assertIsInstance(e.__repr__(), str) self.assertIsInstance(e.history.__repr__(), str) # issue 250 e = self.kp.find_entries(username='blank_title', first=True) self.assertIsNot(e, None) self.assertIsInstance(e.__repr__(), str) class GroupFindTests3(KDBX3Tests): # ---------- Finding groups ----------- def test_find_groups_by_name(self): results = self.kp.find_groups_by_name('subgroup') self.assertEqual(len(results), 1) results = self.kp.find_groups_by_name('subgroup', first=True) self.assertEqual(results.name, 'subgroup') g = self.kp.find_groups(name='foobar_group', first=True) results = self.kp.find_groups(group=g, name='.*group.*', regex=True) self.assertEqual(len(results), 2) results = self.kp.find_groups(group=g, name='.*group.*', regex=True, recursive=False) self.assertEqual(len(results), 1) def test_find_groups_by_path(self): results = self.kp.find_groups_by_path(['foobar_group', 'subgroup']) self.assertIsInstance(results, Group) results = self.kp.find_groups(path=['foobar_group', 'subgroup'], first=True) self.assertEqual(results.name, 'subgroup') results = self.kp.find_groups(path=['foobar_group', 'group_entry']) self.assertEqual(results, None) def test_find_groups_by_uuid(self): uu = uuid.UUID('95155a32-5317-a10f-d4e4-d0c2030264b6') results = self.kp.find_groups_by_uuid(uu, first=True) self.assertIsInstance(results, Group) results = self.kp.find_groups(uuid=uu, regex=True) self.assertEqual(len(results), 1) def test_find_groups_by_notes(self): results = self.kp.find_groups(notes='group notes') self.assertEqual(len(results), 1) uu = uuid.UUID('95155a32-5317-a10f-d4e4-d0c2030264b6') self.assertEqual(results[0].uuid, uu) def test_groups(self): results = self.kp.groups self.assertEqual(len(results), 7) # ---------- Adding/Deleting Groups ----------- def test_add_delete_move_group(self): notes_text = "this is a note for a group!" base_group = self.kp.add_group(self.kp.root_group, 'base_group', notes=notes_text) sub_group = self.kp.add_group(base_group, 'sub_group') sub_group2 = self.kp.add_group(base_group, 'sub_group2') self.assertEqual(base_group.notes, notes_text) base_group.notes = '' self.assertEqual(base_group.notes, '') results = self.kp.find_groups(path=['base_group', 'sub_group'], first=True) self.assertIsInstance(results, Group) self.assertEqual(results.name, sub_group.name) self.assertTrue(results.uuid != None) self.kp.move_group(sub_group2, sub_group) results = self.kp.find_groups(path=['base_group', 'sub_group', 'sub_group2'], first=True) self.assertEqual(results.name, sub_group2.name) self.kp.delete_group(sub_group) results = self.kp.find_groups(path=['base_group', 'sub_group'], first=True) self.assertIsNone(results) # ---------- Groups representation ----------- def test_print_groups(self): self.assertIsInstance(self.kp.groups.__repr__(), str) g = self.kp.find_groups(notes='blank_name') self.assertIsNot(g, None) self.assertIsInstance(g.__repr__(), str) class RecycleBinTests3(KDBX3Tests): def test_recyclebincreation(self): self.assertIsNone(self.kp.recyclebin_group) entry = self.kp.add_entry( self.kp.root_group, "RecycleBinTest1", "login", "password") self.kp.trash_entry(entry) self.assertIsNotNone(self.kp.recyclebin_group) self.assertEqual( len(self.kp.recyclebin_group.entries), 1) def test_entry(self): entry = self.kp.add_entry( self.kp.root_group, "RecycleBinTest2", "login", "password") entry_uuid = entry.uuid self.kp.trash_entry(entry) entries_in_root = self.kp.find_entries(uuid=entry_uuid, group=self.kp.root_group, recursive=False ) self.assertEqual( len(entries_in_root), 0) entries_in_recyclebin = self.kp.find_entries(uuid=entry_uuid, group=self.kp.recyclebin_group, recursive=False ) self.assertEqual( len(entries_in_recyclebin), 1) def test_group(self): group = self.kp.add_group( self.kp.root_group, "RecycleBinTest3 Group") group_uuid = group.uuid entry = self.kp.add_entry( group, "RecycleBinTest3 Entry", "login", "password") entry_uuid = entry.uuid self.kp.trash_group(group) groups_in_root = self.kp.find_groups(uuid=group_uuid, group=self.kp.root_group, recursive=False ) self.assertEqual( len(groups_in_root), 0) groups_in_recyclebin = self.kp.find_groups(uuid=group_uuid, group=self.kp.recyclebin_group, recursive=False ) self.assertEqual( len(groups_in_recyclebin), 1) group_in_recyclebin = groups_in_recyclebin[0] self.assertEqual( len(group_in_recyclebin.entries), 1) self.assertEqual( group_in_recyclebin.entries[0].uuid, entry_uuid) def test_recyclebinemptying(self): entry = self.kp.add_entry( self.kp.root_group, "RecycleBinTest4 Entry", "login", "password") self.kp.trash_entry(entry) group = self.kp.add_group( self.kp.root_group, "RecycleBinTest4 Group") self.kp.trash_group(group) self.assertEqual( len(self.kp.recyclebin_group.subgroups), 1) self.assertEqual( len(self.kp.recyclebin_group.entries), 1) self.kp.empty_group(self.kp.recyclebin_group) self.assertEqual( len(self.kp.recyclebin_group.subgroups), 0) self.assertEqual( len(self.kp.recyclebin_group.entries), 0) class EntryTests3(KDBX3Tests): def test_fields(self): expiry_time = datetime.now(timezone.utc).replace(microsecond=0) entry = Entry( 'title', 'username', 'password', url='url', notes='notes', tags='tags', otp='otp', expires=True, expiry_time=expiry_time, icon=icons.KEY, kp=self.kp ) self.assertEqual(entry.title, 'title') self.assertEqual(entry.username, 'username') self.assertEqual(entry.password, 'password') self.assertEqual(entry.url, 'url') self.assertEqual(entry.notes, 'notes') self.assertEqual(entry.tags, ['tags']) self.assertEqual(entry.otp, 'otp') self.assertEqual(entry.expires, True) self.assertEqual(entry.expiry_time, expiry_time) self.assertEqual(entry.icon, icons.KEY) self.assertEqual(entry.is_a_history_entry, False) self.assertEqual( self.kp.find_entries(title='subentry', first=True).path, ['foobar_group', 'subgroup', 'subentry'] ) self.assertEqual( self.kp.find_entries(title='root_entry', first=True).history[0].group, self.kp.root_group ) def test_references(self): original_entry = self.kp.find_entries(title='foobar_entry', first=True) original_entry_duplicate = self.kp.find_entries(title='foobar_entry', first=True) clone1 = self.kp.find_entries(title='foobar_entry - Clone', first=True) clone2 = self.kp.find_entries(title='foobar_entry - Clone of clone', first=True) prefixed = self.kp.find_entries(title='foobar_entry - Clone with prefix and suffix', first=True) self.assertEqual(self.kp.deref(clone2.username), original_entry.username) self.assertEqual(clone2.deref('username'), original_entry.username) self.assertEqual(clone2.deref('password'), original_entry.password) self.assertEqual(original_entry.ref('username'), clone1.username) self.assertEqual(prefixed.deref('username'), 'domain\\{}2'.format(original_entry.username)) self.assertEqual(prefixed.deref('password'), 'A{}BC'.format(original_entry.password)) self.assertEqual(original_entry, original_entry_duplicate) self.assertEqual(hash(original_entry), hash(original_entry_duplicate)) self.assertNotEqual(original_entry, clone1) self.assertNotEqual(clone1, clone2) def test_set_and_get_fields(self): time = datetime.now(timezone.utc).replace(microsecond=0) changed_time = time + timedelta(hours=9) changed_string = 'changed_' entry = Entry( 'title', 'username', 'password', url='url', notes='notes', tags='tags', expires=True, expiry_time=time, icon=icons.KEY, kp=self.kp ) entry.title = changed_string + 'title' entry.username = changed_string + 'username' entry.password = changed_string + 'password' entry.url = changed_string + 'url' entry.notes = changed_string + 'notes' entry.expires = False entry.expiry_time = changed_time entry.icon = icons.GLOBE entry.set_custom_property('foo', 'bar') entry.set_custom_property('multiline', 'hello\nworld') entry.otp = "otpsecret" self.assertEqual(entry.title, changed_string + 'title') self.assertEqual(entry.username, changed_string + 'username') self.assertEqual(entry.password, changed_string + 'password') self.assertEqual(entry.url, changed_string + 'url') self.assertEqual(entry.notes, changed_string + 'notes') self.assertEqual(entry.icon, icons.GLOBE) self.assertEqual(entry.get_custom_property('foo'), 'bar') self.assertEqual(entry.get_custom_property('multiline'), 'hello\nworld') self.assertEqual(entry.otp, 'otpsecret') self.assertIn('foo', entry.custom_properties) entry.delete_custom_property('foo') self.assertEqual(entry.get_custom_property('foo'), None) # test time properties self.assertEqual(entry.expires, False) self.assertEqual(entry.expiry_time, changed_time) entry.tags = 'changed_tags' self.assertEqual(entry.tags, ['changed_tags']) entry.tags = 'changed;tags' self.assertEqual(entry.tags, ['changed', 'tags']) entry.tags = ['changed', 'again', 'tags'] self.assertEqual(entry.tags, ['changed', 'again', 'tags']) def test_expired_datetime_offset(self): """Test for https://github.com/pschmitt/pykeepass/issues/115""" future_time = datetime.now(timezone.utc) + timedelta(days=1) past_time = datetime.now(timezone.utc) - timedelta(days=1) entry = Entry( 'title', 'username', 'password', expires=True, expiry_time=future_time, kp=self.kp ) self.assertFalse(entry.expired) entry.expiry_time = past_time self.assertTrue(entry.expired) def test_touch(self): """Test for https://github.com/pschmitt/pykeepass/issues/120""" entry = self.kp.find_entries_by_title('root_entry', first=True) atime = entry.atime mtime = entry.mtime ctime = entry.ctime entry.touch() self.assertTrue(atime < entry.atime) self.assertEqual(mtime, entry.mtime) self.assertEqual(ctime, entry.ctime) entry = self.kp.find_entries_by_title('foobar_entry', first=True) atime = entry.atime mtime = entry.mtime ctime = entry.ctime entry.touch(modify=True) self.assertTrue(atime < entry.atime) self.assertTrue(mtime < entry.mtime) self.assertEqual(ctime, entry.ctime) group = self.kp.find_groups(name='foobar_group', first=True) atime = group.atime mtime = group.mtime ctime = group.ctime group.touch(modify=True) self.assertTrue(atime < group.atime) self.assertTrue(mtime < group.mtime) self.assertEqual(ctime, group.ctime) def test_add_remove_attachment(self): entry = self.kp.add_entry( self.kp.root_group, title='title', username='username', password='password', ) num_attach = len(entry.attachments) entry.add_attachment(0, 'foobar.txt') entry.add_attachment(0, 'foobar2.txt') self.assertEqual(len(entry.attachments), num_attach + 2) a = self.kp.find_attachments(id=0, filename='foobar.txt', first=True) self.assertEqual(a.filename, 'foobar.txt') self.assertEqual(a.id, 0) entry.delete_attachment(a) self.assertEqual(len(entry.attachments), num_attach + 1) self.assertEqual(entry.attachments[0].filename, 'foobar2.txt') def test_is_custom_property_protected(self): e = self.kp.add_entry(self.kp.root_group, 'test-protect', 'some-user', 'pass') e.set_custom_property('protected', 'something', protect=True) e.set_custom_property('explicit-unprotected', 'other', protect=False) e.set_custom_property('not-protected', 'secret') self.assertTrue(e.is_custom_property_protected('protected')) self.assertFalse(e.is_custom_property_protected('explicit-unprotected')) self.assertFalse(e.is_custom_property_protected('not-protected')) self.assertFalse(e.is_custom_property_protected('non-existent')) def test_reindex(self): e1 = self.kp.add_entry(self.kp.root_group, 'Test-Index1', 'user-index', 'pass') e2 = self.kp.add_entry(self.kp.root_group, 'Test-Index2', 'user-index', 'pass') e3 = self.kp.add_entry(self.kp.root_group, 'Test-Index3', 'user-index', 'pass') e4 = self.kp.add_entry(self.kp.root_group, 'Test-Index4', 'user-index', 'pass') e2.reindex(0) e3.reindex(0) e4.reindex(0) entries = self.kp.find_entries(username="user-index") self.assertEqual(entries, [e4,e3,e2,e1]) class EntryHistoryTests3(KDBX3Tests): # ---------- History ----------- def test_find_history_entries(self): '''run some tests on entries created by pykeepass''' prefix = 'TFE_' changed = 'tfe_changed_' # create some new entries to have clean start e1 = self.kp.add_entry( self.kp.root_group, prefix + 'title', prefix + 'user', prefix + 'pass' ) g1 = self.kp.add_group(self.kp.root_group, prefix + 'group') e2 = self.kp.add_entry( g1, prefix + 'title', prefix + 'user', prefix + 'pass' ) g2 = self.kp.add_group(g1, prefix + 'sub_group') e2 = self.kp.add_entry( g2, prefix + 'title', prefix + 'user', prefix + 'pass' ) # no history tests res1 = self.kp.find_entries(title=prefix + 'title') self.assertEqual(len(res1), 3) for entry in res1: self.assertFalse(entry.is_a_history_entry) hist = entry.history self.assertIsInstance(hist, list) self.assertEqual(len(hist), 0) res2 = self.kp.find_entries(title=prefix + 'title', history=True) self.assertEqual(len(res2), 3) # create history for entry in res1: entry.save_history() # first history tests # we should not find any history items res1 = self.kp.find_entries(title=prefix + 'title') self.assertEqual(len(res1), 3) for entry in res1: self.assertFalse(entry.is_a_history_entry) hist = entry.history self.assertEqual(len(hist), 1) for item in hist: self.assertTrue(item.is_a_history_entry) self.assertEqual(item.group, entry.group) self.assertTrue(str(item).startswith('HistoryEntry:')) # here history items are expected res2 = self.kp.find_entries(title=prefix + 'title', history=True) self.assertEqual(len(res2), 6) for entry in res2: if entry not in res1: self.assertTrue(entry.is_a_history_entry) # change the active entries to test integrity of the history items backup = {} now = datetime.now(timezone.utc) for entry in res1: backup[entry.uuid] = {"atime": entry.atime, "mtime": entry.mtime, "ctime": entry.ctime} entry.title = changed + 'title' entry.username = changed + 'user' entry.password = changed + 'pass' entry.atime = now entry.mtime = now # changed entries tests # title of active entries has changed, so we shouldn't find anything res = self.kp.find_entries(title=prefix + 'title') self.assertEqual(len(res), 0) # title of history items should still be intact res = self.kp.find_entries(title=prefix + 'title', history=True) self.assertEqual(len(res), 3) # dito username, assuming if this works, it will also work for all other find_by cases res = self.kp.find_entries(username=prefix + 'user') self.assertEqual(len(res), 0) res = self.kp.find_entries(username=prefix + 'user', history=True) self.assertEqual(len(res), 3) # testing integrity of history item res = self.kp.find_entries(title=changed + 'title') for entry in res: for item in entry.history: self.assertEqual(item.title, prefix + 'title') self.assertEqual(item.username, prefix + 'user') self.assertEqual(item.password, prefix + 'pass') self.assertEqual(item.atime, backup[entry.uuid]["atime"]) self.assertEqual(item.mtime, backup[entry.uuid]["mtime"]) self.assertEqual(item.ctime, backup[entry.uuid]["ctime"]) # create a second history item # back in time I had the problem that the first call to save_history() worked but not the second for entry in res: entry.save_history() # second history tests res1 = self.kp.find_entries(title=changed + 'title') self.assertEqual(len(res1), 3) for entry in res1: self.assertFalse(entry.is_a_history_entry) hist = entry.history self.assertEqual(len(hist), 2) for item in hist: self.assertTrue(item.is_a_history_entry) self.assertEqual(item.group, entry.group) res2 = self.kp.find_entries(title=changed + 'title', history=True) self.assertEqual(len(res2), 6) for entry in res2: if entry not in res1: self.assertTrue(entry.is_a_history_entry) # try deleting a history entry h = e1.history[0] self.assertIn(h, e1.history) e1.delete_history(h) self.assertNotIn(h, e1.history) # delete all history self.assertTrue(len(e1.history) > 0) e1.delete_history(all=True) self.assertTrue(len(e1.history) == 0) class GroupTests3(KDBX3Tests): def test_fields(self): self.assertEqual( self.kp.find_groups(name='subgroup2', first=True).path, ['foobar_group', 'subgroup', 'subgroup2'] ) def test_empty_group(self): # test that groups are properly emptied emptytest = self.kp.add_group(self.kp.root_group, 'emptytest_group') self.kp.add_entry(emptytest, 'emptytest_entry', 'user', 'pass') self.kp.add_group(emptytest, 'emptytest_subgroup') self.assertEqual(len(emptytest.entries), 1) self.assertEqual(len(emptytest.subgroups), 1) self.kp.empty_group(emptytest) self.assertEqual(len(emptytest.entries), 0) self.assertEqual(len(emptytest.subgroups), 0) class AttachmentTests3(KDBX3Tests): # get some things ready before testing def test_create_delete_binary(self): with self.assertRaises(BinaryError): self.kp_tmp.delete_binary(999) with self.assertRaises(BinaryError): e = self.kp_tmp.entries[0] e.add_attachment(filename='foo.txt', id=123) e.attachments[0].binary binary_id = self.kp_tmp.add_binary(b'Ronald McDonald Trump') self.kp_tmp.save() self.kp_tmp.reload() self.assertEqual(self.kp_tmp.binaries[binary_id], b'Ronald McDonald Trump') self.assertEqual(len(self.kp_tmp.attachments), 2) num_attach = len(self.kp_tmp.binaries) self.kp_tmp.delete_binary(binary_id) self.kp_tmp.save() self.kp_tmp.reload() self.assertEqual(len(self.kp_tmp.binaries), num_attach - 1) # test empty attachment - issue 314 a = self.kp.find_attachments(filename='foo.txt', first=True) self.assertEqual(a._element.text, None) self.assertEqual(a.data, b'') def test_attachment_reference_decrement(self): e = self.kp.entries[0] binary_id1 = self.kp.add_binary(b'foobar') binary_id2 = self.kp.add_binary(b'foobar2') attachment1 = e.add_attachment(binary_id1, 'foo.txt') attachment2 = e.add_attachment(binary_id2, 'foo.txt') self.kp.delete_binary(binary_id1) self.assertEqual(attachment2.id, binary_id2 - 1) def test_fields(self): # test creation e = self.kp.entries[0] binary_id = self.kp.add_binary(b'foobar') a = e.add_attachment(filename='test.txt', id=binary_id) self.assertEqual(a.data, b'foobar') self.assertEqual(a.id, binary_id) self.assertEqual(a.filename, 'test.txt') class PyKeePassTests3(KDBX3Tests): def test_set_credentials(self): self.kp_tmp.password = 'f00bar' self.kp_tmp.keyfile = base_dir / 'change.key' self.kp_tmp.save() self.kp_tmp = PyKeePass( self.kp_tmp.filename, 'f00bar', self.kp_tmp.keyfile ) results = self.kp.find_entries_by_username('foobar_user', first=True) self.assertEqual('foobar_user', results.username) def test_dump_xml(self): self.kp.dump_xml('db_dump.xml') with open('db_dump.xml') as f: first_line = f.readline() self.assertEqual(first_line, '\n') def test_credchange(self): """ - test rec/req boolean (expired, no expired, days=-1) - test get/set days - test cred set timer reset """ required_days = 5 recommended_days = 5 unexpired_date = datetime.now(timezone.utc) - timedelta(days=1) expired_date = datetime.now(timezone.utc) - timedelta(days=10) self.kp.credchange_required_days = required_days self.kp.credchange_recommended_days = recommended_days # test not expired self.kp.credchange_date = unexpired_date self.assertFalse(self.kp.credchange_required) self.assertFalse(self.kp.credchange_recommended) # test expired self.kp.credchange_date = expired_date self.assertTrue(self.kp.credchange_required) self.assertTrue(self.kp.credchange_recommended) # test expiry disabled self.kp.credchange_required_days = -1 self.kp.credchange_recommended_days = -1 self.assertFalse(self.kp.credchange_required) self.assertFalse(self.kp.credchange_recommended) # test credential update self.kp.credchange_required_days = required_days self.kp.credchange_recommended_days = recommended_days self.kp.credchange_date = expired_date self.assertTrue(self.kp.credchange_required) self.assertTrue(self.kp.credchange_recommended) self.kp.keyfile = 'foo' self.assertFalse(self.kp.credchange_required) self.assertFalse(self.kp.credchange_recommended) class BugRegressionTests3(KDBX3Tests): def test_issue129(self): # issue 129 - protected multiline string fields lose newline e = self.kp.find_entries(title='foobar_entry', first=True) self.assertEqual(e.get_custom_property('multiline'), 'hello\nworld') def test_pull102(self): # PR 102 - entries are protected after save # reset self.kp_tmp self.setUp() e = self.kp_tmp.find_entries(title='foobar_entry', first=True) self.assertEqual(e.password, 'foobar') self.kp_tmp.save() self.assertEqual(e.password, 'foobar') def test_issue193(self): # issue 193 - kp.entries doesn't return entries with title=None e = self.kp.add_entry(self.kp.root_group, 'test', 'user', 'pass') prop = e._xpath('String/Key[text()="Title"]/..', first=True) e._element.remove(prop) self.assertTrue(e.title is None) self.assertTrue(e in self.kp.entries) # also test for kp.groups g = self.kp.add_group(self.kp.root_group, 'test_g') prop = g._xpath('Name', first=True) g._element.remove(prop) self.assertTrue(g.name is None) self.assertTrue(g in self.kp.groups) def test_issue194(self): # entries with Protected=True aren't being protected properly self.kp_tmp.add_entry(self.kp_tmp.root_group, 'protect_test', 'user', 'pass') self.kp_tmp.save() self.kp_tmp.reload() e = self.kp_tmp.find_entries(title='protect_test', first=True) self.assertEqual(e.password, 'pass') def test_issue223(self): # issue 223 - database is clobbered when kp.save() fails # even if exception is caught # test clobbering with file on disk # change keyfile so database save fails self.kp_tmp.keyfile = 'foo' with self.assertRaises(Exception): self.kp_tmp.save() # try to open database self.kp_tmp.keyfile = self.keyfile_tmp PyKeePass(self.database_tmp, self.password, self.keyfile_tmp) # reset test database self.setUp() # test clobbering with buffer stream = BytesIO() self.kp_tmp.save(stream) stream.seek(0) # change keyfile so database save fails self.kp_tmp.keyfile = 'foo' self.kp_tmp.password = ('invalid', 'type') with self.assertRaises(Exception): self.kp_tmp.save(stream) stream.seek(0) # try to open database self.kp_tmp.keyfile = self.keyfile_tmp PyKeePass(stream, self.password, self.keyfile_tmp) def test_issue308(self): # find_entries/find_groups() break when supplied None values directly results = self.kp.find_entries(title='foobar_entry') results2 = self.kp.find_entries(title='foobar_entry', username=None) self.assertEqual(results, results2) def test_issue344(self): # accessing expiry_time throws exception when None e = self.kp_tmp.find_entries(title='none_date', first=True) e._element.xpath('Times/ExpiryTime')[0].text = None self.assertEqual(e.expiry_time, None) class EntryFindTests4(KDBX4Tests, EntryFindTests3): pass class GroupFindTests4(KDBX4Tests, GroupFindTests3): pass class RecycleBinTests4(KDBX4Tests, RecycleBinTests3): pass class EntryTests4(KDBX4Tests, EntryTests3): pass class GroupTests3(KDBX4Tests, GroupTests3): pass class AttachmentTests4(KDBX4Tests, AttachmentTests3): pass class PyKeePassTests4(KDBX4Tests, PyKeePassTests3): pass class BugRegressionTests4(KDBX4Tests, BugRegressionTests3): pass class CtxManagerTests(unittest.TestCase): def test_ctx_manager(self): with PyKeePass(base_dir / 'test4.kdbx', password='password', keyfile=base_dir / 'test4.key') as kp: results = kp.find_entries_by_username('foobar_user', first=True) self.assertEqual('foobar_user', results.username) class KDBXTests(unittest.TestCase): def test_open_save(self): """try to open all databases, save them, then open the result""" # for database stream open test with open(base_dir / 'test3.kdbx', 'rb') as file: stream = BytesIO(file.read()) # for keyfile file descriptor test keyfile_fd = open(base_dir / 'test4.key', 'rb') filenames_in = [ base_dir / 'test3.kdbx', # KDBX v3 base_dir / 'test4_aes.kdbx', # KDBX v4 AES base_dir / 'test4_aeskdf.kdbx', # KDBX v3 AESKDF base_dir / 'test4_chacha20.kdbx', # KDBX v4 ChaCha base_dir / 'test4_twofish.kdbx', # KDBX v4 Twofish base_dir / 'test4_hex.kdbx', # legacy 64 byte hexadecimal keyfile base_dir / 'test3_transformed.kdbx', # KDBX v3 transformed_key open base_dir / 'test4_transformed.kdbx', # KDBX v4 transformed_key open stream, # test stream opening base_dir / 'test4_aes_uncompressed.kdbx',# KDBX v4 AES uncompressed base_dir / 'test4_twofish_uncompressed.kdbx',# KDBX v4 Twofish uncompressed base_dir / 'test4_chacha20_uncompressed.kdbx',# KDBX v4 ChaCha uncompressed base_dir / 'test4_argon2id.kdbx', # KDBX v4 Argon2id base_dir / 'test4.kdbx', # KDBX v4 with keyfile file descriptor ] filenames_out = [ base_dir / 'test3.kdbx.out', base_dir / 'test4_aes.kdbx.out', base_dir / 'test4_aeskdf.kdbx.out', base_dir / 'test4_chacha20.kdbx.out', base_dir / 'test4_twofish.kdbx.out', base_dir / 'test4_hex.kdbx.out', base_dir / 'test3_transformed.kdbx.out', base_dir / 'test4_transformed.kdbx.out', BytesIO(), base_dir / 'test4_aes_uncompressed.kdbx.out', base_dir / 'test4_twofish_uncompressed.kdbx.out',# KDBX v4 Twofish uncompressed base_dir / 'test4_chacha20_uncompressed.kdbx.out',# KDBX v4 ChaCha uncompressed base_dir / 'test4_argon2id.kdbx.out', base_dir / 'test4.kdbx.out', # KDBX v4 with keyfile file descriptor ] passwords = [ 'password', 'password', 'password', 'password', 'password', 'password', None, None, 'password', 'password', 'password', 'password', 'password', 'password', ] transformed_keys = [ None, None, None, None, None, None, b'\xfb\xb1!\x0e0\x94\xd4\x868\xa5\x04\xe6T\x9b<\xf9+\xb8\x82EN\xbc\xbe\xbc\xc8\xd3\xbbf\xfb\xde\xff.', b'\x95\x0be\x9ca\x9e<\xe0\x07\x02\x7f\xc3\xd8\xa1\xa6&\x985\x8f!\xa6\x18k\x13\xa2\xd2\r=\xf3\xebd\xc5', None, None, None, None, None, None, ] keyfiles = [ base_dir / 'test3.key', base_dir / 'test4.key', base_dir / 'test4.key', base_dir / 'test4.key', base_dir / 'test4.key', base_dir / 'test4_hex.key', None, None, base_dir / 'test3.key', None, None, None, None, keyfile_fd ] encryption_algorithms = [ 'aes256', 'aes256', 'aes256', 'chacha20', 'twofish', 'chacha20', 'aes256', 'chacha20', 'aes256', 'aes256', 'twofish', 'chacha20', 'aes256', 'chacha20', ] kdf_algorithms = [ 'aeskdf', 'argon2', 'aeskdf', 'argon2', 'argon2', 'argon2', 'aeskdf', 'argon2', 'aeskdf', 'argon2', 'argon2', 'argon2', 'argon2id', 'argon2', ] versions = [ (3, 1), (4, 0), (4, 0), (4, 0), (4, 0), (4, 0), (3, 1), (4, 0), (3, 1), (4, 0), (4, 0), (4, 0), (4, 0), (4, 0), ] for (filename_in, filename_out, password, transformed_key, keyfile, encryption_algorithm, kdf_algorithm, version) in zip( filenames_in, filenames_out, passwords, transformed_keys, keyfiles, encryption_algorithms, kdf_algorithms, versions ): kp = PyKeePass( filename_in, password, keyfile, transformed_key=transformed_key ) self.assertEqual(kp.encryption_algorithm, encryption_algorithm) self.assertEqual(kp.kdf_algorithm, kdf_algorithm) self.assertEqual(kp.version, version) kp.save( filename_out, transformed_key=transformed_key ) if hasattr(filename_out, "seek"): # rewind so PyKeePass can read from the same stream filename_out.seek(0) kp = PyKeePass( filename_out, password, keyfile, transformed_key=transformed_key ) for filename in base_dir.glob('*.out'): os.remove(filename) keyfile_fd.close() def test_open_error(self): databases = [ 'test3.kdbx', 'test3.kdbx', 'test4.kdbx', 'test4.kdbx', 'test4.kdbx', 'test4.kdbx', 'test3.key', ] passwords = [ 'invalid', 'password', 'invalid', 'password', 'password', 'password', 'password', ] keyfiles = [ 'test3.key', 'test4.key', 'test4.key', 'test_invalidversion.key', 'test.svg', 'test3.key', ] errors = [ CredentialsError, CredentialsError, CredentialsError, CredentialsError, CredentialsError, CredentialsError, HeaderChecksumError, ] for database, password, keyfile, error in zip(databases, passwords, keyfiles, errors): with self.assertRaises(error): PyKeePass( base_dir / database, password, base_dir / keyfile ) def test_open_no_decrypt(self): """Open database but do not decrypt payload. Needed for reading header data for OTP tokens""" databases = [ 'test3.kdbx', 'test4.kdbx', ] passwords = [ 'invalid_password', 'invalid_password', ] enc_algs = [ 'aes256', 'chacha20' ] versions = [ (3, 1), (4, 0), ] for database, password, enc_alg, version in zip(databases, passwords, enc_algs, versions): kp = PyKeePass( os.path.join(base_dir, database), password, decrypt=False ) self.assertEqual(kp.encryption_algorithm, enc_alg) self.assertEqual(kp.version, version) if __name__ == '__main__': unittest.main()