Showing preview only (238K chars total). Download the full file or copy to clipboard to get everything.
Repository: AGWA/git-crypt
Branch: master
Commit: 8c7a90ff38fc
Files: 44
Total size: 225.7 KB
Directory structure:
gitextract_kn52odl0/
├── .gitattributes
├── .github/
│ └── workflows/
│ ├── release-linux-arm64.yml
│ ├── release-linux.yml
│ └── release-windows.yml
├── .gitignore
├── AUTHORS
├── CONTRIBUTING.md
├── COPYING
├── INSTALL
├── INSTALL.md
├── Makefile
├── NEWS.md
├── 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-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
│ └── man1/
│ └── .gitignore
├── parse_options.cpp
├── parse_options.hpp
├── util-unix.cpp
├── util-win32.cpp
├── util.cpp
└── util.hpp
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitattributes
================================================
.git* export-ignore
================================================
FILE: .github/workflows/release-linux-arm64.yml
================================================
on:
release:
types: [published]
name: Build Release Binary (Linux ARM64)
jobs:
build:
name: Build Release Binary
runs-on: ubuntu-22.04-arm
permissions:
contents: read
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Install dependencies
run: sudo apt install libssl-dev
- name: Build binary
run: make
- name: Upload release artifact
uses: actions/upload-artifact@v4
with:
name: git-crypt-artifacts
path: git-crypt
upload:
name: Upload Release Binary
runs-on: ubuntu-latest
needs: build
permissions:
contents: write
steps:
- name: Download release artifact
uses: actions/download-artifact@v4
with:
name: git-crypt-artifacts
- name: Upload release asset
uses: actions/github-script@v6
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const fs = require("fs").promises;
const { repo: { owner, repo }, sha } = context;
await github.rest.repos.uploadReleaseAsset({
owner, repo,
release_id: ${{ github.event.release.id }},
name: 'git-crypt-${{ github.event.release.name }}-linux-aarch64',
data: await fs.readFile('git-crypt'),
});
================================================
FILE: .github/workflows/release-linux.yml
================================================
on:
release:
types: [published]
name: Build Release Binary (Linux)
jobs:
build:
name: Build Release Binary
runs-on: ubuntu-22.04
permissions:
contents: read
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Install dependencies
run: sudo apt install libssl-dev
- name: Build binary
run: make
- name: Upload release artifact
uses: actions/upload-artifact@v4
with:
name: git-crypt-artifacts
path: git-crypt
upload:
name: Upload Release Binary
runs-on: ubuntu-latest
needs: build
permissions:
contents: write
steps:
- name: Download release artifact
uses: actions/download-artifact@v4
with:
name: git-crypt-artifacts
- name: Upload release asset
uses: actions/github-script@v6
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const fs = require("fs").promises;
const { repo: { owner, repo }, sha } = context;
await github.rest.repos.uploadReleaseAsset({
owner, repo,
release_id: ${{ github.event.release.id }},
name: 'git-crypt-${{ github.event.release.name }}-linux-x86_64',
data: await fs.readFile('git-crypt'),
});
================================================
FILE: .github/workflows/release-windows.yml
================================================
on:
release:
types: [published]
name: Build Release Binary (Windows)
jobs:
build:
name: Build Release Binary
runs-on: windows-2022
permissions:
contents: read
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Setup msys2
uses: msys2/setup-msys2@v2
with:
msystem: MINGW64
update: true
install: >-
base-devel
msys2-devel
mingw-w64-x86_64-toolchain
mingw-w64-x86_64-openssl
openssl-devel
- name: Build binary
shell: msys2 {0}
run: make LDFLAGS="-static-libstdc++ -static -lcrypto -lws2_32 -lcrypt32"
- name: Upload release artifact
uses: actions/upload-artifact@v4
with:
name: git-crypt-artifacts
path: git-crypt.exe
upload:
name: Upload Release Binary
runs-on: ubuntu-latest
needs: build
permissions:
contents: write
steps:
- name: Download release artifact
uses: actions/download-artifact@v4
with:
name: git-crypt-artifacts
- name: Upload release asset
uses: actions/github-script@v6
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const fs = require("fs").promises;
const { repo: { owner, repo }, sha } = context;
await github.rest.repos.uploadReleaseAsset({
owner, repo,
release_id: ${{ github.event.release.id }},
name: 'git-crypt-${{ github.event.release.name }}-x86_64.exe',
data: await fs.readFile('git-crypt.exe'),
});
================================================
FILE: .gitignore
================================================
*.o
git-crypt
================================================
FILE: AUTHORS
================================================
Andrew Ayer <agwa@andrewayer.name>
================================================
FILE: CONTRIBUTING.md
================================================
Thanks for your interest in contributing to git-crypt! git-crypt is
open source software and welcomes contributions in the form of code,
documentation, bug reports, or anything else that improves git-crypt.
When contributing code, please consider the following guidelines:
* You are encouraged to open an issue on GitHub to discuss any non-trivial
changes before you start coding.
* Please mimic the existing code style as much as possible. In
particular, please indent code using tab characters with a width
of 8.
* To minimize merge commits, please rebase your changes before opening
a pull request.
* To submit your patch, open a pull request on GitHub.
Finally, be aware that since git-crypt is security-sensitive software,
the bar for contributions is higher than average. Please don't be
discouraged by this, but be prepared for patches to possibly go through
several rounds of feedback and improvement before being accepted.
Your patience and understanding is appreciated.
================================================
FILE: COPYING
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
================================================
FILE: INSTALL
================================================
DEPENDENCIES
To build git-crypt, you need:
Debian/Ubuntu package RHEL/CentOS package
-----------------------------------------------------------------------------
Make make make
A C++11 compiler (e.g. gcc 4.9+) g++ gcc-c++
OpenSSL development files libssl-dev openssl-devel
To use git-crypt, you need:
Debian/Ubuntu package RHEL/CentOS package
-----------------------------------------------------------------------------
Git 1.7.2 or newer git git
OpenSSL openssl openssl
Note: Git 1.8.5 or newer is recommended for best performance.
BUILDING GIT-CRYPT
Run:
$ make
$ make install
To install to a specific location:
$ make install PREFIX=/usr/local
Or, just copy the git-crypt binary to wherever is most convenient for you.
BUILDING THE MAN PAGE
To build and install the git-crypt(1) man page, pass ENABLE_MAN=yes to make:
$ make ENABLE_MAN=yes
$ make ENABLE_MAN=yes install
xsltproc is required to build the man page. Note that xsltproc will access
the Internet to retrieve its stylesheet unless the Docbook stylesheet is
installed locally and registered in the system's XML catalog.
BUILDING A DEBIAN PACKAGE
Debian packaging can be found in the 'debian' branch of the project
Git repository. The package is built using git-buildpackage as follows:
$ git checkout debian
$ git-buildpackage -uc -us
INSTALLING ON MAC OS X
Using the brew package manager, simply run:
$ brew install git-crypt
EXPERIMENTAL WINDOWS SUPPORT
git-crypt should build on Windows with MinGW, although the build system
is not yet finalized so you will need to pass your own CXX, CXXFLAGS, and
LDFLAGS variables to make. Additionally, Windows support is less tested
and does not currently create key files with restrictive permissions,
making it unsuitable for use on a multi-user system. Windows support
will mature in a future version of git-crypt. Bug reports and patches
are most welcome!
================================================
FILE: INSTALL.md
================================================
### Dependencies
To build git-crypt, you need:
| Software | Debian/Ubuntu package | RHEL/CentOS package|
|---------------------------------|-----------------------|--------------------|
|Make | make | make |
|A C++11 compiler (e.g. gcc 4.9+) | g++ | gcc-c++ |
|OpenSSL development files | libssl-dev | openssl-devel |
To use git-crypt, you need:
| Software | Debian/Ubuntu package | RHEL/CentOS package|
|---------------------------------|-----------------------|--------------------|
|Git 1.7.2 or newer | git | git |
|OpenSSL | openssl | openssl |
Note: Git 1.8.5 or newer is recommended for best performance.
### Building git-crypt
Run:
make
make install
To install to a specific location:
make install PREFIX=/usr/local
Or, just copy the git-crypt binary to wherever is most convenient for you.
### Building The Man Page
To build and install the git-crypt(1) man page, pass `ENABLE_MAN=yes` to make:
make ENABLE_MAN=yes
make ENABLE_MAN=yes install
xsltproc is required to build the man page. Note that xsltproc will access
the Internet to retrieve its stylesheet unless the Docbook stylesheet is
installed locally and registered in the system's XML catalog.
### Building A Debian Package
Debian packaging can be found in the 'debian' branch of the project Git
repository. The package is built using git-buildpackage as follows:
git checkout debian
git-buildpackage -uc -us
### Installing On Mac OS X
Using the brew package manager, simply run:
brew install git-crypt
### Experimental Windows Support
git-crypt should build on Windows with MinGW, although the build system
is not yet finalized so you will need to pass your own CXX, CXXFLAGS, and
LDFLAGS variables to make. Additionally, Windows support is less tested
and does not currently create key files with restrictive permissions,
making it unsuitable for use on a multi-user system. Windows support
will mature in a future version of git-crypt. Bug reports and patches
are most welcome!
================================================
FILE: Makefile
================================================
#
# Copyright (c) 2015 Andrew Ayer
#
# See COPYING file for license information.
#
CXXFLAGS ?= -Wall -pedantic -Wno-long-long -O2
CXXFLAGS += -std=c++11
PREFIX ?= /usr/local
BINDIR ?= $(PREFIX)/bin
MANDIR ?= $(PREFIX)/share/man
ENABLE_MAN ?= no
DOCBOOK_XSL ?= http://cdn.docbook.org/release/xsl-nons/current/manpages/docbook.xsl
OBJFILES = \
git-crypt.o \
commands.o \
crypto.o \
gpg.o \
key.o \
util.o \
parse_options.o \
coprocess.o \
fhstream.o
OBJFILES += crypto-openssl-11.o
LDFLAGS += -lcrypto
XSLTPROC ?= xsltproc
DOCBOOK_FLAGS += --param man.output.in.separate.dir 1 \
--stringparam man.output.base.dir man/ \
--param man.output.subdirs.enabled 1 \
--param man.authors.section.enabled 1
all: build
#
# Build
#
BUILD_MAN_TARGETS-yes = build-man
BUILD_MAN_TARGETS-no =
BUILD_TARGETS := build-bin $(BUILD_MAN_TARGETS-$(ENABLE_MAN))
build: $(BUILD_TARGETS)
build-bin: git-crypt
git-crypt: $(OBJFILES)
$(CXX) $(CXXFLAGS) -o $@ $(OBJFILES) $(LDFLAGS)
util.o: util.cpp util-unix.cpp util-win32.cpp
coprocess.o: coprocess.cpp coprocess-unix.cpp coprocess-win32.cpp
build-man: man/man1/git-crypt.1
man/man1/git-crypt.1: man/git-crypt.xml
$(XSLTPROC) $(DOCBOOK_FLAGS) $(DOCBOOK_XSL) man/git-crypt.xml
#
# Clean
#
CLEAN_MAN_TARGETS-yes = clean-man
CLEAN_MAN_TARGETS-no =
CLEAN_TARGETS := clean-bin $(CLEAN_MAN_TARGETS-$(ENABLE_MAN))
clean: $(CLEAN_TARGETS)
clean-bin:
rm -f $(OBJFILES) git-crypt
clean-man:
rm -f man/man1/git-crypt.1
#
# Install
#
INSTALL_MAN_TARGETS-yes = install-man
INSTALL_MAN_TARGETS-no =
INSTALL_TARGETS := install-bin $(INSTALL_MAN_TARGETS-$(ENABLE_MAN))
install: $(INSTALL_TARGETS)
install-bin: build-bin
install -d $(DESTDIR)$(BINDIR)
install -m 755 git-crypt $(DESTDIR)$(BINDIR)/
install-man: build-man
install -d $(DESTDIR)$(MANDIR)/man1
install -m 644 man/man1/git-crypt.1 $(DESTDIR)$(MANDIR)/man1/
.PHONY: all \
build build-bin build-man \
clean clean-bin clean-man \
install install-bin install-man
================================================
FILE: NEWS.md
================================================
# Change Log
## v0.8.0 (2025-09-23)
* Remove OpenSSL 1.0 support, fix compilation with OpenSSL 3.
* Avoid use of problematic short GPG key IDs.
## v0.7.0 (2022-04-21)
* Avoid "argument list too long" errors on macOS.
* Fix handling of "-" arguments.
* Minor documentation improvements.
## v0.6.0 (2017-11-26)
* Add support for OpenSSL 1.1 (still works with OpenSSL 1.0).
* Switch to C++11 (gcc 4.9 or higher now required to build).
* Allow GPG to fail on some keys (makes unlock work better if there are
multiple keys that can unlock the repo but only some are available).
* Allow the repo state directory to be configured with the
git-crypt.repoStateDir git config option.
* Respect the gpg.program git config option.
* Don't hard code path to git-crypt in .git/config on Linux (ensures
repo continues to work if git-crypt is moved).
* Ensure git-crypt's gpg files won't be treated as text by Git.
* Minor improvements to build system, documentation.
## v0.5.0 (2015-05-30)
* Drastically speed up lock/unlock when used with Git 1.8.5 or newer.
* Add git-crypt(1) man page (pass `ENABLE_MAN=yes` to make to build).
* Add --trusted option to `git-crypt gpg-add-user` to add user even if
GPG doesn't trust user's key.
* Improve `git-crypt lock` usability, add --force option.
* Ignore symlinks and other non-files when running `git-crypt status`.
* Fix compilation on old versions of Mac OS X.
* Fix GPG mode when with-fingerprint enabled in gpg.conf.
* Minor bug fixes and improvements to help/error messages.
## v0.4.2 (2015-01-31)
* Fix unlock and lock under Git 2.2.2 and higher.
* Drop support for versions of Git older than 1.7.2.
* Minor improvements to some help/error messages.
## v0.4.1 (2015-01-08)
* Important usability fix to ensure that the .git-crypt directory
can't be encrypted by accident (see
[the release notes](RELEASE_NOTES-0.4.1.md) for more information).
## v0.4 (2014-11-16)
(See [the release notes](RELEASE_NOTES-0.4.md) for important details.)
* Add optional GPG support: GPG can be used to share the repository
between one or more users in lieu of sharing a secret key.
* New workflow: the symmetric key is now stored inside the .git
directory. Although backwards compatibility has been preserved
with repositories created by old versions of git-crypt, the
commands for setting up a repository have changed. See the
release notes file for details.
* Multiple key support: it's now possible to encrypt different parts
of a repository with different keys.
* Initial `git-crypt status` command to report which files are
encrypted and to fix problems that are detected.
* Numerous usability, documentation, and error reporting improvements.
* Major internal code improvements that will make future development
easier.
* Initial experimental Windows support.
## v0.3 (2013-04-05)
* Fix `git-crypt init` on newer versions of Git. Previously,
encrypted files were not being automatically decrypted after running
`git-crypt init` with recent versions of Git.
* Allow `git-crypt init` to be run even if the working tree contains
untracked files.
* `git-crypt init` now properly escapes arguments to the filter
commands it configures, allowing both the path to git-crypt and the
path to the key file to contain arbitrary characters such as spaces.
## v0.2 (2013-01-25)
* Numerous improvements to `git-crypt init` usability.
* Fix gitattributes example in [README](README.md): the old example
showed a colon after the filename where there shouldn't be one.
* Various build fixes and improvements.
## v0.1 (2012-11-29)
* Initial release.
================================================
FILE: README.md
================================================
git-crypt - transparent file encryption in git
==============================================
git-crypt enables transparent encryption and decryption of files in a
git repository. Files which you choose to protect are encrypted when
committed, and decrypted when checked out. git-crypt lets you freely
share a repository containing a mix of public and private content.
git-crypt gracefully degrades, so developers without the secret key can
still clone and commit to a repository with encrypted files. This lets
you store your secret material (such as keys or passwords) in the same
repository as your code, without requiring you to lock down your entire
repository.
git-crypt was written by [Andrew Ayer](https://www.agwa.name) (agwa@andrewayer.name).
For more information, see <https://www.agwa.name/projects/git-crypt>.
Building git-crypt
------------------
See the [INSTALL.md](INSTALL.md) file.
Using git-crypt
---------------
Configure a repository to use git-crypt:
cd repo
git-crypt init
Specify files to encrypt by creating a .gitattributes file:
secretfile filter=git-crypt diff=git-crypt
*.key filter=git-crypt diff=git-crypt
secretdir/** filter=git-crypt diff=git-crypt
Like a .gitignore file, it can match wildcards and should be checked into
the repository. See below for more information about .gitattributes.
Make sure you don't accidentally encrypt the .gitattributes file itself
(or other git files like .gitignore or .gitmodules). Make sure your
.gitattributes rules are in place *before* you add sensitive files, or
those files won't be encrypted!
Share the repository with others (or with yourself) using GPG:
git-crypt add-gpg-user USER_ID
`USER_ID` can be a key ID, a full fingerprint, an email address, or
anything else that uniquely identifies a public key to GPG (see "HOW TO
SPECIFY A USER ID" in the gpg man page). Note: `git-crypt add-gpg-user`
will add and commit a GPG-encrypted key file in the .git-crypt directory
of the root of your repository.
Alternatively, you can export a symmetric secret key, which you must
securely convey to collaborators (GPG is not required, and no files
are added to your repository):
git-crypt export-key /path/to/key
After cloning a repository with encrypted files, unlock with GPG:
git-crypt unlock
Or with a symmetric key:
git-crypt unlock /path/to/key
That's all you need to do - after git-crypt is set up (either with
`git-crypt init` or `git-crypt unlock`), you can use git normally -
encryption and decryption happen transparently.
Current Status
--------------
The latest version of git-crypt is [0.8.0](NEWS.md), released on
2025-09-23. git-crypt aims to be bug-free and reliable, meaning it
shouldn't crash, malfunction, or expose your confidential data.
However, it has not yet reached maturity, meaning it is not as
documented, featureful, or easy-to-use as it should be. Additionally,
there may be backwards-incompatible changes introduced before version
1.0.
Security
--------
git-crypt is more secure than other transparent git encryption systems.
git-crypt encrypts files using AES-256 in CTR mode with a synthetic IV
derived from the SHA-1 HMAC of the file. This mode of operation is
provably semantically secure under deterministic chosen-plaintext attack.
That means that although the encryption is deterministic (which is
required so git can distinguish when a file has and hasn't changed),
it leaks no information beyond whether two files are identical or not.
Other proposals for transparent git encryption use ECB or CBC with a
fixed IV. These systems are not semantically secure and leak information.
Limitations
-----------
git-crypt relies on git filters, which were not designed with encryption
in mind. As such, git-crypt is not the best tool for encrypting most or
all of the files in a repository. Where git-crypt really shines is where
most of your repository is public, but you have a few files (perhaps
private keys named *.key, or a file with API credentials) which you
need to encrypt. For encrypting an entire repository, consider using a
system like [git-remote-gcrypt](https://spwhitton.name/tech/code/git-remote-gcrypt/)
instead. (Note: no endorsement is made of git-remote-gcrypt's security.)
git-crypt does not encrypt file names, commit messages, symlink targets,
gitlinks, or other metadata.
git-crypt does not hide when a file does or doesn't change, the length
of a file, or the fact that two files are identical (see "Security"
section above).
git-crypt does not support revoking access to an encrypted repository
which was previously granted. This applies to both multi-user GPG
mode (there's no del-gpg-user command to complement add-gpg-user)
and also symmetric key mode (there's no support for rotating the key).
This is because it is an inherently complex problem in the context
of historical data. For example, even if a key was rotated at one
point in history, a user having the previous key can still access
previous repository history. This problem is discussed in more detail in
<https://github.com/AGWA/git-crypt/issues/47>.
Files encrypted with git-crypt are not compressible. Even the smallest
change to an encrypted file requires git to store the entire changed file,
instead of just a delta.
Although git-crypt protects individual file contents with a SHA-1
HMAC, git-crypt cannot be used securely unless the entire repository is
protected against tampering (an attacker who can mutate your repository
can alter your .gitattributes file to disable encryption). If necessary,
use git features such as signed tags instead of relying solely on
git-crypt for integrity.
Files encrypted with git-crypt cannot be patched with git-apply, unless
the patch itself is encrypted. To generate an encrypted patch, use `git
diff --no-textconv --binary`. Alternatively, you can apply a plaintext
patch outside of git using the patch command.
git-crypt does not work reliably with some third-party git GUIs, such
as [Atlassian SourceTree](https://jira.atlassian.com/browse/SRCTREE-2511)
and GitHub for Mac. Files might be left in an unencrypted state.
Gitattributes File
------------------
The .gitattributes file is documented in the gitattributes(5) man page.
The file pattern format is the same as the one used by .gitignore,
as documented in the gitignore(5) man page, with the exception that
specifying merely a directory (e.g. `/dir/`) is *not* sufficient to
encrypt all files beneath it.
Also note that the pattern `dir/*` does not match files under
sub-directories of dir/. To encrypt an entire sub-tree dir/, use `dir/**`:
dir/** filter=git-crypt diff=git-crypt
The .gitattributes file must not be encrypted, so make sure wildcards don't
match it accidentally. If necessary, you can exclude .gitattributes from
encryption like this:
.gitattributes !filter !diff
================================================
FILE: RELEASE_NOTES-0.4.1.md
================================================
git-crypt 0.4.1 is a bugfix-only release that contains an important
usability fix for users who use GPG mode to encrypt an entire repository.
Previously, if you used a '*' pattern in the top-level .gitattributes
file, and you did not explicitly add a pattern to exclude the .git-crypt
directory, the files contained therein would be encrypted, rendering
the repository impossible to unlock with GPG.
git-crypt now adds a .gitattributes file to the .git-crypt directory
to prevent its contents from being encrypted, regardless of patterns in
the top-level .gitattributes.
If you are using git-crypt in GPG mode to encrypt an entire repository,
and you do not already have a .gitattributes pattern to exclude the
.git-crypt directory, you are strongly advised to upgrade. After
upgrading, you should do the following in each of your repositories to
ensure that the information inside .git-crypt is properly stored:
1. Remove existing key files: `rm .git-crypt/keys/*/0/*`
2. Re-add GPG user(s): `git-crypt add-gpg-user GPG_USER_ID ...`
================================================
FILE: RELEASE_NOTES-0.4.md
================================================
Changes to be aware of for git-crypt 0.4
========================================
(For a complete list of changes, see the [NEWS](NEWS.md) file.)
### New workflow
The commands for setting up a repository have changed in git-crypt 0.4.
The previous commands continue to work, but will be removed in a future
release of git-crypt. Please get in the habit of using the new syntax:
`git-crypt init` no longer takes an argument, and is now used only when
initializing a repository for the very first time. It generates a key
and stores it in the `.git` directory. There is no longer a separate
`keygen` step, and you no longer need to keep a copy of the key outside
the repository.
`git-crypt init` is no longer used to decrypt a cloned repository. Instead,
run `git-crypt unlock /path/to/keyfile`, where `keyfile` is obtained by
running `git-crypt export-key /path/to/keyfile` from an already-decrypted
repository.
### GPG mode
git-crypt now supports GPG. A repository can be shared with one or more
GPG users in lieu of sharing a secret symmetric key. Symmetric key support
isn't going away, but the workflow of GPG mode is extremely easy and all users
are encouraged to consider it for their repositories.
See the [README](README.md) for details on using GPG.
### Status command
A new command, `git-crypt status`, lists encrypted files, which is
useful for making sure your `.gitattributes` pattern is protecting the
right files.
### Multiple key support
git-crypt now lets you encrypt different sets of files with different
keys, which is useful if you want to grant different collaborators access
to different sets of files.
See [doc/multiple_keys.md](doc/multiple_keys.md) for details.
### Compatibility with old repositories
Repositories created with older versions of git-crypt continue to work
without any changes needed, and backwards compatibility with these
repositories will be maintained indefinitely.
However, you will not be able to take advantage of git-crypt's new
features, such as GPG support, unless you migrate your repository.
To migrate your repository, first ensure the working tree is clean.
Then migrate your current key file and use the migrated key to unlock
your repository as follows:
git-crypt migrate-key /path/to/old_key /path/to/migrated_key
git-crypt unlock /path/to/migrated_key
Once you've confirmed that your repository is functional, you can delete
both the old and migrated key files (though keeping a backup of your key
is always a good idea).
### Known issues
It is not yet possible to revoke access from a GPG user. This will
require substantial development work and will be a major focus of future
git-crypt development.
The output of `git-crypt status` is currently very bare-bones and will
be substantially improved in a future release. Do not rely on its output
being stable. A future release of git-crypt will provide an option for stable
machine-readable output.
On Windows, git-crypt does not create key files with restrictive
permissions. Take care when using git-crypt on a multi-user Windows system.
================================================
FILE: THANKS.md
================================================
For their contributions to git-crypt, I thank:
* Michael Mior and @zimbatm for the Homebrew formula.
* Cyril Cleaud for help with Windows support.
* The following people for contributing patches:
* Adam Nelson
* Caleb Maclennan
* Darayus Nanavati
* Jon Sailor
* Linus G Thiel
* Michael Schout
* Simon Kotlinski
* Kevin Menard
* Wael M. Nasreddine
* Kevin Borgolte
* Adrian Cohea
* And everyone who has tested git-crypt, provided feedback, reported
bugs, and participated in discussions about new features.
Thank you!
================================================
FILE: commands.cpp
================================================
/*
* Copyright 2012, 2014 Andrew Ayer
*
* This file is part of git-crypt.
*
* git-crypt is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* git-crypt is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with git-crypt. If not, see <http://www.gnu.org/licenses/>.
*
* Additional permission under GNU GPL version 3 section 7:
*
* If you modify the Program, or any covered work, by linking or
* combining it with the OpenSSL project's OpenSSL library (or a
* modified version of that library), containing parts covered by the
* terms of the OpenSSL or SSLeay licenses, the licensors of the Program
* grant you additional permission to convey the resulting work.
* Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of OpenSSL used as well
* as that of the covered work.
*/
#include "commands.hpp"
#include "crypto.hpp"
#include "util.hpp"
#include "key.hpp"
#include "gpg.hpp"
#include "parse_options.hpp"
#include "coprocess.hpp"
#include <unistd.h>
#include <stdint.h>
#include <algorithm>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <cstddef>
#include <cstring>
#include <cctype>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <exception>
#include <vector>
enum {
// # of arguments per git checkout call; must be large enough to be efficient but small
// enough to avoid operating system limits on argument length
GIT_CHECKOUT_BATCH_SIZE = 100
};
static std::string attribute_name (const char* key_name)
{
if (key_name) {
// named key
return std::string("git-crypt-") + key_name;
} else {
// default key
return "git-crypt";
}
}
static std::string git_version_string ()
{
std::vector<std::string> command;
command.push_back("git");
command.push_back("version");
std::stringstream output;
if (!successful_exit(exec_command(command, output))) {
throw Error("'git version' failed - is Git installed?");
}
std::string word;
output >> word; // "git"
output >> word; // "version"
output >> word; // "1.7.10.4"
return word;
}
static std::vector<int> parse_version (const std::string& str)
{
std::istringstream in(str);
std::vector<int> version;
std::string component;
while (std::getline(in, component, '.')) {
version.push_back(std::atoi(component.c_str()));
}
return version;
}
static const std::vector<int>& git_version ()
{
static const std::vector<int> version(parse_version(git_version_string()));
return version;
}
static std::vector<int> make_version (int a, int b, int c)
{
std::vector<int> version;
version.push_back(a);
version.push_back(b);
version.push_back(c);
return version;
}
static void git_config (const std::string& name, const std::string& value)
{
std::vector<std::string> command;
command.push_back("git");
command.push_back("config");
command.push_back(name);
command.push_back(value);
if (!successful_exit(exec_command(command))) {
throw Error("'git config' failed");
}
}
static bool git_has_config (const std::string& name)
{
std::vector<std::string> command;
command.push_back("git");
command.push_back("config");
command.push_back("--get-all");
command.push_back(name);
std::stringstream output;
switch (exit_status(exec_command(command, output))) {
case 0: return true;
case 1: return false;
default: throw Error("'git config' failed");
}
}
static void git_deconfig (const std::string& name)
{
std::vector<std::string> command;
command.push_back("git");
command.push_back("config");
command.push_back("--remove-section");
command.push_back(name);
if (!successful_exit(exec_command(command))) {
throw Error("'git config' failed");
}
}
static void configure_git_filters (const char* key_name)
{
std::string escaped_git_crypt_path(escape_shell_arg(our_exe_path()));
if (key_name) {
// Note: key_name contains only shell-safe characters so it need not be escaped.
git_config(std::string("filter.git-crypt-") + key_name + ".smudge",
escaped_git_crypt_path + " smudge --key-name=" + key_name);
git_config(std::string("filter.git-crypt-") + key_name + ".clean",
escaped_git_crypt_path + " clean --key-name=" + key_name);
git_config(std::string("filter.git-crypt-") + key_name + ".required", "true");
git_config(std::string("diff.git-crypt-") + key_name + ".textconv",
escaped_git_crypt_path + " diff --key-name=" + key_name);
} else {
git_config("filter.git-crypt.smudge", escaped_git_crypt_path + " smudge");
git_config("filter.git-crypt.clean", escaped_git_crypt_path + " clean");
git_config("filter.git-crypt.required", "true");
git_config("diff.git-crypt.textconv", escaped_git_crypt_path + " diff");
}
}
static void deconfigure_git_filters (const char* key_name)
{
// deconfigure the git-crypt filters
if (git_has_config("filter." + attribute_name(key_name) + ".smudge") ||
git_has_config("filter." + attribute_name(key_name) + ".clean") ||
git_has_config("filter." + attribute_name(key_name) + ".required")) {
git_deconfig("filter." + attribute_name(key_name));
}
if (git_has_config("diff." + attribute_name(key_name) + ".textconv")) {
git_deconfig("diff." + attribute_name(key_name));
}
}
static bool git_checkout_batch (std::vector<std::string>::const_iterator paths_begin, std::vector<std::string>::const_iterator paths_end)
{
if (paths_begin == paths_end) {
return true;
}
std::vector<std::string> command;
command.push_back("git");
command.push_back("checkout");
command.push_back("--");
for (auto path(paths_begin); path != paths_end; ++path) {
command.push_back(*path);
}
if (!successful_exit(exec_command(command))) {
return false;
}
return true;
}
static bool git_checkout (const std::vector<std::string>& paths)
{
auto paths_begin(paths.begin());
while (paths.end() - paths_begin >= GIT_CHECKOUT_BATCH_SIZE) {
if (!git_checkout_batch(paths_begin, paths_begin + GIT_CHECKOUT_BATCH_SIZE)) {
return false;
}
paths_begin += GIT_CHECKOUT_BATCH_SIZE;
}
return git_checkout_batch(paths_begin, paths.end());
}
static bool same_key_name (const char* a, const char* b)
{
return (!a && !b) || (a && b && std::strcmp(a, b) == 0);
}
static void validate_key_name_or_throw (const char* key_name)
{
std::string reason;
if (!validate_key_name(key_name, &reason)) {
throw Error(reason);
}
}
static std::string get_internal_state_path ()
{
// git rev-parse --git-dir
std::vector<std::string> command;
command.push_back("git");
command.push_back("rev-parse");
command.push_back("--git-dir");
std::stringstream output;
if (!successful_exit(exec_command(command, output))) {
throw Error("'git rev-parse --git-dir' failed - is this a Git repository?");
}
std::string path;
std::getline(output, path);
path += "/git-crypt";
return path;
}
static std::string get_internal_keys_path (const std::string& internal_state_path)
{
return internal_state_path + "/keys";
}
static std::string get_internal_keys_path ()
{
return get_internal_keys_path(get_internal_state_path());
}
static std::string get_internal_key_path (const char* key_name)
{
std::string path(get_internal_keys_path());
path += "/";
path += key_name ? key_name : "default";
return path;
}
std::string get_git_config (const std::string& name)
{
// git config --get
std::vector<std::string> command;
command.push_back("git");
command.push_back("config");
command.push_back("--get");
command.push_back(name);
std::stringstream output;
if (!successful_exit(exec_command(command, output))) {
throw Error("'git config' missing value for key '" + name +"'");
}
std::string value;
std::getline(output, value);
return value;
}
static std::string get_repo_state_path ()
{
// git rev-parse --show-toplevel
std::vector<std::string> command;
command.push_back("git");
command.push_back("rev-parse");
command.push_back("--show-toplevel");
std::stringstream output;
if (!successful_exit(exec_command(command, output))) {
throw Error("'git rev-parse --show-toplevel' failed - is this a Git repository?");
}
std::string path;
std::getline(output, path);
if (path.empty()) {
// could happen for a bare repo
throw Error("Could not determine Git working tree - is this a non-bare repo?");
}
// Check if the repo state dir has been explicitly configured. If so, use that in path construction.
if (git_has_config("git-crypt.repoStateDir")) {
std::string repoStateDir = get_git_config("git-crypt.repoStateDir");
// The repoStateDir value must always be relative to git work tree to ensure the repoStateDir can be committed
// along with the remainder of the repository.
path += '/' + repoStateDir;
} else {
// There is no explicitly configured repo state dir configured, so use the default.
path += "/.git-crypt";
}
return path;
}
static std::string get_repo_keys_path (const std::string& repo_state_path)
{
return repo_state_path + "/keys";
}
static std::string get_repo_keys_path ()
{
return get_repo_keys_path(get_repo_state_path());
}
static std::string get_path_to_top ()
{
// git rev-parse --show-cdup
std::vector<std::string> command;
command.push_back("git");
command.push_back("rev-parse");
command.push_back("--show-cdup");
std::stringstream output;
if (!successful_exit(exec_command(command, output))) {
throw Error("'git rev-parse --show-cdup' failed - is this a Git repository?");
}
std::string path_to_top;
std::getline(output, path_to_top);
return path_to_top;
}
static void get_git_status (std::ostream& output)
{
// git status -uno --porcelain
std::vector<std::string> command;
command.push_back("git");
command.push_back("status");
command.push_back("-uno"); // don't show untracked files
command.push_back("--porcelain");
if (!successful_exit(exec_command(command, output))) {
throw Error("'git status' failed - is this a Git repository?");
}
}
// returns filter and diff attributes as a pair
static std::pair<std::string, std::string> get_file_attributes (const std::string& filename)
{
// git check-attr filter diff -- filename
std::vector<std::string> command;
command.push_back("git");
command.push_back("check-attr");
command.push_back("filter");
command.push_back("diff");
command.push_back("--");
command.push_back(filename);
std::stringstream output;
if (!successful_exit(exec_command(command, output))) {
throw Error("'git check-attr' failed - is this a Git repository?");
}
std::string filter_attr;
std::string diff_attr;
std::string line;
// Example output:
// filename: filter: git-crypt
// filename: diff: git-crypt
while (std::getline(output, line)) {
// filename might contain ": ", so parse line backwards
// filename: attr_name: attr_value
// ^name_pos ^value_pos
const std::string::size_type value_pos(line.rfind(": "));
if (value_pos == std::string::npos || value_pos == 0) {
continue;
}
const std::string::size_type name_pos(line.rfind(": ", value_pos - 1));
if (name_pos == std::string::npos) {
continue;
}
const std::string attr_name(line.substr(name_pos + 2, value_pos - (name_pos + 2)));
const std::string attr_value(line.substr(value_pos + 2));
if (attr_value != "unspecified" && attr_value != "unset" && attr_value != "set") {
if (attr_name == "filter") {
filter_attr = attr_value;
} else if (attr_name == "diff") {
diff_attr = attr_value;
}
}
}
return std::make_pair(filter_attr, diff_attr);
}
// returns filter and diff attributes as a pair
static std::pair<std::string, std::string> get_file_attributes (const std::string& filename, std::ostream& check_attr_stdin, std::istream& check_attr_stdout)
{
check_attr_stdin << filename << '\0' << std::flush;
std::string filter_attr;
std::string diff_attr;
// Example output:
// filename\0filter\0git-crypt\0filename\0diff\0git-crypt\0
for (int i = 0; i < 2; ++i) {
std::string filename;
std::string attr_name;
std::string attr_value;
std::getline(check_attr_stdout, filename, '\0');
std::getline(check_attr_stdout, attr_name, '\0');
std::getline(check_attr_stdout, attr_value, '\0');
if (attr_value != "unspecified" && attr_value != "unset" && attr_value != "set") {
if (attr_name == "filter") {
filter_attr = attr_value;
} else if (attr_name == "diff") {
diff_attr = attr_value;
}
}
}
return std::make_pair(filter_attr, diff_attr);
}
static bool check_if_blob_is_encrypted (const std::string& object_id)
{
// git cat-file blob object_id
std::vector<std::string> command;
command.push_back("git");
command.push_back("cat-file");
command.push_back("blob");
command.push_back(object_id);
// TODO: do this more efficiently - don't read entire command output into buffer, only read what we need
std::stringstream output;
if (!successful_exit(exec_command(command, output))) {
throw Error("'git cat-file' failed - is this a Git repository?");
}
char header[10];
output.read(header, sizeof(header));
return output.gcount() == sizeof(header) && std::memcmp(header, "\0GITCRYPT\0", 10) == 0;
}
static bool check_if_file_is_encrypted (const std::string& filename)
{
// git ls-files -sz filename
std::vector<std::string> command;
command.push_back("git");
command.push_back("ls-files");
command.push_back("-sz");
command.push_back("--");
command.push_back(filename);
std::stringstream output;
if (!successful_exit(exec_command(command, output))) {
throw Error("'git ls-files' failed - is this a Git repository?");
}
if (output.peek() == -1) {
return false;
}
std::string mode;
std::string object_id;
output >> mode >> object_id;
return check_if_blob_is_encrypted(object_id);
}
static bool is_git_file_mode (const std::string& mode)
{
return (std::strtoul(mode.c_str(), nullptr, 8) & 0170000) == 0100000;
}
static void get_encrypted_files (std::vector<std::string>& files, const char* key_name)
{
// git ls-files -cz -- path_to_top
std::vector<std::string> ls_files_command;
ls_files_command.push_back("git");
ls_files_command.push_back("ls-files");
ls_files_command.push_back("-csz");
ls_files_command.push_back("--");
const std::string path_to_top(get_path_to_top());
if (!path_to_top.empty()) {
ls_files_command.push_back(path_to_top);
}
Coprocess ls_files;
std::istream* ls_files_stdout = ls_files.stdout_pipe();
ls_files.spawn(ls_files_command);
Coprocess check_attr;
std::ostream* check_attr_stdin = nullptr;
std::istream* check_attr_stdout = nullptr;
if (git_version() >= make_version(1, 8, 5)) {
// In Git 1.8.5 (released 27 Nov 2013) and higher, we use a single `git check-attr` process
// to get the attributes of all files at once. In prior versions, we have to fork and exec
// a separate `git check-attr` process for each file, since -z and --stdin aren't supported.
// In a repository with thousands of files, this results in an almost 100x speedup.
std::vector<std::string> check_attr_command;
check_attr_command.push_back("git");
check_attr_command.push_back("check-attr");
check_attr_command.push_back("--stdin");
check_attr_command.push_back("-z");
check_attr_command.push_back("filter");
check_attr_command.push_back("diff");
check_attr_stdin = check_attr.stdin_pipe();
check_attr_stdout = check_attr.stdout_pipe();
check_attr.spawn(check_attr_command);
}
while (ls_files_stdout->peek() != -1) {
std::string mode;
std::string object_id;
std::string stage;
std::string filename;
*ls_files_stdout >> mode >> object_id >> stage >> std::ws;
std::getline(*ls_files_stdout, filename, '\0');
if (is_git_file_mode(mode)) {
std::string filter_attribute;
if (check_attr_stdin) {
filter_attribute = get_file_attributes(filename, *check_attr_stdin, *check_attr_stdout).first;
} else {
filter_attribute = get_file_attributes(filename).first;
}
if (filter_attribute == attribute_name(key_name)) {
files.push_back(filename);
}
}
}
if (!successful_exit(ls_files.wait())) {
throw Error("'git ls-files' failed - is this a Git repository?");
}
if (check_attr_stdin) {
check_attr.close_stdin();
if (!successful_exit(check_attr.wait())) {
throw Error("'git check-attr' failed - is this a Git repository?");
}
}
}
static void load_key (Key_file& key_file, const char* key_name, const char* key_path =0, const char* legacy_path =0)
{
if (legacy_path) {
std::ifstream key_file_in(legacy_path, std::fstream::binary);
if (!key_file_in) {
throw Error(std::string("Unable to open key file: ") + legacy_path);
}
key_file.load_legacy(key_file_in);
} else if (key_path) {
std::ifstream key_file_in(key_path, std::fstream::binary);
if (!key_file_in) {
throw Error(std::string("Unable to open key file: ") + key_path);
}
key_file.load(key_file_in);
} else {
std::ifstream key_file_in(get_internal_key_path(key_name).c_str(), std::fstream::binary);
if (!key_file_in) {
// TODO: include key name in error message
throw Error("Unable to open key file - have you unlocked/initialized this repository yet?");
}
key_file.load(key_file_in);
}
}
static bool decrypt_repo_key (Key_file& key_file, const char* key_name, uint32_t key_version, const std::vector<std::string>& secret_keys, const std::string& keys_path)
{
std::exception_ptr gpg_error;
for (std::vector<std::string>::const_iterator seckey(secret_keys.begin()); seckey != secret_keys.end(); ++seckey) {
std::ostringstream path_builder;
path_builder << keys_path << '/' << (key_name ? key_name : "default") << '/' << key_version << '/' << *seckey << ".gpg";
std::string path(path_builder.str());
if (access(path.c_str(), F_OK) == 0) {
std::stringstream decrypted_contents;
try {
gpg_decrypt_from_file(path, decrypted_contents);
} catch (const Gpg_error&) {
gpg_error = std::current_exception();
continue;
}
Key_file this_version_key_file;
this_version_key_file.load(decrypted_contents);
const Key_file::Entry* this_version_entry = this_version_key_file.get(key_version);
if (!this_version_entry) {
throw Error("GPG-encrypted keyfile is malformed because it does not contain expected key version");
}
if (!same_key_name(key_name, this_version_key_file.get_key_name())) {
throw Error("GPG-encrypted keyfile is malformed because it does not contain expected key name");
}
key_file.set_key_name(key_name);
key_file.add(*this_version_entry);
return true;
}
}
if (gpg_error) {
std::rethrow_exception(gpg_error);
}
return false;
}
static bool decrypt_repo_keys (std::vector<Key_file>& key_files, uint32_t key_version, const std::vector<std::string>& secret_keys, const std::string& keys_path)
{
bool successful = false;
std::vector<std::string> dirents;
if (access(keys_path.c_str(), F_OK) == 0) {
dirents = get_directory_contents(keys_path.c_str());
}
for (std::vector<std::string>::const_iterator dirent(dirents.begin()); dirent != dirents.end(); ++dirent) {
const char* key_name = 0;
if (*dirent != "default") {
if (!validate_key_name(dirent->c_str())) {
continue;
}
key_name = dirent->c_str();
}
Key_file key_file;
if (decrypt_repo_key(key_file, key_name, key_version, secret_keys, keys_path)) {
key_files.push_back(key_file);
successful = true;
}
}
return successful;
}
static void encrypt_repo_key (const char* key_name, const Key_file::Entry& key, const std::vector<std::pair<std::string, bool> >& collab_keys, const std::string& keys_path, std::vector<std::string>* new_files)
{
std::string key_file_data;
{
Key_file this_version_key_file;
this_version_key_file.set_key_name(key_name);
this_version_key_file.add(key);
key_file_data = this_version_key_file.store_to_string();
}
for (std::vector<std::pair<std::string, bool> >::const_iterator collab(collab_keys.begin()); collab != collab_keys.end(); ++collab) {
const std::string& fingerprint(collab->first);
const bool key_is_trusted(collab->second);
std::ostringstream path_builder;
path_builder << keys_path << '/' << (key_name ? key_name : "default") << '/' << key.version << '/' << fingerprint << ".gpg";
std::string path(path_builder.str());
if (access(path.c_str(), F_OK) == 0) {
continue;
}
mkdir_parent(path);
gpg_encrypt_to_file(path, fingerprint, key_is_trusted, key_file_data.data(), key_file_data.size());
new_files->push_back(path);
}
}
static int parse_plumbing_options (const char** key_name, const char** key_file, int argc, const char** argv)
{
Options_list options;
options.push_back(Option_def("-k", key_name));
options.push_back(Option_def("--key-name", key_name));
options.push_back(Option_def("--key-file", key_file));
return parse_options(options, argc, argv);
}
// Encrypt contents of stdin and write to stdout
int clean (int argc, const char** argv)
{
const char* key_name = 0;
const char* key_path = 0;
const char* legacy_key_path = 0;
int argi = parse_plumbing_options(&key_name, &key_path, argc, argv);
if (argc - argi == 0) {
} else if (!key_name && !key_path && argc - argi == 1) { // Deprecated - for compatibility with pre-0.4
legacy_key_path = argv[argi];
} else {
std::clog << "Usage: git-crypt clean [--key-name=NAME] [--key-file=PATH]" << std::endl;
return 2;
}
Key_file key_file;
load_key(key_file, key_name, key_path, legacy_key_path);
const Key_file::Entry* key = key_file.get_latest();
if (!key) {
std::clog << "git-crypt: error: key file is empty" << std::endl;
return 1;
}
// Read the entire file
Hmac_sha1_state hmac(key->hmac_key, HMAC_KEY_LEN); // Calculate the file's SHA1 HMAC as we go
uint64_t file_size = 0; // Keep track of the length, make sure it doesn't get too big
std::string file_contents; // First 8MB or so of the file go here
temp_fstream temp_file; // The rest of the file spills into a temporary file on disk
temp_file.exceptions(std::fstream::badbit);
char buffer[1024];
while (std::cin && file_size < Aes_ctr_encryptor::MAX_CRYPT_BYTES) {
std::cin.read(buffer, sizeof(buffer));
const size_t bytes_read = std::cin.gcount();
hmac.add(reinterpret_cast<unsigned char*>(buffer), bytes_read);
file_size += bytes_read;
if (file_size <= 8388608) {
file_contents.append(buffer, bytes_read);
} else {
if (!temp_file.is_open()) {
temp_file.open(std::fstream::in | std::fstream::out | std::fstream::binary | std::fstream::app);
}
temp_file.write(buffer, bytes_read);
}
}
// Make sure the file isn't so large we'll overflow the counter value (which would doom security)
if (file_size >= Aes_ctr_encryptor::MAX_CRYPT_BYTES) {
std::clog << "git-crypt: error: file too long to encrypt securely" << std::endl;
return 1;
}
// We use an HMAC of the file as the encryption nonce (IV) for CTR mode.
// By using a hash of the file we ensure that the encryption is
// deterministic so git doesn't think the file has changed when it really
// hasn't. CTR mode with a synthetic IV is provably semantically secure
// under deterministic CPA as long as the synthetic IV is derived from a
// secure PRF applied to the message. Since HMAC-SHA1 is a secure PRF, this
// encryption scheme is semantically secure under deterministic CPA.
//
// Informally, consider that if a file changes just a tiny bit, the IV will
// be completely different, resulting in a completely different ciphertext
// that leaks no information about the similarities of the plaintexts. Also,
// since we're using the output from a secure hash function plus a counter
// as the input to our block cipher, we should never have a situation where
// two different plaintext blocks get encrypted with the same CTR value. A
// nonce will be reused only if the entire file is the same, which leaks no
// information except that the files are the same.
//
// To prevent an attacker from building a dictionary of hash values and then
// looking up the nonce (which must be stored in the clear to allow for
// decryption), we use an HMAC as opposed to a straight hash.
// Note: Hmac_sha1_state::LEN >= Aes_ctr_encryptor::NONCE_LEN
unsigned char digest[Hmac_sha1_state::LEN];
hmac.get(digest);
// Write a header that...
std::cout.write("\0GITCRYPT\0", 10); // ...identifies this as an encrypted file
std::cout.write(reinterpret_cast<char*>(digest), Aes_ctr_encryptor::NONCE_LEN); // ...includes the nonce
// Now encrypt the file and write to stdout
Aes_ctr_encryptor aes(key->aes_key, digest);
// First read from the in-memory copy
const unsigned char* file_data = reinterpret_cast<const unsigned char*>(file_contents.data());
size_t file_data_len = file_contents.size();
while (file_data_len > 0) {
const size_t buffer_len = std::min(sizeof(buffer), file_data_len);
aes.process(file_data, reinterpret_cast<unsigned char*>(buffer), buffer_len);
std::cout.write(buffer, buffer_len);
file_data += buffer_len;
file_data_len -= buffer_len;
}
// Then read from the temporary file if applicable
if (temp_file.is_open()) {
temp_file.seekg(0);
while (temp_file.peek() != -1) {
temp_file.read(buffer, sizeof(buffer));
const size_t buffer_len = temp_file.gcount();
aes.process(reinterpret_cast<unsigned char*>(buffer),
reinterpret_cast<unsigned char*>(buffer),
buffer_len);
std::cout.write(buffer, buffer_len);
}
}
return 0;
}
static int decrypt_file_to_stdout (const Key_file& key_file, const unsigned char* header, std::istream& in)
{
const unsigned char* nonce = header + 10;
uint32_t key_version = 0; // TODO: get the version from the file header
const Key_file::Entry* key = key_file.get(key_version);
if (!key) {
std::clog << "git-crypt: error: key version " << key_version << " not available - please unlock with the latest version of the key." << std::endl;
return 1;
}
Aes_ctr_decryptor aes(key->aes_key, nonce);
Hmac_sha1_state hmac(key->hmac_key, HMAC_KEY_LEN);
while (in) {
unsigned char buffer[1024];
in.read(reinterpret_cast<char*>(buffer), sizeof(buffer));
aes.process(buffer, buffer, in.gcount());
hmac.add(buffer, in.gcount());
std::cout.write(reinterpret_cast<char*>(buffer), in.gcount());
}
unsigned char digest[Hmac_sha1_state::LEN];
hmac.get(digest);
if (!leakless_equals(digest, nonce, Aes_ctr_decryptor::NONCE_LEN)) {
std::clog << "git-crypt: error: encrypted file has been tampered with!" << std::endl;
// Although we've already written the tampered file to stdout, exiting
// with a non-zero status will tell git the file has not been filtered,
// so git will not replace it.
return 1;
}
return 0;
}
// Decrypt contents of stdin and write to stdout
int smudge (int argc, const char** argv)
{
const char* key_name = 0;
const char* key_path = 0;
const char* legacy_key_path = 0;
int argi = parse_plumbing_options(&key_name, &key_path, argc, argv);
if (argc - argi == 0) {
} else if (!key_name && !key_path && argc - argi == 1) { // Deprecated - for compatibility with pre-0.4
legacy_key_path = argv[argi];
} else {
std::clog << "Usage: git-crypt smudge [--key-name=NAME] [--key-file=PATH]" << std::endl;
return 2;
}
Key_file key_file;
load_key(key_file, key_name, key_path, legacy_key_path);
// Read the header to get the nonce and make sure it's actually encrypted
unsigned char header[10 + Aes_ctr_decryptor::NONCE_LEN];
std::cin.read(reinterpret_cast<char*>(header), sizeof(header));
if (std::cin.gcount() != sizeof(header) || std::memcmp(header, "\0GITCRYPT\0", 10) != 0) {
// File not encrypted - just copy it out to stdout
std::clog << "git-crypt: Warning: file not encrypted" << std::endl;
std::clog << "git-crypt: Run 'git-crypt status' to make sure all files are properly encrypted." << std::endl;
std::clog << "git-crypt: If 'git-crypt status' reports no problems, then an older version of" << std::endl;
std::clog << "git-crypt: this file may be unencrypted in the repository's history. If this" << std::endl;
std::clog << "git-crypt: file contains sensitive information, you can use 'git filter-branch'" << std::endl;
std::clog << "git-crypt: to remove its old versions from the history." << std::endl;
std::cout.write(reinterpret_cast<char*>(header), std::cin.gcount()); // include the bytes which we already read
std::cout << std::cin.rdbuf();
return 0;
}
return decrypt_file_to_stdout(key_file, header, std::cin);
}
int diff (int argc, const char** argv)
{
const char* key_name = 0;
const char* key_path = 0;
const char* filename = 0;
const char* legacy_key_path = 0;
int argi = parse_plumbing_options(&key_name, &key_path, argc, argv);
if (argc - argi == 1) {
filename = argv[argi];
} else if (!key_name && !key_path && argc - argi == 2) { // Deprecated - for compatibility with pre-0.4
legacy_key_path = argv[argi];
filename = argv[argi + 1];
} else {
std::clog << "Usage: git-crypt diff [--key-name=NAME] [--key-file=PATH] FILENAME" << std::endl;
return 2;
}
Key_file key_file;
load_key(key_file, key_name, key_path, legacy_key_path);
// Open the file
std::ifstream in(filename, std::fstream::binary);
if (!in) {
std::clog << "git-crypt: " << filename << ": unable to open for reading" << std::endl;
return 1;
}
in.exceptions(std::fstream::badbit);
// Read the header to get the nonce and determine if it's actually encrypted
unsigned char header[10 + Aes_ctr_decryptor::NONCE_LEN];
in.read(reinterpret_cast<char*>(header), sizeof(header));
if (in.gcount() != sizeof(header) || std::memcmp(header, "\0GITCRYPT\0", 10) != 0) {
// File not encrypted - just copy it out to stdout
std::cout.write(reinterpret_cast<char*>(header), in.gcount()); // include the bytes which we already read
std::cout << in.rdbuf();
return 0;
}
// Go ahead and decrypt it
return decrypt_file_to_stdout(key_file, header, in);
}
void help_init (std::ostream& out)
{
// |--------------------------------------------------------------------------------| 80 chars
out << "Usage: git-crypt init [OPTIONS]" << std::endl;
out << std::endl;
out << " -k, --key-name KEYNAME Initialize the given key, instead of the default" << std::endl;
out << std::endl;
}
int init (int argc, const char** argv)
{
const char* key_name = 0;
Options_list options;
options.push_back(Option_def("-k", &key_name));
options.push_back(Option_def("--key-name", &key_name));
int argi = parse_options(options, argc, argv);
if (!key_name && argc - argi == 1) {
std::clog << "Warning: 'git-crypt init' with a key file is deprecated as of git-crypt 0.4" << std::endl;
std::clog << "and will be removed in a future release. Please get in the habit of using" << std::endl;
std::clog << "'git-crypt unlock KEYFILE' instead." << std::endl;
return unlock(argc, argv);
}
if (argc - argi != 0) {
std::clog << "Error: git-crypt init takes no arguments" << std::endl;
help_init(std::clog);
return 2;
}
if (key_name) {
validate_key_name_or_throw(key_name);
}
std::string internal_key_path(get_internal_key_path(key_name));
if (access(internal_key_path.c_str(), F_OK) == 0) {
// TODO: add a -f option to reinitialize the repo anyways (this should probably imply a refresh)
// TODO: include key_name in error message
std::clog << "Error: this repository has already been initialized with git-crypt." << std::endl;
return 1;
}
// 1. Generate a key and install it
std::clog << "Generating key..." << std::endl;
Key_file key_file;
key_file.set_key_name(key_name);
key_file.generate();
mkdir_parent(internal_key_path);
if (!key_file.store_to_file(internal_key_path.c_str())) {
std::clog << "Error: " << internal_key_path << ": unable to write key file" << std::endl;
return 1;
}
// 2. Configure git for git-crypt
configure_git_filters(key_name);
return 0;
}
void help_unlock (std::ostream& out)
{
// |--------------------------------------------------------------------------------| 80 chars
out << "Usage: git-crypt unlock" << std::endl;
out << " or: git-crypt unlock KEY_FILE ..." << std::endl;
}
int unlock (int argc, const char** argv)
{
// 1. Make sure working directory is clean (ignoring untracked files)
// We do this because we check out files later, and we don't want the
// user to lose any changes. (TODO: only care if encrypted files are
// modified, since we only check out encrypted files)
// Running 'git status' also serves as a check that the Git repo is accessible.
std::stringstream status_output;
get_git_status(status_output);
if (status_output.peek() != -1) {
std::clog << "Error: Working directory not clean." << std::endl;
std::clog << "Please commit your changes or 'git stash' them before running 'git-crypt unlock'." << std::endl;
return 1;
}
// 2. Load the key(s)
std::vector<Key_file> key_files;
if (argc > 0) {
// Read from the symmetric key file(s)
for (int argi = 0; argi < argc; ++argi) {
const char* symmetric_key_file = argv[argi];
Key_file key_file;
try {
if (std::strcmp(symmetric_key_file, "-") == 0) {
key_file.load(std::cin);
} else {
if (!key_file.load_from_file(symmetric_key_file)) {
std::clog << "Error: " << symmetric_key_file << ": unable to read key file" << std::endl;
return 1;
}
}
} catch (Key_file::Incompatible) {
std::clog << "Error: " << symmetric_key_file << " is in an incompatible format" << std::endl;
std::clog << "Please upgrade to a newer version of git-crypt." << std::endl;
return 1;
} catch (Key_file::Malformed) {
std::clog << "Error: " << symmetric_key_file << ": not a valid git-crypt key file" << std::endl;
std::clog << "If this key was created prior to git-crypt 0.4, you need to migrate it" << std::endl;
std::clog << "by running 'git-crypt migrate-key /path/to/old_key /path/to/migrated_key'." << std::endl;
return 1;
}
key_files.push_back(key_file);
}
} else {
// Decrypt GPG key from root of repo
std::string repo_keys_path(get_repo_keys_path());
std::vector<std::string> gpg_secret_keys(gpg_list_secret_keys());
// TODO: command-line option to specify the precise secret key to use
// TODO: don't hard code key version 0 here - instead, determine the most recent version and try to decrypt that, or decrypt all versions if command-line option specified
// TODO: command line option to only unlock specific key instead of all of them
// TODO: avoid decrypting repo keys which are already unlocked in the .git directory
if (!decrypt_repo_keys(key_files, 0, gpg_secret_keys, repo_keys_path)) {
std::clog << "Error: no GPG secret key available to unlock this repository." << std::endl;
std::clog << "To unlock with a shared symmetric key instead, specify the path to the symmetric key as an argument to 'git-crypt unlock'." << std::endl;
// TODO std::clog << "To see a list of GPG keys authorized to unlock this repository, run 'git-crypt ls-gpg-users'." << std::endl;
return 1;
}
}
// 3. Install the key(s) and configure the git filters
std::vector<std::string> encrypted_files;
for (std::vector<Key_file>::iterator key_file(key_files.begin()); key_file != key_files.end(); ++key_file) {
std::string internal_key_path(get_internal_key_path(key_file->get_key_name()));
// TODO: croak if internal_key_path already exists???
mkdir_parent(internal_key_path);
if (!key_file->store_to_file(internal_key_path.c_str())) {
std::clog << "Error: " << internal_key_path << ": unable to write key file" << std::endl;
return 1;
}
configure_git_filters(key_file->get_key_name());
get_encrypted_files(encrypted_files, key_file->get_key_name());
}
// 4. Check out the files that are currently encrypted.
// Git won't check out a file if its mtime hasn't changed, so touch every file first.
for (std::vector<std::string>::const_iterator file(encrypted_files.begin()); file != encrypted_files.end(); ++file) {
touch_file(*file);
}
if (!git_checkout(encrypted_files)) {
std::clog << "Error: 'git checkout' failed" << std::endl;
std::clog << "git-crypt has been set up but existing encrypted files have not been decrypted" << std::endl;
return 1;
}
return 0;
}
void help_lock (std::ostream& out)
{
// |--------------------------------------------------------------------------------| 80 chars
out << "Usage: git-crypt lock [OPTIONS]" << std::endl;
out << std::endl;
out << " -a, --all Lock all keys, instead of just the default" << std::endl;
out << " -k, --key-name KEYNAME Lock the given key, instead of the default" << std::endl;
out << " -f, --force Lock even if unclean (you may lose uncommited work)" << std::endl;
out << std::endl;
}
int lock (int argc, const char** argv)
{
const char* key_name = 0;
bool all_keys = false;
bool force = false;
Options_list options;
options.push_back(Option_def("-k", &key_name));
options.push_back(Option_def("--key-name", &key_name));
options.push_back(Option_def("-a", &all_keys));
options.push_back(Option_def("--all", &all_keys));
options.push_back(Option_def("-f", &force));
options.push_back(Option_def("--force", &force));
int argi = parse_options(options, argc, argv);
if (argc - argi != 0) {
std::clog << "Error: git-crypt lock takes no arguments" << std::endl;
help_lock(std::clog);
return 2;
}
if (all_keys && key_name) {
std::clog << "Error: -k and --all options are mutually exclusive" << std::endl;
return 2;
}
// 1. Make sure working directory is clean (ignoring untracked files)
// We do this because we check out files later, and we don't want the
// user to lose any changes. (TODO: only care if encrypted files are
// modified, since we only check out encrypted files)
// Running 'git status' also serves as a check that the Git repo is accessible.
std::stringstream status_output;
get_git_status(status_output);
if (!force && status_output.peek() != -1) {
std::clog << "Error: Working directory not clean." << std::endl;
std::clog << "Please commit your changes or 'git stash' them before running 'git-crypt lock'." << std::endl;
std::clog << "Or, use 'git-crypt lock --force' and possibly lose uncommitted changes." << std::endl;
return 1;
}
// 2. deconfigure the git filters and remove decrypted keys
std::vector<std::string> encrypted_files;
if (all_keys) {
// deconfigure for all keys
std::vector<std::string> dirents = get_directory_contents(get_internal_keys_path().c_str());
for (std::vector<std::string>::const_iterator dirent(dirents.begin()); dirent != dirents.end(); ++dirent) {
const char* this_key_name = (*dirent == "default" ? 0 : dirent->c_str());
remove_file(get_internal_key_path(this_key_name));
deconfigure_git_filters(this_key_name);
get_encrypted_files(encrypted_files, this_key_name);
}
} else {
// just handle the given key
std::string internal_key_path(get_internal_key_path(key_name));
if (access(internal_key_path.c_str(), F_OK) == -1 && errno == ENOENT) {
std::clog << "Error: this repository is already locked";
if (key_name) {
std::clog << " with key '" << key_name << "'";
}
std::clog << "." << std::endl;
return 1;
}
remove_file(internal_key_path);
deconfigure_git_filters(key_name);
get_encrypted_files(encrypted_files, key_name);
}
// 3. Check out the files that are currently decrypted but should be encrypted.
// Git won't check out a file if its mtime hasn't changed, so touch every file first.
for (std::vector<std::string>::const_iterator file(encrypted_files.begin()); file != encrypted_files.end(); ++file) {
touch_file(*file);
}
if (!git_checkout(encrypted_files)) {
std::clog << "Error: 'git checkout' failed" << std::endl;
std::clog << "git-crypt has been locked up but existing decrypted files have not been encrypted" << std::endl;
return 1;
}
return 0;
}
void help_add_gpg_user (std::ostream& out)
{
// |--------------------------------------------------------------------------------| 80 chars
out << "Usage: git-crypt add-gpg-user [OPTIONS] GPG_USER_ID ..." << std::endl;
out << std::endl;
out << " -k, --key-name KEYNAME Add GPG user to given key, instead of default" << std::endl;
out << " -n, --no-commit Don't automatically commit" << std::endl;
out << " --trusted Assume the GPG user IDs are trusted" << std::endl;
out << std::endl;
}
int add_gpg_user (int argc, const char** argv)
{
const char* key_name = 0;
bool no_commit = false;
bool trusted = false;
Options_list options;
options.push_back(Option_def("-k", &key_name));
options.push_back(Option_def("--key-name", &key_name));
options.push_back(Option_def("-n", &no_commit));
options.push_back(Option_def("--no-commit", &no_commit));
options.push_back(Option_def("--trusted", &trusted));
int argi = parse_options(options, argc, argv);
if (argc - argi == 0) {
std::clog << "Error: no GPG user ID specified" << std::endl;
help_add_gpg_user(std::clog);
return 2;
}
// build a list of key fingerprints, and whether the key is trusted, for every collaborator specified on the command line
std::vector<std::pair<std::string, bool> > collab_keys;
for (int i = argi; i < argc; ++i) {
std::vector<std::string> keys(gpg_lookup_key(argv[i]));
if (keys.empty()) {
std::clog << "Error: public key for '" << argv[i] << "' not found in your GPG keyring" << std::endl;
return 1;
}
if (keys.size() > 1) {
std::clog << "Error: more than one public key matches '" << argv[i] << "' - please be more specific" << std::endl;
return 1;
}
const bool is_full_fingerprint(std::strncmp(argv[i], "0x", 2) == 0 && std::strlen(argv[i]) == 42);
collab_keys.push_back(std::make_pair(keys[0], trusted || is_full_fingerprint));
}
// TODO: have a retroactive option to grant access to all key versions, not just the most recent
Key_file key_file;
load_key(key_file, key_name);
const Key_file::Entry* key = key_file.get_latest();
if (!key) {
std::clog << "Error: key file is empty" << std::endl;
return 1;
}
const std::string state_path(get_repo_state_path());
std::vector<std::string> new_files;
encrypt_repo_key(key_name, *key, collab_keys, get_repo_keys_path(state_path), &new_files);
// Add a .gitatributes file to the repo state directory to prevent files in it from being encrypted.
const std::string state_gitattributes_path(state_path + "/.gitattributes");
if (access(state_gitattributes_path.c_str(), F_OK) != 0) {
std::ofstream state_gitattributes_file(state_gitattributes_path.c_str());
// |--------------------------------------------------------------------------------| 80 chars
state_gitattributes_file << "# Do not edit this file. To specify the files to encrypt, create your own\n";
state_gitattributes_file << "# .gitattributes file in the directory where your files are.\n";
state_gitattributes_file << "* !filter !diff\n";
state_gitattributes_file << "*.gpg binary\n";
state_gitattributes_file.close();
if (!state_gitattributes_file) {
std::clog << "Error: unable to write " << state_gitattributes_path << std::endl;
return 1;
}
new_files.push_back(state_gitattributes_path);
}
// add/commit the new files
if (!new_files.empty()) {
// git add NEW_FILE ...
std::vector<std::string> command;
command.push_back("git");
command.push_back("add");
command.push_back("--");
command.insert(command.end(), new_files.begin(), new_files.end());
if (!successful_exit(exec_command(command))) {
std::clog << "Error: 'git add' failed" << std::endl;
return 1;
}
// git commit ...
if (!no_commit) {
// TODO: include key_name in commit message
std::ostringstream commit_message_builder;
commit_message_builder << "Add " << collab_keys.size() << " git-crypt collaborator" << (collab_keys.size() != 1 ? "s" : "") << "\n\nNew collaborators:\n\n";
for (std::vector<std::pair<std::string, bool> >::const_iterator collab(collab_keys.begin()); collab != collab_keys.end(); ++collab) {
commit_message_builder << " " << collab->first << '\n';
commit_message_builder << " " << gpg_get_uid(collab->first) << '\n';
}
// git commit -m MESSAGE NEW_FILE ...
command.clear();
command.push_back("git");
command.push_back("commit");
command.push_back("-m");
command.push_back(commit_message_builder.str());
command.push_back("--");
command.insert(command.end(), new_files.begin(), new_files.end());
if (!successful_exit(exec_command(command))) {
std::clog << "Error: 'git commit' failed" << std::endl;
return 1;
}
}
}
return 0;
}
void help_rm_gpg_user (std::ostream& out)
{
// |--------------------------------------------------------------------------------| 80 chars
out << "Usage: git-crypt rm-gpg-user [OPTIONS] GPG_USER_ID ..." << std::endl;
out << std::endl;
out << " -k, --key-name KEYNAME Remove user from given key, instead of default" << std::endl;
out << " -n, --no-commit Don't automatically commit" << std::endl;
out << std::endl;
}
int rm_gpg_user (int argc, const char** argv) // TODO
{
std::clog << "Error: rm-gpg-user is not yet implemented." << std::endl;
return 1;
}
void help_ls_gpg_users (std::ostream& out)
{
// |--------------------------------------------------------------------------------| 80 chars
out << "Usage: git-crypt ls-gpg-users" << std::endl;
}
int ls_gpg_users (int argc, const char** argv) // TODO
{
// Sketch:
// Scan the sub-directories in .git-crypt/keys, outputting something like this:
// ====
// Key version 0:
// 0x143DE9B3F7316900 Andrew Ayer <andrew@example.com>
// 0x4E386D9C9C61702F ???
// Key version 1:
// 0x143DE9B3F7316900 Andrew Ayer <andrew@example.com>
// 0x1727274463D27F40 John Smith <smith@example.com>
// 0x4E386D9C9C61702F ???
// ====
// To resolve a long hex ID, use a command like this:
// gpg --options /dev/null --fixed-list-mode --batch --with-colons --list-keys 0x143DE9B3F7316900
std::clog << "Error: ls-gpg-users is not yet implemented." << std::endl;
return 1;
}
void help_export_key (std::ostream& out)
{
// |--------------------------------------------------------------------------------| 80 chars
out << "Usage: git-crypt export-key [OPTIONS] FILENAME" << std::endl;
out << std::endl;
out << " -k, --key-name KEYNAME Export the given key, instead of the default" << std::endl;
out << std::endl;
out << "When FILENAME is -, export to standard out." << std::endl;
}
int export_key (int argc, const char** argv)
{
// TODO: provide options to export only certain key versions
const char* key_name = 0;
Options_list options;
options.push_back(Option_def("-k", &key_name));
options.push_back(Option_def("--key-name", &key_name));
int argi = parse_options(options, argc, argv);
if (argc - argi != 1) {
std::clog << "Error: no filename specified" << std::endl;
help_export_key(std::clog);
return 2;
}
Key_file key_file;
load_key(key_file, key_name);
const char* out_file_name = argv[argi];
if (std::strcmp(out_file_name, "-") == 0) {
key_file.store(std::cout);
} else {
if (!key_file.store_to_file(out_file_name)) {
std::clog << "Error: " << out_file_name << ": unable to write key file" << std::endl;
return 1;
}
}
return 0;
}
void help_keygen (std::ostream& out)
{
// |--------------------------------------------------------------------------------| 80 chars
out << "Usage: git-crypt keygen FILENAME" << std::endl;
out << std::endl;
out << "When FILENAME is -, write to standard out." << std::endl;
}
int keygen (int argc, const char** argv)
{
if (argc != 1) {
std::clog << "Error: no filename specified" << std::endl;
help_keygen(std::clog);
return 2;
}
const char* key_file_name = argv[0];
if (std::strcmp(key_file_name, "-") != 0 && access(key_file_name, F_OK) == 0) {
std::clog << key_file_name << ": File already exists" << std::endl;
return 1;
}
std::clog << "Generating key..." << std::endl;
Key_file key_file;
key_file.generate();
if (std::strcmp(key_file_name, "-") == 0) {
key_file.store(std::cout);
} else {
if (!key_file.store_to_file(key_file_name)) {
std::clog << "Error: " << key_file_name << ": unable to write key file" << std::endl;
return 1;
}
}
return 0;
}
void help_migrate_key (std::ostream& out)
{
// |--------------------------------------------------------------------------------| 80 chars
out << "Usage: git-crypt migrate-key OLDFILENAME NEWFILENAME" << std::endl;
out << std::endl;
out << "Use - to read from standard in/write to standard out." << std::endl;
}
int migrate_key (int argc, const char** argv)
{
if (argc != 2) {
std::clog << "Error: filenames not specified" << std::endl;
help_migrate_key(std::clog);
return 2;
}
const char* key_file_name = argv[0];
const char* new_key_file_name = argv[1];
Key_file key_file;
try {
if (std::strcmp(key_file_name, "-") == 0) {
key_file.load_legacy(std::cin);
} else {
std::ifstream in(key_file_name, std::fstream::binary);
if (!in) {
std::clog << "Error: " << key_file_name << ": unable to open for reading" << std::endl;
return 1;
}
key_file.load_legacy(in);
}
if (std::strcmp(new_key_file_name, "-") == 0) {
key_file.store(std::cout);
} else {
if (!key_file.store_to_file(new_key_file_name)) {
std::clog << "Error: " << new_key_file_name << ": unable to write key file" << std::endl;
return 1;
}
}
} catch (Key_file::Malformed) {
std::clog << "Error: " << key_file_name << ": not a valid legacy git-crypt key file" << std::endl;
return 1;
}
return 0;
}
void help_refresh (std::ostream& out)
{
// |--------------------------------------------------------------------------------| 80 chars
out << "Usage: git-crypt refresh" << std::endl;
}
int refresh (int argc, const char** argv) // TODO: do a force checkout, much like in unlock
{
std::clog << "Error: refresh is not yet implemented." << std::endl;
return 1;
}
void help_status (std::ostream& out)
{
// |--------------------------------------------------------------------------------| 80 chars
out << "Usage: git-crypt status [OPTIONS] [FILE ...]" << std::endl;
//out << " or: git-crypt status -r [OPTIONS]" << std::endl;
//out << " or: git-crypt status -f" << std::endl;
out << std::endl;
out << " -e Show encrypted files only" << std::endl;
out << " -u Show unencrypted files only" << std::endl;
//out << " -r Show repository status only" << std::endl;
out << " -f, --fix Fix problems with the repository" << std::endl;
//out << " -z Machine-parseable output" << std::endl;
out << std::endl;
}
int status (int argc, const char** argv)
{
// Usage:
// git-crypt status -r [-z] Show repo status
// git-crypt status [-e | -u] [-z] [FILE ...] Show encrypted status of files
// git-crypt status -f Fix unencrypted blobs
bool repo_status_only = false; // -r show repo status only
bool show_encrypted_only = false; // -e show encrypted files only
bool show_unencrypted_only = false; // -u show unencrypted files only
bool fix_problems = false; // -f fix problems
bool machine_output = false; // -z machine-parseable output
Options_list options;
options.push_back(Option_def("-r", &repo_status_only));
options.push_back(Option_def("-e", &show_encrypted_only));
options.push_back(Option_def("-u", &show_unencrypted_only));
options.push_back(Option_def("-f", &fix_problems));
options.push_back(Option_def("--fix", &fix_problems));
options.push_back(Option_def("-z", &machine_output));
int argi = parse_options(options, argc, argv);
if (repo_status_only) {
if (show_encrypted_only || show_unencrypted_only) {
std::clog << "Error: -e and -u options cannot be used with -r" << std::endl;
return 2;
}
if (fix_problems) {
std::clog << "Error: -f option cannot be used with -r" << std::endl;
return 2;
}
if (argc - argi != 0) {
std::clog << "Error: filenames cannot be specified when -r is used" << std::endl;
return 2;
}
}
if (show_encrypted_only && show_unencrypted_only) {
std::clog << "Error: -e and -u options are mutually exclusive" << std::endl;
return 2;
}
if (fix_problems && (show_encrypted_only || show_unencrypted_only)) {
std::clog << "Error: -e and -u options cannot be used with -f" << std::endl;
return 2;
}
if (machine_output) {
// TODO: implement machine-parseable output
std::clog << "Sorry, machine-parseable output is not yet implemented" << std::endl;
return 2;
}
if (argc - argi == 0) {
// TODO: check repo status:
// is it set up for git-crypt?
// which keys are unlocked?
// --> check for filter config (see configure_git_filters()) and corresponding internal key
if (repo_status_only) {
return 0;
}
}
// git ls-files -cotsz --exclude-standard ...
std::vector<std::string> command;
command.push_back("git");
command.push_back("ls-files");
command.push_back("-cotsz");
command.push_back("--exclude-standard");
command.push_back("--");
if (argc - argi == 0) {
const std::string path_to_top(get_path_to_top());
if (!path_to_top.empty()) {
command.push_back(path_to_top);
}
} else {
for (int i = argi; i < argc; ++i) {
command.push_back(argv[i]);
}
}
std::stringstream output;
if (!successful_exit(exec_command(command, output))) {
throw Error("'git ls-files' failed - is this a Git repository?");
}
// Output looks like (w/o newlines):
// ? .gitignore\0
// H 100644 06ec22e5ed0de9280731ef000a10f9c3fbc26338 0 afile\0
std::vector<std::string> files;
bool attribute_errors = false;
bool unencrypted_blob_errors = false;
unsigned int nbr_of_fixed_blobs = 0;
unsigned int nbr_of_fix_errors = 0;
while (output.peek() != -1) {
std::string tag;
std::string object_id;
std::string filename;
output >> tag;
if (tag != "?") {
std::string mode;
std::string stage;
output >> mode >> object_id >> stage;
if (!is_git_file_mode(mode)) {
continue;
}
}
output >> std::ws;
std::getline(output, filename, '\0');
// TODO: get file attributes en masse for efficiency... unfortunately this requires machine-parseable output from git check-attr to be workable, and this is only supported in Git 1.8.5 and above (released 27 Nov 2013)
const std::pair<std::string, std::string> file_attrs(get_file_attributes(filename));
if (file_attrs.first == "git-crypt" || std::strncmp(file_attrs.first.c_str(), "git-crypt-", 10) == 0) {
// File is encrypted
const bool blob_is_unencrypted = !object_id.empty() && !check_if_blob_is_encrypted(object_id);
if (fix_problems && blob_is_unencrypted) {
if (access(filename.c_str(), F_OK) != 0) {
std::clog << "Error: " << filename << ": cannot stage encrypted version because not present in working tree - please 'git rm' or 'git checkout' it" << std::endl;
++nbr_of_fix_errors;
} else {
touch_file(filename);
std::vector<std::string> git_add_command;
git_add_command.push_back("git");
git_add_command.push_back("add");
git_add_command.push_back("--");
git_add_command.push_back(filename);
if (!successful_exit(exec_command(git_add_command))) {
throw Error("'git-add' failed");
}
if (check_if_file_is_encrypted(filename)) {
std::cout << filename << ": staged encrypted version" << std::endl;
++nbr_of_fixed_blobs;
} else {
std::clog << "Error: " << filename << ": still unencrypted even after staging" << std::endl;
++nbr_of_fix_errors;
}
}
} else if (!fix_problems && !show_unencrypted_only) {
// TODO: output the key name used to encrypt this file
std::cout << " encrypted: " << filename;
if (file_attrs.second != file_attrs.first) {
// but diff filter is not properly set
std::cout << " *** WARNING: diff=" << file_attrs.first << " attribute not set ***";
attribute_errors = true;
}
if (blob_is_unencrypted) {
// File not actually encrypted
std::cout << " *** WARNING: staged/committed version is NOT ENCRYPTED! ***";
unencrypted_blob_errors = true;
}
std::cout << std::endl;
}
} else {
// File not encrypted
if (!fix_problems && !show_encrypted_only) {
std::cout << "not encrypted: " << filename << std::endl;
}
}
}
int exit_status = 0;
if (attribute_errors) {
std::cout << std::endl;
std::cout << "Warning: one or more files has a git-crypt filter attribute but not a" << std::endl;
std::cout << "corresponding git-crypt diff attribute. For proper 'git diff' operation" << std::endl;
std::cout << "you should fix the .gitattributes file to specify the correct diff attribute." << std::endl;
std::cout << "Consult the git-crypt documentation for help." << std::endl;
exit_status = 1;
}
if (unencrypted_blob_errors) {
std::cout << std::endl;
std::cout << "Warning: one or more files is marked for encryption via .gitattributes but" << std::endl;
std::cout << "was staged and/or committed before the .gitattributes file was in effect." << std::endl;
std::cout << "Run 'git-crypt status' with the '-f' option to stage an encrypted version." << std::endl;
exit_status = 1;
}
if (nbr_of_fixed_blobs) {
std::cout << "Staged " << nbr_of_fixed_blobs << " encrypted file" << (nbr_of_fixed_blobs != 1 ? "s" : "") << "." << std::endl;
std::cout << "Warning: if these files were previously committed, unencrypted versions still exist in the repository's history." << std::endl;
}
if (nbr_of_fix_errors) {
std::cout << "Unable to stage " << nbr_of_fix_errors << " file" << (nbr_of_fix_errors != 1 ? "s" : "") << "." << std::endl;
exit_status = 1;
}
return exit_status;
}
================================================
FILE: commands.hpp
================================================
/*
* Copyright 2012, 2014 Andrew Ayer
*
* This file is part of git-crypt.
*
* git-crypt is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* git-crypt is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with git-crypt. If not, see <http://www.gnu.org/licenses/>.
*
* Additional permission under GNU GPL version 3 section 7:
*
* If you modify the Program, or any covered work, by linking or
* combining it with the OpenSSL project's OpenSSL library (or a
* modified version of that library), containing parts covered by the
* terms of the OpenSSL or SSLeay licenses, the licensors of the Program
* grant you additional permission to convey the resulting work.
* Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of OpenSSL used as well
* as that of the covered work.
*/
#ifndef GIT_CRYPT_COMMANDS_HPP
#define GIT_CRYPT_COMMANDS_HPP
#include <string>
#include <iosfwd>
struct Error {
std::string message;
explicit Error (std::string m) : message(m) { }
};
// Plumbing commands:
int clean (int argc, const char** argv);
int smudge (int argc, const char** argv);
int diff (int argc, const char** argv);
// Public commands:
int init (int argc, const char** argv);
int unlock (int argc, const char** argv);
int lock (int argc, const char** argv);
int add_gpg_user (int argc, const char** argv);
int rm_gpg_user (int argc, const char** argv);
int ls_gpg_users (int argc, const char** argv);
int export_key (int argc, const char** argv);
int keygen (int argc, const char** argv);
int migrate_key (int argc, const char** argv);
int refresh (int argc, const char** argv);
int status (int argc, const char** argv);
// Help messages:
void help_init (std::ostream&);
void help_unlock (std::ostream&);
void help_lock (std::ostream&);
void help_add_gpg_user (std::ostream&);
void help_rm_gpg_user (std::ostream&);
void help_ls_gpg_users (std::ostream&);
void help_export_key (std::ostream&);
void help_keygen (std::ostream&);
void help_migrate_key (std::ostream&);
void help_refresh (std::ostream&);
void help_status (std::ostream&);
// other
std::string get_git_config (const std::string& name);
#endif
================================================
FILE: coprocess-unix.cpp
================================================
/*
* Copyright 2015 Andrew Ayer
*
* This file is part of git-crypt.
*
* git-crypt is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* git-crypt is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with git-crypt. If not, see <http://www.gnu.org/licenses/>.
*
* Additional permission under GNU GPL version 3 section 7:
*
* If you modify the Program, or any covered work, by linking or
* combining it with the OpenSSL project's OpenSSL library (or a
* modified version of that library), containing parts covered by the
* terms of the OpenSSL or SSLeay licenses, the licensors of the Program
* grant you additional permission to convey the resulting work.
* Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of OpenSSL used as well
* as that of the covered work.
*/
#include "coprocess.hpp"
#include "util.hpp"
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
static int execvp (const std::string& file, const std::vector<std::string>& args)
{
std::vector<const char*> args_c_str;
args_c_str.reserve(args.size());
for (std::vector<std::string>::const_iterator arg(args.begin()); arg != args.end(); ++arg) {
args_c_str.push_back(arg->c_str());
}
args_c_str.push_back(nullptr);
return execvp(file.c_str(), const_cast<char**>(&args_c_str[0]));
}
Coprocess::Coprocess ()
{
pid = -1;
stdin_pipe_reader = -1;
stdin_pipe_writer = -1;
stdin_pipe_ostream = nullptr;
stdout_pipe_reader = -1;
stdout_pipe_writer = -1;
stdout_pipe_istream = nullptr;
}
Coprocess::~Coprocess ()
{
close_stdin();
close_stdout();
}
std::ostream* Coprocess::stdin_pipe ()
{
if (!stdin_pipe_ostream) {
int fds[2];
if (pipe(fds) == -1) {
throw System_error("pipe", "", errno);
}
stdin_pipe_reader = fds[0];
stdin_pipe_writer = fds[1];
stdin_pipe_ostream = new ofhstream(this, write_stdin);
}
return stdin_pipe_ostream;
}
void Coprocess::close_stdin ()
{
delete stdin_pipe_ostream;
stdin_pipe_ostream = nullptr;
if (stdin_pipe_writer != -1) {
close(stdin_pipe_writer);
stdin_pipe_writer = -1;
}
if (stdin_pipe_reader != -1) {
close(stdin_pipe_reader);
stdin_pipe_reader = -1;
}
}
std::istream* Coprocess::stdout_pipe ()
{
if (!stdout_pipe_istream) {
int fds[2];
if (pipe(fds) == -1) {
throw System_error("pipe", "", errno);
}
stdout_pipe_reader = fds[0];
stdout_pipe_writer = fds[1];
stdout_pipe_istream = new ifhstream(this, read_stdout);
}
return stdout_pipe_istream;
}
void Coprocess::close_stdout ()
{
delete stdout_pipe_istream;
stdout_pipe_istream = nullptr;
if (stdout_pipe_writer != -1) {
close(stdout_pipe_writer);
stdout_pipe_writer = -1;
}
if (stdout_pipe_reader != -1) {
close(stdout_pipe_reader);
stdout_pipe_reader = -1;
}
}
void Coprocess::spawn (const std::vector<std::string>& args)
{
pid = fork();
if (pid == -1) {
throw System_error("fork", "", errno);
}
if (pid == 0) {
if (stdin_pipe_writer != -1) {
close(stdin_pipe_writer);
}
if (stdout_pipe_reader != -1) {
close(stdout_pipe_reader);
}
if (stdin_pipe_reader != -1) {
dup2(stdin_pipe_reader, 0);
close(stdin_pipe_reader);
}
if (stdout_pipe_writer != -1) {
dup2(stdout_pipe_writer, 1);
close(stdout_pipe_writer);
}
execvp(args[0], args);
perror(args[0].c_str());
_exit(-1);
}
if (stdin_pipe_reader != -1) {
close(stdin_pipe_reader);
stdin_pipe_reader = -1;
}
if (stdout_pipe_writer != -1) {
close(stdout_pipe_writer);
stdout_pipe_writer = -1;
}
}
int Coprocess::wait ()
{
int status = 0;
if (waitpid(pid, &status, 0) == -1) {
throw System_error("waitpid", "", errno);
}
return status;
}
size_t Coprocess::write_stdin (void* handle, const void* buf, size_t count)
{
const int fd = static_cast<Coprocess*>(handle)->stdin_pipe_writer;
ssize_t ret;
while ((ret = write(fd, buf, count)) == -1 && errno == EINTR); // restart if interrupted
if (ret < 0) {
throw System_error("write", "", errno);
}
return ret;
}
size_t Coprocess::read_stdout (void* handle, void* buf, size_t count)
{
const int fd = static_cast<Coprocess*>(handle)->stdout_pipe_reader;
ssize_t ret;
while ((ret = read(fd, buf, count)) == -1 && errno == EINTR); // restart if interrupted
if (ret < 0) {
throw System_error("read", "", errno);
}
return ret;
}
================================================
FILE: coprocess-unix.hpp
================================================
/*
* Copyright 2015 Andrew Ayer
*
* This file is part of git-crypt.
*
* git-crypt is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* git-crypt is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with git-crypt. If not, see <http://www.gnu.org/licenses/>.
*
* Additional permission under GNU GPL version 3 section 7:
*
* If you modify the Program, or any covered work, by linking or
* combining it with the OpenSSL project's OpenSSL library (or a
* modified version of that library), containing parts covered by the
* terms of the OpenSSL or SSLeay licenses, the licensors of the Program
* grant you additional permission to convey the resulting work.
* Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of OpenSSL used as well
* as that of the covered work.
*/
#ifndef GIT_CRYPT_COPROCESS_HPP
#define GIT_CRYPT_COPROCESS_HPP
#include "fhstream.hpp"
#include <unistd.h>
#include <vector>
class Coprocess {
pid_t pid;
int stdin_pipe_reader;
int stdin_pipe_writer;
ofhstream* stdin_pipe_ostream;
static size_t write_stdin (void*, const void*, size_t);
int stdout_pipe_reader;
int stdout_pipe_writer;
ifhstream* stdout_pipe_istream;
static size_t read_stdout (void*, void*, size_t);
Coprocess (const Coprocess&); // Disallow copy
Coprocess& operator= (const Coprocess&); // Disallow assignment
public:
Coprocess ();
~Coprocess ();
std::ostream* stdin_pipe ();
void close_stdin ();
std::istream* stdout_pipe ();
void close_stdout ();
void spawn (const std::vector<std::string>&);
int wait ();
};
#endif
================================================
FILE: coprocess-win32.cpp
================================================
/*
* Copyright 2015 Andrew Ayer
*
* This file is part of git-crypt.
*
* git-crypt is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* git-crypt is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with git-crypt. If not, see <http://www.gnu.org/licenses/>.
*
* Additional permission under GNU GPL version 3 section 7:
*
* If you modify the Program, or any covered work, by linking or
* combining it with the OpenSSL project's OpenSSL library (or a
* modified version of that library), containing parts covered by the
* terms of the OpenSSL or SSLeay licenses, the licensors of the Program
* grant you additional permission to convey the resulting work.
* Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of OpenSSL used as well
* as that of the covered work.
*/
#include "coprocess-win32.hpp"
#include "util.hpp"
static void escape_cmdline_argument (std::string& cmdline, const std::string& arg)
{
// For an explanation of Win32's arcane argument quoting rules, see:
// http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx
// http://msdn.microsoft.com/en-us/library/bb776391%28v=vs.85%29.aspx
// http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx
// http://blogs.msdn.com/b/oldnewthing/archive/2010/09/17/10063629.aspx
cmdline.push_back('"');
std::string::const_iterator p(arg.begin());
while (p != arg.end()) {
if (*p == '"') {
cmdline.push_back('\\');
cmdline.push_back('"');
++p;
} else if (*p == '\\') {
unsigned int num_backslashes = 0;
while (p != arg.end() && *p == '\\') {
++num_backslashes;
++p;
}
if (p == arg.end() || *p == '"') {
// Backslashes need to be escaped
num_backslashes *= 2;
}
while (num_backslashes--) {
cmdline.push_back('\\');
}
} else {
cmdline.push_back(*p++);
}
}
cmdline.push_back('"');
}
static std::string format_cmdline (const std::vector<std::string>& command)
{
std::string cmdline;
for (std::vector<std::string>::const_iterator arg(command.begin()); arg != command.end(); ++arg) {
if (arg != command.begin()) {
cmdline.push_back(' ');
}
escape_cmdline_argument(cmdline, *arg);
}
return cmdline;
}
static HANDLE spawn_command (const std::vector<std::string>& command, HANDLE stdin_handle, HANDLE stdout_handle, HANDLE stderr_handle)
{
PROCESS_INFORMATION proc_info;
ZeroMemory(&proc_info, sizeof(proc_info));
STARTUPINFO start_info;
ZeroMemory(&start_info, sizeof(start_info));
start_info.cb = sizeof(STARTUPINFO);
start_info.hStdInput = stdin_handle ? stdin_handle : GetStdHandle(STD_INPUT_HANDLE);
start_info.hStdOutput = stdout_handle ? stdout_handle : GetStdHandle(STD_OUTPUT_HANDLE);
start_info.hStdError = stderr_handle ? stderr_handle : GetStdHandle(STD_ERROR_HANDLE);
start_info.dwFlags |= STARTF_USESTDHANDLES;
std::string cmdline(format_cmdline(command));
if (!CreateProcessA(nullptr, // application name (nullptr to use command line)
const_cast<char*>(cmdline.c_str()),
nullptr, // process security attributes
nullptr, // primary thread security attributes
TRUE, // handles are inherited
0, // creation flags
nullptr, // use parent's environment
nullptr, // use parent's current directory
&start_info,
&proc_info)) {
throw System_error("CreateProcess", cmdline, GetLastError());
}
CloseHandle(proc_info.hThread);
return proc_info.hProcess;
}
Coprocess::Coprocess ()
{
proc_handle = nullptr;
stdin_pipe_reader = nullptr;
stdin_pipe_writer = nullptr;
stdin_pipe_ostream = nullptr;
stdout_pipe_reader = nullptr;
stdout_pipe_writer = nullptr;
stdout_pipe_istream = nullptr;
}
Coprocess::~Coprocess ()
{
close_stdin();
close_stdout();
if (proc_handle) {
CloseHandle(proc_handle);
}
}
std::ostream* Coprocess::stdin_pipe ()
{
if (!stdin_pipe_ostream) {
SECURITY_ATTRIBUTES sec_attr;
// Set the bInheritHandle flag so pipe handles are inherited.
sec_attr.nLength = sizeof(SECURITY_ATTRIBUTES);
sec_attr.bInheritHandle = TRUE;
sec_attr.lpSecurityDescriptor = nullptr;
// Create a pipe for the child process's STDIN.
if (!CreatePipe(&stdin_pipe_reader, &stdin_pipe_writer, &sec_attr, 0)) {
throw System_error("CreatePipe", "", GetLastError());
}
// Ensure the write handle to the pipe for STDIN is not inherited.
if (!SetHandleInformation(stdin_pipe_writer, HANDLE_FLAG_INHERIT, 0)) {
throw System_error("SetHandleInformation", "", GetLastError());
}
stdin_pipe_ostream = new ofhstream(this, write_stdin);
}
return stdin_pipe_ostream;
}
void Coprocess::close_stdin ()
{
delete stdin_pipe_ostream;
stdin_pipe_ostream = nullptr;
if (stdin_pipe_writer) {
CloseHandle(stdin_pipe_writer);
stdin_pipe_writer = nullptr;
}
if (stdin_pipe_reader) {
CloseHandle(stdin_pipe_reader);
stdin_pipe_reader = nullptr;
}
}
std::istream* Coprocess::stdout_pipe ()
{
if (!stdout_pipe_istream) {
SECURITY_ATTRIBUTES sec_attr;
// Set the bInheritHandle flag so pipe handles are inherited.
sec_attr.nLength = sizeof(SECURITY_ATTRIBUTES);
sec_attr.bInheritHandle = TRUE;
sec_attr.lpSecurityDescriptor = nullptr;
// Create a pipe for the child process's STDOUT.
if (!CreatePipe(&stdout_pipe_reader, &stdout_pipe_writer, &sec_attr, 0)) {
throw System_error("CreatePipe", "", GetLastError());
}
// Ensure the read handle to the pipe for STDOUT is not inherited.
if (!SetHandleInformation(stdout_pipe_reader, HANDLE_FLAG_INHERIT, 0)) {
throw System_error("SetHandleInformation", "", GetLastError());
}
stdout_pipe_istream = new ifhstream(this, read_stdout);
}
return stdout_pipe_istream;
}
void Coprocess::close_stdout ()
{
delete stdout_pipe_istream;
stdout_pipe_istream = nullptr;
if (stdout_pipe_writer) {
CloseHandle(stdout_pipe_writer);
stdout_pipe_writer = nullptr;
}
if (stdout_pipe_reader) {
CloseHandle(stdout_pipe_reader);
stdout_pipe_reader = nullptr;
}
}
void Coprocess::spawn (const std::vector<std::string>& args)
{
proc_handle = spawn_command(args, stdin_pipe_reader, stdout_pipe_writer, nullptr);
if (stdin_pipe_reader) {
CloseHandle(stdin_pipe_reader);
stdin_pipe_reader = nullptr;
}
if (stdout_pipe_writer) {
CloseHandle(stdout_pipe_writer);
stdout_pipe_writer = nullptr;
}
}
int Coprocess::wait ()
{
if (WaitForSingleObject(proc_handle, INFINITE) == WAIT_FAILED) {
throw System_error("WaitForSingleObject", "", GetLastError());
}
DWORD exit_code;
if (!GetExitCodeProcess(proc_handle, &exit_code)) {
throw System_error("GetExitCodeProcess", "", GetLastError());
}
return exit_code;
}
size_t Coprocess::write_stdin (void* handle, const void* buf, size_t count)
{
DWORD bytes_written;
if (!WriteFile(static_cast<Coprocess*>(handle)->stdin_pipe_writer, buf, count, &bytes_written, nullptr)) {
throw System_error("WriteFile", "", GetLastError());
}
return bytes_written;
}
size_t Coprocess::read_stdout (void* handle, void* buf, size_t count)
{
// Note that ReadFile on a pipe may return with bytes_read==0 if the other
// end of the pipe writes zero bytes, so retry when this happens.
// When the other end of the pipe actually closes, ReadFile
// fails with ERROR_BROKEN_PIPE.
DWORD bytes_read;
do {
if (!ReadFile(static_cast<Coprocess*>(handle)->stdout_pipe_reader, buf, count, &bytes_read, nullptr)) {
const DWORD read_error = GetLastError();
if (read_error != ERROR_BROKEN_PIPE) {
throw System_error("ReadFile", "", read_error);
}
return 0;
}
} while (bytes_read == 0);
return bytes_read;
}
================================================
FILE: coprocess-win32.hpp
================================================
/*
* Copyright 2015 Andrew Ayer
*
* This file is part of git-crypt.
*
* git-crypt is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* git-crypt is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with git-crypt. If not, see <http://www.gnu.org/licenses/>.
*
* Additional permission under GNU GPL version 3 section 7:
*
* If you modify the Program, or any covered work, by linking or
* combining it with the OpenSSL project's OpenSSL library (or a
* modified version of that library), containing parts covered by the
* terms of the OpenSSL or SSLeay licenses, the licensors of the Program
* grant you additional permission to convey the resulting work.
* Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of OpenSSL used as well
* as that of the covered work.
*/
#ifndef GIT_CRYPT_COPROCESS_HPP
#define GIT_CRYPT_COPROCESS_HPP
#include "fhstream.hpp"
#include <windows.h>
#include <vector>
class Coprocess {
HANDLE proc_handle;
HANDLE stdin_pipe_reader;
HANDLE stdin_pipe_writer;
ofhstream* stdin_pipe_ostream;
static size_t write_stdin (void*, const void*, size_t);
HANDLE stdout_pipe_reader;
HANDLE stdout_pipe_writer;
ifhstream* stdout_pipe_istream;
static size_t read_stdout (void*, void*, size_t);
Coprocess (const Coprocess&); // Disallow copy
Coprocess& operator= (const Coprocess&); // Disallow assignment
public:
Coprocess ();
~Coprocess ();
std::ostream* stdin_pipe ();
void close_stdin ();
std::istream* stdout_pipe ();
void close_stdout ();
void spawn (const std::vector<std::string>&);
int wait ();
};
#endif
================================================
FILE: coprocess.cpp
================================================
#ifdef _WIN32
#include "coprocess-win32.cpp"
#else
#include "coprocess-unix.cpp"
#endif
================================================
FILE: coprocess.hpp
================================================
#ifdef _WIN32
#include "coprocess-win32.hpp"
#else
#include "coprocess-unix.hpp"
#endif
================================================
FILE: crypto-openssl-11.cpp
================================================
/*
* Copyright 2012, 2014 Andrew Ayer
*
* This file is part of git-crypt.
*
* git-crypt is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* git-crypt is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with git-crypt. If not, see <http://www.gnu.org/licenses/>.
*
* Additional permission under GNU GPL version 3 section 7:
*
* If you modify the Program, or any covered work, by linking or
* combining it with the OpenSSL project's OpenSSL library (or a
* modified version of that library), containing parts covered by the
* terms of the OpenSSL or SSLeay licenses, the licensors of the Program
* grant you additional permission to convey the resulting work.
* Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of OpenSSL used as well
* as that of the covered work.
*/
#include "crypto.hpp"
#include "key.hpp"
#include "util.hpp"
#include <openssl/aes.h>
#include <openssl/sha.h>
#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/err.h>
#include <sstream>
#include <cstring>
void init_crypto ()
{
ERR_load_crypto_strings();
}
struct Aes_ecb_encryptor::Aes_impl {
AES_KEY key;
};
Aes_ecb_encryptor::Aes_ecb_encryptor (const unsigned char* raw_key)
: impl(new Aes_impl)
{
if (AES_set_encrypt_key(raw_key, KEY_LEN * 8, &(impl->key)) != 0) {
throw Crypto_error("Aes_ctr_encryptor::Aes_ctr_encryptor", "AES_set_encrypt_key failed");
}
}
Aes_ecb_encryptor::~Aes_ecb_encryptor ()
{
// Note: Explicit destructor necessary because class contains an unique_ptr
// which contains an incomplete type when the unique_ptr is declared.
explicit_memset(&impl->key, '\0', sizeof(impl->key));
}
void Aes_ecb_encryptor::encrypt(const unsigned char* plain, unsigned char* cipher)
{
AES_encrypt(plain, cipher, &(impl->key));
}
struct Hmac_sha1_state::Hmac_impl {
HMAC_CTX *ctx;
};
Hmac_sha1_state::Hmac_sha1_state (const unsigned char* key, size_t key_len)
: impl(new Hmac_impl)
{
impl->ctx = HMAC_CTX_new();
HMAC_Init_ex(impl->ctx, key, key_len, EVP_sha1(), nullptr);
}
Hmac_sha1_state::~Hmac_sha1_state ()
{
HMAC_CTX_free(impl->ctx);
}
void Hmac_sha1_state::add (const unsigned char* buffer, size_t buffer_len)
{
HMAC_Update(impl->ctx, buffer, buffer_len);
}
void Hmac_sha1_state::get (unsigned char* digest)
{
unsigned int len;
HMAC_Final(impl->ctx, digest, &len);
}
void random_bytes (unsigned char* buffer, size_t len)
{
if (RAND_bytes(buffer, len) != 1) {
std::ostringstream message;
while (unsigned long code = ERR_get_error()) {
char error_string[120];
ERR_error_string_n(code, error_string, sizeof(error_string));
message << "OpenSSL Error: " << error_string << "; ";
}
throw Crypto_error("random_bytes", message.str());
}
}
================================================
FILE: crypto.cpp
================================================
/*
* Copyright 2012, 2014 Andrew Ayer
*
* This file is part of git-crypt.
*
* git-crypt is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* git-crypt is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with git-crypt. If not, see <http://www.gnu.org/licenses/>.
*
* Additional permission under GNU GPL version 3 section 7:
*
* If you modify the Program, or any covered work, by linking or
* combining it with the OpenSSL project's OpenSSL library (or a
* modified version of that library), containing parts covered by the
* terms of the OpenSSL or SSLeay licenses, the licensors of the Program
* grant you additional permission to convey the resulting work.
* Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of OpenSSL used as well
* as that of the covered work.
*/
#include "crypto.hpp"
#include "util.hpp"
#include <cstring>
Aes_ctr_encryptor::Aes_ctr_encryptor (const unsigned char* raw_key, const unsigned char* nonce)
: ecb(raw_key)
{
// Set first 12 bytes of the CTR value to the nonce.
// This stays the same for the entirety of this object's lifetime.
std::memcpy(ctr_value, nonce, NONCE_LEN);
byte_counter = 0;
}
Aes_ctr_encryptor::~Aes_ctr_encryptor ()
{
explicit_memset(pad, '\0', BLOCK_LEN);
}
void Aes_ctr_encryptor::process (const unsigned char* in, unsigned char* out, size_t len)
{
for (size_t i = 0; i < len; ++i) {
if (byte_counter % BLOCK_LEN == 0) {
// Set last 4 bytes of CTR to the (big-endian) block number (sequentially increasing with each block)
store_be32(ctr_value + NONCE_LEN, byte_counter / BLOCK_LEN);
// Generate a new pad
ecb.encrypt(ctr_value, pad);
}
// encrypt one byte
out[i] = in[i] ^ pad[byte_counter++ % BLOCK_LEN];
if (byte_counter == 0) {
throw Crypto_error("Aes_ctr_encryptor::process", "Too much data to encrypt securely");
}
}
}
// Encrypt/decrypt an entire input stream, writing to the given output stream
void Aes_ctr_encryptor::process_stream (std::istream& in, std::ostream& out, const unsigned char* key, const unsigned char* nonce)
{
Aes_ctr_encryptor aes(key, nonce);
unsigned char buffer[1024];
while (in) {
in.read(reinterpret_cast<char*>(buffer), sizeof(buffer));
aes.process(buffer, buffer, in.gcount());
out.write(reinterpret_cast<char*>(buffer), in.gcount());
}
}
================================================
FILE: crypto.hpp
================================================
/*
* Copyright 2012, 2014 Andrew Ayer
*
* This file is part of git-crypt.
*
* git-crypt is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* git-crypt is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with git-crypt. If not, see <http://www.gnu.org/licenses/>.
*
* Additional permission under GNU GPL version 3 section 7:
*
* If you modify the Program, or any covered work, by linking or
* combining it with the OpenSSL project's OpenSSL library (or a
* modified version of that library), containing parts covered by the
* terms of the OpenSSL or SSLeay licenses, the licensors of the Program
* grant you additional permission to convey the resulting work.
* Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of OpenSSL used as well
* as that of the covered work.
*/
#ifndef GIT_CRYPT_CRYPTO_HPP
#define GIT_CRYPT_CRYPTO_HPP
#include "key.hpp"
#include <stdint.h>
#include <stddef.h>
#include <iosfwd>
#include <string>
#include <memory>
void init_crypto ();
struct Crypto_error {
std::string where;
std::string message;
Crypto_error (const std::string& w, const std::string& m) : where(w), message(m) { }
};
class Aes_ecb_encryptor {
public:
enum {
KEY_LEN = AES_KEY_LEN,
BLOCK_LEN = 16
};
private:
struct Aes_impl;
std::unique_ptr<Aes_impl> impl;
public:
Aes_ecb_encryptor (const unsigned char* key);
~Aes_ecb_encryptor ();
void encrypt (const unsigned char* plain, unsigned char* cipher);
};
class Aes_ctr_encryptor {
public:
enum {
NONCE_LEN = 12,
KEY_LEN = AES_KEY_LEN,
BLOCK_LEN = 16,
MAX_CRYPT_BYTES = (1ULL<<32)*16 // Don't encrypt more than this or the CTR value will repeat itself
};
private:
Aes_ecb_encryptor ecb;
unsigned char ctr_value[BLOCK_LEN]; // Current CTR value (used as input to AES to derive pad)
unsigned char pad[BLOCK_LEN]; // Current encryption pad (output of AES)
uint32_t byte_counter; // How many bytes processed so far?
public:
Aes_ctr_encryptor (const unsigned char* key, const unsigned char* nonce);
~Aes_ctr_encryptor ();
void process (const unsigned char* in, unsigned char* out, size_t len);
// Encrypt/decrypt an entire input stream, writing to the given output stream
static void process_stream (std::istream& in, std::ostream& out, const unsigned char* key, const unsigned char* nonce);
};
typedef Aes_ctr_encryptor Aes_ctr_decryptor;
class Hmac_sha1_state {
public:
enum {
LEN = 20,
KEY_LEN = HMAC_KEY_LEN
};
private:
struct Hmac_impl;
std::unique_ptr<Hmac_impl> impl;
public:
Hmac_sha1_state (const unsigned char* key, size_t key_len);
~Hmac_sha1_state ();
void add (const unsigned char* buffer, size_t buffer_len);
void get (unsigned char*);
};
void random_bytes (unsigned char*, size_t);
#endif
================================================
FILE: doc/multiple_keys.md
================================================
In addition to the implicit default key, git-crypt supports alternative
keys which can be used to encrypt specific files and can be shared with
specific GPG users. This is useful if you want to grant different
collaborators access to different sets of files.
To generate an alternative key named KEYNAME, pass the `-k KEYNAME`
option to `git-crypt init` as follows:
git-crypt init -k KEYNAME
To encrypt a file with an alternative key, use the `git-crypt-KEYNAME`
filter in `.gitattributes` as follows:
secretfile filter=git-crypt-KEYNAME diff=git-crypt-KEYNAME
To export an alternative key or share it with a GPG user, pass the `-k
KEYNAME` option to `git-crypt export-key` or `git-crypt add-gpg-user`
as follows:
git-crypt export-key -k KEYNAME /path/to/keyfile
git-crypt add-gpg-user -k KEYNAME GPG_USER_ID
To unlock a repository with an alternative key, use `git-crypt unlock`
normally. git-crypt will automatically determine which key is being used.
================================================
FILE: fhstream.cpp
================================================
/*
* Copyright (C) 2012, 2015 Andrew Ayer
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Except as contained in this notice, the name(s) of the above copyright
* holders shall not be used in advertising or otherwise to promote the
* sale, use or other dealings in this Software without prior written
* authorization.
*/
#include <cstring>
#include <algorithm> // for std::min
#include "fhstream.hpp"
/*
* ofhstream
*/
ofhbuf::ofhbuf (void* arg_handle, size_t (*arg_write_fun)(void*, const void*, size_t))
: handle(arg_handle),
write_fun(arg_write_fun),
buffer(new char[default_buffer_size]),
buffer_size(default_buffer_size)
{
reset_buffer();
}
ofhbuf::~ofhbuf ()
{
if (handle) {
try {
sync();
} catch (...) {
// Ignore exception since we're in the destructor.
// To catch write errors, call sync() explicitly.
}
}
delete[] buffer;
}
ofhbuf::int_type ofhbuf::overflow (ofhbuf::int_type c)
{
const char* p = pbase();
std::streamsize bytes_to_write = pptr() - p;
if (!is_eof(c)) {
*pptr() = c;
++bytes_to_write;
}
while (bytes_to_write > 0) {
const size_t bytes_written = write_fun(handle, p, bytes_to_write);
bytes_to_write -= bytes_written;
p += bytes_written;
}
reset_buffer();
return traits_type::to_int_type(0);
}
int ofhbuf::sync ()
{
return !is_eof(overflow(traits_type::eof())) ? 0 : -1;
}
std::streamsize ofhbuf::xsputn (const char* s, std::streamsize n)
{
// Use heuristic to decide whether to write directly or just use buffer
// Write directly only if n >= MIN(4096, available buffer capacity)
// (this is similar to what basic_filebuf does)
if (n < std::min<std::streamsize>(4096, epptr() - pptr())) {
// Not worth it to do a direct write
return std::streambuf::xsputn(s, n);
}
// Before we can do a direct write of this string, we need to flush
// out the current contents of the buffer.
if (pbase() != pptr()) {
overflow(traits_type::eof()); // throws an exception or it succeeds
}
// Now we can go ahead and write out the string.
size_t bytes_to_write = n;
while (bytes_to_write > 0) {
const size_t bytes_written = write_fun(handle, s, bytes_to_write);
bytes_to_write -= bytes_written;
s += bytes_written;
}
return n; // Return the total bytes written
}
std::streambuf* ofhbuf::setbuf (char* s, std::streamsize n)
{
if (s == 0 && n == 0) {
// Switch to unbuffered
// This won't take effect until the next overflow or sync
// (We defer it taking effect so that write errors can be properly reported)
// To cause it to take effect as soon as possible, we artificially reduce the
// size of the buffer so it has no space left. This will trigger an overflow
// on the next put.
std::streambuf::setp(pbase(), pptr());
std::streambuf::pbump(pptr() - pbase());
buffer_size = 1;
}
return this;
}
/*
* ifhstream
*/
ifhbuf::ifhbuf (void* arg_handle, size_t (*arg_read_fun)(void*, void*, size_t))
: handle(arg_handle),
read_fun(arg_read_fun),
buffer(new char[default_buffer_size + putback_size]),
buffer_size(default_buffer_size)
{
reset_buffer(0, 0);
}
ifhbuf::~ifhbuf ()
{
delete[] buffer;
}
ifhbuf::int_type ifhbuf::underflow ()
{
if (gptr() >= egptr()) { // A true underflow (no bytes in buffer left to read)
// Move the putback_size most-recently-read characters into the putback area
size_t nputback = std::min<size_t>(gptr() - eback(), putback_size);
std::memmove(buffer + (putback_size - nputback), gptr() - nputback, nputback);
// Now read new characters from the file descriptor
const size_t nread = read_fun(handle, buffer + putback_size, buffer_size);
if (nread == 0) {
// EOF
return traits_type::eof();
}
// Reset the buffer
reset_buffer(nputback, nread);
}
// Return the next character
return traits_type::to_int_type(*gptr());
}
std::streamsize ifhbuf::xsgetn (char* s, std::streamsize n)
{
// Use heuristic to decide whether to read directly
// Read directly only if n >= bytes_available + 4096
std::streamsize bytes_available = egptr() - gptr();
if (n < bytes_available + 4096) {
// Not worth it to do a direct read
return std::streambuf::xsgetn(s, n);
}
std::streamsize total_bytes_read = 0;
// First, copy out the bytes currently in the buffer
std::memcpy(s, gptr(), bytes_available);
s += bytes_available;
n -= bytes_available;
total_bytes_read += bytes_available;
// Now do the direct read
while (n > 0) {
const size_t bytes_read = read_fun(handle, s, n);
if (bytes_read == 0) {
// EOF
break;
}
s += bytes_read;
n -= bytes_read;
total_bytes_read += bytes_read;
}
// Fill up the putback area with the most recently read characters
size_t nputback = std::min<size_t>(total_bytes_read, putback_size);
std::memcpy(buffer + (putback_size - nputback), s - nputback, nputback);
// Reset the buffer with no bytes available for reading, but with some putback characters
reset_buffer(nputback, 0);
// Return the total number of bytes read
return total_bytes_read;
}
std::streambuf* ifhbuf::setbuf (char* s, std::streamsize n)
{
if (s == 0 && n == 0) {
// Switch to unbuffered
// This won't take effect until the next underflow (we don't want to
// lose what's currently in the buffer!)
buffer_size = 1;
}
return this;
}
================================================
FILE: fhstream.hpp
================================================
/*
* Copyright (C) 2012, 2015 Andrew Ayer
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Except as contained in this notice, the name(s) of the above copyright
* holders shall not be used in advertising or otherwise to promote the
* sale, use or other dealings in this Software without prior written
* authorization.
*/
#ifndef GIT_CRYPT_FHSTREAM_HPP
#define GIT_CRYPT_FHSTREAM_HPP
#include <ostream>
#include <istream>
#include <streambuf>
/*
* ofhstream
*/
class ofhbuf : public std::streambuf {
enum { default_buffer_size = 8192 };
void* handle;
size_t (*write_fun)(void*, const void*, size_t);
char* buffer;
size_t buffer_size;
inline void reset_buffer ()
{
std::streambuf::setp(buffer, buffer + buffer_size - 1);
}
static inline bool is_eof (int_type ch) { return traits_type::eq_int_type(ch, traits_type::eof()); }
// Disallow copy
#if __cplusplus >= 201103L /* C++11 */
ofhbuf (const ofhbuf&) = delete;
ofhbuf& operator= (const ofhbuf&) = delete;
#else
ofhbuf (const ofhbuf&);
ofhbuf& operator= (const ofhbuf&);
#endif
protected:
virtual int_type overflow (int_type ch =traits_type::eof());
virtual int sync ();
virtual std::streamsize xsputn (const char*, std::streamsize);
virtual std::streambuf* setbuf (char*, std::streamsize);
public:
ofhbuf (void*, size_t (*)(void*, const void*, size_t));
~ofhbuf (); // WARNING: calls sync() and ignores exceptions
};
class ofhstream : public std::ostream {
mutable ofhbuf buf;
public:
ofhstream (void* handle, size_t (*write_fun)(void*, const void*, size_t))
: std::ostream(0), buf(handle, write_fun)
{
std::ostream::rdbuf(&buf);
}
ofhbuf* rdbuf () const { return &buf; }
};
/*
* ifhstream
*/
class ifhbuf : public std::streambuf {
enum {
default_buffer_size = 8192,
putback_size = 4
};
void* handle;
size_t (*read_fun)(void*, void*, size_t);
char* buffer;
size_t buffer_size;
inline void reset_buffer (size_t nputback, size_t nread)
{
std::streambuf::setg(buffer + (putback_size - nputback), buffer + putback_size, buffer + putback_size + nread);
}
// Disallow copy
#if __cplusplus >= 201103L /* C++11 */
ifhbuf (const ifhbuf&) = delete;
ifhbuf& operator= (const ifhbuf&) = delete;
#else
ifhbuf (const ifhbuf&);
ifhbuf& operator= (const ifhbuf&);
#endif
protected:
virtual int_type underflow ();
virtual std::streamsize xsgetn (char*, std::streamsize);
virtual std::streambuf* setbuf (char*, std::streamsize);
public:
ifhbuf (void*, size_t (*)(void*, void*, size_t));
~ifhbuf (); // Can't fail
};
class ifhstream : public std::istream {
mutable ifhbuf buf;
public:
explicit ifhstream (void* handle, size_t (*read_fun)(void*, void*, size_t))
: std::istream(0), buf(handle, read_fun)
{
std::istream::rdbuf(&buf);
}
ifhbuf* rdbuf () const { return &buf; }
};
#endif
================================================
FILE: git-crypt.cpp
================================================
/*
* Copyright 2012, 2014 Andrew Ayer
*
* This file is part of git-crypt.
*
* git-crypt is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* git-crypt is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with git-crypt. If not, see <http://www.gnu.org/licenses/>.
*
* Additional permission under GNU GPL version 3 section 7:
*
* If you modify the Program, or any covered work, by linking or
* combining it with the OpenSSL project's OpenSSL library (or a
* modified version of that library), containing parts covered by the
* terms of the OpenSSL or SSLeay licenses, the licensors of the Program
* grant you additional permission to convey the resulting work.
* Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of OpenSSL used as well
* as that of the covered work.
*/
#include "git-crypt.hpp"
#include "commands.hpp"
#include "util.hpp"
#include "crypto.hpp"
#include "key.hpp"
#include "gpg.hpp"
#include "parse_options.hpp"
#include <cstring>
#include <unistd.h>
#include <iostream>
#include <string.h>
const char* argv0;
static void print_usage (std::ostream& out)
{
out << "Usage: " << argv0 << " COMMAND [ARGS ...]" << std::endl;
out << std::endl;
// |--------------------------------------------------------------------------------| 80 characters
out << "Common commands:" << std::endl;
out << " init generate a key and prepare repo to use git-crypt" << std::endl;
out << " status display which files are encrypted" << std::endl;
//out << " refresh ensure all files in the repo are properly decrypted" << std::endl;
out << " lock de-configure git-crypt and re-encrypt files in work tree" << std::endl;
out << std::endl;
out << "GPG commands:" << std::endl;
out << " add-gpg-user USERID add the user with the given GPG user ID as a collaborator" << std::endl;
//out << " rm-gpg-user USERID revoke collaborator status from the given GPG user ID" << std::endl;
//out << " ls-gpg-users list the GPG key IDs of collaborators" << std::endl;
out << " unlock decrypt this repo using the in-repo GPG-encrypted key" << std::endl;
out << std::endl;
out << "Symmetric key commands:" << std::endl;
out << " export-key FILE export this repo's symmetric key to the given file" << std::endl;
out << " unlock KEYFILE decrypt this repo using the given symmetric key" << std::endl;
out << std::endl;
out << "Legacy commands:" << std::endl;
out << " init KEYFILE alias for 'unlock KEYFILE'" << std::endl;
out << " keygen KEYFILE generate a git-crypt key in the given file" << std::endl;
out << " migrate-key OLD NEW migrate the legacy key file OLD to the new format in NEW" << std::endl;
/*
out << std::endl;
out << "Plumbing commands (not to be used directly):" << std::endl;
out << " clean [LEGACY-KEYFILE]" << std::endl;
out << " smudge [LEGACY-KEYFILE]" << std::endl;
out << " diff [LEGACY-KEYFILE] FILE" << std::endl;
*/
out << std::endl;
out << "See 'git-crypt help COMMAND' for more information on a specific command." << std::endl;
}
static void print_version (std::ostream& out)
{
out << "git-crypt " << VERSION << std::endl;
}
static bool help_for_command (const char* command, std::ostream& out)
{
if (std::strcmp(command, "init") == 0) {
help_init(out);
} else if (std::strcmp(command, "unlock") == 0) {
help_unlock(out);
} else if (std::strcmp(command, "lock") == 0) {
help_lock(out);
} else if (std::strcmp(command, "add-gpg-user") == 0) {
help_add_gpg_user(out);
} else if (std::strcmp(command, "rm-gpg-user") == 0) {
help_rm_gpg_user(out);
} else if (std::strcmp(command, "ls-gpg-users") == 0) {
help_ls_gpg_users(out);
} else if (std::strcmp(command, "export-key") == 0) {
help_export_key(out);
} else if (std::strcmp(command, "keygen") == 0) {
help_keygen(out);
} else if (std::strcmp(command, "migrate-key") == 0) {
help_migrate_key(out);
} else if (std::strcmp(command, "refresh") == 0) {
help_refresh(out);
} else if (std::strcmp(command, "status") == 0) {
help_status(out);
} else {
return false;
}
return true;
}
static int help (int argc, const char** argv)
{
if (argc == 0) {
print_usage(std::cout);
} else {
if (!help_for_command(argv[0], std::cout)) {
std::clog << "Error: '" << argv[0] << "' is not a git-crypt command. See 'git-crypt help'." << std::endl;
return 1;
}
}
return 0;
}
static int version (int argc, const char** argv)
{
print_version(std::cout);
return 0;
}
int main (int argc, const char** argv)
try {
argv0 = argv[0];
/*
* General initialization
*/
init_std_streams();
init_crypto();
/*
* Parse command line arguments
*/
int arg_index = 1;
while (arg_index < argc && argv[arg_index][0] == '-') {
if (std::strcmp(argv[arg_index], "--help") == 0) {
print_usage(std::clog);
return 0;
} else if (std::strcmp(argv[arg_index], "--version") == 0) {
print_version(std::clog);
return 0;
} else if (std::strcmp(argv[arg_index], "--") == 0) {
++arg_index;
break;
} else {
std::clog << argv0 << ": " << argv[arg_index] << ": Unknown option" << std::endl;
print_usage(std::clog);
return 2;
}
}
argc -= arg_index;
argv += arg_index;
if (argc == 0) {
print_usage(std::clog);
return 2;
}
/*
* Pass off to command handler
*/
const char* command = argv[0];
--argc;
++argv;
try {
// Public commands:
if (std::strcmp(command, "help") == 0) {
return help(argc, argv);
}
if (std::strcmp(command, "version") == 0) {
return version(argc, argv);
}
if (std::strcmp(command, "init") == 0) {
return init(argc, argv);
}
if (std::strcmp(command, "unlock") == 0) {
return unlock(argc, argv);
}
if (std::strcmp(command, "lock") == 0) {
return lock(argc, argv);
}
if (std::strcmp(command, "add-gpg-user") == 0) {
return add_gpg_user(argc, argv);
}
if (std::strcmp(command, "rm-gpg-user") == 0) {
return rm_gpg_user(argc, argv);
}
if (std::strcmp(command, "ls-gpg-users") == 0) {
return ls_gpg_users(argc, argv);
}
if (std::strcmp(command, "export-key") == 0) {
return export_key(argc, argv);
}
if (std::strcmp(command, "keygen") == 0) {
return keygen(argc, argv);
}
if (std::strcmp(command, "migrate-key") == 0) {
return migrate_key(argc, argv);
}
if (std::strcmp(command, "refresh") == 0) {
return refresh(argc, argv);
}
if (std::strcmp(command, "status") == 0) {
return status(argc, argv);
}
// Plumbing commands (executed by git, not by user):
if (std::strcmp(command, "clean") == 0) {
return clean(argc, argv);
}
if (std::strcmp(command, "smudge") == 0) {
return smudge(argc, argv);
}
if (std::strcmp(command, "diff") == 0) {
return diff(argc, argv);
}
} catch (const Option_error& e) {
std::clog << "git-crypt: Error: " << e.option_name << ": " << e.message << std::endl;
help_for_command(command, std::clog);
return 2;
}
std::clog << "Error: '" << command << "' is not a git-crypt command. See 'git-crypt help'." << std::endl;
return 2;
} catch (const Error& e) {
std::cerr << "git-crypt: Error: " << e.message << std::endl;
return 1;
} catch (const Gpg_error& e) {
std::cerr << "git-crypt: GPG error: " << e.message << std::endl;
return 1;
} catch (const System_error& e) {
std::cerr << "git-crypt: System error: " << e.message() << std::endl;
return 1;
} catch (const Crypto_error& e) {
std::cerr << "git-crypt: Crypto error: " << e.where << ": " << e.message << std::endl;
return 1;
} catch (Key_file::Incompatible) {
std::cerr << "git-crypt: This repository contains a incompatible key file. Please upgrade git-crypt." << std::endl;
return 1;
} catch (Key_file::Malformed) {
std::cerr << "git-crypt: This repository contains a malformed key file. It may be corrupted." << std::endl;
return 1;
} catch (const std::ios_base::failure& e) {
std::cerr << "git-crypt: I/O error: " << e.what() << std::endl;
return 1;
}
================================================
FILE: git-crypt.hpp
================================================
/*
* Copyright 2014 Andrew Ayer
*
* This file is part of git-crypt.
*
* git-crypt is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* git-crypt is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with git-crypt. If not, see <http://www.gnu.org/licenses/>.
*
* Additional permission under GNU GPL version 3 section 7:
*
* If you modify the Program, or any covered work, by linking or
* combining it with the OpenSSL project's OpenSSL library (or a
* modified version of that library), containing parts covered by the
* terms of the OpenSSL or SSLeay licenses, the licensors of the Program
* grant you additional permission to convey the resulting work.
* Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of OpenSSL used as well
* as that of the covered work.
*/
#ifndef GIT_CRYPT_GIT_CRYPT_HPP
#define GIT_CRYPT_GIT_CRYPT_HPP
#define VERSION "0.8.0"
extern const char* argv0; // initialized in main() to argv[0]
#endif
================================================
FILE: gpg.cpp
================================================
/*
* Copyright 2014 Andrew Ayer
*
* This file is part of git-crypt.
*
* git-crypt is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* git-crypt is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with git-crypt. If not, see <http://www.gnu.org/licenses/>.
*
* Additional permission under GNU GPL version 3 section 7:
*
* If you modify the Program, or any covered work, by linking or
* combining it with the OpenSSL project's OpenSSL library (or a
* modified version of that library), containing parts covered by the
* terms of the OpenSSL or SSLeay licenses, the licensors of the Program
* grant you additional permission to convey the resulting work.
* Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of OpenSSL used as well
* as that of the covered work.
*/
#include "gpg.hpp"
#include "util.hpp"
#include "commands.hpp"
#include <sstream>
static std::string gpg_get_executable()
{
std::string gpgbin = "gpg";
try {
gpgbin = get_git_config("gpg.program");
} catch (...) {
}
return gpgbin;
}
static std::string gpg_nth_column (const std::string& line, unsigned int col)
{
std::string::size_type pos = 0;
for (unsigned int i = 0; i < col; ++i) {
pos = line.find_first_of(':', pos);
if (pos == std::string::npos) {
throw Gpg_error("Malformed output from gpg");
}
pos = pos + 1;
}
const std::string::size_type end_pos = line.find_first_of(':', pos);
return end_pos != std::string::npos ?
line.substr(pos, end_pos - pos) :
line.substr(pos);
}
// given a key fingerprint, return the key's UID (e.g. "John Smith <jsmith@example.com>")
std::string gpg_get_uid (const std::string& fingerprint)
{
// gpg --batch --with-colons --fixed-list-mode --list-keys 0x7A399B2DB06D039020CD1CE1D0F3702D61489532
std::vector<std::string> command;
command.push_back(gpg_get_executable());
command.push_back("--batch");
command.push_back("--with-colons");
command.push_back("--fixed-list-mode");
command.push_back("--list-keys");
command.push_back("0x" + fingerprint);
std::stringstream command_output;
if (!successful_exit(exec_command(command, command_output))) {
// This could happen if the keyring does not contain a public key with this fingerprint
return "";
}
while (command_output.peek() != -1) {
std::string line;
std::getline(command_output, line);
if (line.substr(0, 4) == "uid:") {
// uid:u::::1395975462::AB97D6E3E5D8789988CA55E5F77D9E7397D05229::John Smith <jsmith@example.com>:
// want the 9th column (counting from 0)
return gpg_nth_column(line, 9);
}
}
return "";
}
// return a list of fingerprints of public keys matching the given search query (such as jsmith@example.com)
std::vector<std::string> gpg_lookup_key (const std::string& query)
{
std::vector<std::string> fingerprints;
// gpg --batch --with-colons --fingerprint --list-keys jsmith@example.com
std::vector<std::string> command;
command.push_back(gpg_get_executable());
command.push_back("--batch");
command.push_back("--with-colons");
command.push_back("--fingerprint");
command.push_back("--list-keys");
command.push_back(query);
std::stringstream command_output;
if (successful_exit(exec_command(command, command_output))) {
bool is_pubkey = false;
while (command_output.peek() != -1) {
std::string line;
std::getline(command_output, line);
if (line.substr(0, 4) == "pub:") {
is_pubkey = true;
} else if (line.substr(0, 4) == "sub:") {
is_pubkey = false;
} else if (is_pubkey && line.substr(0, 4) == "fpr:") {
// fpr:::::::::7A399B2DB06D039020CD1CE1D0F3702D61489532:
// want the 9th column (counting from 0)
fingerprints.push_back(gpg_nth_column(line, 9));
}
}
}
return fingerprints;
}
std::vector<std::string> gpg_list_secret_keys ()
{
// gpg --batch --with-colons --list-secret-keys --fingerprint
std::vector<std::string> command;
command.push_back(gpg_get_executable());
command.push_back("--batch");
command.push_back("--with-colons");
command.push_back("--list-secret-keys");
command.push_back("--fingerprint");
std::stringstream command_output;
if (!successful_exit(exec_command(command, command_output))) {
throw Gpg_error("gpg --list-secret-keys failed");
}
std::vector<std::string> secret_keys;
while (command_output.peek() != -1) {
std::string line;
std::getline(command_output, line);
if (line.substr(0, 4) == "fpr:") {
// fpr:::::::::7A399B2DB06D039020CD1CE1D0F3702D61489532:
// want the 9th column (counting from 0)
secret_keys.push_back(gpg_nth_column(line, 9));
}
}
return secret_keys;
}
void gpg_encrypt_to_file (const std::string& filename, const std::string& recipient_fingerprint, bool key_is_trusted, const char* p, size_t len)
{
// gpg --batch -o FILENAME -r RECIPIENT -e
std::vector<std::string> command;
command.push_back(gpg_get_executable());
command.push_back("--batch");
if (key_is_trusted) {
command.push_back("--trust-model");
command.push_back("always");
}
command.push_back("-o");
command.push_back(filename);
command.push_back("-r");
command.push_back("0x" + recipient_fingerprint);
command.push_back("-e");
if (!successful_exit(exec_command_with_input(command, p, len))) {
throw Gpg_error("Failed to encrypt");
}
}
void gpg_decrypt_from_file (const std::string& filename, std::ostream& output)
{
// gpg -q -d FILENAME
std::vector<std::string> command;
command.push_back(gpg_get_executable());
command.push_back("-q");
command.push_back("-d");
command.push_back(filename);
if (!successful_exit(exec_command(command, output))) {
throw Gpg_error("Failed to decrypt");
}
}
================================================
FILE: gpg.hpp
================================================
/*
* Copyright 2014 Andrew Ayer
*
* This file is part of git-crypt.
*
* git-crypt is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* git-crypt is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with git-crypt. If not, see <http://www.gnu.org/licenses/>.
*
* Additional permission under GNU GPL version 3 section 7:
*
* If you modify the Program, or any covered work, by linking or
* combining it with the OpenSSL project's OpenSSL library (or a
* modified version of that library), containing parts covered by the
* terms of the OpenSSL or SSLeay licenses, the licensors of the Program
* grant you additional permission to convey the resulting work.
* Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of OpenSSL used as well
* as that of the covered work.
*/
#ifndef GIT_CRYPT_GPG_HPP
#define GIT_CRYPT_GPG_HPP
#include <string>
#include <vector>
#include <cstddef>
struct Gpg_error {
std::string message;
explicit Gpg_error (std::string m) : message(m) { }
};
std::string gpg_get_uid (const std::string& fingerprint);
std::vector<std::string> gpg_lookup_key (const std::string& query);
std::vector<std::string> gpg_list_secret_keys ();
void gpg_encrypt_to_file (const std::string& filename, const std::string& recipient_fingerprint, bool key_is_trusted, const char* p, size_t len);
void gpg_decrypt_from_file (const std::string& filename, std::ostream&);
#endif
================================================
FILE: key.cpp
================================================
/*
* Copyright 2014 Andrew Ayer
*
* This file is part of git-crypt.
*
* git-crypt is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* git-crypt is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with git-crypt. If not, see <http://www.gnu.org/licenses/>.
*
* Additional permission under GNU GPL version 3 section 7:
*
* If you modify the Program, or any covered work, by linking or
* combining it with the OpenSSL project's OpenSSL library (or a
* modified version of that library), containing parts covered by the
* terms of the OpenSSL or SSLeay licenses, the licensors of the Program
* grant you additional permission to convey the resulting work.
* Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of OpenSSL used as well
* as that of the covered work.
*/
#include "key.hpp"
#include "util.hpp"
#include "crypto.hpp"
#include <sys/types.h>
#include <sys/stat.h>
#include <stdint.h>
#include <fstream>
#include <istream>
#include <ostream>
#include <sstream>
#include <cstring>
#include <stdexcept>
#include <vector>
Key_file::Entry::Entry ()
{
version = 0;
explicit_memset(aes_key, 0, AES_KEY_LEN);
explicit_memset(hmac_key, 0, HMAC_KEY_LEN);
}
void Key_file::Entry::load (std::istream& in)
{
while (true) {
uint32_t field_id;
if (!read_be32(in, field_id)) {
throw Malformed();
}
if (field_id == KEY_FIELD_END) {
break;
}
uint32_t field_len;
if (!read_be32(in, field_len)) {
throw Malformed();
}
if (field_id == KEY_FIELD_VERSION) {
if (field_len != 4) {
throw Malformed();
}
if (!read_be32(in, version)) {
throw Malformed();
}
} else if (field_id == KEY_FIELD_AES_KEY) {
if (field_len != AES_KEY_LEN) {
throw Malformed();
}
in.read(reinterpret_cast<char*>(aes_key), AES_KEY_LEN);
if (in.gcount() != AES_KEY_LEN) {
throw Malformed();
}
} else if (field_id == KEY_FIELD_HMAC_KEY) {
if (field_len != HMAC_KEY_LEN) {
throw Malformed();
}
in.read(reinterpret_cast<char*>(hmac_key), HMAC_KEY_LEN);
if (in.gcount() != HMAC_KEY_LEN) {
throw Malformed();
}
} else if (field_id & 1) { // unknown critical field
throw Incompatible();
} else {
// unknown non-critical field - safe to ignore
if (field_len > MAX_FIELD_LEN) {
throw Malformed();
}
in.ignore(field_len);
if (in.gcount() != static_cast<std::streamsize>(field_len)) {
throw Malformed();
}
}
}
}
void Key_file::Entry::load_legacy (uint32_t arg_version, std::istream& in)
{
version = arg_version;
// First comes the AES key
in.read(reinterpret_cast<char*>(aes_key), AES_KEY_LEN);
if (in.gcount() != AES_KEY_LEN) {
throw Malformed();
}
// Then the HMAC key
in.read(reinterpret_cast<char*>(hmac_key), HMAC_KEY_LEN);
if (in.gcount() != HMAC_KEY_LEN) {
throw Malformed();
}
if (in.peek() != -1) {
// Trailing data is a good indication that we are not actually reading a
// legacy key file. (This is important to check since legacy key files
// did not have any sort of file header.)
throw Malformed();
}
}
void Key_file::Entry::store (std::ostream& out) const
{
// Version
write_be32(out, KEY_FIELD_VERSION);
write_be32(out, 4);
write_be32(out, version);
// AES key
write_be32(out, KEY_FIELD_AES_KEY);
write_be32(out, AES_KEY_LEN);
out.write(reinterpret_cast<const char*>(aes_key), AES_KEY_LEN);
// HMAC key
write_be32(out, KEY_FIELD_HMAC_KEY);
write_be32(out, HMAC_KEY_LEN);
out.write(reinterpret_cast<const char*>(hmac_key), HMAC_KEY_LEN);
// End
write_be32(out, KEY_FIELD_END);
}
void Key_file::Entry::generate (uint32_t arg_version)
{
version = arg_version;
random_bytes(aes_key, AES_KEY_LEN);
random_bytes(hmac_key, HMAC_KEY_LEN);
}
const Key_file::Entry* Key_file::get_latest () const
{
return is_filled() ? get(latest()) : 0;
}
const Key_file::Entry* Key_file::get (uint32_t version) const
{
Map::const_iterator it(entries.find(version));
return it != entries.end() ? &it->second : 0;
}
void Key_file::add (const Entry& entry)
{
entries[entry.version] = entry;
}
void Key_file::load_legacy (std::istream& in)
{
entries[0].load_legacy(0, in);
}
void Key_file::load (std::istream& in)
{
unsigned char preamble[16];
in.read(reinterpret_cast<char*>(preamble), 16);
if (in.gcount() != 16) {
throw Malformed();
}
if (std::memcmp(preamble, "\0GITCRYPTKEY", 12) != 0) {
throw Malformed();
}
if (load_be32(preamble + 12) != FORMAT_VERSION) {
throw Incompatible();
}
load_header(in);
while (in.peek() != -1) {
Entry entry;
entry.load(in);
add(entry);
}
}
void Key_file::load_header (std::istream& in)
{
while (true) {
uint32_t field_id;
if (!read_be32(in, field_id)) {
throw Malformed();
}
if (field_id == HEADER_FIELD_END) {
break;
}
uint32_t field_len;
if (!read_be32(in, field_len)) {
throw Malformed();
}
if (field_id == HEADER_FIELD_KEY_NAME) {
if (field_len > KEY_NAME_MAX_LEN) {
throw Malformed();
}
if (field_len == 0) {
// special case field_len==0 to avoid possible undefined behavior
// edge cases with an empty std::vector (particularly, &bytes[0]).
key_name.clear();
} else {
std::vector<char> bytes(field_len);
in.read(&bytes[0], field_len);
if (in.gcount() != static_cast<std::streamsize>(field_len)) {
throw Malformed();
}
key_name.assign(&bytes[0], field_len);
}
if (!validate_key_name(key_name.c_str())) {
key_name.clear();
throw Malformed();
}
} else if (field_id & 1) { // unknown critical field
throw Incompatible();
} else {
// unknown non-critical field - safe to ignore
if (field_len > MAX_FIELD_LEN) {
throw Malformed();
}
in.ignore(field_len);
if (in.gcount() != static_cast<std::streamsize>(field_len)) {
throw Malformed();
}
}
}
}
void Key_file::store (std::ostream& out) const
{
out.write("\0GITCRYPTKEY", 12);
write_be32(out, FORMAT_VERSION);
if (!key_name.empty()) {
write_be32(out, HEADER_FIELD_KEY_NAME);
write_be32(out, key_name.size());
out.write(key_name.data(), key_name.size());
}
write_be32(out, HEADER_FIELD_END);
for (Map::const_iterator it(entries.begin()); it != entries.end(); ++it) {
it->second.store(out);
}
}
bool Key_file::load_from_file (const char* key_file_name)
{
std::ifstream key_file_in(key_file_name, std::fstream::binary);
if (!key_file_in) {
return false;
}
load(key_file_in);
return true;
}
bool Key_file::store_to_file (const char* key_file_name) const
{
create_protected_file(key_file_name);
std::ofstream key_file_out(key_file_name, std::fstream::binary);
if (!key_file_out) {
return false;
}
store(key_file_out);
key_file_out.close();
if (!key_file_out) {
return false;
}
return true;
}
std::string Key_file::store_to_string () const
{
std::ostringstream ss;
store(ss);
return ss.str();
}
void Key_file::generate ()
{
uint32_t version(is_empty() ? 0 : latest() + 1);
entries[version].generate(version);
}
uint32_t Key_file::latest () const
{
if (is_empty()) {
throw std::invalid_argument("Key_file::latest");
}
return entries.begin()->first;
}
bool validate_key_name (const char* key_name, std::string* reason)
{
if (!*key_name) {
if (reason) { *reason = "Key name may not be empty"; }
return false;
}
if (std::strcmp(key_name, "default") == 0) {
if (reason) { *reason = "`default' is not a legal key name"; }
return false;
}
// Need to be restrictive with key names because they're used as part of a Git filter name
size_t len = 0;
while (char c = *key_name++) {
if (!std::isalnum(c) && c != '-' && c != '_') {
if (reason) { *reason = "Key names may contain only A-Z, a-z, 0-9, '-', and '_'"; }
return false;
}
if (++len > KEY_NAME_MAX_LEN) {
if (reason) { *reason = "Key name is too long"; }
return false;
}
}
return true;
}
================================================
FILE: key.hpp
================================================
/*
* Copyright 2014 Andrew Ayer
*
* This file is part of git-crypt.
*
* git-crypt is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* git-crypt is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with git-crypt. If not, see <http://www.gnu.org/licenses/>.
*
* Additional permission under GNU GPL version 3 section 7:
*
* If you modify the Program, or any covered work, by linking or
* combining it with the OpenSSL project's OpenSSL library (or a
* modified version of that library), containing parts covered by the
* terms of the OpenSSL or SSLeay licenses, the licensors of the Program
* grant you additional permission to convey the resulting work.
* Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of OpenSSL used as well
* as that of the covered work.
*/
#ifndef GIT_CRYPT_KEY_HPP
#define GIT_CRYPT_KEY_HPP
#include <map>
#include <functional>
#include <stdint.h>
#include <iosfwd>
#include <string>
enum {
HMAC_KEY_LEN = 64,
AES_KEY_LEN = 32
};
struct Key_file {
public:
struct Entry {
uint32_t version;
unsigned char aes_key[AES_KEY_LEN];
unsigned char hmac_key[HMAC_KEY_LEN];
Entry ();
void load (std::istream&);
void load_legacy (uint32_t version, std::istream&);
void store (std::ostream&) const;
void generate (uint32_t version);
};
struct Malformed { }; // exception class
struct Incompatible { }; // exception class
const Entry* get_latest () const;
const Entry* get (uint32_t version) const;
void add (const Entry&);
void load_legacy (std::istream&);
void load (std::istream&);
void store (std::ostream&) const;
bool load_from_file (const char* filename);
bool store_to_file (const char* filename) const;
std::string store_to_string () const;
void generate ();
bool is_empty () const { return entries.empty(); }
bool is_filled () const { return !is_empty(); }
uint32_t latest () const;
void set_key_name (const char* k) { key_name = k ? k : ""; }
const char* get_key_name () const { return key_name.empty() ? 0 : key_name.c_str(); }
private:
typedef std::map<uint32_t, Entry, std::greater<uint32_t> > Map;
enum { FORMAT_VERSION = 2 };
Map entries;
std::string key_name;
void load_header (std::istream&);
enum {
HEADER_FIELD_END = 0,
HEADER_FIELD_KEY_NAME = 1
};
enum {
KEY_FIELD_END = 0,
KEY_FIELD_VERSION = 1,
KEY_FIELD_AES_KEY = 3,
KEY_FIELD_HMAC_KEY = 5
};
enum {
MAX_FIELD_LEN = 1<<20
};
};
enum {
KEY_NAME_MAX_LEN = 128
};
bool validate_key_name (const char* key_name, std::string* reason =0);
#endif
================================================
FILE: man/git-crypt.xml
================================================
<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd">
<refentry>
<!--
Copyright (c) 2015 Andrew Ayer
See COPYING file for license information.
-->
<refentryinfo>
<title>git-crypt</title>
<date>2022-04-21</date>
<productname>git-crypt 0.8.0</productname>
<author>
<othername>Andrew Ayer</othername>
<contrib></contrib>
<email>agwa@andrewayer.name</email>
<uri>https://www.agwa.name</uri>
</author>
</refentryinfo>
<refmeta>
<refentrytitle>git-crypt</refentrytitle>
<manvolnum>1</manvolnum>
</refmeta>
<refnamediv>
<refname>git-crypt</refname>
<refpurpose>transparent file encryption in Git</refpurpose>
</refnamediv>
<refsynopsisdiv>
<cmdsynopsis>
<command>git-crypt <arg choice="opt"><replaceable>OPTIONS</replaceable></arg> <arg choice="plain"><replaceable>COMMAND</replaceable></arg> <arg choice="opt" rep="repeat"><replaceable>ARGS</replaceable></arg></command>
</cmdsynopsis>
</refsynopsisdiv>
<refsynopsisdiv>
<title>Common commands</title>
<cmdsynopsis>
<command>git-crypt init</command>
</cmdsynopsis>
<cmdsynopsis>
<command>git-crypt status</command>
</cmdsynopsis>
<cmdsynopsis>
<command>git-crypt lock</command>
</cmdsynopsis>
</refsynopsisdiv>
<refsynopsisdiv>
<title>GPG commands</title>
<cmdsynopsis>
<command>git-crypt add-gpg-user <arg choice="plain"><replaceable>GPG_USER_ID</replaceable></arg></command>
</cmdsynopsis>
<cmdsynopsis>
<command>git-crypt unlock</command>
</cmdsynopsis>
</refsynopsisdiv>
<refsynopsisdiv>
<title>Symmetric key commands</title>
<cmdsynopsis>
<command>git-crypt export-key <arg choice="plain"><replaceable>OUTPUT_KEY_FILE</replaceable></arg></command>
</cmdsynopsis>
<cmdsynopsis>
<command>git-crypt unlock <arg choice="plain"><replaceable>KEY_FILE</replaceable></arg></command>
</cmdsynopsis>
</refsynopsisdiv>
<refsect1>
<title>Description</title>
<para>
<command>git-crypt</command> enables transparent encryption and decryption
of files in a git repository. Files which you choose to protect are encrypted when committed,
and decrypted when checked out. git-crypt lets you freely share a repository containing a mix of
public and private content. git-crypt gracefully degrades, so developers without the secret key
can still clone and commit to a repository with encrypted files. This lets you store your secret
material (such as keys or passwords) in the same repository as your code, without requiring you
to lock down your entire repository.
</para>
</refsect1>
<refsect1>
<title>Commands</title>
<para>
<command>git-crypt</command> is logically divided into several sub-commands which
perform distinct tasks. Each sub-command, and its arguments,
are documented below. Note that arguments and options to sub-commands must be
specified on the command line <emphasis>after</emphasis> the name of the sub-command.
</para>
<variablelist>
<varlistentry>
<term><option>init <arg choice="opt"><replaceable>OPTIONS</replaceable></arg></option></term>
<listitem>
<para>
Generate a key and prepare the current Git repository to use git-crypt.
</para>
<para>
The following options are understood:
</para>
<variablelist>
<varlistentry>
<term><option>-k</option> <replaceable>KEY_NAME</replaceable></term>
<term><option>--key-name</option> <replaceable>KEY_NAME</replaceable></term>
<listitem>
<para>
Initialize the given key instead of the default key. git-crypt
supports multiple keys per repository, allowing you to share
different files with different sets of collaborators.
</para>
</listitem>
</varlistentry>
</variablelist>
</listitem>
</varlistentry>
<varlistentry>
<term><option>status <arg choice="opt"><replaceable>OPTIONS</replaceable></arg></option></term>
<listitem>
<para>
Display a list of files in the repository, with their status (encrypted or unencrypted).
</para>
<para>
The following options are understood:
</para>
<variablelist>
<varlistentry>
<term><option>-e</option></term>
<listitem>
<para>
Show only encrypted files.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-u</option></term>
<listitem>
<para>
Show only unencrypted files.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-f</option></term>
<term><option>--fix</option></term>
<listitem>
<para>
Encrypt files that should be encrypted but were
committed to the repository or added to the index
without encryption. (This can happen if a file
is added before git-crypt is initialized or before
the file is added to the gitattributes file.)
</para>
</listitem>
</varlistentry>
</variablelist>
</listitem>
</varlistentry>
<varlistentry>
<term><option>add-gpg-user <arg choice="opt"><replaceable>OPTIONS</replaceable></arg> <arg choice="plain" rep="repea
gitextract_kn52odl0/ ├── .gitattributes ├── .github/ │ └── workflows/ │ ├── release-linux-arm64.yml │ ├── release-linux.yml │ └── release-windows.yml ├── .gitignore ├── AUTHORS ├── CONTRIBUTING.md ├── COPYING ├── INSTALL ├── INSTALL.md ├── Makefile ├── NEWS.md ├── 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-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 │ └── man1/ │ └── .gitignore ├── parse_options.cpp ├── parse_options.hpp ├── util-unix.cpp ├── util-win32.cpp ├── util.cpp └── util.hpp
SYMBOL INDEX (158 symbols across 20 files)
FILE: commands.cpp
function attribute_name (line 60) | static std::string attribute_name (const char* key_name)
function git_version_string (line 71) | static std::string git_version_string ()
function parse_version (line 88) | static std::vector<int> parse_version (const std::string& str)
function make_version (line 105) | static std::vector<int> make_version (int a, int b, int c)
function git_config (line 114) | static void git_config (const std::string& name, const std::string& value)
function git_has_config (line 127) | static bool git_has_config (const std::string& name)
function git_deconfig (line 143) | static void git_deconfig (const std::string& name)
function configure_git_filters (line 156) | static void configure_git_filters (const char* key_name)
function deconfigure_git_filters (line 177) | static void deconfigure_git_filters (const char* key_name)
function git_checkout_batch (line 192) | static bool git_checkout_batch (std::vector<std::string>::const_iterator...
function git_checkout (line 215) | static bool git_checkout (const std::vector<std::string>& paths)
function same_key_name (line 227) | static bool same_key_name (const char* a, const char* b)
function validate_key_name_or_throw (line 232) | static void validate_key_name_or_throw (const char* key_name)
function get_internal_state_path (line 240) | static std::string get_internal_state_path ()
function get_internal_keys_path (line 261) | static std::string get_internal_keys_path (const std::string& internal_s...
function get_internal_keys_path (line 266) | static std::string get_internal_keys_path ()
function get_internal_key_path (line 271) | static std::string get_internal_key_path (const char* key_name)
function get_git_config (line 280) | std::string get_git_config (const std::string& name)
function get_repo_state_path (line 301) | static std::string get_repo_state_path ()
function get_repo_keys_path (line 338) | static std::string get_repo_keys_path (const std::string& repo_state_path)
function get_repo_keys_path (line 343) | static std::string get_repo_keys_path ()
function get_path_to_top (line 348) | static std::string get_path_to_top ()
function get_git_status (line 368) | static void get_git_status (std::ostream& output)
function get_file_attributes (line 383) | static std::pair<std::string, std::string> get_file_attributes (const st...
function get_file_attributes (line 435) | static std::pair<std::string, std::string> get_file_attributes (const st...
function check_if_blob_is_encrypted (line 464) | static bool check_if_blob_is_encrypted (const std::string& object_id)
function check_if_file_is_encrypted (line 485) | static bool check_if_file_is_encrypted (const std::string& filename)
function is_git_file_mode (line 511) | static bool is_git_file_mode (const std::string& mode)
function get_encrypted_files (line 516) | static void get_encrypted_files (std::vector<std::string>& files, const ...
function load_key (line 589) | static void load_key (Key_file& key_file, const char* key_name, const ch...
function decrypt_repo_key (line 613) | static bool decrypt_repo_key (Key_file& key_file, const char* key_name, ...
function decrypt_repo_keys (line 651) | static bool decrypt_repo_keys (std::vector<Key_file>& key_files, uint32_...
function encrypt_repo_key (line 678) | static void encrypt_repo_key (const char* key_name, const Key_file::Entr...
function parse_plumbing_options (line 705) | static int parse_plumbing_options (const char** key_name, const char** k...
function clean (line 716) | int clean (int argc, const char** argv)
function decrypt_file_to_stdout (line 835) | static int decrypt_file_to_stdout (const Key_file& key_file, const unsig...
function smudge (line 870) | int smudge (int argc, const char** argv)
function diff (line 906) | int diff (int argc, const char** argv)
function help_init (line 948) | void help_init (std::ostream& out)
function init (line 957) | int init (int argc, const char** argv)
function help_unlock (line 1008) | void help_unlock (std::ostream& out)
function unlock (line 1014) | int unlock (int argc, const char** argv)
function help_lock (line 1108) | void help_lock (std::ostream& out)
function lock (line 1118) | int lock (int argc, const char** argv)
function help_add_gpg_user (line 1203) | void help_add_gpg_user (std::ostream& out)
function add_gpg_user (line 1213) | int add_gpg_user (int argc, const char** argv)
function help_rm_gpg_user (line 1323) | void help_rm_gpg_user (std::ostream& out)
function rm_gpg_user (line 1332) | int rm_gpg_user (int argc, const char** argv) // TODO
function help_ls_gpg_users (line 1338) | void help_ls_gpg_users (std::ostream& out)
function ls_gpg_users (line 1343) | int ls_gpg_users (int argc, const char** argv) // TODO
function help_export_key (line 1363) | void help_export_key (std::ostream& out)
function export_key (line 1372) | int export_key (int argc, const char** argv)
function help_keygen (line 1405) | void help_keygen (std::ostream& out)
function keygen (line 1412) | int keygen (int argc, const char** argv)
function help_migrate_key (line 1442) | void help_migrate_key (std::ostream& out)
function migrate_key (line 1449) | int migrate_key (int argc, const char** argv)
function help_refresh (line 1489) | void help_refresh (std::ostream& out)
function refresh (line 1494) | int refresh (int argc, const char** argv) // TODO: do a force checkout, ...
function help_status (line 1500) | void help_status (std::ostream& out)
function status (line 1514) | int status (int argc, const char** argv)
FILE: commands.hpp
type Error (line 37) | struct Error {
method Error (line 40) | explicit Error (std::string m) : message(m) { }
FILE: coprocess-unix.cpp
function execvp (line 37) | static int execvp (const std::string& file, const std::vector<std::strin...
FILE: coprocess-unix.hpp
class Coprocess (line 38) | class Coprocess {
FILE: coprocess-win32.cpp
function escape_cmdline_argument (line 35) | static void escape_cmdline_argument (std::string& cmdline, const std::st...
function format_cmdline (line 71) | static std::string format_cmdline (const std::vector<std::string>& command)
function HANDLE (line 83) | static HANDLE spawn_command (const std::vector<std::string>& command, HA...
FILE: coprocess-win32.hpp
class Coprocess (line 38) | class Coprocess {
FILE: crypto-openssl-11.cpp
function init_crypto (line 43) | void init_crypto ()
type Aes_ecb_encryptor::Aes_impl (line 48) | struct Aes_ecb_encryptor::Aes_impl {
type Hmac_sha1_state::Hmac_impl (line 73) | struct Hmac_sha1_state::Hmac_impl {
function random_bytes (line 102) | void random_bytes (unsigned char* buffer, size_t len)
FILE: crypto.hpp
type Crypto_error (line 43) | struct Crypto_error {
method Crypto_error (line 47) | Crypto_error (const std::string& w, const std::string& m) : where(w), ...
class Aes_ecb_encryptor (line 50) | class Aes_ecb_encryptor {
type Aes_impl (line 58) | struct Aes_impl
class Aes_ctr_encryptor (line 68) | class Aes_ctr_encryptor {
class Hmac_sha1_state (line 95) | class Hmac_sha1_state {
type Hmac_impl (line 103) | struct Hmac_impl
FILE: fhstream.hpp
class ofhbuf (line 38) | class ofhbuf : public std::streambuf {
method reset_buffer (line 46) | inline void reset_buffer ()
method is_eof (line 50) | static inline bool is_eof (int_type ch) { return traits_type::eq_int_t...
method ofhbuf (line 54) | ofhbuf (const ofhbuf&) = delete;
method ofhbuf (line 55) | ofhbuf& operator= (const ofhbuf&) = delete;
class ofhstream (line 72) | class ofhstream : public std::ostream {
method ofhstream (line 75) | ofhstream (void* handle, size_t (*write_fun)(void*, const void*, size_t))
method ofhbuf (line 81) | ofhbuf* rdbuf () const { return &buf; }
class ifhbuf (line 88) | class ifhbuf : public std::streambuf {
method reset_buffer (line 99) | inline void reset_buffer (size_t nputback, size_t nread)
method ifhbuf (line 105) | ifhbuf (const ifhbuf&) = delete;
method ifhbuf (line 106) | ifhbuf& operator= (const ifhbuf&) = delete;
class ifhstream (line 122) | class ifhstream : public std::istream {
method ifhstream (line 125) | explicit ifhstream (void* handle, size_t (*read_fun)(void*, void*, siz...
method ifhbuf (line 131) | ifhbuf* rdbuf () const { return &buf; }
FILE: git-crypt.cpp
function print_usage (line 45) | static void print_usage (std::ostream& out)
function print_version (line 81) | static void print_version (std::ostream& out)
function help_for_command (line 86) | static bool help_for_command (const char* command, std::ostream& out)
function help (line 116) | static int help (int argc, const char** argv)
function version (line 129) | static int version (int argc, const char** argv)
function main (line 136) | int main (int argc, const char** argv)
FILE: gpg.cpp
function gpg_get_executable (line 36) | static std::string gpg_get_executable()
function gpg_nth_column (line 45) | static std::string gpg_nth_column (const std::string& line, unsigned int...
function gpg_get_uid (line 65) | std::string gpg_get_uid (const std::string& fingerprint)
function gpg_lookup_key (line 95) | std::vector<std::string> gpg_lookup_key (const std::string& query)
function gpg_list_secret_keys (line 128) | std::vector<std::string> gpg_list_secret_keys ()
function gpg_encrypt_to_file (line 157) | void gpg_encrypt_to_file (const std::string& filename, const std::string...
function gpg_decrypt_from_file (line 177) | void gpg_decrypt_from_file (const std::string& filename, std::ostream& o...
FILE: gpg.hpp
type Gpg_error (line 38) | struct Gpg_error {
method Gpg_error (line 41) | explicit Gpg_error (std::string m) : message(m) { }
FILE: key.cpp
function validate_key_name (line 311) | bool validate_key_name (const char* key_name, std::string* reason)
FILE: key.hpp
type Key_file (line 45) | struct Key_file {
type Entry (line 47) | struct Entry {
type Malformed (line 60) | struct Malformed { }
type Incompatible (line 61) | struct Incompatible { }
method is_empty (line 79) | bool is_empty () const { return entries.empty(); }
method is_filled (line 80) | bool is_filled () const { return !is_empty(); }
method set_key_name (line 84) | void set_key_name (const char* k) { key_name = k ? k : ""; }
FILE: parse_options.cpp
function Option_def (line 32) | static const Option_def* find_option (const Options_list& options, const...
function parse_options (line 42) | int parse_options (const Options_list& options, int argc, const char** a...
FILE: parse_options.hpp
type Option_def (line 34) | struct Option_def {
method Option_def (line 39) | Option_def () : is_set(0), value(0) { }
method Option_def (line 40) | Option_def (const std::string& arg_name, bool* arg_is_set)
method Option_def (line 42) | Option_def (const std::string& arg_name, const char** arg_value)
type Option_error (line 50) | struct Option_error {
method Option_error (line 54) | Option_error (const std::string& n, const std::string& m) : option_nam...
FILE: util-unix.cpp
function mkdir_parent (line 103) | void mkdir_parent (const std::string& path)
function our_exe_path (line 128) | std::string our_exe_path ()
function exit_status (line 145) | int exit_status (int wait_status)
function touch_file (line 150) | void touch_file (const std::string& filename)
function remove_file (line 157) | void remove_file (const std::string& filename)
function init_std_streams_platform (line 164) | static void init_std_streams_platform ()
function create_protected_file (line 168) | void create_protected_file (const char* path)
function util_rename (line 177) | int util_rename (const char* from, const char* to)
function get_directory_contents (line 182) | std::vector<std::string> get_directory_contents (const char* path)
FILE: util-win32.cpp
function mkdir_parent (line 96) | void mkdir_parent (const std::string& path)
function our_exe_path (line 112) | std::string our_exe_path ()
function exit_status (line 128) | int exit_status (int status)
function touch_file (line 133) | void touch_file (const std::string& filename)
function remove_file (line 157) | void remove_file (const std::string& filename)
function init_std_streams_platform (line 169) | static void init_std_streams_platform ()
function create_protected_file (line 175) | void create_protected_file (const char* path) // TODO
function util_rename (line 179) | int util_rename (const char* from, const char* to)
function get_directory_contents (line 186) | std::vector<std::string> get_directory_contents (const char* path)
FILE: util.cpp
function exec_command (line 37) | int exec_command (const std::vector<std::string>& args)
function exec_command (line 44) | int exec_command (const std::vector<std::string>& args, std::ostream& ou...
function exec_command_with_input (line 53) | int exec_command_with_input (const std::vector<std::string>& args, const...
function escape_shell_arg (line 63) | std::string escape_shell_arg (const std::string& str)
function load_be32 (line 77) | uint32_t load_be32 (const unsigned char* p)
function store_be32 (line 85) | void store_be32 (unsigned char* p, uint32_t i)
function read_be32 (line 93) | bool read_be32 (std::istream& in, uint32_t& i)
function write_be32 (line 104) | void write_be32 (std::ostream& out, uint32_t i)
function leakless_equals_char (line 122) | static bool leakless_equals_char (const unsigned char* a, const unsigned...
function leakless_equals (line 134) | bool leakless_equals (const void* a, const void* b, std::size_t len)
function init_std_streams (line 141) | void init_std_streams ()
FILE: util.hpp
type System_error (line 42) | struct System_error {
method System_error (line 47) | System_error (const std::string& a, const std::string& t, int e) : act...
class temp_fstream (line 52) | class temp_fstream : public std::fstream {
function successful_exit (line 67) | inline bool successful_exit (int wait_status) { return exit_status(wait_...
Condensed preview — 44 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (249K chars).
[
{
"path": ".gitattributes",
"chars": 20,
"preview": ".git* export-ignore\n"
},
{
"path": ".github/workflows/release-linux-arm64.yml",
"chars": 1374,
"preview": "on:\n release:\n types: [published]\nname: Build Release Binary (Linux ARM64)\njobs:\n build:\n name: Build Release Bi"
},
{
"path": ".github/workflows/release-linux.yml",
"chars": 1363,
"preview": "on:\n release:\n types: [published]\nname: Build Release Binary (Linux)\njobs:\n build:\n name: Build Release Binary\n "
},
{
"path": ".github/workflows/release-windows.yml",
"chars": 1680,
"preview": "on:\n release:\n types: [published]\nname: Build Release Binary (Windows)\njobs:\n build:\n name: Build Release Binary"
},
{
"path": ".gitignore",
"chars": 14,
"preview": "*.o\ngit-crypt\n"
},
{
"path": "AUTHORS",
"chars": 35,
"preview": "Andrew Ayer <agwa@andrewayer.name>\n"
},
{
"path": "CONTRIBUTING.md",
"chars": 1005,
"preview": "Thanks for your interest in contributing to git-crypt! git-crypt is\nopen source software and welcomes contributions in "
},
{
"path": "COPYING",
"chars": 35147,
"preview": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
},
{
"path": "INSTALL",
"chars": 2172,
"preview": "DEPENDENCIES\n\nTo build git-crypt, you need:\n\n Debian/Ubuntu package RHEL/CentOS pac"
},
{
"path": "INSTALL.md",
"chars": 2268,
"preview": "### Dependencies\n\nTo build git-crypt, you need:\n\n| Software | Debian/Ubuntu package | RHEL/CentOS"
},
{
"path": "Makefile",
"chars": 2005,
"preview": "#\n# Copyright (c) 2015 Andrew Ayer\n#\n# See COPYING file for license information.\n#\n\nCXXFLAGS ?= -Wall -pedantic -Wno-lon"
},
{
"path": "NEWS.md",
"chars": 3605,
"preview": "# Change Log\n\n## v0.8.0 (2025-09-23)\n* Remove OpenSSL 1.0 support, fix compilation with OpenSSL 3.\n* Avoid use of proble"
},
{
"path": "README.md",
"chars": 6882,
"preview": "git-crypt - transparent file encryption in git\n==============================================\n\ngit-crypt enables transpa"
},
{
"path": "RELEASE_NOTES-0.4.1.md",
"chars": 1040,
"preview": "git-crypt 0.4.1 is a bugfix-only release that contains an important\nusability fix for users who use GPG mode to encrypt "
},
{
"path": "RELEASE_NOTES-0.4.md",
"chars": 3095,
"preview": "Changes to be aware of for git-crypt 0.4\n========================================\n\n(For a complete list of changes, see "
},
{
"path": "THANKS.md",
"chars": 562,
"preview": "For their contributions to git-crypt, I thank:\n\n * Michael Mior and @zimbatm for the Homebrew formula.\n\n * Cyril Cleaud "
},
{
"path": "commands.cpp",
"chars": 58290,
"preview": "/*\n * Copyright 2012, 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can r"
},
{
"path": "commands.hpp",
"chars": 2626,
"preview": "/*\n * Copyright 2012, 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can r"
},
{
"path": "coprocess-unix.cpp",
"chars": 4775,
"preview": "/*\n * Copyright 2015 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistr"
},
{
"path": "coprocess-unix.hpp",
"chars": 2072,
"preview": "/*\n * Copyright 2015 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistr"
},
{
"path": "coprocess-win32.cpp",
"chars": 8080,
"preview": "/*\n * Copyright 2015 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistr"
},
{
"path": "coprocess-win32.hpp",
"chars": 2094,
"preview": "/*\n * Copyright 2015 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistr"
},
{
"path": "coprocess.cpp",
"chars": 88,
"preview": "#ifdef _WIN32\n#include \"coprocess-win32.cpp\"\n#else\n#include \"coprocess-unix.cpp\"\n#endif\n"
},
{
"path": "coprocess.hpp",
"chars": 88,
"preview": "#ifdef _WIN32\n#include \"coprocess-win32.hpp\"\n#else\n#include \"coprocess-unix.hpp\"\n#endif\n"
},
{
"path": "crypto-openssl-11.cpp",
"chars": 3237,
"preview": "/*\n * Copyright 2012, 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can r"
},
{
"path": "crypto.cpp",
"chars": 2807,
"preview": "/*\n * Copyright 2012, 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can r"
},
{
"path": "crypto.hpp",
"chars": 3241,
"preview": "/*\n * Copyright 2012, 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can r"
},
{
"path": "doc/multiple_keys.md",
"chars": 979,
"preview": "In addition to the implicit default key, git-crypt supports alternative\nkeys which can be used to encrypt specific files"
},
{
"path": "fhstream.cpp",
"chars": 6313,
"preview": "/*\n * Copyright (C) 2012, 2015 Andrew Ayer\n *\n * Permission is hereby granted, free of charge, to any person obtaining a"
},
{
"path": "fhstream.hpp",
"chars": 3855,
"preview": "/*\n * Copyright (C) 2012, 2015 Andrew Ayer\n *\n * Permission is hereby granted, free of charge, to any person obtaining a"
},
{
"path": "git-crypt.cpp",
"chars": 8505,
"preview": "/*\n * Copyright 2012, 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can r"
},
{
"path": "git-crypt.hpp",
"chars": 1451,
"preview": "/*\n * Copyright 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistr"
},
{
"path": "gpg.cpp",
"chars": 6112,
"preview": "/*\n * Copyright 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistr"
},
{
"path": "gpg.hpp",
"chars": 1910,
"preview": "/*\n * Copyright 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistr"
},
{
"path": "key.cpp",
"chars": 8331,
"preview": "/*\n * Copyright 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistr"
},
{
"path": "key.hpp",
"chars": 3096,
"preview": "/*\n * Copyright 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistr"
},
{
"path": "man/git-crypt.xml",
"chars": 16809,
"preview": "<!DOCTYPE refentry PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\" \"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\">"
},
{
"path": "man/man1/.gitignore",
"chars": 12,
"preview": "git-crypt.1\n"
},
{
"path": "parse_options.cpp",
"chars": 3352,
"preview": "/*\n * Copyright 2014 Andrew Ayer\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy o"
},
{
"path": "parse_options.hpp",
"chars": 2091,
"preview": "/*\n * Copyright 2014 Andrew Ayer\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy o"
},
{
"path": "util-unix.cpp",
"chars": 5682,
"preview": "/*\n * Copyright 2012, 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can r"
},
{
"path": "util-win32.cpp",
"chars": 5696,
"preview": "/*\n * Copyright 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can redistr"
},
{
"path": "util.cpp",
"chars": 4077,
"preview": "/*\n * Copyright 2012, 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can r"
},
{
"path": "util.hpp",
"chars": 3225,
"preview": "/*\n * Copyright 2012, 2014 Andrew Ayer\n *\n * This file is part of git-crypt.\n *\n * git-crypt is free software: you can r"
}
]
About this extraction
This page contains the full source code of the AGWA/git-crypt GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 44 files (225.7 KB), approximately 60.7k tokens, and a symbol index with 158 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.