Compare commits

..
2 Commits
Author SHA1 Message Date
Zachary Rice fe0778828e Create index.md 2021-11-19 08:34:24 -06:00
Zachary Rice 655ae6a957 Set theme jekyll-theme-minimal 2021-11-19 08:33:55 -06:00
24 changed files with 38 additions and 3816 deletions

No files matched your search

-12
View File
@@ -1,12 +0,0 @@
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary
*.test
*.out
tmp
-20
View File
@@ -1,20 +0,0 @@
sudo: required
language: go
go:
- 1.11
services:
- docker
script:
- env GO111MODULE=on make test
after_success:
- env GO111MODULE=on go build
- export REPO=zricethezav/gitleaks
- export TAG=`if [ "$TRAVIS_BRANCH" == "master" ]; then echo "latest"; else echo $TRAVIS_BRANCH;
fi`
- if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then make deploy; fi
env:
global:
- secure: kUjq6Jgnm57V+ikDoYJ4IrFu4bLMHkaBb9uLtbQj0A545zZt4Dbooarnwqbfz2efqqMDZ9TXP6kN6677yWm0DyvFOCYx/Xq2innnVbBJczQciEUb5PI/9fcmLOfTe/QgGNi0GZOCdIOGlki2sbKxob6tTOUsm52ugRSJU92cXkX8w+Gzc6pC6fAb4moLE2QpwK1xWDHm2sHiZYExpBOH8eidSH5VPGVdNE9QmUA/FwwJ9NFGsZ8BgWCJPy7IJreyixsv2nNpiZNHoj0UgKe4wylzceu4sG/yQDIYk3fLVWBXSm/nSA17QYIjVMzQFjSAVC5dRqzq8HzFYiAYLKzkoOtrbBqEGtXzYZMN6yC8zEedk9gX6P6mvGpWYBy280uumcpGl6eoKYj5ke2H6kfcCUhMNTGZP17nmnTa1KFLAz1nxB1jfJwwO6v1l+xdytju5yAhm049Af7VyDM5GmE2x5ha48uKvK7wHtv+IKiZbbcR9ExsXvm21+7NVjQvRPzAw4/Sor9SG/yjoA/Sf7e4evy1w3fALv4WlaSisj5Yalmv7mzeeFZaIB7EIq6OryeRld2Rr1MZwwhZgIs7+SWwpjKfwhkfLVEUvSWCdnS2tnTydK6R6OFxfG5TGfR/WHooXLHEv5gMuKhUu/CqnbLyvI+8IOH2ybz2AtZWjf5n7oY=
- secure: cIxKSkBNkPFAn243eHtwHJb8z6Uty1cZ43ZK/UABjwJoSrhu/roK4soqdZLwdVRA/0QswAlp6AC25Zs3ngLKGxxFHoeB8Tx6VLanE1zoi8OT0I2KbT92FdrLV4HlcRshKZtTFoTCfgVKPnWNKC+hil97CQzQPGRpZLBSfNefk5uCMnQiAzaJ5lyWPx+sjLHzpVlGA6aQx9ZeBQqngQJoDHKc0K3hKwug4h9mkkhyaYE3kgxtsdOYlHvOtQgVk+Zih5uW7ABOQCyAOaQVipXBC+uiuNf2DeAuGDaX69DTRKqPzuIasbhwyGqlfsr2JeofEWgZGmTaWGKMi03hnIY+U9+lHjygBW1qqVglODboouUrV3LwER9kqrT+ZFTM5Ca8VB+Gx5khkknbjWd06jpzRQxNXdukYN89kEaAHkBH844G99pMDqcZ32lHK7lpCu8n1H/Liz3ygoV6ScJXnYAP6y9rrd3bb9KEmnKhmFacVLRIAUw1vN/cgspJpl/Mk6s5rvGwsbQih1OxGyooOLxGjEGWqVDFgHFtyiwX9s9kT+hNTwKgbhp7Ragk/QuDYUPZ3Vum7HoiNPS9KpQNstLvDckdtd8h13JIw6nX+xdWbNKjjdYbAZRstJHUROQtNq3XdWNQ9YjqbCoybaxCOwOUTwOiTSWNKXjTFbFI5mR/ZO0=
- COMMIT=${TRAVIS_COMMIT::8}
- secure: o6uPX071qGRKgOQmitxiDr1j+KRW8W6ru0wmKNBFuUlZvQudwCUZMnVfk6OeofT1IgLCHmLS8ST81cTyeXqOQhYVZrlxTmEUpDHHRTu6dOj3eqRzdJow1LIWNpw5xfOaqXUdQ8+SQ47ZeSFapsmaY9oeRDvSJ8zLS4qUdgUylvZFJWjSrjzi2xemJa1l3MDdZRhEaNkfMliDGCv2vuUFp7tYz0QtyqBkBMORQl53dzgrcQcsRjDSE274WJl9CUg1l0pNMFsAbVCUGwUqCmKace9LXZ9JV00TRdg4EpryDsUCi23q0THnwstvRffwyJrw+xbhY/X3GKC4zOKqiCLJ4MTPQEIKlpVJQ9e9lWJ8FYhpUrl3QaHfEPINJ0taUfGhCyNzi5QBkSWbTcWVmRMmu+QIy7moW9crcz2xmVEUey7AaGwZT2Kk6JGw26w5q9IUy1Z9mwaljmHrUTqZrOX4Hj3UblpkHN+mGkoia/ipta5KhN5lTTIs4N3V+El7O2R2GggBrVHNiSualfydo+RX8k/S6PM1/C88IQO3Y2utoJrr415CznncvhF9Sc6tncZcShcNQj1iEOSsGxY2noW265eHzTMKJ/xuN6Bp9OXVK+8iOcUsz1T7F0UqwY3xnD8F7fBZ7IGG41DsXBDIcPmb+SIYbhv0uJjm3BEuv4TzIU0=
-224
View File
@@ -1,224 +0,0 @@
CHANGELOG
=========
1.25.0
----
- Pretty big refactor, see `src` directory
- Dropping dep for go modules
- Separating email and author
- Readding branch support with `--branch=`
1.24.0
----
- `--commit` now allows users to target a specific commit to audit
- `--commit-stop` audit all commits up to and including what is specified at `--commit-stop`
- Updated go-git version to 4.9.1
1.23.0
----
-- `--repo-config` allows users to load configs specific to a repo target
1.22.0
----
- context inclusion for redactions
- noise reduction for entropy signals
1.21.0
----
- added support for cloning repositories using github api
- auditing PRs now allows for whitelisting files
1.20.0
----
- adding gitlab user and group support
1.19.3
----
- memoizing root commit
- only count commits (not commit + parent) for total commit number
1.19.2
----
- fixed a bug where gitleaks was skipping the initial commit
- commit cache now checks curr commit + parent commit hash
- removed newlines from commit message
1.19.1
----
- mistakenly removed default whitelist files
1.19.0
----
- removed `--all-refs`. By default gitleaks now scans all branches, remote and local.
- added commit memoizer to prevent duplicate commit audits
- removed branch whitelist
- removed branch from report as a commit is an object independent of branch
- Better regexes for facebook, github, twitter (no more unbounded wildcards)
1.18.0
----
- fixing slack token
- defaulting to single thread process
- `--max-go=` --> `--threads=`
- guarding `--threads=` > max threads available (you aint gettin any more performance)
1.17.0
----
- Default regex added to search: slack, telegram.
- Default whitelisting: bin, doc, jpeg, gif
1.16.1
----
- Fixing default ssh auth logic
1.16.0
----
- Better commit coverage. Now iterates through each commit in git log and generates a patch with each commit's parent.
- Removing the need for --private/-p option. Instead gitleaks will determine if the repo is private or not.
1.15.0
----
- Whitelist repos use regex now
- Whitelist repo check before clone
1.14.0
----
- Entropy Range support in gitleaks config
1.13.0
----
- Github PR support
- Github has its own go file. All other services, bitbucket, gitlab, etc should follow this convention
1.12.1
----
- Show program usage when no arguments are provided
- Exit program after the -h or --help options are used
1.12.0
----
- removing --csv option
- --report option now requires .json or .csv in filename
- adding total time to audit in logs
1.11.1
----
- fix commit whitelist logic
1.11.0
-----
- Commit depth option
- Commit stats output
1.10.0
-----
- Add entropy option
1.9.0
-----
- exclude fork option
1.8.0
-----
- whitelist repos
- sample config option
1.7.3
-----
- style points
1.7.2
-----
- Fixing dangling goroutines, removing channel messaging
1.7.1
-----
- Fixing bug where single repos were not being audited
1.7.0
-----
- Exit code == 2 on error
- Cleaning up some logs
- Removing some unreachable code
1.6.1
-----
- Recover from panic when diffing
1.6.0
-----
- Default maximum goroutines spawned is number of cores your CPU run with. See benchmarks in wiki.
- Cleanup after each repo audit for organizations rather than waiting for the entire organization to complete. Eliminates the risk of running out of disk space.
1.5.0
-----
- Support for CSV reporting
- Refactoring Github user/owner audits
1.4.0
-----
- Support for single commit repos
- Bumped go-git version from 4.5.0 to 4.7.0
1.3.0
-----
- Target specific branch
1.2.1
-----
- Check errors when generating commit patch
1.2.0
-----
- Added support for providing an alternate GitHub URL to support scanning GitHub Enterprise repositories
1.1.2
-----
- Added version option
- Introduced changelog
1.1.1
-----
- Fixed commit patch order
- Updated Readme
1.1.0
-----
- Fixed Twitter typo
- Fixed sample docker command
- Default clone option to "in-memory"
- Added clone option for "disk"
- Updated Makefile
1.0.0
-----
- Rewrite, see Readme.md: https://github.com/zricethezav/gitleaks/releases/tag/v1.0.0
0.4.0
-----
- Added support for external regexes
0.3.0
-----
- Added local scan
- Meaningful exit codes
- Timestamped logs
- Refactored for some maintainability
0.2.0
-----
- Additionally regex checking
- $HOME/.gitleaks/ directory for clones and reports
- Pagination for Org/User list... no more partial repo lists
- Persistent repos for Orgs and Users (no more re-cloning)
- Updated README
- Multi-staged Docker build
- Travis CI
0.1.0
-----
- full git history search
- regex/entropy checks
- report generation
-19
View File
@@ -1,19 +0,0 @@
# Contributing Guidelines
The gitleaks project is under [GNU General Public License v3.0](LICENSE.md) and accepts
contributions via GitHub pull requests.
## How to Contribute
Open a PR. Give the PR a descriptive title. Add some comments describing what is the purpose of the PR.
__BUT before you do that!__
Make sure you pass this list of requirements.
- You've run `go fmt`.
- You've run `golint`.
- You've added test cases for your changes.
- You've updated [the changelog](CHANGELOG.md).
- Your tests pass.
-16
View File
@@ -1,16 +0,0 @@
FROM golang:1.11.6 AS build
WORKDIR /go/src/github.com/zricethezav/gitleaks
COPY . .
RUN GO111MODULE=on CGO_ENABLED=0 go build -o bin/gitleaks *.go
FROM alpine:3.7
RUN apk add --no-cache bash git openssh
COPY --from=build /go/src/github.com/zricethezav/gitleaks/bin/* /usr/bin/
ENTRYPOINT ["gitleaks"]
# How to use me :
# docker build -t gitleaks .
# docker run --rm --name=gitleaks gitleaks --repo=https://github.com/zricethezav/gitleaks
# This will check for secrets in https://github.com/zricethezav/gitleaks
-674
View File
@@ -1,674 +0,0 @@
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>.
-27
View File
@@ -1,27 +0,0 @@
.PHONY: test build-all deploy
test:
go get golang.org/x/lint/golint
go fmt
golint
go test --race --cover github.com/zricethezav/gitleaks/src -v
deploy:
@echo "$(DOCKER_PASSWORD)" | docker login -u "$(DOCKER_USERNAME)" --password-stdin
docker build -f Dockerfile -t $(REPO):$(TAG) .
echo "Pushing $(REPO):$(COMMIT) $(REPO):$(TAG)"
docker push $(REPO)
build-all:
rm -rf build
mkdir build
env GOOS="windows" GOARCH="amd64" go build -o "build/gitleaks-windows-amd64.exe"
env GOOS="windows" GOARCH="386" go build -o "build/gitleaks-windows-386.exe"
env GOOS="linux" GOARCH="amd64" go build -o "build/gitleaks-linux-amd64"
env GOOS="linux" GOARCH="arm" go build -o "build/gitleaks-linux-arm"
env GOOS="linux" GOARCH="mips" go build -o "build/gitleaks-linux-mips"
env GOOS="linux" GOARCH="mips" go build -o "build/gitleaks-linux-mips"
env GOOS="darwin" GOARCH="amd64" go build -o "build/gitleaks-darwin-amd64"
benchmark:
go test -run=Benchmark -bench=. -benchtime=5s
benchmark-fast:
go test -bench=BenchmarkAuditLeakRepo -run=BenchmarkAuditLeakRepo$
-130
View File
@@ -1,130 +0,0 @@
Gitleaks
--------
<p align="left">
<a href="https://travis-ci.org/zricethezav/gitleaks"><img alt="Travis" src="https://img.shields.io/travis/zricethezav/gitleaks/master.svg?style=flat-square"></a>
</p>
Audit git repos for secrets. Gitleaks provides a way for you to find unencrypted secrets and other unwanted data types in git source code repositories. As part of it's core functionality, it provides;
* Github and Gitlab support including support for bulk organization and repository owner (user) repository scans, as well as pull request scanning for use in common CI workflows.
* Support for private repository scans, and repositories that require key based authentication
* Output in CSV and JSON formats for consumption in other reporting tools and frameworks
* Externalised configuration for environment specific customisation including regex rules
* Customizable repository name, file type, commit ID, branchname and regex whitelisting to reduce false positives
* High performance through the use of src-d's [go-git](https://github.com/src-d/go-git) framework
It has been sucessfully used in a number of different scenarios, including;
* Adhoc scans of local and remote repositories by filesystem path or clone URL
* Automated scans of github users and organizations (Both public and enterprise platforms)
* As part of a CICD workflow to identify secrets before they make it deeper into your codebase
* As part of a wider secrets auditing automation capability for git data in large environments
### Example execution
<p align="left">
<img src="https://cdn.rawgit.com/zricethezav/5bf8259b7fea0170becffc06b8588edb/raw/f762769fe20ef3669bff34612b1bede6457631e6/termtosvg_je8bp82s.svg">
</p>
#### Installation
Written in Go, gitleaks is available in binary form for many popular platforms and OS types from the [releases page](https://github.com/zricethezav/gitleaks/releases). Alternatively, executed via Docker or it can be installed using Go directly, as per the below;
##### MacOS
```
brew install gitleaks
```
##### Docker
```bash
# Run gitleaks against a public repository
docker run --rm --name=gitleaks zricethezav/gitleaks -v -r https://github.com/zricethezav/gitleaks.git
# Run gitleaks against a local repository already cloned into /tmp/
docker run --rm --name=gitleaks -v /tmp/:/code/ zricethezav/gitleaks -v --repo-path=/code/gitleaks
# Run gitleaks against a specific Github Pull request
docker run --rm --name=gitleaks -e GITHUB_TOKEN={your token} zricethezav/gitleaks --github-pr=https://github.com/owner/repo/pull/9000
```
##### Go
```bash
go get -u github.com/zricethezav/gitleaks
```
#### Usage and Options
gitleaks has a wide range of configuration options that can be adjusted at runtime or via a configuration file based on your specific requirements.
```
Usage:
gitleaks [OPTIONS]
Application Options:
-r, --repo= Repo url to audit
--github-user= Github user to audit
--github-org= Github organization to audit
--github-url= GitHub API Base URL, use for GitHub Enterprise. Example: https://github.example.com/api/v3/ (default: https://api.github.com/)
--github-pr= Github PR url to audit. This does not clone the repo. GITHUB_TOKEN must be set
--gitlab-user= GitLab user ID to audit
--gitlab-org= GitLab group ID to audit
--commit-stop= sha of commit to stop at
--commit= sha of commit to audit
--depth= maximum commit depth
--repo-path= Path to repo
--owner-path= Path to owner directory (repos discovered)
--threads= Maximum number of threads gitleaks spawns
--disk Clones repo(s) to disk
--single-search= single regular expression to search for
--config= path to gitleaks config
--ssh-key= path to ssh key
--exclude-forks exclude forks for organization/user audits
-e, --entropy= Include entropy checks during audit. Entropy scale: 0.0(no entropy) - 8.0(max entropy)
--noise-reduction Reduce the number of finds when entropy checks are enabled
--repo-config Load config from target repo. Config file must be ".gitleaks.toml"
--branch= Branch to audit
-l, --log= log level
-v, --verbose Show verbose output from gitleaks audit
--report= path to write report file
--redact redact secrets from log messages and report
--version version number
--sample-config prints a sample config file
Help Options:
-h, --help Show this help message
```
#### Exit Codes
Gitleaks provides consistent exist codes to assist in automation workflows such as CICD platforms and bulk scanning.
These can be effectively used in conjunction with the report output file to detect and return meaningful data back to the user or external system about if leaks have been detected, and where they reside.
The code return codes are:
```
0: no leaks
1: leaks present
2: error encountered
```
### Additional information
* Additional documentation about how gitleaks functions can be found on the [wiki page](https://github.com/zricethezav/gitleaks/wiki)
* The below links detail the various approaches to remediating unwanted data in git repos
* [Removing sensitive data from a repository (github.com)](https://help.github.com/articles/removing-sensitive-data-from-a-repository/)
* [Removing sensitive files from commit history (atlassian.com)](https://community.atlassian.com/t5/Bitbucket-questions/Remove-sensitive-files-from-commit-history/qaq-p/243807)
* [Rewrite git history with the BFG (theguardian.com)](https://www.theguardian.com/info/developer-blog/2013/apr/29/rewrite-git-history-with-the-bfg)
* [Auditing Bitbucket Server Data for Credentials in AWS (sourcedgroup.com)](https://www.sourcedgroup.com/blog/auditing-bitbucket-server-data-credentials-in-aws)
This blog post details how gitleaks was used to audit data in Atlassian Bitbucket server when hosted on AWS and visualise the results in a compliance dashboard using Splunk.
* How does gitleaks differ to Github token scanning?
* [Github recently announced](https://blog.github.com/2018-10-16-future-of-software/#github-token-scanning-for-public-repositories-public-beta) a new capability to their cloud platform that detects exposed credentials for a number of common services and platforms and automatically notifies the provider for revocation or similar action. Gitleaks provides a similar detection capability for non-Github cloud users, in which repositories can be easily audited and results provided in a number of formats.
### Give Thanks
If using gitleaks has made you job easier consider donating to an organization, C-U at Home, that does vital work for those who most need it in the community of Champaign-Urbana, IL (my home).
Donate: https://www.cuathome.us/give/
+1
View File
@@ -0,0 +1 @@
theme: jekyll-theme-minimal
-39
View File
@@ -1,39 +0,0 @@
title = "gitleaks config"
[[regexes]]
description = "AWS"
regex = '''AKIA[0-9A-Z]{16}'''
[[regexes]]
description = "RKCS8"
regex = '''-----BEGIN PRIVATE KEY-----'''
[[regexes]]
description = "RSA"
regex = '''-----BEGIN RSA PRIVATE KEY-----'''
[[regexes]]
description = "Github"
regex = '''(?i)github.*['\"][0-9a-zA-Z]{35,40}['\"]'''
[[regexes]]
description = "SSH"
regex = '''-----BEGIN OPENSSH PRIVATE KEY-----'''
[[regexes]]
description = "Facebook"
regex = '''(?i)facebook.*['\"][0-9a-f]{32}['\"]'''
[[regexes]]
description = "Twitter"
regex = '''(?i)twitter.*['\"][0-9a-zA-Z]{35,44}['\"]'''
[[regexes]]
description = "PGP"
regex = '''-----BEGIN PGP PRIVATE KEY BLOCK-----'''
[[regexes]]
description = "Slack token"
regex = '''xox[baprs]-.*'''
[[regexes]]
description = "Strip API Key"
regex = '''(?i)(sk|pk)_(test|live)_[0-9a-zA-Z]{10,32}'''
[whitelist]
regexes = [
# "AKIA.*EXAMPLE",
]
files = [
"(.*?)(jpg|gif|doc|pdf|bin)$"
]
-26
View File
@@ -1,26 +0,0 @@
module github.com/zricethezav/gitleaks
require (
github.com/BurntSushi/toml v0.3.1
github.com/emirpasic/gods v1.12.0 // indirect
github.com/franela/goblin v0.0.0-20181003173013-ead4ad1d2727
github.com/google/go-github v15.0.0+incompatible
github.com/google/go-querystring v1.0.0 // indirect
github.com/hako/durafmt v0.0.0-20180520121703-7b7ae1e72ead
github.com/ipfs/go-ipfs v0.4.19 // indirect
github.com/jessevdk/go-flags v1.4.0
github.com/onsi/ginkgo v1.8.0 // indirect
github.com/onsi/gomega v1.5.0 // indirect
github.com/sirupsen/logrus v1.0.6
github.com/xanzy/go-gitlab v0.11.3
golang.org/x/crypto v0.0.0-20180910181607-0e37d006457b // indirect
golang.org/x/net v0.0.0-20180925072008-f04abc6bdfa7 // indirect
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6 // indirect
golang.org/x/sys v0.0.0-20180925112736-b09afc3d579e // indirect
google.golang.org/appengine v1.2.0 // indirect
gopkg.in/airbrake/gobrake.v2 v2.0.9 // indirect
gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2 // indirect
gopkg.in/src-d/go-billy.v4 v4.3.0 // indirect
gopkg.in/src-d/go-git.v4 v4.9.1
)
-111
View File
@@ -1,111 +0,0 @@
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/alcortesm/tgz v0.0.0-20161220082320-9c5fe88206d7 h1:uSoVVbwJiQipAclBbw+8quDsfcvFjOpI5iCf4p/cqCs=
github.com/alcortesm/tgz v0.0.0-20161220082320-9c5fe88206d7/go.mod h1:6zEj6s6u/ghQa61ZWa/C2Aw3RkjiTBOix7dkqa1VLIs=
github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239 h1:kFOfPq6dUM1hTo4JG6LR5AXSUEsOjtdm0kw0FtQtMJA=
github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/emirpasic/gods v1.9.0/go.mod h1:YfzfFFoVP/catgzJb4IKIqXjX78Ha8FMSDh3ymbK86o=
github.com/emirpasic/gods v1.12.0 h1:QAUIPSaCu4G+POclxeqb3F+WPpdKqFGlw36+yOzGlrg=
github.com/emirpasic/gods v1.12.0/go.mod h1:YfzfFFoVP/catgzJb4IKIqXjX78Ha8FMSDh3ymbK86o=
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 h1:BHsljHzVlRcyQhjrss6TZTdY2VfCqZPbv5k3iBFa2ZQ=
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc=
github.com/franela/goblin v0.0.0-20181003173013-ead4ad1d2727 h1:eouy4stZdUKn7n98c1+rdUTxWMg+jvhP+oHt0K8fiug=
github.com/franela/goblin v0.0.0-20181003173013-ead4ad1d2727/go.mod h1:7dvUGVsVBjqR7JHJk0brhHOZYGmfBYOrK0ZhYMEtBr4=
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/gliderlabs/ssh v0.1.1 h1:j3L6gSLQalDETeEg/Jg0mGY0/y/N6zI2xX1978P0Uqw=
github.com/gliderlabs/ssh v0.1.1/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0=
github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-github v15.0.0+incompatible h1:jlPg2Cpsxb/FyEV/MFiIE9tW/2RAevQNZDPeHbf5a94=
github.com/google/go-github v15.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ=
github.com/google/go-querystring v1.0.0 h1:Xkwi/a1rcvNg1PPYe5vI8GbeBY/jrVuDX5ASuANWTrk=
github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck=
github.com/hako/durafmt v0.0.0-20180520121703-7b7ae1e72ead h1:Y9WOGZY2nw5ksbEf5AIpk+vK52Tdg/VN/rHFRfEeeGQ=
github.com/hako/durafmt v0.0.0-20180520121703-7b7ae1e72ead/go.mod h1:5Scbynm8dF1XAPwIwkGPqzkM/shndPm79Jd1003hTjE=
github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/ipfs/go-ipfs v0.4.19 h1:ioUvuv1L3Zb9XgPi6S8selFMMlTa5AntQzVGvaoYHXM=
github.com/ipfs/go-ipfs v0.4.19/go.mod h1:iXzbK+Wa6eePj3jQg/uY6Uoq5iOwY+GToD/bgaRadto=
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A=
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo=
github.com/jessevdk/go-flags v1.4.0 h1:4IU2WS7AumrZ/40jfhf4QVDMsQwqA7VEHozFRrGARJA=
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
github.com/kevinburke/ssh_config v0.0.0-20180830205328-81db2a75821e h1:RgQk53JHp/Cjunrr1WlsXSZpqXn+uREuHvUVcK82CV8=
github.com/kevinburke/ssh_config v0.0.0-20180830205328-81db2a75821e/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/mitchellh/go-homedir v1.0.0 h1:vKb8ShqSby24Yrqr/yDYkuFz8d0WUjys40rvnGC8aR0=
github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.8.0 h1:VkHVNpR4iVnU8XQR6DBm8BqYjN7CRzw+xKUbVVbbW9w=
github.com/onsi/ginkgo v1.8.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/gomega v1.5.0 h1:izbySO9zDPmjJ8rDjLvkA2zJHIo+HkYXHnf7eN7SSyo=
github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
github.com/pelletier/go-buffruneio v0.2.0 h1:U4t4R6YkofJ5xHm3dJzuRpPZ0mr5MMCoAWooScCR7aA=
github.com/pelletier/go-buffruneio v0.2.0/go.mod h1:JkE26KsDizTr40EUHkXVtNPvgGtbSNq5BcowyYOWdKo=
github.com/pkg/errors v0.8.0 h1:WdK/asTD0HN+q6hsWO3/vpuAkAr+tw6aNJNDFFf0+qw=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ=
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
github.com/sirupsen/logrus v1.0.6 h1:hcP1GmhGigz/O7h1WVUM5KklBp1JoNS9FggWKdj/j3s=
github.com/sirupsen/logrus v1.0.6/go.mod h1:pMByvHTf9Beacp5x1UXfOR9xyW/9antXMhjMPG0dEzc=
github.com/src-d/gcfg v1.4.0 h1:xXbNR5AlLSA315x2UO+fTSSAXCDf+Ar38/6oyGbDKQ4=
github.com/src-d/gcfg v1.4.0/go.mod h1:p/UMsR43ujA89BJY9duynAwIpvqEujIH/jFlfL7jWoI=
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/xanzy/go-gitlab v0.11.3 h1:gSYcSb+pCx3fco6/O3w784/omQVTcrgxRzyf14SBvUQ=
github.com/xanzy/go-gitlab v0.11.3/go.mod h1:CRKHkvFWNU6C3AEfqLWjnCNnAs4nj8Zk95rX2S3X6Mw=
github.com/xanzy/ssh-agent v0.2.0 h1:Adglfbi5p9Z0BmK2oKU9nTG+zKfniSfnaMYB+ULd+Ro=
github.com/xanzy/ssh-agent v0.2.0/go.mod h1:0NyE30eGUDliuLEHJgYte/zncp2zdTStcOnWhgSqHD8=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20180910181607-0e37d006457b h1:2b9XGzhjiYsYPnKXoEfL7klWZQIt8IfyRCz62gCqqlQ=
golang.org/x/crypto v0.0.0-20180910181607-0e37d006457b/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180925072008-f04abc6bdfa7 h1:zKzVgSQ8WOSHzD7I4k8LQjrHUUCNOlBsgc0PcYLVNnY=
golang.org/x/net v0.0.0-20180925072008-f04abc6bdfa7/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be h1:vEDujvNQGv4jgYKudGeI/+DAX4Jffq6hpD55MmoEvKs=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6 h1:bjcUS9ztw9kFmmIxJInhon/0Is3p+EHBKNgquIzo1OI=
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180903190138-2b024373dcd9/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180925112736-b09afc3d579e h1:LSlw/Dbj0MkNvPYAAkGinYmGliq+aqS7eKPYlE4oWC4=
golang.org/x/sys v0.0.0-20180925112736-b09afc3d579e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
google.golang.org/appengine v1.2.0 h1:S0iUepdCWODXRvtE+gcRDd15L+k+k1AiHlMiMjefH24=
google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
gopkg.in/airbrake/gobrake.v2 v2.0.9 h1:7z2uVWwn7oVeeugY1DtlPAy5H+KYgB1KeKTnqjNatLo=
gopkg.in/airbrake/gobrake.v2 v2.0.9/go.mod h1:/h5ZAUhDkGaJfjzjKLSjv6zCL6O0LLBxU4K+aSYdM/U=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2 h1:OAj3g0cR6Dx/R07QgQe8wkA9RNjB2u4i700xBkIT4e0=
gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2/go.mod h1:Xk6kEKp8OKb+X14hQBKWaSkCsqBpgog8nAV2xsGOxlo=
gopkg.in/src-d/go-billy.v4 v4.2.1/go.mod h1:tm33zBoOwxjYHZIE+OV8bxTWFMJLrconzFMd38aARFk=
gopkg.in/src-d/go-billy.v4 v4.3.0 h1:KtlZ4c1OWbIs4jCv5ZXrTqG8EQocr0g/d4DjNg70aek=
gopkg.in/src-d/go-billy.v4 v4.3.0/go.mod h1:tm33zBoOwxjYHZIE+OV8bxTWFMJLrconzFMd38aARFk=
gopkg.in/src-d/go-git-fixtures.v3 v3.1.1 h1:XWW/s5W18RaJpmo1l0IYGqXKuJITWRFuA45iOf1dKJs=
gopkg.in/src-d/go-git-fixtures.v3 v3.1.1/go.mod h1:dLBcvytrw/TYZsNTWCnkNF2DSIlzWYqTe3rJR56Ac7g=
gopkg.in/src-d/go-git.v4 v4.9.1 h1:0oKHJZY8tM7B71378cfTg2c5jmWyNlXvestTT6WfY+4=
gopkg.in/src-d/go-git.v4 v4.9.1/go.mod h1:Vtut8izDyrM8BUVQnzJ+YvmNcem2J89EmfZYCkLokZk=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/warnings.v0 v0.1.2 h1:wFXVbFY8DY5/xOe1ECiWdKCzZlxgshcYVNkBHstARME=
gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI=
gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
+37
View File
@@ -0,0 +1,37 @@
## Welcome to GitHub Pages
You can use the [editor on GitHub](https://github.com/zricethezav/gitleaks/edit/gh-pages/index.md) to maintain and preview the content for your website in Markdown files.
Whenever you commit to this repository, GitHub Pages will run [Jekyll](https://jekyllrb.com/) to rebuild the pages in your site, from the content in your Markdown files.
### Markdown
Markdown is a lightweight and easy-to-use syntax for styling your writing. It includes conventions for
```markdown
Syntax highlighted code block
# Header 1
## Header 2
### Header 3
- Bulleted
- List
1. Numbered
2. List
**Bold** and _Italic_ and `Code` text
[Link](url) and ![Image](src)
```
For more details see [Basic writing and formatting syntax](https://docs.github.com/en/github/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax).
### Jekyll Themes
Your Pages site will use the layout and styles from the Jekyll theme you have selected in your [repository settings](https://github.com/zricethezav/gitleaks/settings/pages). The name of this theme is saved in the Jekyll `_config.yml` configuration file.
### Support or Contact
Having trouble with Pages? Check out our [documentation](https://docs.github.com/categories/github-pages-basics/) or [contact support](https://support.github.com/contact) and we’ll help you sort it out.
-23
View File
@@ -1,23 +0,0 @@
package main
import (
"os"
log "github.com/sirupsen/logrus"
"github.com/zricethezav/gitleaks/src"
)
func main() {
report, err := gitleaks.Run(gitleaks.ParseOpts())
if err != nil {
log.Error(err)
os.Exit(gitleaks.ErrExit)
}
if len(report.Leaks) != 0 {
log.Warnf("%d leaks detected. %d commits inspected in %s", len(report.Leaks), report.Commits, report.Duration)
os.Exit(gitleaks.LeakExit)
} else {
log.Infof("%d leaks detected. %d commits inspected in %s", len(report.Leaks), report.Commits, report.Duration)
}
}
-224
View File
@@ -1,224 +0,0 @@
package gitleaks
import (
"fmt"
"os"
"os/user"
"regexp"
"strconv"
"strings"
"github.com/BurntSushi/toml"
"gopkg.in/src-d/go-git.v4/plumbing/transport/ssh"
)
type entropyRange struct {
v1 float64
v2 float64
}
type Regex struct {
description string
regex *regexp.Regexp
}
// TomlConfig is used for loading gitleaks configs from a toml file
type TomlConfig struct {
Regexes []struct {
Description string
Regex string
}
Entropy struct {
LineRegexes []string
Ranges []string
}
Whitelist struct {
Files []string
Regexes []string
Commits []string
Repos []string
}
}
// Config contains gitleaks config
type Config struct {
Regexes []Regex
WhiteList struct {
regexes []*regexp.Regexp
files []*regexp.Regexp
commits map[string]bool
repos []*regexp.Regexp
}
Entropy struct {
entropyRanges []*entropyRange
regexes []*regexp.Regexp
}
sshAuth *ssh.PublicKeys
}
// loadToml loads of the toml config containing regexes and whitelists.
// This function will first look if the configPath is set and load the config
// from that file. Otherwise will then look for the path set by the GITHLEAKS_CONIFG
// env var. If that is not set, then gitleaks will continue with the default configs
// specified by the const var at the top `defaultConfig`
func newConfig() (*Config, error) {
var (
tomlConfig TomlConfig
configPath string
config Config
)
if opts.ConfigPath != "" {
configPath = opts.ConfigPath
_, err := os.Stat(configPath)
if err != nil {
return nil, fmt.Errorf("no gitleaks config at %s", configPath)
}
} else {
configPath = os.Getenv("GITLEAKS_CONFIG")
}
if configPath != "" {
if _, err := toml.DecodeFile(configPath, &tomlConfig); err != nil {
return nil, fmt.Errorf("problem loading config: %v", err)
}
} else {
_, err := toml.Decode(defaultConfig, &tomlConfig)
if err != nil {
return nil, fmt.Errorf("problem loading default config: %v", err)
}
}
sshAuth, err := getSSHAuth()
if err != nil {
return nil, err
}
config.sshAuth = sshAuth
err = config.update(tomlConfig)
if err != nil {
return nil, err
}
return &config, err
}
// updateConfig will update a the global config values
func (config *Config) update(tomlConfig TomlConfig) error {
if len(tomlConfig.Entropy.Ranges) != 0 {
err := config.updateEntropyRanges(tomlConfig.Entropy.Ranges)
if err != nil {
return err
}
}
for _, regex := range tomlConfig.Entropy.LineRegexes {
config.Entropy.regexes = append(config.Entropy.regexes, regexp.MustCompile(regex))
}
if singleSearchRegex != nil {
config.Regexes = append(config.Regexes, Regex{
description: "single search",
regex: singleSearchRegex,
})
} else {
for _, regex := range tomlConfig.Regexes {
config.Regexes = append(config.Regexes, Regex{
description: regex.Description,
regex: regexp.MustCompile(regex.Regex),
})
}
}
config.WhiteList.commits = make(map[string]bool)
for _, commit := range tomlConfig.Whitelist.Commits {
config.WhiteList.commits[commit] = true
}
for _, regex := range tomlConfig.Whitelist.Files {
config.WhiteList.files = append(config.WhiteList.files, regexp.MustCompile(regex))
}
for _, regex := range tomlConfig.Whitelist.Regexes {
config.WhiteList.regexes = append(config.WhiteList.regexes, regexp.MustCompile(regex))
}
for _, regex := range tomlConfig.Whitelist.Repos {
config.WhiteList.repos = append(config.WhiteList.repos, regexp.MustCompile(regex))
}
return nil
}
// entropyRanges hydrates entropyRanges which allows for fine tuning entropy checking
func (config *Config) updateEntropyRanges(entropyLimitStr []string) error {
for _, span := range entropyLimitStr {
split := strings.Split(span, "-")
v1, err := strconv.ParseFloat(split[0], 64)
if err != nil {
return err
}
v2, err := strconv.ParseFloat(split[1], 64)
if err != nil {
return err
}
if v1 > v2 {
return fmt.Errorf("entropy range must be ascending")
}
r := &entropyRange{
v1: v1,
v2: v2,
}
if r.v1 > 8.0 || r.v1 < 0.0 || r.v2 > 8.0 || r.v2 < 0.0 {
return fmt.Errorf("invalid entropy ranges, must be within 0.0-8.0")
}
config.Entropy.entropyRanges = append(config.Entropy.entropyRanges, r)
}
return nil
}
// externalConfig will attempt to load a pinned ".gitleaks.toml" configuration file
// from a remote or local repo. Use the --repo-config option to trigger this.
func (config *Config) updateFromRepo(repo *RepoInfo) error {
var tomlConfig TomlConfig
wt, err := repo.repository.Worktree()
if err != nil {
return err
}
f, err := wt.Filesystem.Open(".gitleaks.toml")
if err != nil {
return err
}
if _, err := toml.DecodeReader(f, &config); err != nil {
return fmt.Errorf("problem loading config: %v", err)
}
f.Close()
if err != nil {
return err
}
return config.update(tomlConfig)
}
// getSSHAuth return an ssh auth use by go-git to clone repos behind authentication.
// If --ssh-key is set then it will attempt to load the key from that path. If not,
// gitleaks will use the default $HOME/.ssh/id_rsa key
func getSSHAuth() (*ssh.PublicKeys, error) {
var (
sshKeyPath string
)
if opts.SSHKey != "" {
sshKeyPath = opts.SSHKey
} else {
// try grabbing default
c, err := user.Current()
if err != nil {
return nil, nil
}
sshKeyPath = fmt.Sprintf("%s/.ssh/id_rsa", c.HomeDir)
}
sshAuth, err := ssh.NewPublicKeysFromFile("git", sshKeyPath, "")
if err != nil {
if strings.HasPrefix(opts.Repo, "git") {
// if you are attempting to clone a git repo via ssh and supply a bad ssh key,
// the clone will fail.
return nil, fmt.Errorf("unable to generate ssh key: %v", err)
}
}
return sshAuth, nil
}
-77
View File
@@ -1,77 +0,0 @@
package gitleaks
const version = "1.25.0"
const defaultGithubURL = "https://api.github.com/"
const defaultThreadNum = 1
const ErrExit = 2
const LeakExit = 1
const defaultConfig = `
# This is a sample config file for gitleaks. You can configure gitleaks what to search for and what to whitelist.
# The output you are seeing here is the default gitleaks config. If GITLEAKS_CONFIG environment variable
# is set, gitleaks will load configurations from that path. If option --config-path is set, gitleaks will load
# configurations from that path. Gitleaks does not whitelist anything by default.
title = "gitleaks config"
# add regexes to the regex table
[[regexes]]
description = "AWS"
regex = '''AKIA[0-9A-Z]{16}'''
[[regexes]]
description = "PKCS8"
regex = '''-----BEGIN PRIVATE KEY-----'''
[[regexes]]
description = "RSA"
regex = '''-----BEGIN RSA PRIVATE KEY-----'''
[[regexes]]
description = "SSH"
regex = '''-----BEGIN OPENSSH PRIVATE KEY-----'''
[[regexes]]
description = "PGP"
regex = '''-----BEGIN PGP PRIVATE KEY BLOCK-----'''
[[regexes]]
description = "Facebook"
regex = '''(?i)facebook(.{0,4})?['\"][0-9a-f]{32}['\"]'''
[[regexes]]
description = "Twitter"
regex = '''(?i)twitter(.{0,4})?['\"][0-9a-zA-Z]{35,44}['\"]'''
[[regexes]]
description = "Github"
regex = '''(?i)github(.{0,4})?['\"][0-9a-zA-Z]{35,40}['\"]'''
[[regexes]]
description = "Slack"
regex = '''xox[baprs]-([0-9a-zA-Z]{10,48})?'''
[entropy]
lineregexes = [
"api",
"key",
"signature",
"secret",
"password",
"pass",
"pwd",
"token",
"curl",
"wget",
"https?",
]
[whitelist]
files = [
"(.*?)(jpg|gif|doc|pdf|bin)$"
]
#commits = [
# "BADHA5H1",
# "BADHA5H2",
#]
#repos = [
# "mygoodrepo"
#]
[misc]
#entropy = [
# "3.3-4.30"
# "6.0-8.0
#]
`
-117
View File
@@ -1,117 +0,0 @@
package gitleaks
import (
"io/ioutil"
"os"
"regexp"
"strings"
"sync"
"time"
"github.com/hako/durafmt"
log "github.com/sirupsen/logrus"
)
var (
opts *Options
config *Config
singleSearchRegex *regexp.Regexp
dir string
threads int
totalCommits int64
commitMap = make(map[string]bool)
auditDone bool
mutex = &sync.Mutex{}
)
func init() {
log.SetOutput(os.Stdout)
threads = defaultThreadNum
}
// Report is
type Report struct {
Leaks []Leak
Duration string
Commits int64
}
// Run is the entry point for gitleaks
func Run(optsL *Options) (*Report, error) {
var (
leaks []Leak
err error
)
now := time.Now()
opts = optsL
config, err = newConfig()
if err != nil {
return nil, err
}
if opts.Disk {
// temporary directory where all the gitleaks plain clones will reside
dir, err = ioutil.TempDir("", "gitleaks")
defer os.RemoveAll(dir)
if err != nil {
goto postAudit
}
}
// start audits
if opts.Repo != "" || opts.RepoPath != "" {
repoInfo, err := newRepoInfo()
if err != nil {
goto postAudit
}
err = repoInfo.clone()
if err != nil {
goto postAudit
}
leaks, err = repoInfo.audit()
} else if opts.OwnerPath != "" {
repoDs, err := discoverRepos(opts.OwnerPath)
if err != nil {
goto postAudit
}
for _, repoInfo := range repoDs {
err = repoInfo.clone()
if err != nil {
continue
}
leaksFromRepo, err := repoInfo.audit()
if err != nil {
log.Warnf("error occured auditing repo: %s, continuing", repoInfo.name)
}
leaks = append(leaksFromRepo, leaks...)
}
} else if opts.GithubOrg != "" || opts.GithubUser != "" {
leaks, err = auditGithubRepos()
} else if opts.GitLabOrg != "" || opts.GitLabUser != "" {
leaks, err = auditGitlabRepos()
} else if opts.GithubPR != "" {
leaks, err = auditGithubPR()
}
postAudit:
if err != nil {
if strings.Contains(err.Error(), "whitelisted") {
log.Info(err.Error())
os.Exit(0)
}
log.Error(err)
os.Exit(ErrExit)
}
if opts.Report != "" {
writeReport(leaks)
}
return &Report{
Leaks: leaks,
Duration: durafmt.Parse(time.Now().Sub(now)).String(),
Commits: totalCommits,
}, err
}
-52
View File
@@ -1,52 +0,0 @@
package gitleaks
import (
"math"
)
// getShannonEntropy https://en.wiktionary.org/wiki/Shannon_entropy
func getShannonEntropy(data string) (entropy float64) {
if data == "" {
return 0
}
charCounts := make(map[rune]int)
for _, char := range data {
charCounts[char]++
}
invLength := 1.0 / float64(len(data))
for _, count := range charCounts {
freq := float64(count) * invLength
entropy -= freq * math.Log2(freq)
}
return entropy
}
func entropyIsHighEnough(entropy float64) bool {
if entropy >= opts.Entropy && len(config.Entropy.entropyRanges) == 0 {
return true
}
for _, eR := range config.Entropy.entropyRanges {
if entropy > eR.v1 && entropy < eR.v2 {
return true
}
}
return false
}
func highEntropyLineIsALeak(line string) bool {
if !opts.NoiseReduction {
return true
}
for _, re := range config.Entropy.regexes {
if re.FindString(line) != "" {
return true
}
}
return false
}
-268
View File
@@ -1,268 +0,0 @@
package gitleaks
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"github.com/google/go-github/github"
log "github.com/sirupsen/logrus"
"golang.org/x/oauth2"
git "gopkg.in/src-d/go-git.v4"
gitHttp "gopkg.in/src-d/go-git.v4/plumbing/transport/http"
"gopkg.in/src-d/go-git.v4/storage/memory"
)
var githubPages = 100
// auditPR audits a single github PR
func auditGithubPR() ([]Leak, error) {
var leaks []Leak
ctx := context.Background()
githubClient := github.NewClient(githubToken())
splits := strings.Split(opts.GithubPR, "/")
owner := splits[len(splits)-4]
repo := splits[len(splits)-3]
prNum, err := strconv.Atoi(splits[len(splits)-1])
if err != nil {
return nil, err
}
page := 1
for {
commits, resp, err := githubClient.PullRequests.ListCommits(ctx, owner, repo, prNum, &github.ListOptions{
PerPage: githubPages,
Page: page,
})
if err != nil {
return leaks, err
}
for _, c := range commits {
totalCommits = totalCommits + 1
c, _, err := githubClient.Repositories.GetCommit(ctx, owner, repo, *c.SHA)
if err != nil {
continue
}
files := c.Files
for _, f := range files {
skipFile := false
if f.Patch == nil || f.Filename == nil {
continue
}
for _, re := range config.WhiteList.files {
if re.FindString(f.GetFilename()) != "" {
log.Infof("skipping whitelisted file (matched regex '%s'): %s", re.String(), f.GetFilename())
skipFile = true
break
}
}
if skipFile {
continue
}
commit := commitInfo{
sha: c.GetSHA(),
content: *f.Patch,
filePath: *f.Filename,
repoName: repo,
author: c.GetCommitter().GetLogin(),
message: *c.Commit.Message,
date: *c.Commit.Committer.Date,
}
leaks = append(leaks, inspect(commit)...)
}
}
page = resp.NextPage
if resp.LastPage == 0 {
break
}
}
return leaks, nil
}
// auditGithubRepos kicks off audits if --github-user or --github-org options are set.
// First, we gather all the github repositories from the github api (this doesnt actually clone the repo).
// After all the repos have been pulled from github's api we proceed to audit the repos by calling auditGithubRepo.
// If an error occurs during an audit of a repo, that error is logged but won't break the execution cycle.
func auditGithubRepos() ([]Leak, error) {
var (
err error
githubRepos []*github.Repository
pagedGithubRepos []*github.Repository
resp *github.Response
githubOrgOptions *github.RepositoryListByOrgOptions
githubOptions *github.RepositoryListOptions
done bool
leaks []Leak
ownerDir string
)
ctx := context.Background()
githubClient := github.NewClient(githubToken())
if opts.GithubOrg != "" {
if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
ghURL, _ := url.Parse(opts.GithubURL)
githubClient.BaseURL = ghURL
}
githubOrgOptions = &github.RepositoryListByOrgOptions{
ListOptions: github.ListOptions{PerPage: 100},
}
} else if opts.GithubUser != "" {
if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
ghURL, _ := url.Parse(opts.GithubURL)
githubClient.BaseURL = ghURL
}
githubOptions = &github.RepositoryListOptions{
Affiliation: "owner",
ListOptions: github.ListOptions{
PerPage: 100,
},
}
}
for {
if done {
break
}
if opts.GithubUser != "" {
pagedGithubRepos, resp, err = githubClient.Repositories.List(ctx, opts.GithubUser, githubOptions)
if err != nil {
done = true
}
githubOptions.Page = resp.NextPage
githubRepos = append(githubRepos, pagedGithubRepos...)
if resp.NextPage == 0 {
done = true
}
} else if opts.GithubOrg != "" {
pagedGithubRepos, resp, err = githubClient.Repositories.ListByOrg(ctx, opts.GithubOrg, githubOrgOptions)
if err != nil {
done = true
}
githubOrgOptions.Page = resp.NextPage
githubRepos = append(githubRepos, pagedGithubRepos...)
if resp.NextPage == 0 {
done = true
}
}
if opts.Log == "Debug" || opts.Log == "debug" {
for _, githubRepo := range pagedGithubRepos {
log.Debugf("staging repos %s", *githubRepo.Name)
}
}
}
if opts.Disk {
ownerDir, _ = ioutil.TempDir(dir, opts.GithubUser)
}
for _, githubRepo := range githubRepos {
repoD, err := cloneGithubRepo(githubRepo)
if err != nil {
log.Warn(err)
continue
}
leaksFromRepo, err := repoD.audit()
if opts.Disk {
os.RemoveAll(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name))
}
if len(leaksFromRepo) == 0 {
log.Infof("no leaks found for repo %s", *githubRepo.Name)
} else {
log.Warnf("leaks found for repo %s", *githubRepo.Name)
}
if err != nil {
log.Warn(err)
}
leaks = append(leaks, leaksFromRepo...)
}
return leaks, nil
}
// cloneGithubRepo clones a repo from the url parsed from a github repo. The repo
// will be cloned to disk if --disk is set.
func cloneGithubRepo(githubRepo *github.Repository) (*RepoInfo, error) {
var (
repo *git.Repository
err error
)
githubToken := os.Getenv("GITHUB_TOKEN")
if opts.ExcludeForks && githubRepo.GetFork() {
return nil, fmt.Errorf("skipping %s, excluding forks", *githubRepo.Name)
}
for _, re := range config.WhiteList.repos {
if re.FindString(*githubRepo.Name) != "" {
return nil, fmt.Errorf("skipping %s, whitelisted", *githubRepo.Name)
}
}
log.Infof("cloning: %s", *githubRepo.Name)
if opts.Disk {
ownerDir, err := ioutil.TempDir(dir, opts.GithubUser)
if err != nil {
return nil, fmt.Errorf("unable to generater owner temp dir: %v", err)
}
if config.sshAuth != nil && githubToken == "" {
repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
URL: *githubRepo.SSHURL,
Auth: config.sshAuth,
})
} else if githubToken != "" {
repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
URL: *githubRepo.CloneURL,
Auth: &gitHttp.BasicAuth{
Username: "fakeUsername", // yes, this can be anything except an empty string
Password: githubToken,
},
})
} else {
repo, err = git.PlainClone(fmt.Sprintf("%s/%s", ownerDir, *githubRepo.Name), false, &git.CloneOptions{
URL: *githubRepo.CloneURL,
})
}
} else {
if config.sshAuth != nil && githubToken == "" {
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: *githubRepo.SSHURL,
Auth: config.sshAuth,
})
} else if githubToken != "" {
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: *githubRepo.CloneURL,
Auth: &gitHttp.BasicAuth{
Username: "fakeUsername", // yes, this can be anything except an empty string
Password: githubToken,
},
})
} else {
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: *githubRepo.CloneURL,
})
}
}
if err != nil {
return nil, err
}
return &RepoInfo{
repository: repo,
name: *githubRepo.Name,
}, nil
}
// githubToken returns an oauth2 client for the github api to consume. This token is necessary
// if you are running audits with --github-user or --github-org
func githubToken() *http.Client {
githubToken := os.Getenv("GITHUB_TOKEN")
if githubToken == "" {
return nil
}
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: githubToken},
)
return oauth2.NewClient(context.Background(), ts)
}
-166
View File
@@ -1,166 +0,0 @@
package gitleaks
import (
"fmt"
"io/ioutil"
"os"
log "github.com/sirupsen/logrus"
"github.com/xanzy/go-gitlab"
"gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/storage/memory"
)
// gitlabPages number of records per request
const gitlabPages = 100
// auditGitlabRepos kicks off audits if --gitlab-user or --gitlab-org options are set.
// Getting all repositories from the GitLab API and run audit. If an error occurs during an audit of a repo,
// that error is logged.
func auditGitlabRepos() ([]Leak, error) {
var (
ps []*gitlab.Project
resp *gitlab.Response
leaks []Leak
tempDir string
err error
)
repos := make([]*gitlab.Project, 0, gitlabPages)
page := 1
cl := gitlab.NewClient(nil, os.Getenv("GITLAB_TOKEN"))
// if self hosted GitLab server
if url := os.Getenv("GITLAB_URL"); url != "" {
cl.SetBaseURL(url)
}
for {
if opts.GitLabOrg != "" {
opt := &gitlab.ListGroupProjectsOptions{
ListOptions: gitlab.ListOptions{
PerPage: gitlabPages,
Page: page,
},
}
ps, resp, err = cl.Groups.ListGroupProjects(opts.GitLabOrg, opt)
} else if opts.GitLabUser != "" {
opt := &gitlab.ListProjectsOptions{
ListOptions: gitlab.ListOptions{
PerPage: gitlabPages,
Page: page,
},
}
ps, resp, err = cl.Projects.ListUserProjects(opts.GitLabUser, opt)
}
if err != nil {
// exit when can't make API call
log.Fatal("error listing projects: ", err)
}
repos = append(repos, ps...)
if page >= resp.TotalPages {
// exit when we've seen all pages
break
}
page = resp.NextPage
}
log.Debugf("found projects: %d", len(repos))
if opts.Disk {
if tempDir, err = createGitlabTempDir(); err != nil {
log.Fatal("error creating temp directory: ", err)
}
}
for _, p := range repos {
repoInfo, err := cloneGitlabRepo(tempDir, p)
if err != nil {
log.Warn(err)
continue
}
leaksFromRepo, err := repoInfo.audit()
if err != nil {
log.Warn(err)
}
if opts.Disk {
os.RemoveAll(fmt.Sprintf("%s/%d", tempDir, p.ID))
}
if len(leaksFromRepo) == 0 {
log.Infof("no leaks found for repo %s", p.Name)
} else {
log.Warnf("leaks found for repo %s", p.Name)
}
leaks = append(leaks, leaksFromRepo...)
}
return leaks, nil
}
func createGitlabTempDir() (string, error) {
pathName := opts.GitLabUser
if opts.GitLabOrg != "" {
pathName = opts.GitLabOrg
}
os.RemoveAll(fmt.Sprintf("%s/%s", dir, pathName))
ownerDir, err := ioutil.TempDir(dir, pathName)
if err != nil {
return "", err
}
return ownerDir, nil
}
func cloneGitlabRepo(tempDir string, p *gitlab.Project) (*RepoInfo, error) {
var (
repo *git.Repository
err error
)
if opts.ExcludeForks && p.ForkedFromProject != nil {
return nil, fmt.Errorf("skipping %s, excluding forks", p.Name)
}
for _, re := range config.WhiteList.repos {
if re.FindString(p.Name) != "" {
return nil, fmt.Errorf("skipping %s, whitelisted", p.Name)
}
}
opt := &git.CloneOptions{
URL: p.HTTPURLToRepo,
}
if config.sshAuth != nil {
opt.URL = p.SSHURLToRepo
opt.Auth = config.sshAuth
}
log.Infof("cloning: %s", p.Name)
if opts.Disk {
repo, err = git.PlainClone(fmt.Sprintf("%s/%d", tempDir, p.ID), false, opt)
} else {
repo, err = git.Clone(memory.NewStorage(), nil, opt)
}
if err != nil {
return nil, err
}
return &RepoInfo{
repository: repo,
name: p.Name,
}, nil
}
-902
View File
@@ -1,902 +0,0 @@
package gitleaks
import (
"fmt"
"io/ioutil"
"os"
"path"
"regexp"
"strings"
"testing"
"time"
"github.com/franela/goblin"
log "github.com/sirupsen/logrus"
git "gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/storage/memory"
)
const testWhitelistCommit = `
[[regexes]]
description = "AWS"
regex = '''AKIA[0-9A-Z]{16}'''
[whitelist]
commits = [
"eaeffdc65b4c73ccb67e75d96bd8743be2c85973",
]
`
const testWhitelistFile = `
[[regexes]]
description = "AWS"
regex = '''AKIA[0-9A-Z]{16}'''
[whitelist]
files = [
".go",
]
`
const testWhitelistRegex = `
[[regexes]]
description = "AWS"
regex = '''AKIA[0-9A-Z]{16}'''
[whitelist]
regexes= [
"AKIA",
]
`
const testWhitelistRepo = `
[[regexes]]
description = "AWS"
regex = '''AKIA[0-9A-Z]{16}'''
[whitelist]
repos = [
"gronit",
]
`
const testEntropyRange = `
[entropy]
ranges = [
"7.5-8.0",
"3.2-3.4",
]
lineregexes = [
"(?i)api",
"(?i)key",
"signature",
"secret",
"password",
"pass",
"pwd",
"token",
"curl",
"wget",
"https?",
]
`
const testBadEntropyRange = `
[entropy]
ranges = [
"8.0-3.0",
]
`
const testBadEntropyRange2 = `
[entropy]
ranges = [
"8.0-8.9",
]
`
func TestGetRepo(t *testing.T) {
var err error
dir, err = ioutil.TempDir("", "gitleaksTestRepo")
defer os.RemoveAll(dir)
if err != nil {
panic(err)
}
_, err = git.PlainClone(dir, false, &git.CloneOptions{
URL: "https://github.com/gitleakstest/gronit",
})
if err != nil {
panic(err)
}
var tests = []struct {
testOpts *Options
description string
expectedErrMsg string
}{
{
testOpts: &Options{
Repo: "https://github.com/gitleakstest/gronit",
},
description: "test plain clone remote repo",
expectedErrMsg: "",
},
{
testOpts: &Options{
Repo: "https://github.com/gitleakstest/gronit",
Disk: true,
},
description: "test on disk clone remote repo",
expectedErrMsg: "",
},
{
testOpts: &Options{
RepoPath: dir,
},
description: "test local clone repo",
expectedErrMsg: "",
},
{
testOpts: &Options{
Repo: "https://github.com/gitleakstest/nope",
},
description: "test no repo",
expectedErrMsg: "authentication required",
},
{
testOpts: &Options{
Repo: "https://github.com/gitleakstest/private",
},
description: "test private repo",
expectedErrMsg: "authentication required",
},
{
testOpts: &Options{
Repo: "https://github.com/gitleakstest/private",
Disk: true,
},
description: "test private repo",
expectedErrMsg: "authentication required",
},
}
g := goblin.Goblin(t)
for _, test := range tests {
g.Describe("TestGetRepo", func() {
g.It(test.description, func() {
opts = test.testOpts
config, err = newConfig()
if err != nil {
log.Fatal(err)
}
repo, _ := newRepoInfo()
err := repo.clone()
if err != nil {
g.Assert(err.Error()).Equal(test.expectedErrMsg)
}
})
})
}
}
func TestRun(t *testing.T) {
var err error
configsDir := testTomlLoader()
dir, err = ioutil.TempDir("", "gitleaksTestOwner")
defer os.RemoveAll(dir)
if err != nil {
panic(err)
}
git.PlainClone(dir+"/gronit", false, &git.CloneOptions{
URL: "https://github.com/gitleakstest/gronit",
})
git.PlainClone(dir+"/h1domains", false, &git.CloneOptions{
URL: "https://github.com/gitleakstest/h1domains",
})
var tests = []struct {
testOpts *Options
description string
expectedErrMsg string
whiteListRepos []string
whiteListFiles []*regexp.Regexp
numLeaks int
configPath string
commitPerPage int
}{
{
testOpts: &Options{
GitLabUser: "gitleakstest",
},
description: "test gitlab user",
numLeaks: 2,
expectedErrMsg: "",
},
{
testOpts: &Options{
GithubUser: "gitleakstest",
},
description: "test github user",
numLeaks: 2,
expectedErrMsg: "",
},
{
testOpts: &Options{
GithubUser: "gitleakstest",
Disk: true,
},
description: "test github user on disk ",
numLeaks: 2,
expectedErrMsg: "",
},
{
testOpts: &Options{
GithubOrg: "gitleakstestorg",
},
description: "test github org",
numLeaks: 2,
expectedErrMsg: "",
},
{
testOpts: &Options{
GithubOrg: "gitleakstestorg",
Disk: true,
},
description: "test org on disk",
numLeaks: 2,
expectedErrMsg: "",
},
{
testOpts: &Options{
OwnerPath: dir,
},
description: "test owner path",
numLeaks: 2,
expectedErrMsg: "",
},
{
testOpts: &Options{
Repo: "git@github.com:gitleakstest/gronit.git",
SSHKey: "trash",
},
description: "test leak",
numLeaks: 0,
expectedErrMsg: "unable to generate ssh key: open trash: no such file or directory",
},
{
testOpts: &Options{
Repo: "https://github.com/gitleakstest/gronit.git",
},
description: "test leak",
numLeaks: 2,
expectedErrMsg: "",
},
{
testOpts: &Options{
Repo: "https://github.com/gitleakstest/h1domains.git",
},
description: "test clean",
numLeaks: 0,
expectedErrMsg: "",
},
{
testOpts: &Options{
Repo: "https://github.com/gitleakstest/empty.git",
},
description: "test empty",
numLeaks: 0,
expectedErrMsg: "reference not found",
},
{
testOpts: &Options{
GithubOrg: "gitleakstestorg",
},
description: "test github org, whitelist repo",
numLeaks: 0,
expectedErrMsg: "",
configPath: path.Join(configsDir, "repo"),
},
{
testOpts: &Options{
GithubOrg: "gitleakstestorg",
ExcludeForks: true,
},
description: "test github org, exclude forks",
numLeaks: 0,
expectedErrMsg: "",
},
{
testOpts: &Options{
GithubPR: "https://github.com/gitleakstest/gronit/pull/1",
},
description: "test github pr",
numLeaks: 4,
expectedErrMsg: "",
},
{
testOpts: &Options{
GithubPR: "https://github.com/gitleakstest/gronit/pull/1",
},
description: "test github pr",
numLeaks: 4,
expectedErrMsg: "",
commitPerPage: 1,
},
{
testOpts: &Options{
GithubPR: "https://github.com/gitleakstest/gronit/pull/1",
},
description: "test github pr with whitelisted files",
numLeaks: 0,
expectedErrMsg: "",
commitPerPage: 1,
configPath: path.Join(configsDir, "file"),
},
{
testOpts: &Options{
GithubPR: "https://github.com/gitleakstest/gronit/pull/2",
},
description: "test github pr with commits without patch info",
numLeaks: 0,
expectedErrMsg: "",
commitPerPage: 1,
},
}
g := goblin.Goblin(t)
for _, test := range tests {
g.Describe("TestRun", func() {
g.It(test.description, func() {
if test.configPath != "" {
os.Setenv("GITLEAKS_CONFIG", test.configPath)
}
if test.commitPerPage != 0 {
githubPages = test.commitPerPage
}
report, err := Run(test.testOpts)
if err != nil {
g.Assert(err.Error()).Equal(test.expectedErrMsg)
} else {
g.Assert(len(report.Leaks)).Equal(test.numLeaks)
}
githubPages = 100
})
})
}
}
func TestWriteReport(t *testing.T) {
tmpDir, _ := ioutil.TempDir("", "reportDir")
reportJSON := path.Join(tmpDir, "report.json")
reportJASON := path.Join(tmpDir, "report.jason")
reportVOID := path.Join("thereIsNoWay", "thisReportWillGetWritten.json")
reportCSV := path.Join(tmpDir, "report.csv")
defer os.RemoveAll(tmpDir)
leaks := []Leak{
{
Line: "eat",
Commit: "your",
Offender: "veggies",
Type: "and",
Message: "get",
Author: "some",
File: "sleep",
Date: time.Now(),
},
}
var tests = []struct {
leaks []Leak
reportFile string
fileName string
description string
testOpts Options
expectedErrMsg string
}{
{
leaks: leaks,
reportFile: reportJSON,
fileName: "report.json",
description: "can we write a json file",
testOpts: Options{
Report: reportJSON,
},
},
{
leaks: leaks,
reportFile: reportCSV,
fileName: "report.csv",
description: "can we write a csv file",
testOpts: Options{
Report: reportCSV,
},
},
{
leaks: leaks,
reportFile: reportJASON,
fileName: "report.jason",
description: "bad file",
expectedErrMsg: "Report should be a .json or .csv file",
testOpts: Options{
Report: reportJASON,
},
},
{
leaks: leaks,
reportFile: reportVOID,
fileName: "report.jason",
description: "bad dir",
expectedErrMsg: "thereIsNoWay does not exist",
testOpts: Options{
Report: reportVOID,
},
},
}
g := goblin.Goblin(t)
for _, test := range tests {
g.Describe("TestWriteReport", func() {
g.It(test.description, func() {
opts = &(test.testOpts)
err := opts.guard()
if err != nil {
g.Assert(err.Error()).Equal(test.expectedErrMsg)
} else {
writeReport(test.leaks)
f, _ := os.Stat(test.reportFile)
g.Assert(f.Name()).Equal(test.fileName)
}
})
})
}
}
func testTomlLoader() string {
tmpDir, _ := ioutil.TempDir("", "whiteListConfigs")
ioutil.WriteFile(path.Join(tmpDir, "regex"), []byte(testWhitelistRegex), 0644)
ioutil.WriteFile(path.Join(tmpDir, "commit"), []byte(testWhitelistCommit), 0644)
ioutil.WriteFile(path.Join(tmpDir, "file"), []byte(testWhitelistFile), 0644)
ioutil.WriteFile(path.Join(tmpDir, "repo"), []byte(testWhitelistRepo), 0644)
ioutil.WriteFile(path.Join(tmpDir, "entropy"), []byte(testEntropyRange), 0644)
ioutil.WriteFile(path.Join(tmpDir, "badEntropy"), []byte(testBadEntropyRange), 0644)
ioutil.WriteFile(path.Join(tmpDir, "badEntropy2"), []byte(testBadEntropyRange2), 0644)
return tmpDir
}
func TestAuditRepo(t *testing.T) {
var leaks []Leak
configsDir := testTomlLoader()
defer os.RemoveAll(configsDir)
leaksR, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: "https://github.com/gitleakstest/gronit.git",
})
if err != nil {
panic(err)
}
leaksRepo := &RepoInfo{
repository: leaksR,
name: "gronit",
}
cleanR, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: "https://github.com/gitleakstest/h1domains.git",
})
if err != nil {
panic(err)
}
cleanRepo := &RepoInfo{
repository: cleanR,
name: "h1domains",
}
var tests = []struct {
testOpts *Options
description string
expectedErrMsg string
numLeaks int
repo *RepoInfo
whiteListFiles []*regexp.Regexp
whiteListCommits map[string]bool
whiteListRepos []*regexp.Regexp
whiteListRegexes []*regexp.Regexp
configPath string
}{
{
repo: leaksRepo,
description: "pinned config",
numLeaks: 0,
testOpts: &Options{
RepoConfig: true,
},
},
{
repo: leaksRepo,
description: "commit depth = 1, one leak",
numLeaks: 1,
testOpts: &Options{
Depth: 1,
},
},
{
repo: leaksRepo,
description: "two leaks present",
numLeaks: 2,
testOpts: &Options{},
},
{
repo: leaksRepo,
description: "no leaks present on branch",
numLeaks: 0,
testOpts: &Options{
Branch: "dev",
},
},
{
repo: leaksRepo,
description: "two leaks present limit goroutines",
numLeaks: 2,
testOpts: &Options{
Threads: 4,
},
},
{
repo: leaksRepo,
description: "two leaks present whitelist AWS.. no leaks",
testOpts: &Options{},
configPath: path.Join(configsDir, "regex"),
numLeaks: 0,
},
{
repo: leaksRepo,
description: "two leaks present limit goroutines",
testOpts: &Options{
Threads: 2,
},
numLeaks: 2,
},
{
repo: cleanRepo,
description: "no leaks present",
testOpts: &Options{},
numLeaks: 0,
},
{
repo: leaksRepo,
description: "two leaks present whitelist go files",
testOpts: &Options{},
configPath: path.Join(configsDir, "file"),
numLeaks: 0,
},
{
repo: leaksRepo,
description: "two leaks present whitelist bad commit",
configPath: path.Join(configsDir, "commit"),
testOpts: &Options{},
numLeaks: 1,
},
{
repo: leaksRepo,
description: "redact",
testOpts: &Options{
Redact: true,
},
numLeaks: 2,
},
{
repo: leaksRepo,
description: "Audit a specific commit",
numLeaks: 1,
testOpts: &Options{
Commit: "cb5599aeed261b2c038aa4729e2d53ca050a4988",
},
},
{
repo: leaksRepo,
description: "Audit a specific commit no leaks",
numLeaks: 0,
testOpts: &Options{
Commit: "2b033e012eee364fc41b4ab7c5db1497399b8e67",
},
},
{
repo: leaksRepo,
description: "toml whitelist regex",
configPath: path.Join(configsDir, "regex"),
testOpts: &Options{},
numLeaks: 0,
},
{
repo: leaksRepo,
description: "toml whitelist file",
configPath: path.Join(configsDir, "file"),
testOpts: &Options{},
numLeaks: 0,
},
{
repo: leaksRepo,
description: "toml whitelist commit",
configPath: path.Join(configsDir, "commit"),
testOpts: &Options{},
numLeaks: 1,
},
{
repo: leaksRepo,
description: "audit whitelist repo",
numLeaks: 0,
testOpts: &Options{},
configPath: path.Join(configsDir, "repo"),
},
{
repo: leaksRepo,
description: "toml whitelist repo",
numLeaks: 0,
testOpts: &Options{},
configPath: path.Join(configsDir, "repo"),
},
{
repo: leaksRepo,
description: "leaks present with entropy",
testOpts: &Options{
Entropy: 4.7,
},
numLeaks: 6,
},
{
repo: leaksRepo,
description: "leaks present with entropy",
testOpts: &Options{
Entropy: 4.7,
NoiseReduction: true,
},
numLeaks: 2,
},
{
repo: leaksRepo,
description: "Audit until specific commit",
numLeaks: 2,
testOpts: &Options{
CommitStop: "f6839959b7bbdcd23008f1fb16f797f35bcd3a0c",
},
},
{
repo: leaksRepo,
description: "commit depth = 2, two leaks",
numLeaks: 2,
testOpts: &Options{
Depth: 2,
},
},
{
repo: leaksRepo,
description: "toml entropy range from opts",
numLeaks: 454,
testOpts: &Options{
ConfigPath: path.Join(configsDir, "entropy"),
},
},
{
repo: leaksRepo,
description: "toml entropy range",
numLeaks: 454,
testOpts: &Options{},
configPath: path.Join(configsDir, "entropy"),
},
{
repo: leaksRepo,
testOpts: &Options{
NoiseReduction: true,
},
description: "toml entropy noise reduction range",
numLeaks: 64,
configPath: path.Join(configsDir, "entropy"),
},
{
repo: leaksRepo,
description: "toml bad entropy range",
numLeaks: 0,
testOpts: &Options{},
configPath: path.Join(configsDir, "badEntropy"),
expectedErrMsg: "entropy range must be ascending",
},
{
repo: leaksRepo,
description: "toml bad entropy2 range",
numLeaks: 0,
testOpts: &Options{},
configPath: path.Join(configsDir, "badEntropy2"),
expectedErrMsg: "invalid entropy ranges, must be within 0.0-8.0",
},
}
g := goblin.Goblin(t)
for _, test := range tests {
g.Describe("TestAuditRepo", func() {
g.It(test.description, func() {
auditDone = false
opts = test.testOpts
totalCommits = 0
config, err = newConfig()
// config paths
if test.configPath != "" {
os.Setenv("GITLEAKS_CONFIG", test.configPath)
config, err = newConfig()
if err != nil {
g.Assert(err.Error()).Equal(test.expectedErrMsg)
goto next
}
}
leaks, err = test.repo.audit()
if test.testOpts.Depth != 0 {
g.Assert(totalCommits).Equal(test.testOpts.Depth)
} else {
if opts.Redact {
g.Assert(leaks[0].Offender).Equal("REDACTED")
}
g.Assert(len(leaks)).Equal(test.numLeaks)
}
next:
os.Setenv("GITLEAKS_CONFIG", "")
})
})
}
}
func TestOptionGuard(t *testing.T) {
var tests = []struct {
testOpts *Options
githubToken bool
description string
expectedErrMsg string
expectedErrMsgFuzzy string
}{
{
testOpts: &Options{},
description: "default no opts",
expectedErrMsg: "",
},
{
testOpts: &Options{
GithubUser: "fakeUser",
GithubOrg: "fakeOrg",
},
description: "double owner",
expectedErrMsg: "github user and organization set",
},
{
testOpts: &Options{
GithubOrg: "fakeOrg",
OwnerPath: "/dev/null",
},
description: "local and remote target",
expectedErrMsg: "github organization set and local owner path",
},
{
testOpts: &Options{
GithubUser: "fakeUser",
OwnerPath: "/dev/null",
},
description: "local and remote target",
expectedErrMsg: "github user set and local owner path",
},
{
testOpts: &Options{
GithubUser: "fakeUser",
SingleSearch: "*/./....",
},
description: "single search invalid regex gaurd",
expectedErrMsgFuzzy: "unable to compile regex: */./...., ",
},
{
testOpts: &Options{
GithubUser: "fakeUser",
SingleSearch: "mystring",
},
description: "single search regex gaurd",
expectedErrMsg: "",
},
{
testOpts: &Options{
GithubOrg: "fakeOrg",
Entropy: 9,
},
description: "Invalid entropy level guard",
expectedErrMsg: "The maximum level of entropy is 8",
},
}
g := goblin.Goblin(t)
for _, test := range tests {
g.Describe("Test Option Gaurd", func() {
g.It(test.description, func() {
os.Clearenv()
opts = test.testOpts
if test.githubToken {
os.Setenv("GITHUB_TOKEN", "fakeToken")
}
err := opts.guard()
if err != nil {
if test.expectedErrMsgFuzzy != "" {
g.Assert(strings.Contains(err.Error(), test.expectedErrMsgFuzzy)).Equal(true)
} else {
g.Assert(err.Error()).Equal(test.expectedErrMsg)
}
} else {
g.Assert("").Equal(test.expectedErrMsg)
}
})
})
}
}
func TestLoadToml(t *testing.T) {
tmpDir, _ := ioutil.TempDir("", "gitleaksTestConfigDir")
defer os.RemoveAll(tmpDir)
err := ioutil.WriteFile(path.Join(tmpDir, "gitleaksConfig"), []byte(defaultConfig), 0644)
if err != nil {
panic(err)
}
configPath := path.Join(tmpDir, "gitleaksConfig")
noConfigPath := path.Join(tmpDir, "gitleaksConfigNope")
var tests = []struct {
testOpts *Options
description string
configPath string
expectedErrMsg string
singleSearch bool
}{
{
testOpts: &Options{
ConfigPath: configPath,
},
description: "path to config",
},
{
testOpts: &Options{},
description: "env var path to no config",
singleSearch: true,
},
{
testOpts: &Options{
ConfigPath: noConfigPath,
},
description: "no path to config",
expectedErrMsg: fmt.Sprintf("no gitleaks config at %s", noConfigPath),
},
{
testOpts: &Options{},
description: "env var path to config",
configPath: configPath,
expectedErrMsg: "",
},
{
testOpts: &Options{},
description: "env var path to no config",
configPath: noConfigPath,
expectedErrMsg: fmt.Sprintf("problem loading config: open %s: no such file or directory", noConfigPath),
},
}
g := goblin.Goblin(t)
for _, test := range tests {
g.Describe("TestLoadToml", func() {
g.It(test.description, func() {
opts = test.testOpts
if test.singleSearch {
singleSearchRegex = regexp.MustCompile("test")
} else {
singleSearchRegex = nil
}
if test.configPath != "" {
os.Setenv("GITLEAKS_CONFIG", test.configPath)
} else {
os.Clearenv()
}
_, err = newConfig()
if err != nil {
g.Assert(err.Error()).Equal(test.expectedErrMsg)
} else {
g.Assert("").Equal(test.expectedErrMsg)
}
})
})
}
}
-170
View File
@@ -1,170 +0,0 @@
package gitleaks
import (
"fmt"
"net"
"net/url"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"
"github.com/jessevdk/go-flags"
log "github.com/sirupsen/logrus"
)
// Options for gitleaks
type Options struct {
// remote target options
Repo string `short:"r" long:"repo" description:"Repo url to audit"`
GithubUser string `long:"github-user" description:"Github user to audit"`
GithubOrg string `long:"github-org" description:"Github organization to audit"`
GithubURL string `long:"github-url" default:"https://api.github.com/" description:"GitHub API Base URL, use for GitHub Enterprise. Example: https://github.example.com/api/v3/"`
GithubPR string `long:"github-pr" description:"Github PR url to audit. This does not clone the repo. GITHUB_TOKEN must be set"`
GitLabUser string `long:"gitlab-user" description:"GitLab user ID to audit"`
GitLabOrg string `long:"gitlab-org" description:"GitLab group ID to audit"`
CommitStop string `long:"commit-stop" description:"sha of commit to stop at"`
Commit string `long:"commit" description:"sha of commit to audit"`
Depth int64 `long:"depth" description:"maximum commit depth"`
// local target option
RepoPath string `long:"repo-path" description:"Path to repo"`
OwnerPath string `long:"owner-path" description:"Path to owner directory (repos discovered)"`
// Process options
Threads int `long:"threads" description:"Maximum number of threads gitleaks spawns"`
Disk bool `long:"disk" description:"Clones repo(s) to disk"`
SingleSearch string `long:"single-search" description:"single regular expression to search for"`
ConfigPath string `long:"config" description:"path to gitleaks config"`
SSHKey string `long:"ssh-key" description:"path to ssh key"`
ExcludeForks bool `long:"exclude-forks" description:"exclude forks for organization/user audits"`
Entropy float64 `long:"entropy" short:"e" description:"Include entropy checks during audit. Entropy scale: 0.0(no entropy) - 8.0(max entropy)"`
NoiseReduction bool `long:"noise-reduction" description:"Reduce the number of finds when entropy checks are enabled"`
RepoConfig bool `long:"repo-config" description:"Load config from target repo. Config file must be \".gitleaks.toml\""`
Branch string `long:"branch" description:"Branch to audit"`
// TODO: IncludeMessages string `long:"messages" description:"include commit messages in audit"`
// Output options
Log string `short:"l" long:"log" description:"log level"`
Verbose bool `short:"v" long:"verbose" description:"Show verbose output from gitleaks audit"`
Report string `long:"report" description:"path to write report file. Needs to be csv or json"`
Redact bool `long:"redact" description:"redact secrets from log messages and report"`
Version bool `long:"version" description:"version number"`
SampleConfig bool `long:"sample-config" description:"prints a sample config file"`
}
// ParseOpts parses the options
func ParseOpts() *Options {
var opts Options
parser := flags.NewParser(&opts, flags.Default)
_, err := parser.Parse()
if err != nil {
if flagsErr, ok := err.(*flags.Error); ok && flagsErr.Type == flags.ErrHelp {
os.Exit(0)
}
}
if len(os.Args) == 1 {
// TODO: this will be a feature, check locally
parser.WriteHelp(os.Stdout)
os.Exit(0)
}
if opts.Version {
fmt.Println(version)
os.Exit(0)
}
if opts.SampleConfig {
fmt.Println(defaultConfig)
os.Exit(0)
}
opts.setLogs()
err = opts.guard()
if err != nil {
log.Fatal(err)
}
return &opts
}
// optsGuard prevents invalid options
func (opts *Options) guard() error {
var err error
if opts.GithubOrg != "" && opts.GithubUser != "" {
return fmt.Errorf("github user and organization set")
} else if opts.GithubOrg != "" && opts.OwnerPath != "" {
return fmt.Errorf("github organization set and local owner path")
} else if opts.GithubUser != "" && opts.OwnerPath != "" {
return fmt.Errorf("github user set and local owner path")
}
if opts.Threads > runtime.GOMAXPROCS(0) {
return fmt.Errorf("%d available threads", runtime.GOMAXPROCS(0))
}
// do the URL Parse and error checking here, so we can skip it later
// empty string is OK, it will default to the public github URL.
if opts.GithubURL != "" && opts.GithubURL != defaultGithubURL {
if !strings.HasSuffix(opts.GithubURL, "/") {
opts.GithubURL += "/"
}
ghURL, err := url.Parse(opts.GithubURL)
if err != nil {
return err
}
tcpPort := "443"
if ghURL.Scheme == "http" {
tcpPort = "80"
}
timeout := time.Duration(1 * time.Second)
_, err = net.DialTimeout("tcp", ghURL.Host+":"+tcpPort, timeout)
if err != nil {
return fmt.Errorf("%s unreachable, error: %s", ghURL.Host, err)
}
}
if opts.SingleSearch != "" {
singleSearchRegex, err = regexp.Compile(opts.SingleSearch)
if err != nil {
return fmt.Errorf("unable to compile regex: %s, %v", opts.SingleSearch, err)
}
}
if opts.Entropy > 8 {
return fmt.Errorf("The maximum level of entropy is 8")
}
if opts.Report != "" {
if !strings.HasSuffix(opts.Report, ".json") && !strings.HasSuffix(opts.Report, ".csv") {
return fmt.Errorf("Report should be a .json or .csv file")
}
dirPath := filepath.Dir(opts.Report)
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
return fmt.Errorf("%s does not exist", dirPath)
}
}
return nil
}
// setLogLevel sets log level for gitleaks. Default is Warning
func (opts *Options) setLogs() {
switch opts.Log {
case "info":
log.SetLevel(log.InfoLevel)
case "debug":
log.SetLevel(log.DebugLevel)
case "warn":
log.SetLevel(log.WarnLevel)
default:
log.SetLevel(log.InfoLevel)
}
log.SetFormatter(&log.TextFormatter{
FullTimestamp: true,
})
}
-318
View File
@@ -1,318 +0,0 @@
package gitleaks
import (
"crypto/md5"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
log "github.com/sirupsen/logrus"
git "gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing"
diffType "gopkg.in/src-d/go-git.v4/plumbing/format/diff"
"gopkg.in/src-d/go-git.v4/plumbing/object"
"gopkg.in/src-d/go-git.v4/plumbing/storer"
"gopkg.in/src-d/go-git.v4/storage/memory"
)
// Leak represents a leaked secret or regex match.
type Leak struct {
Line string `json:"line"`
Commit string `json:"commit"`
Offender string `json:"offender"`
Type string `json:"reason"`
Message string `json:"commitMsg"`
Author string `json:"author"`
Email string `json:"email"`
File string `json:"file"`
Repo string `json:"repo"`
Date time.Time `json:"date"`
}
// RepoInfo contains a src-d git repository and other data about the repo
type RepoInfo struct {
path string
url string
name string
repository *git.Repository
err error
}
func newRepoInfo() (*RepoInfo, error) {
for _, re := range config.WhiteList.repos {
if re.FindString(opts.Repo) != "" {
return nil, fmt.Errorf("skipping %s, whitelisted", opts.Repo)
}
}
return &RepoInfo{
path: opts.RepoPath,
url: opts.Repo,
name: filepath.Base(opts.Repo),
}, nil
}
// clone will clone a repo
func (repoInfo *RepoInfo) clone() error {
var (
err error
repo *git.Repository
)
// check if cloning to disk
if opts.Disk {
log.Infof("cloning %s to disk", opts.Repo)
cloneTarget := fmt.Sprintf("%s/%x", dir, md5.Sum([]byte(fmt.Sprintf("%s%s", opts.GithubUser, opts.Repo))))
if strings.HasPrefix(opts.Repo, "git") {
// private
repo, err = git.PlainClone(cloneTarget, false, &git.CloneOptions{
URL: opts.Repo,
Progress: os.Stdout,
Auth: config.sshAuth,
})
} else {
// public
repo, err = git.PlainClone(cloneTarget, false, &git.CloneOptions{
URL: opts.Repo,
Progress: os.Stdout,
})
}
} else if repoInfo.path != "" {
log.Infof("opening %s", opts.RepoPath)
repo, err = git.PlainOpen(repoInfo.path)
} else {
// cloning to memory
log.Infof("cloning %s", opts.Repo)
if strings.HasPrefix(opts.Repo, "git") {
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: opts.Repo,
Progress: os.Stdout,
Auth: config.sshAuth,
})
} else {
repo, err = git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: opts.Repo,
Progress: os.Stdout,
})
}
}
repoInfo.repository = repo
repoInfo.err = err
return err
}
// audit performs an audit
func (repoInfo *RepoInfo) audit() ([]Leak, error) {
var (
err error
leaks []Leak
commitCount int64
commitWg sync.WaitGroup
semaphore chan bool
logOpts git.LogOptions
)
for _, re := range config.WhiteList.repos {
if re.FindString(repoInfo.name) != "" {
return leaks, fmt.Errorf("skipping %s, whitelisted", repoInfo.name)
}
}
// check if target contains an external gitleaks toml
if opts.RepoConfig {
err := config.updateFromRepo(repoInfo)
if err != nil {
return leaks, nil
}
}
if opts.Branch != "" {
refs, err := repoInfo.repository.Storer.IterReferences()
if err != nil {
return leaks, err
}
err = refs.ForEach(func(ref *plumbing.Reference) error {
if ref.Name().IsTag() {
return nil
}
// check heads first
if ref.Name().String() == "refs/heads/"+opts.Branch {
logOpts = git.LogOptions{
From: ref.Hash(),
}
return nil
} else if ref.Name().String() == "refs/remotes/origin/"+opts.Branch {
logOpts = git.LogOptions{
From: ref.Hash(),
}
return nil
}
return nil
})
} else {
logOpts = git.LogOptions{
All: true,
}
}
// iterate all through commits
cIter, err := repoInfo.repository.Log(&logOpts)
if err != nil {
return leaks, nil
}
if opts.Threads != 0 {
threads = opts.Threads
}
if opts.RepoPath != "" {
threads = 1
}
semaphore = make(chan bool, threads)
err = cIter.ForEach(func(c *object.Commit) error {
if c == nil || (opts.Depth != 0 && commitCount == opts.Depth) {
return storer.ErrStop
}
if config.WhiteList.commits[c.Hash.String()] {
log.Infof("skipping commit: %s\n", c.Hash.String())
return nil
}
commitCount = commitCount + 1
totalCommits = totalCommits + 1
// commits w/o parent (root of git the git ref) or option for single commit is not empty str
if len(c.ParentHashes) == 0 || opts.Commit == c.Hash.String() {
leaksFromSingleCommit := repoInfo.auditSingleCommit(c)
mutex.Lock()
leaks = append(leaksFromSingleCommit, leaks...)
mutex.Unlock()
if opts.Commit == c.Hash.String() {
return storer.ErrStop
}
return nil
}
if opts.Commit != "" {
return nil
}
// regular commit audit
err = c.Parents().ForEach(func(parent *object.Commit) error {
commitWg.Add(1)
semaphore <- true
go func(c *object.Commit, parent *object.Commit) {
var (
filePath string
skipFile bool
)
defer func() {
commitWg.Done()
<-semaphore
if r := recover(); r != nil {
log.Warnf("recovering from panic on commit %s, likely large diff causing panic", c.Hash.String())
}
}()
patch, err := c.Patch(parent)
if err != nil {
log.Warnf("problem generating patch for commit: %s\n", c.Hash.String())
return
}
for _, f := range patch.FilePatches() {
if f.IsBinary() {
continue
}
skipFile = false
from, to := f.Files()
filePath = "???"
if from != nil {
filePath = from.Path()
} else if to != nil {
filePath = to.Path()
}
for _, re := range config.WhiteList.files {
if re.FindString(filePath) != "" {
log.Debugf("skipping whitelisted file (matched regex '%s'): %s", re.String(), filePath)
skipFile = true
break
}
}
if skipFile {
continue
}
chunks := f.Chunks()
for _, chunk := range chunks {
if chunk.Type() == diffType.Add || chunk.Type() == diffType.Delete {
diff := commitInfo{
repoName: repoInfo.name,
filePath: filePath,
content: chunk.Content(),
sha: c.Hash.String(),
author: c.Author.Name,
email: c.Author.Email,
message: strings.Replace(c.Message, "\n", " ", -1),
date: c.Author.When,
}
chunkLeaks := inspect(diff)
for _, leak := range chunkLeaks {
mutex.Lock()
leaks = append(leaks, leak)
mutex.Unlock()
}
}
}
}
}(c, parent)
return nil
})
return nil
})
commitWg.Wait()
return leaks, nil
}
func (repoInfo *RepoInfo) auditSingleCommit(c *object.Commit) []Leak {
var leaks []Leak
fIter, err := c.Files()
if err != nil {
return nil
}
err = fIter.ForEach(func(f *object.File) error {
bin, err := f.IsBinary()
if bin || err != nil {
return nil
}
for _, re := range config.WhiteList.files {
if re.FindString(f.Name) != "" {
log.Debugf("skipping whitelisted file (matched regex '%s'): %s", re.String(), f.Name)
return nil
}
}
content, err := f.Contents()
if err != nil {
return nil
}
diff := commitInfo{
repoName: repoInfo.name,
filePath: f.Name,
content: content,
sha: c.Hash.String(),
author: c.Author.Name,
email: c.Author.Email,
message: strings.Replace(c.Message, "\n", " ", -1),
date: c.Author.When,
}
fileLeaks := inspect(diff)
mutex.Lock()
leaks = append(leaks, fileLeaks...)
mutex.Unlock()
return nil
})
return leaks
}
-201
View File
@@ -1,201 +0,0 @@
package gitleaks
import (
"encoding/csv"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path"
"strings"
"time"
log "github.com/sirupsen/logrus"
"gopkg.in/src-d/go-git.v4/plumbing/object"
)
type commitInfo struct {
content string
commit *object.Commit
filePath string
repoName string
sha string
message string
author string
email string
date time.Time
}
// writeReport writes a report to a file specified in the --report= option.
// Default format for report is JSON. You can use the --csv option to write the report as a csv
func writeReport(leaks []Leak) error {
if len(leaks) == 0 {
return nil
}
log.Infof("writing report to %s", opts.Report)
if strings.HasSuffix(opts.Report, ".csv") {
f, err := os.Create(opts.Report)
if err != nil {
return err
}
defer f.Close()
w := csv.NewWriter(f)
w.Write([]string{"repo", "line", "commit", "offender", "reason", "commitMsg", "author", "email", "file", "date"})
for _, leak := range leaks {
w.Write([]string{leak.Repo, leak.Line, leak.Commit, leak.Offender, leak.Type, leak.Message, leak.Author, leak.Email, leak.File, leak.Date.Format(time.RFC3339)})
}
w.Flush()
} else {
f, err := os.Create(opts.Report)
if err != nil {
return err
}
defer f.Close()
encoder := json.NewEncoder(f)
encoder.SetIndent("", "\t")
if _, err := f.WriteString("[\n"); err != nil {
return err
}
for i := 0; i < len(leaks); i++ {
if err := encoder.Encode(leaks[i]); err != nil {
return err
}
// for all but the last leak, seek back and overwrite the newline appended by Encode() with comma & newline
if i+1 < len(leaks) {
if _, err := f.Seek(-1, 1); err != nil {
return err
}
if _, err := f.WriteString(",\n"); err != nil {
return err
}
}
}
if _, err := f.WriteString("]"); err != nil {
return err
}
if err := f.Sync(); err != nil {
log.Error(err)
return err
}
}
return nil
}
// inspect will parse each line of the git diff's content against a set of regexes or
// a set of regexes set by the config (see gitleaks.toml for example). This function
// will skip lines that include a whitelisted regex. A list of leaks is returned.
// If verbose mode (-v/--verbose) is set, then checkDiff will log leaks as they are discovered.
func inspect(commit commitInfo) []Leak {
var (
leaks []Leak
skipLine bool
)
lines := strings.Split(commit.content, "\n")
for _, line := range lines {
skipLine = false
for _, re := range config.Regexes {
match := re.regex.FindString(line)
if match == "" {
continue
}
if skipLine = isLineWhitelisted(line); skipLine {
break
}
leaks = addLeak(leaks, line, match, re.description, commit)
}
if !skipLine && (opts.Entropy > 0 || len(config.Entropy.entropyRanges) != 0) {
words := strings.Fields(line)
for _, word := range words {
entropy := getShannonEntropy(word)
// Only check entropyRegexes and whiteListRegexes once per line, and only if an entropy leak type
// was found above, since regex checks are expensive.
if !entropyIsHighEnough(entropy) {
continue
}
// If either the line is whitelisted or the line fails the noiseReduction check (when enabled),
// then we can skip checking the rest of the line for high entropy words.
if skipLine = !highEntropyLineIsALeak(line) || isLineWhitelisted(line); skipLine {
break
}
leaks = addLeak(leaks, line, word, fmt.Sprintf("Entropy: %.2f", entropy), commit)
}
}
}
return leaks
}
// isLineWhitelisted returns true iff the line is matched by at least one of the whiteListRegexes.
func isLineWhitelisted(line string) bool {
for _, wRe := range config.WhiteList.regexes {
whitelistMatch := wRe.FindString(line)
if whitelistMatch != "" {
return true
}
}
return false
}
// addLeak is helper for func inspect() to append leaks if found during a diff check.
func addLeak(leaks []Leak, line string, offender string, leakType string, commit commitInfo) []Leak {
leak := Leak{
Line: line,
Commit: commit.sha,
Offender: offender,
Type: leakType,
Author: commit.author,
Email: commit.email,
File: commit.filePath,
Repo: commit.repoName,
Message: commit.message,
Date: commit.date,
}
if opts.Redact {
leak.Offender = "REDACTED"
leak.Line = strings.Replace(line, offender, "REDACTED", -1)
}
if opts.Verbose {
leak.log()
}
leaks = append(leaks, leak)
return leaks
}
// discoverRepos walks all the children of `path`. If a child directory
// contain a .git subdirectory then that repo will be added to the list of repos returned
func discoverRepos(ownerPath string) ([]*RepoInfo, error) {
var (
err error
repoDs []*RepoInfo
)
files, err := ioutil.ReadDir(ownerPath)
if err != nil {
return repoDs, err
}
for _, f := range files {
repoPath := path.Join(ownerPath, f.Name())
if f.IsDir() && containsGit(repoPath) {
repoDs = append(repoDs, &RepoInfo{
name: f.Name(),
path: repoPath,
})
}
}
return repoDs, err
}
func (leak Leak) log() {
b, _ := json.MarshalIndent(leak, "", " ")
fmt.Println(string(b))
}
func containsGit(repoPath string) bool {
if _, err := os.Stat(repoPath); os.IsNotExist(err) {
return false
}
return true
}