audit-labs/evidence-seal
Tamper-evident seals and chain of custody for audit evidence.
clone: git clone https://gitbay.org/audit-labs/evidence-seal.git
5a9365de648fbebc60be14161e394e959bdb7e5c
verified · cmc
author: Christian Cleberg <hello@cleberg.net> · 2026-08-06T08:07:13Z
.gitignore | 16 ++ CODEOWNERS | 1 + LICENSE | 674 ++++++++++++++++++++++++++++++++++++++++++++++ README.md | 131 +++++++++ conftest.py | 6 + evidence_seal/__init__.py | 8 + evidence_seal/__main__.py | 6 + evidence_seal/cli.py | 226 ++++++++++++++++ evidence_seal/hashing.py | 54 ++++ evidence_seal/manifest.py | 191 +++++++++++++ evidence_seal/signing.py | 113 ++++++++ pyproject.toml | 28 ++ requirements-dev.txt | 3 + ruff.toml | 7 + tests/test_cli.py | 74 +++++ tests/test_hashing.py | 39 +++ tests/test_manifest.py | 102 +++++++ tests/test_signing.py | 63 +++++ 18 files changed, 1742 insertions(+) new file mode 100644 @@ -0,0 +1,16 @@ +.venv +venv + +# Python +__pycache__/ +**/__pycache__/ +*.py[cod] +*.egg-info/ +.pytest_cache/ +.ruff_cache/ +build/ +dist/ + +# Local keys and manifests produced by ad-hoc runs +*.pem +/scratch/ new file mode 100644 @@ -0,0 +1 @@ +* @ccleberg @ekraai2 new file mode 100644 @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +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: + + <program> Copyright (C) <year> <name of author> + 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 +<https://www.gnu.org/licenses/>. + + 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 +<https://www.gnu.org/licenses/why-not-lgpl.html>. new file mode 100644 @@ -0,0 +1,131 @@ +# evidence-seal + +[](LICENSE) +[]() + +Tamper-evident seals and chain of custody for audit evidence packages. + +Every Audit Labs tool assumes the evidence it handles is authentic. `evidence-seal` +is what makes that assumption checkable. Point it at a directory of evidence — an +[audit-tools](https://github.com/audit-labs/audit-tools) package, a folder of +exported screenshots, anything — and it writes a `manifest.json` that pins every +file's SHA-256 into a single Merkle fingerprint. Later, `verify` proves the +directory is byte-for-byte what was sealed, and names anything that changed. + +- **Integrity** — detect any modified, added, or removed file. +- **Chain of custody** — link sequential seals so a series of dated packages + forms an append-only history; reordering or removing one is detectable. +- **Attribution** *(optional)* — sign a manifest with an ed25519 key so a named + party attests "I collected this," not just "it is unchanged." + +The core (`seal`, `verify`, `chain`) is **pure standard library** — no +dependencies. Signing needs `cryptography` (`pip install evidence-seal[sign]`). + +## Install + +```bash +git clone https://github.com/audit-labs/evidence-seal +cd evidence-seal +python -m venv .venv && source .venv/bin/activate +pip install -e ".[sign]" # drop [sign] for the zero-dependency core +``` + +## Usage + +```bash +# Seal a package (manifest written to <dir>.manifest.json alongside it) +evidence-seal seal ./output/aws_audit_prod_2026-01-01 \ + --meta engagement=ACME-2026 --meta collector="Christian Cleberg" + +# Later, prove nothing changed +evidence-seal verify ./output/aws_audit_prod_2026-01-01 +# -> intact — 8 files match the seal (exit 0) +# -> TAMPERED … MODIFIED iam_users.csv (exit 1) +``` + +### Chain of custody + +Seal each new package against the previous manifest to build a verifiable +timeline: + +```bash +evidence-seal seal ./pkg_jan --out seals/jan.json +evidence-seal seal ./pkg_feb --out seals/feb.json --prev seals/jan.json +evidence-seal seal ./pkg_mar --out seals/mar.json --prev seals/feb.json + +evidence-seal chain seals/jan.json seals/feb.json seals/mar.json +# -> chain intact — 3 seals link correctly +``` + +Each manifest's `id` is the hash of its own canonical contents, and `previous` +holds the prior manifest's id — so a broken, reordered, or spliced-out link is +caught. + +### Signing (attribution) + +```bash +evidence-seal keygen --private acme.key --public acme.pub # once +evidence-seal seal ./pkg --sign acme.key # seal + sign +evidence-seal verify ./pkg --pubkey acme.pub # require this signer +``` + +Without `--pubkey`, a present signature is still checked for validity; with it, +the signer's key must also match, proving *identity* and not just integrity. + +## The manifest + +Canonical JSON, sorted keys — diff-friendly and reproducible: + +```json +{ + "algorithm": "sha256", + "created_at": "2026-08-06T08:06:05Z", + "subject": "aws_audit_prod_2026-01-01", + "previous": null, + "metadata": { "collector": "Christian Cleberg", "engagement": "ACME-2026" }, + "root": "23fdf7eb…", + "file_count": 8, + "files": [ { "path": "iam_users.csv", "sha256": "309b0e45…", "bytes": 412 } ], + "id": "08b846a0…", + "signature": { "algorithm": "ed25519", "public_key": "1bea5f1d…", "value": "2d7c2d63…" } +} +``` + +- **`root`** — Merkle root over all `(path, sha256)` leaves; one value that + changes if any file, name, or byte changes. +- **`id`** — SHA-256 of the manifest's canonical form (excluding `id` and + `signature`); makes it self-verifying and chainable. +- **`ignore`** — glob patterns skipped at seal time; `verify` reuses them so it + never false-flags an intentionally excluded file. + +## Exit codes + +| Code | Meaning | +| --- | --- | +| `0` | Intact / valid. | +| `1` | Tamper detected, chain broken, or signature invalid. | +| `2` | Usage error (missing directory, bad `--meta`, missing `cryptography`). | + +Fail a pipeline on `1`; treat `2` as a misconfiguration to fix. + +## Threat model + +`evidence-seal` proves a directory matches a manifest, and (when signed) who +produced that manifest. It does **not** prove *when* something was sealed beyond +the self-reported `created_at`, and an unsigned manifest can be regenerated by +anyone with the files. For strong "sealed at time T by party P" guarantees, +sign the manifest and retain the public key out of band; optionally submit the +manifest `id` to an external timestamping authority. Private keys are written +unencrypted — store them accordingly. + +## Development + +```bash +pip install -e ".[dev]" +pytest +ruff check . +``` + +## License + +GPL-3.0-or-later. See [LICENSE](LICENSE). new file mode 100644 @@ -0,0 +1,6 @@ +"""Pin the project root on sys.path so ``import evidence_seal`` works in tests.""" + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent)) new file mode 100644 @@ -0,0 +1,8 @@ +"""evidence-seal — tamper-evident seals for audit evidence packages.""" + +__version__ = "0.1.0" + +# Hash algorithm and manifest format version. Bump MANIFEST_VERSION only on a +# breaking change to the manifest schema so verify can refuse the unknown. +ALGORITHM = "sha256" +MANIFEST_VERSION = 1 new file mode 100644 @@ -0,0 +1,6 @@ +"""Enable ``python -m evidence_seal``.""" + +from .cli import main + +if __name__ == "__main__": + raise SystemExit(main()) new file mode 100644 @@ -0,0 +1,226 @@ +"""Command-line interface for evidence-seal.""" + +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +from . import __version__ +from .manifest import ( + build_manifest, + load_manifest, + verify_chain, + verify_manifest, + write_manifest, +) + +# Exit codes: 0 = intact/valid, 1 = tamper/verification failure, 2 = usage error. +OK, FAILED, USAGE = 0, 1, 2 + + +def _default_manifest_path(directory: Path) -> Path: + return directory.parent / f"{directory.name}.manifest.json" + + +def _manifest_exclude(directory: Path, manifest_path: Path) -> set[str]: + """If the manifest lives inside the sealed dir, it must not seal itself.""" + try: + return {manifest_path.resolve().relative_to(directory.resolve()).as_posix()} + except ValueError: + return set() + + +def _parse_meta(pairs: list[str]) -> dict: + meta = {} + for pair in pairs or []: + if "=" not in pair: + raise ValueError(f"metadata must be key=value, got {pair!r}") + key, value = pair.split("=", 1) + meta[key.strip()] = value.strip() + return meta + + +def _cmd_seal(args) -> int: + directory = Path(args.directory) + manifest_path = Path(args.out) if args.out else _default_manifest_path(directory) + + previous = None + if args.prev: + previous = load_manifest(args.prev).get("id") + + try: + manifest = build_manifest( + directory, + metadata=_parse_meta(args.meta), + previous=previous, + ignore=args.ignore, + exclude=_manifest_exclude(directory, manifest_path), + ) + except (FileNotFoundError, ValueError) as exc: + print(f"error: {exc}", file=sys.stderr) + return USAGE + + if args.sign: + from .signing import sign_manifest + + try: + manifest = sign_manifest(manifest, args.sign) + except (RuntimeError, OSError) as exc: + print(f"error: {exc}", file=sys.stderr) + return USAGE + + write_manifest(manifest, manifest_path) + signed = " (signed)" if "signature" in manifest else "" + print(f"sealed {manifest['file_count']} files{signed}", file=sys.stderr) + print(f" root {manifest['root']}", file=sys.stderr) + print(f" id {manifest['id']}", file=sys.stderr) + print(f" -> {manifest_path}", file=sys.stderr) + return OK + + +def _cmd_verify(args) -> int: + directory = Path(args.directory) + manifest_path = Path(args.manifest) if args.manifest else _default_manifest_path(directory) + try: + manifest = load_manifest(manifest_path) + except (FileNotFoundError, ValueError) as exc: + print(f"error: cannot read manifest: {exc}", file=sys.stderr) + return USAGE + + result = verify_manifest( + directory, + manifest, + ignore=manifest.get("ignore"), + exclude=_manifest_exclude(directory, manifest_path), + ) + + for path in result.modified: + print(f" MODIFIED {path}") + for path in result.added: + print(f" ADDED {path}") + for path in result.removed: + print(f" REMOVED {path}") + if not result.id_ok: + print(" MANIFEST id does not re-derive — the manifest itself was altered") + if not result.root_ok: + print(" MANIFEST Merkle root does not match the file list") + + status = OK + if not result.intact: + status = FAILED + + # Verify a signature when present, or when the caller supplied a key to trust. + if manifest.get("signature") or args.pubkey: + sig_ok = _verify_sig_cli(manifest, args.pubkey) + if not sig_ok: + status = FAILED + + if status == OK: + print(f"intact — {result.checked} files match the seal") + else: + print("TAMPERED — the directory does not match its seal", file=sys.stderr) + return status + + +def _verify_sig_cli(manifest: dict, pubkey_path: str | None) -> bool: + from .signing import load_public_hex, verify_signature + + expected = load_public_hex(pubkey_path) if pubkey_path else None + ok, message = verify_signature(manifest, expected) + print(f" signature {'OK' if ok else 'FAIL'}: {message}") + return ok + + +def _cmd_chain(args) -> int: + try: + manifests = [load_manifest(p) for p in args.manifests] + except (FileNotFoundError, ValueError) as exc: + print(f"error: cannot read manifest: {exc}", file=sys.stderr) + return USAGE + + result = verify_chain(manifests) + if result.ok: + print(f"chain intact — {result.length} seals link correctly") + return OK + where = "" if result.broken_at is None else f" at position {result.broken_at}" + print(f"CHAIN BROKEN{where}: {result.reason}", file=sys.stderr) + return FAILED + + +def _cmd_keygen(args) -> int: + from .signing import generate_keypair + + try: + generate_keypair(args.private, args.public) + except (RuntimeError, OSError) as exc: + print(f"error: {exc}", file=sys.stderr) + return USAGE + print(f"wrote private key {args.private}", file=sys.stderr) + print(f"wrote public key {args.public}", file=sys.stderr) + return OK + + +def _cmd_sign(args) -> int: + from .signing import sign_manifest + + try: + manifest = load_manifest(args.manifest) + signed = sign_manifest(manifest, args.key) + except (RuntimeError, FileNotFoundError, ValueError, OSError) as exc: + print(f"error: {exc}", file=sys.stderr) + return USAGE + write_manifest(signed, args.out or args.manifest) + print(f"signed {args.out or args.manifest}", file=sys.stderr) + return OK + + +def _build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="evidence-seal", + description="Tamper-evident seals for audit evidence packages.", + ) + parser.add_argument("--version", action="version", version=f"evidence-seal {__version__}") + sub = parser.add_subparsers(dest="command", required=True) + + p_seal = sub.add_parser("seal", help="seal a directory into a manifest") + p_seal.add_argument("directory") + p_seal.add_argument("--out", help="manifest path (default: <dir>.manifest.json alongside)") + p_seal.add_argument("--prev", help="prior manifest to chain from (records its id as previous)") + p_seal.add_argument("--meta", action="append", metavar="KEY=VALUE", help="provenance metadata") + p_seal.add_argument("--ignore", action="append", metavar="GLOB", help="skip matching paths") + p_seal.add_argument("--sign", metavar="PRIVATE_KEY", help="also sign with an ed25519 key") + p_seal.set_defaults(func=_cmd_seal) + + p_verify = sub.add_parser("verify", help="verify a directory against its manifest") + p_verify.add_argument("directory") + p_verify.add_argument("--manifest", help="manifest path (default: <dir>.manifest.json)") + p_verify.add_argument("--pubkey", metavar="PEM", help="require a signature by this public key") + p_verify.set_defaults(func=_cmd_verify) + + p_chain = sub.add_parser("chain", help="verify manifests link oldest -> newest") + p_chain.add_argument("manifests", nargs="+", help="manifest files, oldest first") + p_chain.set_defaults(func=_cmd_chain) + + p_keygen = sub.add_parser("keygen", help="generate an ed25519 keypair") + p_keygen.add_argument("--private", default="evidence-seal.key") + p_keygen.add_argument("--public", default="evidence-seal.pub") + p_keygen.set_defaults(func=_cmd_keygen) + + p_sign = sub.add_parser("sign", help="sign an existing manifest") + p_sign.add_argument("manifest") + p_sign.add_argument("--key", required=True, metavar="PRIVATE_KEY") + p_sign.add_argument("--out", help="write here instead of overwriting the manifest") + p_sign.set_defaults(func=_cmd_sign) + + return parser + + +def main(argv: list[str] | None = None) -> int: + parser = _build_parser() + args = parser.parse_args(argv if argv is not None else sys.argv[1:]) + return args.func(args) + + +if __name__ == "__main__": + raise SystemExit(main()) new file mode 100644 @@ -0,0 +1,54 @@ +"""File hashing and a Merkle root over a set of files. + +The Merkle root condenses a whole package into one hash. Two packages with the +same root are byte-identical in content and layout; any change to any file — or +to the set of files — changes the root. +""" + +from __future__ import annotations + +import hashlib +from pathlib import Path + +_CHUNK = 1 << 20 # 1 MiB streaming reads keep memory flat on large evidence + + +def hash_file(path: str | Path) -> str: + """Return the SHA-256 hex digest of a file, read in streaming chunks.""" + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for chunk in iter(lambda: handle.read(_CHUNK), b""): + digest.update(chunk) + return digest.hexdigest() + + +def hash_bytes(data: bytes) -> str: + """Return the SHA-256 hex digest of a bytes object.""" + return hashlib.sha256(data).hexdigest() + + +def _leaf(path: str, file_hash: str) -> str: + # Bind the path into the leaf so renaming a file changes the root even when + # its contents are unchanged. A domain prefix separates leaves from nodes. + return hashlib.sha256(f"leaf:{path}\x00{file_hash}".encode()).hexdigest() + + +def _pair(left: str, right: str) -> str: + return hashlib.sha256(f"node:{left}{right}".encode()).hexdigest() + + +def merkle_root(entries: dict[str, str]) -> str: + """Compute a Merkle root from a ``{path: file_hash}`` mapping. + + Leaves are ordered by path so the root is deterministic regardless of + filesystem iteration order. An empty package has a well-defined empty root. + """ + if not entries: + return hashlib.sha256(b"empty").hexdigest() + + level = [_leaf(path, file_hash) for path, file_hash in sorted(entries.items())] + while len(level) > 1: + if len(level) % 2: + level.append(level[-1]) # duplicate the last node on an odd level + level = [_pair(level[i], level[i + 1]) for i in range(0, len(level), 2)] + return level[0] new file mode 100644 @@ -0,0 +1,191 @@ +"""Build, load, and verify evidence manifests, and verify seal chains. + +A manifest is a JSON object describing a sealed directory: every file's SHA-256, +a Merkle ``root`` over them, provenance metadata, and a ``previous`` link to an +earlier manifest's id. Its own ``id`` is the SHA-256 of its canonical form +(excluding ``id`` and ``signature``), so the manifest is self-verifying and can +be chained. +""" + +from __future__ import annotations + +import fnmatch +import json +from dataclasses import dataclass, field +from datetime import datetime, timezone +from pathlib import Path + +from . import ALGORITHM, MANIFEST_VERSION, __version__ +from .hashing import hash_bytes, hash_file, merkle_root + +# Keys excluded from the canonical bytes the id is computed over. The id cannot +# cover itself, and a signature is applied *to* the id afterwards. +_ID_EXCLUDED = ("id", "signature") + + +def iter_files( + directory: Path, ignore: list[str] | None, exclude: set[str] +) -> list[tuple[str, Path]]: + """Return ``(posix_relpath, abspath)`` for every file under *directory*. + + Paths matching an *ignore* glob (against the relative path) or present in + *exclude* are skipped. Results are sorted by relative path. + """ + ignore = ignore or [] + out: list[tuple[str, Path]] = [] + for path in directory.rglob("*"): + if not path.is_file(): + continue + rel = path.relative_to(directory).as_posix() + if rel in exclude or any(fnmatch.fnmatch(rel, pat) for pat in ignore): + continue + out.append((rel, path)) + out.sort(key=lambda pair: pair[0]) + return out + + +def canonical_bytes(manifest: dict, exclude: tuple[str, ...] = _ID_EXCLUDED) -> bytes: + """Serialize a manifest deterministically for hashing or signing.""" + trimmed = {k: v for k, v in manifest.items() if k not in exclude} + return json.dumps(trimmed, sort_keys=True, separators=(",", ":")).encode() + + +def compute_id(manifest: dict) -> str: + """The manifest's self-id: SHA-256 of its canonical form.""" + return hash_bytes(canonical_bytes(manifest)) + + +def build_manifest( + directory: str | Path, + metadata: dict | None = None, + previous: str | None = None, + ignore: list[str] | None = None, + exclude: set[str] | None = None, +) -> dict: + """Seal *directory* into a manifest dict (id included, unsigned).""" + directory = Path(directory) + if not directory.is_dir(): + raise FileNotFoundError(f"not a directory: {directory}") + + files = iter_files(directory, ignore, exclude or set()) + entries = [ + {"path": rel, ALGORITHM: hash_file(abs_path), "bytes": abs_path.stat().st_size} + for rel, abs_path in files + ] + hashes = {entry["path"]: entry[ALGORITHM] for entry in entries} + + manifest = { + "manifest_version": MANIFEST_VERSION, + "algorithm": ALGORITHM, + "tool": f"evidence-seal/{__version__}", + "created_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + "subject": directory.name, + "previous": previous, + "metadata": dict(sorted((metadata or {}).items())), + "ignore": sorted(ignore or []), + "file_count": len(entries), + "total_bytes": sum(entry["bytes"] for entry in entries), + "root": merkle_root(hashes), + "files": entries, + } + manifest["id"] = compute_id(manifest) + return manifest + + +def write_manifest(manifest: dict, path: str | Path) -> None: + """Write a manifest as pretty JSON (stable key order).""" + Path(path).write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8") + + +def load_manifest(path: str | Path) -> dict: + """Load a manifest JSON file.""" + return json.loads(Path(path).read_text(encoding="utf-8")) + + +@dataclass +class VerifyResult: + """The outcome of verifying a directory against its manifest.""" + + modified: list[str] = field(default_factory=list) + added: list[str] = field(default_factory=list) + removed: list[str] = field(default_factory=list) + id_ok: bool = True + root_ok: bool = True + checked: int = 0 + + @property + def intact(self) -> bool: + """True only if nothing drifted and the manifest is internally sound.""" + return ( + not self.modified + and not self.added + and not self.removed + and self.id_ok + and self.root_ok + ) + + +def verify_manifest( + directory: str | Path, + manifest: dict, + ignore: list[str] | None = None, + exclude: set[str] | None = None, +) -> VerifyResult: + """Compare the current contents of *directory* against *manifest*.""" + directory = Path(directory) + recorded = {entry["path"]: entry[ALGORITHM] for entry in manifest.get("files", [])} + + result = VerifyResult() + # The manifest is only trustworthy if its id and root re-derive. + result.id_ok = compute_id(manifest) == manifest.get("id") + result.root_ok = merkle_root(recorded) == manifest.get("root") + + present: dict[str, str] = {} + for rel, abs_path in iter_files(directory, ignore, exclude or set()): + present[rel] = hash_file(abs_path) + + result.checked = len(present) + for rel, digest in present.items(): + if rel not in recorded: + result.added.append(rel) + elif recorded[rel] != digest: + result.modified.append(rel) + result.removed = [rel for rel in recorded if rel not in present] + + for bucket in (result.modified, result.added, result.removed): + bucket.sort() + return result + + +@dataclass +class ChainResult: + """The outcome of verifying a sequence of chained manifests.""" + + ok: bool + length: int + broken_at: int | None = None # index whose `previous` did not match + reason: str = "" + + +def verify_chain(manifests: list[dict]) -> ChainResult: + """Verify manifests link oldest→newest via ``previous`` == prior ``id``. + + Also checks that each manifest's own id re-derives, so a tampered link in + the middle is caught whether the break is in the pointer or the content. + """ + if not manifests: + return ChainResult(ok=False, length=0, reason="no manifests given") + + for index, manifest in enumerate(manifests): + if compute_id(manifest) != manifest.get("id"): + return ChainResult(False, len(manifests), index, "manifest id does not re-derive") + expected_prev = manifests[index - 1]["id"] if index else None + if manifest.get("previous") != expected_prev: + reason = ( + "first manifest should have no previous" + if index == 0 + else "previous does not match the prior manifest id" + ) + return ChainResult(False, len(manifests), index, reason) + + return ChainResult(ok=True, length=len(manifests)) new file mode 100644 @@ -0,0 +1,113 @@ +"""Optional ed25519 signing of manifests. + +Signing adds attribution — *who* sealed the evidence — on top of the integrity +the hashes already provide. It requires the ``cryptography`` package (install +``evidence-seal[sign]``); the core seal/verify path never imports this module. + +The signature covers the manifest's canonical bytes (the same bytes its id is +derived from), so a valid signature vouches for every file hash and all +metadata at once. +""" + +from __future__ import annotations + +from datetime import datetime, timezone +from pathlib import Path + +from .manifest import canonical_bytes + + +def _require_crypto(): + try: + from cryptography.hazmat.primitives.asymmetric import ed25519 + except ImportError as exc: # pragma: no cover - exercised via a clear message + raise RuntimeError( + "signing requires the 'cryptography' package — install evidence-seal[sign]" + ) from exc + return ed25519 + + +def generate_keypair(private_path: str | Path, public_path: str | Path) -> None: + """Write a new ed25519 keypair as PEM files (private key is unencrypted).""" + ed25519 = _require_crypto() + from cryptography.hazmat.primitives import serialization + + private = ed25519.Ed25519PrivateKey.generate() + Path(private_path).write_bytes( + private.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.NoEncryption(), + ) + ) + Path(public_path).write_bytes( + private.public_key().public_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PublicFormat.SubjectPublicKeyInfo, + ) + ) + + +def _public_hex(public_key) -> str: + from cryptography.hazmat.primitives import serialization + + raw = public_key.public_bytes( + encoding=serialization.Encoding.Raw, + format=serialization.PublicFormat.Raw, + ) + return raw.hex() + + +def sign_manifest(manifest: dict, private_key_path: str | Path) -> dict: + """Return a copy of *manifest* with a ``signature`` block attached.""" + _require_crypto() + from cryptography.hazmat.primitives import serialization + + private = serialization.load_pem_private_key( + Path(private_key_path).read_bytes(), password=None + ) + signature = private.sign(canonical_bytes(manifest)) + signed = dict(manifest) + signed["signature"] = { + "algorithm": "ed25519", + "public_key": _public_hex(private.public_key()), + "value": signature.hex(), + "signed_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + } + return signed + + +def verify_signature(manifest: dict, expected_public_key: str | None = None) -> tuple[bool, str]: + """Verify a manifest's signature. + + Returns ``(ok, message)``. If *expected_public_key* (hex) is given, the + signer's key must also match it — otherwise a valid signature by *any* key + would pass, which proves integrity but not identity. + """ + ed25519 = _require_crypto() + + block = manifest.get("signature") + if not block: + return False, "manifest is not signed" + if block.get("algorithm") != "ed25519": + return False, f"unsupported signature algorithm: {block.get('algorithm')}" + + signer_key = block.get("public_key", "") + if expected_public_key and signer_key != expected_public_key: + return False, "signer key does not match the expected public key" + + try: + public = ed25519.Ed25519PublicKey.from_public_bytes(bytes.fromhex(signer_key)) + public.verify(bytes.fromhex(block["value"]), canonical_bytes(manifest)) + except Exception as exc: + return False, f"signature is invalid: {exc}" + return True, f"valid ed25519 signature by {signer_key[:16]}…" + + +def load_public_hex(public_key_path: str | Path) -> str: + """Load a PEM public key and return its raw hex form (for --pubkey checks).""" + _require_crypto() + from cryptography.hazmat.primitives import serialization + + public = serialization.load_pem_public_key(Path(public_key_path).read_bytes()) + return _public_hex(public) new file mode 100644 @@ -0,0 +1,28 @@ +[build-system] +requires = ["setuptools>=68"] +build-backend = "setuptools.build_meta" + +[project] +name = "evidence-seal" +version = "0.1.0" +description = "Tamper-evident seals and chain of custody for audit evidence packages." +readme = "README.md" +requires-python = ">=3.10" +license = { text = "GPL-3.0-or-later" } +authors = [{ name = "Audit Labs" }] +# The core seal/verify/chain path is pure standard library. +dependencies = [] + +[project.optional-dependencies] +sign = ["cryptography>=42.0"] +dev = ["pytest>=8.0", "ruff>=0.5", "cryptography>=42.0"] + +[project.scripts] +evidence-seal = "evidence_seal.cli:main" + +[project.urls] +Homepage = "https://audit-labs.dev" +Repository = "https://github.com/audit-labs/evidence-seal" + +[tool.setuptools] +packages = ["evidence_seal"] new file mode 100644 @@ -0,0 +1,3 @@ +pytest>=8.0 +ruff>=0.5 +cryptography>=42.0 new file mode 100644 @@ -0,0 +1,7 @@ +# Ruff configuration for evidence-seal. +# +# BLE001 is disabled because signature verification deliberately catches any +# exception and reports it as a failed verification rather than crashing — an +# invalid signature is a normal, expected outcome, not a program error. +[lint] +ignore = ["BLE001"] new file mode 100644 @@ -0,0 +1,74 @@ +"""End-to-end tests for the CLI, covering exit codes.""" + +import pytest + +from evidence_seal.cli import OK, USAGE, main + + +@pytest.fixture +def pkg(tmp_path): + d = tmp_path / "aws_audit_acme_2026-01-01" + d.mkdir() + (d / "iam.csv").write_text("user,mfa\nalice,true\n", encoding="utf-8") + return d + + +def test_seal_then_verify_intact(pkg, tmp_path): + manifest = tmp_path / "m.json" + assert main(["seal", str(pkg), "--out", str(manifest), "--meta", "engagement=ACME"]) == OK + assert manifest.exists() + assert main(["verify", str(pkg), "--manifest", str(manifest)]) == OK + + +def test_verify_fails_after_tamper(pkg, tmp_path): + manifest = tmp_path / "m.json" + main(["seal", str(pkg), "--out", str(manifest)]) + (pkg / "iam.csv").write_text("user,mfa\nalice,false\n", encoding="utf-8") + assert main(["verify", str(pkg), "--manifest", str(manifest)]) == 1 + + +def test_default_manifest_path(pkg): + # No --out: manifest lands next to the dir and verify finds it by default. + assert main(["seal", str(pkg)]) == OK + assert (pkg.parent / f"{pkg.name}.manifest.json").exists() + assert main(["verify", str(pkg)]) == OK + + +def test_manifest_inside_dir_is_not_self_sealed(pkg): + inside = pkg / "seal.json" + assert main(["seal", str(pkg), "--out", str(inside)]) == OK + # Verifying still passes even though the manifest now sits inside the dir. + assert main(["verify", str(pkg), "--manifest", str(inside)]) == OK + + +def test_chain_command(pkg, tmp_path): + m1, m2 = tmp_path / "m1.json", tmp_path / "m2.json" + main(["seal", str(pkg), "--out", str(m1)]) + (pkg / "iam.csv").write_text("user,mfa\nalice,true\nbob,true\n", encoding="utf-8") + main(["seal", str(pkg), "--out", str(m2), "--prev", str(m1)]) + assert main(["chain", str(m1), str(m2)]) == OK + assert main(["chain", str(m2), str(m1)]) == 1 + + +def test_bad_metadata_is_usage_error(pkg, tmp_path): + assert main(["seal", str(pkg), "--out", str(tmp_path / "m.json"), "--meta", "novalue"]) == USAGE + + +def test_sign_and_verify_via_cli(pkg, tmp_path): + pytest.importorskip("cryptography") + priv, pub = tmp_path / "k.key", tmp_path / "k.pub" + assert main(["keygen", "--private", str(priv), "--public", str(pub)]) == OK + manifest = tmp_path / "m.json" + assert main(["seal", str(pkg), "--out", str(manifest), "--sign", str(priv)]) == OK + assert main(["verify", str(pkg), "--manifest", str(manifest), "--pubkey", str(pub)]) == OK + + +def test_verify_rejects_wrong_signer(pkg, tmp_path): + pytest.importorskip("cryptography") + priv, pub = tmp_path / "k.key", tmp_path / "k.pub" + other_pub = tmp_path / "o.pub" + main(["keygen", "--private", str(priv), "--public", str(pub)]) + main(["keygen", "--private", str(tmp_path / "o.key"), "--public", str(other_pub)]) + manifest = tmp_path / "m.json" + main(["seal", str(pkg), "--out", str(manifest), "--sign", str(priv)]) + assert main(["verify", str(pkg), "--manifest", str(manifest), "--pubkey", str(other_pub)]) == 1 new file mode 100644 @@ -0,0 +1,39 @@ +"""Tests for file hashing and the Merkle root.""" + +from evidence_seal.hashing import hash_bytes, hash_file, merkle_root + + +def test_hash_file_matches_known_sha256(tmp_path): + f = tmp_path / "x.txt" + f.write_bytes(b"hello") + # Known SHA-256 of "hello". + assert hash_file(f) == "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824" + assert hash_bytes(b"hello") == hash_file(f) + + +def test_merkle_root_is_order_independent(): + a = {"a": "1", "b": "2", "c": "3"} + b = {"c": "3", "a": "1", "b": "2"} + assert merkle_root(a) == merkle_root(b) + + +def test_merkle_root_changes_on_content(): + base = {"a": "1", "b": "2"} + changed = {"a": "1", "b": "changed"} + assert merkle_root(base) != merkle_root(changed) + + +def test_merkle_root_changes_on_rename(): + # Same content hash, different path -> different root (path is bound in). + assert merkle_root({"a": "1"}) != merkle_root({"b": "1"}) + + +def test_empty_root_is_defined_and_distinct(): + assert merkle_root({}) == hash_bytes(b"empty") + assert merkle_root({}) != merkle_root({"a": "1"}) + + +def test_odd_number_of_leaves(): + # Three leaves exercises the duplicate-last branch; just needs to be stable. + entries = {"a": "1", "b": "2", "c": "3"} + assert merkle_root(entries) == merkle_root(dict(entries)) new file mode 100644 @@ -0,0 +1,102 @@ +"""Tests for building, verifying, and chaining manifests.""" + +import pytest + +from evidence_seal.manifest import ( + build_manifest, + compute_id, + verify_chain, + verify_manifest, +) + + +@pytest.fixture +def pkg(tmp_path): + d = tmp_path / "aws_audit_acme_2026-01-01" + d.mkdir() + (d / "iam.csv").write_text("user,mfa\nalice,true\n", encoding="utf-8") + (d / "summary.txt").write_text("ok\n", encoding="utf-8") + return d + + +def test_build_manifest_shape(pkg): + m = build_manifest(pkg, metadata={"engagement": "ACME"}) + assert m["subject"] == "aws_audit_acme_2026-01-01" + assert m["file_count"] == 2 + assert m["metadata"] == {"engagement": "ACME"} + assert [f["path"] for f in m["files"]] == ["iam.csv", "summary.txt"] + assert m["id"] == compute_id(m) + + +def test_verify_clean(pkg): + m = build_manifest(pkg) + result = verify_manifest(pkg, m) + assert result.intact + assert result.checked == 2 + + +def test_verify_detects_modification(pkg): + m = build_manifest(pkg) + (pkg / "iam.csv").write_text("user,mfa\nalice,false\n", encoding="utf-8") + result = verify_manifest(pkg, m) + assert not result.intact + assert result.modified == ["iam.csv"] + + +def test_verify_detects_added_and_removed(pkg): + m = build_manifest(pkg) + (pkg / "extra.csv").write_text("new\n", encoding="utf-8") + (pkg / "summary.txt").unlink() + result = verify_manifest(pkg, m) + assert result.added == ["extra.csv"] + assert result.removed == ["summary.txt"] + assert not result.intact + + +def test_verify_detects_manifest_tampering(pkg): + m = build_manifest(pkg) + # Rewrite a recorded hash but leave the (now stale) id in place. + m["files"][0]["sha256"] = "0" * 64 + result = verify_manifest(pkg, m) + assert not result.id_ok + assert not result.root_ok + assert not result.intact + + +def test_ignore_patterns_excluded_and_recorded(pkg): + (pkg / "notes.tmp").write_text("scratch\n", encoding="utf-8") + m = build_manifest(pkg, ignore=["*.tmp"]) + assert m["ignore"] == ["*.tmp"] + assert all(not f["path"].endswith(".tmp") for f in m["files"]) + # Verify with the same ignore keeps it intact despite the tmp file present. + assert verify_manifest(pkg, m, ignore=m["ignore"]).intact + + +def test_chain_links(pkg): + m1 = build_manifest(pkg) + (pkg / "iam.csv").write_text("user,mfa\nalice,true\nbob,true\n", encoding="utf-8") + m2 = build_manifest(pkg, previous=m1["id"]) + assert verify_chain([m1, m2]).ok + + +def test_chain_detects_wrong_order(pkg): + m1 = build_manifest(pkg) + m2 = build_manifest(pkg, previous=m1["id"]) + result = verify_chain([m2, m1]) + assert not result.ok + assert result.broken_at == 0 + + +def test_chain_detects_spliced_entry(pkg): + m1 = build_manifest(pkg) + m2 = build_manifest(pkg, previous=m1["id"]) + m3 = build_manifest(pkg, previous=m2["id"]) + # Drop the middle manifest: m3.previous no longer matches m1.id. + result = verify_chain([m1, m3]) + assert not result.ok + assert result.broken_at == 1 + + +def test_missing_directory_raises(tmp_path): + with pytest.raises(FileNotFoundError): + build_manifest(tmp_path / "nope") new file mode 100644 @@ -0,0 +1,63 @@ +"""Tests for optional ed25519 signing (skipped if cryptography is absent).""" + +import pytest + +pytest.importorskip("cryptography") + +from evidence_seal.manifest import build_manifest +from evidence_seal.signing import ( + generate_keypair, + load_public_hex, + sign_manifest, + verify_signature, +) + + +@pytest.fixture +def sealed(tmp_path): + d = tmp_path / "pkg" + d.mkdir() + (d / "a.csv").write_text("x\n", encoding="utf-8") + return build_manifest(d) + + +@pytest.fixture +def keys(tmp_path): + priv, pub = tmp_path / "k.key", tmp_path / "k.pub" + generate_keypair(priv, pub) + return priv, pub + + +def test_sign_then_verify(sealed, keys): + priv, pub = keys + signed = sign_manifest(sealed, priv) + ok, _ = verify_signature(signed) + assert ok + # And the embedded key matches the PEM public key. + ok_matched, _ = verify_signature(signed, load_public_hex(pub)) + assert ok_matched + + +def test_unsigned_manifest_reports_clearly(sealed): + ok, message = verify_signature(sealed) + assert not ok + assert "not signed" in message + + +def test_tampered_manifest_fails_signature(sealed, keys): + priv, _ = keys + signed = sign_manifest(sealed, priv) + # Alter a hash after signing; the signature no longer covers it. + signed["files"][0]["sha256"] = "0" * 64 + ok, _ = verify_signature(signed) + assert not ok + + +def test_wrong_expected_key_rejected(sealed, tmp_path, keys): + priv, _ = keys + signed = sign_manifest(sealed, priv) + other_priv, other_pub = tmp_path / "o.key", tmp_path / "o.pub" + generate_keypair(other_priv, other_pub) + ok, message = verify_signature(signed, load_public_hex(other_pub)) + assert not ok + assert "does not match" in message