pax_global_header00006660000000000000000000000064125324736200014516gustar00rootroot0000000000000052 comment=bc7e55b68f6a43a9cf9e99081f860ce428835ec3 git-crypt-0.5.0/000077500000000000000000000000001253247362000134425ustar00rootroot00000000000000git-crypt-0.5.0/AUTHORS000066400000000000000000000000431253247362000145070ustar00rootroot00000000000000Andrew Ayer git-crypt-0.5.0/CONTRIBUTING.md000066400000000000000000000021651253247362000156770ustar00rootroot00000000000000Thanks for your interest in contributing to git-crypt! git-crypt is open source software and welcomes contributions in the form of code, documentation, bug reports, or anything else that improves git-crypt. When contributing code, please consider the following guidelines: * You are encouraged to open an issue on GitHub or send mail to git-crypt-discuss@lists.cloudmutt.com to discuss any non-trivial changes before you start coding. * Please mimic the existing code style as much as possible. In particular, please indent code using tab characters with a width of 8. * To minimize merge commits, please rebase your changes before opening a pull request. * To submit your patch, open a pull request on GitHub or send a properly-formatted patch to git-crypt-discuss@lists.cloudmutt.com. Finally, be aware that since git-crypt is security-sensitive software, the bar for contributions is higher than average. Please don't be discouraged by this, but be prepared for patches to possibly go through several rounds of feedback and improvement before being accepted. Your patience and understanding is appreciated. git-crypt-0.5.0/COPYING000066400000000000000000001045131253247362000145010ustar00rootroot00000000000000 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 . git-crypt-0.5.0/INSTALL000066400000000000000000000041401253247362000144720ustar00rootroot00000000000000DEPENDENCIES To build git-crypt, you need: Debian/Ubuntu package RHEL/CentOS package ----------------------------------------------------------------------------- Make make make A C++ compiler (e.g. gcc) g++ gcc-c++ OpenSSL development files libssl-dev openssl-devel To use git-crypt, you need: Debian/Ubuntu package RHEL/CentOS package ----------------------------------------------------------------------------- Git 1.7.2 or newer git git OpenSSL openssl openssl Note: Git 1.8.5 or newer is recommended for best performance. BUILDING GIT-CRYPT Run: $ make $ make install To install to a specific location: $ make install PREFIX=/usr/local Or, just copy the git-crypt binary to wherever is most convenient for you. BUILDING THE MAN PAGE To build and install the git-crypt(1) man page, pass ENABLE_MAN=yes to make: $ make ENABLE_MAN=yes $ make ENABLE_MAN=yes install xsltproc is required to build the man page. Note that xsltproc will access the Internet to retrieve its stylesheet unless the Docbook stylesheet is installed locally and registered in the system's XML catalog. BUILDING A DEBIAN PACKAGE Debian packaging can be found in the 'debian' branch of the project Git repository. The package is built using git-buildpackage as follows: $ git checkout debian $ git-buildpackage -uc -us INSTALLING ON MAC OS X Using the brew package manager, simply run: $ brew install git-crypt EXPERIMENTAL WINDOWS SUPPORT git-crypt should build on Windows with MinGW, although the build system is not yet finalized so you will need to pass your own CXX, CXXFLAGS, and LDFLAGS variables to make. Additionally, Windows support is less tested and does not currently create key files with restrictive permissions, making it unsuitable for use on a multi-user system. Windows support will mature in a future version of git-crypt. Bug reports and patches are most welcome! git-crypt-0.5.0/INSTALL.md000066400000000000000000000041371253247362000150770ustar00rootroot00000000000000### Dependencies To build git-crypt, you need: | Debian/Ubuntu package | RHEL/CentOS package ---------------------------|-----------------------|------------------------ Make | make | make A C++ compiler (e.g. gcc) | g++ | gcc-c++ OpenSSL development files | libssl-dev | openssl-devel To use git-crypt, you need: | Debian/Ubuntu package | RHEL/CentOS package ---------------------------|-----------------------|------------------------ Git 1.7.2 or newer | git | git OpenSSL | openssl | openssl Note: Git 1.8.5 or newer is recommended for best performance. ### Building git-crypt Run: make make install To install to a specific location: make install PREFIX=/usr/local Or, just copy the git-crypt binary to wherever is most convenient for you. ### Building The Man Page To build and install the git-crypt(1) man page, pass `ENABLE_MAN=yes` to make: make ENABLE_MAN=yes make ENABLE_MAN=yes install xsltproc is required to build the man page. Note that xsltproc will access the Internet to retrieve its stylesheet unless the Docbook stylesheet is installed locally and registered in the system's XML catalog. ### Building A Debian Package Debian packaging can be found in the 'debian' branch of the project Git repository. The package is built using git-buildpackage as follows: git checkout debian git-buildpackage -uc -us ### Installing On Mac OS X Using the brew package manager, simply run: brew install git-crypt ### Experimental Windows Support git-crypt should build on Windows with MinGW, although the build system is not yet finalized so you will need to pass your own CXX, CXXFLAGS, and LDFLAGS variables to make. Additionally, Windows support is less tested and does not currently create key files with restrictive permissions, making it unsuitable for use on a multi-user system. Windows support will mature in a future version of git-crypt. Bug reports and patches are most welcome! git-crypt-0.5.0/Makefile000066400000000000000000000036571253247362000151150ustar00rootroot00000000000000# # Copyright (c) 2015 Andrew Ayer # # See COPYING file for license information. # CXXFLAGS ?= -Wall -pedantic -Wno-long-long -O2 PREFIX ?= /usr/local BINDIR ?= $(PREFIX)/bin MANDIR ?= $(PREFIX)/share/man ENABLE_MAN ?= no DOCBOOK_XSL ?= http://docbook.sourceforge.net/release/xsl/current/manpages/docbook.xsl OBJFILES = \ git-crypt.o \ commands.o \ crypto.o \ gpg.o \ key.o \ util.o \ parse_options.o \ coprocess.o \ fhstream.o OBJFILES += crypto-openssl.o LDFLAGS += -lcrypto XSLTPROC ?= xsltproc DOCBOOK_FLAGS += --param man.output.in.separate.dir 1 \ --stringparam man.output.base.dir man/ \ --param man.output.subdirs.enabled 1 \ --param man.authors.section.enabled 1 all: build # # Build # BUILD_MAN_TARGETS-yes = build-man BUILD_MAN_TARGETS-no = BUILD_TARGETS := build-bin $(BUILD_MAN_TARGETS-$(ENABLE_MAN)) build: $(BUILD_TARGETS) build-bin: git-crypt git-crypt: $(OBJFILES) $(CXX) $(CXXFLAGS) -o $@ $(OBJFILES) $(LDFLAGS) util.o: util.cpp util-unix.cpp util-win32.cpp coprocess.o: coprocess.cpp coprocess-unix.cpp coprocess-win32.cpp build-man: man/man1/git-crypt.1 man/man1/git-crypt.1: man/git-crypt.xml $(XSLTPROC) $(DOCBOOK_FLAGS) $(DOCBOOK_XSL) $< # # Clean # CLEAN_MAN_TARGETS-yes = clean-man CLEAN_MAN_TARGETS-no = CLEAN_TARGETS := clean-bin $(CLEAN_MAN_TARGETS-$(ENABLE_MAN)) clean: $(CLEAN_TARGETS) clean-bin: rm -f $(OBJFILES) git-crypt clean-man: rm -f man/man1/git-crypt.1 # # Install # INSTALL_MAN_TARGETS-yes = install-man INSTALL_MAN_TARGETS-no = INSTALL_TARGETS := install-bin $(INSTALL_MAN_TARGETS-$(ENABLE_MAN)) install: $(INSTALL_TARGETS) install-bin: build-bin install -d $(DESTDIR)$(BINDIR) install -m 755 git-crypt $(DESTDIR)$(BINDIR)/ install-man: build-man install -d $(DESTDIR)$(MANDIR)/man1 install -m 644 man/man1/git-crypt.1 $(DESTDIR)$(MANDIR)/man1/ .PHONY: all \ build build-bin build-man \ clean clean-bin clean-man \ install install-bin install-man git-crypt-0.5.0/NEWS000066400000000000000000000051351253247362000141450ustar00rootroot00000000000000v0.5.0 (2015-05-30) * Drastically speed up lock/unlock when used with Git 1.8.5 or newer. * Add git-crypt(1) man page (pass ENABLE_MAN=yes to make to build). * Add --trusted option to 'git-crypt gpg-add-user' to add user even if GPG doesn't trust user's key. * Improve 'git-crypt lock' usability, add --force option. * Ignore symlinks and other non-files when running 'git-crypt status'. * Fix compilation on old versions of Mac OS X. * Fix GPG mode when with-fingerprint enabled in gpg.conf. * Minor bug fixes and improvements to help/error messages. v0.4.2 (2015-01-31) * Fix unlock and lock under Git 2.2.2 and higher. * Drop support for versions of Git older than 1.7.2. * Minor improvements to some help/error messages. v0.4.1 (2015-01-08) * Important usability fix to ensure that the .git-crypt directory can't be encrypted by accident (see RELEASE_NOTES-0.4.1.md for more information). v0.4 (2014-11-16) (See RELEASE_NOTES-0.4.md for important details.) * Add optional GPG support: GPG can be used to share the repository between one or more users in lieu of sharing a secret key. * New workflow: the symmetric key is now stored inside the .git directory. Although backwards compatibility has been preserved with repositories created by old versions of git-crypt, the commands for setting up a repository have changed. See the release notes file for details. * Multiple key support: it's now possible to encrypt different parts of a repository with different keys. * Initial 'git-crypt status' command to report which files are encrypted and to fix problems that are detected. * Numerous usability, documentation, and error reporting improvements. * Major internal code improvements that will make future development easier. * Initial experimental Windows support. v0.3 (2013-04-05) * Fix 'git-crypt init' on newer versions of Git. Previously, encrypted files were not being automatically decrypted after running 'git-crypt init' with recent versions of Git. * Allow 'git-crypt init' to be run even if the working tree contains untracked files. * 'git-crypt init' now properly escapes arguments to the filter commands it configures, allowing both the path to git-crypt and the path to the key file to contain arbitrary characters such as spaces. v0.2 (2013-01-25) * Numerous improvements to 'git-crypt init' usability. * Fix gitattributes example in README: the old example showed a colon after the filename where there shouldn't be one. * Various build fixes and improvements. v0.1 (2012-11-29) * Initial release. git-crypt-0.5.0/NEWS.md000066400000000000000000000052531253247362000145450ustar00rootroot00000000000000News ==== ######v0.5.0 (2015-05-30) * Drastically speed up lock/unlock when used with Git 1.8.5 or newer. * Add git-crypt(1) man page (pass `ENABLE_MAN=yes` to make to build). * Add --trusted option to `git-crypt gpg-add-user` to add user even if GPG doesn't trust user's key. * Improve `git-crypt lock` usability, add --force option. * Ignore symlinks and other non-files when running `git-crypt status`. * Fix compilation on old versions of Mac OS X. * Fix GPG mode when with-fingerprint enabled in gpg.conf. * Minor bug fixes and improvements to help/error messages. ######v0.4.2 (2015-01-31) * Fix unlock and lock under Git 2.2.2 and higher. * Drop support for versions of Git older than 1.7.2. * Minor improvements to some help/error messages. ######v0.4.1 (2015-01-08) * Important usability fix to ensure that the .git-crypt directory can't be encrypted by accident (see [the release notes](RELEASE_NOTES-0.4.1.md) for more information). ######v0.4 (2014-11-16) (See [the release notes](RELEASE_NOTES-0.4.md) for important details.) * Add optional GPG support: GPG can be used to share the repository between one or more users in lieu of sharing a secret key. * New workflow: the symmetric key is now stored inside the .git directory. Although backwards compatibility has been preserved with repositories created by old versions of git-crypt, the commands for setting up a repository have changed. See the release notes file for details. * Multiple key support: it's now possible to encrypt different parts of a repository with different keys. * Initial `git-crypt status` command to report which files are encrypted and to fix problems that are detected. * Numerous usability, documentation, and error reporting improvements. * Major internal code improvements that will make future development easier. * Initial experimental Windows support. ######v0.3 (2013-04-05) * Fix `git-crypt init` on newer versions of Git. Previously, encrypted files were not being automatically decrypted after running `git-crypt init` with recent versions of Git. * Allow `git-crypt init` to be run even if the working tree contains untracked files. * `git-crypt init` now properly escapes arguments to the filter commands it configures, allowing both the path to git-crypt and the path to the key file to contain arbitrary characters such as spaces. ######v0.2 (2013-01-25) * Numerous improvements to `git-crypt init` usability. * Fix gitattributes example in [README](README.md): the old example showed a colon after the filename where there shouldn't be one. * Various build fixes and improvements. ######v0.1 (2012-11-29) * Initial release. git-crypt-0.5.0/README000066400000000000000000000141351253247362000143260ustar00rootroot00000000000000ABOUT GIT-CRYPT git-crypt enables transparent encryption and decryption of files in a git repository. Files which you choose to protect are encrypted when committed, and decrypted when checked out. git-crypt lets you freely share a repository containing a mix of public and private content. git-crypt gracefully degrades, so developers without the secret key can still clone and commit to a repository with encrypted files. This lets you store your secret material (such as keys or passwords) in the same repository as your code, without requiring you to lock down your entire repository. git-crypt was written by Andrew Ayer . For more information, see . BUILDING GIT-CRYPT See the INSTALL file. USING GIT-CRYPT Configure a repository to use git-crypt: $ cd repo $ git-crypt init Specify files to encrypt by creating a .gitattributes file: secretfile filter=git-crypt diff=git-crypt *.key filter=git-crypt diff=git-crypt Like a .gitignore file, it can match wildcards and should be checked into the repository. See below for more information about .gitattributes. Make sure you don't accidentally encrypt the .gitattributes file itself (or other git files like .gitignore or .gitmodules). Make sure your .gitattributes rules are in place *before* you add sensitive files, or those files won't be encrypted! Share the repository with others (or with yourself) using GPG: $ git-crypt add-gpg-user USER_ID USER_ID can be a key ID, a full fingerprint, an email address, or anything else that uniquely identifies a public key to GPG (see "HOW TO SPECIFY A USER ID" in the gpg man page). Note: `git-crypt add-gpg-user` will add and commit a GPG-encrypted key file in the .git-crypt directory of the root of your repository. Alternatively, you can export a symmetric secret key, which you must securely convey to collaborators (GPG is not required, and no files are added to your repository): $ git-crypt export-key /path/to/key After cloning a repository with encrypted files, unlock with with GPG: $ git-crypt unlock Or with a symmetric key: $ git-crypt unlock /path/to/key That's all you need to do - after git-crypt is set up (either with `git-crypt init` or `git-crypt unlock`), you can use git normally - encryption and decryption happen transparently. CURRENT STATUS The latest version of git-crypt is 0.5.0, released on 2015-05-30. git-crypt aims to be bug-free and reliable, meaning it shouldn't crash, malfunction, or expose your confidential data. However, it has not yet reached maturity, meaning it is not as documented, featureful, or easy-to-use as it should be. Additionally, there may be backwards-incompatible changes introduced before version 1.0. SECURITY git-crypt is more secure that other transparent git encryption systems. git-crypt encrypts files using AES-256 in CTR mode with a synthetic IV derived from the SHA-1 HMAC of the file. This mode of operation is provably semantically secure under deterministic chosen-plaintext attack. That means that although the encryption is deterministic (which is required so git can distinguish when a file has and hasn't changed), it leaks no information beyond whether two files are identical or not. Other proposals for transparent git encryption use ECB or CBC with a fixed IV. These systems are not semantically secure and leak information. LIMITATIONS git-crypt relies on git filters, which were not designed with encryption in mind. As such, git-crypt is not the best tool for encrypting most or all of the files in a repository. Where git-crypt really shines is where most of your repository is public, but you have a few files (perhaps private keys named *.key, or a file with API credentials) which you need to encrypt. For encrypting an entire repository, consider using a system like git-remote-gcrypt instead. (Note: no endorsement is made of git-remote-gcrypt's security.) git-crypt does not encrypt file names, commit messages, symlink targets, gitlinks, or other metadata. git-crypt does not hide when a file does or doesn't change, the length of a file, or the fact that two files are identical (see "Security" section above). Files encrypted with git-crypt are not compressible. Even the smallest change to an encrypted file requires git to store the entire changed file, instead of just a delta. Although git-crypt protects individual file contents with a SHA-1 HMAC, git-crypt cannot be used securely unless the entire repository is protected against tampering (an attacker who can mutate your repository can alter your .gitattributes file to disable encryption). If necessary, use git features such as signed tags instead of relying solely on git-crypt for integrity. Files encrypted with git-crypt cannot be patched with git-apply, unless the patch itself is encrypted. To generate an encrypted patch, use `git diff --no-textconv --binary`. Alternatively, you can apply a plaintext patch outside of git using the patch command. git-crypt does not work reliably with some third-party git GUIs, such as Atlassian SourceTree and GitHub for Mac. Files might be left in an unencrypted state. GITATTRIBUTES FILE The .gitattributes file is documented in the gitattributes(5) man page. The file pattern format is the same as the one used by .gitignore, as documented in the gitignore(5) man page, with the exception that specifying merely a directory (e.g. `/dir/`) is NOT sufficient to encrypt all files beneath it. Also note that the pattern `dir/*` does not match files under sub-directories of dir/. To encrypt an entire sub-tree dir/, place the following in dir/.gitattributes: * filter=git-crypt diff=git-crypt .gitattributes !filter !diff The second pattern is essential for ensuring that .gitattributes itself is not encrypted. MAILING LISTS To stay abreast of, and provide input to, git-crypt development, consider subscribing to one or both of our mailing lists: Announcements: https://lists.cloudmutt.com/mailman/listinfo/git-crypt-announce Discussion: https://lists.cloudmutt.com/mailman/listinfo/git-crypt-discuss git-crypt-0.5.0/README.md000066400000000000000000000145351253247362000147310ustar00rootroot00000000000000git-crypt - transparent file encryption in git ============================================== git-crypt enables transparent encryption and decryption of files in a git repository. Files which you choose to protect are encrypted when committed, and decrypted when checked out. git-crypt lets you freely share a repository containing a mix of public and private content. git-crypt gracefully degrades, so developers without the secret key can still clone and commit to a repository with encrypted files. This lets you store your secret material (such as keys or passwords) in the same repository as your code, without requiring you to lock down your entire repository. git-crypt was written by [Andrew Ayer](https://www.agwa.name) (agwa@andrewayer.name). For more information, see . Building git-crypt ------------------ See the [INSTALL.md](INSTALL.md) file. Using git-crypt --------------- Configure a repository to use git-crypt: cd repo git-crypt init Specify files to encrypt by creating a .gitattributes file: secretfile filter=git-crypt diff=git-crypt *.key filter=git-crypt diff=git-crypt Like a .gitignore file, it can match wildcards and should be checked into the repository. See below for more information about .gitattributes. Make sure you don't accidentally encrypt the .gitattributes file itself (or other git files like .gitignore or .gitmodules). Make sure your .gitattributes rules are in place *before* you add sensitive files, or those files won't be encrypted! Share the repository with others (or with yourself) using GPG: git-crypt add-gpg-user USER_ID `USER_ID` can be a key ID, a full fingerprint, an email address, or anything else that uniquely identifies a public key to GPG (see "HOW TO SPECIFY A USER ID" in the gpg man page). Note: `git-crypt add-gpg-user` will add and commit a GPG-encrypted key file in the .git-crypt directory of the root of your repository. Alternatively, you can export a symmetric secret key, which you must securely convey to collaborators (GPG is not required, and no files are added to your repository): git-crypt export-key /path/to/key After cloning a repository with encrypted files, unlock with with GPG: git-crypt unlock Or with a symmetric key: git-crypt unlock /path/to/key That's all you need to do - after git-crypt is set up (either with `git-crypt init` or `git-crypt unlock`), you can use git normally - encryption and decryption happen transparently. Current Status -------------- The latest version of git-crypt is [0.5.0](NEWS.md), released on 2015-05-30. git-crypt aims to be bug-free and reliable, meaning it shouldn't crash, malfunction, or expose your confidential data. However, it has not yet reached maturity, meaning it is not as documented, featureful, or easy-to-use as it should be. Additionally, there may be backwards-incompatible changes introduced before version 1.0. Security -------- git-crypt is more secure that other transparent git encryption systems. git-crypt encrypts files using AES-256 in CTR mode with a synthetic IV derived from the SHA-1 HMAC of the file. This mode of operation is provably semantically secure under deterministic chosen-plaintext attack. That means that although the encryption is deterministic (which is required so git can distinguish when a file has and hasn't changed), it leaks no information beyond whether two files are identical or not. Other proposals for transparent git encryption use ECB or CBC with a fixed IV. These systems are not semantically secure and leak information. Limitations ----------- git-crypt relies on git filters, which were not designed with encryption in mind. As such, git-crypt is not the best tool for encrypting most or all of the files in a repository. Where git-crypt really shines is where most of your repository is public, but you have a few files (perhaps private keys named *.key, or a file with API credentials) which you need to encrypt. For encrypting an entire repository, consider using a system like [git-remote-gcrypt](https://github.com/joeyh/git-remote-gcrypt) instead. (Note: no endorsement is made of git-remote-gcrypt's security.) git-crypt does not encrypt file names, commit messages, symlink targets, gitlinks, or other metadata. git-crypt does not hide when a file does or doesn't change, the length of a file, or the fact that two files are identical (see "Security" section above). Files encrypted with git-crypt are not compressible. Even the smallest change to an encrypted file requires git to store the entire changed file, instead of just a delta. Although git-crypt protects individual file contents with a SHA-1 HMAC, git-crypt cannot be used securely unless the entire repository is protected against tampering (an attacker who can mutate your repository can alter your .gitattributes file to disable encryption). If necessary, use git features such as signed tags instead of relying solely on git-crypt for integrity. Files encrypted with git-crypt cannot be patched with git-apply, unless the patch itself is encrypted. To generate an encrypted patch, use `git diff --no-textconv --binary`. Alternatively, you can apply a plaintext patch outside of git using the patch command. git-crypt does not work reliably with some third-party git GUIs, such as [Atlassian SourceTree](https://jira.atlassian.com/browse/SRCTREE-2511) and GitHub for Mac. Files might be left in an unencrypted state. Gitattributes File ------------------ The .gitattributes file is documented in the gitattributes(5) man page. The file pattern format is the same as the one used by .gitignore, as documented in the gitignore(5) man page, with the exception that specifying merely a directory (e.g. `/dir/`) is *not* sufficient to encrypt all files beneath it. Also note that the pattern `dir/*` does not match files under sub-directories of dir/. To encrypt an entire sub-tree dir/, place the following in dir/.gitattributes: * filter=git-crypt diff=git-crypt .gitattributes !filter !diff The second pattern is essential for ensuring that .gitattributes itself is not encrypted. Mailing Lists ------------- To stay abreast of, and provide input to, git-crypt development, consider subscribing to one or both of our mailing lists: * [Announcements](https://lists.cloudmutt.com/mailman/listinfo/git-crypt-announce) * [Discussion](https://lists.cloudmutt.com/mailman/listinfo/git-crypt-discuss) git-crypt-0.5.0/RELEASE_NOTES-0.4.1.md000066400000000000000000000020201253247362000164440ustar00rootroot00000000000000git-crypt 0.4.1 is a bugfix-only release that contains an important usability fix for users who use GPG mode to encrypt an entire repository. Previously, if you used a '*' pattern in the top-level .gitattributes file, and you did not explicitly add a pattern to exclude the .git-crypt directory, the files contained therein would be encrypted, rendering the repository impossible to unlock with GPG. git-crypt now adds a .gitattributes file to the .git-crypt directory to prevent its contents from being encrypted, regardless of patterns in the top-level .gitattributes. If you are using git-crypt in GPG mode to encrypt an entire repository, and you do not already have a .gitattributes pattern to exclude the .git-crypt directory, you are strongly advised to upgrade. After upgrading, you should do the following in each of your repositories to ensure that the information inside .git-crypt is properly stored: 1. Remove existing key files: `rm .git-crypt/keys/*/0/*` 2. Re-add GPG user(s): `git-crypt add-gpg-user GPG_USER_ID ...` git-crypt-0.5.0/RELEASE_NOTES-0.4.md000066400000000000000000000060271253247362000163200ustar00rootroot00000000000000Changes to be aware of for git-crypt 0.4 ======================================== (For a complete list of changes, see the [NEWS](NEWS.md) file.) ### New workflow The commands for setting up a repository have changed in git-crypt 0.4. The previous commands continue to work, but will be removed in a future release of git-crypt. Please get in the habit of using the new syntax: `git-crypt init` no longer takes an argument, and is now used only when initializing a repository for the very first time. It generates a key and stores it in the `.git` directory. There is no longer a separate `keygen` step, and you no longer need to keep a copy of the key outside the repository. `git-crypt init` is no longer used to decrypt a cloned repository. Instead, run `git-crypt unlock /path/to/keyfile`, where `keyfile` is obtained by running `git-crypt export-key /path/to/keyfile` from an already-decrypted repository. ### GPG mode git-crypt now supports GPG. A repository can be shared with one or more GPG users in lieu of sharing a secret symmetric key. Symmetric key support isn't going away, but the workflow of GPG mode is extremely easy and all users are encouraged to consider it for their repositories. See the [README](README.md) for details on using GPG. ### Status command A new command, `git-crypt status`, lists encrypted files, which is useful for making sure your `.gitattributes` pattern is protecting the right files. ### Multiple key support git-crypt now lets you encrypt different sets of files with different keys, which is useful if you want to grant different collaborators access to different sets of files. See [doc/multiple_keys.md](doc/multiple_keys.md) for details. ### Compatibility with old repositories Repositories created with older versions of git-crypt continue to work without any changes needed, and backwards compatibility with these repositories will be maintained indefinitely. However, you will not be able to take advantage of git-crypt's new features, such as GPG support, unless you migrate your repository. To migrate your repository, first ensure the working tree is clean. Then migrate your current key file and use the migrated key to unlock your repository as follows: git-crypt migrate-key /path/to/old_key /path/to/migrated_key git-crypt unlock /path/to/migrated_key Once you've confirmed that your repository is functional, you can delete both the old and migrated key files (though keeping a backup of your key is always a good idea). ### Known issues It is not yet possible to revoke access from a GPG user. This will require substantial development work and will be a major focus of future git-crypt development. The output of `git-crypt status` is currently very bare-bones and will be substantially improved in a future release. Do not rely on its output being stable. A future release of git-crypt will provide an option for stable machine-readable output. On Windows, git-crypt does not create key files with restrictive permissions. Take care when using git-crypt on a multi-user Windows system. git-crypt-0.5.0/THANKS.md000066400000000000000000000007421253247362000147570ustar00rootroot00000000000000For their contributions to git-crypt, I thank: * Michael Mior and @zimbatm for the Homebrew formula. * Cyril Cleaud for help with Windows support. * The following people for contributing patches: * Adam Nelson * Caleb Maclennan * Darayus Nanavati * Jon Sailor * Linus G Thiel * Michael Schout * Simon Kotlinski * And everyone who has tested git-crypt, provided feedback, reported bugs, and participated in discussions about new features. Thank you! git-crypt-0.5.0/commands.cpp000066400000000000000000001561031253247362000157550ustar00rootroot00000000000000/* * Copyright 2012, 2014 Andrew Ayer * * This file is part of git-crypt. * * git-crypt 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. * * git-crypt 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 git-crypt. If not, see . * * Additional permission under GNU GPL version 3 section 7: * * If you modify the Program, or any covered work, by linking or * combining it with the OpenSSL project's OpenSSL library (or a * modified version of that library), containing parts covered by the * terms of the OpenSSL or SSLeay licenses, the licensors of the Program * grant you additional permission to convey the resulting work. * Corresponding Source for a non-source form of such a combination * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ #include "commands.hpp" #include "crypto.hpp" #include "util.hpp" #include "key.hpp" #include "gpg.hpp" #include "parse_options.hpp" #include "coprocess.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include static std::string attribute_name (const char* key_name) { if (key_name) { // named key return std::string("git-crypt-") + key_name; } else { // default key return "git-crypt"; } } static std::string git_version_string () { std::vector command; command.push_back("git"); command.push_back("version"); std::stringstream output; if (!successful_exit(exec_command(command, output))) { throw Error("'git version' failed - is Git installed?"); } std::string word; output >> word; // "git" output >> word; // "version" output >> word; // "1.7.10.4" return word; } static std::vector parse_version (const std::string& str) { std::istringstream in(str); std::vector version; std::string component; while (std::getline(in, component, '.')) { version.push_back(std::atoi(component.c_str())); } return version; } static const std::vector& git_version () { static const std::vector version(parse_version(git_version_string())); return version; } static std::vector make_version (int a, int b, int c) { std::vector version; version.push_back(a); version.push_back(b); version.push_back(c); return version; } static void git_config (const std::string& name, const std::string& value) { std::vector command; command.push_back("git"); command.push_back("config"); command.push_back(name); command.push_back(value); if (!successful_exit(exec_command(command))) { throw Error("'git config' failed"); } } static bool git_has_config (const std::string& name) { std::vector command; command.push_back("git"); command.push_back("config"); command.push_back("--get-all"); command.push_back(name); std::stringstream output; switch (exit_status(exec_command(command, output))) { case 0: return true; case 1: return false; default: throw Error("'git config' failed"); } } static void git_deconfig (const std::string& name) { std::vector command; command.push_back("git"); command.push_back("config"); command.push_back("--remove-section"); command.push_back(name); if (!successful_exit(exec_command(command))) { throw Error("'git config' failed"); } } static void configure_git_filters (const char* key_name) { std::string escaped_git_crypt_path(escape_shell_arg(our_exe_path())); if (key_name) { // Note: key_name contains only shell-safe characters so it need not be escaped. git_config(std::string("filter.git-crypt-") + key_name + ".smudge", escaped_git_crypt_path + " smudge --key-name=" + key_name); git_config(std::string("filter.git-crypt-") + key_name + ".clean", escaped_git_crypt_path + " clean --key-name=" + key_name); git_config(std::string("filter.git-crypt-") + key_name + ".required", "true"); git_config(std::string("diff.git-crypt-") + key_name + ".textconv", escaped_git_crypt_path + " diff --key-name=" + key_name); } else { git_config("filter.git-crypt.smudge", escaped_git_crypt_path + " smudge"); git_config("filter.git-crypt.clean", escaped_git_crypt_path + " clean"); git_config("filter.git-crypt.required", "true"); git_config("diff.git-crypt.textconv", escaped_git_crypt_path + " diff"); } } static void deconfigure_git_filters (const char* key_name) { // deconfigure the git-crypt filters if (git_has_config("filter." + attribute_name(key_name) + ".smudge") || git_has_config("filter." + attribute_name(key_name) + ".clean") || git_has_config("filter." + attribute_name(key_name) + ".required")) { git_deconfig("filter." + attribute_name(key_name)); } if (git_has_config("diff." + attribute_name(key_name) + ".textconv")) { git_deconfig("diff." + attribute_name(key_name)); } } static bool git_checkout (const std::vector& paths) { std::vector command; command.push_back("git"); command.push_back("checkout"); command.push_back("--"); for (std::vector::const_iterator path(paths.begin()); path != paths.end(); ++path) { command.push_back(*path); } if (!successful_exit(exec_command(command))) { return false; } return true; } static bool same_key_name (const char* a, const char* b) { return (!a && !b) || (a && b && std::strcmp(a, b) == 0); } static void validate_key_name_or_throw (const char* key_name) { std::string reason; if (!validate_key_name(key_name, &reason)) { throw Error(reason); } } static std::string get_internal_state_path () { // git rev-parse --git-dir std::vector command; command.push_back("git"); command.push_back("rev-parse"); command.push_back("--git-dir"); std::stringstream output; if (!successful_exit(exec_command(command, output))) { throw Error("'git rev-parse --git-dir' failed - is this a Git repository?"); } std::string path; std::getline(output, path); path += "/git-crypt"; return path; } static std::string get_internal_keys_path (const std::string& internal_state_path) { return internal_state_path + "/keys"; } static std::string get_internal_keys_path () { return get_internal_keys_path(get_internal_state_path()); } static std::string get_internal_key_path (const char* key_name) { std::string path(get_internal_keys_path()); path += "/"; path += key_name ? key_name : "default"; return path; } static std::string get_repo_state_path () { // git rev-parse --show-toplevel std::vector command; command.push_back("git"); command.push_back("rev-parse"); command.push_back("--show-toplevel"); std::stringstream output; if (!successful_exit(exec_command(command, output))) { throw Error("'git rev-parse --show-toplevel' failed - is this a Git repository?"); } std::string path; std::getline(output, path); if (path.empty()) { // could happen for a bare repo throw Error("Could not determine Git working tree - is this a non-bare repo?"); } path += "/.git-crypt"; return path; } static std::string get_repo_keys_path (const std::string& repo_state_path) { return repo_state_path + "/keys"; } static std::string get_repo_keys_path () { return get_repo_keys_path(get_repo_state_path()); } static std::string get_path_to_top () { // git rev-parse --show-cdup std::vector command; command.push_back("git"); command.push_back("rev-parse"); command.push_back("--show-cdup"); std::stringstream output; if (!successful_exit(exec_command(command, output))) { throw Error("'git rev-parse --show-cdup' failed - is this a Git repository?"); } std::string path_to_top; std::getline(output, path_to_top); return path_to_top; } static void get_git_status (std::ostream& output) { // git status -uno --porcelain std::vector command; command.push_back("git"); command.push_back("status"); command.push_back("-uno"); // don't show untracked files command.push_back("--porcelain"); if (!successful_exit(exec_command(command, output))) { throw Error("'git status' failed - is this a Git repository?"); } } // returns filter and diff attributes as a pair static std::pair get_file_attributes (const std::string& filename) { // git check-attr filter diff -- filename std::vector command; command.push_back("git"); command.push_back("check-attr"); command.push_back("filter"); command.push_back("diff"); command.push_back("--"); command.push_back(filename); std::stringstream output; if (!successful_exit(exec_command(command, output))) { throw Error("'git check-attr' failed - is this a Git repository?"); } std::string filter_attr; std::string diff_attr; std::string line; // Example output: // filename: filter: git-crypt // filename: diff: git-crypt while (std::getline(output, line)) { // filename might contain ": ", so parse line backwards // filename: attr_name: attr_value // ^name_pos ^value_pos const std::string::size_type value_pos(line.rfind(": ")); if (value_pos == std::string::npos || value_pos == 0) { continue; } const std::string::size_type name_pos(line.rfind(": ", value_pos - 1)); if (name_pos == std::string::npos) { continue; } const std::string attr_name(line.substr(name_pos + 2, value_pos - (name_pos + 2))); const std::string attr_value(line.substr(value_pos + 2)); if (attr_value != "unspecified" && attr_value != "unset" && attr_value != "set") { if (attr_name == "filter") { filter_attr = attr_value; } else if (attr_name == "diff") { diff_attr = attr_value; } } } return std::make_pair(filter_attr, diff_attr); } // returns filter and diff attributes as a pair static std::pair get_file_attributes (const std::string& filename, std::ostream& check_attr_stdin, std::istream& check_attr_stdout) { check_attr_stdin << filename << '\0' << std::flush; std::string filter_attr; std::string diff_attr; // Example output: // filename\0filter\0git-crypt\0filename\0diff\0git-crypt\0 for (int i = 0; i < 2; ++i) { std::string filename; std::string attr_name; std::string attr_value; std::getline(check_attr_stdout, filename, '\0'); std::getline(check_attr_stdout, attr_name, '\0'); std::getline(check_attr_stdout, attr_value, '\0'); if (attr_value != "unspecified" && attr_value != "unset" && attr_value != "set") { if (attr_name == "filter") { filter_attr = attr_value; } else if (attr_name == "diff") { diff_attr = attr_value; } } } return std::make_pair(filter_attr, diff_attr); } static bool check_if_blob_is_encrypted (const std::string& object_id) { // git cat-file blob object_id std::vector command; command.push_back("git"); command.push_back("cat-file"); command.push_back("blob"); command.push_back(object_id); // TODO: do this more efficiently - don't read entire command output into buffer, only read what we need std::stringstream output; if (!successful_exit(exec_command(command, output))) { throw Error("'git cat-file' failed - is this a Git repository?"); } char header[10]; output.read(header, sizeof(header)); return output.gcount() == sizeof(header) && std::memcmp(header, "\0GITCRYPT\0", 10) == 0; } static bool check_if_file_is_encrypted (const std::string& filename) { // git ls-files -sz filename std::vector command; command.push_back("git"); command.push_back("ls-files"); command.push_back("-sz"); command.push_back("--"); command.push_back(filename); std::stringstream output; if (!successful_exit(exec_command(command, output))) { throw Error("'git ls-files' failed - is this a Git repository?"); } if (output.peek() == -1) { return false; } std::string mode; std::string object_id; output >> mode >> object_id; return check_if_blob_is_encrypted(object_id); } static bool is_git_file_mode (const std::string& mode) { return (std::strtoul(mode.c_str(), NULL, 8) & 0170000) == 0100000; } static void get_encrypted_files (std::vector& files, const char* key_name) { // git ls-files -cz -- path_to_top std::vector ls_files_command; ls_files_command.push_back("git"); ls_files_command.push_back("ls-files"); ls_files_command.push_back("-csz"); ls_files_command.push_back("--"); const std::string path_to_top(get_path_to_top()); if (!path_to_top.empty()) { ls_files_command.push_back(path_to_top); } Coprocess ls_files; std::istream* ls_files_stdout = ls_files.stdout_pipe(); ls_files.spawn(ls_files_command); Coprocess check_attr; std::ostream* check_attr_stdin = NULL; std::istream* check_attr_stdout = NULL; if (git_version() >= make_version(1, 8, 5)) { // In Git 1.8.5 (released 27 Nov 2013) and higher, we use a single `git check-attr` process // to get the attributes of all files at once. In prior versions, we have to fork and exec // a separate `git check-attr` process for each file, since -z and --stdin aren't supported. // In a repository with thousands of files, this results in an almost 100x speedup. std::vector check_attr_command; check_attr_command.push_back("git"); check_attr_command.push_back("check-attr"); check_attr_command.push_back("--stdin"); check_attr_command.push_back("-z"); check_attr_command.push_back("filter"); check_attr_command.push_back("diff"); check_attr_stdin = check_attr.stdin_pipe(); check_attr_stdout = check_attr.stdout_pipe(); check_attr.spawn(check_attr_command); } while (ls_files_stdout->peek() != -1) { std::string mode; std::string object_id; std::string stage; std::string filename; *ls_files_stdout >> mode >> object_id >> stage >> std::ws; std::getline(*ls_files_stdout, filename, '\0'); if (is_git_file_mode(mode)) { std::string filter_attribute; if (check_attr_stdin) { filter_attribute = get_file_attributes(filename, *check_attr_stdin, *check_attr_stdout).first; } else { filter_attribute = get_file_attributes(filename).first; } if (filter_attribute == attribute_name(key_name)) { files.push_back(filename); } } } if (!successful_exit(ls_files.wait())) { throw Error("'git ls-files' failed - is this a Git repository?"); } if (check_attr_stdin) { check_attr.close_stdin(); if (!successful_exit(check_attr.wait())) { throw Error("'git check-attr' failed - is this a Git repository?"); } } } static void load_key (Key_file& key_file, const char* key_name, const char* key_path =0, const char* legacy_path =0) { if (legacy_path) { std::ifstream key_file_in(legacy_path, std::fstream::binary); if (!key_file_in) { throw Error(std::string("Unable to open key file: ") + legacy_path); } key_file.load_legacy(key_file_in); } else if (key_path) { std::ifstream key_file_in(key_path, std::fstream::binary); if (!key_file_in) { throw Error(std::string("Unable to open key file: ") + key_path); } key_file.load(key_file_in); } else { std::ifstream key_file_in(get_internal_key_path(key_name).c_str(), std::fstream::binary); if (!key_file_in) { // TODO: include key name in error message throw Error("Unable to open key file - have you unlocked/initialized this repository yet?"); } key_file.load(key_file_in); } } static bool decrypt_repo_key (Key_file& key_file, const char* key_name, uint32_t key_version, const std::vector& secret_keys, const std::string& keys_path) { for (std::vector::const_iterator seckey(secret_keys.begin()); seckey != secret_keys.end(); ++seckey) { std::ostringstream path_builder; path_builder << keys_path << '/' << (key_name ? key_name : "default") << '/' << key_version << '/' << *seckey << ".gpg"; std::string path(path_builder.str()); if (access(path.c_str(), F_OK) == 0) { std::stringstream decrypted_contents; gpg_decrypt_from_file(path, decrypted_contents); Key_file this_version_key_file; this_version_key_file.load(decrypted_contents); const Key_file::Entry* this_version_entry = this_version_key_file.get(key_version); if (!this_version_entry) { throw Error("GPG-encrypted keyfile is malformed because it does not contain expected key version"); } if (!same_key_name(key_name, this_version_key_file.get_key_name())) { throw Error("GPG-encrypted keyfile is malformed because it does not contain expected key name"); } key_file.set_key_name(key_name); key_file.add(*this_version_entry); return true; } } return false; } static bool decrypt_repo_keys (std::vector& key_files, uint32_t key_version, const std::vector& secret_keys, const std::string& keys_path) { bool successful = false; std::vector dirents; if (access(keys_path.c_str(), F_OK) == 0) { dirents = get_directory_contents(keys_path.c_str()); } for (std::vector::const_iterator dirent(dirents.begin()); dirent != dirents.end(); ++dirent) { const char* key_name = 0; if (*dirent != "default") { if (!validate_key_name(dirent->c_str())) { continue; } key_name = dirent->c_str(); } Key_file key_file; if (decrypt_repo_key(key_file, key_name, key_version, secret_keys, keys_path)) { key_files.push_back(key_file); successful = true; } } return successful; } static void encrypt_repo_key (const char* key_name, const Key_file::Entry& key, const std::vector >& collab_keys, const std::string& keys_path, std::vector* new_files) { std::string key_file_data; { Key_file this_version_key_file; this_version_key_file.set_key_name(key_name); this_version_key_file.add(key); key_file_data = this_version_key_file.store_to_string(); } for (std::vector >::const_iterator collab(collab_keys.begin()); collab != collab_keys.end(); ++collab) { const std::string& fingerprint(collab->first); const bool key_is_trusted(collab->second); std::ostringstream path_builder; path_builder << keys_path << '/' << (key_name ? key_name : "default") << '/' << key.version << '/' << fingerprint << ".gpg"; std::string path(path_builder.str()); if (access(path.c_str(), F_OK) == 0) { continue; } mkdir_parent(path); gpg_encrypt_to_file(path, fingerprint, key_is_trusted, key_file_data.data(), key_file_data.size()); new_files->push_back(path); } } static int parse_plumbing_options (const char** key_name, const char** key_file, int argc, const char** argv) { Options_list options; options.push_back(Option_def("-k", key_name)); options.push_back(Option_def("--key-name", key_name)); options.push_back(Option_def("--key-file", key_file)); return parse_options(options, argc, argv); } // Encrypt contents of stdin and write to stdout int clean (int argc, const char** argv) { const char* key_name = 0; const char* key_path = 0; const char* legacy_key_path = 0; int argi = parse_plumbing_options(&key_name, &key_path, argc, argv); if (argc - argi == 0) { } else if (!key_name && !key_path && argc - argi == 1) { // Deprecated - for compatibility with pre-0.4 legacy_key_path = argv[argi]; } else { std::clog << "Usage: git-crypt clean [--key-name=NAME] [--key-file=PATH]" << std::endl; return 2; } Key_file key_file; load_key(key_file, key_name, key_path, legacy_key_path); const Key_file::Entry* key = key_file.get_latest(); if (!key) { std::clog << "git-crypt: error: key file is empty" << std::endl; return 1; } // Read the entire file Hmac_sha1_state hmac(key->hmac_key, HMAC_KEY_LEN); // Calculate the file's SHA1 HMAC as we go uint64_t file_size = 0; // Keep track of the length, make sure it doesn't get too big std::string file_contents; // First 8MB or so of the file go here temp_fstream temp_file; // The rest of the file spills into a temporary file on disk temp_file.exceptions(std::fstream::badbit); char buffer[1024]; while (std::cin && file_size < Aes_ctr_encryptor::MAX_CRYPT_BYTES) { std::cin.read(buffer, sizeof(buffer)); const size_t bytes_read = std::cin.gcount(); hmac.add(reinterpret_cast(buffer), bytes_read); file_size += bytes_read; if (file_size <= 8388608) { file_contents.append(buffer, bytes_read); } else { if (!temp_file.is_open()) { temp_file.open(std::fstream::in | std::fstream::out | std::fstream::binary | std::fstream::app); } temp_file.write(buffer, bytes_read); } } // Make sure the file isn't so large we'll overflow the counter value (which would doom security) if (file_size >= Aes_ctr_encryptor::MAX_CRYPT_BYTES) { std::clog << "git-crypt: error: file too long to encrypt securely" << std::endl; return 1; } // We use an HMAC of the file as the encryption nonce (IV) for CTR mode. // By using a hash of the file we ensure that the encryption is // deterministic so git doesn't think the file has changed when it really // hasn't. CTR mode with a synthetic IV is provably semantically secure // under deterministic CPA as long as the synthetic IV is derived from a // secure PRF applied to the message. Since HMAC-SHA1 is a secure PRF, this // encryption scheme is semantically secure under deterministic CPA. // // Informally, consider that if a file changes just a tiny bit, the IV will // be completely different, resulting in a completely different ciphertext // that leaks no information about the similarities of the plaintexts. Also, // since we're using the output from a secure hash function plus a counter // as the input to our block cipher, we should never have a situation where // two different plaintext blocks get encrypted with the same CTR value. A // nonce will be reused only if the entire file is the same, which leaks no // information except that the files are the same. // // To prevent an attacker from building a dictionary of hash values and then // looking up the nonce (which must be stored in the clear to allow for // decryption), we use an HMAC as opposed to a straight hash. // Note: Hmac_sha1_state::LEN >= Aes_ctr_encryptor::NONCE_LEN unsigned char digest[Hmac_sha1_state::LEN]; hmac.get(digest); // Write a header that... std::cout.write("\0GITCRYPT\0", 10); // ...identifies this as an encrypted file std::cout.write(reinterpret_cast(digest), Aes_ctr_encryptor::NONCE_LEN); // ...includes the nonce // Now encrypt the file and write to stdout Aes_ctr_encryptor aes(key->aes_key, digest); // First read from the in-memory copy const unsigned char* file_data = reinterpret_cast(file_contents.data()); size_t file_data_len = file_contents.size(); while (file_data_len > 0) { const size_t buffer_len = std::min(sizeof(buffer), file_data_len); aes.process(file_data, reinterpret_cast(buffer), buffer_len); std::cout.write(buffer, buffer_len); file_data += buffer_len; file_data_len -= buffer_len; } // Then read from the temporary file if applicable if (temp_file.is_open()) { temp_file.seekg(0); while (temp_file.peek() != -1) { temp_file.read(buffer, sizeof(buffer)); const size_t buffer_len = temp_file.gcount(); aes.process(reinterpret_cast(buffer), reinterpret_cast(buffer), buffer_len); std::cout.write(buffer, buffer_len); } } return 0; } static int decrypt_file_to_stdout (const Key_file& key_file, const unsigned char* header, std::istream& in) { const unsigned char* nonce = header + 10; uint32_t key_version = 0; // TODO: get the version from the file header const Key_file::Entry* key = key_file.get(key_version); if (!key) { std::clog << "git-crypt: error: key version " << key_version << " not available - please unlock with the latest version of the key." << std::endl; return 1; } Aes_ctr_decryptor aes(key->aes_key, nonce); Hmac_sha1_state hmac(key->hmac_key, HMAC_KEY_LEN); while (in) { unsigned char buffer[1024]; in.read(reinterpret_cast(buffer), sizeof(buffer)); aes.process(buffer, buffer, in.gcount()); hmac.add(buffer, in.gcount()); std::cout.write(reinterpret_cast(buffer), in.gcount()); } unsigned char digest[Hmac_sha1_state::LEN]; hmac.get(digest); if (!leakless_equals(digest, nonce, Aes_ctr_decryptor::NONCE_LEN)) { std::clog << "git-crypt: error: encrypted file has been tampered with!" << std::endl; // Although we've already written the tampered file to stdout, exiting // with a non-zero status will tell git the file has not been filtered, // so git will not replace it. return 1; } return 0; } // Decrypt contents of stdin and write to stdout int smudge (int argc, const char** argv) { const char* key_name = 0; const char* key_path = 0; const char* legacy_key_path = 0; int argi = parse_plumbing_options(&key_name, &key_path, argc, argv); if (argc - argi == 0) { } else if (!key_name && !key_path && argc - argi == 1) { // Deprecated - for compatibility with pre-0.4 legacy_key_path = argv[argi]; } else { std::clog << "Usage: git-crypt smudge [--key-name=NAME] [--key-file=PATH]" << std::endl; return 2; } Key_file key_file; load_key(key_file, key_name, key_path, legacy_key_path); // Read the header to get the nonce and make sure it's actually encrypted unsigned char header[10 + Aes_ctr_decryptor::NONCE_LEN]; std::cin.read(reinterpret_cast(header), sizeof(header)); if (std::cin.gcount() != sizeof(header) || std::memcmp(header, "\0GITCRYPT\0", 10) != 0) { // File not encrypted - just copy it out to stdout std::clog << "git-crypt: Warning: file not encrypted" << std::endl; std::clog << "git-crypt: Run 'git-crypt status' to make sure all files are properly encrypted." << std::endl; std::clog << "git-crypt: If 'git-crypt status' reports no problems, then an older version of" << std::endl; std::clog << "git-crypt: this file may be unencrypted in the repository's history. If this" << std::endl; std::clog << "git-crypt: file contains sensitive information, you can use 'git filter-branch'" << std::endl; std::clog << "git-crypt: to remove its old versions from the history." << std::endl; std::cout.write(reinterpret_cast(header), std::cin.gcount()); // include the bytes which we already read std::cout << std::cin.rdbuf(); return 0; } return decrypt_file_to_stdout(key_file, header, std::cin); } int diff (int argc, const char** argv) { const char* key_name = 0; const char* key_path = 0; const char* filename = 0; const char* legacy_key_path = 0; int argi = parse_plumbing_options(&key_name, &key_path, argc, argv); if (argc - argi == 1) { filename = argv[argi]; } else if (!key_name && !key_path && argc - argi == 2) { // Deprecated - for compatibility with pre-0.4 legacy_key_path = argv[argi]; filename = argv[argi + 1]; } else { std::clog << "Usage: git-crypt diff [--key-name=NAME] [--key-file=PATH] FILENAME" << std::endl; return 2; } Key_file key_file; load_key(key_file, key_name, key_path, legacy_key_path); // Open the file std::ifstream in(filename, std::fstream::binary); if (!in) { std::clog << "git-crypt: " << filename << ": unable to open for reading" << std::endl; return 1; } in.exceptions(std::fstream::badbit); // Read the header to get the nonce and determine if it's actually encrypted unsigned char header[10 + Aes_ctr_decryptor::NONCE_LEN]; in.read(reinterpret_cast(header), sizeof(header)); if (in.gcount() != sizeof(header) || std::memcmp(header, "\0GITCRYPT\0", 10) != 0) { // File not encrypted - just copy it out to stdout std::cout.write(reinterpret_cast(header), in.gcount()); // include the bytes which we already read std::cout << in.rdbuf(); return 0; } // Go ahead and decrypt it return decrypt_file_to_stdout(key_file, header, in); } void help_init (std::ostream& out) { // |--------------------------------------------------------------------------------| 80 chars out << "Usage: git-crypt init [OPTIONS]" << std::endl; out << std::endl; out << " -k, --key-name KEYNAME Initialize the given key, instead of the default" << std::endl; out << std::endl; } int init (int argc, const char** argv) { const char* key_name = 0; Options_list options; options.push_back(Option_def("-k", &key_name)); options.push_back(Option_def("--key-name", &key_name)); int argi = parse_options(options, argc, argv); if (!key_name && argc - argi == 1) { std::clog << "Warning: 'git-crypt init' with a key file is deprecated as of git-crypt 0.4" << std::endl; std::clog << "and will be removed in a future release. Please get in the habit of using" << std::endl; std::clog << "'git-crypt unlock KEYFILE' instead." << std::endl; return unlock(argc, argv); } if (argc - argi != 0) { std::clog << "Error: git-crypt init takes no arguments" << std::endl; help_init(std::clog); return 2; } if (key_name) { validate_key_name_or_throw(key_name); } std::string internal_key_path(get_internal_key_path(key_name)); if (access(internal_key_path.c_str(), F_OK) == 0) { // TODO: add a -f option to reinitialize the repo anyways (this should probably imply a refresh) // TODO: include key_name in error message std::clog << "Error: this repository has already been initialized with git-crypt." << std::endl; return 1; } // 1. Generate a key and install it std::clog << "Generating key..." << std::endl; Key_file key_file; key_file.set_key_name(key_name); key_file.generate(); mkdir_parent(internal_key_path); if (!key_file.store_to_file(internal_key_path.c_str())) { std::clog << "Error: " << internal_key_path << ": unable to write key file" << std::endl; return 1; } // 2. Configure git for git-crypt configure_git_filters(key_name); return 0; } void help_unlock (std::ostream& out) { // |--------------------------------------------------------------------------------| 80 chars out << "Usage: git-crypt unlock" << std::endl; out << " or: git-crypt unlock KEY_FILE ..." << std::endl; } int unlock (int argc, const char** argv) { // 1. Make sure working directory is clean (ignoring untracked files) // We do this because we check out files later, and we don't want the // user to lose any changes. (TODO: only care if encrypted files are // modified, since we only check out encrypted files) // Running 'git status' also serves as a check that the Git repo is accessible. std::stringstream status_output; get_git_status(status_output); if (status_output.peek() != -1) { std::clog << "Error: Working directory not clean." << std::endl; std::clog << "Please commit your changes or 'git stash' them before running 'git-crypt unlock'." << std::endl; return 1; } // 2. Load the key(s) std::vector key_files; if (argc > 0) { // Read from the symmetric key file(s) for (int argi = 0; argi < argc; ++argi) { const char* symmetric_key_file = argv[argi]; Key_file key_file; try { if (std::strcmp(symmetric_key_file, "-") == 0) { key_file.load(std::cin); } else { if (!key_file.load_from_file(symmetric_key_file)) { std::clog << "Error: " << symmetric_key_file << ": unable to read key file" << std::endl; return 1; } } } catch (Key_file::Incompatible) { std::clog << "Error: " << symmetric_key_file << " is in an incompatible format" << std::endl; std::clog << "Please upgrade to a newer version of git-crypt." << std::endl; return 1; } catch (Key_file::Malformed) { std::clog << "Error: " << symmetric_key_file << ": not a valid git-crypt key file" << std::endl; std::clog << "If this key was created prior to git-crypt 0.4, you need to migrate it" << std::endl; std::clog << "by running 'git-crypt migrate-key /path/to/old_key /path/to/migrated_key'." << std::endl; return 1; } key_files.push_back(key_file); } } else { // Decrypt GPG key from root of repo std::string repo_keys_path(get_repo_keys_path()); std::vector gpg_secret_keys(gpg_list_secret_keys()); // TODO: command-line option to specify the precise secret key to use // TODO: don't hard code key version 0 here - instead, determine the most recent version and try to decrypt that, or decrypt all versions if command-line option specified // TODO: command line option to only unlock specific key instead of all of them // TODO: avoid decrypting repo keys which are already unlocked in the .git directory if (!decrypt_repo_keys(key_files, 0, gpg_secret_keys, repo_keys_path)) { std::clog << "Error: no GPG secret key available to unlock this repository." << std::endl; std::clog << "To unlock with a shared symmetric key instead, specify the path to the symmetric key as an argument to 'git-crypt unlock'." << std::endl; // TODO std::clog << "To see a list of GPG keys authorized to unlock this repository, run 'git-crypt ls-gpg-users'." << std::endl; return 1; } } // 3. Install the key(s) and configure the git filters std::vector encrypted_files; for (std::vector::iterator key_file(key_files.begin()); key_file != key_files.end(); ++key_file) { std::string internal_key_path(get_internal_key_path(key_file->get_key_name())); // TODO: croak if internal_key_path already exists??? mkdir_parent(internal_key_path); if (!key_file->store_to_file(internal_key_path.c_str())) { std::clog << "Error: " << internal_key_path << ": unable to write key file" << std::endl; return 1; } configure_git_filters(key_file->get_key_name()); get_encrypted_files(encrypted_files, key_file->get_key_name()); } // 4. Check out the files that are currently encrypted. // Git won't check out a file if its mtime hasn't changed, so touch every file first. for (std::vector::const_iterator file(encrypted_files.begin()); file != encrypted_files.end(); ++file) { touch_file(*file); } if (!git_checkout(encrypted_files)) { std::clog << "Error: 'git checkout' failed" << std::endl; std::clog << "git-crypt has been set up but existing encrypted files have not been decrypted" << std::endl; return 1; } return 0; } void help_lock (std::ostream& out) { // |--------------------------------------------------------------------------------| 80 chars out << "Usage: git-crypt lock [OPTIONS]" << std::endl; out << std::endl; out << " -a, --all Lock all keys, instead of just the default" << std::endl; out << " -k, --key-name KEYNAME Lock the given key, instead of the default" << std::endl; out << " -f, --force Lock even if unclean (you may lose uncommited work)" << std::endl; out << std::endl; } int lock (int argc, const char** argv) { const char* key_name = 0; bool all_keys = false; bool force = false; Options_list options; options.push_back(Option_def("-k", &key_name)); options.push_back(Option_def("--key-name", &key_name)); options.push_back(Option_def("-a", &all_keys)); options.push_back(Option_def("--all", &all_keys)); options.push_back(Option_def("-f", &force)); options.push_back(Option_def("--force", &force)); int argi = parse_options(options, argc, argv); if (argc - argi != 0) { std::clog << "Error: git-crypt lock takes no arguments" << std::endl; help_lock(std::clog); return 2; } if (all_keys && key_name) { std::clog << "Error: -k and --all options are mutually exclusive" << std::endl; return 2; } // 1. Make sure working directory is clean (ignoring untracked files) // We do this because we check out files later, and we don't want the // user to lose any changes. (TODO: only care if encrypted files are // modified, since we only check out encrypted files) // Running 'git status' also serves as a check that the Git repo is accessible. std::stringstream status_output; get_git_status(status_output); if (!force && status_output.peek() != -1) { std::clog << "Error: Working directory not clean." << std::endl; std::clog << "Please commit your changes or 'git stash' them before running 'git-crypt lock'." << std::endl; std::clog << "Or, use 'git-crypt lock --force' and possibly lose uncommitted changes." << std::endl; return 1; } // 2. deconfigure the git filters and remove decrypted keys std::vector encrypted_files; if (all_keys) { // deconfigure for all keys std::vector dirents = get_directory_contents(get_internal_keys_path().c_str()); for (std::vector::const_iterator dirent(dirents.begin()); dirent != dirents.end(); ++dirent) { const char* this_key_name = (*dirent == "default" ? 0 : dirent->c_str()); remove_file(get_internal_key_path(this_key_name)); deconfigure_git_filters(this_key_name); get_encrypted_files(encrypted_files, this_key_name); } } else { // just handle the given key std::string internal_key_path(get_internal_key_path(key_name)); if (access(internal_key_path.c_str(), F_OK) == -1 && errno == ENOENT) { std::clog << "Error: this repository is already locked"; if (key_name) { std::clog << " with key '" << key_name << "'"; } std::clog << "." << std::endl; return 1; } remove_file(internal_key_path); deconfigure_git_filters(key_name); get_encrypted_files(encrypted_files, key_name); } // 3. Check out the files that are currently decrypted but should be encrypted. // Git won't check out a file if its mtime hasn't changed, so touch every file first. for (std::vector::const_iterator file(encrypted_files.begin()); file != encrypted_files.end(); ++file) { touch_file(*file); } if (!git_checkout(encrypted_files)) { std::clog << "Error: 'git checkout' failed" << std::endl; std::clog << "git-crypt has been locked but up but existing decrypted files have not been encrypted" << std::endl; return 1; } return 0; } void help_add_gpg_user (std::ostream& out) { // |--------------------------------------------------------------------------------| 80 chars out << "Usage: git-crypt add-gpg-user [OPTIONS] GPG_USER_ID ..." << std::endl; out << std::endl; out << " -k, --key-name KEYNAME Add GPG user to given key, instead of default" << std::endl; out << " -n, --no-commit Don't automatically commit" << std::endl; out << " --trusted Assume the GPG user IDs are trusted" << std::endl; out << std::endl; } int add_gpg_user (int argc, const char** argv) { const char* key_name = 0; bool no_commit = false; bool trusted = false; Options_list options; options.push_back(Option_def("-k", &key_name)); options.push_back(Option_def("--key-name", &key_name)); options.push_back(Option_def("-n", &no_commit)); options.push_back(Option_def("--no-commit", &no_commit)); options.push_back(Option_def("--trusted", &trusted)); int argi = parse_options(options, argc, argv); if (argc - argi == 0) { std::clog << "Error: no GPG user ID specified" << std::endl; help_add_gpg_user(std::clog); return 2; } // build a list of key fingerprints, and whether the key is trusted, for every collaborator specified on the command line std::vector > collab_keys; for (int i = argi; i < argc; ++i) { std::vector keys(gpg_lookup_key(argv[i])); if (keys.empty()) { std::clog << "Error: public key for '" << argv[i] << "' not found in your GPG keyring" << std::endl; return 1; } if (keys.size() > 1) { std::clog << "Error: more than one public key matches '" << argv[i] << "' - please be more specific" << std::endl; return 1; } const bool is_full_fingerprint(std::strncmp(argv[i], "0x", 2) == 0 && std::strlen(argv[i]) == 42); collab_keys.push_back(std::make_pair(keys[0], trusted || is_full_fingerprint)); } // TODO: have a retroactive option to grant access to all key versions, not just the most recent Key_file key_file; load_key(key_file, key_name); const Key_file::Entry* key = key_file.get_latest(); if (!key) { std::clog << "Error: key file is empty" << std::endl; return 1; } const std::string state_path(get_repo_state_path()); std::vector new_files; encrypt_repo_key(key_name, *key, collab_keys, get_repo_keys_path(state_path), &new_files); // Add a .gitatributes file to the repo state directory to prevent files in it from being encrypted. const std::string state_gitattributes_path(state_path + "/.gitattributes"); if (access(state_gitattributes_path.c_str(), F_OK) != 0) { std::ofstream state_gitattributes_file(state_gitattributes_path.c_str()); // |--------------------------------------------------------------------------------| 80 chars state_gitattributes_file << "# Do not edit this file. To specify the files to encrypt, create your own\n"; state_gitattributes_file << "# .gitattributes file in the directory where your files are.\n"; state_gitattributes_file << "* !filter !diff\n"; state_gitattributes_file.close(); if (!state_gitattributes_file) { std::clog << "Error: unable to write " << state_gitattributes_path << std::endl; return 1; } new_files.push_back(state_gitattributes_path); } // add/commit the new files if (!new_files.empty()) { // git add NEW_FILE ... std::vector command; command.push_back("git"); command.push_back("add"); command.push_back("--"); command.insert(command.end(), new_files.begin(), new_files.end()); if (!successful_exit(exec_command(command))) { std::clog << "Error: 'git add' failed" << std::endl; return 1; } // git commit ... if (!no_commit) { // TODO: include key_name in commit message std::ostringstream commit_message_builder; commit_message_builder << "Add " << collab_keys.size() << " git-crypt collaborator" << (collab_keys.size() != 1 ? "s" : "") << "\n\nNew collaborators:\n\n"; for (std::vector >::const_iterator collab(collab_keys.begin()); collab != collab_keys.end(); ++collab) { commit_message_builder << '\t' << gpg_shorten_fingerprint(collab->first) << ' ' << gpg_get_uid(collab->first) << '\n'; } // git commit -m MESSAGE NEW_FILE ... command.clear(); command.push_back("git"); command.push_back("commit"); command.push_back("-m"); command.push_back(commit_message_builder.str()); command.push_back("--"); command.insert(command.end(), new_files.begin(), new_files.end()); if (!successful_exit(exec_command(command))) { std::clog << "Error: 'git commit' failed" << std::endl; return 1; } } } return 0; } void help_rm_gpg_user (std::ostream& out) { // |--------------------------------------------------------------------------------| 80 chars out << "Usage: git-crypt rm-gpg-user [OPTIONS] GPG_USER_ID ..." << std::endl; out << std::endl; out << " -k, --key-name KEYNAME Remove user from given key, instead of default" << std::endl; out << " -n, --no-commit Don't automatically commit" << std::endl; out << std::endl; } int rm_gpg_user (int argc, const char** argv) // TODO { std::clog << "Error: rm-gpg-user is not yet implemented." << std::endl; return 1; } void help_ls_gpg_users (std::ostream& out) { // |--------------------------------------------------------------------------------| 80 chars out << "Usage: git-crypt ls-gpg-users" << std::endl; } int ls_gpg_users (int argc, const char** argv) // TODO { // Sketch: // Scan the sub-directories in .git-crypt/keys, outputting something like this: // ==== // Key version 0: // 0x143DE9B3F7316900 Andrew Ayer // 0x4E386D9C9C61702F ??? // Key version 1: // 0x143DE9B3F7316900 Andrew Ayer // 0x1727274463D27F40 John Smith // 0x4E386D9C9C61702F ??? // ==== // To resolve a long hex ID, use a command like this: // gpg --options /dev/null --fixed-list-mode --batch --with-colons --list-keys 0x143DE9B3F7316900 std::clog << "Error: ls-gpg-users is not yet implemented." << std::endl; return 1; } void help_export_key (std::ostream& out) { // |--------------------------------------------------------------------------------| 80 chars out << "Usage: git-crypt export-key [OPTIONS] FILENAME" << std::endl; out << std::endl; out << " -k, --key-name KEYNAME Export the given key, instead of the default" << std::endl; out << std::endl; out << "When FILENAME is -, export to standard out." << std::endl; } int export_key (int argc, const char** argv) { // TODO: provide options to export only certain key versions const char* key_name = 0; Options_list options; options.push_back(Option_def("-k", &key_name)); options.push_back(Option_def("--key-name", &key_name)); int argi = parse_options(options, argc, argv); if (argc - argi != 1) { std::clog << "Error: no filename specified" << std::endl; help_export_key(std::clog); return 2; } Key_file key_file; load_key(key_file, key_name); const char* out_file_name = argv[argi]; if (std::strcmp(out_file_name, "-") == 0) { key_file.store(std::cout); } else { if (!key_file.store_to_file(out_file_name)) { std::clog << "Error: " << out_file_name << ": unable to write key file" << std::endl; return 1; } } return 0; } void help_keygen (std::ostream& out) { // |--------------------------------------------------------------------------------| 80 chars out << "Usage: git-crypt keygen FILENAME" << std::endl; out << std::endl; out << "When FILENAME is -, write to standard out." << std::endl; } int keygen (int argc, const char** argv) { if (argc != 1) { std::clog << "Error: no filename specified" << std::endl; help_keygen(std::clog); return 2; } const char* key_file_name = argv[0]; if (std::strcmp(key_file_name, "-") != 0 && access(key_file_name, F_OK) == 0) { std::clog << key_file_name << ": File already exists" << std::endl; return 1; } std::clog << "Generating key..." << std::endl; Key_file key_file; key_file.generate(); if (std::strcmp(key_file_name, "-") == 0) { key_file.store(std::cout); } else { if (!key_file.store_to_file(key_file_name)) { std::clog << "Error: " << key_file_name << ": unable to write key file" << std::endl; return 1; } } return 0; } void help_migrate_key (std::ostream& out) { // |--------------------------------------------------------------------------------| 80 chars out << "Usage: git-crypt migrate-key OLDFILENAME NEWFILENAME" << std::endl; out << std::endl; out << "Use - to read from standard in/write to standard out." << std::endl; } int migrate_key (int argc, const char** argv) { if (argc != 2) { std::clog << "Error: filenames not specified" << std::endl; help_migrate_key(std::clog); return 2; } const char* key_file_name = argv[0]; const char* new_key_file_name = argv[1]; Key_file key_file; try { if (std::strcmp(key_file_name, "-") == 0) { key_file.load_legacy(std::cin); } else { std::ifstream in(key_file_name, std::fstream::binary); if (!in) { std::clog << "Error: " << key_file_name << ": unable to open for reading" << std::endl; return 1; } key_file.load_legacy(in); } if (std::strcmp(new_key_file_name, "-") == 0) { key_file.store(std::cout); } else { if (!key_file.store_to_file(new_key_file_name)) { std::clog << "Error: " << new_key_file_name << ": unable to write key file" << std::endl; return 1; } } } catch (Key_file::Malformed) { std::clog << "Error: " << key_file_name << ": not a valid legacy git-crypt key file" << std::endl; return 1; } return 0; } void help_refresh (std::ostream& out) { // |--------------------------------------------------------------------------------| 80 chars out << "Usage: git-crypt refresh" << std::endl; } int refresh (int argc, const char** argv) // TODO: do a force checkout, much like in unlock { std::clog << "Error: refresh is not yet implemented." << std::endl; return 1; } void help_status (std::ostream& out) { // |--------------------------------------------------------------------------------| 80 chars out << "Usage: git-crypt status [OPTIONS] [FILE ...]" << std::endl; //out << " or: git-crypt status -r [OPTIONS]" << std::endl; //out << " or: git-crypt status -f" << std::endl; out << std::endl; out << " -e Show encrypted files only" << std::endl; out << " -u Show unencrypted files only" << std::endl; //out << " -r Show repository status only" << std::endl; out << " -f, --fix Fix problems with the repository" << std::endl; //out << " -z Machine-parseable output" << std::endl; out << std::endl; } int status (int argc, const char** argv) { // Usage: // git-crypt status -r [-z] Show repo status // git-crypt status [-e | -u] [-z] [FILE ...] Show encrypted status of files // git-crypt status -f Fix unencrypted blobs bool repo_status_only = false; // -r show repo status only bool show_encrypted_only = false; // -e show encrypted files only bool show_unencrypted_only = false; // -u show unencrypted files only bool fix_problems = false; // -f fix problems bool machine_output = false; // -z machine-parseable output Options_list options; options.push_back(Option_def("-r", &repo_status_only)); options.push_back(Option_def("-e", &show_encrypted_only)); options.push_back(Option_def("-u", &show_unencrypted_only)); options.push_back(Option_def("-f", &fix_problems)); options.push_back(Option_def("--fix", &fix_problems)); options.push_back(Option_def("-z", &machine_output)); int argi = parse_options(options, argc, argv); if (repo_status_only) { if (show_encrypted_only || show_unencrypted_only) { std::clog << "Error: -e and -u options cannot be used with -r" << std::endl; return 2; } if (fix_problems) { std::clog << "Error: -f option cannot be used with -r" << std::endl; return 2; } if (argc - argi != 0) { std::clog << "Error: filenames cannot be specified when -r is used" << std::endl; return 2; } } if (show_encrypted_only && show_unencrypted_only) { std::clog << "Error: -e and -u options are mutually exclusive" << std::endl; return 2; } if (fix_problems && (show_encrypted_only || show_unencrypted_only)) { std::clog << "Error: -e and -u options cannot be used with -f" << std::endl; return 2; } if (machine_output) { // TODO: implement machine-parseable output std::clog << "Sorry, machine-parseable output is not yet implemented" << std::endl; return 2; } if (argc - argi == 0) { // TODO: check repo status: // is it set up for git-crypt? // which keys are unlocked? // --> check for filter config (see configure_git_filters()) and corresponding internal key if (repo_status_only) { return 0; } } // git ls-files -cotsz --exclude-standard ... std::vector command; command.push_back("git"); command.push_back("ls-files"); command.push_back("-cotsz"); command.push_back("--exclude-standard"); command.push_back("--"); if (argc - argi == 0) { const std::string path_to_top(get_path_to_top()); if (!path_to_top.empty()) { command.push_back(path_to_top); } } else { for (int i = argi; i < argc; ++i) { command.push_back(argv[i]); } } std::stringstream output; if (!successful_exit(exec_command(command, output))) { throw Error("'git ls-files' failed - is this a Git repository?"); } // Output looks like (w/o newlines): // ? .gitignore\0 // H 100644 06ec22e5ed0de9280731ef000a10f9c3fbc26338 0 afile\0 std::vector files; bool attribute_errors = false; bool unencrypted_blob_errors = false; unsigned int nbr_of_fixed_blobs = 0; unsigned int nbr_of_fix_errors = 0; while (output.peek() != -1) { std::string tag; std::string object_id; std::string filename; output >> tag; if (tag != "?") { std::string mode; std::string stage; output >> mode >> object_id >> stage; if (!is_git_file_mode(mode)) { continue; } } output >> std::ws; std::getline(output, filename, '\0'); // TODO: get file attributes en masse for efficiency... unfortunately this requires machine-parseable output from git check-attr to be workable, and this is only supported in Git 1.8.5 and above (released 27 Nov 2013) const std::pair file_attrs(get_file_attributes(filename)); if (file_attrs.first == "git-crypt" || std::strncmp(file_attrs.first.c_str(), "git-crypt-", 10) == 0) { // File is encrypted const bool blob_is_unencrypted = !object_id.empty() && !check_if_blob_is_encrypted(object_id); if (fix_problems && blob_is_unencrypted) { if (access(filename.c_str(), F_OK) != 0) { std::clog << "Error: " << filename << ": cannot stage encrypted version because not present in working tree - please 'git rm' or 'git checkout' it" << std::endl; ++nbr_of_fix_errors; } else { touch_file(filename); std::vector git_add_command; git_add_command.push_back("git"); git_add_command.push_back("add"); git_add_command.push_back("--"); git_add_command.push_back(filename); if (!successful_exit(exec_command(git_add_command))) { throw Error("'git-add' failed"); } if (check_if_file_is_encrypted(filename)) { std::cout << filename << ": staged encrypted version" << std::endl; ++nbr_of_fixed_blobs; } else { std::clog << "Error: " << filename << ": still unencrypted even after staging" << std::endl; ++nbr_of_fix_errors; } } } else if (!fix_problems && !show_unencrypted_only) { // TODO: output the key name used to encrypt this file std::cout << " encrypted: " << filename; if (file_attrs.second != file_attrs.first) { // but diff filter is not properly set std::cout << " *** WARNING: diff=" << file_attrs.first << " attribute not set ***"; attribute_errors = true; } if (blob_is_unencrypted) { // File not actually encrypted std::cout << " *** WARNING: staged/committed version is NOT ENCRYPTED! ***"; unencrypted_blob_errors = true; } std::cout << std::endl; } } else { // File not encrypted if (!fix_problems && !show_encrypted_only) { std::cout << "not encrypted: " << filename << std::endl; } } } int exit_status = 0; if (attribute_errors) { std::cout << std::endl; std::cout << "Warning: one or more files has a git-crypt filter attribute but not a" << std::endl; std::cout << "corresponding git-crypt diff attribute. For proper 'git diff' operation" << std::endl; std::cout << "you should fix the .gitattributes file to specify the correct diff attribute." << std::endl; std::cout << "Consult the git-crypt documentation for help." << std::endl; exit_status = 1; } if (unencrypted_blob_errors) { std::cout << std::endl; std::cout << "Warning: one or more files is marked for encryption via .gitattributes but" << std::endl; std::cout << "was staged and/or committed before the .gitattributes file was in effect." << std::endl; std::cout << "Run 'git-crypt status' with the '-f' option to stage an encrypted version." << std::endl; exit_status = 1; } if (nbr_of_fixed_blobs) { std::cout << "Staged " << nbr_of_fixed_blobs << " encrypted file" << (nbr_of_fixed_blobs != 1 ? "s" : "") << "." << std::endl; std::cout << "Warning: if these files were previously committed, unencrypted versions still exist in the repository's history." << std::endl; } if (nbr_of_fix_errors) { std::cout << "Unable to stage " << nbr_of_fix_errors << " file" << (nbr_of_fix_errors != 1 ? "s" : "") << "." << std::endl; exit_status = 1; } return exit_status; } git-crypt-0.5.0/commands.hpp000066400000000000000000000050021253247362000157510ustar00rootroot00000000000000/* * Copyright 2012, 2014 Andrew Ayer * * This file is part of git-crypt. * * git-crypt 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. * * git-crypt 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 git-crypt. If not, see . * * Additional permission under GNU GPL version 3 section 7: * * If you modify the Program, or any covered work, by linking or * combining it with the OpenSSL project's OpenSSL library (or a * modified version of that library), containing parts covered by the * terms of the OpenSSL or SSLeay licenses, the licensors of the Program * grant you additional permission to convey the resulting work. * Corresponding Source for a non-source form of such a combination * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ #ifndef GIT_CRYPT_COMMANDS_HPP #define GIT_CRYPT_COMMANDS_HPP #include #include struct Error { std::string message; explicit Error (std::string m) : message(m) { } }; // Plumbing commands: int clean (int argc, const char** argv); int smudge (int argc, const char** argv); int diff (int argc, const char** argv); // Public commands: int init (int argc, const char** argv); int unlock (int argc, const char** argv); int lock (int argc, const char** argv); int add_gpg_user (int argc, const char** argv); int rm_gpg_user (int argc, const char** argv); int ls_gpg_users (int argc, const char** argv); int export_key (int argc, const char** argv); int keygen (int argc, const char** argv); int migrate_key (int argc, const char** argv); int refresh (int argc, const char** argv); int status (int argc, const char** argv); // Help messages: void help_init (std::ostream&); void help_unlock (std::ostream&); void help_lock (std::ostream&); void help_add_gpg_user (std::ostream&); void help_rm_gpg_user (std::ostream&); void help_ls_gpg_users (std::ostream&); void help_export_key (std::ostream&); void help_keygen (std::ostream&); void help_migrate_key (std::ostream&); void help_refresh (std::ostream&); void help_status (std::ostream&); #endif git-crypt-0.5.0/coprocess-unix.cpp000066400000000000000000000112301253247362000171240ustar00rootroot00000000000000/* * Copyright 2015 Andrew Ayer * * This file is part of git-crypt. * * git-crypt 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. * * git-crypt 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 git-crypt. If not, see . * * Additional permission under GNU GPL version 3 section 7: * * If you modify the Program, or any covered work, by linking or * combining it with the OpenSSL project's OpenSSL library (or a * modified version of that library), containing parts covered by the * terms of the OpenSSL or SSLeay licenses, the licensors of the Program * grant you additional permission to convey the resulting work. * Corresponding Source for a non-source form of such a combination * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ #include "coprocess.hpp" #include "util.hpp" #include #include #include static int execvp (const std::string& file, const std::vector& args) { std::vector args_c_str; args_c_str.reserve(args.size()); for (std::vector::const_iterator arg(args.begin()); arg != args.end(); ++arg) { args_c_str.push_back(arg->c_str()); } args_c_str.push_back(NULL); return execvp(file.c_str(), const_cast(&args_c_str[0])); } Coprocess::Coprocess () { pid = -1; stdin_pipe_reader = -1; stdin_pipe_writer = -1; stdin_pipe_ostream = NULL; stdout_pipe_reader = -1; stdout_pipe_writer = -1; stdout_pipe_istream = NULL; } Coprocess::~Coprocess () { close_stdin(); close_stdout(); } std::ostream* Coprocess::stdin_pipe () { if (!stdin_pipe_ostream) { int fds[2]; if (pipe(fds) == -1) { throw System_error("pipe", "", errno); } stdin_pipe_reader = fds[0]; stdin_pipe_writer = fds[1]; stdin_pipe_ostream = new ofhstream(this, write_stdin); } return stdin_pipe_ostream; } void Coprocess::close_stdin () { delete stdin_pipe_ostream; stdin_pipe_ostream = NULL; if (stdin_pipe_writer != -1) { close(stdin_pipe_writer); stdin_pipe_writer = -1; } if (stdin_pipe_reader != -1) { close(stdin_pipe_reader); stdin_pipe_reader = -1; } } std::istream* Coprocess::stdout_pipe () { if (!stdout_pipe_istream) { int fds[2]; if (pipe(fds) == -1) { throw System_error("pipe", "", errno); } stdout_pipe_reader = fds[0]; stdout_pipe_writer = fds[1]; stdout_pipe_istream = new ifhstream(this, read_stdout); } return stdout_pipe_istream; } void Coprocess::close_stdout () { delete stdout_pipe_istream; stdout_pipe_istream = NULL; if (stdout_pipe_writer != -1) { close(stdout_pipe_writer); stdout_pipe_writer = -1; } if (stdout_pipe_reader != -1) { close(stdout_pipe_reader); stdout_pipe_reader = -1; } } void Coprocess::spawn (const std::vector& args) { pid = fork(); if (pid == -1) { throw System_error("fork", "", errno); } if (pid == 0) { if (stdin_pipe_writer != -1) { close(stdin_pipe_writer); } if (stdout_pipe_reader != -1) { close(stdout_pipe_reader); } if (stdin_pipe_reader != -1) { dup2(stdin_pipe_reader, 0); close(stdin_pipe_reader); } if (stdout_pipe_writer != -1) { dup2(stdout_pipe_writer, 1); close(stdout_pipe_writer); } execvp(args[0], args); perror(args[0].c_str()); _exit(-1); } if (stdin_pipe_reader != -1) { close(stdin_pipe_reader); stdin_pipe_reader = -1; } if (stdout_pipe_writer != -1) { close(stdout_pipe_writer); stdout_pipe_writer = -1; } } int Coprocess::wait () { int status = 0; if (waitpid(pid, &status, 0) == -1) { throw System_error("waitpid", "", errno); } return status; } size_t Coprocess::write_stdin (void* handle, const void* buf, size_t count) { const int fd = static_cast(handle)->stdin_pipe_writer; ssize_t ret; while ((ret = write(fd, buf, count)) == -1 && errno == EINTR); // restart if interrupted if (ret < 0) { throw System_error("write", "", errno); } return ret; } size_t Coprocess::read_stdout (void* handle, void* buf, size_t count) { const int fd = static_cast(handle)->stdout_pipe_reader; ssize_t ret; while ((ret = read(fd, buf, count)) == -1 && errno == EINTR); // restart if interrupted if (ret < 0) { throw System_error("read", "", errno); } return ret; } git-crypt-0.5.0/coprocess-unix.hpp000066400000000000000000000040301253247362000171310ustar00rootroot00000000000000/* * Copyright 2015 Andrew Ayer * * This file is part of git-crypt. * * git-crypt 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. * * git-crypt 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 git-crypt. If not, see . * * Additional permission under GNU GPL version 3 section 7: * * If you modify the Program, or any covered work, by linking or * combining it with the OpenSSL project's OpenSSL library (or a * modified version of that library), containing parts covered by the * terms of the OpenSSL or SSLeay licenses, the licensors of the Program * grant you additional permission to convey the resulting work. * Corresponding Source for a non-source form of such a combination * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ #ifndef GIT_CRYPT_COPROCESS_HPP #define GIT_CRYPT_COPROCESS_HPP #include "fhstream.hpp" #include #include class Coprocess { pid_t pid; int stdin_pipe_reader; int stdin_pipe_writer; ofhstream* stdin_pipe_ostream; static size_t write_stdin (void*, const void*, size_t); int stdout_pipe_reader; int stdout_pipe_writer; ifhstream* stdout_pipe_istream; static size_t read_stdout (void*, void*, size_t); Coprocess (const Coprocess&); // Disallow copy Coprocess& operator= (const Coprocess&); // Disallow assignment public: Coprocess (); ~Coprocess (); std::ostream* stdin_pipe (); void close_stdin (); std::istream* stdout_pipe (); void close_stdout (); void spawn (const std::vector&); int wait (); }; #endif git-crypt-0.5.0/coprocess-win32.cpp000066400000000000000000000175061253247362000171170ustar00rootroot00000000000000/* * Copyright 2015 Andrew Ayer * * This file is part of git-crypt. * * git-crypt 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. * * git-crypt 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 git-crypt. If not, see . * * Additional permission under GNU GPL version 3 section 7: * * If you modify the Program, or any covered work, by linking or * combining it with the OpenSSL project's OpenSSL library (or a * modified version of that library), containing parts covered by the * terms of the OpenSSL or SSLeay licenses, the licensors of the Program * grant you additional permission to convey the resulting work. * Corresponding Source for a non-source form of such a combination * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ #include "coprocess-win32.hpp" #include "util.hpp" static void escape_cmdline_argument (std::string& cmdline, const std::string& arg) { // For an explanation of Win32's arcane argument quoting rules, see: // http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx // http://msdn.microsoft.com/en-us/library/bb776391%28v=vs.85%29.aspx // http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx // http://blogs.msdn.com/b/oldnewthing/archive/2010/09/17/10063629.aspx cmdline.push_back('"'); std::string::const_iterator p(arg.begin()); while (p != arg.end()) { if (*p == '"') { cmdline.push_back('\\'); cmdline.push_back('"'); ++p; } else if (*p == '\\') { unsigned int num_backslashes = 0; while (p != arg.end() && *p == '\\') { ++num_backslashes; ++p; } if (p == arg.end() || *p == '"') { // Backslashes need to be escaped num_backslashes *= 2; } while (num_backslashes--) { cmdline.push_back('\\'); } } else { cmdline.push_back(*p++); } } cmdline.push_back('"'); } static std::string format_cmdline (const std::vector& command) { std::string cmdline; for (std::vector::const_iterator arg(command.begin()); arg != command.end(); ++arg) { if (arg != command.begin()) { cmdline.push_back(' '); } escape_cmdline_argument(cmdline, *arg); } return cmdline; } static HANDLE spawn_command (const std::vector& command, HANDLE stdin_handle, HANDLE stdout_handle, HANDLE stderr_handle) { PROCESS_INFORMATION proc_info; ZeroMemory(&proc_info, sizeof(proc_info)); STARTUPINFO start_info; ZeroMemory(&start_info, sizeof(start_info)); start_info.cb = sizeof(STARTUPINFO); start_info.hStdInput = stdin_handle ? stdin_handle : GetStdHandle(STD_INPUT_HANDLE); start_info.hStdOutput = stdout_handle ? stdout_handle : GetStdHandle(STD_OUTPUT_HANDLE); start_info.hStdError = stderr_handle ? stderr_handle : GetStdHandle(STD_ERROR_HANDLE); start_info.dwFlags |= STARTF_USESTDHANDLES; std::string cmdline(format_cmdline(command)); if (!CreateProcessA(NULL, // application name (NULL to use command line) const_cast(cmdline.c_str()), NULL, // process security attributes NULL, // primary thread security attributes TRUE, // handles are inherited 0, // creation flags NULL, // use parent's environment NULL, // use parent's current directory &start_info, &proc_info)) { throw System_error("CreateProcess", cmdline, GetLastError()); } CloseHandle(proc_info.hThread); return proc_info.hProcess; } Coprocess::Coprocess () { proc_handle = NULL; stdin_pipe_reader = NULL; stdin_pipe_writer = NULL; stdin_pipe_ostream = NULL; stdout_pipe_reader = NULL; stdout_pipe_writer = NULL; stdout_pipe_istream = NULL; } Coprocess::~Coprocess () { close_stdin(); close_stdout(); if (proc_handle) { CloseHandle(proc_handle); } } std::ostream* Coprocess::stdin_pipe () { if (!stdin_pipe_ostream) { SECURITY_ATTRIBUTES sec_attr; // Set the bInheritHandle flag so pipe handles are inherited. sec_attr.nLength = sizeof(SECURITY_ATTRIBUTES); sec_attr.bInheritHandle = TRUE; sec_attr.lpSecurityDescriptor = NULL; // Create a pipe for the child process's STDIN. if (!CreatePipe(&stdin_pipe_reader, &stdin_pipe_writer, &sec_attr, 0)) { throw System_error("CreatePipe", "", GetLastError()); } // Ensure the write handle to the pipe for STDIN is not inherited. if (!SetHandleInformation(stdin_pipe_writer, HANDLE_FLAG_INHERIT, 0)) { throw System_error("SetHandleInformation", "", GetLastError()); } stdin_pipe_ostream = new ofhstream(this, write_stdin); } return stdin_pipe_ostream; } void Coprocess::close_stdin () { delete stdin_pipe_ostream; stdin_pipe_ostream = NULL; if (stdin_pipe_writer) { CloseHandle(stdin_pipe_writer); stdin_pipe_writer = NULL; } if (stdin_pipe_reader) { CloseHandle(stdin_pipe_reader); stdin_pipe_reader = NULL; } } std::istream* Coprocess::stdout_pipe () { if (!stdout_pipe_istream) { SECURITY_ATTRIBUTES sec_attr; // Set the bInheritHandle flag so pipe handles are inherited. sec_attr.nLength = sizeof(SECURITY_ATTRIBUTES); sec_attr.bInheritHandle = TRUE; sec_attr.lpSecurityDescriptor = NULL; // Create a pipe for the child process's STDOUT. if (!CreatePipe(&stdout_pipe_reader, &stdout_pipe_writer, &sec_attr, 0)) { throw System_error("CreatePipe", "", GetLastError()); } // Ensure the read handle to the pipe for STDOUT is not inherited. if (!SetHandleInformation(stdout_pipe_reader, HANDLE_FLAG_INHERIT, 0)) { throw System_error("SetHandleInformation", "", GetLastError()); } stdout_pipe_istream = new ifhstream(this, read_stdout); } return stdout_pipe_istream; } void Coprocess::close_stdout () { delete stdout_pipe_istream; stdout_pipe_istream = NULL; if (stdout_pipe_writer) { CloseHandle(stdout_pipe_writer); stdout_pipe_writer = NULL; } if (stdout_pipe_reader) { CloseHandle(stdout_pipe_reader); stdout_pipe_reader = NULL; } } void Coprocess::spawn (const std::vector& args) { proc_handle = spawn_command(args, stdin_pipe_reader, stdout_pipe_writer, NULL); if (stdin_pipe_reader) { CloseHandle(stdin_pipe_reader); stdin_pipe_reader = NULL; } if (stdout_pipe_writer) { CloseHandle(stdout_pipe_writer); stdout_pipe_writer = NULL; } } int Coprocess::wait () { if (WaitForSingleObject(proc_handle, INFINITE) == WAIT_FAILED) { throw System_error("WaitForSingleObject", "", GetLastError()); } DWORD exit_code; if (!GetExitCodeProcess(proc_handle, &exit_code)) { throw System_error("GetExitCodeProcess", "", GetLastError()); } return exit_code; } size_t Coprocess::write_stdin (void* handle, const void* buf, size_t count) { DWORD bytes_written; if (!WriteFile(static_cast(handle)->stdin_pipe_writer, buf, count, &bytes_written, NULL)) { throw System_error("WriteFile", "", GetLastError()); } return bytes_written; } size_t Coprocess::read_stdout (void* handle, void* buf, size_t count) { // Note that ReadFile on a pipe may return with bytes_read==0 if the other // end of the pipe writes zero bytes, so retry when this happens. // When the other end of the pipe actually closes, ReadFile // fails with ERROR_BROKEN_PIPE. DWORD bytes_read; do { if (!ReadFile(static_cast(handle)->stdout_pipe_reader, buf, count, &bytes_read, NULL)) { const DWORD read_error = GetLastError(); if (read_error != ERROR_BROKEN_PIPE) { throw System_error("ReadFile", "", read_error); } return 0; } } while (bytes_read == 0); return bytes_read; } git-crypt-0.5.0/coprocess-win32.hpp000066400000000000000000000040561253247362000171200ustar00rootroot00000000000000/* * Copyright 2015 Andrew Ayer * * This file is part of git-crypt. * * git-crypt 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. * * git-crypt 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 git-crypt. If not, see . * * Additional permission under GNU GPL version 3 section 7: * * If you modify the Program, or any covered work, by linking or * combining it with the OpenSSL project's OpenSSL library (or a * modified version of that library), containing parts covered by the * terms of the OpenSSL or SSLeay licenses, the licensors of the Program * grant you additional permission to convey the resulting work. * Corresponding Source for a non-source form of such a combination * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ #ifndef GIT_CRYPT_COPROCESS_HPP #define GIT_CRYPT_COPROCESS_HPP #include "fhstream.hpp" #include #include class Coprocess { HANDLE proc_handle; HANDLE stdin_pipe_reader; HANDLE stdin_pipe_writer; ofhstream* stdin_pipe_ostream; static size_t write_stdin (void*, const void*, size_t); HANDLE stdout_pipe_reader; HANDLE stdout_pipe_writer; ifhstream* stdout_pipe_istream; static size_t read_stdout (void*, void*, size_t); Coprocess (const Coprocess&); // Disallow copy Coprocess& operator= (const Coprocess&); // Disallow assignment public: Coprocess (); ~Coprocess (); std::ostream* stdin_pipe (); void close_stdin (); std::istream* stdout_pipe (); void close_stdout (); void spawn (const std::vector&); int wait (); }; #endif git-crypt-0.5.0/coprocess.cpp000066400000000000000000000001301253247362000161400ustar00rootroot00000000000000#ifdef _WIN32 #include "coprocess-win32.cpp" #else #include "coprocess-unix.cpp" #endif git-crypt-0.5.0/coprocess.hpp000066400000000000000000000001301253247362000161450ustar00rootroot00000000000000#ifdef _WIN32 #include "coprocess-win32.hpp" #else #include "coprocess-unix.hpp" #endif git-crypt-0.5.0/crypto-openssl.cpp000066400000000000000000000064231253247362000171540ustar00rootroot00000000000000/* * Copyright 2012, 2014 Andrew Ayer * * This file is part of git-crypt. * * git-crypt 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. * * git-crypt 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 git-crypt. If not, see . * * Additional permission under GNU GPL version 3 section 7: * * If you modify the Program, or any covered work, by linking or * combining it with the OpenSSL project's OpenSSL library (or a * modified version of that library), containing parts covered by the * terms of the OpenSSL or SSLeay licenses, the licensors of the Program * grant you additional permission to convey the resulting work. * Corresponding Source for a non-source form of such a combination * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ #include "crypto.hpp" #include "key.hpp" #include "util.hpp" #include #include #include #include #include #include #include #include void init_crypto () { ERR_load_crypto_strings(); } struct Aes_ecb_encryptor::Aes_impl { AES_KEY key; }; Aes_ecb_encryptor::Aes_ecb_encryptor (const unsigned char* raw_key) : impl(new Aes_impl) { if (AES_set_encrypt_key(raw_key, KEY_LEN * 8, &(impl->key)) != 0) { throw Crypto_error("Aes_ctr_encryptor::Aes_ctr_encryptor", "AES_set_encrypt_key failed"); } } Aes_ecb_encryptor::~Aes_ecb_encryptor () { // Note: Explicit destructor necessary because class contains an auto_ptr // which contains an incomplete type when the auto_ptr is declared. explicit_memset(&impl->key, '\0', sizeof(impl->key)); } void Aes_ecb_encryptor::encrypt(const unsigned char* plain, unsigned char* cipher) { AES_encrypt(plain, cipher, &(impl->key)); } struct Hmac_sha1_state::Hmac_impl { HMAC_CTX ctx; }; Hmac_sha1_state::Hmac_sha1_state (const unsigned char* key, size_t key_len) : impl(new Hmac_impl) { HMAC_Init(&(impl->ctx), key, key_len, EVP_sha1()); } Hmac_sha1_state::~Hmac_sha1_state () { // Note: Explicit destructor necessary because class contains an auto_ptr // which contains an incomplete type when the auto_ptr is declared. HMAC_cleanup(&(impl->ctx)); } void Hmac_sha1_state::add (const unsigned char* buffer, size_t buffer_len) { HMAC_Update(&(impl->ctx), buffer, buffer_len); } void Hmac_sha1_state::get (unsigned char* digest) { unsigned int len; HMAC_Final(&(impl->ctx), digest, &len); } void random_bytes (unsigned char* buffer, size_t len) { if (RAND_bytes(buffer, len) != 1) { std::ostringstream message; while (unsigned long code = ERR_get_error()) { char error_string[120]; ERR_error_string_n(code, error_string, sizeof(error_string)); message << "OpenSSL Error: " << error_string << "; "; } throw Crypto_error("random_bytes", message.str()); } } git-crypt-0.5.0/crypto.cpp000066400000000000000000000053671253247362000155010ustar00rootroot00000000000000/* * Copyright 2012, 2014 Andrew Ayer * * This file is part of git-crypt. * * git-crypt 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. * * git-crypt 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 git-crypt. If not, see . * * Additional permission under GNU GPL version 3 section 7: * * If you modify the Program, or any covered work, by linking or * combining it with the OpenSSL project's OpenSSL library (or a * modified version of that library), containing parts covered by the * terms of the OpenSSL or SSLeay licenses, the licensors of the Program * grant you additional permission to convey the resulting work. * Corresponding Source for a non-source form of such a combination * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ #include "crypto.hpp" #include "util.hpp" #include Aes_ctr_encryptor::Aes_ctr_encryptor (const unsigned char* raw_key, const unsigned char* nonce) : ecb(raw_key) { // Set first 12 bytes of the CTR value to the nonce. // This stays the same for the entirety of this object's lifetime. std::memcpy(ctr_value, nonce, NONCE_LEN); byte_counter = 0; } Aes_ctr_encryptor::~Aes_ctr_encryptor () { explicit_memset(pad, '\0', BLOCK_LEN); } void Aes_ctr_encryptor::process (const unsigned char* in, unsigned char* out, size_t len) { for (size_t i = 0; i < len; ++i) { if (byte_counter % BLOCK_LEN == 0) { // Set last 4 bytes of CTR to the (big-endian) block number (sequentially increasing with each block) store_be32(ctr_value + NONCE_LEN, byte_counter / BLOCK_LEN); // Generate a new pad ecb.encrypt(ctr_value, pad); } // encrypt one byte out[i] = in[i] ^ pad[byte_counter++ % BLOCK_LEN]; if (byte_counter == 0) { throw Crypto_error("Aes_ctr_encryptor::process", "Too much data to encrypt securely"); } } } // Encrypt/decrypt an entire input stream, writing to the given output stream void Aes_ctr_encryptor::process_stream (std::istream& in, std::ostream& out, const unsigned char* key, const unsigned char* nonce) { Aes_ctr_encryptor aes(key, nonce); unsigned char buffer[1024]; while (in) { in.read(reinterpret_cast(buffer), sizeof(buffer)); aes.process(buffer, buffer, in.gcount()); out.write(reinterpret_cast(buffer), in.gcount()); } } git-crypt-0.5.0/crypto.hpp000066400000000000000000000062451253247362000155020ustar00rootroot00000000000000/* * Copyright 2012, 2014 Andrew Ayer * * This file is part of git-crypt. * * git-crypt 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. * * git-crypt 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 git-crypt. If not, see . * * Additional permission under GNU GPL version 3 section 7: * * If you modify the Program, or any covered work, by linking or * combining it with the OpenSSL project's OpenSSL library (or a * modified version of that library), containing parts covered by the * terms of the OpenSSL or SSLeay licenses, the licensors of the Program * grant you additional permission to convey the resulting work. * Corresponding Source for a non-source form of such a combination * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ #ifndef GIT_CRYPT_CRYPTO_HPP #define GIT_CRYPT_CRYPTO_HPP #include "key.hpp" #include #include #include #include #include void init_crypto (); struct Crypto_error { std::string where; std::string message; Crypto_error (const std::string& w, const std::string& m) : where(w), message(m) { } }; class Aes_ecb_encryptor { public: enum { KEY_LEN = AES_KEY_LEN, BLOCK_LEN = 16 }; private: struct Aes_impl; std::auto_ptr impl; public: Aes_ecb_encryptor (const unsigned char* key); ~Aes_ecb_encryptor (); void encrypt (const unsigned char* plain, unsigned char* cipher); }; class Aes_ctr_encryptor { public: enum { NONCE_LEN = 12, KEY_LEN = AES_KEY_LEN, BLOCK_LEN = 16, MAX_CRYPT_BYTES = (1ULL<<32)*16 // Don't encrypt more than this or the CTR value will repeat itself }; private: Aes_ecb_encryptor ecb; unsigned char ctr_value[BLOCK_LEN]; // Current CTR value (used as input to AES to derive pad) unsigned char pad[BLOCK_LEN]; // Current encryption pad (output of AES) uint32_t byte_counter; // How many bytes processed so far? public: Aes_ctr_encryptor (const unsigned char* key, const unsigned char* nonce); ~Aes_ctr_encryptor (); void process (const unsigned char* in, unsigned char* out, size_t len); // Encrypt/decrypt an entire input stream, writing to the given output stream static void process_stream (std::istream& in, std::ostream& out, const unsigned char* key, const unsigned char* nonce); }; typedef Aes_ctr_encryptor Aes_ctr_decryptor; class Hmac_sha1_state { public: enum { LEN = 20, KEY_LEN = HMAC_KEY_LEN }; private: struct Hmac_impl; std::auto_ptr impl; public: Hmac_sha1_state (const unsigned char* key, size_t key_len); ~Hmac_sha1_state (); void add (const unsigned char* buffer, size_t buffer_len); void get (unsigned char*); }; void random_bytes (unsigned char*, size_t); #endif git-crypt-0.5.0/doc/000077500000000000000000000000001253247362000142075ustar00rootroot00000000000000git-crypt-0.5.0/doc/multiple_keys.md000066400000000000000000000017231253247362000174220ustar00rootroot00000000000000In addition to the implicit default key, git-crypt supports alternative keys which can be used to encrypt specific files and can be shared with specific GPG users. This is useful if you want to grant different collaborators access to different sets of files. To generate an alternative key named KEYNAME, pass the `-k KEYNAME` option to `git-crypt init` as follows: git-crypt init -k KEYNAME To encrypt a file with an alternative key, use the `git-crypt-KEYNAME` filter in `.gitattributes` as follows: secretfile filter=git-crypt-KEYNAME diff=git-crypt-KEYNAME To export an alternative key or share it with a GPG user, pass the `-k KEYNAME` option to `git-crypt export-key` or `git-crypt add-gpg-user` as follows: git-crypt export-key -k KEYNAME /path/to/keyfile git-crypt add-gpg-user -k KEYNAME GPG_USER_ID To unlock a repository with an alternative key, use `git-crypt unlock` normally. git-crypt will automatically determine which key is being used. git-crypt-0.5.0/fhstream.cpp000066400000000000000000000142511253247362000157620ustar00rootroot00000000000000/* * Copyright (C) 2012, 2015 Andrew Ayer * * 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. * * Except as contained in this notice, the name(s) of the above copyright * holders shall not be used in advertising or otherwise to promote the * sale, use or other dealings in this Software without prior written * authorization. */ #include #include // for std::min #include "fhstream.hpp" /* * ofhstream */ ofhbuf::ofhbuf (void* arg_handle, size_t (*arg_write_fun)(void*, const void*, size_t)) : handle(arg_handle), write_fun(arg_write_fun), buffer(new char[default_buffer_size]), buffer_size(default_buffer_size) { reset_buffer(); } ofhbuf::~ofhbuf () { if (handle) { try { sync(); } catch (...) { // Ignore exception since we're in the destructor. // To catch write errors, call sync() explicitly. } } delete[] buffer; } ofhbuf::int_type ofhbuf::overflow (ofhbuf::int_type c) { const char* p = pbase(); std::streamsize bytes_to_write = pptr() - p; if (!is_eof(c)) { *pptr() = c; ++bytes_to_write; } while (bytes_to_write > 0) { const size_t bytes_written = write_fun(handle, p, bytes_to_write); bytes_to_write -= bytes_written; p += bytes_written; } reset_buffer(); return traits_type::to_int_type(0); } int ofhbuf::sync () { return !is_eof(overflow(traits_type::eof())) ? 0 : -1; } std::streamsize ofhbuf::xsputn (const char* s, std::streamsize n) { // Use heuristic to decide whether to write directly or just use buffer // Write directly only if n >= MIN(4096, available buffer capacity) // (this is similar to what basic_filebuf does) if (n < std::min(4096, epptr() - pptr())) { // Not worth it to do a direct write return std::streambuf::xsputn(s, n); } // Before we can do a direct write of this string, we need to flush // out the current contents of the buffer. if (pbase() != pptr()) { overflow(traits_type::eof()); // throws an exception or it succeeds } // Now we can go ahead and write out the string. size_t bytes_to_write = n; while (bytes_to_write > 0) { const size_t bytes_written = write_fun(handle, s, bytes_to_write); bytes_to_write -= bytes_written; s += bytes_written; } return n; // Return the total bytes written } std::streambuf* ofhbuf::setbuf (char* s, std::streamsize n) { if (s == 0 && n == 0) { // Switch to unbuffered // This won't take effect until the next overflow or sync // (We defer it taking effect so that write errors can be properly reported) // To cause it to take effect as soon as possible, we artificially reduce the // size of the buffer so it has no space left. This will trigger an overflow // on the next put. std::streambuf::setp(pbase(), pptr()); std::streambuf::pbump(pptr() - pbase()); buffer_size = 1; } return this; } /* * ifhstream */ ifhbuf::ifhbuf (void* arg_handle, size_t (*arg_read_fun)(void*, void*, size_t)) : handle(arg_handle), read_fun(arg_read_fun), buffer(new char[default_buffer_size + putback_size]), buffer_size(default_buffer_size) { reset_buffer(0, 0); } ifhbuf::~ifhbuf () { delete[] buffer; } ifhbuf::int_type ifhbuf::underflow () { if (gptr() >= egptr()) { // A true underflow (no bytes in buffer left to read) // Move the putback_size most-recently-read characters into the putback area size_t nputback = std::min(gptr() - eback(), putback_size); std::memmove(buffer + (putback_size - nputback), gptr() - nputback, nputback); // Now read new characters from the file descriptor const size_t nread = read_fun(handle, buffer + putback_size, buffer_size); if (nread == 0) { // EOF return traits_type::eof(); } // Reset the buffer reset_buffer(nputback, nread); } // Return the next character return traits_type::to_int_type(*gptr()); } std::streamsize ifhbuf::xsgetn (char* s, std::streamsize n) { // Use heuristic to decide whether to read directly // Read directly only if n >= bytes_available + 4096 std::streamsize bytes_available = egptr() - gptr(); if (n < bytes_available + 4096) { // Not worth it to do a direct read return std::streambuf::xsgetn(s, n); } std::streamsize total_bytes_read = 0; // First, copy out the bytes currently in the buffer std::memcpy(s, gptr(), bytes_available); s += bytes_available; n -= bytes_available; total_bytes_read += bytes_available; // Now do the direct read while (n > 0) { const size_t bytes_read = read_fun(handle, s, n); if (bytes_read == 0) { // EOF break; } s += bytes_read; n -= bytes_read; total_bytes_read += bytes_read; } // Fill up the putback area with the most recently read characters size_t nputback = std::min(total_bytes_read, putback_size); std::memcpy(buffer + (putback_size - nputback), s - nputback, nputback); // Reset the buffer with no bytes available for reading, but with some putback characters reset_buffer(nputback, 0); // Return the total number of bytes read return total_bytes_read; } std::streambuf* ifhbuf::setbuf (char* s, std::streamsize n) { if (s == 0 && n == 0) { // Switch to unbuffered // This won't take effect until the next underflow (we don't want to // lose what's currently in the buffer!) buffer_size = 1; } return this; } git-crypt-0.5.0/fhstream.hpp000066400000000000000000000074171253247362000157750ustar00rootroot00000000000000/* * Copyright (C) 2012, 2015 Andrew Ayer * * 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. * * Except as contained in this notice, the name(s) of the above copyright * holders shall not be used in advertising or otherwise to promote the * sale, use or other dealings in this Software without prior written * authorization. */ #ifndef GIT_CRYPT_FHSTREAM_HPP #define GIT_CRYPT_FHSTREAM_HPP #include #include #include /* * ofhstream */ class ofhbuf : public std::streambuf { enum { default_buffer_size = 8192 }; void* handle; size_t (*write_fun)(void*, const void*, size_t); char* buffer; size_t buffer_size; inline void reset_buffer () { std::streambuf::setp(buffer, buffer + buffer_size - 1); } static inline bool is_eof (int_type ch) { return traits_type::eq_int_type(ch, traits_type::eof()); } // Disallow copy #if __cplusplus >= 201103L /* C++11 */ ofhbuf (const ofhbuf&) = delete; ofhbuf& operator= (const ofhbuf&) = delete; #else ofhbuf (const ofhbuf&); ofhbuf& operator= (const ofhbuf&); #endif protected: virtual int_type overflow (int_type ch =traits_type::eof()); virtual int sync (); virtual std::streamsize xsputn (const char*, std::streamsize); virtual std::streambuf* setbuf (char*, std::streamsize); public: ofhbuf (void*, size_t (*)(void*, const void*, size_t)); ~ofhbuf (); // WARNING: calls sync() and ignores exceptions }; class ofhstream : public std::ostream { mutable ofhbuf buf; public: ofhstream (void* handle, size_t (*write_fun)(void*, const void*, size_t)) : std::ostream(0), buf(handle, write_fun) { std::ostream::rdbuf(&buf); } ofhbuf* rdbuf () const { return &buf; } }; /* * ifhstream */ class ifhbuf : public std::streambuf { enum { default_buffer_size = 8192, putback_size = 4 }; void* handle; size_t (*read_fun)(void*, void*, size_t); char* buffer; size_t buffer_size; inline void reset_buffer (size_t nputback, size_t nread) { std::streambuf::setg(buffer + (putback_size - nputback), buffer + putback_size, buffer + putback_size + nread); } // Disallow copy #if __cplusplus >= 201103L /* C++11 */ ifhbuf (const ifhbuf&) = delete; ifhbuf& operator= (const ifhbuf&) = delete; #else ifhbuf (const ifhbuf&); ifhbuf& operator= (const ifhbuf&); #endif protected: virtual int_type underflow (); virtual std::streamsize xsgetn (char*, std::streamsize); virtual std::streambuf* setbuf (char*, std::streamsize); public: ifhbuf (void*, size_t (*)(void*, void*, size_t)); ~ifhbuf (); // Can't fail }; class ifhstream : public std::istream { mutable ifhbuf buf; public: explicit ifhstream (void* handle, size_t (*read_fun)(void*, void*, size_t)) : std::istream(0), buf(handle, read_fun) { std::istream::rdbuf(&buf); } ifhbuf* rdbuf () const { return &buf; } }; #endif git-crypt-0.5.0/git-crypt.cpp000066400000000000000000000204711253247362000160740ustar00rootroot00000000000000/* * Copyright 2012, 2014 Andrew Ayer * * This file is part of git-crypt. * * git-crypt 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. * * git-crypt 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 git-crypt. If not, see . * * Additional permission under GNU GPL version 3 section 7: * * If you modify the Program, or any covered work, by linking or * combining it with the OpenSSL project's OpenSSL library (or a * modified version of that library), containing parts covered by the * terms of the OpenSSL or SSLeay licenses, the licensors of the Program * grant you additional permission to convey the resulting work. * Corresponding Source for a non-source form of such a combination * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ #include "git-crypt.hpp" #include "commands.hpp" #include "util.hpp" #include "crypto.hpp" #include "key.hpp" #include "gpg.hpp" #include "parse_options.hpp" #include #include #include #include const char* argv0; static void print_usage (std::ostream& out) { out << "Usage: " << argv0 << " COMMAND [ARGS ...]" << std::endl; out << std::endl; // |--------------------------------------------------------------------------------| 80 characters out << "Common commands:" << std::endl; out << " init generate a key and prepare repo to use git-crypt" << std::endl; out << " status display which files are encrypted" << std::endl; //out << " refresh ensure all files in the repo are properly decrypted" << std::endl; out << " lock de-configure git-crypt and re-encrypt files in work tree" << std::endl; out << std::endl; out << "GPG commands:" << std::endl; out << " add-gpg-user USERID add the user with the given GPG user ID as a collaborator" << std::endl; //out << " rm-gpg-user USERID revoke collaborator status from the given GPG user ID" << std::endl; //out << " ls-gpg-users list the GPG key IDs of collaborators" << std::endl; out << " unlock decrypt this repo using the in-repo GPG-encrypted key" << std::endl; out << std::endl; out << "Symmetric key commands:" << std::endl; out << " export-key FILE export this repo's symmetric key to the given file" << std::endl; out << " unlock KEYFILE decrypt this repo using the given symmetric key" << std::endl; out << std::endl; out << "Legacy commands:" << std::endl; out << " init KEYFILE alias for 'unlock KEYFILE'" << std::endl; out << " keygen KEYFILE generate a git-crypt key in the given file" << std::endl; out << " migrate-key OLD NEW migrate the legacy key file OLD to the new format in NEW" << std::endl; /* out << std::endl; out << "Plumbing commands (not to be used directly):" << std::endl; out << " clean [LEGACY-KEYFILE]" << std::endl; out << " smudge [LEGACY-KEYFILE]" << std::endl; out << " diff [LEGACY-KEYFILE] FILE" << std::endl; */ out << std::endl; out << "See 'git-crypt help COMMAND' for more information on a specific command." << std::endl; } static void print_version (std::ostream& out) { out << "git-crypt " << VERSION << std::endl; } static bool help_for_command (const char* command, std::ostream& out) { if (std::strcmp(command, "init") == 0) { help_init(out); } else if (std::strcmp(command, "unlock") == 0) { help_unlock(out); } else if (std::strcmp(command, "lock") == 0) { help_lock(out); } else if (std::strcmp(command, "add-gpg-user") == 0) { help_add_gpg_user(out); } else if (std::strcmp(command, "rm-gpg-user") == 0) { help_rm_gpg_user(out); } else if (std::strcmp(command, "ls-gpg-users") == 0) { help_ls_gpg_users(out); } else if (std::strcmp(command, "export-key") == 0) { help_export_key(out); } else if (std::strcmp(command, "keygen") == 0) { help_keygen(out); } else if (std::strcmp(command, "migrate-key") == 0) { help_migrate_key(out); } else if (std::strcmp(command, "refresh") == 0) { help_refresh(out); } else if (std::strcmp(command, "status") == 0) { help_status(out); } else { return false; } return true; } static int help (int argc, const char** argv) { if (argc == 0) { print_usage(std::cout); } else { if (!help_for_command(argv[0], std::cout)) { std::clog << "Error: '" << argv[0] << "' is not a git-crypt command. See 'git-crypt help'." << std::endl; return 1; } } return 0; } static int version (int argc, const char** argv) { print_version(std::cout); return 0; } int main (int argc, const char** argv) try { argv0 = argv[0]; /* * General initialization */ init_std_streams(); init_crypto(); /* * Parse command line arguments */ int arg_index = 1; while (arg_index < argc && argv[arg_index][0] == '-') { if (std::strcmp(argv[arg_index], "--help") == 0) { print_usage(std::clog); return 0; } else if (std::strcmp(argv[arg_index], "--version") == 0) { print_version(std::clog); return 0; } else if (std::strcmp(argv[arg_index], "--") == 0) { ++arg_index; break; } else { std::clog << argv0 << ": " << argv[arg_index] << ": Unknown option" << std::endl; print_usage(std::clog); return 2; } } argc -= arg_index; argv += arg_index; if (argc == 0) { print_usage(std::clog); return 2; } /* * Pass off to command handler */ const char* command = argv[0]; --argc; ++argv; try { // Public commands: if (std::strcmp(command, "help") == 0) { return help(argc, argv); } if (std::strcmp(command, "version") == 0) { return version(argc, argv); } if (std::strcmp(command, "init") == 0) { return init(argc, argv); } if (std::strcmp(command, "unlock") == 0) { return unlock(argc, argv); } if (std::strcmp(command, "lock") == 0) { return lock(argc, argv); } if (std::strcmp(command, "add-gpg-user") == 0) { return add_gpg_user(argc, argv); } if (std::strcmp(command, "rm-gpg-user") == 0) { return rm_gpg_user(argc, argv); } if (std::strcmp(command, "ls-gpg-users") == 0) { return ls_gpg_users(argc, argv); } if (std::strcmp(command, "export-key") == 0) { return export_key(argc, argv); } if (std::strcmp(command, "keygen") == 0) { return keygen(argc, argv); } if (std::strcmp(command, "migrate-key") == 0) { return migrate_key(argc, argv); } if (std::strcmp(command, "refresh") == 0) { return refresh(argc, argv); } if (std::strcmp(command, "status") == 0) { return status(argc, argv); } // Plumbing commands (executed by git, not by user): if (std::strcmp(command, "clean") == 0) { return clean(argc, argv); } if (std::strcmp(command, "smudge") == 0) { return smudge(argc, argv); } if (std::strcmp(command, "diff") == 0) { return diff(argc, argv); } } catch (const Option_error& e) { std::clog << "git-crypt: Error: " << e.option_name << ": " << e.message << std::endl; help_for_command(command, std::clog); return 2; } std::clog << "Error: '" << command << "' is not a git-crypt command. See 'git-crypt help'." << std::endl; return 2; } catch (const Error& e) { std::cerr << "git-crypt: Error: " << e.message << std::endl; return 1; } catch (const Gpg_error& e) { std::cerr << "git-crypt: GPG error: " << e.message << std::endl; return 1; } catch (const System_error& e) { std::cerr << "git-crypt: System error: " << e.message() << std::endl; return 1; } catch (const Crypto_error& e) { std::cerr << "git-crypt: Crypto error: " << e.where << ": " << e.message << std::endl; return 1; } catch (Key_file::Incompatible) { std::cerr << "git-crypt: This repository contains a incompatible key file. Please upgrade git-crypt." << std::endl; return 1; } catch (Key_file::Malformed) { std::cerr << "git-crypt: This repository contains a malformed key file. It may be corrupted." << std::endl; return 1; } catch (const std::ios_base::failure& e) { std::cerr << "git-crypt: I/O error: " << e.what() << std::endl; return 1; } git-crypt-0.5.0/git-crypt.hpp000066400000000000000000000026531253247362000161030ustar00rootroot00000000000000/* * Copyright 2014 Andrew Ayer * * This file is part of git-crypt. * * git-crypt 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. * * git-crypt 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 git-crypt. If not, see . * * Additional permission under GNU GPL version 3 section 7: * * If you modify the Program, or any covered work, by linking or * combining it with the OpenSSL project's OpenSSL library (or a * modified version of that library), containing parts covered by the * terms of the OpenSSL or SSLeay licenses, the licensors of the Program * grant you additional permission to convey the resulting work. * Corresponding Source for a non-source form of such a combination * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ #ifndef GIT_CRYPT_GIT_CRYPT_HPP #define GIT_CRYPT_GIT_CRYPT_HPP #define VERSION "0.5.0" extern const char* argv0; // initialized in main() to argv[0] #endif git-crypt-0.5.0/gpg.cpp000066400000000000000000000136501253247362000147300ustar00rootroot00000000000000/* * Copyright 2014 Andrew Ayer * * This file is part of git-crypt. * * git-crypt 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. * * git-crypt 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 git-crypt. If not, see . * * Additional permission under GNU GPL version 3 section 7: * * If you modify the Program, or any covered work, by linking or * combining it with the OpenSSL project's OpenSSL library (or a * modified version of that library), containing parts covered by the * terms of the OpenSSL or SSLeay licenses, the licensors of the Program * grant you additional permission to convey the resulting work. * Corresponding Source for a non-source form of such a combination * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ #include "gpg.hpp" #include "util.hpp" #include static std::string gpg_nth_column (const std::string& line, unsigned int col) { std::string::size_type pos = 0; for (unsigned int i = 0; i < col; ++i) { pos = line.find_first_of(':', pos); if (pos == std::string::npos) { throw Gpg_error("Malformed output from gpg"); } pos = pos + 1; } const std::string::size_type end_pos = line.find_first_of(':', pos); return end_pos != std::string::npos ? line.substr(pos, end_pos - pos) : line.substr(pos); } // given a key fingerprint, return the last 8 nibbles std::string gpg_shorten_fingerprint (const std::string& fingerprint) { return fingerprint.size() == 40 ? fingerprint.substr(32) : fingerprint; } // given a key fingerprint, return the key's UID (e.g. "John Smith ") std::string gpg_get_uid (const std::string& fingerprint) { // gpg --batch --with-colons --fixed-list-mode --list-keys 0x7A399B2DB06D039020CD1CE1D0F3702D61489532 std::vector command; command.push_back("gpg"); command.push_back("--batch"); command.push_back("--with-colons"); command.push_back("--fixed-list-mode"); command.push_back("--list-keys"); command.push_back("0x" + fingerprint); std::stringstream command_output; if (!successful_exit(exec_command(command, command_output))) { // This could happen if the keyring does not contain a public key with this fingerprint return ""; } while (command_output.peek() != -1) { std::string line; std::getline(command_output, line); if (line.substr(0, 4) == "uid:") { // uid:u::::1395975462::AB97D6E3E5D8789988CA55E5F77D9E7397D05229::John Smith : // want the 9th column (counting from 0) return gpg_nth_column(line, 9); } } return ""; } // return a list of fingerprints of public keys matching the given search query (such as jsmith@example.com) std::vector gpg_lookup_key (const std::string& query) { std::vector fingerprints; // gpg --batch --with-colons --fingerprint --list-keys jsmith@example.com std::vector command; command.push_back("gpg"); command.push_back("--batch"); command.push_back("--with-colons"); command.push_back("--fingerprint"); command.push_back("--list-keys"); command.push_back(query); std::stringstream command_output; if (successful_exit(exec_command(command, command_output))) { bool is_pubkey = false; while (command_output.peek() != -1) { std::string line; std::getline(command_output, line); if (line.substr(0, 4) == "pub:") { is_pubkey = true; } else if (line.substr(0, 4) == "sub:") { is_pubkey = false; } else if (is_pubkey && line.substr(0, 4) == "fpr:") { // fpr:::::::::7A399B2DB06D039020CD1CE1D0F3702D61489532: // want the 9th column (counting from 0) fingerprints.push_back(gpg_nth_column(line, 9)); } } } return fingerprints; } std::vector gpg_list_secret_keys () { // gpg --batch --with-colons --list-secret-keys --fingerprint std::vector command; command.push_back("gpg"); command.push_back("--batch"); command.push_back("--with-colons"); command.push_back("--list-secret-keys"); command.push_back("--fingerprint"); std::stringstream command_output; if (!successful_exit(exec_command(command, command_output))) { throw Gpg_error("gpg --list-secret-keys failed"); } std::vector secret_keys; while (command_output.peek() != -1) { std::string line; std::getline(command_output, line); if (line.substr(0, 4) == "fpr:") { // fpr:::::::::7A399B2DB06D039020CD1CE1D0F3702D61489532: // want the 9th column (counting from 0) secret_keys.push_back(gpg_nth_column(line, 9)); } } return secret_keys; } void gpg_encrypt_to_file (const std::string& filename, const std::string& recipient_fingerprint, bool key_is_trusted, const char* p, size_t len) { // gpg --batch -o FILENAME -r RECIPIENT -e std::vector command; command.push_back("gpg"); command.push_back("--batch"); if (key_is_trusted) { command.push_back("--trust-model"); command.push_back("always"); } command.push_back("-o"); command.push_back(filename); command.push_back("-r"); command.push_back("0x" + recipient_fingerprint); command.push_back("-e"); if (!successful_exit(exec_command_with_input(command, p, len))) { throw Gpg_error("Failed to encrypt"); } } void gpg_decrypt_from_file (const std::string& filename, std::ostream& output) { // gpg -q -d FILENAME std::vector command; command.push_back("gpg"); command.push_back("-q"); command.push_back("-d"); command.push_back(filename); if (!successful_exit(exec_command(command, output))) { throw Gpg_error("Failed to decrypt"); } } git-crypt-0.5.0/gpg.hpp000066400000000000000000000036761253247362000147440ustar00rootroot00000000000000/* * Copyright 2014 Andrew Ayer * * This file is part of git-crypt. * * git-crypt 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. * * git-crypt 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 git-crypt. If not, see . * * Additional permission under GNU GPL version 3 section 7: * * If you modify the Program, or any covered work, by linking or * combining it with the OpenSSL project's OpenSSL library (or a * modified version of that library), containing parts covered by the * terms of the OpenSSL or SSLeay licenses, the licensors of the Program * grant you additional permission to convey the resulting work. * Corresponding Source for a non-source form of such a combination * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ #ifndef GIT_CRYPT_GPG_HPP #define GIT_CRYPT_GPG_HPP #include #include #include struct Gpg_error { std::string message; explicit Gpg_error (std::string m) : message(m) { } }; std::string gpg_shorten_fingerprint (const std::string& fingerprint); std::string gpg_get_uid (const std::string& fingerprint); std::vector gpg_lookup_key (const std::string& query); std::vector gpg_list_secret_keys (); void gpg_encrypt_to_file (const std::string& filename, const std::string& recipient_fingerprint, bool key_is_trusted, const char* p, size_t len); void gpg_decrypt_from_file (const std::string& filename, std::ostream&); #endif git-crypt-0.5.0/key.cpp000066400000000000000000000202131253247362000147340ustar00rootroot00000000000000/* * Copyright 2014 Andrew Ayer * * This file is part of git-crypt. * * git-crypt 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. * * git-crypt 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 git-crypt. If not, see . * * Additional permission under GNU GPL version 3 section 7: * * If you modify the Program, or any covered work, by linking or * combining it with the OpenSSL project's OpenSSL library (or a * modified version of that library), containing parts covered by the * terms of the OpenSSL or SSLeay licenses, the licensors of the Program * grant you additional permission to convey the resulting work. * Corresponding Source for a non-source form of such a combination * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ #include "key.hpp" #include "util.hpp" #include "crypto.hpp" #include #include #include #include #include #include #include #include #include #include Key_file::Entry::Entry () { version = 0; explicit_memset(aes_key, 0, AES_KEY_LEN); explicit_memset(hmac_key, 0, HMAC_KEY_LEN); } void Key_file::Entry::load (std::istream& in) { while (true) { uint32_t field_id; if (!read_be32(in, field_id)) { throw Malformed(); } if (field_id == KEY_FIELD_END) { break; } uint32_t field_len; if (!read_be32(in, field_len)) { throw Malformed(); } if (field_id == KEY_FIELD_VERSION) { if (field_len != 4) { throw Malformed(); } if (!read_be32(in, version)) { throw Malformed(); } } else if (field_id == KEY_FIELD_AES_KEY) { if (field_len != AES_KEY_LEN) { throw Malformed(); } in.read(reinterpret_cast(aes_key), AES_KEY_LEN); if (in.gcount() != AES_KEY_LEN) { throw Malformed(); } } else if (field_id == KEY_FIELD_HMAC_KEY) { if (field_len != HMAC_KEY_LEN) { throw Malformed(); } in.read(reinterpret_cast(hmac_key), HMAC_KEY_LEN); if (in.gcount() != HMAC_KEY_LEN) { throw Malformed(); } } else if (field_id & 1) { // unknown critical field throw Incompatible(); } else { // unknown non-critical field - safe to ignore if (field_len > MAX_FIELD_LEN) { throw Malformed(); } in.ignore(field_len); if (in.gcount() != static_cast(field_len)) { throw Malformed(); } } } } void Key_file::Entry::load_legacy (uint32_t arg_version, std::istream& in) { version = arg_version; // First comes the AES key in.read(reinterpret_cast(aes_key), AES_KEY_LEN); if (in.gcount() != AES_KEY_LEN) { throw Malformed(); } // Then the HMAC key in.read(reinterpret_cast(hmac_key), HMAC_KEY_LEN); if (in.gcount() != HMAC_KEY_LEN) { throw Malformed(); } if (in.peek() != -1) { // Trailing data is a good indication that we are not actually reading a // legacy key file. (This is important to check since legacy key files // did not have any sort of file header.) throw Malformed(); } } void Key_file::Entry::store (std::ostream& out) const { // Version write_be32(out, KEY_FIELD_VERSION); write_be32(out, 4); write_be32(out, version); // AES key write_be32(out, KEY_FIELD_AES_KEY); write_be32(out, AES_KEY_LEN); out.write(reinterpret_cast(aes_key), AES_KEY_LEN); // HMAC key write_be32(out, KEY_FIELD_HMAC_KEY); write_be32(out, HMAC_KEY_LEN); out.write(reinterpret_cast(hmac_key), HMAC_KEY_LEN); // End write_be32(out, KEY_FIELD_END); } void Key_file::Entry::generate (uint32_t arg_version) { version = arg_version; random_bytes(aes_key, AES_KEY_LEN); random_bytes(hmac_key, HMAC_KEY_LEN); } const Key_file::Entry* Key_file::get_latest () const { return is_filled() ? get(latest()) : 0; } const Key_file::Entry* Key_file::get (uint32_t version) const { Map::const_iterator it(entries.find(version)); return it != entries.end() ? &it->second : 0; } void Key_file::add (const Entry& entry) { entries[entry.version] = entry; } void Key_file::load_legacy (std::istream& in) { entries[0].load_legacy(0, in); } void Key_file::load (std::istream& in) { unsigned char preamble[16]; in.read(reinterpret_cast(preamble), 16); if (in.gcount() != 16) { throw Malformed(); } if (std::memcmp(preamble, "\0GITCRYPTKEY", 12) != 0) { throw Malformed(); } if (load_be32(preamble + 12) != FORMAT_VERSION) { throw Incompatible(); } load_header(in); while (in.peek() != -1) { Entry entry; entry.load(in); add(entry); } } void Key_file::load_header (std::istream& in) { while (true) { uint32_t field_id; if (!read_be32(in, field_id)) { throw Malformed(); } if (field_id == HEADER_FIELD_END) { break; } uint32_t field_len; if (!read_be32(in, field_len)) { throw Malformed(); } if (field_id == HEADER_FIELD_KEY_NAME) { if (field_len > KEY_NAME_MAX_LEN) { throw Malformed(); } if (field_len == 0) { // special case field_len==0 to avoid possible undefined behavior // edge cases with an empty std::vector (particularly, &bytes[0]). key_name.clear(); } else { std::vector bytes(field_len); in.read(&bytes[0], field_len); if (in.gcount() != static_cast(field_len)) { throw Malformed(); } key_name.assign(&bytes[0], field_len); } if (!validate_key_name(key_name.c_str())) { key_name.clear(); throw Malformed(); } } else if (field_id & 1) { // unknown critical field throw Incompatible(); } else { // unknown non-critical field - safe to ignore if (field_len > MAX_FIELD_LEN) { throw Malformed(); } in.ignore(field_len); if (in.gcount() != static_cast(field_len)) { throw Malformed(); } } } } void Key_file::store (std::ostream& out) const { out.write("\0GITCRYPTKEY", 12); write_be32(out, FORMAT_VERSION); if (!key_name.empty()) { write_be32(out, HEADER_FIELD_KEY_NAME); write_be32(out, key_name.size()); out.write(key_name.data(), key_name.size()); } write_be32(out, HEADER_FIELD_END); for (Map::const_iterator it(entries.begin()); it != entries.end(); ++it) { it->second.store(out); } } bool Key_file::load_from_file (const char* key_file_name) { std::ifstream key_file_in(key_file_name, std::fstream::binary); if (!key_file_in) { return false; } load(key_file_in); return true; } bool Key_file::store_to_file (const char* key_file_name) const { create_protected_file(key_file_name); std::ofstream key_file_out(key_file_name, std::fstream::binary); if (!key_file_out) { return false; } store(key_file_out); key_file_out.close(); if (!key_file_out) { return false; } return true; } std::string Key_file::store_to_string () const { std::ostringstream ss; store(ss); return ss.str(); } void Key_file::generate () { uint32_t version(is_empty() ? 0 : latest() + 1); entries[version].generate(version); } uint32_t Key_file::latest () const { if (is_empty()) { throw std::invalid_argument("Key_file::latest"); } return entries.begin()->first; } bool validate_key_name (const char* key_name, std::string* reason) { if (!*key_name) { if (reason) { *reason = "Key name may not be empty"; } return false; } if (std::strcmp(key_name, "default") == 0) { if (reason) { *reason = "`default' is not a legal key name"; } return false; } // Need to be restrictive with key names because they're used as part of a Git filter name size_t len = 0; while (char c = *key_name++) { if (!std::isalnum(c) && c != '-' && c != '_') { if (reason) { *reason = "Key names may contain only A-Z, a-z, 0-9, '-', and '_'"; } return false; } if (++len > KEY_NAME_MAX_LEN) { if (reason) { *reason = "Key name is too long"; } return false; } } return true; } git-crypt-0.5.0/key.hpp000066400000000000000000000060301253247362000147420ustar00rootroot00000000000000/* * Copyright 2014 Andrew Ayer * * This file is part of git-crypt. * * git-crypt 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. * * git-crypt 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 git-crypt. If not, see . * * Additional permission under GNU GPL version 3 section 7: * * If you modify the Program, or any covered work, by linking or * combining it with the OpenSSL project's OpenSSL library (or a * modified version of that library), containing parts covered by the * terms of the OpenSSL or SSLeay licenses, the licensors of the Program * grant you additional permission to convey the resulting work. * Corresponding Source for a non-source form of such a combination * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ #ifndef GIT_CRYPT_KEY_HPP #define GIT_CRYPT_KEY_HPP #include #include #include #include #include enum { HMAC_KEY_LEN = 64, AES_KEY_LEN = 32 }; struct Key_file { public: struct Entry { uint32_t version; unsigned char aes_key[AES_KEY_LEN]; unsigned char hmac_key[HMAC_KEY_LEN]; Entry (); void load (std::istream&); void load_legacy (uint32_t version, std::istream&); void store (std::ostream&) const; void generate (uint32_t version); }; struct Malformed { }; // exception class struct Incompatible { }; // exception class const Entry* get_latest () const; const Entry* get (uint32_t version) const; void add (const Entry&); void load_legacy (std::istream&); void load (std::istream&); void store (std::ostream&) const; bool load_from_file (const char* filename); bool store_to_file (const char* filename) const; std::string store_to_string () const; void generate (); bool is_empty () const { return entries.empty(); } bool is_filled () const { return !is_empty(); } uint32_t latest () const; void set_key_name (const char* k) { key_name = k ? k : ""; } const char* get_key_name () const { return key_name.empty() ? 0 : key_name.c_str(); } private: typedef std::map > Map; enum { FORMAT_VERSION = 2 }; Map entries; std::string key_name; void load_header (std::istream&); enum { HEADER_FIELD_END = 0, HEADER_FIELD_KEY_NAME = 1 }; enum { KEY_FIELD_END = 0, KEY_FIELD_VERSION = 1, KEY_FIELD_AES_KEY = 3, KEY_FIELD_HMAC_KEY = 5 }; enum { MAX_FIELD_LEN = 1<<20 }; }; enum { KEY_NAME_MAX_LEN = 128 }; bool validate_key_name (const char* key_name, std::string* reason =0); #endif git-crypt-0.5.0/man/000077500000000000000000000000001253247362000142155ustar00rootroot00000000000000git-crypt-0.5.0/man/git-crypt.xml000066400000000000000000000406511253247362000166670ustar00rootroot00000000000000 git-crypt 2015-05-30 git-crypt 0.5.0 Andrew Ayer agwa@andrewayer.name https://www.agwa.name git-crypt 1 git-crypt transparent file encryption in Git git-crypt OPTIONS COMMAND ARGS Common commands git-crypt init git-crypt status git-crypt lock GPG commands git-crypt add-gpg-user GPG_USER_ID git-crypt unlock Symmetric key commands git-crypt export-key OUTPUT_KEY_FILE git-crypt unlock KEY_FILE Description git-crypt enables transparent encryption and decryption of files in a git repository. Files which you choose to protect are encrypted when committed, and decrypted when checked out. git-crypt lets you freely share a repository containing a mix of public and private content. git-crypt gracefully degrades, so developers without the secret key can still clone and commit to a repository with encrypted files. This lets you store your secret material (such as keys or passwords) in the same repository as your code, without requiring you to lock down your entire repository. Commands git-crypt is logically divided into several sub-commands which perform distinct tasks. Each sub-command, and its arguments, are documented below. Note that arguments and options to sub-commands must be specified on the command line after the name of the sub-command. Generate a key and prepare the current Git repository to use git-crypt. The following options are understood: KEY_NAME KEY_NAME Initialize the given key instead of the default key. git-crypt supports multiple keys per repository, allowing you to share different files with different sets of collaborators. Display a list of files in the repository, with their status (encrypted or unencrypted). The following options are understood: Show only encrypted files. Show only unencrypted files. Encrypt files that should be encrypted but were committed to the repository or added to the index without encryption. (This can happen if a file is added before git-crypt is initialized or before the file is added to the gitattributes file.) Add the users with the given GPG user IDs as collaborators. Specifically, git-crypt uses gpg1 to encrypt the shared symmetric key to the public keys of each GPG user ID, and stores the GPG-encrypted keys in the .git-crypt directory at the root of the repository. GPG_USER_ID can be a key ID, a full fingerprint, an email address, or anything else that uniquely identifies a public key to GPG (see "HOW TO SPECIFY A USER ID" in the gpg1 man page). The following options are understood: KEY_NAME KEY_NAME Grant access to the given key, rather than the default key. Don't automatically commit the changes to the .git-crypt directory. Assume that the GPG keys specified on the command line are trusted; i.e. they actually belong to the users that they claim to belong to. Without this option, git-crypt uses the same trust model as GPG, which is based on the Web of Trust by default. Under this model, git-crypt will reject GPG keys that do not have trusted signatures. If you don't want to use the Web of Trust, you can either change GPG's trust model by setting the option in ~/.gnupg/gpg.conf (see gpg1), or use the option to add-gpg-user on a case-by-case basis. Decrypt the repository. If one or more key files are specified on the command line, git-crypt attempts to decrypt using those shared symmetric keys. If no key files are specified, git-crypt attempts to decrypt using a GPG-encrypted key stored in the repository's .git-crypt directory. This command takes no options. Export the repository's shared symmetric key to the given file. The following options are understood: KEY_NAME KEY_NAME Export the given key, rather than the default key. Display help for the given COMMAND, or an overview of all commands if no command is specified. Print the currently-installed version of git-crypt. The format of the output is always "git-crypt", followed by a space, followed by the dotted version number. Using git-crypt First, you prepare a repository to use git-crypt by running git-crypt init. Then, you specify the files to encrypt by creating a gitattributes5 file. Each file which you want to encrypt should be assigned the "filter=git-crypt diff=git-crypt" attributes. For example: secretfile filter=git-crypt diff=git-crypt *.key filter=git-crypt diff=git-crypt Like a .gitignore file, .gitattributes files can match wildcards and should be checked into the repository. Make sure you don't accidentally encrypt the .gitattributes file itself (or other git files like .gitignore or .gitmodules). Make sure your .gitattributes rules are in place before you add sensitive files, or those files won't be encrypted! To share the repository with others (or with yourself) using GPG, run: git-crypt add-gpg-user GPG_USER_ID GPG_USER_ID can be a key ID, a full fingerprint, an email address, or anything else that uniquely identifies a public key to GPG. Note: git-crypt add-gpg-user will add and commit a GPG-encrypted key file in the .git-crypt directory of the root of your repository. Alternatively, you can export a symmetric secret key, which you must securely convey to collaborators (GPG is not required, and no files are added to your repository): git-crypt export-key /path/to/key After cloning a repository with encrypted files, unlock with with GPG: git-crypt unlock Or with a symmetric key: git-crypt unlock /path/to/key That's all you need to do - after git-crypt is set up (either with git-crypt init or git-crypt unlock), you can use git normally - encryption and decryption happen transparently. The .gitattributes file The .gitattributes file is documented in gitattributes5. The file pattern format is the same as the one used by .gitignore, as documented in gitignore5, with the exception that specifying merely a directory (e.g. "/dir/") is not sufficient to encrypt all files beneath it. Also note that the pattern "dir/*" does not match files under sub-directories of dir/. To encrypt an entire sub-tree dir/, place the following in dir/.gitattributes: * filter=git-crypt diff=git-crypt .gitattributes !filter !diff The second pattern is essential for ensuring that .gitattributes itself is not encrypted. Multiple Key Support In addition to the implicit default key, git-crypt supports alternative keys which can be used to encrypt specific files and can be shared with specific GPG users. This is useful if you want to grant different collaborators access to different sets of files. To generate an alternative key named KEYNAME, pass the -k KEYNAME option to git-crypt init as follows: git-crypt init -k KEYNAME To encrypt a file with an alternative key, use the git-crypt-KEYNAME filter in .gitattributes as follows: secretfile filter=git-crypt-KEYNAME diff=git-crypt-KEYNAME To export an alternative key or share it with a GPG user, pass the -k KEYNAME option to git-crypt export-key or git-crypt add-gpg-user as follows: git-crypt export-key -k KEYNAME /path/to/keyfile git-crypt add-gpg-user -k KEYNAME GPG_USER_ID To unlock a repository with an alternative key, use git-crypt unlock normally. git-crypt will automatically determine which key is being used. See Also git1, gitattributes5, git-crypt home page, GitHub repository git-crypt-0.5.0/man/man1/000077500000000000000000000000001253247362000150515ustar00rootroot00000000000000git-crypt-0.5.0/parse_options.cpp000066400000000000000000000063771253247362000170500ustar00rootroot00000000000000/* * Copyright 2014 Andrew Ayer * * 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. * * Except as contained in this notice, the name(s) of the above copyright * holders shall not be used in advertising or otherwise to promote the * sale, use or other dealings in this Software without prior written * authorization. */ #include "parse_options.hpp" #include static const Option_def* find_option (const Options_list& options, const std::string& name) { for (Options_list::const_iterator opt(options.begin()); opt != options.end(); ++opt) { if (opt->name == name) { return &*opt; } } return 0; } int parse_options (const Options_list& options, int argc, const char** argv) { int argi = 0; while (argi < argc && argv[argi][0] == '-') { if (std::strcmp(argv[argi], "--") == 0) { ++argi; break; } else if (std::strncmp(argv[argi], "--", 2) == 0) { std::string option_name; const char* option_value = 0; if (const char* eq = std::strchr(argv[argi], '=')) { option_name.assign(argv[argi], eq); option_value = eq + 1; } else { option_name = argv[argi]; } ++argi; const Option_def* opt(find_option(options, option_name)); if (!opt) { throw Option_error(option_name, "Invalid option"); } if (opt->is_set) { *opt->is_set = true; } if (opt->value) { if (option_value) { *opt->value = option_value; } else { if (argi >= argc) { throw Option_error(option_name, "Option requires a value"); } *opt->value = argv[argi]; ++argi; } } else { if (option_value) { throw Option_error(option_name, "Option takes no value"); } } } else { const char* arg = argv[argi] + 1; ++argi; while (*arg) { std::string option_name("-"); option_name.push_back(*arg); ++arg; const Option_def* opt(find_option(options, option_name)); if (!opt) { throw Option_error(option_name, "Invalid option"); } if (opt->is_set) { *opt->is_set = true; } if (opt->value) { if (*arg) { *opt->value = arg; } else { if (argi >= argc) { throw Option_error(option_name, "Option requires a value"); } *opt->value = argv[argi]; ++argi; } break; } } } } return argi; } git-crypt-0.5.0/parse_options.hpp000066400000000000000000000040531253247362000170420ustar00rootroot00000000000000/* * Copyright 2014 Andrew Ayer * * 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. * * Except as contained in this notice, the name(s) of the above copyright * holders shall not be used in advertising or otherwise to promote the * sale, use or other dealings in this Software without prior written * authorization. */ #ifndef PARSE_OPTIONS_HPP #define PARSE_OPTIONS_HPP #include #include struct Option_def { std::string name; bool* is_set; const char** value; Option_def () : is_set(0), value(0) { } Option_def (const std::string& arg_name, bool* arg_is_set) : name(arg_name), is_set(arg_is_set), value(0) { } Option_def (const std::string& arg_name, const char** arg_value) : name(arg_name), is_set(0), value(arg_value) { } }; typedef std::vector Options_list; int parse_options (const Options_list& options, int argc, const char** argv); struct Option_error { std::string option_name; std::string message; Option_error (const std::string& n, const std::string& m) : option_name(n), message(m) { } }; #endif git-crypt-0.5.0/util-unix.cpp000066400000000000000000000143101253247362000161030ustar00rootroot00000000000000/* * Copyright 2012, 2014 Andrew Ayer * * This file is part of git-crypt. * * git-crypt 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. * * git-crypt 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 git-crypt. If not, see . * * Additional permission under GNU GPL version 3 section 7: * * If you modify the Program, or any covered work, by linking or * combining it with the OpenSSL project's OpenSSL library (or a * modified version of that library), containing parts covered by the * terms of the OpenSSL or SSLeay licenses, the licensors of the Program * grant you additional permission to convey the resulting work. * Corresponding Source for a non-source form of such a combination * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include std::string System_error::message () const { std::string mesg(action); if (!target.empty()) { mesg += ": "; mesg += target; } if (error) { mesg += ": "; mesg += strerror(error); } return mesg; } void temp_fstream::open (std::ios_base::openmode mode) { close(); const char* tmpdir = getenv("TMPDIR"); size_t tmpdir_len = tmpdir ? std::strlen(tmpdir) : 0; if (tmpdir_len == 0 || tmpdir_len > 4096) { // no $TMPDIR or it's excessively long => fall back to /tmp tmpdir = "/tmp"; tmpdir_len = 4; } std::vector path_buffer(tmpdir_len + 18); char* path = &path_buffer[0]; std::strcpy(path, tmpdir); std::strcpy(path + tmpdir_len, "/git-crypt.XXXXXX"); mode_t old_umask = umask(0077); int fd = mkstemp(path); if (fd == -1) { int mkstemp_errno = errno; umask(old_umask); throw System_error("mkstemp", "", mkstemp_errno); } umask(old_umask); std::fstream::open(path, mode); if (!std::fstream::is_open()) { unlink(path); ::close(fd); throw System_error("std::fstream::open", path, 0); } unlink(path); ::close(fd); } void temp_fstream::close () { if (std::fstream::is_open()) { std::fstream::close(); } } void mkdir_parent (const std::string& path) { std::string::size_type slash(path.find('/', 1)); while (slash != std::string::npos) { std::string prefix(path.substr(0, slash)); struct stat status; if (stat(prefix.c_str(), &status) == 0) { // already exists - make sure it's a directory if (!S_ISDIR(status.st_mode)) { throw System_error("mkdir_parent", prefix, ENOTDIR); } } else { if (errno != ENOENT) { throw System_error("mkdir_parent", prefix, errno); } // doesn't exist - mkdir it if (mkdir(prefix.c_str(), 0777) == -1) { throw System_error("mkdir", prefix, errno); } } slash = path.find('/', slash + 1); } } static std::string readlink (const char* pathname) { std::vector buffer(64); ssize_t len; while ((len = ::readlink(pathname, &buffer[0], buffer.size())) == static_cast(buffer.size())) { // buffer may have been truncated - grow and try again buffer.resize(buffer.size() * 2); } if (len == -1) { throw System_error("readlink", pathname, errno); } return std::string(buffer.begin(), buffer.begin() + len); } std::string our_exe_path () { try { return readlink("/proc/self/exe"); } catch (const System_error&) { if (argv0[0] == '/') { // argv[0] starts with / => it's an absolute path return argv0; } else if (std::strchr(argv0, '/')) { // argv[0] contains / => it a relative path that should be resolved char* resolved_path_p = realpath(argv0, NULL); std::string resolved_path(resolved_path_p); free(resolved_path_p); return resolved_path; } else { // argv[0] is just a bare filename => not much we can do return argv0; } } } int exit_status (int wait_status) { return wait_status != -1 && WIFEXITED(wait_status) ? WEXITSTATUS(wait_status) : -1; } void touch_file (const std::string& filename) { if (utimes(filename.c_str(), NULL) == -1 && errno != ENOENT) { throw System_error("utimes", filename, errno); } } void remove_file (const std::string& filename) { if (unlink(filename.c_str()) == -1 && errno != ENOENT) { throw System_error("unlink", filename, errno); } } static void init_std_streams_platform () { } void create_protected_file (const char* path) { int fd = open(path, O_WRONLY | O_CREAT, 0600); if (fd == -1) { throw System_error("open", path, errno); } close(fd); } int util_rename (const char* from, const char* to) { return rename(from, to); } static size_t sizeof_dirent_for (DIR* p) { long name_max = fpathconf(dirfd(p), _PC_NAME_MAX); if (name_max == -1) { #ifdef NAME_MAX name_max = NAME_MAX; #else name_max = 255; #endif } return offsetof(struct dirent, d_name) + name_max + 1; // final +1 is for d_name's null terminator } std::vector get_directory_contents (const char* path) { std::vector contents; DIR* dir = opendir(path); if (!dir) { throw System_error("opendir", path, errno); } try { std::vector buffer(sizeof_dirent_for(dir)); struct dirent* dirent_buffer = reinterpret_cast(&buffer[0]); struct dirent* ent = NULL; int err = 0; while ((err = readdir_r(dir, dirent_buffer, &ent)) == 0 && ent != NULL) { if (std::strcmp(ent->d_name, ".") == 0 || std::strcmp(ent->d_name, "..") == 0) { continue; } contents.push_back(ent->d_name); } if (err != 0) { throw System_error("readdir_r", path, errno); } } catch (...) { closedir(dir); throw; } closedir(dir); std::sort(contents.begin(), contents.end()); return contents; } git-crypt-0.5.0/util-win32.cpp000066400000000000000000000130501253247362000160620ustar00rootroot00000000000000/* * Copyright 2014 Andrew Ayer * * This file is part of git-crypt. * * git-crypt 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. * * git-crypt 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 git-crypt. If not, see . * * Additional permission under GNU GPL version 3 section 7: * * If you modify the Program, or any covered work, by linking or * combining it with the OpenSSL project's OpenSSL library (or a * modified version of that library), containing parts covered by the * terms of the OpenSSL or SSLeay licenses, the licensors of the Program * grant you additional permission to convey the resulting work. * Corresponding Source for a non-source form of such a combination * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ #include #include #include #include #include #include std::string System_error::message () const { std::string mesg(action); if (!target.empty()) { mesg += ": "; mesg += target; } if (error) { LPTSTR error_message; FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast(&error_message), 0, NULL); mesg += error_message; LocalFree(error_message); } return mesg; } void temp_fstream::open (std::ios_base::openmode mode) { close(); char tmpdir[MAX_PATH + 1]; DWORD ret = GetTempPath(sizeof(tmpdir), tmpdir); if (ret == 0) { throw System_error("GetTempPath", "", GetLastError()); } else if (ret > sizeof(tmpdir) - 1) { throw System_error("GetTempPath", "", ERROR_BUFFER_OVERFLOW); } char tmpfilename[MAX_PATH + 1]; if (GetTempFileName(tmpdir, TEXT("git-crypt"), 0, tmpfilename) == 0) { throw System_error("GetTempFileName", "", GetLastError()); } filename = tmpfilename; std::fstream::open(filename.c_str(), mode); if (!std::fstream::is_open()) { DeleteFile(filename.c_str()); throw System_error("std::fstream::open", filename, 0); } } void temp_fstream::close () { if (std::fstream::is_open()) { std::fstream::close(); DeleteFile(filename.c_str()); } } void mkdir_parent (const std::string& path) { std::string::size_type slash(path.find('/', 1)); while (slash != std::string::npos) { std::string prefix(path.substr(0, slash)); if (GetFileAttributes(prefix.c_str()) == INVALID_FILE_ATTRIBUTES) { // prefix does not exist, so try to create it if (!CreateDirectory(prefix.c_str(), NULL)) { throw System_error("CreateDirectory", prefix, GetLastError()); } } slash = path.find('/', slash + 1); } } std::string our_exe_path () { std::vector buffer(128); size_t len; while ((len = GetModuleFileNameA(NULL, &buffer[0], buffer.size())) == buffer.size()) { // buffer may have been truncated - grow and try again buffer.resize(buffer.size() * 2); } if (len == 0) { throw System_error("GetModuleFileNameA", "", GetLastError()); } return std::string(buffer.begin(), buffer.begin() + len); } int exit_status (int status) { return status; } void touch_file (const std::string& filename) { HANDLE fh = CreateFileA(filename.c_str(), FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if (fh == INVALID_HANDLE_VALUE) { DWORD error = GetLastError(); if (error == ERROR_FILE_NOT_FOUND) { return; } else { throw System_error("CreateFileA", filename, error); } } SYSTEMTIME system_time; GetSystemTime(&system_time); FILETIME file_time; SystemTimeToFileTime(&system_time, &file_time); if (!SetFileTime(fh, NULL, NULL, &file_time)) { DWORD error = GetLastError(); CloseHandle(fh); throw System_error("SetFileTime", filename, error); } CloseHandle(fh); } void remove_file (const std::string& filename) { if (!DeleteFileA(filename.c_str())) { DWORD error = GetLastError(); if (error == ERROR_FILE_NOT_FOUND) { return; } else { throw System_error("DeleteFileA", filename, error); } } } static void init_std_streams_platform () { _setmode(_fileno(stdin), _O_BINARY); _setmode(_fileno(stdout), _O_BINARY); } void create_protected_file (const char* path) // TODO { } int util_rename (const char* from, const char* to) { // On Windows OS, it is necessary to ensure target file doesn't exist unlink(to); return rename(from, to); } std::vector get_directory_contents (const char* path) { std::vector filenames; std::string patt(path); if (!patt.empty() && patt[patt.size() - 1] != '/' && patt[patt.size() - 1] != '\\') { patt.push_back('\\'); } patt.push_back('*'); WIN32_FIND_DATAA ffd; HANDLE h = FindFirstFileA(patt.c_str(), &ffd); if (h == INVALID_HANDLE_VALUE) { throw System_error("FindFirstFileA", patt, GetLastError()); } do { if (std::strcmp(ffd.cFileName, ".") != 0 && std::strcmp(ffd.cFileName, "..") != 0) { filenames.push_back(ffd.cFileName); } } while (FindNextFileA(h, &ffd) != 0); DWORD err = GetLastError(); if (err != ERROR_NO_MORE_FILES) { throw System_error("FileNextFileA", patt, err); } FindClose(h); return filenames; } git-crypt-0.5.0/util.cpp000066400000000000000000000077551253247362000151410ustar00rootroot00000000000000/* * Copyright 2012, 2014 Andrew Ayer * * This file is part of git-crypt. * * git-crypt 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. * * git-crypt 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 git-crypt. If not, see . * * Additional permission under GNU GPL version 3 section 7: * * If you modify the Program, or any covered work, by linking or * combining it with the OpenSSL project's OpenSSL library (or a * modified version of that library), containing parts covered by the * terms of the OpenSSL or SSLeay licenses, the licensors of the Program * grant you additional permission to convey the resulting work. * Corresponding Source for a non-source form of such a combination * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ #include "git-crypt.hpp" #include "util.hpp" #include "coprocess.hpp" #include #include int exec_command (const std::vector& args) { Coprocess proc; proc.spawn(args); return proc.wait(); } int exec_command (const std::vector& args, std::ostream& output) { Coprocess proc; std::istream* proc_stdout = proc.stdout_pipe(); proc.spawn(args); output << proc_stdout->rdbuf(); return proc.wait(); } int exec_command_with_input (const std::vector& args, const char* p, size_t len) { Coprocess proc; std::ostream* proc_stdin = proc.stdin_pipe(); proc.spawn(args); proc_stdin->write(p, len); proc.close_stdin(); return proc.wait(); } std::string escape_shell_arg (const std::string& str) { std::string new_str; new_str.push_back('"'); for (std::string::const_iterator it(str.begin()); it != str.end(); ++it) { if (*it == '"' || *it == '\\' || *it == '$' || *it == '`') { new_str.push_back('\\'); } new_str.push_back(*it); } new_str.push_back('"'); return new_str; } uint32_t load_be32 (const unsigned char* p) { return (static_cast(p[3]) << 0) | (static_cast(p[2]) << 8) | (static_cast(p[1]) << 16) | (static_cast(p[0]) << 24); } void store_be32 (unsigned char* p, uint32_t i) { p[3] = i; i >>= 8; p[2] = i; i >>= 8; p[1] = i; i >>= 8; p[0] = i; } bool read_be32 (std::istream& in, uint32_t& i) { unsigned char buffer[4]; in.read(reinterpret_cast(buffer), 4); if (in.gcount() != 4) { return false; } i = load_be32(buffer); return true; } void write_be32 (std::ostream& out, uint32_t i) { unsigned char buffer[4]; store_be32(buffer, i); out.write(reinterpret_cast(buffer), 4); } void* explicit_memset (void* s, int c, std::size_t n) { volatile unsigned char* p = reinterpret_cast(s); while (n--) { *p++ = c; } return s; } static bool leakless_equals_char (const unsigned char* a, const unsigned char* b, std::size_t len) { volatile int diff = 0; while (len > 0) { diff |= *a++ ^ *b++; --len; } return diff == 0; } bool leakless_equals (const void* a, const void* b, std::size_t len) { return leakless_equals_char(reinterpret_cast(a), reinterpret_cast(b), len); } static void init_std_streams_platform (); // platform-specific initialization void init_std_streams () { // The following two lines are essential for achieving good performance: std::ios_base::sync_with_stdio(false); std::cin.tie(0); std::cin.exceptions(std::ios_base::badbit); std::cout.exceptions(std::ios_base::badbit); init_std_streams_platform(); } #ifdef _WIN32 #include "util-win32.cpp" #else #include "util-unix.cpp" #endif git-crypt-0.5.0/util.hpp000066400000000000000000000062311253247362000151320ustar00rootroot00000000000000/* * Copyright 2012, 2014 Andrew Ayer * * This file is part of git-crypt. * * git-crypt 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. * * git-crypt 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 git-crypt. If not, see . * * Additional permission under GNU GPL version 3 section 7: * * If you modify the Program, or any covered work, by linking or * combining it with the OpenSSL project's OpenSSL library (or a * modified version of that library), containing parts covered by the * terms of the OpenSSL or SSLeay licenses, the licensors of the Program * grant you additional permission to convey the resulting work. * Corresponding Source for a non-source form of such a combination * shall include the source code for the parts of OpenSSL used as well * as that of the covered work. */ #ifndef GIT_CRYPT_UTIL_HPP #define GIT_CRYPT_UTIL_HPP #include #include #include #include #include #include #include struct System_error { std::string action; std::string target; int error; System_error (const std::string& a, const std::string& t, int e) : action(a), target(t), error(e) { } std::string message () const; }; class temp_fstream : public std::fstream { std::string filename; public: ~temp_fstream () { close(); } void open (std::ios_base::openmode); void close (); }; void mkdir_parent (const std::string& path); // Create parent directories of path, __but not path itself__ std::string our_exe_path (); int exec_command (const std::vector&); int exec_command (const std::vector&, std::ostream& output); int exec_command_with_input (const std::vector&, const char* p, size_t len); int exit_status (int wait_status); // returns -1 if process did not exit (but was signaled, etc.) inline bool successful_exit (int wait_status) { return exit_status(wait_status) == 0; } void touch_file (const std::string&); // ignores non-existent files void remove_file (const std::string&); // ignores non-existent files std::string escape_shell_arg (const std::string&); uint32_t load_be32 (const unsigned char*); void store_be32 (unsigned char*, uint32_t); bool read_be32 (std::istream& in, uint32_t&); void write_be32 (std::ostream& out, uint32_t); void* explicit_memset (void* s, int c, size_t n); // memset that won't be optimized away bool leakless_equals (const void* a, const void* b, size_t len); // compare bytes w/o leaking timing void init_std_streams (); void create_protected_file (const char* path); // create empty file accessible only by current user int util_rename (const char*, const char*); std::vector get_directory_contents (const char* path); #endif