├── AUTHORS ├── CONTRIBUTING.md ├── COPYING ├── INSTALL ├── INSTALL.md ├── Makefile ├── NEWS ├── NEWS.md ├── README ├── README.md ├── RELEASE_NOTES-0.4.1.md ├── RELEASE_NOTES-0.4.md ├── THANKS.md ├── commands.cpp ├── commands.hpp ├── coprocess-unix.cpp ├── coprocess-unix.hpp ├── coprocess-win32.cpp ├── coprocess-win32.hpp ├── coprocess.cpp ├── coprocess.hpp ├── crypto-openssl-10.cpp ├── crypto-openssl-11.cpp ├── crypto.cpp ├── crypto.hpp ├── doc └── multiple_keys.md ├── fhstream.cpp ├── fhstream.hpp ├── git-crypt.cpp ├── git-crypt.hpp ├── gpg.cpp ├── gpg.hpp ├── key.cpp ├── key.hpp ├── man └── git-crypt.xml ├── parse_options.cpp ├── parse_options.hpp ├── util-unix.cpp ├── util-win32.cpp ├── util.cpp └── util.hpp /AUTHORS: -------------------------------------------------------------------------------- 1 | Andrew Ayer 2 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Thanks for your interest in contributing to git-crypt! git-crypt is 2 | open source software and welcomes contributions in the form of code, 3 | documentation, bug reports, or anything else that improves git-crypt. 4 | 5 | When contributing code, please consider the following guidelines: 6 | 7 | * You are encouraged to open an issue on GitHub to discuss any non-trivial 8 | changes before you start coding. 9 | 10 | * Please mimic the existing code style as much as possible. In 11 | particular, please indent code using tab characters with a width 12 | of 8. 13 | 14 | * To minimize merge commits, please rebase your changes before opening 15 | a pull request. 16 | 17 | * To submit your patch, open a pull request on GitHub. 18 | 19 | Finally, be aware that since git-crypt is security-sensitive software, 20 | the bar for contributions is higher than average. Please don't be 21 | discouraged by this, but be prepared for patches to possibly go through 22 | several rounds of feedback and improvement before being accepted. 23 | Your patience and understanding is appreciated. 24 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /INSTALL: -------------------------------------------------------------------------------- 1 | DEPENDENCIES 2 | 3 | To build git-crypt, you need: 4 | 5 | Debian/Ubuntu package RHEL/CentOS package 6 | ----------------------------------------------------------------------------- 7 | Make make make 8 | A C++11 compiler (e.g. gcc 4.9+) g++ gcc-c++ 9 | OpenSSL development files libssl-dev openssl-devel 10 | 11 | 12 | To use git-crypt, you need: 13 | 14 | Debian/Ubuntu package RHEL/CentOS package 15 | ----------------------------------------------------------------------------- 16 | Git 1.7.2 or newer git git 17 | OpenSSL openssl openssl 18 | 19 | Note: Git 1.8.5 or newer is recommended for best performance. 20 | 21 | 22 | BUILDING GIT-CRYPT 23 | 24 | Run: 25 | 26 | $ make 27 | $ make install 28 | 29 | To install to a specific location: 30 | 31 | $ make install PREFIX=/usr/local 32 | 33 | Or, just copy the git-crypt binary to wherever is most convenient for you. 34 | 35 | 36 | BUILDING THE MAN PAGE 37 | 38 | To build and install the git-crypt(1) man page, pass ENABLE_MAN=yes to make: 39 | 40 | $ make ENABLE_MAN=yes 41 | $ make ENABLE_MAN=yes install 42 | 43 | xsltproc is required to build the man page. Note that xsltproc will access 44 | the Internet to retrieve its stylesheet unless the Docbook stylesheet is 45 | installed locally and registered in the system's XML catalog. 46 | 47 | 48 | BUILDING A DEBIAN PACKAGE 49 | 50 | Debian packaging can be found in the 'debian' branch of the project 51 | Git repository. The package is built using git-buildpackage as follows: 52 | 53 | $ git checkout debian 54 | $ git-buildpackage -uc -us 55 | 56 | 57 | INSTALLING ON MAC OS X 58 | 59 | Using the brew package manager, simply run: 60 | 61 | $ brew install git-crypt 62 | 63 | 64 | EXPERIMENTAL WINDOWS SUPPORT 65 | 66 | git-crypt should build on Windows with MinGW, although the build system 67 | is not yet finalized so you will need to pass your own CXX, CXXFLAGS, and 68 | LDFLAGS variables to make. Additionally, Windows support is less tested 69 | and does not currently create key files with restrictive permissions, 70 | making it unsuitable for use on a multi-user system. Windows support 71 | will mature in a future version of git-crypt. Bug reports and patches 72 | are most welcome! 73 | -------------------------------------------------------------------------------- /INSTALL.md: -------------------------------------------------------------------------------- 1 | ### Dependencies 2 | 3 | To build git-crypt, you need: 4 | 5 | | Software | Debian/Ubuntu package | RHEL/CentOS package| 6 | |---------------------------------|-----------------------|--------------------| 7 | |Make | make | make | 8 | |A C++11 compiler (e.g. gcc 4.9+) | g++ | gcc-c++ | 9 | |OpenSSL development files | libssl-dev | openssl-devel | 10 | 11 | 12 | To use git-crypt, you need: 13 | 14 | | Software | Debian/Ubuntu package | RHEL/CentOS package| 15 | |---------------------------------|-----------------------|--------------------| 16 | |Git 1.7.2 or newer | git | git | 17 | |OpenSSL | openssl | openssl | 18 | 19 | Note: Git 1.8.5 or newer is recommended for best performance. 20 | 21 | 22 | ### Building git-crypt 23 | 24 | Run: 25 | 26 | make 27 | make install 28 | 29 | To install to a specific location: 30 | 31 | make install PREFIX=/usr/local 32 | 33 | Or, just copy the git-crypt binary to wherever is most convenient for you. 34 | 35 | 36 | ### Building The Man Page 37 | 38 | To build and install the git-crypt(1) man page, pass `ENABLE_MAN=yes` to make: 39 | 40 | make ENABLE_MAN=yes 41 | make ENABLE_MAN=yes install 42 | 43 | xsltproc is required to build the man page. Note that xsltproc will access 44 | the Internet to retrieve its stylesheet unless the Docbook stylesheet is 45 | installed locally and registered in the system's XML catalog. 46 | 47 | 48 | ### Building A Debian Package 49 | 50 | Debian packaging can be found in the 'debian' branch of the project Git 51 | repository. The package is built using git-buildpackage as follows: 52 | 53 | git checkout debian 54 | git-buildpackage -uc -us 55 | 56 | 57 | ### Installing On Mac OS X 58 | 59 | Using the brew package manager, simply run: 60 | 61 | brew install git-crypt 62 | 63 | ### Experimental Windows Support 64 | 65 | git-crypt should build on Windows with MinGW, although the build system 66 | is not yet finalized so you will need to pass your own CXX, CXXFLAGS, and 67 | LDFLAGS variables to make. Additionally, Windows support is less tested 68 | and does not currently create key files with restrictive permissions, 69 | making it unsuitable for use on a multi-user system. Windows support 70 | will mature in a future version of git-crypt. Bug reports and patches 71 | are most welcome! 72 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2015 Andrew Ayer 3 | # 4 | # See COPYING file for license information. 5 | # 6 | 7 | CXXFLAGS ?= -Wall -pedantic -Wno-long-long -O2 8 | CXXFLAGS += -std=c++11 9 | PREFIX ?= /usr/local 10 | BINDIR ?= $(PREFIX)/bin 11 | MANDIR ?= $(PREFIX)/share/man 12 | 13 | ENABLE_MAN ?= no 14 | DOCBOOK_XSL ?= http://docbook.sourceforge.net/release/xsl/current/manpages/docbook.xsl 15 | 16 | OBJFILES = \ 17 | git-crypt.o \ 18 | commands.o \ 19 | crypto.o \ 20 | gpg.o \ 21 | key.o \ 22 | util.o \ 23 | parse_options.o \ 24 | coprocess.o \ 25 | fhstream.o 26 | 27 | OBJFILES += crypto-openssl-10.o crypto-openssl-11.o 28 | LDFLAGS += -lcrypto 29 | 30 | XSLTPROC ?= xsltproc 31 | DOCBOOK_FLAGS += --param man.output.in.separate.dir 1 \ 32 | --stringparam man.output.base.dir man/ \ 33 | --param man.output.subdirs.enabled 1 \ 34 | --param man.authors.section.enabled 1 35 | 36 | all: build 37 | 38 | # 39 | # Build 40 | # 41 | BUILD_MAN_TARGETS-yes = build-man 42 | BUILD_MAN_TARGETS-no = 43 | BUILD_TARGETS := build-bin $(BUILD_MAN_TARGETS-$(ENABLE_MAN)) 44 | 45 | build: $(BUILD_TARGETS) 46 | 47 | build-bin: git-crypt 48 | 49 | git-crypt: $(OBJFILES) 50 | $(CXX) $(CXXFLAGS) -o $@ $(OBJFILES) $(LDFLAGS) 51 | 52 | util.o: util.cpp util-unix.cpp util-win32.cpp 53 | coprocess.o: coprocess.cpp coprocess-unix.cpp coprocess-win32.cpp 54 | 55 | build-man: man/man1/git-crypt.1 56 | 57 | man/man1/git-crypt.1: man/git-crypt.xml 58 | $(XSLTPROC) $(DOCBOOK_FLAGS) $(DOCBOOK_XSL) man/git-crypt.xml 59 | 60 | # 61 | # Clean 62 | # 63 | CLEAN_MAN_TARGETS-yes = clean-man 64 | CLEAN_MAN_TARGETS-no = 65 | CLEAN_TARGETS := clean-bin $(CLEAN_MAN_TARGETS-$(ENABLE_MAN)) 66 | 67 | clean: $(CLEAN_TARGETS) 68 | 69 | clean-bin: 70 | rm -f $(OBJFILES) git-crypt 71 | 72 | clean-man: 73 | rm -f man/man1/git-crypt.1 74 | 75 | # 76 | # Install 77 | # 78 | INSTALL_MAN_TARGETS-yes = install-man 79 | INSTALL_MAN_TARGETS-no = 80 | INSTALL_TARGETS := install-bin $(INSTALL_MAN_TARGETS-$(ENABLE_MAN)) 81 | 82 | install: $(INSTALL_TARGETS) 83 | 84 | install-bin: build-bin 85 | install -d $(DESTDIR)$(BINDIR) 86 | install -m 755 git-crypt $(DESTDIR)$(BINDIR)/ 87 | 88 | install-man: build-man 89 | install -d $(DESTDIR)$(MANDIR)/man1 90 | install -m 644 man/man1/git-crypt.1 $(DESTDIR)$(MANDIR)/man1/ 91 | 92 | .PHONY: all \ 93 | build build-bin build-man \ 94 | clean clean-bin clean-man \ 95 | install install-bin install-man 96 | -------------------------------------------------------------------------------- /NEWS: -------------------------------------------------------------------------------- 1 | v0.7.0 (2022-04-21) 2 | * Avoid "argument list too long" errors on macOS. 3 | * Fix handling of "-" arguments. 4 | * Minor documentation improvements. 5 | 6 | v0.6.0 (2017-11-26) 7 | * Add support for OpenSSL 1.1 (still works with OpenSSL 1.0). 8 | * Switch to C++11 (gcc 4.9 or higher now required to build). 9 | * Allow GPG to fail on some keys (makes unlock work better if there are 10 | multiple keys that can unlock the repo but only some are available). 11 | * Allow the repo state directory to be configured with the 12 | git-crypt.repoStateDir git config option. 13 | * Respect the gpg.program git config option. 14 | * Don't hard code path to git-crypt in .git/config on Linux (ensures 15 | repo continues to work if git-crypt is moved). 16 | * Ensure git-crypt's gpg files won't be treated as text by Git. 17 | * Minor improvements to build system, documentation. 18 | 19 | v0.5.0 (2015-05-30) 20 | * Drastically speed up lock/unlock when used with Git 1.8.5 or newer. 21 | * Add git-crypt(1) man page (pass ENABLE_MAN=yes to make to build). 22 | * Add --trusted option to 'git-crypt gpg-add-user' to add user even if 23 | GPG doesn't trust user's key. 24 | * Improve 'git-crypt lock' usability, add --force option. 25 | * Ignore symlinks and other non-files when running 'git-crypt status'. 26 | * Fix compilation on old versions of Mac OS X. 27 | * Fix GPG mode when with-fingerprint enabled in gpg.conf. 28 | * Minor bug fixes and improvements to help/error messages. 29 | 30 | v0.4.2 (2015-01-31) 31 | * Fix unlock and lock under Git 2.2.2 and higher. 32 | * Drop support for versions of Git older than 1.7.2. 33 | * Minor improvements to some help/error messages. 34 | 35 | v0.4.1 (2015-01-08) 36 | * Important usability fix to ensure that the .git-crypt directory 37 | can't be encrypted by accident (see RELEASE_NOTES-0.4.1.md for 38 | more information). 39 | 40 | v0.4 (2014-11-16) 41 | (See RELEASE_NOTES-0.4.md for important details.) 42 | * Add optional GPG support: GPG can be used to share the repository 43 | between one or more users in lieu of sharing a secret key. 44 | * New workflow: the symmetric key is now stored inside the .git 45 | directory. Although backwards compatibility has been preserved 46 | with repositories created by old versions of git-crypt, the 47 | commands for setting up a repository have changed. See the 48 | release notes file for details. 49 | * Multiple key support: it's now possible to encrypt different parts 50 | of a repository with different keys. 51 | * Initial 'git-crypt status' command to report which files are 52 | encrypted and to fix problems that are detected. 53 | * Numerous usability, documentation, and error reporting improvements. 54 | * Major internal code improvements that will make future development 55 | easier. 56 | * Initial experimental Windows support. 57 | 58 | v0.3 (2013-04-05) 59 | * Fix 'git-crypt init' on newer versions of Git. Previously, 60 | encrypted files were not being automatically decrypted after 61 | running 'git-crypt init' with recent versions of Git. 62 | * Allow 'git-crypt init' to be run even if the working tree contains 63 | untracked files. 64 | * 'git-crypt init' now properly escapes arguments to the filter 65 | commands it configures, allowing both the path to git-crypt and the 66 | path to the key file to contain arbitrary characters such as spaces. 67 | 68 | v0.2 (2013-01-25) 69 | * Numerous improvements to 'git-crypt init' usability. 70 | * Fix gitattributes example in README: the old example showed a colon 71 | after the filename where there shouldn't be one. 72 | * Various build fixes and improvements. 73 | 74 | v0.1 (2012-11-29) 75 | * Initial release. 76 | -------------------------------------------------------------------------------- /NEWS.md: -------------------------------------------------------------------------------- 1 | News 2 | ==== 3 | 4 | ######v0.7.0 (2022-04-21) 5 | * Avoid "argument list too long" errors on macOS. 6 | * Fix handling of "-" arguments. 7 | * Minor documentation improvements. 8 | 9 | ######v0.6.0 (2017-11-26) 10 | * Add support for OpenSSL 1.1 (still works with OpenSSL 1.0). 11 | * Switch to C++11 (gcc 4.9 or higher now required to build). 12 | * Allow GPG to fail on some keys (makes unlock work better if there are 13 | multiple keys that can unlock the repo but only some are available). 14 | * Allow the repo state directory to be configured with the 15 | git-crypt.repoStateDir git config option. 16 | * Respect the gpg.program git config option. 17 | * Don't hard code path to git-crypt in .git/config on Linux (ensures 18 | repo continues to work if git-crypt is moved). 19 | * Ensure git-crypt's gpg files won't be treated as text by Git. 20 | * Minor improvements to build system, documentation. 21 | 22 | ######v0.5.0 (2015-05-30) 23 | * Drastically speed up lock/unlock when used with Git 1.8.5 or newer. 24 | * Add git-crypt(1) man page (pass `ENABLE_MAN=yes` to make to build). 25 | * Add --trusted option to `git-crypt gpg-add-user` to add user even if 26 | GPG doesn't trust user's key. 27 | * Improve `git-crypt lock` usability, add --force option. 28 | * Ignore symlinks and other non-files when running `git-crypt status`. 29 | * Fix compilation on old versions of Mac OS X. 30 | * Fix GPG mode when with-fingerprint enabled in gpg.conf. 31 | * Minor bug fixes and improvements to help/error messages. 32 | 33 | ######v0.4.2 (2015-01-31) 34 | * Fix unlock and lock under Git 2.2.2 and higher. 35 | * Drop support for versions of Git older than 1.7.2. 36 | * Minor improvements to some help/error messages. 37 | 38 | ######v0.4.1 (2015-01-08) 39 | * Important usability fix to ensure that the .git-crypt directory 40 | can't be encrypted by accident (see 41 | [the release notes](RELEASE_NOTES-0.4.1.md) for more information). 42 | 43 | ######v0.4 (2014-11-16) 44 | (See [the release notes](RELEASE_NOTES-0.4.md) for important details.) 45 | * Add optional GPG support: GPG can be used to share the repository 46 | between one or more users in lieu of sharing a secret key. 47 | * New workflow: the symmetric key is now stored inside the .git 48 | directory. Although backwards compatibility has been preserved 49 | with repositories created by old versions of git-crypt, the 50 | commands for setting up a repository have changed. See the 51 | release notes file for details. 52 | * Multiple key support: it's now possible to encrypt different parts 53 | of a repository with different keys. 54 | * Initial `git-crypt status` command to report which files are 55 | encrypted and to fix problems that are detected. 56 | * Numerous usability, documentation, and error reporting improvements. 57 | * Major internal code improvements that will make future development 58 | easier. 59 | * Initial experimental Windows support. 60 | 61 | ######v0.3 (2013-04-05) 62 | * Fix `git-crypt init` on newer versions of Git. Previously, 63 | encrypted files were not being automatically decrypted after running 64 | `git-crypt init` with recent versions of Git. 65 | * Allow `git-crypt init` to be run even if the working tree contains 66 | untracked files. 67 | * `git-crypt init` now properly escapes arguments to the filter 68 | commands it configures, allowing both the path to git-crypt and the 69 | path to the key file to contain arbitrary characters such as spaces. 70 | 71 | ######v0.2 (2013-01-25) 72 | * Numerous improvements to `git-crypt init` usability. 73 | * Fix gitattributes example in [README](README.md): the old example 74 | showed a colon after the filename where there shouldn't be one. 75 | * Various build fixes and improvements. 76 | 77 | ######v0.1 (2012-11-29) 78 | * Initial release. 79 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | ABOUT GIT-CRYPT 2 | 3 | git-crypt enables transparent encryption and decryption of files in a 4 | git repository. Files which you choose to protect are encrypted when 5 | committed, and decrypted when checked out. git-crypt lets you freely 6 | share a repository containing a mix of public and private content. 7 | git-crypt gracefully degrades, so developers without the secret key can 8 | still clone and commit to a repository with encrypted files. This lets 9 | you store your secret material (such as keys or passwords) in the same 10 | repository as your code, without requiring you to lock down your entire 11 | repository. 12 | 13 | git-crypt was written by Andrew Ayer . For more 14 | information, see . 15 | 16 | 17 | BUILDING GIT-CRYPT 18 | 19 | See the INSTALL file. 20 | 21 | 22 | USING GIT-CRYPT 23 | 24 | Configure a repository to use git-crypt: 25 | 26 | $ cd repo 27 | $ git-crypt init 28 | 29 | Specify files to encrypt by creating a .gitattributes file: 30 | 31 | secretfile filter=git-crypt diff=git-crypt 32 | *.key filter=git-crypt diff=git-crypt 33 | secretdir/** filter=git-crypt diff=git-crypt 34 | 35 | Like a .gitignore file, it can match wildcards and should be checked into 36 | the repository. See below for more information about .gitattributes. 37 | Make sure you don't accidentally encrypt the .gitattributes file itself 38 | (or other git files like .gitignore or .gitmodules). Make sure your 39 | .gitattributes rules are in place *before* you add sensitive files, or 40 | those files won't be encrypted! 41 | 42 | Share the repository with others (or with yourself) using GPG: 43 | 44 | $ git-crypt add-gpg-user USER_ID 45 | 46 | USER_ID can be a key ID, a full fingerprint, an email address, or anything 47 | else that uniquely identifies a public key to GPG (see "HOW TO SPECIFY 48 | A USER ID" in the gpg man page). Note: `git-crypt add-gpg-user` will 49 | add and commit a GPG-encrypted key file in the .git-crypt directory of 50 | the root of your repository. 51 | 52 | Alternatively, you can export a symmetric secret key, which you must 53 | securely convey to collaborators (GPG is not required, and no files 54 | are added to your repository): 55 | 56 | $ git-crypt export-key /path/to/key 57 | 58 | After cloning a repository with encrypted files, unlock with GPG: 59 | 60 | $ git-crypt unlock 61 | 62 | Or with a symmetric key: 63 | 64 | $ git-crypt unlock /path/to/key 65 | 66 | That's all you need to do - after git-crypt is set up (either with 67 | `git-crypt init` or `git-crypt unlock`), you can use git normally - 68 | encryption and decryption happen transparently. 69 | 70 | 71 | CURRENT STATUS 72 | 73 | The latest version of git-crypt is 0.7.0, released on 2022-04-21. 74 | git-crypt aims to be bug-free and reliable, meaning it shouldn't 75 | crash, malfunction, or expose your confidential data. However, 76 | it has not yet reached maturity, meaning it is not as documented, 77 | featureful, or easy-to-use as it should be. Additionally, there may be 78 | backwards-incompatible changes introduced before version 1.0. 79 | 80 | 81 | SECURITY 82 | 83 | git-crypt is more secure than other transparent git encryption systems. 84 | git-crypt encrypts files using AES-256 in CTR mode with a synthetic IV 85 | derived from the SHA-1 HMAC of the file. This mode of operation is 86 | provably semantically secure under deterministic chosen-plaintext attack. 87 | That means that although the encryption is deterministic (which is 88 | required so git can distinguish when a file has and hasn't changed), 89 | it leaks no information beyond whether two files are identical or not. 90 | Other proposals for transparent git encryption use ECB or CBC with a 91 | fixed IV. These systems are not semantically secure and leak information. 92 | 93 | 94 | LIMITATIONS 95 | 96 | git-crypt relies on git filters, which were not designed with encryption 97 | in mind. As such, git-crypt is not the best tool for encrypting most or 98 | all of the files in a repository. Where git-crypt really shines is where 99 | most of your repository is public, but you have a few files (perhaps 100 | private keys named *.key, or a file with API credentials) which you 101 | need to encrypt. For encrypting an entire repository, consider using a 102 | system like git-remote-gcrypt 103 | instead. (Note: no endorsement is made of git-remote-gcrypt's security.) 104 | 105 | git-crypt does not encrypt file names, commit messages, symlink targets, 106 | gitlinks, or other metadata. 107 | 108 | git-crypt does not hide when a file does or doesn't change, the length 109 | of a file, or the fact that two files are identical (see "Security" 110 | section above). 111 | 112 | git-crypt does not support revoking access to an encrypted repository 113 | which was previously granted. This applies to both multi-user GPG 114 | mode (there's no del-gpg-user command to complement add-gpg-user) 115 | and also symmetric key mode (there's no support for rotating the key). 116 | This is because it is an inherently complex problem in the context 117 | of historical data. For example, even if a key was rotated at one 118 | point in history, a user having the previous key can still access 119 | previous repository history. This problem is discussed in more detail in 120 | . 121 | 122 | Files encrypted with git-crypt are not compressible. Even the smallest 123 | change to an encrypted file requires git to store the entire changed file, 124 | instead of just a delta. 125 | 126 | Although git-crypt protects individual file contents with a SHA-1 127 | HMAC, git-crypt cannot be used securely unless the entire repository is 128 | protected against tampering (an attacker who can mutate your repository 129 | can alter your .gitattributes file to disable encryption). If necessary, 130 | use git features such as signed tags instead of relying solely on 131 | git-crypt for integrity. 132 | 133 | Files encrypted with git-crypt cannot be patched with git-apply, unless 134 | the patch itself is encrypted. To generate an encrypted patch, use `git 135 | diff --no-textconv --binary`. Alternatively, you can apply a plaintext 136 | patch outside of git using the patch command. 137 | 138 | git-crypt does not work reliably with some third-party git GUIs, such 139 | as Atlassian SourceTree 140 | and GitHub for Mac. Files might be left in an unencrypted state. 141 | 142 | 143 | GITATTRIBUTES FILE 144 | 145 | The .gitattributes file is documented in the gitattributes(5) man page. 146 | The file pattern format is the same as the one used by .gitignore, 147 | as documented in the gitignore(5) man page, with the exception that 148 | specifying merely a directory (e.g. `/dir/`) is NOT sufficient to 149 | encrypt all files beneath it. 150 | 151 | Also note that the pattern `dir/*` does not match files under 152 | sub-directories of dir/. To encrypt an entire sub-tree dir/, use `dir/**`: 153 | 154 | dir/** filter=git-crypt diff=git-crypt 155 | 156 | The .gitattributes file must not be encrypted, so make sure wildcards don't 157 | match it accidentally. If necessary, you can exclude .gitattributes from 158 | encryption like this: 159 | 160 | .gitattributes !filter !diff 161 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | git-crypt - transparent file encryption in git 2 | ============================================== 3 | 4 | git-crypt enables transparent encryption and decryption of files in a 5 | git repository. Files which you choose to protect are encrypted when 6 | committed, and decrypted when checked out. git-crypt lets you freely 7 | share a repository containing a mix of public and private content. 8 | git-crypt gracefully degrades, so developers without the secret key can 9 | still clone and commit to a repository with encrypted files. This lets 10 | you store your secret material (such as keys or passwords) in the same 11 | repository as your code, without requiring you to lock down your entire 12 | repository. 13 | 14 | git-crypt was written by [Andrew Ayer](https://www.agwa.name) (agwa@andrewayer.name). 15 | For more information, see . 16 | 17 | Building git-crypt 18 | ------------------ 19 | See the [INSTALL.md](INSTALL.md) file. 20 | 21 | 22 | Using git-crypt 23 | --------------- 24 | 25 | Configure a repository to use git-crypt: 26 | 27 | cd repo 28 | git-crypt init 29 | 30 | Specify files to encrypt by creating a .gitattributes file: 31 | 32 | secretfile filter=git-crypt diff=git-crypt 33 | *.key filter=git-crypt diff=git-crypt 34 | secretdir/** filter=git-crypt diff=git-crypt 35 | 36 | Like a .gitignore file, it can match wildcards and should be checked into 37 | the repository. See below for more information about .gitattributes. 38 | Make sure you don't accidentally encrypt the .gitattributes file itself 39 | (or other git files like .gitignore or .gitmodules). Make sure your 40 | .gitattributes rules are in place *before* you add sensitive files, or 41 | those files won't be encrypted! 42 | 43 | Share the repository with others (or with yourself) using GPG: 44 | 45 | git-crypt add-gpg-user USER_ID 46 | 47 | `USER_ID` can be a key ID, a full fingerprint, an email address, or 48 | anything else that uniquely identifies a public key to GPG (see "HOW TO 49 | SPECIFY A USER ID" in the gpg man page). Note: `git-crypt add-gpg-user` 50 | will add and commit a GPG-encrypted key file in the .git-crypt directory 51 | of the root of your repository. 52 | 53 | Alternatively, you can export a symmetric secret key, which you must 54 | securely convey to collaborators (GPG is not required, and no files 55 | are added to your repository): 56 | 57 | git-crypt export-key /path/to/key 58 | 59 | After cloning a repository with encrypted files, unlock with GPG: 60 | 61 | git-crypt unlock 62 | 63 | Or with a symmetric key: 64 | 65 | git-crypt unlock /path/to/key 66 | 67 | That's all you need to do - after git-crypt is set up (either with 68 | `git-crypt init` or `git-crypt unlock`), you can use git normally - 69 | encryption and decryption happen transparently. 70 | 71 | Current Status 72 | -------------- 73 | 74 | The latest version of git-crypt is [0.7.0](NEWS.md), released on 75 | 2022-04-21. git-crypt aims to be bug-free and reliable, meaning it 76 | shouldn't crash, malfunction, or expose your confidential data. 77 | However, it has not yet reached maturity, meaning it is not as 78 | documented, featureful, or easy-to-use as it should be. Additionally, 79 | there may be backwards-incompatible changes introduced before version 80 | 1.0. 81 | 82 | Security 83 | -------- 84 | 85 | git-crypt is more secure than other transparent git encryption systems. 86 | git-crypt encrypts files using AES-256 in CTR mode with a synthetic IV 87 | derived from the SHA-1 HMAC of the file. This mode of operation is 88 | provably semantically secure under deterministic chosen-plaintext attack. 89 | That means that although the encryption is deterministic (which is 90 | required so git can distinguish when a file has and hasn't changed), 91 | it leaks no information beyond whether two files are identical or not. 92 | Other proposals for transparent git encryption use ECB or CBC with a 93 | fixed IV. These systems are not semantically secure and leak information. 94 | 95 | Limitations 96 | ----------- 97 | 98 | git-crypt relies on git filters, which were not designed with encryption 99 | in mind. As such, git-crypt is not the best tool for encrypting most or 100 | all of the files in a repository. Where git-crypt really shines is where 101 | most of your repository is public, but you have a few files (perhaps 102 | private keys named *.key, or a file with API credentials) which you 103 | need to encrypt. For encrypting an entire repository, consider using a 104 | system like [git-remote-gcrypt](https://spwhitton.name/tech/code/git-remote-gcrypt/) 105 | instead. (Note: no endorsement is made of git-remote-gcrypt's security.) 106 | 107 | git-crypt does not encrypt file names, commit messages, symlink targets, 108 | gitlinks, or other metadata. 109 | 110 | git-crypt does not hide when a file does or doesn't change, the length 111 | of a file, or the fact that two files are identical (see "Security" 112 | section above). 113 | 114 | git-crypt does not support revoking access to an encrypted repository 115 | which was previously granted. This applies to both multi-user GPG 116 | mode (there's no del-gpg-user command to complement add-gpg-user) 117 | and also symmetric key mode (there's no support for rotating the key). 118 | This is because it is an inherently complex problem in the context 119 | of historical data. For example, even if a key was rotated at one 120 | point in history, a user having the previous key can still access 121 | previous repository history. This problem is discussed in more detail in 122 | . 123 | 124 | Files encrypted with git-crypt are not compressible. Even the smallest 125 | change to an encrypted file requires git to store the entire changed file, 126 | instead of just a delta. 127 | 128 | Although git-crypt protects individual file contents with a SHA-1 129 | HMAC, git-crypt cannot be used securely unless the entire repository is 130 | protected against tampering (an attacker who can mutate your repository 131 | can alter your .gitattributes file to disable encryption). If necessary, 132 | use git features such as signed tags instead of relying solely on 133 | git-crypt for integrity. 134 | 135 | Files encrypted with git-crypt cannot be patched with git-apply, unless 136 | the patch itself is encrypted. To generate an encrypted patch, use `git 137 | diff --no-textconv --binary`. Alternatively, you can apply a plaintext 138 | patch outside of git using the patch command. 139 | 140 | git-crypt does not work reliably with some third-party git GUIs, such 141 | as [Atlassian SourceTree](https://jira.atlassian.com/browse/SRCTREE-2511) 142 | and GitHub for Mac. Files might be left in an unencrypted state. 143 | 144 | Gitattributes File 145 | ------------------ 146 | 147 | The .gitattributes file is documented in the gitattributes(5) man page. 148 | The file pattern format is the same as the one used by .gitignore, 149 | as documented in the gitignore(5) man page, with the exception that 150 | specifying merely a directory (e.g. `/dir/`) is *not* sufficient to 151 | encrypt all files beneath it. 152 | 153 | Also note that the pattern `dir/*` does not match files under 154 | sub-directories of dir/. To encrypt an entire sub-tree dir/, use `dir/**`: 155 | 156 | dir/** filter=git-crypt diff=git-crypt 157 | 158 | The .gitattributes file must not be encrypted, so make sure wildcards don't 159 | match it accidentally. If necessary, you can exclude .gitattributes from 160 | encryption like this: 161 | 162 | .gitattributes !filter !diff 163 | -------------------------------------------------------------------------------- /RELEASE_NOTES-0.4.1.md: -------------------------------------------------------------------------------- 1 | git-crypt 0.4.1 is a bugfix-only release that contains an important 2 | usability fix for users who use GPG mode to encrypt an entire repository. 3 | 4 | Previously, if you used a '*' pattern in the top-level .gitattributes 5 | file, and you did not explicitly add a pattern to exclude the .git-crypt 6 | directory, the files contained therein would be encrypted, rendering 7 | the repository impossible to unlock with GPG. 8 | 9 | git-crypt now adds a .gitattributes file to the .git-crypt directory 10 | to prevent its contents from being encrypted, regardless of patterns in 11 | the top-level .gitattributes. 12 | 13 | If you are using git-crypt in GPG mode to encrypt an entire repository, 14 | and you do not already have a .gitattributes pattern to exclude the 15 | .git-crypt directory, you are strongly advised to upgrade. After 16 | upgrading, you should do the following in each of your repositories to 17 | ensure that the information inside .git-crypt is properly stored: 18 | 19 | 1. Remove existing key files: `rm .git-crypt/keys/*/0/*` 20 | 21 | 2. Re-add GPG user(s): `git-crypt add-gpg-user GPG_USER_ID ...` 22 | -------------------------------------------------------------------------------- /RELEASE_NOTES-0.4.md: -------------------------------------------------------------------------------- 1 | Changes to be aware of for git-crypt 0.4 2 | ======================================== 3 | 4 | (For a complete list of changes, see the [NEWS](NEWS.md) file.) 5 | 6 | 7 | ### New workflow 8 | 9 | The commands for setting up a repository have changed in git-crypt 0.4. 10 | The previous commands continue to work, but will be removed in a future 11 | release of git-crypt. Please get in the habit of using the new syntax: 12 | 13 | `git-crypt init` no longer takes an argument, and is now used only when 14 | initializing a repository for the very first time. It generates a key 15 | and stores it in the `.git` directory. There is no longer a separate 16 | `keygen` step, and you no longer need to keep a copy of the key outside 17 | the repository. 18 | 19 | `git-crypt init` is no longer used to decrypt a cloned repository. Instead, 20 | run `git-crypt unlock /path/to/keyfile`, where `keyfile` is obtained by 21 | running `git-crypt export-key /path/to/keyfile` from an already-decrypted 22 | repository. 23 | 24 | 25 | ### GPG mode 26 | 27 | git-crypt now supports GPG. A repository can be shared with one or more 28 | GPG users in lieu of sharing a secret symmetric key. Symmetric key support 29 | isn't going away, but the workflow of GPG mode is extremely easy and all users 30 | are encouraged to consider it for their repositories. 31 | 32 | See the [README](README.md) for details on using GPG. 33 | 34 | 35 | ### Status command 36 | 37 | A new command, `git-crypt status`, lists encrypted files, which is 38 | useful for making sure your `.gitattributes` pattern is protecting the 39 | right files. 40 | 41 | 42 | ### Multiple key support 43 | 44 | git-crypt now lets you encrypt different sets of files with different 45 | keys, which is useful if you want to grant different collaborators access 46 | to different sets of files. 47 | 48 | See [doc/multiple_keys.md](doc/multiple_keys.md) for details. 49 | 50 | 51 | ### Compatibility with old repositories 52 | 53 | Repositories created with older versions of git-crypt continue to work 54 | without any changes needed, and backwards compatibility with these 55 | repositories will be maintained indefinitely. 56 | 57 | However, you will not be able to take advantage of git-crypt's new 58 | features, such as GPG support, unless you migrate your repository. 59 | 60 | To migrate your repository, first ensure the working tree is clean. 61 | Then migrate your current key file and use the migrated key to unlock 62 | your repository as follows: 63 | 64 | git-crypt migrate-key /path/to/old_key /path/to/migrated_key 65 | git-crypt unlock /path/to/migrated_key 66 | 67 | Once you've confirmed that your repository is functional, you can delete 68 | both the old and migrated key files (though keeping a backup of your key 69 | is always a good idea). 70 | 71 | 72 | ### Known issues 73 | 74 | It is not yet possible to revoke access from a GPG user. This will 75 | require substantial development work and will be a major focus of future 76 | git-crypt development. 77 | 78 | The output of `git-crypt status` is currently very bare-bones and will 79 | be substantially improved in a future release. Do not rely on its output 80 | being stable. A future release of git-crypt will provide an option for stable 81 | machine-readable output. 82 | 83 | On Windows, git-crypt does not create key files with restrictive 84 | permissions. Take care when using git-crypt on a multi-user Windows system. 85 | -------------------------------------------------------------------------------- /THANKS.md: -------------------------------------------------------------------------------- 1 | For their contributions to git-crypt, I thank: 2 | 3 | * Michael Mior and @zimbatm for the Homebrew formula. 4 | 5 | * Cyril Cleaud for help with Windows support. 6 | 7 | * The following people for contributing patches: 8 | * Adam Nelson 9 | * Caleb Maclennan 10 | * Darayus Nanavati 11 | * Jon Sailor 12 | * Linus G Thiel 13 | * Michael Schout 14 | * Simon Kotlinski 15 | * Kevin Menard 16 | * Wael M. Nasreddine 17 | * Kevin Borgolte 18 | * Adrian Cohea 19 | 20 | * And everyone who has tested git-crypt, provided feedback, reported 21 | bugs, and participated in discussions about new features. 22 | 23 | Thank you! 24 | -------------------------------------------------------------------------------- /commands.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012, 2014 Andrew Ayer 3 | * 4 | * This file is part of git-crypt. 5 | * 6 | * git-crypt is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * git-crypt is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with git-crypt. If not, see . 18 | * 19 | * Additional permission under GNU GPL version 3 section 7: 20 | * 21 | * If you modify the Program, or any covered work, by linking or 22 | * combining it with the OpenSSL project's OpenSSL library (or a 23 | * modified version of that library), containing parts covered by the 24 | * terms of the OpenSSL or SSLeay licenses, the licensors of the Program 25 | * grant you additional permission to convey the resulting work. 26 | * Corresponding Source for a non-source form of such a combination 27 | * shall include the source code for the parts of OpenSSL used as well 28 | * as that of the covered work. 29 | */ 30 | 31 | #ifndef GIT_CRYPT_COMMANDS_HPP 32 | #define GIT_CRYPT_COMMANDS_HPP 33 | 34 | #include 35 | #include 36 | 37 | struct Error { 38 | std::string message; 39 | 40 | explicit Error (std::string m) : message(m) { } 41 | }; 42 | 43 | // Plumbing commands: 44 | int clean (int argc, const char** argv); 45 | int smudge (int argc, const char** argv); 46 | int diff (int argc, const char** argv); 47 | // Public commands: 48 | int init (int argc, const char** argv); 49 | int unlock (int argc, const char** argv); 50 | int lock (int argc, const char** argv); 51 | int add_gpg_user (int argc, const char** argv); 52 | int rm_gpg_user (int argc, const char** argv); 53 | int ls_gpg_users (int argc, const char** argv); 54 | int export_key (int argc, const char** argv); 55 | int keygen (int argc, const char** argv); 56 | int migrate_key (int argc, const char** argv); 57 | int refresh (int argc, const char** argv); 58 | int status (int argc, const char** argv); 59 | 60 | // Help messages: 61 | void help_init (std::ostream&); 62 | void help_unlock (std::ostream&); 63 | void help_lock (std::ostream&); 64 | void help_add_gpg_user (std::ostream&); 65 | void help_rm_gpg_user (std::ostream&); 66 | void help_ls_gpg_users (std::ostream&); 67 | void help_export_key (std::ostream&); 68 | void help_keygen (std::ostream&); 69 | void help_migrate_key (std::ostream&); 70 | void help_refresh (std::ostream&); 71 | void help_status (std::ostream&); 72 | 73 | // other 74 | std::string get_git_config (const std::string& name); 75 | 76 | #endif 77 | -------------------------------------------------------------------------------- /coprocess-unix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Andrew Ayer 3 | * 4 | * This file is part of git-crypt. 5 | * 6 | * git-crypt is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * git-crypt is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with git-crypt. If not, see . 18 | * 19 | * Additional permission under GNU GPL version 3 section 7: 20 | * 21 | * If you modify the Program, or any covered work, by linking or 22 | * combining it with the OpenSSL project's OpenSSL library (or a 23 | * modified version of that library), containing parts covered by the 24 | * terms of the OpenSSL or SSLeay licenses, the licensors of the Program 25 | * grant you additional permission to convey the resulting work. 26 | * Corresponding Source for a non-source form of such a combination 27 | * shall include the source code for the parts of OpenSSL used as well 28 | * as that of the covered work. 29 | */ 30 | 31 | #include "coprocess.hpp" 32 | #include "util.hpp" 33 | #include 34 | #include 35 | #include 36 | 37 | static int execvp (const std::string& file, const std::vector& args) 38 | { 39 | std::vector args_c_str; 40 | args_c_str.reserve(args.size()); 41 | for (std::vector::const_iterator arg(args.begin()); arg != args.end(); ++arg) { 42 | args_c_str.push_back(arg->c_str()); 43 | } 44 | args_c_str.push_back(nullptr); 45 | return execvp(file.c_str(), const_cast(&args_c_str[0])); 46 | } 47 | 48 | Coprocess::Coprocess () 49 | { 50 | pid = -1; 51 | stdin_pipe_reader = -1; 52 | stdin_pipe_writer = -1; 53 | stdin_pipe_ostream = nullptr; 54 | stdout_pipe_reader = -1; 55 | stdout_pipe_writer = -1; 56 | stdout_pipe_istream = nullptr; 57 | } 58 | 59 | Coprocess::~Coprocess () 60 | { 61 | close_stdin(); 62 | close_stdout(); 63 | } 64 | 65 | std::ostream* Coprocess::stdin_pipe () 66 | { 67 | if (!stdin_pipe_ostream) { 68 | int fds[2]; 69 | if (pipe(fds) == -1) { 70 | throw System_error("pipe", "", errno); 71 | } 72 | stdin_pipe_reader = fds[0]; 73 | stdin_pipe_writer = fds[1]; 74 | stdin_pipe_ostream = new ofhstream(this, write_stdin); 75 | } 76 | return stdin_pipe_ostream; 77 | } 78 | 79 | void Coprocess::close_stdin () 80 | { 81 | delete stdin_pipe_ostream; 82 | stdin_pipe_ostream = nullptr; 83 | if (stdin_pipe_writer != -1) { 84 | close(stdin_pipe_writer); 85 | stdin_pipe_writer = -1; 86 | } 87 | if (stdin_pipe_reader != -1) { 88 | close(stdin_pipe_reader); 89 | stdin_pipe_reader = -1; 90 | } 91 | } 92 | 93 | std::istream* Coprocess::stdout_pipe () 94 | { 95 | if (!stdout_pipe_istream) { 96 | int fds[2]; 97 | if (pipe(fds) == -1) { 98 | throw System_error("pipe", "", errno); 99 | } 100 | stdout_pipe_reader = fds[0]; 101 | stdout_pipe_writer = fds[1]; 102 | stdout_pipe_istream = new ifhstream(this, read_stdout); 103 | } 104 | return stdout_pipe_istream; 105 | } 106 | 107 | void Coprocess::close_stdout () 108 | { 109 | delete stdout_pipe_istream; 110 | stdout_pipe_istream = nullptr; 111 | if (stdout_pipe_writer != -1) { 112 | close(stdout_pipe_writer); 113 | stdout_pipe_writer = -1; 114 | } 115 | if (stdout_pipe_reader != -1) { 116 | close(stdout_pipe_reader); 117 | stdout_pipe_reader = -1; 118 | } 119 | } 120 | 121 | void Coprocess::spawn (const std::vector& args) 122 | { 123 | pid = fork(); 124 | if (pid == -1) { 125 | throw System_error("fork", "", errno); 126 | } 127 | if (pid == 0) { 128 | if (stdin_pipe_writer != -1) { 129 | close(stdin_pipe_writer); 130 | } 131 | if (stdout_pipe_reader != -1) { 132 | close(stdout_pipe_reader); 133 | } 134 | if (stdin_pipe_reader != -1) { 135 | dup2(stdin_pipe_reader, 0); 136 | close(stdin_pipe_reader); 137 | } 138 | if (stdout_pipe_writer != -1) { 139 | dup2(stdout_pipe_writer, 1); 140 | close(stdout_pipe_writer); 141 | } 142 | 143 | execvp(args[0], args); 144 | perror(args[0].c_str()); 145 | _exit(-1); 146 | } 147 | if (stdin_pipe_reader != -1) { 148 | close(stdin_pipe_reader); 149 | stdin_pipe_reader = -1; 150 | } 151 | if (stdout_pipe_writer != -1) { 152 | close(stdout_pipe_writer); 153 | stdout_pipe_writer = -1; 154 | } 155 | } 156 | 157 | int Coprocess::wait () 158 | { 159 | int status = 0; 160 | if (waitpid(pid, &status, 0) == -1) { 161 | throw System_error("waitpid", "", errno); 162 | } 163 | return status; 164 | } 165 | 166 | size_t Coprocess::write_stdin (void* handle, const void* buf, size_t count) 167 | { 168 | const int fd = static_cast(handle)->stdin_pipe_writer; 169 | ssize_t ret; 170 | while ((ret = write(fd, buf, count)) == -1 && errno == EINTR); // restart if interrupted 171 | if (ret < 0) { 172 | throw System_error("write", "", errno); 173 | } 174 | return ret; 175 | } 176 | 177 | size_t Coprocess::read_stdout (void* handle, void* buf, size_t count) 178 | { 179 | const int fd = static_cast(handle)->stdout_pipe_reader; 180 | ssize_t ret; 181 | while ((ret = read(fd, buf, count)) == -1 && errno == EINTR); // restart if interrupted 182 | if (ret < 0) { 183 | throw System_error("read", "", errno); 184 | } 185 | return ret; 186 | } 187 | -------------------------------------------------------------------------------- /coprocess-unix.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Andrew Ayer 3 | * 4 | * This file is part of git-crypt. 5 | * 6 | * git-crypt is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * git-crypt is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with git-crypt. If not, see . 18 | * 19 | * Additional permission under GNU GPL version 3 section 7: 20 | * 21 | * If you modify the Program, or any covered work, by linking or 22 | * combining it with the OpenSSL project's OpenSSL library (or a 23 | * modified version of that library), containing parts covered by the 24 | * terms of the OpenSSL or SSLeay licenses, the licensors of the Program 25 | * grant you additional permission to convey the resulting work. 26 | * Corresponding Source for a non-source form of such a combination 27 | * shall include the source code for the parts of OpenSSL used as well 28 | * as that of the covered work. 29 | */ 30 | 31 | #ifndef GIT_CRYPT_COPROCESS_HPP 32 | #define GIT_CRYPT_COPROCESS_HPP 33 | 34 | #include "fhstream.hpp" 35 | #include 36 | #include 37 | 38 | class Coprocess { 39 | pid_t pid; 40 | 41 | int stdin_pipe_reader; 42 | int stdin_pipe_writer; 43 | ofhstream* stdin_pipe_ostream; 44 | static size_t write_stdin (void*, const void*, size_t); 45 | 46 | int stdout_pipe_reader; 47 | int stdout_pipe_writer; 48 | ifhstream* stdout_pipe_istream; 49 | static size_t read_stdout (void*, void*, size_t); 50 | 51 | Coprocess (const Coprocess&); // Disallow copy 52 | Coprocess& operator= (const Coprocess&); // Disallow assignment 53 | public: 54 | Coprocess (); 55 | ~Coprocess (); 56 | 57 | std::ostream* stdin_pipe (); 58 | void close_stdin (); 59 | 60 | std::istream* stdout_pipe (); 61 | void close_stdout (); 62 | 63 | void spawn (const std::vector&); 64 | 65 | int wait (); 66 | }; 67 | 68 | #endif 69 | -------------------------------------------------------------------------------- /coprocess-win32.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Andrew Ayer 3 | * 4 | * This file is part of git-crypt. 5 | * 6 | * git-crypt is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * git-crypt is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with git-crypt. If not, see . 18 | * 19 | * Additional permission under GNU GPL version 3 section 7: 20 | * 21 | * If you modify the Program, or any covered work, by linking or 22 | * combining it with the OpenSSL project's OpenSSL library (or a 23 | * modified version of that library), containing parts covered by the 24 | * terms of the OpenSSL or SSLeay licenses, the licensors of the Program 25 | * grant you additional permission to convey the resulting work. 26 | * Corresponding Source for a non-source form of such a combination 27 | * shall include the source code for the parts of OpenSSL used as well 28 | * as that of the covered work. 29 | */ 30 | 31 | #include "coprocess-win32.hpp" 32 | #include "util.hpp" 33 | 34 | 35 | static void escape_cmdline_argument (std::string& cmdline, const std::string& arg) 36 | { 37 | // For an explanation of Win32's arcane argument quoting rules, see: 38 | // http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx 39 | // http://msdn.microsoft.com/en-us/library/bb776391%28v=vs.85%29.aspx 40 | // http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx 41 | // http://blogs.msdn.com/b/oldnewthing/archive/2010/09/17/10063629.aspx 42 | cmdline.push_back('"'); 43 | 44 | std::string::const_iterator p(arg.begin()); 45 | while (p != arg.end()) { 46 | if (*p == '"') { 47 | cmdline.push_back('\\'); 48 | cmdline.push_back('"'); 49 | ++p; 50 | } else if (*p == '\\') { 51 | unsigned int num_backslashes = 0; 52 | while (p != arg.end() && *p == '\\') { 53 | ++num_backslashes; 54 | ++p; 55 | } 56 | if (p == arg.end() || *p == '"') { 57 | // Backslashes need to be escaped 58 | num_backslashes *= 2; 59 | } 60 | while (num_backslashes--) { 61 | cmdline.push_back('\\'); 62 | } 63 | } else { 64 | cmdline.push_back(*p++); 65 | } 66 | } 67 | 68 | cmdline.push_back('"'); 69 | } 70 | 71 | static std::string format_cmdline (const std::vector& command) 72 | { 73 | std::string cmdline; 74 | for (std::vector::const_iterator arg(command.begin()); arg != command.end(); ++arg) { 75 | if (arg != command.begin()) { 76 | cmdline.push_back(' '); 77 | } 78 | escape_cmdline_argument(cmdline, *arg); 79 | } 80 | return cmdline; 81 | } 82 | 83 | static HANDLE spawn_command (const std::vector& command, HANDLE stdin_handle, HANDLE stdout_handle, HANDLE stderr_handle) 84 | { 85 | PROCESS_INFORMATION proc_info; 86 | ZeroMemory(&proc_info, sizeof(proc_info)); 87 | 88 | STARTUPINFO start_info; 89 | ZeroMemory(&start_info, sizeof(start_info)); 90 | 91 | start_info.cb = sizeof(STARTUPINFO); 92 | start_info.hStdInput = stdin_handle ? stdin_handle : GetStdHandle(STD_INPUT_HANDLE); 93 | start_info.hStdOutput = stdout_handle ? stdout_handle : GetStdHandle(STD_OUTPUT_HANDLE); 94 | start_info.hStdError = stderr_handle ? stderr_handle : GetStdHandle(STD_ERROR_HANDLE); 95 | start_info.dwFlags |= STARTF_USESTDHANDLES; 96 | 97 | std::string cmdline(format_cmdline(command)); 98 | 99 | if (!CreateProcessA(nullptr, // application name (nullptr to use command line) 100 | const_cast(cmdline.c_str()), 101 | nullptr, // process security attributes 102 | nullptr, // primary thread security attributes 103 | TRUE, // handles are inherited 104 | 0, // creation flags 105 | nullptr, // use parent's environment 106 | nullptr, // use parent's current directory 107 | &start_info, 108 | &proc_info)) { 109 | throw System_error("CreateProcess", cmdline, GetLastError()); 110 | } 111 | 112 | CloseHandle(proc_info.hThread); 113 | 114 | return proc_info.hProcess; 115 | } 116 | 117 | 118 | Coprocess::Coprocess () 119 | { 120 | proc_handle = nullptr; 121 | stdin_pipe_reader = nullptr; 122 | stdin_pipe_writer = nullptr; 123 | stdin_pipe_ostream = nullptr; 124 | stdout_pipe_reader = nullptr; 125 | stdout_pipe_writer = nullptr; 126 | stdout_pipe_istream = nullptr; 127 | } 128 | 129 | Coprocess::~Coprocess () 130 | { 131 | close_stdin(); 132 | close_stdout(); 133 | if (proc_handle) { 134 | CloseHandle(proc_handle); 135 | } 136 | } 137 | 138 | std::ostream* Coprocess::stdin_pipe () 139 | { 140 | if (!stdin_pipe_ostream) { 141 | SECURITY_ATTRIBUTES sec_attr; 142 | 143 | // Set the bInheritHandle flag so pipe handles are inherited. 144 | sec_attr.nLength = sizeof(SECURITY_ATTRIBUTES); 145 | sec_attr.bInheritHandle = TRUE; 146 | sec_attr.lpSecurityDescriptor = nullptr; 147 | 148 | // Create a pipe for the child process's STDIN. 149 | if (!CreatePipe(&stdin_pipe_reader, &stdin_pipe_writer, &sec_attr, 0)) { 150 | throw System_error("CreatePipe", "", GetLastError()); 151 | } 152 | 153 | // Ensure the write handle to the pipe for STDIN is not inherited. 154 | if (!SetHandleInformation(stdin_pipe_writer, HANDLE_FLAG_INHERIT, 0)) { 155 | throw System_error("SetHandleInformation", "", GetLastError()); 156 | } 157 | 158 | stdin_pipe_ostream = new ofhstream(this, write_stdin); 159 | } 160 | return stdin_pipe_ostream; 161 | } 162 | 163 | void Coprocess::close_stdin () 164 | { 165 | delete stdin_pipe_ostream; 166 | stdin_pipe_ostream = nullptr; 167 | if (stdin_pipe_writer) { 168 | CloseHandle(stdin_pipe_writer); 169 | stdin_pipe_writer = nullptr; 170 | } 171 | if (stdin_pipe_reader) { 172 | CloseHandle(stdin_pipe_reader); 173 | stdin_pipe_reader = nullptr; 174 | } 175 | } 176 | 177 | std::istream* Coprocess::stdout_pipe () 178 | { 179 | if (!stdout_pipe_istream) { 180 | SECURITY_ATTRIBUTES sec_attr; 181 | 182 | // Set the bInheritHandle flag so pipe handles are inherited. 183 | sec_attr.nLength = sizeof(SECURITY_ATTRIBUTES); 184 | sec_attr.bInheritHandle = TRUE; 185 | sec_attr.lpSecurityDescriptor = nullptr; 186 | 187 | // Create a pipe for the child process's STDOUT. 188 | if (!CreatePipe(&stdout_pipe_reader, &stdout_pipe_writer, &sec_attr, 0)) { 189 | throw System_error("CreatePipe", "", GetLastError()); 190 | } 191 | 192 | // Ensure the read handle to the pipe for STDOUT is not inherited. 193 | if (!SetHandleInformation(stdout_pipe_reader, HANDLE_FLAG_INHERIT, 0)) { 194 | throw System_error("SetHandleInformation", "", GetLastError()); 195 | } 196 | 197 | stdout_pipe_istream = new ifhstream(this, read_stdout); 198 | } 199 | return stdout_pipe_istream; 200 | } 201 | 202 | void Coprocess::close_stdout () 203 | { 204 | delete stdout_pipe_istream; 205 | stdout_pipe_istream = nullptr; 206 | if (stdout_pipe_writer) { 207 | CloseHandle(stdout_pipe_writer); 208 | stdout_pipe_writer = nullptr; 209 | } 210 | if (stdout_pipe_reader) { 211 | CloseHandle(stdout_pipe_reader); 212 | stdout_pipe_reader = nullptr; 213 | } 214 | } 215 | 216 | void Coprocess::spawn (const std::vector& args) 217 | { 218 | proc_handle = spawn_command(args, stdin_pipe_reader, stdout_pipe_writer, nullptr); 219 | if (stdin_pipe_reader) { 220 | CloseHandle(stdin_pipe_reader); 221 | stdin_pipe_reader = nullptr; 222 | } 223 | if (stdout_pipe_writer) { 224 | CloseHandle(stdout_pipe_writer); 225 | stdout_pipe_writer = nullptr; 226 | } 227 | } 228 | 229 | int Coprocess::wait () 230 | { 231 | if (WaitForSingleObject(proc_handle, INFINITE) == WAIT_FAILED) { 232 | throw System_error("WaitForSingleObject", "", GetLastError()); 233 | } 234 | 235 | DWORD exit_code; 236 | if (!GetExitCodeProcess(proc_handle, &exit_code)) { 237 | throw System_error("GetExitCodeProcess", "", GetLastError()); 238 | } 239 | 240 | return exit_code; 241 | } 242 | 243 | size_t Coprocess::write_stdin (void* handle, const void* buf, size_t count) 244 | { 245 | DWORD bytes_written; 246 | if (!WriteFile(static_cast(handle)->stdin_pipe_writer, buf, count, &bytes_written, nullptr)) { 247 | throw System_error("WriteFile", "", GetLastError()); 248 | } 249 | return bytes_written; 250 | } 251 | 252 | size_t Coprocess::read_stdout (void* handle, void* buf, size_t count) 253 | { 254 | // Note that ReadFile on a pipe may return with bytes_read==0 if the other 255 | // end of the pipe writes zero bytes, so retry when this happens. 256 | // When the other end of the pipe actually closes, ReadFile 257 | // fails with ERROR_BROKEN_PIPE. 258 | DWORD bytes_read; 259 | do { 260 | if (!ReadFile(static_cast(handle)->stdout_pipe_reader, buf, count, &bytes_read, nullptr)) { 261 | const DWORD read_error = GetLastError(); 262 | if (read_error != ERROR_BROKEN_PIPE) { 263 | throw System_error("ReadFile", "", read_error); 264 | } 265 | return 0; 266 | } 267 | } while (bytes_read == 0); 268 | return bytes_read; 269 | } 270 | -------------------------------------------------------------------------------- /coprocess-win32.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Andrew Ayer 3 | * 4 | * This file is part of git-crypt. 5 | * 6 | * git-crypt is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * git-crypt is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with git-crypt. If not, see . 18 | * 19 | * Additional permission under GNU GPL version 3 section 7: 20 | * 21 | * If you modify the Program, or any covered work, by linking or 22 | * combining it with the OpenSSL project's OpenSSL library (or a 23 | * modified version of that library), containing parts covered by the 24 | * terms of the OpenSSL or SSLeay licenses, the licensors of the Program 25 | * grant you additional permission to convey the resulting work. 26 | * Corresponding Source for a non-source form of such a combination 27 | * shall include the source code for the parts of OpenSSL used as well 28 | * as that of the covered work. 29 | */ 30 | 31 | #ifndef GIT_CRYPT_COPROCESS_HPP 32 | #define GIT_CRYPT_COPROCESS_HPP 33 | 34 | #include "fhstream.hpp" 35 | #include 36 | #include 37 | 38 | class Coprocess { 39 | HANDLE proc_handle; 40 | 41 | HANDLE stdin_pipe_reader; 42 | HANDLE stdin_pipe_writer; 43 | ofhstream* stdin_pipe_ostream; 44 | static size_t write_stdin (void*, const void*, size_t); 45 | 46 | HANDLE stdout_pipe_reader; 47 | HANDLE stdout_pipe_writer; 48 | ifhstream* stdout_pipe_istream; 49 | static size_t read_stdout (void*, void*, size_t); 50 | 51 | Coprocess (const Coprocess&); // Disallow copy 52 | Coprocess& operator= (const Coprocess&); // Disallow assignment 53 | public: 54 | Coprocess (); 55 | ~Coprocess (); 56 | 57 | std::ostream* stdin_pipe (); 58 | void close_stdin (); 59 | 60 | std::istream* stdout_pipe (); 61 | void close_stdout (); 62 | 63 | void spawn (const std::vector&); 64 | 65 | int wait (); 66 | }; 67 | 68 | #endif 69 | -------------------------------------------------------------------------------- /coprocess.cpp: -------------------------------------------------------------------------------- 1 | #ifdef _WIN32 2 | #include "coprocess-win32.cpp" 3 | #else 4 | #include "coprocess-unix.cpp" 5 | #endif 6 | -------------------------------------------------------------------------------- /coprocess.hpp: -------------------------------------------------------------------------------- 1 | #ifdef _WIN32 2 | #include "coprocess-win32.hpp" 3 | #else 4 | #include "coprocess-unix.hpp" 5 | #endif 6 | -------------------------------------------------------------------------------- /crypto-openssl-10.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012, 2014 Andrew Ayer 3 | * 4 | * This file is part of git-crypt. 5 | * 6 | * git-crypt is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * git-crypt is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with git-crypt. If not, see . 18 | * 19 | * Additional permission under GNU GPL version 3 section 7: 20 | * 21 | * If you modify the Program, or any covered work, by linking or 22 | * combining it with the OpenSSL project's OpenSSL library (or a 23 | * modified version of that library), containing parts covered by the 24 | * terms of the OpenSSL or SSLeay licenses, the licensors of the Program 25 | * grant you additional permission to convey the resulting work. 26 | * Corresponding Source for a non-source form of such a combination 27 | * shall include the source code for the parts of OpenSSL used as well 28 | * as that of the covered work. 29 | */ 30 | 31 | #include 32 | 33 | #if !defined(OPENSSL_API_COMPAT) 34 | 35 | #include "crypto.hpp" 36 | #include "key.hpp" 37 | #include "util.hpp" 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include 43 | #include 44 | #include 45 | #include 46 | 47 | void init_crypto () 48 | { 49 | ERR_load_crypto_strings(); 50 | } 51 | 52 | struct Aes_ecb_encryptor::Aes_impl { 53 | AES_KEY key; 54 | }; 55 | 56 | Aes_ecb_encryptor::Aes_ecb_encryptor (const unsigned char* raw_key) 57 | : impl(new Aes_impl) 58 | { 59 | if (AES_set_encrypt_key(raw_key, KEY_LEN * 8, &(impl->key)) != 0) { 60 | throw Crypto_error("Aes_ctr_encryptor::Aes_ctr_encryptor", "AES_set_encrypt_key failed"); 61 | } 62 | } 63 | 64 | Aes_ecb_encryptor::~Aes_ecb_encryptor () 65 | { 66 | // Note: Explicit destructor necessary because class contains an unique_ptr 67 | // which contains an incomplete type when the unique_ptr is declared. 68 | 69 | explicit_memset(&impl->key, '\0', sizeof(impl->key)); 70 | } 71 | 72 | void Aes_ecb_encryptor::encrypt(const unsigned char* plain, unsigned char* cipher) 73 | { 74 | AES_encrypt(plain, cipher, &(impl->key)); 75 | } 76 | 77 | struct Hmac_sha1_state::Hmac_impl { 78 | HMAC_CTX ctx; 79 | }; 80 | 81 | Hmac_sha1_state::Hmac_sha1_state (const unsigned char* key, size_t key_len) 82 | : impl(new Hmac_impl) 83 | { 84 | HMAC_Init(&(impl->ctx), key, key_len, EVP_sha1()); 85 | } 86 | 87 | Hmac_sha1_state::~Hmac_sha1_state () 88 | { 89 | // Note: Explicit destructor necessary because class contains an unique_ptr 90 | // which contains an incomplete type when the unique_ptr is declared. 91 | 92 | HMAC_cleanup(&(impl->ctx)); 93 | } 94 | 95 | void Hmac_sha1_state::add (const unsigned char* buffer, size_t buffer_len) 96 | { 97 | HMAC_Update(&(impl->ctx), buffer, buffer_len); 98 | } 99 | 100 | void Hmac_sha1_state::get (unsigned char* digest) 101 | { 102 | unsigned int len; 103 | HMAC_Final(&(impl->ctx), digest, &len); 104 | } 105 | 106 | 107 | void random_bytes (unsigned char* buffer, size_t len) 108 | { 109 | if (RAND_bytes(buffer, len) != 1) { 110 | std::ostringstream message; 111 | while (unsigned long code = ERR_get_error()) { 112 | char error_string[120]; 113 | ERR_error_string_n(code, error_string, sizeof(error_string)); 114 | message << "OpenSSL Error: " << error_string << "; "; 115 | } 116 | throw Crypto_error("random_bytes", message.str()); 117 | } 118 | } 119 | 120 | #endif 121 | -------------------------------------------------------------------------------- /crypto-openssl-11.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012, 2014 Andrew Ayer 3 | * 4 | * This file is part of git-crypt. 5 | * 6 | * git-crypt is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * git-crypt is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with git-crypt. If not, see . 18 | * 19 | * Additional permission under GNU GPL version 3 section 7: 20 | * 21 | * If you modify the Program, or any covered work, by linking or 22 | * combining it with the OpenSSL project's OpenSSL library (or a 23 | * modified version of that library), containing parts covered by the 24 | * terms of the OpenSSL or SSLeay licenses, the licensors of the Program 25 | * grant you additional permission to convey the resulting work. 26 | * Corresponding Source for a non-source form of such a combination 27 | * shall include the source code for the parts of OpenSSL used as well 28 | * as that of the covered work. 29 | */ 30 | 31 | #include 32 | 33 | #if defined(OPENSSL_API_COMPAT) 34 | 35 | #include "crypto.hpp" 36 | #include "key.hpp" 37 | #include "util.hpp" 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include 43 | #include 44 | #include 45 | #include 46 | 47 | void init_crypto () 48 | { 49 | ERR_load_crypto_strings(); 50 | } 51 | 52 | struct Aes_ecb_encryptor::Aes_impl { 53 | AES_KEY key; 54 | }; 55 | 56 | Aes_ecb_encryptor::Aes_ecb_encryptor (const unsigned char* raw_key) 57 | : impl(new Aes_impl) 58 | { 59 | if (AES_set_encrypt_key(raw_key, KEY_LEN * 8, &(impl->key)) != 0) { 60 | throw Crypto_error("Aes_ctr_encryptor::Aes_ctr_encryptor", "AES_set_encrypt_key failed"); 61 | } 62 | } 63 | 64 | Aes_ecb_encryptor::~Aes_ecb_encryptor () 65 | { 66 | // Note: Explicit destructor necessary because class contains an unique_ptr 67 | // which contains an incomplete type when the unique_ptr is declared. 68 | 69 | explicit_memset(&impl->key, '\0', sizeof(impl->key)); 70 | } 71 | 72 | void Aes_ecb_encryptor::encrypt(const unsigned char* plain, unsigned char* cipher) 73 | { 74 | AES_encrypt(plain, cipher, &(impl->key)); 75 | } 76 | 77 | struct Hmac_sha1_state::Hmac_impl { 78 | HMAC_CTX *ctx; 79 | }; 80 | 81 | Hmac_sha1_state::Hmac_sha1_state (const unsigned char* key, size_t key_len) 82 | : impl(new Hmac_impl) 83 | { 84 | 85 | impl->ctx = HMAC_CTX_new(); 86 | HMAC_Init_ex(impl->ctx, key, key_len, EVP_sha1(), nullptr); 87 | } 88 | 89 | Hmac_sha1_state::~Hmac_sha1_state () 90 | { 91 | HMAC_CTX_free(impl->ctx); 92 | } 93 | 94 | void Hmac_sha1_state::add (const unsigned char* buffer, size_t buffer_len) 95 | { 96 | HMAC_Update(impl->ctx, buffer, buffer_len); 97 | } 98 | 99 | void Hmac_sha1_state::get (unsigned char* digest) 100 | { 101 | unsigned int len; 102 | HMAC_Final(impl->ctx, digest, &len); 103 | } 104 | 105 | 106 | void random_bytes (unsigned char* buffer, size_t len) 107 | { 108 | if (RAND_bytes(buffer, len) != 1) { 109 | std::ostringstream message; 110 | while (unsigned long code = ERR_get_error()) { 111 | char error_string[120]; 112 | ERR_error_string_n(code, error_string, sizeof(error_string)); 113 | message << "OpenSSL Error: " << error_string << "; "; 114 | } 115 | throw Crypto_error("random_bytes", message.str()); 116 | } 117 | } 118 | 119 | #endif 120 | -------------------------------------------------------------------------------- /crypto.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012, 2014 Andrew Ayer 3 | * 4 | * This file is part of git-crypt. 5 | * 6 | * git-crypt is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * git-crypt is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with git-crypt. If not, see . 18 | * 19 | * Additional permission under GNU GPL version 3 section 7: 20 | * 21 | * If you modify the Program, or any covered work, by linking or 22 | * combining it with the OpenSSL project's OpenSSL library (or a 23 | * modified version of that library), containing parts covered by the 24 | * terms of the OpenSSL or SSLeay licenses, the licensors of the Program 25 | * grant you additional permission to convey the resulting work. 26 | * Corresponding Source for a non-source form of such a combination 27 | * shall include the source code for the parts of OpenSSL used as well 28 | * as that of the covered work. 29 | */ 30 | 31 | #include "crypto.hpp" 32 | #include "util.hpp" 33 | #include 34 | 35 | Aes_ctr_encryptor::Aes_ctr_encryptor (const unsigned char* raw_key, const unsigned char* nonce) 36 | : ecb(raw_key) 37 | { 38 | // Set first 12 bytes of the CTR value to the nonce. 39 | // This stays the same for the entirety of this object's lifetime. 40 | std::memcpy(ctr_value, nonce, NONCE_LEN); 41 | byte_counter = 0; 42 | } 43 | 44 | Aes_ctr_encryptor::~Aes_ctr_encryptor () 45 | { 46 | explicit_memset(pad, '\0', BLOCK_LEN); 47 | } 48 | 49 | void Aes_ctr_encryptor::process (const unsigned char* in, unsigned char* out, size_t len) 50 | { 51 | for (size_t i = 0; i < len; ++i) { 52 | if (byte_counter % BLOCK_LEN == 0) { 53 | // Set last 4 bytes of CTR to the (big-endian) block number (sequentially increasing with each block) 54 | store_be32(ctr_value + NONCE_LEN, byte_counter / BLOCK_LEN); 55 | 56 | // Generate a new pad 57 | ecb.encrypt(ctr_value, pad); 58 | } 59 | 60 | // encrypt one byte 61 | out[i] = in[i] ^ pad[byte_counter++ % BLOCK_LEN]; 62 | 63 | if (byte_counter == 0) { 64 | throw Crypto_error("Aes_ctr_encryptor::process", "Too much data to encrypt securely"); 65 | } 66 | } 67 | } 68 | 69 | // Encrypt/decrypt an entire input stream, writing to the given output stream 70 | void Aes_ctr_encryptor::process_stream (std::istream& in, std::ostream& out, const unsigned char* key, const unsigned char* nonce) 71 | { 72 | Aes_ctr_encryptor aes(key, nonce); 73 | 74 | unsigned char buffer[1024]; 75 | while (in) { 76 | in.read(reinterpret_cast(buffer), sizeof(buffer)); 77 | aes.process(buffer, buffer, in.gcount()); 78 | out.write(reinterpret_cast(buffer), in.gcount()); 79 | } 80 | } 81 | 82 | -------------------------------------------------------------------------------- /crypto.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012, 2014 Andrew Ayer 3 | * 4 | * This file is part of git-crypt. 5 | * 6 | * git-crypt is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * git-crypt is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with git-crypt. If not, see . 18 | * 19 | * Additional permission under GNU GPL version 3 section 7: 20 | * 21 | * If you modify the Program, or any covered work, by linking or 22 | * combining it with the OpenSSL project's OpenSSL library (or a 23 | * modified version of that library), containing parts covered by the 24 | * terms of the OpenSSL or SSLeay licenses, the licensors of the Program 25 | * grant you additional permission to convey the resulting work. 26 | * Corresponding Source for a non-source form of such a combination 27 | * shall include the source code for the parts of OpenSSL used as well 28 | * as that of the covered work. 29 | */ 30 | 31 | #ifndef GIT_CRYPT_CRYPTO_HPP 32 | #define GIT_CRYPT_CRYPTO_HPP 33 | 34 | #include "key.hpp" 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | 41 | void init_crypto (); 42 | 43 | struct Crypto_error { 44 | std::string where; 45 | std::string message; 46 | 47 | Crypto_error (const std::string& w, const std::string& m) : where(w), message(m) { } 48 | }; 49 | 50 | class Aes_ecb_encryptor { 51 | public: 52 | enum { 53 | KEY_LEN = AES_KEY_LEN, 54 | BLOCK_LEN = 16 55 | }; 56 | 57 | private: 58 | struct Aes_impl; 59 | 60 | std::unique_ptr impl; 61 | 62 | public: 63 | Aes_ecb_encryptor (const unsigned char* key); 64 | ~Aes_ecb_encryptor (); 65 | void encrypt (const unsigned char* plain, unsigned char* cipher); 66 | }; 67 | 68 | class Aes_ctr_encryptor { 69 | public: 70 | enum { 71 | NONCE_LEN = 12, 72 | KEY_LEN = AES_KEY_LEN, 73 | BLOCK_LEN = 16, 74 | MAX_CRYPT_BYTES = (1ULL<<32)*16 // Don't encrypt more than this or the CTR value will repeat itself 75 | }; 76 | 77 | private: 78 | Aes_ecb_encryptor ecb; 79 | unsigned char ctr_value[BLOCK_LEN]; // Current CTR value (used as input to AES to derive pad) 80 | unsigned char pad[BLOCK_LEN]; // Current encryption pad (output of AES) 81 | uint32_t byte_counter; // How many bytes processed so far? 82 | 83 | public: 84 | Aes_ctr_encryptor (const unsigned char* key, const unsigned char* nonce); 85 | ~Aes_ctr_encryptor (); 86 | 87 | void process (const unsigned char* in, unsigned char* out, size_t len); 88 | 89 | // Encrypt/decrypt an entire input stream, writing to the given output stream 90 | static void process_stream (std::istream& in, std::ostream& out, const unsigned char* key, const unsigned char* nonce); 91 | }; 92 | 93 | typedef Aes_ctr_encryptor Aes_ctr_decryptor; 94 | 95 | class Hmac_sha1_state { 96 | public: 97 | enum { 98 | LEN = 20, 99 | KEY_LEN = HMAC_KEY_LEN 100 | }; 101 | 102 | private: 103 | struct Hmac_impl; 104 | 105 | std::unique_ptr impl; 106 | 107 | public: 108 | Hmac_sha1_state (const unsigned char* key, size_t key_len); 109 | ~Hmac_sha1_state (); 110 | 111 | void add (const unsigned char* buffer, size_t buffer_len); 112 | void get (unsigned char*); 113 | }; 114 | 115 | void random_bytes (unsigned char*, size_t); 116 | 117 | #endif 118 | -------------------------------------------------------------------------------- /doc/multiple_keys.md: -------------------------------------------------------------------------------- 1 | In addition to the implicit default key, git-crypt supports alternative 2 | keys which can be used to encrypt specific files and can be shared with 3 | specific GPG users. This is useful if you want to grant different 4 | collaborators access to different sets of files. 5 | 6 | To generate an alternative key named KEYNAME, pass the `-k KEYNAME` 7 | option to `git-crypt init` as follows: 8 | 9 | git-crypt init -k KEYNAME 10 | 11 | To encrypt a file with an alternative key, use the `git-crypt-KEYNAME` 12 | filter in `.gitattributes` as follows: 13 | 14 | secretfile filter=git-crypt-KEYNAME diff=git-crypt-KEYNAME 15 | 16 | To export an alternative key or share it with a GPG user, pass the `-k 17 | KEYNAME` option to `git-crypt export-key` or `git-crypt add-gpg-user` 18 | as follows: 19 | 20 | git-crypt export-key -k KEYNAME /path/to/keyfile 21 | git-crypt add-gpg-user -k KEYNAME GPG_USER_ID 22 | 23 | To unlock a repository with an alternative key, use `git-crypt unlock` 24 | normally. git-crypt will automatically determine which key is being used. 25 | -------------------------------------------------------------------------------- /fhstream.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012, 2015 Andrew Ayer 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included 12 | * in all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 18 | * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 19 | * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 20 | * OTHER DEALINGS IN THE SOFTWARE. 21 | * 22 | * Except as contained in this notice, the name(s) of the above copyright 23 | * holders shall not be used in advertising or otherwise to promote the 24 | * sale, use or other dealings in this Software without prior written 25 | * authorization. 26 | */ 27 | 28 | #include 29 | #include // for std::min 30 | 31 | #include "fhstream.hpp" 32 | 33 | /* 34 | * ofhstream 35 | */ 36 | 37 | ofhbuf::ofhbuf (void* arg_handle, size_t (*arg_write_fun)(void*, const void*, size_t)) 38 | : handle(arg_handle), 39 | write_fun(arg_write_fun), 40 | buffer(new char[default_buffer_size]), 41 | buffer_size(default_buffer_size) 42 | { 43 | reset_buffer(); 44 | } 45 | 46 | ofhbuf::~ofhbuf () 47 | { 48 | if (handle) { 49 | try { 50 | sync(); 51 | } catch (...) { 52 | // Ignore exception since we're in the destructor. 53 | // To catch write errors, call sync() explicitly. 54 | } 55 | } 56 | delete[] buffer; 57 | } 58 | 59 | ofhbuf::int_type ofhbuf::overflow (ofhbuf::int_type c) 60 | { 61 | const char* p = pbase(); 62 | std::streamsize bytes_to_write = pptr() - p; 63 | 64 | if (!is_eof(c)) { 65 | *pptr() = c; 66 | ++bytes_to_write; 67 | } 68 | 69 | while (bytes_to_write > 0) { 70 | const size_t bytes_written = write_fun(handle, p, bytes_to_write); 71 | bytes_to_write -= bytes_written; 72 | p += bytes_written; 73 | } 74 | 75 | reset_buffer(); 76 | 77 | return traits_type::to_int_type(0); 78 | } 79 | 80 | int ofhbuf::sync () 81 | { 82 | return !is_eof(overflow(traits_type::eof())) ? 0 : -1; 83 | } 84 | 85 | std::streamsize ofhbuf::xsputn (const char* s, std::streamsize n) 86 | { 87 | // Use heuristic to decide whether to write directly or just use buffer 88 | // Write directly only if n >= MIN(4096, available buffer capacity) 89 | // (this is similar to what basic_filebuf does) 90 | 91 | if (n < std::min(4096, epptr() - pptr())) { 92 | // Not worth it to do a direct write 93 | return std::streambuf::xsputn(s, n); 94 | } 95 | 96 | // Before we can do a direct write of this string, we need to flush 97 | // out the current contents of the buffer. 98 | if (pbase() != pptr()) { 99 | overflow(traits_type::eof()); // throws an exception or it succeeds 100 | } 101 | 102 | // Now we can go ahead and write out the string. 103 | size_t bytes_to_write = n; 104 | 105 | while (bytes_to_write > 0) { 106 | const size_t bytes_written = write_fun(handle, s, bytes_to_write); 107 | bytes_to_write -= bytes_written; 108 | s += bytes_written; 109 | } 110 | 111 | return n; // Return the total bytes written 112 | } 113 | 114 | std::streambuf* ofhbuf::setbuf (char* s, std::streamsize n) 115 | { 116 | if (s == 0 && n == 0) { 117 | // Switch to unbuffered 118 | // This won't take effect until the next overflow or sync 119 | // (We defer it taking effect so that write errors can be properly reported) 120 | // To cause it to take effect as soon as possible, we artificially reduce the 121 | // size of the buffer so it has no space left. This will trigger an overflow 122 | // on the next put. 123 | std::streambuf::setp(pbase(), pptr()); 124 | std::streambuf::pbump(pptr() - pbase()); 125 | buffer_size = 1; 126 | } 127 | return this; 128 | } 129 | 130 | 131 | 132 | /* 133 | * ifhstream 134 | */ 135 | 136 | ifhbuf::ifhbuf (void* arg_handle, size_t (*arg_read_fun)(void*, void*, size_t)) 137 | : handle(arg_handle), 138 | read_fun(arg_read_fun), 139 | buffer(new char[default_buffer_size + putback_size]), 140 | buffer_size(default_buffer_size) 141 | { 142 | reset_buffer(0, 0); 143 | } 144 | 145 | ifhbuf::~ifhbuf () 146 | { 147 | delete[] buffer; 148 | } 149 | 150 | ifhbuf::int_type ifhbuf::underflow () 151 | { 152 | if (gptr() >= egptr()) { // A true underflow (no bytes in buffer left to read) 153 | 154 | // Move the putback_size most-recently-read characters into the putback area 155 | size_t nputback = std::min(gptr() - eback(), putback_size); 156 | std::memmove(buffer + (putback_size - nputback), gptr() - nputback, nputback); 157 | 158 | // Now read new characters from the file descriptor 159 | const size_t nread = read_fun(handle, buffer + putback_size, buffer_size); 160 | if (nread == 0) { 161 | // EOF 162 | return traits_type::eof(); 163 | } 164 | 165 | // Reset the buffer 166 | reset_buffer(nputback, nread); 167 | } 168 | 169 | // Return the next character 170 | return traits_type::to_int_type(*gptr()); 171 | } 172 | 173 | std::streamsize ifhbuf::xsgetn (char* s, std::streamsize n) 174 | { 175 | // Use heuristic to decide whether to read directly 176 | // Read directly only if n >= bytes_available + 4096 177 | 178 | std::streamsize bytes_available = egptr() - gptr(); 179 | 180 | if (n < bytes_available + 4096) { 181 | // Not worth it to do a direct read 182 | return std::streambuf::xsgetn(s, n); 183 | } 184 | 185 | std::streamsize total_bytes_read = 0; 186 | 187 | // First, copy out the bytes currently in the buffer 188 | std::memcpy(s, gptr(), bytes_available); 189 | 190 | s += bytes_available; 191 | n -= bytes_available; 192 | total_bytes_read += bytes_available; 193 | 194 | // Now do the direct read 195 | while (n > 0) { 196 | const size_t bytes_read = read_fun(handle, s, n); 197 | if (bytes_read == 0) { 198 | // EOF 199 | break; 200 | } 201 | 202 | s += bytes_read; 203 | n -= bytes_read; 204 | total_bytes_read += bytes_read; 205 | } 206 | 207 | // Fill up the putback area with the most recently read characters 208 | size_t nputback = std::min(total_bytes_read, putback_size); 209 | std::memcpy(buffer + (putback_size - nputback), s - nputback, nputback); 210 | 211 | // Reset the buffer with no bytes available for reading, but with some putback characters 212 | reset_buffer(nputback, 0); 213 | 214 | // Return the total number of bytes read 215 | return total_bytes_read; 216 | } 217 | 218 | std::streambuf* ifhbuf::setbuf (char* s, std::streamsize n) 219 | { 220 | if (s == 0 && n == 0) { 221 | // Switch to unbuffered 222 | // This won't take effect until the next underflow (we don't want to 223 | // lose what's currently in the buffer!) 224 | buffer_size = 1; 225 | } 226 | return this; 227 | } 228 | -------------------------------------------------------------------------------- /fhstream.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012, 2015 Andrew Ayer 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included 12 | * in all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 18 | * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 19 | * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 20 | * OTHER DEALINGS IN THE SOFTWARE. 21 | * 22 | * Except as contained in this notice, the name(s) of the above copyright 23 | * holders shall not be used in advertising or otherwise to promote the 24 | * sale, use or other dealings in this Software without prior written 25 | * authorization. 26 | */ 27 | 28 | #ifndef GIT_CRYPT_FHSTREAM_HPP 29 | #define GIT_CRYPT_FHSTREAM_HPP 30 | 31 | #include 32 | #include 33 | #include 34 | 35 | /* 36 | * ofhstream 37 | */ 38 | class ofhbuf : public std::streambuf { 39 | enum { default_buffer_size = 8192 }; 40 | 41 | void* handle; 42 | size_t (*write_fun)(void*, const void*, size_t); 43 | char* buffer; 44 | size_t buffer_size; 45 | 46 | inline void reset_buffer () 47 | { 48 | std::streambuf::setp(buffer, buffer + buffer_size - 1); 49 | } 50 | static inline bool is_eof (int_type ch) { return traits_type::eq_int_type(ch, traits_type::eof()); } 51 | 52 | // Disallow copy 53 | #if __cplusplus >= 201103L /* C++11 */ 54 | ofhbuf (const ofhbuf&) = delete; 55 | ofhbuf& operator= (const ofhbuf&) = delete; 56 | #else 57 | ofhbuf (const ofhbuf&); 58 | ofhbuf& operator= (const ofhbuf&); 59 | #endif 60 | 61 | protected: 62 | virtual int_type overflow (int_type ch =traits_type::eof()); 63 | virtual int sync (); 64 | virtual std::streamsize xsputn (const char*, std::streamsize); 65 | virtual std::streambuf* setbuf (char*, std::streamsize); 66 | 67 | public: 68 | ofhbuf (void*, size_t (*)(void*, const void*, size_t)); 69 | ~ofhbuf (); // WARNING: calls sync() and ignores exceptions 70 | }; 71 | 72 | class ofhstream : public std::ostream { 73 | mutable ofhbuf buf; 74 | public: 75 | ofhstream (void* handle, size_t (*write_fun)(void*, const void*, size_t)) 76 | : std::ostream(0), buf(handle, write_fun) 77 | { 78 | std::ostream::rdbuf(&buf); 79 | } 80 | 81 | ofhbuf* rdbuf () const { return &buf; } 82 | }; 83 | 84 | 85 | /* 86 | * ifhstream 87 | */ 88 | class ifhbuf : public std::streambuf { 89 | enum { 90 | default_buffer_size = 8192, 91 | putback_size = 4 92 | }; 93 | 94 | void* handle; 95 | size_t (*read_fun)(void*, void*, size_t); 96 | char* buffer; 97 | size_t buffer_size; 98 | 99 | inline void reset_buffer (size_t nputback, size_t nread) 100 | { 101 | std::streambuf::setg(buffer + (putback_size - nputback), buffer + putback_size, buffer + putback_size + nread); 102 | } 103 | // Disallow copy 104 | #if __cplusplus >= 201103L /* C++11 */ 105 | ifhbuf (const ifhbuf&) = delete; 106 | ifhbuf& operator= (const ifhbuf&) = delete; 107 | #else 108 | ifhbuf (const ifhbuf&); 109 | ifhbuf& operator= (const ifhbuf&); 110 | #endif 111 | 112 | protected: 113 | virtual int_type underflow (); 114 | virtual std::streamsize xsgetn (char*, std::streamsize); 115 | virtual std::streambuf* setbuf (char*, std::streamsize); 116 | 117 | public: 118 | ifhbuf (void*, size_t (*)(void*, void*, size_t)); 119 | ~ifhbuf (); // Can't fail 120 | }; 121 | 122 | class ifhstream : public std::istream { 123 | mutable ifhbuf buf; 124 | public: 125 | explicit ifhstream (void* handle, size_t (*read_fun)(void*, void*, size_t)) 126 | : std::istream(0), buf(handle, read_fun) 127 | { 128 | std::istream::rdbuf(&buf); 129 | } 130 | 131 | ifhbuf* rdbuf () const { return &buf; } 132 | }; 133 | 134 | #endif 135 | -------------------------------------------------------------------------------- /git-crypt.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012, 2014 Andrew Ayer 3 | * 4 | * This file is part of git-crypt. 5 | * 6 | * git-crypt is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * git-crypt is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with git-crypt. If not, see . 18 | * 19 | * Additional permission under GNU GPL version 3 section 7: 20 | * 21 | * If you modify the Program, or any covered work, by linking or 22 | * combining it with the OpenSSL project's OpenSSL library (or a 23 | * modified version of that library), containing parts covered by the 24 | * terms of the OpenSSL or SSLeay licenses, the licensors of the Program 25 | * grant you additional permission to convey the resulting work. 26 | * Corresponding Source for a non-source form of such a combination 27 | * shall include the source code for the parts of OpenSSL used as well 28 | * as that of the covered work. 29 | */ 30 | 31 | #include "git-crypt.hpp" 32 | #include "commands.hpp" 33 | #include "util.hpp" 34 | #include "crypto.hpp" 35 | #include "key.hpp" 36 | #include "gpg.hpp" 37 | #include "parse_options.hpp" 38 | #include 39 | #include 40 | #include 41 | #include 42 | 43 | const char* argv0; 44 | 45 | static void print_usage (std::ostream& out) 46 | { 47 | out << "Usage: " << argv0 << " COMMAND [ARGS ...]" << std::endl; 48 | out << std::endl; 49 | // |--------------------------------------------------------------------------------| 80 characters 50 | out << "Common commands:" << std::endl; 51 | out << " init generate a key and prepare repo to use git-crypt" << std::endl; 52 | out << " status display which files are encrypted" << std::endl; 53 | //out << " refresh ensure all files in the repo are properly decrypted" << std::endl; 54 | out << " lock de-configure git-crypt and re-encrypt files in work tree" << std::endl; 55 | out << std::endl; 56 | out << "GPG commands:" << std::endl; 57 | out << " add-gpg-user USERID add the user with the given GPG user ID as a collaborator" << std::endl; 58 | //out << " rm-gpg-user USERID revoke collaborator status from the given GPG user ID" << std::endl; 59 | //out << " ls-gpg-users list the GPG key IDs of collaborators" << std::endl; 60 | out << " unlock decrypt this repo using the in-repo GPG-encrypted key" << std::endl; 61 | out << std::endl; 62 | out << "Symmetric key commands:" << std::endl; 63 | out << " export-key FILE export this repo's symmetric key to the given file" << std::endl; 64 | out << " unlock KEYFILE decrypt this repo using the given symmetric key" << std::endl; 65 | out << std::endl; 66 | out << "Legacy commands:" << std::endl; 67 | out << " init KEYFILE alias for 'unlock KEYFILE'" << std::endl; 68 | out << " keygen KEYFILE generate a git-crypt key in the given file" << std::endl; 69 | out << " migrate-key OLD NEW migrate the legacy key file OLD to the new format in NEW" << std::endl; 70 | /* 71 | out << std::endl; 72 | out << "Plumbing commands (not to be used directly):" << std::endl; 73 | out << " clean [LEGACY-KEYFILE]" << std::endl; 74 | out << " smudge [LEGACY-KEYFILE]" << std::endl; 75 | out << " diff [LEGACY-KEYFILE] FILE" << std::endl; 76 | */ 77 | out << std::endl; 78 | out << "See 'git-crypt help COMMAND' for more information on a specific command." << std::endl; 79 | } 80 | 81 | static void print_version (std::ostream& out) 82 | { 83 | out << "git-crypt " << VERSION << std::endl; 84 | } 85 | 86 | static bool help_for_command (const char* command, std::ostream& out) 87 | { 88 | if (std::strcmp(command, "init") == 0) { 89 | help_init(out); 90 | } else if (std::strcmp(command, "unlock") == 0) { 91 | help_unlock(out); 92 | } else if (std::strcmp(command, "lock") == 0) { 93 | help_lock(out); 94 | } else if (std::strcmp(command, "add-gpg-user") == 0) { 95 | help_add_gpg_user(out); 96 | } else if (std::strcmp(command, "rm-gpg-user") == 0) { 97 | help_rm_gpg_user(out); 98 | } else if (std::strcmp(command, "ls-gpg-users") == 0) { 99 | help_ls_gpg_users(out); 100 | } else if (std::strcmp(command, "export-key") == 0) { 101 | help_export_key(out); 102 | } else if (std::strcmp(command, "keygen") == 0) { 103 | help_keygen(out); 104 | } else if (std::strcmp(command, "migrate-key") == 0) { 105 | help_migrate_key(out); 106 | } else if (std::strcmp(command, "refresh") == 0) { 107 | help_refresh(out); 108 | } else if (std::strcmp(command, "status") == 0) { 109 | help_status(out); 110 | } else { 111 | return false; 112 | } 113 | return true; 114 | } 115 | 116 | static int help (int argc, const char** argv) 117 | { 118 | if (argc == 0) { 119 | print_usage(std::cout); 120 | } else { 121 | if (!help_for_command(argv[0], std::cout)) { 122 | std::clog << "Error: '" << argv[0] << "' is not a git-crypt command. See 'git-crypt help'." << std::endl; 123 | return 1; 124 | } 125 | } 126 | return 0; 127 | } 128 | 129 | static int version (int argc, const char** argv) 130 | { 131 | print_version(std::cout); 132 | return 0; 133 | } 134 | 135 | 136 | int main (int argc, const char** argv) 137 | try { 138 | argv0 = argv[0]; 139 | 140 | /* 141 | * General initialization 142 | */ 143 | 144 | init_std_streams(); 145 | init_crypto(); 146 | 147 | /* 148 | * Parse command line arguments 149 | */ 150 | int arg_index = 1; 151 | while (arg_index < argc && argv[arg_index][0] == '-') { 152 | if (std::strcmp(argv[arg_index], "--help") == 0) { 153 | print_usage(std::clog); 154 | return 0; 155 | } else if (std::strcmp(argv[arg_index], "--version") == 0) { 156 | print_version(std::clog); 157 | return 0; 158 | } else if (std::strcmp(argv[arg_index], "--") == 0) { 159 | ++arg_index; 160 | break; 161 | } else { 162 | std::clog << argv0 << ": " << argv[arg_index] << ": Unknown option" << std::endl; 163 | print_usage(std::clog); 164 | return 2; 165 | } 166 | } 167 | 168 | argc -= arg_index; 169 | argv += arg_index; 170 | 171 | if (argc == 0) { 172 | print_usage(std::clog); 173 | return 2; 174 | } 175 | 176 | /* 177 | * Pass off to command handler 178 | */ 179 | const char* command = argv[0]; 180 | --argc; 181 | ++argv; 182 | 183 | try { 184 | // Public commands: 185 | if (std::strcmp(command, "help") == 0) { 186 | return help(argc, argv); 187 | } 188 | if (std::strcmp(command, "version") == 0) { 189 | return version(argc, argv); 190 | } 191 | if (std::strcmp(command, "init") == 0) { 192 | return init(argc, argv); 193 | } 194 | if (std::strcmp(command, "unlock") == 0) { 195 | return unlock(argc, argv); 196 | } 197 | if (std::strcmp(command, "lock") == 0) { 198 | return lock(argc, argv); 199 | } 200 | if (std::strcmp(command, "add-gpg-user") == 0) { 201 | return add_gpg_user(argc, argv); 202 | } 203 | if (std::strcmp(command, "rm-gpg-user") == 0) { 204 | return rm_gpg_user(argc, argv); 205 | } 206 | if (std::strcmp(command, "ls-gpg-users") == 0) { 207 | return ls_gpg_users(argc, argv); 208 | } 209 | if (std::strcmp(command, "export-key") == 0) { 210 | return export_key(argc, argv); 211 | } 212 | if (std::strcmp(command, "keygen") == 0) { 213 | return keygen(argc, argv); 214 | } 215 | if (std::strcmp(command, "migrate-key") == 0) { 216 | return migrate_key(argc, argv); 217 | } 218 | if (std::strcmp(command, "refresh") == 0) { 219 | return refresh(argc, argv); 220 | } 221 | if (std::strcmp(command, "status") == 0) { 222 | return status(argc, argv); 223 | } 224 | // Plumbing commands (executed by git, not by user): 225 | if (std::strcmp(command, "clean") == 0) { 226 | return clean(argc, argv); 227 | } 228 | if (std::strcmp(command, "smudge") == 0) { 229 | return smudge(argc, argv); 230 | } 231 | if (std::strcmp(command, "diff") == 0) { 232 | return diff(argc, argv); 233 | } 234 | } catch (const Option_error& e) { 235 | std::clog << "git-crypt: Error: " << e.option_name << ": " << e.message << std::endl; 236 | help_for_command(command, std::clog); 237 | return 2; 238 | } 239 | 240 | std::clog << "Error: '" << command << "' is not a git-crypt command. See 'git-crypt help'." << std::endl; 241 | return 2; 242 | 243 | } catch (const Error& e) { 244 | std::cerr << "git-crypt: Error: " << e.message << std::endl; 245 | return 1; 246 | } catch (const Gpg_error& e) { 247 | std::cerr << "git-crypt: GPG error: " << e.message << std::endl; 248 | return 1; 249 | } catch (const System_error& e) { 250 | std::cerr << "git-crypt: System error: " << e.message() << std::endl; 251 | return 1; 252 | } catch (const Crypto_error& e) { 253 | std::cerr << "git-crypt: Crypto error: " << e.where << ": " << e.message << std::endl; 254 | return 1; 255 | } catch (Key_file::Incompatible) { 256 | std::cerr << "git-crypt: This repository contains a incompatible key file. Please upgrade git-crypt." << std::endl; 257 | return 1; 258 | } catch (Key_file::Malformed) { 259 | std::cerr << "git-crypt: This repository contains a malformed key file. It may be corrupted." << std::endl; 260 | return 1; 261 | } catch (const std::ios_base::failure& e) { 262 | std::cerr << "git-crypt: I/O error: " << e.what() << std::endl; 263 | return 1; 264 | } 265 | 266 | 267 | -------------------------------------------------------------------------------- /git-crypt.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Andrew Ayer 3 | * 4 | * This file is part of git-crypt. 5 | * 6 | * git-crypt is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * git-crypt is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with git-crypt. If not, see . 18 | * 19 | * Additional permission under GNU GPL version 3 section 7: 20 | * 21 | * If you modify the Program, or any covered work, by linking or 22 | * combining it with the OpenSSL project's OpenSSL library (or a 23 | * modified version of that library), containing parts covered by the 24 | * terms of the OpenSSL or SSLeay licenses, the licensors of the Program 25 | * grant you additional permission to convey the resulting work. 26 | * Corresponding Source for a non-source form of such a combination 27 | * shall include the source code for the parts of OpenSSL used as well 28 | * as that of the covered work. 29 | */ 30 | 31 | #ifndef GIT_CRYPT_GIT_CRYPT_HPP 32 | #define GIT_CRYPT_GIT_CRYPT_HPP 33 | 34 | #define VERSION "0.7.0" 35 | 36 | extern const char* argv0; // initialized in main() to argv[0] 37 | 38 | #endif 39 | -------------------------------------------------------------------------------- /gpg.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Andrew Ayer 3 | * 4 | * This file is part of git-crypt. 5 | * 6 | * git-crypt is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * git-crypt is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with git-crypt. If not, see . 18 | * 19 | * Additional permission under GNU GPL version 3 section 7: 20 | * 21 | * If you modify the Program, or any covered work, by linking or 22 | * combining it with the OpenSSL project's OpenSSL library (or a 23 | * modified version of that library), containing parts covered by the 24 | * terms of the OpenSSL or SSLeay licenses, the licensors of the Program 25 | * grant you additional permission to convey the resulting work. 26 | * Corresponding Source for a non-source form of such a combination 27 | * shall include the source code for the parts of OpenSSL used as well 28 | * as that of the covered work. 29 | */ 30 | 31 | #include "gpg.hpp" 32 | #include "util.hpp" 33 | #include "commands.hpp" 34 | #include 35 | 36 | static std::string gpg_get_executable() 37 | { 38 | std::string gpgbin = "gpg"; 39 | try { 40 | gpgbin = get_git_config("gpg.program"); 41 | } catch (...) { 42 | } 43 | return gpgbin; 44 | } 45 | static std::string gpg_nth_column (const std::string& line, unsigned int col) 46 | { 47 | std::string::size_type pos = 0; 48 | 49 | for (unsigned int i = 0; i < col; ++i) { 50 | pos = line.find_first_of(':', pos); 51 | if (pos == std::string::npos) { 52 | throw Gpg_error("Malformed output from gpg"); 53 | } 54 | pos = pos + 1; 55 | } 56 | 57 | const std::string::size_type end_pos = line.find_first_of(':', pos); 58 | 59 | return end_pos != std::string::npos ? 60 | line.substr(pos, end_pos - pos) : 61 | line.substr(pos); 62 | } 63 | 64 | // given a key fingerprint, return the key's UID (e.g. "John Smith ") 65 | std::string gpg_get_uid (const std::string& fingerprint) 66 | { 67 | // gpg --batch --with-colons --fixed-list-mode --list-keys 0x7A399B2DB06D039020CD1CE1D0F3702D61489532 68 | std::vector command; 69 | command.push_back(gpg_get_executable()); 70 | command.push_back("--batch"); 71 | command.push_back("--with-colons"); 72 | command.push_back("--fixed-list-mode"); 73 | command.push_back("--list-keys"); 74 | command.push_back("0x" + fingerprint); 75 | std::stringstream command_output; 76 | if (!successful_exit(exec_command(command, command_output))) { 77 | // This could happen if the keyring does not contain a public key with this fingerprint 78 | return ""; 79 | } 80 | 81 | while (command_output.peek() != -1) { 82 | std::string line; 83 | std::getline(command_output, line); 84 | if (line.substr(0, 4) == "uid:") { 85 | // uid:u::::1395975462::AB97D6E3E5D8789988CA55E5F77D9E7397D05229::John Smith : 86 | // want the 9th column (counting from 0) 87 | return gpg_nth_column(line, 9); 88 | } 89 | } 90 | 91 | return ""; 92 | } 93 | 94 | // return a list of fingerprints of public keys matching the given search query (such as jsmith@example.com) 95 | std::vector gpg_lookup_key (const std::string& query) 96 | { 97 | std::vector fingerprints; 98 | 99 | // gpg --batch --with-colons --fingerprint --list-keys jsmith@example.com 100 | std::vector command; 101 | command.push_back(gpg_get_executable()); 102 | command.push_back("--batch"); 103 | command.push_back("--with-colons"); 104 | command.push_back("--fingerprint"); 105 | command.push_back("--list-keys"); 106 | command.push_back(query); 107 | std::stringstream command_output; 108 | if (successful_exit(exec_command(command, command_output))) { 109 | bool is_pubkey = false; 110 | while (command_output.peek() != -1) { 111 | std::string line; 112 | std::getline(command_output, line); 113 | if (line.substr(0, 4) == "pub:") { 114 | is_pubkey = true; 115 | } else if (line.substr(0, 4) == "sub:") { 116 | is_pubkey = false; 117 | } else if (is_pubkey && line.substr(0, 4) == "fpr:") { 118 | // fpr:::::::::7A399B2DB06D039020CD1CE1D0F3702D61489532: 119 | // want the 9th column (counting from 0) 120 | fingerprints.push_back(gpg_nth_column(line, 9)); 121 | } 122 | } 123 | } 124 | 125 | return fingerprints; 126 | } 127 | 128 | std::vector gpg_list_secret_keys () 129 | { 130 | // gpg --batch --with-colons --list-secret-keys --fingerprint 131 | std::vector command; 132 | command.push_back(gpg_get_executable()); 133 | command.push_back("--batch"); 134 | command.push_back("--with-colons"); 135 | command.push_back("--list-secret-keys"); 136 | command.push_back("--fingerprint"); 137 | std::stringstream command_output; 138 | if (!successful_exit(exec_command(command, command_output))) { 139 | throw Gpg_error("gpg --list-secret-keys failed"); 140 | } 141 | 142 | std::vector secret_keys; 143 | 144 | while (command_output.peek() != -1) { 145 | std::string line; 146 | std::getline(command_output, line); 147 | if (line.substr(0, 4) == "fpr:") { 148 | // fpr:::::::::7A399B2DB06D039020CD1CE1D0F3702D61489532: 149 | // want the 9th column (counting from 0) 150 | secret_keys.push_back(gpg_nth_column(line, 9)); 151 | } 152 | } 153 | 154 | return secret_keys; 155 | } 156 | 157 | void gpg_encrypt_to_file (const std::string& filename, const std::string& recipient_fingerprint, bool key_is_trusted, const char* p, size_t len) 158 | { 159 | // gpg --batch -o FILENAME -r RECIPIENT -e 160 | std::vector command; 161 | command.push_back(gpg_get_executable()); 162 | command.push_back("--batch"); 163 | if (key_is_trusted) { 164 | command.push_back("--trust-model"); 165 | command.push_back("always"); 166 | } 167 | command.push_back("-o"); 168 | command.push_back(filename); 169 | command.push_back("-r"); 170 | command.push_back("0x" + recipient_fingerprint); 171 | command.push_back("-e"); 172 | if (!successful_exit(exec_command_with_input(command, p, len))) { 173 | throw Gpg_error("Failed to encrypt"); 174 | } 175 | } 176 | 177 | void gpg_decrypt_from_file (const std::string& filename, std::ostream& output) 178 | { 179 | // gpg -q -d FILENAME 180 | std::vector command; 181 | command.push_back(gpg_get_executable()); 182 | command.push_back("-q"); 183 | command.push_back("-d"); 184 | command.push_back(filename); 185 | if (!successful_exit(exec_command(command, output))) { 186 | throw Gpg_error("Failed to decrypt"); 187 | } 188 | } 189 | 190 | -------------------------------------------------------------------------------- /gpg.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Andrew Ayer 3 | * 4 | * This file is part of git-crypt. 5 | * 6 | * git-crypt is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * git-crypt is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with git-crypt. If not, see . 18 | * 19 | * Additional permission under GNU GPL version 3 section 7: 20 | * 21 | * If you modify the Program, or any covered work, by linking or 22 | * combining it with the OpenSSL project's OpenSSL library (or a 23 | * modified version of that library), containing parts covered by the 24 | * terms of the OpenSSL or SSLeay licenses, the licensors of the Program 25 | * grant you additional permission to convey the resulting work. 26 | * Corresponding Source for a non-source form of such a combination 27 | * shall include the source code for the parts of OpenSSL used as well 28 | * as that of the covered work. 29 | */ 30 | 31 | #ifndef GIT_CRYPT_GPG_HPP 32 | #define GIT_CRYPT_GPG_HPP 33 | 34 | #include 35 | #include 36 | #include 37 | 38 | struct Gpg_error { 39 | std::string message; 40 | 41 | explicit Gpg_error (std::string m) : message(m) { } 42 | }; 43 | 44 | std::string gpg_get_uid (const std::string& fingerprint); 45 | std::vector gpg_lookup_key (const std::string& query); 46 | std::vector gpg_list_secret_keys (); 47 | void gpg_encrypt_to_file (const std::string& filename, const std::string& recipient_fingerprint, bool key_is_trusted, const char* p, size_t len); 48 | void gpg_decrypt_from_file (const std::string& filename, std::ostream&); 49 | 50 | #endif 51 | -------------------------------------------------------------------------------- /key.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Andrew Ayer 3 | * 4 | * This file is part of git-crypt. 5 | * 6 | * git-crypt is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * git-crypt is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with git-crypt. If not, see . 18 | * 19 | * Additional permission under GNU GPL version 3 section 7: 20 | * 21 | * If you modify the Program, or any covered work, by linking or 22 | * combining it with the OpenSSL project's OpenSSL library (or a 23 | * modified version of that library), containing parts covered by the 24 | * terms of the OpenSSL or SSLeay licenses, the licensors of the Program 25 | * grant you additional permission to convey the resulting work. 26 | * Corresponding Source for a non-source form of such a combination 27 | * shall include the source code for the parts of OpenSSL used as well 28 | * as that of the covered work. 29 | */ 30 | 31 | #include "key.hpp" 32 | #include "util.hpp" 33 | #include "crypto.hpp" 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include 43 | #include 44 | 45 | Key_file::Entry::Entry () 46 | { 47 | version = 0; 48 | explicit_memset(aes_key, 0, AES_KEY_LEN); 49 | explicit_memset(hmac_key, 0, HMAC_KEY_LEN); 50 | } 51 | 52 | void Key_file::Entry::load (std::istream& in) 53 | { 54 | while (true) { 55 | uint32_t field_id; 56 | if (!read_be32(in, field_id)) { 57 | throw Malformed(); 58 | } 59 | if (field_id == KEY_FIELD_END) { 60 | break; 61 | } 62 | uint32_t field_len; 63 | if (!read_be32(in, field_len)) { 64 | throw Malformed(); 65 | } 66 | 67 | if (field_id == KEY_FIELD_VERSION) { 68 | if (field_len != 4) { 69 | throw Malformed(); 70 | } 71 | if (!read_be32(in, version)) { 72 | throw Malformed(); 73 | } 74 | } else if (field_id == KEY_FIELD_AES_KEY) { 75 | if (field_len != AES_KEY_LEN) { 76 | throw Malformed(); 77 | } 78 | in.read(reinterpret_cast(aes_key), AES_KEY_LEN); 79 | if (in.gcount() != AES_KEY_LEN) { 80 | throw Malformed(); 81 | } 82 | } else if (field_id == KEY_FIELD_HMAC_KEY) { 83 | if (field_len != HMAC_KEY_LEN) { 84 | throw Malformed(); 85 | } 86 | in.read(reinterpret_cast(hmac_key), HMAC_KEY_LEN); 87 | if (in.gcount() != HMAC_KEY_LEN) { 88 | throw Malformed(); 89 | } 90 | } else if (field_id & 1) { // unknown critical field 91 | throw Incompatible(); 92 | } else { 93 | // unknown non-critical field - safe to ignore 94 | if (field_len > MAX_FIELD_LEN) { 95 | throw Malformed(); 96 | } 97 | in.ignore(field_len); 98 | if (in.gcount() != static_cast(field_len)) { 99 | throw Malformed(); 100 | } 101 | } 102 | } 103 | } 104 | 105 | void Key_file::Entry::load_legacy (uint32_t arg_version, std::istream& in) 106 | { 107 | version = arg_version; 108 | 109 | // First comes the AES key 110 | in.read(reinterpret_cast(aes_key), AES_KEY_LEN); 111 | if (in.gcount() != AES_KEY_LEN) { 112 | throw Malformed(); 113 | } 114 | 115 | // Then the HMAC key 116 | in.read(reinterpret_cast(hmac_key), HMAC_KEY_LEN); 117 | if (in.gcount() != HMAC_KEY_LEN) { 118 | throw Malformed(); 119 | } 120 | 121 | if (in.peek() != -1) { 122 | // Trailing data is a good indication that we are not actually reading a 123 | // legacy key file. (This is important to check since legacy key files 124 | // did not have any sort of file header.) 125 | throw Malformed(); 126 | } 127 | } 128 | 129 | void Key_file::Entry::store (std::ostream& out) const 130 | { 131 | // Version 132 | write_be32(out, KEY_FIELD_VERSION); 133 | write_be32(out, 4); 134 | write_be32(out, version); 135 | 136 | // AES key 137 | write_be32(out, KEY_FIELD_AES_KEY); 138 | write_be32(out, AES_KEY_LEN); 139 | out.write(reinterpret_cast(aes_key), AES_KEY_LEN); 140 | 141 | // HMAC key 142 | write_be32(out, KEY_FIELD_HMAC_KEY); 143 | write_be32(out, HMAC_KEY_LEN); 144 | out.write(reinterpret_cast(hmac_key), HMAC_KEY_LEN); 145 | 146 | // End 147 | write_be32(out, KEY_FIELD_END); 148 | } 149 | 150 | void Key_file::Entry::generate (uint32_t arg_version) 151 | { 152 | version = arg_version; 153 | random_bytes(aes_key, AES_KEY_LEN); 154 | random_bytes(hmac_key, HMAC_KEY_LEN); 155 | } 156 | 157 | const Key_file::Entry* Key_file::get_latest () const 158 | { 159 | return is_filled() ? get(latest()) : 0; 160 | } 161 | 162 | const Key_file::Entry* Key_file::get (uint32_t version) const 163 | { 164 | Map::const_iterator it(entries.find(version)); 165 | return it != entries.end() ? &it->second : 0; 166 | } 167 | 168 | void Key_file::add (const Entry& entry) 169 | { 170 | entries[entry.version] = entry; 171 | } 172 | 173 | 174 | void Key_file::load_legacy (std::istream& in) 175 | { 176 | entries[0].load_legacy(0, in); 177 | } 178 | 179 | void Key_file::load (std::istream& in) 180 | { 181 | unsigned char preamble[16]; 182 | in.read(reinterpret_cast(preamble), 16); 183 | if (in.gcount() != 16) { 184 | throw Malformed(); 185 | } 186 | if (std::memcmp(preamble, "\0GITCRYPTKEY", 12) != 0) { 187 | throw Malformed(); 188 | } 189 | if (load_be32(preamble + 12) != FORMAT_VERSION) { 190 | throw Incompatible(); 191 | } 192 | load_header(in); 193 | while (in.peek() != -1) { 194 | Entry entry; 195 | entry.load(in); 196 | add(entry); 197 | } 198 | } 199 | 200 | void Key_file::load_header (std::istream& in) 201 | { 202 | while (true) { 203 | uint32_t field_id; 204 | if (!read_be32(in, field_id)) { 205 | throw Malformed(); 206 | } 207 | if (field_id == HEADER_FIELD_END) { 208 | break; 209 | } 210 | uint32_t field_len; 211 | if (!read_be32(in, field_len)) { 212 | throw Malformed(); 213 | } 214 | 215 | if (field_id == HEADER_FIELD_KEY_NAME) { 216 | if (field_len > KEY_NAME_MAX_LEN) { 217 | throw Malformed(); 218 | } 219 | if (field_len == 0) { 220 | // special case field_len==0 to avoid possible undefined behavior 221 | // edge cases with an empty std::vector (particularly, &bytes[0]). 222 | key_name.clear(); 223 | } else { 224 | std::vector bytes(field_len); 225 | in.read(&bytes[0], field_len); 226 | if (in.gcount() != static_cast(field_len)) { 227 | throw Malformed(); 228 | } 229 | key_name.assign(&bytes[0], field_len); 230 | } 231 | if (!validate_key_name(key_name.c_str())) { 232 | key_name.clear(); 233 | throw Malformed(); 234 | } 235 | } else if (field_id & 1) { // unknown critical field 236 | throw Incompatible(); 237 | } else { 238 | // unknown non-critical field - safe to ignore 239 | if (field_len > MAX_FIELD_LEN) { 240 | throw Malformed(); 241 | } 242 | in.ignore(field_len); 243 | if (in.gcount() != static_cast(field_len)) { 244 | throw Malformed(); 245 | } 246 | } 247 | } 248 | } 249 | 250 | void Key_file::store (std::ostream& out) const 251 | { 252 | out.write("\0GITCRYPTKEY", 12); 253 | write_be32(out, FORMAT_VERSION); 254 | if (!key_name.empty()) { 255 | write_be32(out, HEADER_FIELD_KEY_NAME); 256 | write_be32(out, key_name.size()); 257 | out.write(key_name.data(), key_name.size()); 258 | } 259 | write_be32(out, HEADER_FIELD_END); 260 | for (Map::const_iterator it(entries.begin()); it != entries.end(); ++it) { 261 | it->second.store(out); 262 | } 263 | } 264 | 265 | bool Key_file::load_from_file (const char* key_file_name) 266 | { 267 | std::ifstream key_file_in(key_file_name, std::fstream::binary); 268 | if (!key_file_in) { 269 | return false; 270 | } 271 | load(key_file_in); 272 | return true; 273 | } 274 | 275 | bool Key_file::store_to_file (const char* key_file_name) const 276 | { 277 | create_protected_file(key_file_name); 278 | std::ofstream key_file_out(key_file_name, std::fstream::binary); 279 | if (!key_file_out) { 280 | return false; 281 | } 282 | store(key_file_out); 283 | key_file_out.close(); 284 | if (!key_file_out) { 285 | return false; 286 | } 287 | return true; 288 | } 289 | 290 | std::string Key_file::store_to_string () const 291 | { 292 | std::ostringstream ss; 293 | store(ss); 294 | return ss.str(); 295 | } 296 | 297 | void Key_file::generate () 298 | { 299 | uint32_t version(is_empty() ? 0 : latest() + 1); 300 | entries[version].generate(version); 301 | } 302 | 303 | uint32_t Key_file::latest () const 304 | { 305 | if (is_empty()) { 306 | throw std::invalid_argument("Key_file::latest"); 307 | } 308 | return entries.begin()->first; 309 | } 310 | 311 | bool validate_key_name (const char* key_name, std::string* reason) 312 | { 313 | if (!*key_name) { 314 | if (reason) { *reason = "Key name may not be empty"; } 315 | return false; 316 | } 317 | 318 | if (std::strcmp(key_name, "default") == 0) { 319 | if (reason) { *reason = "`default' is not a legal key name"; } 320 | return false; 321 | } 322 | // Need to be restrictive with key names because they're used as part of a Git filter name 323 | size_t len = 0; 324 | while (char c = *key_name++) { 325 | if (!std::isalnum(c) && c != '-' && c != '_') { 326 | if (reason) { *reason = "Key names may contain only A-Z, a-z, 0-9, '-', and '_'"; } 327 | return false; 328 | } 329 | if (++len > KEY_NAME_MAX_LEN) { 330 | if (reason) { *reason = "Key name is too long"; } 331 | return false; 332 | } 333 | } 334 | return true; 335 | } 336 | 337 | -------------------------------------------------------------------------------- /key.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Andrew Ayer 3 | * 4 | * This file is part of git-crypt. 5 | * 6 | * git-crypt is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * git-crypt is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with git-crypt. If not, see . 18 | * 19 | * Additional permission under GNU GPL version 3 section 7: 20 | * 21 | * If you modify the Program, or any covered work, by linking or 22 | * combining it with the OpenSSL project's OpenSSL library (or a 23 | * modified version of that library), containing parts covered by the 24 | * terms of the OpenSSL or SSLeay licenses, the licensors of the Program 25 | * grant you additional permission to convey the resulting work. 26 | * Corresponding Source for a non-source form of such a combination 27 | * shall include the source code for the parts of OpenSSL used as well 28 | * as that of the covered work. 29 | */ 30 | 31 | #ifndef GIT_CRYPT_KEY_HPP 32 | #define GIT_CRYPT_KEY_HPP 33 | 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | 40 | enum { 41 | HMAC_KEY_LEN = 64, 42 | AES_KEY_LEN = 32 43 | }; 44 | 45 | struct Key_file { 46 | public: 47 | struct Entry { 48 | uint32_t version; 49 | unsigned char aes_key[AES_KEY_LEN]; 50 | unsigned char hmac_key[HMAC_KEY_LEN]; 51 | 52 | Entry (); 53 | 54 | void load (std::istream&); 55 | void load_legacy (uint32_t version, std::istream&); 56 | void store (std::ostream&) const; 57 | void generate (uint32_t version); 58 | }; 59 | 60 | struct Malformed { }; // exception class 61 | struct Incompatible { }; // exception class 62 | 63 | const Entry* get_latest () const; 64 | 65 | const Entry* get (uint32_t version) const; 66 | void add (const Entry&); 67 | 68 | void load_legacy (std::istream&); 69 | void load (std::istream&); 70 | void store (std::ostream&) const; 71 | 72 | bool load_from_file (const char* filename); 73 | bool store_to_file (const char* filename) const; 74 | 75 | std::string store_to_string () const; 76 | 77 | void generate (); 78 | 79 | bool is_empty () const { return entries.empty(); } 80 | bool is_filled () const { return !is_empty(); } 81 | 82 | uint32_t latest () const; 83 | 84 | void set_key_name (const char* k) { key_name = k ? k : ""; } 85 | const char* get_key_name () const { return key_name.empty() ? 0 : key_name.c_str(); } 86 | private: 87 | typedef std::map > Map; 88 | enum { FORMAT_VERSION = 2 }; 89 | 90 | Map entries; 91 | std::string key_name; 92 | 93 | void load_header (std::istream&); 94 | 95 | enum { 96 | HEADER_FIELD_END = 0, 97 | HEADER_FIELD_KEY_NAME = 1 98 | }; 99 | enum { 100 | KEY_FIELD_END = 0, 101 | KEY_FIELD_VERSION = 1, 102 | KEY_FIELD_AES_KEY = 3, 103 | KEY_FIELD_HMAC_KEY = 5 104 | }; 105 | enum { 106 | MAX_FIELD_LEN = 1<<20 107 | }; 108 | }; 109 | 110 | enum { 111 | KEY_NAME_MAX_LEN = 128 112 | }; 113 | 114 | bool validate_key_name (const char* key_name, std::string* reason =0); 115 | 116 | #endif 117 | -------------------------------------------------------------------------------- /man/git-crypt.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | git-crypt 10 | 2022-04-21 11 | git-crypt 0.7.0 12 | 13 | 14 | Andrew Ayer 15 | 16 | agwa@andrewayer.name 17 | https://www.agwa.name 18 | 19 | 20 | 21 | 22 | git-crypt 23 | 1 24 | 25 | 26 | 27 | git-crypt 28 | transparent file encryption in Git 29 | 30 | 31 | 32 | 33 | git-crypt OPTIONS COMMAND ARGS 34 | 35 | 36 | 37 | 38 | Common commands 39 | 40 | git-crypt init 41 | 42 | 43 | git-crypt status 44 | 45 | 46 | git-crypt lock 47 | 48 | 49 | 50 | GPG commands 51 | 52 | git-crypt add-gpg-user GPG_USER_ID 53 | 54 | 55 | git-crypt unlock 56 | 57 | 58 | 59 | Symmetric key commands 60 | 61 | git-crypt export-key OUTPUT_KEY_FILE 62 | 63 | 64 | git-crypt unlock KEY_FILE 65 | 66 | 67 | 68 | 69 | Description 70 | 71 | 72 | git-crypt enables transparent encryption and decryption 73 | of files in a git repository. Files which you choose to protect are encrypted when committed, 74 | and decrypted when checked out. git-crypt lets you freely share a repository containing a mix of 75 | public and private content. git-crypt gracefully degrades, so developers without the secret key 76 | can still clone and commit to a repository with encrypted files. This lets you store your secret 77 | material (such as keys or passwords) in the same repository as your code, without requiring you 78 | to lock down your entire repository. 79 | 80 | 81 | 82 | 83 | Commands 84 | 85 | 86 | git-crypt is logically divided into several sub-commands which 87 | perform distinct tasks. Each sub-command, and its arguments, 88 | are documented below. Note that arguments and options to sub-commands must be 89 | specified on the command line after the name of the sub-command. 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | Generate a key and prepare the current Git repository to use git-crypt. 98 | 99 | 100 | 101 | The following options are understood: 102 | 103 | 104 | 105 | KEY_NAME 106 | KEY_NAME 107 | 108 | 109 | 110 | Initialize the given key instead of the default key. git-crypt 111 | supports multiple keys per repository, allowing you to share 112 | different files with different sets of collaborators. 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | Display a list of files in the repository, with their status (encrypted or unencrypted). 125 | 126 | 127 | 128 | The following options are understood: 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | Show only encrypted files. 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | Show only unencrypted files. 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | Encrypt files that should be encrypted but were 156 | committed to the repository or added to the index 157 | without encryption. (This can happen if a file 158 | is added before git-crypt is initialized or before 159 | the file is added to the gitattributes file.) 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | Add the users with the given GPG user IDs as collaborators. Specifically, 172 | git-crypt uses gpg1 173 | to encrypt the shared symmetric key 174 | to the public keys of each GPG user ID, and stores the GPG-encrypted 175 | keys in the .git-crypt directory at the root of the repository. 176 | 177 | 178 | 179 | GPG_USER_ID can be a key ID, a full fingerprint, an email address, or anything 180 | else that uniquely identifies a public key to GPG (see "HOW TO SPECIFY 181 | A USER ID" in the gpg1 182 | man page). 183 | 184 | 185 | 186 | The following options are understood: 187 | 188 | 189 | 190 | KEY_NAME 191 | KEY_NAME 192 | 193 | 194 | 195 | Grant access to the given key, rather than the default key. 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | Don't automatically commit the changes to the .git-crypt 206 | directory. 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | Assume that the GPG keys specified on the command line are trusted; 216 | i.e. they actually belong to the users that they claim to belong to. 217 | 218 | 219 | Without this option, git-crypt uses the same trust model as GPG, 220 | which is based on the Web of Trust by default. Under this 221 | model, git-crypt will reject GPG keys that do not have 222 | trusted signatures. 223 | 224 | 225 | If you don't want to use the Web of Trust, you can either change 226 | GPG's trust model by setting the 227 | option in ~/.gnupg/gpg.conf (see 228 | gpg1), 229 | or use the option to add-gpg-user 230 | on a case-by-case basis. 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | Decrypt the repository. If one or more key files are specified on the command line, 243 | git-crypt attempts to decrypt using those shared symmetric keys. If no key files 244 | are specified, git-crypt attempts to decrypt using a GPG-encrypted key stored in 245 | the repository's .git-crypt directory. 246 | 247 | 248 | 249 | This command takes no options. 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | Export the repository's shared symmetric key to the given file. 259 | 260 | 261 | 262 | The following options are understood: 263 | 264 | 265 | 266 | KEY_NAME 267 | KEY_NAME 268 | 269 | 270 | 271 | Export the given key, rather than the default key. 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | Display help for the given COMMAND, 284 | or an overview of all commands if no command is specified. 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | Print the currently-installed version of git-crypt. 294 | The format of the output is always "git-crypt", followed by a space, 295 | followed by the dotted version number. 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | Using git-crypt 305 | 306 | 307 | First, you prepare a repository to use git-crypt by running git-crypt init. 308 | 309 | 310 | 311 | Then, you specify the files to encrypt by creating a 312 | gitattributes5 file. 313 | Each file which you want to encrypt should be assigned the "filter=git-crypt diff=git-crypt" 314 | attributes. For example: 315 | 316 | 317 | secretfile filter=git-crypt diff=git-crypt *.key filter=git-crypt diff=git-crypt 318 | 319 | 320 | Like a .gitignore file, .gitattributes files can match wildcards and 321 | should be checked into the repository. Make sure you don't accidentally encrypt the 322 | .gitattributes file itself (or other git files like .gitignore 323 | or .gitmodules). Make sure your .gitattributes rules 324 | are in place before you add sensitive files, or those files won't be encrypted! 325 | 326 | 327 | 328 | To share the repository with others (or with yourself) using GPG, run: 329 | 330 | 331 | git-crypt add-gpg-user GPG_USER_ID 332 | 333 | 334 | GPG_USER_ID can be a key ID, a full fingerprint, an email address, or anything 335 | else that uniquely identifies a public key to GPG. Note: git-crypt add-gpg-user will 336 | add and commit a GPG-encrypted key file in the .git-crypt directory of 337 | the root of your repository. 338 | 339 | 340 | 341 | Alternatively, you can export a symmetric secret key, which you must 342 | securely convey to collaborators (GPG is not required, and no files 343 | are added to your repository): 344 | 345 | 346 | git-crypt export-key /path/to/key 347 | 348 | 349 | After cloning a repository with encrypted files, unlock with with GPG: 350 | 351 | 352 | git-crypt unlock 353 | 354 | 355 | Or with a symmetric key: 356 | 357 | 358 | git-crypt unlock /path/to/key 359 | 360 | 361 | That's all you need to do - after git-crypt is set up (either with 362 | git-crypt init or git-crypt unlock), 363 | you can use git normally - encryption and decryption happen transparently. 364 | 365 | 366 | 367 | 368 | 369 | The .gitattributes file 370 | 371 | 372 | The .gitattributes file is documented in 373 | gitattributes5. 374 | The file pattern format is the same as the one used by .gitignore, 375 | as documented in gitignore5, 376 | with the exception that specifying merely a directory (e.g. "/dir/") 377 | is not sufficient to encrypt all files beneath it. 378 | 379 | 380 | 381 | Also note that the pattern "dir/*" does not match files under 382 | sub-directories of dir/. To encrypt an entire sub-tree dir/, place the 383 | following in dir/.gitattributes: 384 | 385 | 386 | * filter=git-crypt diff=git-crypt .gitattributes !filter !diff 387 | 388 | 389 | The second pattern is essential for ensuring that .gitattributes itself 390 | is not encrypted. 391 | 392 | 393 | 394 | 395 | Multiple Key Support 396 | 397 | 398 | In addition to the implicit default key, git-crypt supports alternative 399 | keys which can be used to encrypt specific files and can be shared with 400 | specific GPG users. This is useful if you want to grant different 401 | collaborators access to different sets of files. 402 | 403 | 404 | 405 | To generate an alternative key named KEYNAME, 406 | pass the -k KEYNAME 407 | option to git-crypt init as follows: 408 | 409 | 410 | git-crypt init -k KEYNAME 411 | 412 | 413 | To encrypt a file with an alternative key, use the git-crypt-KEYNAME 414 | filter in .gitattributes as follows: 415 | 416 | 417 | secretfile filter=git-crypt-KEYNAME diff=git-crypt-KEYNAME 418 | 419 | 420 | To export an alternative key or share it with a GPG user, pass the 421 | -k KEYNAME option to 422 | git-crypt export-key or git-crypt add-gpg-user 423 | as follows: 424 | 425 | 426 | git-crypt export-key -k KEYNAME /path/to/keyfile git-crypt add-gpg-user -k KEYNAME GPG_USER_ID 427 | 428 | 429 | To unlock a repository with an alternative key, use git-crypt unlock 430 | normally. git-crypt will automatically determine which key is being used. 431 | 432 | 433 | 447 | 448 | 459 | 460 | 474 | 475 | 482 | 483 | 484 | See Also 485 | 486 | git1, 487 | gitattributes5, 488 | git-crypt home page, 489 | GitHub repository 490 | 491 | 492 | 493 | 494 | -------------------------------------------------------------------------------- /parse_options.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Andrew Ayer 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included 12 | * in all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 18 | * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 19 | * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 20 | * OTHER DEALINGS IN THE SOFTWARE. 21 | * 22 | * Except as contained in this notice, the name(s) of the above copyright 23 | * holders shall not be used in advertising or otherwise to promote the 24 | * sale, use or other dealings in this Software without prior written 25 | * authorization. 26 | */ 27 | 28 | #include "parse_options.hpp" 29 | #include 30 | 31 | 32 | static const Option_def* find_option (const Options_list& options, const std::string& name) 33 | { 34 | for (Options_list::const_iterator opt(options.begin()); opt != options.end(); ++opt) { 35 | if (opt->name == name) { 36 | return &*opt; 37 | } 38 | } 39 | return 0; 40 | } 41 | 42 | int parse_options (const Options_list& options, int argc, const char** argv) 43 | { 44 | int argi = 0; 45 | 46 | while (argi < argc && argv[argi][0] == '-' && argv[argi][1] != '\0') { 47 | if (std::strcmp(argv[argi], "--") == 0) { 48 | ++argi; 49 | break; 50 | } else if (std::strncmp(argv[argi], "--", 2) == 0) { 51 | std::string option_name; 52 | const char* option_value = 0; 53 | if (const char* eq = std::strchr(argv[argi], '=')) { 54 | option_name.assign(argv[argi], eq); 55 | option_value = eq + 1; 56 | } else { 57 | option_name = argv[argi]; 58 | } 59 | ++argi; 60 | 61 | const Option_def* opt(find_option(options, option_name)); 62 | if (!opt) { 63 | throw Option_error(option_name, "Invalid option"); 64 | } 65 | 66 | if (opt->is_set) { 67 | *opt->is_set = true; 68 | } 69 | if (opt->value) { 70 | if (option_value) { 71 | *opt->value = option_value; 72 | } else { 73 | if (argi >= argc) { 74 | throw Option_error(option_name, "Option requires a value"); 75 | } 76 | *opt->value = argv[argi]; 77 | ++argi; 78 | } 79 | } else { 80 | if (option_value) { 81 | throw Option_error(option_name, "Option takes no value"); 82 | } 83 | } 84 | } else { 85 | const char* arg = argv[argi] + 1; 86 | ++argi; 87 | while (*arg) { 88 | std::string option_name("-"); 89 | option_name.push_back(*arg); 90 | ++arg; 91 | 92 | const Option_def* opt(find_option(options, option_name)); 93 | if (!opt) { 94 | throw Option_error(option_name, "Invalid option"); 95 | } 96 | if (opt->is_set) { 97 | *opt->is_set = true; 98 | } 99 | if (opt->value) { 100 | if (*arg) { 101 | *opt->value = arg; 102 | } else { 103 | if (argi >= argc) { 104 | throw Option_error(option_name, "Option requires a value"); 105 | } 106 | *opt->value = argv[argi]; 107 | ++argi; 108 | } 109 | break; 110 | } 111 | } 112 | } 113 | } 114 | return argi; 115 | } 116 | -------------------------------------------------------------------------------- /parse_options.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Andrew Ayer 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a 5 | * copy of this software and associated documentation files (the "Software"), 6 | * to deal in the Software without restriction, including without limitation 7 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 8 | * and/or sell copies of the Software, and to permit persons to whom the 9 | * Software is furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included 12 | * in all copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 18 | * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 19 | * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 20 | * OTHER DEALINGS IN THE SOFTWARE. 21 | * 22 | * Except as contained in this notice, the name(s) of the above copyright 23 | * holders shall not be used in advertising or otherwise to promote the 24 | * sale, use or other dealings in this Software without prior written 25 | * authorization. 26 | */ 27 | 28 | #ifndef PARSE_OPTIONS_HPP 29 | #define PARSE_OPTIONS_HPP 30 | 31 | #include 32 | #include 33 | 34 | struct Option_def { 35 | std::string name; 36 | bool* is_set; 37 | const char** value; 38 | 39 | Option_def () : is_set(0), value(0) { } 40 | Option_def (const std::string& arg_name, bool* arg_is_set) 41 | : name(arg_name), is_set(arg_is_set), value(0) { } 42 | Option_def (const std::string& arg_name, const char** arg_value) 43 | : name(arg_name), is_set(0), value(arg_value) { } 44 | }; 45 | 46 | typedef std::vector Options_list; 47 | 48 | int parse_options (const Options_list& options, int argc, const char** argv); 49 | 50 | struct Option_error { 51 | std::string option_name; 52 | std::string message; 53 | 54 | Option_error (const std::string& n, const std::string& m) : option_name(n), message(m) { } 55 | }; 56 | 57 | #endif 58 | -------------------------------------------------------------------------------- /util-unix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012, 2014 Andrew Ayer 3 | * 4 | * This file is part of git-crypt. 5 | * 6 | * git-crypt is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * git-crypt is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with git-crypt. If not, see . 18 | * 19 | * Additional permission under GNU GPL version 3 section 7: 20 | * 21 | * If you modify the Program, or any covered work, by linking or 22 | * combining it with the OpenSSL project's OpenSSL library (or a 23 | * modified version of that library), containing parts covered by the 24 | * terms of the OpenSSL or SSLeay licenses, the licensors of the Program 25 | * grant you additional permission to convey the resulting work. 26 | * Corresponding Source for a non-source form of such a combination 27 | * shall include the source code for the parts of OpenSSL used as well 28 | * as that of the covered work. 29 | */ 30 | 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include 43 | #include 44 | #include 45 | #include 46 | #include 47 | #include 48 | 49 | std::string System_error::message () const 50 | { 51 | std::string mesg(action); 52 | if (!target.empty()) { 53 | mesg += ": "; 54 | mesg += target; 55 | } 56 | if (error) { 57 | mesg += ": "; 58 | mesg += strerror(error); 59 | } 60 | return mesg; 61 | } 62 | 63 | void temp_fstream::open (std::ios_base::openmode mode) 64 | { 65 | close(); 66 | 67 | const char* tmpdir = getenv("TMPDIR"); 68 | size_t tmpdir_len = tmpdir ? std::strlen(tmpdir) : 0; 69 | if (tmpdir_len == 0 || tmpdir_len > 4096) { 70 | // no $TMPDIR or it's excessively long => fall back to /tmp 71 | tmpdir = "/tmp"; 72 | tmpdir_len = 4; 73 | } 74 | std::vector path_buffer(tmpdir_len + 18); 75 | char* path = &path_buffer[0]; 76 | std::strcpy(path, tmpdir); 77 | std::strcpy(path + tmpdir_len, "/git-crypt.XXXXXX"); 78 | mode_t old_umask = umask(0077); 79 | int fd = mkstemp(path); 80 | if (fd == -1) { 81 | int mkstemp_errno = errno; 82 | umask(old_umask); 83 | throw System_error("mkstemp", "", mkstemp_errno); 84 | } 85 | umask(old_umask); 86 | std::fstream::open(path, mode); 87 | if (!std::fstream::is_open()) { 88 | unlink(path); 89 | ::close(fd); 90 | throw System_error("std::fstream::open", path, 0); 91 | } 92 | unlink(path); 93 | ::close(fd); 94 | } 95 | 96 | void temp_fstream::close () 97 | { 98 | if (std::fstream::is_open()) { 99 | std::fstream::close(); 100 | } 101 | } 102 | 103 | void mkdir_parent (const std::string& path) 104 | { 105 | std::string::size_type slash(path.find('/', 1)); 106 | while (slash != std::string::npos) { 107 | std::string prefix(path.substr(0, slash)); 108 | struct stat status; 109 | if (stat(prefix.c_str(), &status) == 0) { 110 | // already exists - make sure it's a directory 111 | if (!S_ISDIR(status.st_mode)) { 112 | throw System_error("mkdir_parent", prefix, ENOTDIR); 113 | } 114 | } else { 115 | if (errno != ENOENT) { 116 | throw System_error("mkdir_parent", prefix, errno); 117 | } 118 | // doesn't exist - mkdir it 119 | if (mkdir(prefix.c_str(), 0777) == -1) { 120 | throw System_error("mkdir", prefix, errno); 121 | } 122 | } 123 | 124 | slash = path.find('/', slash + 1); 125 | } 126 | } 127 | 128 | std::string our_exe_path () 129 | { 130 | if (argv0[0] == '/') { 131 | // argv[0] starts with / => it's an absolute path 132 | return argv0; 133 | } else if (std::strchr(argv0, '/')) { 134 | // argv[0] contains / => it a relative path that should be resolved 135 | char* resolved_path_p = realpath(argv0, nullptr); 136 | std::string resolved_path(resolved_path_p); 137 | free(resolved_path_p); 138 | return resolved_path; 139 | } else { 140 | // argv[0] is just a bare filename => not much we can do 141 | return argv0; 142 | } 143 | } 144 | 145 | int exit_status (int wait_status) 146 | { 147 | return wait_status != -1 && WIFEXITED(wait_status) ? WEXITSTATUS(wait_status) : -1; 148 | } 149 | 150 | void touch_file (const std::string& filename) 151 | { 152 | if (utimes(filename.c_str(), nullptr) == -1 && errno != ENOENT) { 153 | throw System_error("utimes", filename, errno); 154 | } 155 | } 156 | 157 | void remove_file (const std::string& filename) 158 | { 159 | if (unlink(filename.c_str()) == -1 && errno != ENOENT) { 160 | throw System_error("unlink", filename, errno); 161 | } 162 | } 163 | 164 | static void init_std_streams_platform () 165 | { 166 | } 167 | 168 | void create_protected_file (const char* path) 169 | { 170 | int fd = open(path, O_WRONLY | O_CREAT, 0600); 171 | if (fd == -1) { 172 | throw System_error("open", path, errno); 173 | } 174 | close(fd); 175 | } 176 | 177 | int util_rename (const char* from, const char* to) 178 | { 179 | return rename(from, to); 180 | } 181 | 182 | std::vector get_directory_contents (const char* path) 183 | { 184 | std::vector contents; 185 | 186 | DIR* dir = opendir(path); 187 | if (!dir) { 188 | throw System_error("opendir", path, errno); 189 | } 190 | try { 191 | errno = 0; 192 | // Note: readdir is reentrant in new implementations. In old implementations, 193 | // it might not be, but git-crypt isn't multi-threaded so that's OK. 194 | // We don't use readdir_r because it's buggy and deprecated: 195 | // https://womble.decadent.org.uk/readdir_r-advisory.html 196 | // http://austingroupbugs.net/view.php?id=696 197 | // http://man7.org/linux/man-pages/man3/readdir_r.3.html 198 | while (struct dirent* ent = readdir(dir)) { 199 | if (!(std::strcmp(ent->d_name, ".") == 0 || std::strcmp(ent->d_name, "..") == 0)) { 200 | contents.push_back(ent->d_name); 201 | } 202 | } 203 | 204 | if (errno) { 205 | throw System_error("readdir", path, errno); 206 | } 207 | 208 | } catch (...) { 209 | closedir(dir); 210 | throw; 211 | } 212 | closedir(dir); 213 | 214 | std::sort(contents.begin(), contents.end()); 215 | return contents; 216 | } 217 | -------------------------------------------------------------------------------- /util-win32.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Andrew Ayer 3 | * 4 | * This file is part of git-crypt. 5 | * 6 | * git-crypt is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * git-crypt is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with git-crypt. If not, see . 18 | * 19 | * Additional permission under GNU GPL version 3 section 7: 20 | * 21 | * If you modify the Program, or any covered work, by linking or 22 | * combining it with the OpenSSL project's OpenSSL library (or a 23 | * modified version of that library), containing parts covered by the 24 | * terms of the OpenSSL or SSLeay licenses, the licensors of the Program 25 | * grant you additional permission to convey the resulting work. 26 | * Corresponding Source for a non-source form of such a combination 27 | * shall include the source code for the parts of OpenSSL used as well 28 | * as that of the covered work. 29 | */ 30 | 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | 38 | std::string System_error::message () const 39 | { 40 | std::string mesg(action); 41 | if (!target.empty()) { 42 | mesg += ": "; 43 | mesg += target; 44 | } 45 | if (error) { 46 | LPTSTR error_message; 47 | FormatMessageA( 48 | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 49 | nullptr, 50 | error, 51 | MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 52 | reinterpret_cast(&error_message), 53 | 0, 54 | nullptr); 55 | mesg += error_message; 56 | LocalFree(error_message); 57 | } 58 | return mesg; 59 | } 60 | 61 | void temp_fstream::open (std::ios_base::openmode mode) 62 | { 63 | close(); 64 | 65 | char tmpdir[MAX_PATH + 1]; 66 | 67 | DWORD ret = GetTempPath(sizeof(tmpdir), tmpdir); 68 | if (ret == 0) { 69 | throw System_error("GetTempPath", "", GetLastError()); 70 | } else if (ret > sizeof(tmpdir) - 1) { 71 | throw System_error("GetTempPath", "", ERROR_BUFFER_OVERFLOW); 72 | } 73 | 74 | char tmpfilename[MAX_PATH + 1]; 75 | if (GetTempFileName(tmpdir, TEXT("git-crypt"), 0, tmpfilename) == 0) { 76 | throw System_error("GetTempFileName", "", GetLastError()); 77 | } 78 | 79 | filename = tmpfilename; 80 | 81 | std::fstream::open(filename.c_str(), mode); 82 | if (!std::fstream::is_open()) { 83 | DeleteFile(filename.c_str()); 84 | throw System_error("std::fstream::open", filename, 0); 85 | } 86 | } 87 | 88 | void temp_fstream::close () 89 | { 90 | if (std::fstream::is_open()) { 91 | std::fstream::close(); 92 | DeleteFile(filename.c_str()); 93 | } 94 | } 95 | 96 | void mkdir_parent (const std::string& path) 97 | { 98 | std::string::size_type slash(path.find('/', 1)); 99 | while (slash != std::string::npos) { 100 | std::string prefix(path.substr(0, slash)); 101 | if (GetFileAttributes(prefix.c_str()) == INVALID_FILE_ATTRIBUTES) { 102 | // prefix does not exist, so try to create it 103 | if (!CreateDirectory(prefix.c_str(), nullptr)) { 104 | throw System_error("CreateDirectory", prefix, GetLastError()); 105 | } 106 | } 107 | 108 | slash = path.find('/', slash + 1); 109 | } 110 | } 111 | 112 | std::string our_exe_path () 113 | { 114 | std::vector buffer(128); 115 | size_t len; 116 | 117 | while ((len = GetModuleFileNameA(nullptr, &buffer[0], buffer.size())) == buffer.size()) { 118 | // buffer may have been truncated - grow and try again 119 | buffer.resize(buffer.size() * 2); 120 | } 121 | if (len == 0) { 122 | throw System_error("GetModuleFileNameA", "", GetLastError()); 123 | } 124 | 125 | return std::string(buffer.begin(), buffer.begin() + len); 126 | } 127 | 128 | int exit_status (int status) 129 | { 130 | return status; 131 | } 132 | 133 | void touch_file (const std::string& filename) 134 | { 135 | HANDLE fh = CreateFileA(filename.c_str(), FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); 136 | if (fh == INVALID_HANDLE_VALUE) { 137 | DWORD error = GetLastError(); 138 | if (error == ERROR_FILE_NOT_FOUND) { 139 | return; 140 | } else { 141 | throw System_error("CreateFileA", filename, error); 142 | } 143 | } 144 | SYSTEMTIME system_time; 145 | GetSystemTime(&system_time); 146 | FILETIME file_time; 147 | SystemTimeToFileTime(&system_time, &file_time); 148 | 149 | if (!SetFileTime(fh, nullptr, nullptr, &file_time)) { 150 | DWORD error = GetLastError(); 151 | CloseHandle(fh); 152 | throw System_error("SetFileTime", filename, error); 153 | } 154 | CloseHandle(fh); 155 | } 156 | 157 | void remove_file (const std::string& filename) 158 | { 159 | if (!DeleteFileA(filename.c_str())) { 160 | DWORD error = GetLastError(); 161 | if (error == ERROR_FILE_NOT_FOUND) { 162 | return; 163 | } else { 164 | throw System_error("DeleteFileA", filename, error); 165 | } 166 | } 167 | } 168 | 169 | static void init_std_streams_platform () 170 | { 171 | _setmode(_fileno(stdin), _O_BINARY); 172 | _setmode(_fileno(stdout), _O_BINARY); 173 | } 174 | 175 | void create_protected_file (const char* path) // TODO 176 | { 177 | } 178 | 179 | int util_rename (const char* from, const char* to) 180 | { 181 | // On Windows OS, it is necessary to ensure target file doesn't exist 182 | unlink(to); 183 | return rename(from, to); 184 | } 185 | 186 | std::vector get_directory_contents (const char* path) 187 | { 188 | std::vector filenames; 189 | std::string patt(path); 190 | if (!patt.empty() && patt[patt.size() - 1] != '/' && patt[patt.size() - 1] != '\\') { 191 | patt.push_back('\\'); 192 | } 193 | patt.push_back('*'); 194 | 195 | WIN32_FIND_DATAA ffd; 196 | HANDLE h = FindFirstFileA(patt.c_str(), &ffd); 197 | if (h == INVALID_HANDLE_VALUE) { 198 | throw System_error("FindFirstFileA", patt, GetLastError()); 199 | } 200 | do { 201 | if (std::strcmp(ffd.cFileName, ".") != 0 && std::strcmp(ffd.cFileName, "..") != 0) { 202 | filenames.push_back(ffd.cFileName); 203 | } 204 | } while (FindNextFileA(h, &ffd) != 0); 205 | 206 | DWORD err = GetLastError(); 207 | if (err != ERROR_NO_MORE_FILES) { 208 | throw System_error("FileNextFileA", patt, err); 209 | } 210 | FindClose(h); 211 | return filenames; 212 | } 213 | -------------------------------------------------------------------------------- /util.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012, 2014 Andrew Ayer 3 | * 4 | * This file is part of git-crypt. 5 | * 6 | * git-crypt is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * git-crypt is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with git-crypt. If not, see . 18 | * 19 | * Additional permission under GNU GPL version 3 section 7: 20 | * 21 | * If you modify the Program, or any covered work, by linking or 22 | * combining it with the OpenSSL project's OpenSSL library (or a 23 | * modified version of that library), containing parts covered by the 24 | * terms of the OpenSSL or SSLeay licenses, the licensors of the Program 25 | * grant you additional permission to convey the resulting work. 26 | * Corresponding Source for a non-source form of such a combination 27 | * shall include the source code for the parts of OpenSSL used as well 28 | * as that of the covered work. 29 | */ 30 | 31 | #include "git-crypt.hpp" 32 | #include "util.hpp" 33 | #include "coprocess.hpp" 34 | #include 35 | #include 36 | 37 | int exec_command (const std::vector& args) 38 | { 39 | Coprocess proc; 40 | proc.spawn(args); 41 | return proc.wait(); 42 | } 43 | 44 | int exec_command (const std::vector& args, std::ostream& output) 45 | { 46 | Coprocess proc; 47 | std::istream* proc_stdout = proc.stdout_pipe(); 48 | proc.spawn(args); 49 | output << proc_stdout->rdbuf(); 50 | return proc.wait(); 51 | } 52 | 53 | int exec_command_with_input (const std::vector& args, const char* p, size_t len) 54 | { 55 | Coprocess proc; 56 | std::ostream* proc_stdin = proc.stdin_pipe(); 57 | proc.spawn(args); 58 | proc_stdin->write(p, len); 59 | proc.close_stdin(); 60 | return proc.wait(); 61 | } 62 | 63 | std::string escape_shell_arg (const std::string& str) 64 | { 65 | std::string new_str; 66 | new_str.push_back('"'); 67 | for (std::string::const_iterator it(str.begin()); it != str.end(); ++it) { 68 | if (*it == '"' || *it == '\\' || *it == '$' || *it == '`') { 69 | new_str.push_back('\\'); 70 | } 71 | new_str.push_back(*it); 72 | } 73 | new_str.push_back('"'); 74 | return new_str; 75 | } 76 | 77 | uint32_t load_be32 (const unsigned char* p) 78 | { 79 | return (static_cast(p[3]) << 0) | 80 | (static_cast(p[2]) << 8) | 81 | (static_cast(p[1]) << 16) | 82 | (static_cast(p[0]) << 24); 83 | } 84 | 85 | void store_be32 (unsigned char* p, uint32_t i) 86 | { 87 | p[3] = i; i >>= 8; 88 | p[2] = i; i >>= 8; 89 | p[1] = i; i >>= 8; 90 | p[0] = i; 91 | } 92 | 93 | bool read_be32 (std::istream& in, uint32_t& i) 94 | { 95 | unsigned char buffer[4]; 96 | in.read(reinterpret_cast(buffer), 4); 97 | if (in.gcount() != 4) { 98 | return false; 99 | } 100 | i = load_be32(buffer); 101 | return true; 102 | } 103 | 104 | void write_be32 (std::ostream& out, uint32_t i) 105 | { 106 | unsigned char buffer[4]; 107 | store_be32(buffer, i); 108 | out.write(reinterpret_cast(buffer), 4); 109 | } 110 | 111 | void* explicit_memset (void* s, int c, std::size_t n) 112 | { 113 | volatile unsigned char* p = reinterpret_cast(s); 114 | 115 | while (n--) { 116 | *p++ = c; 117 | } 118 | 119 | return s; 120 | } 121 | 122 | static bool leakless_equals_char (const unsigned char* a, const unsigned char* b, std::size_t len) 123 | { 124 | volatile int diff = 0; 125 | 126 | while (len > 0) { 127 | diff |= *a++ ^ *b++; 128 | --len; 129 | } 130 | 131 | return diff == 0; 132 | } 133 | 134 | bool leakless_equals (const void* a, const void* b, std::size_t len) 135 | { 136 | return leakless_equals_char(reinterpret_cast(a), reinterpret_cast(b), len); 137 | } 138 | 139 | static void init_std_streams_platform (); // platform-specific initialization 140 | 141 | void init_std_streams () 142 | { 143 | // The following two lines are essential for achieving good performance: 144 | std::ios_base::sync_with_stdio(false); 145 | std::cin.tie(0); 146 | 147 | std::cin.exceptions(std::ios_base::badbit); 148 | std::cout.exceptions(std::ios_base::badbit); 149 | 150 | init_std_streams_platform(); 151 | } 152 | 153 | #ifdef _WIN32 154 | #include "util-win32.cpp" 155 | #else 156 | #include "util-unix.cpp" 157 | #endif 158 | -------------------------------------------------------------------------------- /util.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012, 2014 Andrew Ayer 3 | * 4 | * This file is part of git-crypt. 5 | * 6 | * git-crypt is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * git-crypt is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with git-crypt. If not, see . 18 | * 19 | * Additional permission under GNU GPL version 3 section 7: 20 | * 21 | * If you modify the Program, or any covered work, by linking or 22 | * combining it with the OpenSSL project's OpenSSL library (or a 23 | * modified version of that library), containing parts covered by the 24 | * terms of the OpenSSL or SSLeay licenses, the licensors of the Program 25 | * grant you additional permission to convey the resulting work. 26 | * Corresponding Source for a non-source form of such a combination 27 | * shall include the source code for the parts of OpenSSL used as well 28 | * as that of the covered work. 29 | */ 30 | 31 | #ifndef GIT_CRYPT_UTIL_HPP 32 | #define GIT_CRYPT_UTIL_HPP 33 | 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | 42 | struct System_error { 43 | std::string action; 44 | std::string target; 45 | int error; 46 | 47 | System_error (const std::string& a, const std::string& t, int e) : action(a), target(t), error(e) { } 48 | 49 | std::string message () const; 50 | }; 51 | 52 | class temp_fstream : public std::fstream { 53 | std::string filename; 54 | public: 55 | ~temp_fstream () { close(); } 56 | 57 | void open (std::ios_base::openmode); 58 | void close (); 59 | }; 60 | 61 | void mkdir_parent (const std::string& path); // Create parent directories of path, __but not path itself__ 62 | std::string our_exe_path (); 63 | int exec_command (const std::vector&); 64 | int exec_command (const std::vector&, std::ostream& output); 65 | int exec_command_with_input (const std::vector&, const char* p, size_t len); 66 | int exit_status (int wait_status); // returns -1 if process did not exit (but was signaled, etc.) 67 | inline bool successful_exit (int wait_status) { return exit_status(wait_status) == 0; } 68 | void touch_file (const std::string&); // ignores non-existent files 69 | void remove_file (const std::string&); // ignores non-existent files 70 | std::string escape_shell_arg (const std::string&); 71 | uint32_t load_be32 (const unsigned char*); 72 | void store_be32 (unsigned char*, uint32_t); 73 | bool read_be32 (std::istream& in, uint32_t&); 74 | void write_be32 (std::ostream& out, uint32_t); 75 | void* explicit_memset (void* s, int c, size_t n); // memset that won't be optimized away 76 | bool leakless_equals (const void* a, const void* b, size_t len); // compare bytes w/o leaking timing 77 | void init_std_streams (); 78 | void create_protected_file (const char* path); // create empty file accessible only by current user 79 | int util_rename (const char*, const char*); 80 | std::vector get_directory_contents (const char* path); 81 | 82 | #endif 83 | 84 | --------------------------------------------------------------------------------